<commit_before>'use strict';
const path = require('path');
const electron = require('electron');
const {app} = require('electron');
const ipc = require('electron').ipcMain;
const electronLocalshortcut = require('electron-localshortcut');
const Configstore = require('electron-config');
const isDev = require('electron-is-dev');
const appMenu = require('./menu');
const {appUpdater} = require('./autoupdater');

// Adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const conf = new Configstore();

// Setting userAgent so that server-side code can identify the desktop app

// Prevent window being garbage collected
let mainWindow;

let isQuitting = false;

// Load this url in main window
const mainURL = 'file://' + path.join(__dirname, '../renderer', 'main.html');

const isAlreadyRunning = app.makeSingleInstance(() => {
	if (mainWindow) {
		if (mainWindow.isMinimized()) {
			mainWindow.restore();
		}

		mainWindow.show();
	}
});

if (isAlreadyRunning) {
	return app.quit();
}

function isWindowsOrmacOS() {
	return process.platform === 'darwin' || process.platform === 'win32';
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
	return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
};

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 500,
		webPreferences: {
			plugins: true,
			allowDisplayingInsecureContent: true,
			nodeIntegration: true
		},
		show: false
	});

	win.on('focus', () => {
		win.webContents.send('focus');
	});

	win.once('ready-to-show', () => {
		win.show();
	});

	win.loadURL(mainURL);

	// Keep the app running in background on close event
	win.on('close', e => {
		if (!isQuitting) {
			e.preventDefault();

			if (process.platform === 'darwin') {
				app.hide();
			} else {
				win.hide();
			}
		}

	// Unregister all the shortcuts so that they don't interfare with other apps
		electronLocalshortcut.unregisterAll(mainWindow);
	});

	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
		win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
		win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', () => {
		conf.set('maximize', true);
	});

	win.on('unmaximize', () => {
		conf.set('maximize', false);
	});

	win.on('resize', function () {
		const size = this.getSize();
		conf.set({
			width: size[0],
			height: size[1]
		});
	});

	// On osx it's 'moved'
	win.on('move', function () {
		const pos = this.getPosition();
		conf.set({
			x: pos[0],
			y: pos[1]
		});
	});

	//  To destroy tray icon when navigate to a new URL
	win.webContents.on('will-navigate', e => {
		if (e) {
			win.webContents.send('destroytray');
		}
	});

	return win;
}

// eslint-disable-next-line max-params
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
	event.preventDefault();
	callback(true);
});

app.on('window-all-closed', () => {
	// Unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	electron.Menu.setApplicationMenu(appMenu);
	mainWindow = createMainWindow();

	const page = mainWindow.webContents;

	// TODO - use global shortcut instead
	electronLocalshortcut.register(mainWindow, 'CommandOrControl+R', () => {
		// page.send('reload');
		mainWindow.reload();
		page.send('destroytray');
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => {
		page.send('back');
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+]', () => {
		page.send('forward');
	});

	page.on('dom-ready', () => {
		mainWindow.show();
	});

	page.once('did-frame-finish-load', () => {
		const checkOS = isWindowsOrmacOS();
		if (checkOS && !isDev) {
			// Initate auto-updates on MacOS and Windows
			appUpdater();
		}
	});
	electron.powerMonitor.on('resume', () => {
		mainWindow.reload();
		page.send('destroytray');
	});

	ipc.on('focus-app', () => {
		mainWindow.show();
	});

	ipc.on('quit-app', () => {
		app.quit();
	});

	ipc.on('reload-main', () => {
		page.reload();
		page.send('destroytray');
	});

	ipc.on('toggle-app', () => {
		if (mainWindow.isVisible()) {
			mainWindow.hide();
		} else {
			mainWindow.show();
		}
	});

	ipc.on('update-badge', (event, messageCount) => {
		if (process.platform === 'darwin') {
			app.setBadgeCount(messageCount);
		}
		page.send('tray', messageCount);
	});

	ipc.on('forward-message', (event, listener, ...params) => {
		console.log(listener, ...params);
		page.send(listener);
	});

	ipc.on('register-server-tab-shortcut', (event, index) => {
		electronLocalshortcut.register(mainWindow, `CommandOrControl+${index}`, () => {
			// Array index == Shown index - 1
			page.send('switch-server-tab', index - 1);
		});
	});
});

app.on('will-quit', () => {
	// Unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

app.on('before-quit', () => {
	isQuitting = true;
});
<commit_msg>Unregister local shortcuts after reload.<commit_after>'use strict';
const path = require('path');
const electron = require('electron');
const {app} = require('electron');
const ipc = require('electron').ipcMain;
const electronLocalshortcut = require('electron-localshortcut');
const Configstore = require('electron-config');
const isDev = require('electron-is-dev');
const appMenu = require('./menu');
const {appUpdater} = require('./autoupdater');

// Adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const conf = new Configstore();

// Setting userAgent so that server-side code can identify the desktop app

// Prevent window being garbage collected
let mainWindow;

let isQuitting = false;

// Load this url in main window
const mainURL = 'file://' + path.join(__dirname, '../renderer', 'main.html');

const isAlreadyRunning = app.makeSingleInstance(() => {
	if (mainWindow) {
		if (mainWindow.isMinimized()) {
			mainWindow.restore();
		}

		mainWindow.show();
	}
});

if (isAlreadyRunning) {
	return app.quit();
}

function isWindowsOrmacOS() {
	return process.platform === 'darwin' || process.platform === 'win32';
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
	return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
};

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 500,
		webPreferences: {
			plugins: true,
			allowDisplayingInsecureContent: true,
			nodeIntegration: true
		},
		show: false
	});

	win.on('focus', () => {
		win.webContents.send('focus');
	});

	win.once('ready-to-show', () => {
		win.show();
	});

	win.loadURL(mainURL);

	// Keep the app running in background on close event
	win.on('close', e => {
		if (!isQuitting) {
			e.preventDefault();

			if (process.platform === 'darwin') {
				app.hide();
			} else {
				win.hide();
			}
		}

	// Unregister all the shortcuts so that they don't interfare with other apps
		electronLocalshortcut.unregisterAll(mainWindow);
	});

	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
		win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
		win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', () => {
		conf.set('maximize', true);
	});

	win.on('unmaximize', () => {
		conf.set('maximize', false);
	});

	win.on('resize', function () {
		const size = this.getSize();
		conf.set({
			width: size[0],
			height: size[1]
		});
	});

	// On osx it's 'moved'
	win.on('move', function () {
		const pos = this.getPosition();
		conf.set({
			x: pos[0],
			y: pos[1]
		});
	});

	//  To destroy tray icon when navigate to a new URL
	win.webContents.on('will-navigate', e => {
		if (e) {
			win.webContents.send('destroytray');
		}
	});

	return win;
}

// eslint-disable-next-line max-params
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
	event.preventDefault();
	callback(true);
});

app.on('window-all-closed', () => {
	// Unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	electron.Menu.setApplicationMenu(appMenu);
	mainWindow = createMainWindow();

	const page = mainWindow.webContents;

	page.on('dom-ready', () => {
		mainWindow.show();
	});

	page.once('did-frame-finish-load', () => {
		const checkOS = isWindowsOrmacOS();
		if (checkOS && !isDev) {
			// Initate auto-updates on MacOS and Windows
			appUpdater();
		}
	});
	electron.powerMonitor.on('resume', () => {
		mainWindow.reload();
		page.send('destroytray');
	});

	ipc.on('focus-app', () => {
		mainWindow.show();
	});

	ipc.on('quit-app', () => {
		app.quit();
	});

	ipc.on('reload-main', () => {
		page.reload();
		page.send('destroytray');
		electronLocalshortcut.unregisterAll(mainWindow);
	});

	ipc.on('toggle-app', () => {
		if (mainWindow.isVisible()) {
			mainWindow.hide();
		} else {
			mainWindow.show();
		}
	});

	ipc.on('update-badge', (event, messageCount) => {
		if (process.platform === 'darwin') {
			app.setBadgeCount(messageCount);
		}
		page.send('tray', messageCount);
	});

	ipc.on('forward-message', (event, listener, ...params) => {
		console.log(listener, ...params);
		page.send(listener);
	});

	ipc.on('register-server-tab-shortcut', (event, index) => {
		electronLocalshortcut.register(mainWindow, `CommandOrControl+${index}`, () => {
			// Array index == Shown index - 1
			page.send('switch-server-tab', index - 1);
		});
	});
});

app.on('will-quit', () => {
	// Unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

app.on('before-quit', () => {
	isQuitting = true;
});
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const {app} = require('electron');
const ipc = require('electron').ipcMain;
const electronLocalshortcut = require('electron-localshortcut');
const Configstore = require('configstore');
const JsonDB = require('node-json-db');
const isDev = require('electron-is-dev');
const tray = require('./tray');
const appMenu = require('./menu');
const {linkIsInternal, skipImages} = require('./link-helper');
const {appUpdater} = require('./autoupdater');

const db = new JsonDB(app.getPath('userData') + '/domain.json', true, true);
const data = db.getData('/');

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const conf = new Configstore('Zulip-Desktop');

// prevent window being garbage collected
let mainWindow;
let targetLink;

// Load this url in main window
const staticURL = 'file://' + path.join(__dirname, '../renderer', 'index.html');

const targetURL = function () {
	if (data.domain === undefined) {
		return staticURL;
	}
	return data.domain;
};

const isAlreadyRunning = app.makeSingleInstance(() => {
	if (mainWindow) {
		if (mainWindow.isMinimized()) {
			mainWindow.restore();
		}

		mainWindow.show();
	}
});

if (isAlreadyRunning) {
	app.quit();
}

function checkWindowURL() {
	if (data.domain !== undefined) {
		return data.domain;
	}
	return targetLink;
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
	return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
};

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function updateDockBadge(title) {
	if (title.indexOf('Zulip') === -1) {
		return;
	}

	let messageCount = (/\(([0-9]+)\)/).exec(title);
	messageCount = messageCount ? Number(messageCount[1]) : 0;

	if (process.platform === 'darwin') {
		app.setBadgeCount(messageCount);
	}
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 400,
		webPreferences: {
			preload: path.join(__dirname, 'preload.js'),
			plugins: true,
			allowDisplayingInsecureContent: true,
			nodeIntegration: false
		}
	});

	win.loadURL(targetURL());
	win.on('closed', onClosed);
	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
		win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
		win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', () => {
		conf.set('maximize', true);
	});

	win.on('unmaximize', () => {
		conf.set('maximize', false);
	});

	win.on('resize', function () {
		const size = this.getSize();
		conf.set({
			width: size[0],
			height: size[1]
		});
	});

	// on osx it's 'moved'
	win.on('move', function () {
		const pos = this.getPosition();
		conf.set({
			x: pos[0],
			y: pos[1]
		});
	});

	// stop page to update it's title
	win.on('page-title-updated', (e, title) => {
		e.preventDefault();
		updateDockBadge(title);
	});

	return win;
}

// TODO - fix certificate errors
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	electron.Menu.setApplicationMenu(appMenu);
	mainWindow = createMainWindow();
	tray.create(mainWindow);

	const page = mainWindow.webContents;

	// TODO - use global shortcut instead
	electronLocalshortcut.register(mainWindow, 'CommandOrControl+R', () => {
		mainWindow.reload();
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => {
		if (page.canGoBack()) {
			page.goBack();
		}
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+]', () => {
		if (page.canGoForward()) {
			page.goForward();
		}
	});

	page.on('dom-ready', () => {
		page.insertCSS(fs.readFileSync(path.join(__dirname, 'preload.css'), 'utf8'));
		mainWindow.show();
	});

	page.on('new-window', (event, url) => {
		if (linkIsInternal(checkWindowURL(), url) && url.match(skipImages) === null) {
			event.preventDefault();
			return mainWindow.loadURL(url);
		}
		event.preventDefault();
		electron.shell.openExternal(url);
	});

	page.once('did-frame-finish-load', () => {
		if (process.platform === 'darwin' && !isDev) {
			// Initate auto-updates
			appUpdater();
		}
	});
});

app.on('window-all-closed' || 'will-quit', () => {
	// unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

ipc.on('new-domain', (e, domain) => {
	// mainWindow.loadURL(domain);
	if (!mainWindow) {
		mainWindow = createMainWindow();
		mainWindow.loadURL(domain);
	} else if (mainWindow.isMinimized()) {
		mainWindow.loadURL(domain);
		mainWindow.show();
	} else {
		mainWindow.loadURL(domain);
	}
	targetLink = domain;
});
<commit_msg>Unregister shortcuts on will-quit<commit_after>'use strict';
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const {app} = require('electron');
const ipc = require('electron').ipcMain;
const electronLocalshortcut = require('electron-localshortcut');
const Configstore = require('configstore');
const JsonDB = require('node-json-db');
const isDev = require('electron-is-dev');
const tray = require('./tray');
const appMenu = require('./menu');
const {linkIsInternal, skipImages} = require('./link-helper');
const {appUpdater} = require('./autoupdater');

const db = new JsonDB(app.getPath('userData') + '/domain.json', true, true);
const data = db.getData('/');

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const conf = new Configstore('Zulip-Desktop');

// prevent window being garbage collected
let mainWindow;
let targetLink;

// Load this url in main window
const staticURL = 'file://' + path.join(__dirname, '../renderer', 'index.html');

const targetURL = function () {
	if (data.domain === undefined) {
		return staticURL;
	}
	return data.domain;
};

const isAlreadyRunning = app.makeSingleInstance(() => {
	if (mainWindow) {
		if (mainWindow.isMinimized()) {
			mainWindow.restore();
		}

		mainWindow.show();
	}
});

if (isAlreadyRunning) {
	app.quit();
}

function checkWindowURL() {
	if (data.domain !== undefined) {
		return data.domain;
	}
	return targetLink;
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
	return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
};

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function updateDockBadge(title) {
	if (title.indexOf('Zulip') === -1) {
		return;
	}

	let messageCount = (/\(([0-9]+)\)/).exec(title);
	messageCount = messageCount ? Number(messageCount[1]) : 0;

	if (process.platform === 'darwin') {
		app.setBadgeCount(messageCount);
	}
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 400,
		webPreferences: {
			preload: path.join(__dirname, 'preload.js'),
			plugins: true,
			allowDisplayingInsecureContent: true,
			nodeIntegration: false
		}
	});

	win.loadURL(targetURL());
	win.on('closed', onClosed);
	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
		win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
		win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', () => {
		conf.set('maximize', true);
	});

	win.on('unmaximize', () => {
		conf.set('maximize', false);
	});

	win.on('resize', function () {
		const size = this.getSize();
		conf.set({
			width: size[0],
			height: size[1]
		});
	});

	// on osx it's 'moved'
	win.on('move', function () {
		const pos = this.getPosition();
		conf.set({
			x: pos[0],
			y: pos[1]
		});
	});

	// stop page to update it's title
	win.on('page-title-updated', (e, title) => {
		e.preventDefault();
		updateDockBadge(title);
	});

	return win;
}

// TODO - fix certificate errors
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');

app.on('window-all-closed', () => {
	// unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	electron.Menu.setApplicationMenu(appMenu);
	mainWindow = createMainWindow();
	tray.create(mainWindow);

	const page = mainWindow.webContents;

	// TODO - use global shortcut instead
	electronLocalshortcut.register(mainWindow, 'CommandOrControl+R', () => {
		mainWindow.reload();
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => {
		if (page.canGoBack()) {
			page.goBack();
		}
	});

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+]', () => {
		if (page.canGoForward()) {
			page.goForward();
		}
	});

	page.on('dom-ready', () => {
		page.insertCSS(fs.readFileSync(path.join(__dirname, 'preload.css'), 'utf8'));
		mainWindow.show();
	});

	page.on('new-window', (event, url) => {
		if (linkIsInternal(checkWindowURL(), url) && url.match(skipImages) === null) {
			event.preventDefault();
			return mainWindow.loadURL(url);
		}
		event.preventDefault();
		electron.shell.openExternal(url);
	});

	page.once('did-frame-finish-load', () => {
		if (process.platform === 'darwin' && !isDev) {
			// Initate auto-updates
			appUpdater();
		}
	});
});

app.on('will-quit', () => {
	// unregister all the shortcuts so that they don't interfare with other apps
	electronLocalshortcut.unregisterAll(mainWindow);
});

ipc.on('new-domain', (e, domain) => {
	// mainWindow.loadURL(domain);
	if (!mainWindow) {
		mainWindow = createMainWindow();
		mainWindow.loadURL(domain);
	} else if (mainWindow.isMinimized()) {
		mainWindow.loadURL(domain);
		mainWindow.show();
	} else {
		mainWindow.loadURL(domain);
	}
	targetLink = domain;
});
<|endoftext|>


<commit_before>var mainModule = angular.module('ananke-main',['angularSpinners','ngFileUpload']);

mainModule.controller('nodeController',function($scope,$http,spinnerService) {

    $scope.status = "dormant";
    $scope.ip = {'real':false, 'value':'127.0.0.1'};
    $scope.app_id = false;
    $scope.chunk3 = {};
    $scope.chunk4 = {};
    $scope.error = {};
    $scope.slave_ip = false;
    $scope.slave_owner = {"active":false};
    $scope.master_owner = false;
    $scope.pysparknotebook = false;
    $scope.hdfs = {"active":false, "starting":false};
    $scope.slaves = 0;

    var msg = {'master_active':0, 'slave_active':1, 'notebook_active':2, 'stopped_pysparknotebook':3,
        'stopped_sparkmaster':4, 'stopped_sparkslave':5, 'node_active':6, 'stopped_singlenode':7, 'hdfs_active':8, 'stopped_hdfs':9, 'slave_count':10};

    $http.get('api/status',{params: {}}).success(function(data, status, headers, config) {
        if (data.virtual) {
            $scope.env = {"virtual":true};
        }
        else {
            $scope.env = {"virtual":false};
        }

        if (data.network) {
            $scope.network = true;
            $scope.app_id = data.appid;
            $scope.ip.real = data.realip;
            if (data.realip) {
                $scope.ip.real = data.ext_ip;
            };
            $scope.ipchunks = [{i:data.ip[0]}, {i:data.ip[1]}];
            $scope.master_url = data.ip.join('.')+":8080";
            $scope.slave_ip = data.slave_ip;
            $scope.master_owner = data.master_owner;
            $scope.pysparknotebook = data.pysparknotebook;
        }
        else {
            $scope.network = false;
        }
        $scope.status = data.status;
    }).error(function(data, status, headers, config) {
        $scope.ipchunks = [{i:0}, {i:0}];
    });

    var remote_conn = false;

    get_remote_conn = function(ip) {
        remote_conn = new WebSocket("ws://"+ip+":5001");

        remote_conn.onopen = function() {
            remote_conn.send('remote_socket');
        };

        remote_conn.onmessage = function(e) {
            var msChunks = e.data.split(" ");
            var ms_action = parseInt(msg[msChunks[0]]);
            switch (ms_action) {
                case msg.stopped_sparkmaster:
                $scope.status = 'dormant'; $scope.slaves = 0; $scope.$apply(); $scope.leave_cluster(); break;
                case msg.slave_count: $scope.slaves = msChunks[1]; $scope.$apply(); break;
            }
        };
    };

    var auto_conn = false;

    get_auto_conn = function(ip) {
        auto_conn =  WebSocket("ws://"+ip+":5001");
        auto_conn.onopen = function() {
            auto_conn.send('local_socket');
        };
    };

    auto_conn.onmessage = function(e) {
        var msChunks = e.data.split(" ");
        var ms_action = parseInt(msg[msChunks[0]]);
        switch (ms_action) {
            case msg.master_active:
                $scope.status = 'active'; $scope.master_owner = true; $scope.master_ip = msChunks[1]; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.slave_active:
                $scope.status = 'active'; $scope.slave_ip = msChunks[1]; $scope.slave_owner.active = true; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.notebook_active:
                $scope.status = 'active'; $scope.pysparknotebook = true; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_pysparknotebook:
                $scope.status = 'active'; $scope.pysparknotebook = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_sparkmaster:
                $scope.status = 'dormant'; $scope.slaves = 0; $scope.master_owner = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_sparkslave:
                $scope.status = 'dormant'; $scope.slave_owner.active = false; $scope.slave_ip = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.node_active: $scope.status = "single"; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.hdfs_active: $scope.hdfs.active = true; $scope.hdfs.waiting=false; $scope.hdfs_ip = msChunks[1]; $scope.$broadcast('hdfsUp', true); $scope.$apply(); break;
            case msg.stopped_hdfs: $scope.hdfs.active = false; $scope.hdfs.starting = false; $scope.$broadcast('hdfsDown', true); $scope.$apply(); break;
            case msg.slave_count: $scope.slaves = msChunks[1]; $scope.$apply(); break;
            case msg.stopped_singlenode:
                if ($scope.network) {
                    $scope.status = 'dormant';
                } else {
                    $scope.status = 'error';
                }
                spinnerService.hide('wait'); $scope.$apply(); break;
        }
    }

    $scope.test_ip = function() {
        var trial_ip = ([$scope.ipchunks[0].i, $scope.ipchunks[1].i, $scope.chunk3.i, $scope.chunk4.i]).join('.');
        var params =  '&ip='+trial_ip+'&id='+$scope.app_id;
        $http.jsonp("http://"+trial_ip+":5000/api/testip?callback=JSON_CALLBACK"+params).success(function(data) {
            if (data.okay) {
                $scope.ip.real = true;
                $scope.ip.value = trial_ip;
                get_auto_conn(trial_ip);
                $scope.$apply();
            }
        });

    };

    $scope.start_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get('api/startcluster',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                $scope.status = 'dormant';
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.join_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        var master_ip = ([$scope.ipchunks[0].i, $scope.ipchunks[1].i, $scope.chunk3.i, $scope.chunk4.i]).join('.');
        $scope.master_ip = master_ip
        $http.get('api/joincluster',{params: {'ip':master_ip}}).success(function(data, status, headers, config) {
            $scope.master_url = master_ip+":8080";
            if (!data.okay) {
                $scope.error.msg = data.error;
                $scope.status = 'dormant';
                spinnerService.hide('wait');
            } else {
                 get_remote_conn(master_ip);
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.leave_cluster = function() {
        remote_conn.close();
        $http.get('api/leavecluster',{params: {'ip':$scope.master_ip}}).success(function(data, status, headers, config) {
        }).error(function(data, status, headers, config) {});
    }

    $scope.notebook_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get('api/startclusternotebook',{params: {'ip':$scope.master_ip}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.start_hdfs = function() {
        $scope.hdfs.starting = true;
        $http.get('api/starthdfs',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
            }
        }).error(function(data, status, headers, config) {});
    };

     $scope.stop_hdfs = function() {
         $http.get('api/stophdfs',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
            }
        }).error(function(data, status, headers, config) {});
     };

    $scope.cluster_notebook_stop = function() {
        simple_service('api/stopclusternotebook');
    };

    $scope.stop_cluster = function() {
        simple_service('api/stopcluster');
    };

    $scope.start_single_node = function() {
        simple_service('/api/startsinglenotebook');
    };

    $scope.single_notebook_stop = function() {
        simple_service('/api/stopsinglenotebook');
    };

    simple_service = function(endpoint) {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get(endpoint,{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

});

mainModule.controller('docController',function($scope,$http) {

    $http.get('api/getdocs',{params: {}}).success(function(data, status, headers, config) {
        $scope.allthedocs = data.allthedocs;
    }).error(function(data, status, headers, config) {
    });

});

mainModule.controller('uploadController', ['$scope','Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.upload = {"active":false};

    $scope.$on('hdfsUp', function(event, args) {$scope.upload.active=true; $scope.$apply();});
    $scope.$on('hdfsDown', function(event, args) {$scope.upload.active=false; $scope.$apply();});

    $scope.uploadFile = function (file, errFiles) {
        if (file) {
            file.upload = Upload.upload({
                url: 'api/hdfsupload',
                data: {file: file, name: file.name}
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                                         evt.loaded / evt.total));
            });

        }

    };

}]);
<commit_msg>	modified:   ananke/static/js/ananke.js<commit_after>var mainModule = angular.module('ananke-main',['angularSpinners','ngFileUpload']);

mainModule.controller('nodeController',function($scope,$http,spinnerService) {

    $scope.status = "dormant";
    $scope.ip = {'real':false, 'value':'127.0.0.1'};
    $scope.app_id = false;
    $scope.chunk3 = {};
    $scope.chunk4 = {};
    $scope.error = {};
    $scope.slave_ip = false;
    $scope.slave_owner = {"active":false};
    $scope.master_owner = false;
    $scope.pysparknotebook = false;
    $scope.hdfs = {"active":false, "starting":false};
    $scope.slaves = 0;

    var msg = {'master_active':0, 'slave_active':1, 'notebook_active':2, 'stopped_pysparknotebook':3,
        'stopped_sparkmaster':4, 'stopped_sparkslave':5, 'node_active':6, 'stopped_singlenode':7, 'hdfs_active':8, 'stopped_hdfs':9, 'slave_count':10};

    $http.get('api/status',{params: {}}).success(function(data, status, headers, config) {
        if (data.virtual) {
            $scope.env = {"virtual":true};
        }
        else {
            $scope.env = {"virtual":false};
        }

        if (data.network) {
            $scope.network = true;
            $scope.app_id = data.appid;
            $scope.ip.real = data.realip;
            if (data.realip) {
                $scope.ip.real = data.ext_ip;
            };
            $scope.ipchunks = [{i:data.ip[0]}, {i:data.ip[1]}];
            $scope.master_url = data.ip.join('.')+":8080";
            $scope.slave_ip = data.slave_ip;
            $scope.master_owner = data.master_owner;
            $scope.pysparknotebook = data.pysparknotebook;
        }
        else {
            $scope.network = false;
        }
        $scope.status = data.status;
        $scope.apply();
    }).error(function(data, status, headers, config) {
        $scope.ipchunks = [{i:0}, {i:0}];
    });

    var remote_conn = false;

    get_remote_conn = function(ip) {
        remote_conn = new WebSocket("ws://"+ip+":5001");

        remote_conn.onopen = function() {
            remote_conn.send('remote_socket');
        };

        remote_conn.onmessage = function(e) {
            var msChunks = e.data.split(" ");
            var ms_action = parseInt(msg[msChunks[0]]);
            switch (ms_action) {
                case msg.stopped_sparkmaster:
                $scope.status = 'dormant'; $scope.slaves = 0; $scope.$apply(); $scope.leave_cluster(); break;
                case msg.slave_count: $scope.slaves = msChunks[1]; $scope.$apply(); break;
            }
        };
    };

    var auto_conn = false;

    get_auto_conn = function(ip) {
        auto_conn =  WebSocket("ws://"+ip+":5001");
        auto_conn.onopen = function() {
            auto_conn.send('local_socket');
        };
    };

    auto_conn.onmessage = function(e) {
        var msChunks = e.data.split(" ");
        var ms_action = parseInt(msg[msChunks[0]]);
        switch (ms_action) {
            case msg.master_active:
                $scope.status = 'active'; $scope.master_owner = true; $scope.master_ip = msChunks[1]; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.slave_active:
                $scope.status = 'active'; $scope.slave_ip = msChunks[1]; $scope.slave_owner.active = true; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.notebook_active:
                $scope.status = 'active'; $scope.pysparknotebook = true; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_pysparknotebook:
                $scope.status = 'active'; $scope.pysparknotebook = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_sparkmaster:
                $scope.status = 'dormant'; $scope.slaves = 0; $scope.master_owner = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.stopped_sparkslave:
                $scope.status = 'dormant'; $scope.slave_owner.active = false; $scope.slave_ip = false; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.node_active: $scope.status = "single"; spinnerService.hide('wait'); $scope.$apply(); break;
            case msg.hdfs_active: $scope.hdfs.active = true; $scope.hdfs.waiting=false; $scope.hdfs_ip = msChunks[1]; $scope.$broadcast('hdfsUp', true); $scope.$apply(); break;
            case msg.stopped_hdfs: $scope.hdfs.active = false; $scope.hdfs.starting = false; $scope.$broadcast('hdfsDown', true); $scope.$apply(); break;
            case msg.slave_count: $scope.slaves = msChunks[1]; $scope.$apply(); break;
            case msg.stopped_singlenode:
                if ($scope.network) {
                    $scope.status = 'dormant';
                } else {
                    $scope.status = 'error';
                }
                spinnerService.hide('wait'); $scope.$apply(); break;
        }
    }

    $scope.test_ip = function() {
        var trial_ip = ([$scope.ipchunks[0].i, $scope.ipchunks[1].i, $scope.chunk3.i, $scope.chunk4.i]).join('.');
        var params =  '&ip='+trial_ip+'&id='+$scope.app_id;
        $http.jsonp("http://"+trial_ip+":5000/api/testip?callback=JSON_CALLBACK"+params).success(function(data) {
            if (data.okay) {
                $scope.ip.real = true;
                $scope.ip.value = trial_ip;
                get_auto_conn(trial_ip);
                $scope.$apply();
            }
        });

    };

    $scope.start_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get('api/startcluster',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                $scope.status = 'dormant';
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.join_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        var master_ip = ([$scope.ipchunks[0].i, $scope.ipchunks[1].i, $scope.chunk3.i, $scope.chunk4.i]).join('.');
        $scope.master_ip = master_ip
        $http.get('api/joincluster',{params: {'ip':master_ip}}).success(function(data, status, headers, config) {
            $scope.master_url = master_ip+":8080";
            if (!data.okay) {
                $scope.error.msg = data.error;
                $scope.status = 'dormant';
                spinnerService.hide('wait');
            } else {
                 get_remote_conn(master_ip);
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.leave_cluster = function() {
        remote_conn.close();
        $http.get('api/leavecluster',{params: {'ip':$scope.master_ip}}).success(function(data, status, headers, config) {
        }).error(function(data, status, headers, config) {});
    }

    $scope.notebook_cluster = function() {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get('api/startclusternotebook',{params: {'ip':$scope.master_ip}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

    $scope.start_hdfs = function() {
        $scope.hdfs.starting = true;
        $http.get('api/starthdfs',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
            }
        }).error(function(data, status, headers, config) {});
    };

     $scope.stop_hdfs = function() {
         $http.get('api/stophdfs',{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
            }
        }).error(function(data, status, headers, config) {});
     };

    $scope.cluster_notebook_stop = function() {
        simple_service('api/stopclusternotebook');
    };

    $scope.stop_cluster = function() {
        simple_service('api/stopcluster');
    };

    $scope.start_single_node = function() {
        simple_service('/api/startsinglenotebook');
    };

    $scope.single_notebook_stop = function() {
        simple_service('/api/stopsinglenotebook');
    };

    simple_service = function(endpoint) {
        $scope.status = 'waiting';
        spinnerService.show('wait');
        $http.get(endpoint,{params: {}}).success(function(data, status, headers, config) {
            if (!data.okay) {
                $scope.error.msg = data.error;
                spinnerService.hide('wait');
            }
        }).error(function(data, status, headers, config) {});
    };

});

mainModule.controller('docController',function($scope,$http) {

    $http.get('api/getdocs',{params: {}}).success(function(data, status, headers, config) {
        $scope.allthedocs = data.allthedocs;
    }).error(function(data, status, headers, config) {
    });

});

mainModule.controller('uploadController', ['$scope','Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.upload = {"active":false};

    $scope.$on('hdfsUp', function(event, args) {$scope.upload.active=true; $scope.$apply();});
    $scope.$on('hdfsDown', function(event, args) {$scope.upload.active=false; $scope.$apply();});

    $scope.uploadFile = function (file, errFiles) {
        if (file) {
            file.upload = Upload.upload({
                url: 'api/hdfsupload',
                data: {file: file, name: file.name}
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                                         evt.loaded / evt.total));
            });

        }

    };

}]);
<|endoftext|>


<commit_before>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(FILL_ME_IN);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(FILL_ME_IN);
    expect(multiTypeArray[2]).toBe(FILL_ME_IN);
    expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
    expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
    expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
    expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, FILL_ME_IN]);

    array.push(3);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(FILL_ME_IN);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(FILL_ME_IN);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>First complete attempt - AboutArrays<commit_after>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe(Object); //A mistake? - http:javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1, 2]);

    array.push(3);
    expect(array).toEqual([1,2,3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(["peanut"]);
    expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
    expect(array.slice(2, 2)).toEqual([]]);
    expect(array.slice(2, 20)).toEqual(["and", "jelly"]);
    expect(array.slice(3, 0)).toEqual([]]);
    expect(array.slice(3, 100)).toEqual(["jelly"]);
    expect(array.slice(5, 1)).toEqual([]]);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
      refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe("changed in function");

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe("changed in assignedArray");

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe("three");
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual([1,2,3]);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(3);
    expect(array).toEqual([1,2]);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual([3,1,2]);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(3);
    expect(array).toEqual([1,2]);
  });
});
<|endoftext|>


<commit_before>const svarUt = require('../index')
const fs = require('fs')

const options = {
  config: {
    url: process.env.SVARUT_URL || 'https://username:password@test.svarut.ks.no/tjenester/forsendelseservice/ForsendelsesServiceV7'
  },
  query: {
    dokumenter: [
      {
        data: fs.readFileSync('../test/data/skoleskyss_avslag_vedtak.pdf').toString('base64'), // Must be base64
        filnavn: 'skoleskyss_avslag_vedtak.pdf',
        mimetype: 'application/pdf'
      }
    ],
    tittel: 'SvarUt testdokument',
    avgivendeSystem: 'node-svarut test',
    konteringskode: '1111',
    krevNiva4Innlogging: false,
    kryptert: false,
    kunDigitalLevering: false,
    printkonfigurasjon: {
      brevtype: 'BPOST',
      fargePrint: true,
      tosidig: false
    },
    eksternref: 11,
    forsendelseType: 'string',
    lenker: [
      {
        ledetekst: 'string',
        urlLenke: 'string',
        urlTekst: 'string'
      }
    ],
    metadataForImport: {
      dokumentetsDato: new Date().toISOString(),
      journalposttype: 'string',
      journalstatus: 'string',
      saksaar: 11,
      sakssekvensnummer: 11,
      tittel: 'string'
    },
    metadataFraAvleverendeSystem: {
      dokumentetsDato: new Date().toISOString(),
      ekstraMetadata: [
        {
          key: 'string',
          value: 'string'
        }
      ],
      journalaar: 11,
      journaldato: new Date().toISOString(),
      journalpostnummer: 11,
      journalposttype: 'string',
      journalsekvensnummer: 11,
      journalstatus: 'string',
      saksaar: 111,
      saksbehandler: 111,
      sakssekvensnummer: 111,
      tittel: 'string'
    },
    signaturtype: 'AUTENTISERT_SIGNATUR',
    signeringUtloper: new Date().toISOString(),
    svarPaForsendelse: 'http://google.no',
    svarPaForsendelseLink: false,
    svarSendesTil: {
      navn: 'Terje Tverrtryne',
      adresse1: 'Skogsveien 42',
      adresse2: '',
      adresse3: '',
      postnr: '3710',
      poststed: 'Skien',
      fodselsnr: '01029400470'
    },
    mottaker: [
      {
        navn: 'Terje Tverrtryne',
        adresse1: 'Skogsveien 42',
        adresse2: '',
        adresse3: '',
        postnr: '3710',
        poststed: 'Skien',
        fodselsnr: '01029400470'
        // orgnr: '940192226' // Hvis organisasjon
      }
    ]
  }
}

svarUt.sendForsendelse(options)
  .then(data => console.log(JSON.stringify(data, null, 2)))
  .catch(error => console.error(error))
<commit_msg>fodselsnr to fnr<commit_after>const svarUt = require('../index')
const fs = require('fs')

const options = {
  config: {
    url: process.env.SVARUT_URL || 'https://username:password@test.svarut.ks.no/tjenester/forsendelseservice/ForsendelsesServiceV7'
  },
  query: {
    dokumenter: [
      {
        data: fs.readFileSync('../test/data/skoleskyss_avslag_vedtak.pdf').toString('base64'), // Must be base64
        filnavn: 'skoleskyss_avslag_vedtak.pdf',
        mimetype: 'application/pdf'
      }
    ],
    tittel: 'SvarUt testdokument',
    avgivendeSystem: 'node-svarut test',
    konteringskode: '1111',
    krevNiva4Innlogging: false,
    kryptert: false,
    kunDigitalLevering: false,
    printkonfigurasjon: {
      brevtype: 'BPOST',
      fargePrint: true,
      tosidig: false
    },
    eksternref: 11,
    forsendelseType: 'string',
    lenker: [
      {
        ledetekst: 'string',
        urlLenke: 'string',
        urlTekst: 'string'
      }
    ],
    metadataForImport: {
      dokumentetsDato: new Date().toISOString(),
      journalposttype: 'string',
      journalstatus: 'string',
      saksaar: 11,
      sakssekvensnummer: 11,
      tittel: 'string'
    },
    metadataFraAvleverendeSystem: {
      dokumentetsDato: new Date().toISOString(),
      ekstraMetadata: [
        {
          key: 'string',
          value: 'string'
        }
      ],
      journalaar: 11,
      journaldato: new Date().toISOString(),
      journalpostnummer: 11,
      journalposttype: 'string',
      journalsekvensnummer: 11,
      journalstatus: 'string',
      saksaar: 111,
      saksbehandler: 111,
      sakssekvensnummer: 111,
      tittel: 'string'
    },
    signaturtype: 'AUTENTISERT_SIGNATUR',
    signeringUtloper: new Date().toISOString(),
    svarPaForsendelse: 'http://google.no',
    svarPaForsendelseLink: false,
    svarSendesTil: {
      navn: 'Terje Tverrtryne',
      adresse1: 'Skogsveien 42',
      adresse2: '',
      adresse3: '',
      postnr: '3710',
      poststed: 'Skien',
      fodselsnr: '01029400470'
    },
    mottaker: [
      {
        navn: 'Terje Tverrtryne',
        adresse1: 'Skogsveien 42',
        adresse2: '',
        adresse3: '',
        postnr: '3710',
        poststed: 'Skien',
        fnr: '01029400470'
        // orgnr: '940192226' // Hvis organisasjon
      }
    ]
  }
}

svarUt.sendForsendelse(options)
  .then(data => console.log(JSON.stringify(data, null, 2)))
  .catch(error => console.error(error))
<|endoftext|>


<commit_before>'use strict';

var callable   = require('es5-ext/object/valid-callable')
  , d          = require('d/d')
  , isCallable = require('es5-ext/object/is-callable')
  , ee         = require('event-emitter')
  , isPromise  = require('./is-promise')

  , create = Object.create, defineProperty = Object.defineProperty
  , deferred, resolve, reject;

module.exports = exports = function (name, unres, onres, res) {
	name = String(name);
	(callable(res) && ((onres == null) || callable(onres)) && callable(unres));
	defineProperty(exports._unresolved, name, d(unres));
	exports._onresolve[name] = onres;
	defineProperty(exports._resolved, name, d(res));
	exports._names.push(name);
};

exports._names = ['done', 'then', 'valueOf'];

exports._unresolved = ee(create(Function.prototype, {
	then: d(function (win, fail) {
		var def;
		if (!this.pending) this.pending = [];
		def = deferred();
		this.pending.push('then', [win, fail, def.resolve, def.reject]);
		return def.promise;
	}),
	done: d(function (win, fail) {
		((win == null) || callable(win));
		((fail == null) || callable(fail));
		if (!this.pending) this.pending = [];
		this.pending.push('done', arguments);
	}),
	resolved: d(false),
	returnsPromise: d(true),
	valueOf: d(function () { return this; })
}));

exports._onresolve = {
	then: function (win, fail, resolve, reject) {
		var value, cb = this.failed ? fail : win;
		if (cb == null) {
			if (this.failed) reject(this.value);
			else resolve(this.value);
			return;
		}
		if (isCallable(cb)) {
			if (isPromise(cb)) {
				if (cb.resolved) {
					if (cb.failed) reject(cb.value);
					else resolve(cb.value);
					return;
				}
				cb.done(resolve, reject);
				return;
			}
			try { value = cb(this.value); } catch (e) {
				reject(e);
				return;
			}
			resolve(value);
			return;
		}
		resolve(cb);
	},
	done: function (win, fail) {
		if (this.failed) {
			if (fail) {
				fail(this.value);
				return;
			}
			throw this.value;
		}
		if (win) win(this.value);
	}
};

exports._resolved = ee(create(Function.prototype, {
	then: d(function (win, fail) {
		var value, cb = this.failed ? fail : win;
		if (cb == null) return this;
		if (isCallable(cb)) {
			if (isPromise(cb)) return cb;
			try { value = cb(this.value); } catch (e) { return reject(e); }
			return resolve(value);
		}
		return resolve(cb);
	}),
	done: d(function (win, fail) {
		((win == null) || callable(win));
		((fail == null) || callable(fail));
		if (this.failed) {
			if (fail) {
				fail(this.value);
				return;
			}
			throw this.value;
		}
		if (win) win(this.value);
	}),
	resolved: d(true),
	returnsPromise: d(true),
	valueOf: d(function () { return this.value; })
}));

deferred = require('./deferred');
resolve = deferred.resolve;
reject = deferred.reject;
deferred.extend = exports;
<commit_msg>Update up to changes in d package<commit_after>'use strict';

var callable   = require('es5-ext/object/valid-callable')
  , d          = require('d')
  , isCallable = require('es5-ext/object/is-callable')
  , ee         = require('event-emitter')
  , isPromise  = require('./is-promise')

  , create = Object.create, defineProperty = Object.defineProperty
  , deferred, resolve, reject;

module.exports = exports = function (name, unres, onres, res) {
	name = String(name);
	(callable(res) && ((onres == null) || callable(onres)) && callable(unres));
	defineProperty(exports._unresolved, name, d(unres));
	exports._onresolve[name] = onres;
	defineProperty(exports._resolved, name, d(res));
	exports._names.push(name);
};

exports._names = ['done', 'then', 'valueOf'];

exports._unresolved = ee(create(Function.prototype, {
	then: d(function (win, fail) {
		var def;
		if (!this.pending) this.pending = [];
		def = deferred();
		this.pending.push('then', [win, fail, def.resolve, def.reject]);
		return def.promise;
	}),
	done: d(function (win, fail) {
		((win == null) || callable(win));
		((fail == null) || callable(fail));
		if (!this.pending) this.pending = [];
		this.pending.push('done', arguments);
	}),
	resolved: d(false),
	returnsPromise: d(true),
	valueOf: d(function () { return this; })
}));

exports._onresolve = {
	then: function (win, fail, resolve, reject) {
		var value, cb = this.failed ? fail : win;
		if (cb == null) {
			if (this.failed) reject(this.value);
			else resolve(this.value);
			return;
		}
		if (isCallable(cb)) {
			if (isPromise(cb)) {
				if (cb.resolved) {
					if (cb.failed) reject(cb.value);
					else resolve(cb.value);
					return;
				}
				cb.done(resolve, reject);
				return;
			}
			try { value = cb(this.value); } catch (e) {
				reject(e);
				return;
			}
			resolve(value);
			return;
		}
		resolve(cb);
	},
	done: function (win, fail) {
		if (this.failed) {
			if (fail) {
				fail(this.value);
				return;
			}
			throw this.value;
		}
		if (win) win(this.value);
	}
};

exports._resolved = ee(create(Function.prototype, {
	then: d(function (win, fail) {
		var value, cb = this.failed ? fail : win;
		if (cb == null) return this;
		if (isCallable(cb)) {
			if (isPromise(cb)) return cb;
			try { value = cb(this.value); } catch (e) { return reject(e); }
			return resolve(value);
		}
		return resolve(cb);
	}),
	done: d(function (win, fail) {
		((win == null) || callable(win));
		((fail == null) || callable(fail));
		if (this.failed) {
			if (fail) {
				fail(this.value);
				return;
			}
			throw this.value;
		}
		if (win) win(this.value);
	}),
	resolved: d(true),
	returnsPromise: d(true),
	valueOf: d(function () { return this.value; })
}));

deferred = require('./deferred');
resolve = deferred.resolve;
reject = deferred.reject;
deferred.extend = exports;
<|endoftext|>


<commit_before>var AWS           = require('aws-sdk')
    , fs          = require('fs-extra')
    , path        = require('path')
    , async       = require('async')
    , chalk       = require('chalk')
    , ncp         = require('ncp')
    , gulp        = require('gulp')
    , zip         = require('gulp-zip')
    , gutil       = require('gulp-util')
    , task        = require('gulp-task')
    , pkg         = require(process.cwd() + '/package.json')
    ;

var data = {
  folderPath: null,   //e.g. ./functions/hello-world
  distPath: null,     //e.g. ./dist/hello-world
  environment: null   //e.g. staging
};

var clean = function(callback) {
  gutil.log('cleanup prep...');

  fs.remove(path.join(process.cwd(), 'dist'), function(err) {
    if (err) return callback(err);
    fs.ensureDir(data.distPath, function(err) { callback(err); });
  });
};

var npm = function(callback) {
  gutil.log('copying NPM modules for deployment...');
  ncp(
    path.join(process.cwd(), 'node_modules'),
    path.join(data.distPath, 'node_modules'),
    function(err) { callback(err); }
  );

};

// var envFile = function(callback) {
//   console.log('copying .env file...');
//   //use environment specific .env file if there is one
//   fs.exists(path.join(data.folderPath, '.env.' + data.environment), function(exists) {
//     var filename = "";

//     if (exists) {
//       filename = path.join(data.folderPath, '.env.' + data.environment);
//       console.log(chalk.yellow('using .env.' + data.environment + '...'), filename);
//       fs.createReadStream(filename).pipe(fs.createWriteStream(path.join(data.distPath, '.env.' + data.environment)));
//     }
//     else {
//       filename = path.join(data.folderPath, '.env');
//       console.log('copying file:', filename);
//       fs.createReadStream(filename).pipe(fs.createWriteStream(path.join(data.distPath, '.env')));
//     }

//     callback(null);
//   });
// };

var makeDist = function(callback) {
  gutil.log('creating dist folder...');

  //copy any file dependencies
  var devRoot = path.join(process.cwd(), 'dependencies');
  var runRoot = path.join(process.cwd(), 'node_modules/lambinator/dependencies');
  var lambRoot = fs.existsSync(runRoot) ? runRoot : devRoot;

  if (data.dependencies) {
    data.dependencies.forEach(function(file) {
      gutil.log('adding dependency:', file);
      var functionDependency = path.join(data.folderPath, file);
      var globalDependency = path.join(lambRoot, file);

      // console.log('functionDependency', functionDependency);
      // console.log('globalDependency', globalDependency);

      //look in function directory for file
      if (fs.existsSync(functionDependency)) {
        fs.copySync(functionDependency, path.join(data.distPath, file));
        // fs.createReadStream(functionDependency).pipe(fs.createWriteStream(path.join(data.distPath, file)));
      }
      //look in global dependencies folder
      else if (fs.existsSync(globalDependency)) {
        fs.copySync(globalDependency, path.join(data.distPath, file));
        // fs.createReadStream(globalDependency).pipe(fs.createWriteStream(path.join(data.distPath, file)));
      }
    });
  }

  //copy function itself
  var functionFile = path.join(data.folderPath, data.functionName + '.js');
  gutil.log('copying function:', functionFile);
  fs.createReadStream(functionFile).pipe(fs.createWriteStream(path.join(data.distPath, data.functionName + '.js')));
  callback(null);
};

// var zipFiles = function(callback) {
//   var input = data.distPath;
//   var output = path.join(process.cwd(), 'dist', data.functionName + '.zip');
//   var zip = new Zip();

//   console.log('zipping contents in ' + input + '...');
//   console.log('zipping to ' + output + '...');

//   zip.add(output, input)
//     .then(callback)
//     .catch(callback);
// };

var zipFiles = function(callback) {
  gutil.log('zipping files...');
  try {
    task.run(function() {
      gulp.src(data.distPath + '/**/*')
        .pipe(zip(data.functionName + '.zip'))
        .pipe(gulp.dest('./dist'));
    })
      .then(function() {
        callback(null);
      });
  }
  catch(err) {
    callback(err);
  }
};

var upload = function(callback) {
  var lambda;

  //use .env file to load permissions to use for Lambda execution, if a .env exists
  if (fs.existsSync(path.join(process.cwd(), '.env'))) {
    gutil.log('.env file exists, checking for AWS permission keys...');
    require('dotenv').load();
    if (process.env.accessKeyId && process.env.secretAccessKey && process.env.region) {
      gutil.log('using .env for Lambda permissions...');
      lambda = new AWS.Lambda({
        accessKeyId: process.env.accessKeyId,
        secretAccessKey: process.env.secretAccessKey,
        region: process.env.region
      });
    }
    else {
      gutil.log('AWS permission keys not found - using default...');
      lambda = new AWS.Lambda();
    }
  }
  else {
      gutil.log('No .env file found - using default...');
      lambda = new AWS.Lambda();
  }

  var functionName = data.environment + '-' + data.functionName;
  var zipFile = './dist/' + data.functionName + '.zip';

  var createLambda = function() {
    gutil.log('Updating function ' + functionName);

    var params = {
      Code: {
        ZipFile: fs.readFileSync(zipFile)
      },
      FunctionName: functionName,
      Handler: data.handler,
      Role: data.roleArn,
      Runtime: 'nodejs',  /* duh */
      Description: data.description,
      MemorySize: data.memorySize,
      Timeout: data.timeout
    };

    lambda.createFunction(params, function(err, result) {
      if (err) {
        gutil.log(chalk.red('Error uploading ' + data.functionName), err);
        callback(err);
      }
      else  {
        callback(null);
      }
    });
  }

  var updateLambda = function() {
    var params = {
      FunctionName: functionName,
      ZipFile: fs.readFileSync(zipFile)
    };

    gutil.log('Updating function ' + functionName + ' from ' + zipFile);

    lambda.updateFunctionCode(params, function(err, result) {
      if (err) {
        gutil.log(chalk.red('Error uploading ' + functionName), err);
        callback(err);
      }
      else {
        callback();
      }
    });
  }

  var startUpload = function() {
    lambda.getFunction({FunctionName: functionName}, function(err, result) {
      if (err) {
        if (err.statusCode === 404) {
          //function doesn't exist yet -- call lambda.createFunction to create it
          createLambda();
        }
        else {
          var warning = 'AWS API request failed. '
          warning += 'Check your AWS credentials and permissions.'
          gutil.log(chalk.yellow(warning));
          callback(new Error(warning));
        }
      }
      else {
        //function already exists -- upload latest version
        updateLambda();
      }
    });
  };

  //having async issues with zip task completing -- wait a second before starting upload
  setTimeout(startUpload, 7000);
};

var main = function(functionName, environment, zipOnly) {
  var folderPath = path.join(process.cwd(), '/functions', '/' + functionName);
  gutil.log('deploying function', folderPath);

  //set up global data
  data = JSON.parse(fs.readFileSync(path.join(folderPath, 'lambinator.json'), {encoding:'utf-8'}));
  data.folderPath = folderPath;
  data.distPath = path.join(process.cwd(), '/dist', functionName);
  data.environment = environment;

  gutil.log('data', data);

  var functionsToRun = [clean, npm, makeDist, zipFiles];
  if (!zipOnly) functionsToRun.push(upload);

  //let the water fall baby
  async.waterfall(functionsToRun, function(err, results) {
    if (err) {
      gutil.log('ERROR', err);
    }
    else {
      gutil.log('Done!');
    }
  });
};

module.exports = main;
<commit_msg>added logging for deploy<commit_after>var AWS           = require('aws-sdk')
    , fs          = require('fs-extra')
    , path        = require('path')
    , async       = require('async')
    , chalk       = require('chalk')
    , ncp         = require('ncp')
    , gulp        = require('gulp')
    , zip         = require('gulp-zip')
    , gutil       = require('gulp-util')
    , task        = require('gulp-task')
    , pkg         = require(process.cwd() + '/package.json')
    ;

var data = {
  folderPath: null,   //e.g. ./functions/hello-world
  distPath: null,     //e.g. ./dist/hello-world
  environment: null   //e.g. staging
};

var clean = function(callback) {
  gutil.log('cleanup prep...');

  fs.remove(path.join(process.cwd(), 'dist'), function(err) {
    if (err) return callback(err);
    fs.ensureDir(data.distPath, function(err) { callback(err); });
  });
};

var npm = function(callback) {
  gutil.log('copying NPM modules for deployment...');
  ncp(
    path.join(process.cwd(), 'node_modules'),
    path.join(data.distPath, 'node_modules'),
    function(err) { callback(err); }
  );

};

// var envFile = function(callback) {
//   console.log('copying .env file...');
//   //use environment specific .env file if there is one
//   fs.exists(path.join(data.folderPath, '.env.' + data.environment), function(exists) {
//     var filename = "";

//     if (exists) {
//       filename = path.join(data.folderPath, '.env.' + data.environment);
//       console.log(chalk.yellow('using .env.' + data.environment + '...'), filename);
//       fs.createReadStream(filename).pipe(fs.createWriteStream(path.join(data.distPath, '.env.' + data.environment)));
//     }
//     else {
//       filename = path.join(data.folderPath, '.env');
//       console.log('copying file:', filename);
//       fs.createReadStream(filename).pipe(fs.createWriteStream(path.join(data.distPath, '.env')));
//     }

//     callback(null);
//   });
// };

var makeDist = function(callback) {
  gutil.log('creating dist folder...');

  //copy any file dependencies
  var devRoot = path.join(process.cwd(), 'dependencies');
  var runRoot = path.join(process.cwd(), 'node_modules/lambinator/dependencies');
  var lambRoot = fs.existsSync(runRoot) ? runRoot : devRoot;

  if (data.dependencies) {
    data.dependencies.forEach(function(file) {
      gutil.log('adding dependency:', file);
      var functionDependency = path.join(data.folderPath, file);
      var globalDependency = path.join(lambRoot, file);

      //look in function directory for file
      if (fs.existsSync(functionDependency)) {
        gutil.log('functionDependency', functionDependency);
        fs.copySync(functionDependency, path.join(data.distPath, file));
        // fs.createReadStream(functionDependency).pipe(fs.createWriteStream(path.join(data.distPath, file)));
      }
      //look in global dependencies folder
      else if (fs.existsSync(globalDependency)) {
        gutil.log('globalDependency', globalDependency);
        fs.copySync(globalDependency, path.join(data.distPath, file));
        // fs.createReadStream(globalDependency).pipe(fs.createWriteStream(path.join(data.distPath, file)));
      }
    });
  }

  //copy function itself
  var functionFile = path.join(data.folderPath, data.functionName + '.js');
  gutil.log('copying function:', functionFile);
  fs.createReadStream(functionFile).pipe(fs.createWriteStream(path.join(data.distPath, data.functionName + '.js')));
  callback(null);
};

// var zipFiles = function(callback) {
//   var input = data.distPath;
//   var output = path.join(process.cwd(), 'dist', data.functionName + '.zip');
//   var zip = new Zip();

//   console.log('zipping contents in ' + input + '...');
//   console.log('zipping to ' + output + '...');

//   zip.add(output, input)
//     .then(callback)
//     .catch(callback);
// };

var zipFiles = function(callback) {
  gutil.log('zipping files...');
  try {
    task.run(function() {
      gulp.src(data.distPath + '/**/*')
        .pipe(zip(data.functionName + '.zip'))
        .pipe(gulp.dest('./dist'));
    })
      .then(function() {
        callback(null);
      });
  }
  catch(err) {
    callback(err);
  }
};

var upload = function(callback) {
  var lambda;

  //use .env file to load permissions to use for Lambda execution, if a .env exists
  if (fs.existsSync(path.join(process.cwd(), '.env'))) {
    gutil.log('.env file exists, checking for AWS permission keys...');
    require('dotenv').load();
    if (process.env.accessKeyId && process.env.secretAccessKey && process.env.region) {
      gutil.log('using .env for Lambda permissions...');
      lambda = new AWS.Lambda({
        accessKeyId: process.env.accessKeyId,
        secretAccessKey: process.env.secretAccessKey,
        region: process.env.region
      });
    }
    else {
      gutil.log('AWS permission keys not found - using default...');
      lambda = new AWS.Lambda();
    }
  }
  else {
      gutil.log('No .env file found - using default...');
      lambda = new AWS.Lambda();
  }

  var functionName = data.environment + '-' + data.functionName;
  var zipFile = './dist/' + data.functionName + '.zip';

  var createLambda = function() {
    gutil.log('Updating function ' + functionName);

    var params = {
      Code: {
        ZipFile: fs.readFileSync(zipFile)
      },
      FunctionName: functionName,
      Handler: data.handler,
      Role: data.roleArn,
      Runtime: 'nodejs',  /* duh */
      Description: data.description,
      MemorySize: data.memorySize,
      Timeout: data.timeout
    };

    lambda.createFunction(params, function(err, result) {
      if (err) {
        gutil.log(chalk.red('Error uploading ' + data.functionName), err);
        callback(err);
      }
      else  {
        callback(null);
      }
    });
  }

  var updateLambda = function() {
    var params = {
      FunctionName: functionName,
      ZipFile: fs.readFileSync(zipFile)
    };

    gutil.log('Updating function ' + functionName + ' from ' + zipFile);

    lambda.updateFunctionCode(params, function(err, result) {
      if (err) {
        gutil.log(chalk.red('Error uploading ' + functionName), err);
        callback(err);
      }
      else {
        callback();
      }
    });
  }

  var startUpload = function() {
    lambda.getFunction({FunctionName: functionName}, function(err, result) {
      if (err) {
        if (err.statusCode === 404) {
          //function doesn't exist yet -- call lambda.createFunction to create it
          createLambda();
        }
        else {
          var warning = 'AWS API request failed. '
          warning += 'Check your AWS credentials and permissions.'
          gutil.log(chalk.yellow(warning));
          callback(new Error(warning));
        }
      }
      else {
        //function already exists -- upload latest version
        updateLambda();
      }
    });
  };

  //having async issues with zip task completing -- wait a second before starting upload
  setTimeout(startUpload, 7000);
};

var main = function(functionName, environment, zipOnly) {
  var folderPath = path.join(process.cwd(), '/functions', '/' + functionName);
  gutil.log('deploying function', folderPath);

  //set up global data
  data = JSON.parse(fs.readFileSync(path.join(folderPath, 'lambinator.json'), {encoding:'utf-8'}));
  data.folderPath = folderPath;
  data.distPath = path.join(process.cwd(), '/dist', functionName);
  data.environment = environment;

  gutil.log('data', data);

  var functionsToRun = [clean, npm, makeDist, zipFiles];
  if (!zipOnly) functionsToRun.push(upload);

  //let the water fall baby
  async.waterfall(functionsToRun, function(err, results) {
    if (err) {
      gutil.log('ERROR', err);
    }
    else {
      gutil.log('Done!');
    }
  });
};

module.exports = main;
<|endoftext|>


<commit_before>import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import { existsSync } from 'fs';
import { join } from 'path';
import autoprefixer from 'autoprefixer';
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import notifier from 'node-notifier';

import getBabelCommonConfig from './getBabelCommonConfig';
/* eslint quotes:0 */

export default function getWebpackCommonConfig(args = {}) {
    const pkgPath = join(args.cwd || '.', 'package.json');
    const pkg = existsSync(pkgPath) ? require(pkgPath) : {};

    const jsFileName = args.hash ? '[name]-[chunkhash].js' : '[name].js';
    const cssFileName = args.hash ? '[name]-[chunkhash].css' : '[name].css';
    const commonName = args.hash ? 'PICIDAE_COMMON-[chunkhash].js' : 'PICIDAE_COMMON.js';
    const chunkFilename = args.hash ? '[name]-[chunkhash].js' : '[name].js';
    //         chunkFilename: 'modules/[name].min.js?v=[chunkhash]'

    const silent = args.silent === true;
    const dev = 'dev' in args ? args.dev : true
    const babelOptions = getBabelCommonConfig();

    const postcssOptions = {
        sourceMap: true,
        plugins: [
            // require('postcss-focus'),
            autoprefixer({
                browsers: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 8', 'iOS >= 8', 'Android >= 4'],
            }),
        ],
    };

    const emptyBuildins = [
        'child_process',
        'cluster',
        'dgram',
        'dns',
        'fs',
        'module',
        'net',
        'readline',
        'repl',
        'tls',
    ];

    const browser = pkg.browser || {};

    const node = emptyBuildins.reduce((obj, name) => {
        if (!(name in browser)) {
            return { ...obj, ...{ [name]: 'empty' } };
        }
        return obj;
    }, {});

    const config = {
        babel: babelOptions,
        cache: true,
        postcss: postcssOptions,
        output: {
            path: join(process.cwd(), './dist/'),
            filename: jsFileName,
            chunkFilename: chunkFilename,
        },

        devtool: dev && 'source-map',

        // context: join(__dirname, '/../../../node_modules'),

        resolve: {
            modules: ['node_modules', join(__dirname, '/../../../node_modules')],
            // root: ['node_modules', join(__dirname, '/../../../node_modules')],
        },

        entry: pkg.entry,

        node,

        module: {
            // noParse: [/moment.js/],
            loaders: [
                {
                    test: /\.less$/,
                    loader: dev
                        ? 'style-loader!css-loader?sourceMap!postcss-loader?sourceMap!less-loader?sourceMap'
                        : ExtractTextPlugin.extract(['css-loader', 'postcss-loader', 'less-loader'])
                },
                {
                    test: /\.css$/,
                    loader: dev
                        ? 'style-loader!css-loader?sourceMap'
                        : ExtractTextPlugin.extract(['css-loader', 'postcss-loader'])
                },
                {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    exclude: [
                        function (name) {
                            return !/\/picidae-(plugin|transformer|theme|commander)/.test(name)
                                && !/(node_modules|bower_components)\/picidae/.test(name)
                                && /(node_modules|bower_components)/.test(name)
                        },
                        /\/node_modules\/core-js\//
                    ],
                    options: babelOptions,
                },
                {
                    test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/font-woff',
                    },
                },
                {
                    test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/font-woff',
                    },
                },
                {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/octet-stream',
                    },
                },
                {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/vnd.ms-fontobject',
                    },
                },
                {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'image/svg+xml',
                    },
                },
                {
                    test: /\.(png|jpg|jpeg|gif)(\?v=\d+\.\d+\.\d+)?$/i,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                    },
                },
                {
                    test: /\.html?$/,
                    loader: 'file-loader',
                    options: {
                    },
                },
                {
                    test: /\.json$/,
                    loader: 'json-loader',
                    options: {
                        name: '[path][name].[ext]',
                    },
                },
            ],
        },

        plugins: [
            new webpack.ProgressPlugin(function(percentage, msg) {
                const stream = process.stdout;
                if (stream.isTTY && percentage < 0.71) {
                    stream.cursorTo(0);
                    stream.write('  ' + require('chalk').cyan(msg));
                    stream.clearLine(1);
                } else if (percentage === 1) {
                    console.log('');
                    console.log(require('chalk').cyan('webpack: bundle build is now finished.'));
                }
            }),
            args.hash && new webpack.optimize.CommonsChunkPlugin('common', commonName),
            new ExtractTextPlugin('style.css', {
                // filename: cssFileName,
                disable: false,
                allChunks: true,
            }),
            dev && new webpack.HotModuleReplacementPlugin(),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': dev ? '"development"' : '"production"',
            }),
            new webpack.optimize.OccurrenceOrderPlugin(),
            !dev && new webpack.optimize.UglifyJsPlugin({
                output: {comments: false},
                compress: {
                    warnings: false
                }
            }),
            new CaseSensitivePathsPlugin(),
            dev && new FriendlyErrorsWebpackPlugin({
                onErrors: (severity, errors) => {
                    if (silent) return;
                    if (severity !== 'error') {
                        notifier.notify({
                            title: 'picidae',
                            message: 'warn',
                            // contentImage: join(__dirname, '../assets/warn.png'),
                            sound: 'Glass',
                        });
                        return;
                    }
                    const error = errors[0];
                    notifier.notify({
                        title: 'picidae',
                        message: `${severity} : ${error.name}`,
                        subtitle: error.file || '',
                        // contentImage: join(__dirname, '../assets/fail.png'),
                        sound: 'Glass',
                    });
                },
            }),
        ].filter(Boolean),
    };

    return config;
}
<commit_msg>append commonjs<commit_after>import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import { existsSync } from 'fs';
import { join } from 'path';
import autoprefixer from 'autoprefixer';
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import notifier from 'node-notifier';

import getBabelCommonConfig from './getBabelCommonConfig';
/* eslint quotes:0 */

export default function getWebpackCommonConfig(args = {}) {
    const pkgPath = join(args.cwd || '.', 'package.json');
    const pkg = existsSync(pkgPath) ? require(pkgPath) : {};

    const jsFileName = args.hash ? '[name]-[chunkhash].js' : '[name].js';
    const cssFileName = args.hash ? '[name]-[chunkhash].css' : '[name].css';
    const commonName = args.hash ? 'PICIDAE_COMMON-[chunkhash].js' : 'PICIDAE_COMMON.js';
    const chunkFilename = args.hash ? '[name]-[chunkhash].js' : '[name].js';
    //         chunkFilename: 'modules/[name].min.js?v=[chunkhash]'

    const silent = args.silent === true;
    const dev = 'dev' in args ? args.dev : true
    const babelOptions = getBabelCommonConfig();

    const postcssOptions = {
        sourceMap: true,
        plugins: [
            // require('postcss-focus'),
            autoprefixer({
                browsers: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 8', 'iOS >= 8', 'Android >= 4'],
            }),
        ],
    };

    const emptyBuildins = [
        'child_process',
        'cluster',
        'dgram',
        'dns',
        'fs',
        'module',
        'net',
        'readline',
        'repl',
        'tls',
    ];

    const browser = pkg.browser || {};

    const node = emptyBuildins.reduce((obj, name) => {
        if (!(name in browser)) {
            return { ...obj, ...{ [name]: 'empty' } };
        }
        return obj;
    }, {});

    const config = {
        babel: babelOptions,
        cache: true,
        postcss: postcssOptions,
        output: {
            path: join(process.cwd(), './dist/'),
            filename: jsFileName,
            chunkFilename: chunkFilename,
        },

        devtool: dev && 'source-map',

        // context: join(__dirname, '/../../../node_modules'),

        resolve: {
            modules: ['node_modules', join(__dirname, '/../../../node_modules')],
            // root: ['node_modules', join(__dirname, '/../../../node_modules')],
        },

        entry: pkg.entry,

        node,

        module: {
            // noParse: [/moment.js/],
            loaders: [
                {
                    test: /\.less$/,
                    loader: dev
                        ? 'style-loader!css-loader?sourceMap!postcss-loader?sourceMap!less-loader?sourceMap'
                        : ExtractTextPlugin.extract(['css-loader', 'postcss-loader', 'less-loader'])
                },
                {
                    test: /\.css$/,
                    loader: dev
                        ? 'style-loader!css-loader?sourceMap'
                        : ExtractTextPlugin.extract(['css-loader', 'postcss-loader'])
                },
                {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    exclude: [
                        function (name) {
                            return !/\/picidae-(plugin|transformer|theme|commander)/.test(name)
                                && !/(node_modules|bower_components)\/picidae/.test(name)
                                && /(node_modules|bower_components)/.test(name)
                        },
                        /\/node_modules\/core-js\//
                    ],
                    options: babelOptions,
                },
                {
                    test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/font-woff',
                    },
                },
                {
                    test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/font-woff',
                    },
                },
                {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/octet-stream',
                    },
                },
                {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'application/vnd.ms-fontobject',
                    },
                },
                {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        minetype: 'image/svg+xml',
                    },
                },
                {
                    test: /\.(png|jpg|jpeg|gif)(\?v=\d+\.\d+\.\d+)?$/i,
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                    },
                },
                {
                    test: /\.html?$/,
                    loader: 'file-loader',
                    options: {
                    },
                },
                {
                    test: /\.json$/,
                    loader: 'json-loader',
                    options: {
                        name: '[path][name].[ext]',
                    },
                },
            ],
        },

        plugins: [
            new webpack.ProgressPlugin(function(percentage, msg) {
                const stream = process.stdout;
                if (stream.isTTY && percentage < 0.71) {
                    stream.cursorTo(0);
                    stream.write('  ' + require('chalk').cyan(msg));
                    stream.clearLine(1);
                } else if (percentage === 1) {
                    console.log('');
                    console.log(require('chalk').cyan('webpack: bundle build is now finished.'));
                }
            }),
            /*args.hash && */new webpack.optimize.CommonsChunkPlugin('common', commonName),
            new ExtractTextPlugin('style.css', {
                // filename: cssFileName,
                disable: false,
                allChunks: true,
            }),
            dev && new webpack.HotModuleReplacementPlugin(),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': dev ? '"development"' : '"production"',
            }),
            new webpack.optimize.OccurrenceOrderPlugin(),
            !dev && new webpack.optimize.UglifyJsPlugin({
                output: {comments: false},
                compress: {
                    warnings: false
                }
            }),
            new CaseSensitivePathsPlugin(),
            dev && new FriendlyErrorsWebpackPlugin({
                onErrors: (severity, errors) => {
                    if (silent) return;
                    if (severity !== 'error') {
                        notifier.notify({
                            title: 'picidae',
                            message: 'warn',
                            // contentImage: join(__dirname, '../assets/warn.png'),
                            sound: 'Glass',
                        });
                        return;
                    }
                    const error = errors[0];
                    notifier.notify({
                        title: 'picidae',
                        message: `${severity} : ${error.name}`,
                        subtitle: error.file || '',
                        // contentImage: join(__dirname, '../assets/fail.png'),
                        sound: 'Glass',
                    });
                },
            }),
        ].filter(Boolean),
    };

    return config;
}
<|endoftext|>