<commit_before>(function () {

  /* On Linux, BLE normally needs admin right to be able to access BLE
  *
  * sudo apt-get install libcap2-bin
  * sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
  */

  if (typeof require === 'undefined') return;
  var noble = undefined;
  try {
    noble = require('noble');
  } catch (e) {
    console.log("'noble' module couldn't be loaded, no node.js Bluetooth Low Energy\n", e);
    // super nasty workaround for https://github.com/sandeepmistry/noble/issues/502
    process.removeAllListeners('exit');
    return;
  }

  var NORDIC_SERVICE = "6e400001b5a3f393e0a9e50e24dcca9e";
  var NORDIC_TX = "6e400002b5a3f393e0a9e50e24dcca9e";
  var NORDIC_RX = "6e400003b5a3f393e0a9e50e24dcca9e";

  var initialised = false;
  var errored = false;
  var scanWhenInitialised = undefined;
  var firstGetPortsCall = true;

  function str2buf(str) {
    var buf = new Buffer(str.length);
    for (var i = 0; i < buf.length; i++) {
      buf.writeUInt8(str.charCodeAt(i), i);
    }
    return buf;
  }

  function dataview2ab(dv) {
    var bufView = new Uint8Array(dv.byteLength);
    for (var i = 0; i < bufView.length; i++) {
      bufView[i] = dv.getUint8(i);
    }
    return bufView.buffer;
  }

  function findByUUID(list, uuid) {
    for (var i=0;i<list.length;i++)
      if (list[i].uuid==uuid) return list[i];
    return undefined;
  }

  // map of bluetooth devices found by getPorts
  var btDevices = {};
  var newDevices = [];
  var lastDevices = [];

  var btDevice;
  var txCharacteristic;
  var rxCharacteristic;
  var txDataQueue = undefined;
  var txInProgress = false;
  var scanStopTimeout = undefined;

  function init() {
    Espruino.Core.Config.add("BLUETOOTH_LOW_ENERGY", {
      section: "Communications",
      name: "Connect over Bluetooth Smart (BTLE) via 'noble'",
      descriptionHTML: 'Allow connection to Espruino via BLE with the Nordic UART implementation',
      type: "boolean",
      defaultValue: true
    });
  }

  noble.on('stateChange', function(state) {
    if (state=="poweredOn") {
      if (Espruino.Config.WEB_BLUETOOTH) {
        // Everything has already initialised, so we must disable
        // web bluetooth this way instead
        console.log("Disable Web Bluetooth as we have Noble instead");
        Espruino.Config.WEB_BLUETOOTH = false;
      }
      initialised = true;
      if (scanWhenInitialised) {
        getPorts(scanWhenInitialised);
        scanWhenInitialised = undefined;
      }
    }
    if (state=="poweredOff") initialised = false;
  });
  // if we didn't initialise for whatever reason, keep going anyway
  setTimeout(function() {
    errored = true;
    if (scanWhenInitialised) {
      scanWhenInitialised([]);
      scanWhenInitialised = undefined;
    }
  }, 1000);

  noble.on('discover', function(dev) {
    if (!dev.advertisement) return;
    for (var i in newDevices)
      if (newDevices[i].path == dev.address) return; // already seen it
    var name = dev.advertisement.localName;
    var hasUartService = dev.advertisement.serviceUuids.indexOf(NORDIC_SERVICE)>=0;
    if (hasUartService ||
        (name &&
          (name.substr(0, 7) == "Puck.js" ||
           name.substr(0, 7) == "Badge" ||
           name.substr(0, 8) == "Espruino"))) {
      console.log("Found UART device:", name, dev.address);
      newDevices.push({ path: dev.address, description: name, type : "bluetooth" });
      btDevices[dev.address] = dev;
    } else console.log("Found device:", name, dev.address);
  });

  var getPorts = function (callback) {
    if (errored || !Espruino.Config.BLUETOOTH_LOW_ENERGY) {
      callback([]);
    } else if (!initialised) {
      // if not initialised yet, wait until we are
      if (scanWhenInitialised) scanWhenInitialised([]);
      scanWhenInitialised = callback;
    } else { // all ok - let's go!
      if (scanStopTimeout) {
        clearTimeout(scanStopTimeout);
        scanStopTimeout = undefined;
      } else {
        console.log("noble starting scan");
        lastDevices = [];
        newDevices = [];
        noble.startScanning([], true);
      }
      /* we want the first call to return immediately, so if the
      user isn't after Bluetooth everything still works fast */
      if (firstGetPortsCall) {
        firstGetPortsCall = false;
        return callback([]);
      }

      setTimeout(function() {
        scanStopTimeout = setTimeout(function () {
          scanStopTimeout = undefined;
          console.log("noble stopping scan");
          noble.stopScanning();
        }, 3000);
        // report back device list from both the last scan and this one...
        var reportedDevices = [];
        newDevices.forEach(function (d) {
          reportedDevices.push(d);
        });
        lastDevices.forEach(function (d) {
          var found = false;
          reportedDevices.forEach(function (dv) {
            if (dv.path == d.path) found = true;
          });
          if (!found) reportedDevices.push(d);
        });
        reportedDevices.sort(function (a, b) { return a.path.localeCompare(b.path); });
        lastDevices = newDevices;
        newDevices = [];
        callback(reportedDevices);
      }, 1500);
    }
  };

  var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) {
    btDevice = btDevices[serialPort];
    if (btDevice === undefined) throw "BT device not found"

    if (scanStopTimeout) {
      clearTimeout(scanStopTimeout);
      scanStopTimeout = undefined;
      console.log("noble stopping scan");
      noble.stopScanning();
    }

    txDataQueue = undefined;
    txInProgress = false;

    console.log("BT> Connecting");
    btDevice.on('disconnect', function() {
      txCharacteristic = undefined;
      rxCharacteristic = undefined;
      btDevice = undefined;
      txDataQueue = undefined;
      txInProgress = false;
      disconnectCallback();
    });

    btDevice.connect(function (error) {
      if (error) {
        console.log("BT> ERROR Connecting");
        btDevice = undefined;
        return openCallback();
      }
      console.log("BT> Connected");

      btDevice.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
        var btUARTService = findByUUID(services, NORDIC_SERVICE);
        txCharacteristic = findByUUID(characteristics, NORDIC_TX);
        rxCharacteristic = findByUUID(characteristics, NORDIC_RX);
        if (error || !btUARTService || !txCharacteristic || !rxCharacteristic) {
          console.log("BT> ERROR getting services/characteristics");
          console.log("Service "+btUARTService);
          console.log("TX "+txCharacteristic);
          console.log("RX "+rxCharacteristic);
          btDevice.disconnect();
          txCharacteristic = undefined;
          rxCharacteristic = undefined;
          btDevice = undefined;
          return openCallback();
        }

        rxCharacteristic.on('data', function (data) {
          receiveCallback(new Uint8Array(data).buffer);
        });
        rxCharacteristic.subscribe(function() {
          openCallback({});
        });
      });
    });
  };

  var closeSerial = function () {
    if (btDevice) {
      btDevice.disconnect(); // should call disconnect callback?
    }
  };

  // Throttled serial write
  var writeSerial = function (data, callback) {
    if (txCharacteristic === undefined) return;
    if (typeof txDataQueue != "undefined" || txInProgress) {
      if (txDataQueue === undefined)
        txDataQueue = "";
      txDataQueue += data;
      return callback();
    } else {
      txDataQueue = data;
    }

    function writeChunk() {
      var chunk;
      var CHUNKSIZE = 20;
      if (txDataQueue.length <= CHUNKSIZE) {
        chunk = txDataQueue;
        txDataQueue = undefined;
      } else {
        chunk = txDataQueue.substr(0, CHUNKSIZE);
        txDataQueue = txDataQueue.substr(CHUNKSIZE);
      }
      txInProgress = true;
      console.log("BT> Sending " + JSON.stringify(chunk));
      try {
        txCharacteristic.write(str2buf(chunk), false, function() {
          txInProgress = false;
          if (txDataQueue)
            writeChunk();
        });
      } catch (e) {
        console.log("BT> ERROR " + e);
        txDataQueue = undefined;
      }
    }
    writeChunk();
    return callback();
  };

  // ----------------------------------------------------------

  Espruino.Core.Serial.devices.push({
    "name" : "Noble",
    "init": init,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial
  });
})();
<commit_msg>newb mistake<commit_after>(function () {

  /* On Linux, BLE normally needs admin right to be able to access BLE
  *
  * sudo apt-get install libcap2-bin
  * sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
  */

  if (typeof require === 'undefined') return;
  var noble = undefined;
  try {
    noble = require('noble');
  } catch (e) {
    console.log("'noble' module couldn't be loaded, no node.js Bluetooth Low Energy\n", e);
    // super nasty workaround for https://github.com/sandeepmistry/noble/issues/502
    process.removeAllListeners('exit');
    return;
  }

  var NORDIC_SERVICE = "6e400001b5a3f393e0a9e50e24dcca9e";
  var NORDIC_TX = "6e400002b5a3f393e0a9e50e24dcca9e";
  var NORDIC_RX = "6e400003b5a3f393e0a9e50e24dcca9e";

  var initialised = false;
  var errored = false;
  var scanWhenInitialised = undefined;
  var firstGetPortsCall = true;

  function str2buf(str) {
    var buf = new Buffer(str.length);
    for (var i = 0; i < buf.length; i++) {
      buf.writeUInt8(str.charCodeAt(i), i);
    }
    return buf;
  }

  function dataview2ab(dv) {
    var bufView = new Uint8Array(dv.byteLength);
    for (var i = 0; i < bufView.length; i++) {
      bufView[i] = dv.getUint8(i);
    }
    return bufView.buffer;
  }

  function findByUUID(list, uuid) {
    for (var i=0;i<list.length;i++)
      if (list[i].uuid==uuid) return list[i];
    return undefined;
  }

  // map of bluetooth devices found by getPorts
  var btDevices = {};
  var newDevices = [];
  var lastDevices = [];

  var btDevice;
  var txCharacteristic;
  var rxCharacteristic;
  var txDataQueue = undefined;
  var txInProgress = false;
  var scanStopTimeout = undefined;

  function init() {
    Espruino.Core.Config.add("BLUETOOTH_LOW_ENERGY", {
      section: "Communications",
      name: "Connect over Bluetooth Smart (BTLE) via 'noble'",
      descriptionHTML: 'Allow connection to Espruino via BLE with the Nordic UART implementation',
      type: "boolean",
      defaultValue: true
    });
  }

  noble.on('stateChange', function(state) {
    if (state=="poweredOn") {
      if (Espruino.Config.WEB_BLUETOOTH) {
        // Everything has already initialised, so we must disable
        // web bluetooth this way instead
        console.log("Disable Web Bluetooth as we have Noble instead");
        Espruino.Config.WEB_BLUETOOTH = false;
      }
      initialised = true;
      if (scanWhenInitialised) {
        getPorts(scanWhenInitialised);
        scanWhenInitialised = undefined;
      }
    }
    if (state=="poweredOff") initialised = false;
  });
  // if we didn't initialise for whatever reason, keep going anyway
  setTimeout(function() {
    errored = true;
    if (scanWhenInitialised) {
      scanWhenInitialised([]);
      scanWhenInitialised = undefined;
    }
  }, 1000);

  noble.on('discover', function(dev) {
    if (!dev.advertisement) return;
    for (var i in newDevices)
      if (newDevices[i].path == dev.address) return; // already seen it
    var name = dev.advertisement.localName;
    var hasUartService = dev.advertisement.serviceUuids.indexOf(NORDIC_SERVICE)>=0;
    if (hasUartService ||
        (name &&
          (name.substr(0, 7) == "Puck.js" ||
           name.substr(0, 5) == "Badge" ||
           name.substr(0, 8) == "Espruino"))) {
      console.log("Found UART device:", name, dev.address);
      newDevices.push({ path: dev.address, description: name, type : "bluetooth" });
      btDevices[dev.address] = dev;
    } else console.log("Found device:", name, dev.address);
  });

  var getPorts = function (callback) {
    if (errored || !Espruino.Config.BLUETOOTH_LOW_ENERGY) {
      callback([]);
    } else if (!initialised) {
      // if not initialised yet, wait until we are
      if (scanWhenInitialised) scanWhenInitialised([]);
      scanWhenInitialised = callback;
    } else { // all ok - let's go!
      if (scanStopTimeout) {
        clearTimeout(scanStopTimeout);
        scanStopTimeout = undefined;
      } else {
        console.log("noble starting scan");
        lastDevices = [];
        newDevices = [];
        noble.startScanning([], true);
      }
      /* we want the first call to return immediately, so if the
      user isn't after Bluetooth everything still works fast */
      if (firstGetPortsCall) {
        firstGetPortsCall = false;
        return callback([]);
      }

      setTimeout(function() {
        scanStopTimeout = setTimeout(function () {
          scanStopTimeout = undefined;
          console.log("noble stopping scan");
          noble.stopScanning();
        }, 3000);
        // report back device list from both the last scan and this one...
        var reportedDevices = [];
        newDevices.forEach(function (d) {
          reportedDevices.push(d);
        });
        lastDevices.forEach(function (d) {
          var found = false;
          reportedDevices.forEach(function (dv) {
            if (dv.path == d.path) found = true;
          });
          if (!found) reportedDevices.push(d);
        });
        reportedDevices.sort(function (a, b) { return a.path.localeCompare(b.path); });
        lastDevices = newDevices;
        newDevices = [];
        callback(reportedDevices);
      }, 1500);
    }
  };

  var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) {
    btDevice = btDevices[serialPort];
    if (btDevice === undefined) throw "BT device not found"

    if (scanStopTimeout) {
      clearTimeout(scanStopTimeout);
      scanStopTimeout = undefined;
      console.log("noble stopping scan");
      noble.stopScanning();
    }

    txDataQueue = undefined;
    txInProgress = false;

    console.log("BT> Connecting");
    btDevice.on('disconnect', function() {
      txCharacteristic = undefined;
      rxCharacteristic = undefined;
      btDevice = undefined;
      txDataQueue = undefined;
      txInProgress = false;
      disconnectCallback();
    });

    btDevice.connect(function (error) {
      if (error) {
        console.log("BT> ERROR Connecting");
        btDevice = undefined;
        return openCallback();
      }
      console.log("BT> Connected");

      btDevice.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
        var btUARTService = findByUUID(services, NORDIC_SERVICE);
        txCharacteristic = findByUUID(characteristics, NORDIC_TX);
        rxCharacteristic = findByUUID(characteristics, NORDIC_RX);
        if (error || !btUARTService || !txCharacteristic || !rxCharacteristic) {
          console.log("BT> ERROR getting services/characteristics");
          console.log("Service "+btUARTService);
          console.log("TX "+txCharacteristic);
          console.log("RX "+rxCharacteristic);
          btDevice.disconnect();
          txCharacteristic = undefined;
          rxCharacteristic = undefined;
          btDevice = undefined;
          return openCallback();
        }

        rxCharacteristic.on('data', function (data) {
          receiveCallback(new Uint8Array(data).buffer);
        });
        rxCharacteristic.subscribe(function() {
          openCallback({});
        });
      });
    });
  };

  var closeSerial = function () {
    if (btDevice) {
      btDevice.disconnect(); // should call disconnect callback?
    }
  };

  // Throttled serial write
  var writeSerial = function (data, callback) {
    if (txCharacteristic === undefined) return;
    if (typeof txDataQueue != "undefined" || txInProgress) {
      if (txDataQueue === undefined)
        txDataQueue = "";
      txDataQueue += data;
      return callback();
    } else {
      txDataQueue = data;
    }

    function writeChunk() {
      var chunk;
      var CHUNKSIZE = 20;
      if (txDataQueue.length <= CHUNKSIZE) {
        chunk = txDataQueue;
        txDataQueue = undefined;
      } else {
        chunk = txDataQueue.substr(0, CHUNKSIZE);
        txDataQueue = txDataQueue.substr(CHUNKSIZE);
      }
      txInProgress = true;
      console.log("BT> Sending " + JSON.stringify(chunk));
      try {
        txCharacteristic.write(str2buf(chunk), false, function() {
          txInProgress = false;
          if (txDataQueue)
            writeChunk();
        });
      } catch (e) {
        console.log("BT> ERROR " + e);
        txDataQueue = undefined;
      }
    }
    writeChunk();
    return callback();
  };

  // ----------------------------------------------------------

  Espruino.Core.Serial.devices.push({
    "name" : "Noble",
    "init": init,
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial
  });
})();
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var loaderUtils = require("loader-utils");
var processCss = require("./processCss");
var getImportPrefix = require("./getImportPrefix");
var compileExports = require("./compile-exports");

module.exports = function(content) {
	if(this.cacheable) this.cacheable();
	var callback = this.async();
	var query = loaderUtils.getOptions(this) || {};
	var moduleMode = query.modules || query.module;
	var camelCaseKeys = query.camelCase || query.camelcase;

	processCss(content, null, {
		mode: moduleMode ? "local" : "global",
		query: query,
		minimize: this.minimize,
		loaderContext: this
	}, function(err, result) {
		if(err) return callback(err);

		// for importing CSS
		var importUrlPrefix = getImportPrefix(this, query);

		function importItemMatcher(item) {
			var match = result.importItemRegExp.exec(item);
			var idx = +match[1];
			var importItem = result.importItems[idx];
			var importUrl = importUrlPrefix + importItem.url;
			return "\" + require(" + loaderUtils.stringifyRequest(this, importUrl) + ")" +
				"[" + JSON.stringify(importItem.export) + "] + \"";
		}

		var exportJs = compileExports(result, importItemMatcher.bind(this), camelCaseKeys);
		if (exportJs) {
			exportJs = "module.exports = " + exportJs + ";";
		}

		callback(null, exportJs);
	}.bind(this));
};
<commit_msg>fix: pass resolver to `localsLoader` (`options.alias`)  (#601)<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var loaderUtils = require("loader-utils");
var processCss = require("./processCss");
var getImportPrefix = require("./getImportPrefix");
var compileExports = require("./compile-exports");
var createResolver = require("./createResolver");

module.exports = function(content) {
	if(this.cacheable) this.cacheable();
	var callback = this.async();
	var query = loaderUtils.getOptions(this) || {};
	var moduleMode = query.modules || query.module;
	var camelCaseKeys = query.camelCase || query.camelcase;
	var resolve = createResolver(query.alias);

	processCss(content, null, {
		mode: moduleMode ? "local" : "global",
		query: query,
		minimize: this.minimize,
		loaderContext: this,
		resolve: resolve
	}, function(err, result) {
		if(err) return callback(err);

		// for importing CSS
		var importUrlPrefix = getImportPrefix(this, query);

		function importItemMatcher(item) {
			var match = result.importItemRegExp.exec(item);
			var idx = +match[1];
			var importItem = result.importItems[idx];
			var importUrl = importUrlPrefix + importItem.url;
			return "\" + require(" + loaderUtils.stringifyRequest(this, importUrl) + ")" +
				"[" + JSON.stringify(importItem.export) + "] + \"";
		}

		var exportJs = compileExports(result, importItemMatcher.bind(this), camelCaseKeys);
		if (exportJs) {
			exportJs = "module.exports = " + exportJs + ";";
		}

		callback(null, exportJs);
	}.bind(this));
};
<|endoftext|>


<commit_before>/**
 * ekathuwa
 * @version v0.2.8 - 2015-03-06
 * @link https://github.com/sarath2/ngEkathuwa
 * @author Sarath Ambegoda <sarath2mail@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
(function (window, document, undefined) {
    'use strict';
    angular.module('ngEkathuwa', []);
    (function (window, document, undefined) {
        angular.module('ngEkathuwa', []);
        angular.module('ngEkathuwa', []).run([
      '$rootScope',
      '$ekathuwa',
      function ($rootScope, $ekathuwa) {
                    $rootScope.$ekathuwa = $ekathuwa;
      }
    ]).provider('$ekathuwa', function () {
                this.$get = [
        '$compile',
        '$rootScope',
        '$timeout',
        '$q',
        function ($compile, $rootScope, $timeout, $q) {
                        this.modal = function (op) {
                            var d = {
                                id: 'ekathuwaModalID',
                                scope: $rootScope.$new(),
                                controller: null,
                                backdrop: true,
                                keyboard: true,
                                remote: false,
                                show: true,
                                modalClass: 'fade',
                                role: 'dialog',
                                contentStyle: null,
                                contentCustomSize: 0,
                                contentPreSize: 'df',
                                templateURL: null,
                                templateHTML: null,
                                bodyTemplateURL: null,
                                bodyTemplate: null,
                                header: true,
                                headerText: null,
                                headerClass: '',
                                headerTemplate: null,
                                headerCloseBtn: true,
                                headerDraggable: true,
                                footer: true,
                                footerClass: '',
                                footerTemplate: null,
                                footerCloseBtn: true,
                                footerCloseBtnText: 'Close',
                                footerSaveBtn: false,
                                footerSaveBtnText: 'Save changes'
                            };
                            var t = '',
                                s = '',
                                c = '',
                                b = '',
                                f = '',
                                h = '';
                            op = angular.extend(d, op);
                            var btOPs = {
                                backdrop: op.backdrop,
                                keyboard: op.keyboard,
                                remote: op.remote,
                                show: op.show
                            };
                            var modSelector = '#' + op.id + ' .modal';
                            c = op.controller ? 'data-ng-controller=' + op.controller : '';
                            if (op.templateURL !== null && op.templateURL !== '') {
                                t = '

';
                            } else {
                                var a = '
';
                                if (op.templateHTML !== null && op.templateHTML !== '') {
                                    t = a + op.templateHTML + '
';
                                } else {
                                    if (op.bodyTemplateURL !== null && op.bodyTemplateURL !== '') {
                                        b = '

';
                                    } else {
                                        if (op.bodyTemplate !== null && op.bodyTemplate !== '') {
                                            b = '
' + op.bodyTemplate + '
';
                                        } else {
                                            b = '
Ekathuwa modal body.
';
                                        }
                                    }
                                    if (op.header) {
                                        if (op.headerTemplate !== null && op.headerTemplate !== '') {
                                            h = '
' + op.headerTemplate + '
';
                                        } else {
                                            var ht = '';
                                            if (op.headerText !== null && op.headerText !== '') {
                                                ht = '
' + op.headerText + '
';
                                            }
                                            h = '
<button data-ng-if="' + op.headerCloseBtn + '" aria-hidden="true" data-dismiss="modal" class="close" type="button">\xd7</button>' + ht + '
';
                                        }
                                    }
                                    if (op.footer) {
                                        if (op.footerTemplate !== null && op.footerTemplate !== '') {
                                            f = '
' + op.footerTemplate + '
';
                                        } else {
                                            f = '
<button data-ng-if="' + op.footerCloseBtn + '" data-dismiss="modal" class="btn btn-default" type="button">' + op.footerCloseBtnText + '</button><button data-ng-if="' + op.footerSaveBtn + '" class="btn btn-primary" type="button">' + op.footerSaveBtnText + '</button>
';
                                        }
                                    }
                                    t = a + '

' + h + b + f + '

';
                                }
                            }
                            if (op.contentStyle !== null && op.contentStyle !== '') {
                                s = op.contentStyle;
                            }
                            if (op.contentCustomSize !== 0 && angular.isNumber(op.contentCustomSize) && op.contentCustomSize !== '' && op.contentCustomSize !== null) {
                                s = s + ';width: ' + op.contentCustomSize + '%;';
                            }
                            switch (op.contentPreSize) {
                            case 'sm':
                                s = s + ';width:25%;';
                                break;
                            case 'md':
                                s = s + ';width:50%;';
                                break;
                            case 'lg':
                                s = s + ';width:75%;';
                                break;
                            case 'fl':
                                s = s + ';width:98%;';
                                break;
                            default:
                                break;
                            }
                            var mq = '#' + op.id + ' .modal-dialog { ' + s + '} @media (max-width: 768px) {' + '#' + op.id + ' .modal-dialog {width:90%;}}';
                            angular.element('#ekathuwaSt' + op.id).remove();
                            angular.element('head').append('');
                            angular.element('#' + op.id).remove();
                            var m = angular.element(t);
                            angular.element('body').append(m);
                            var deferred = $q.defer();
                            op.scope.ekathuaLoaded = function () {
                                deferred.resolve(angular.element(modSelector).modal(btOPs));
                            };
                            $compile(m)(op.scope);
                            if (op.templateURL !== null && op.templateURL !== '') {} else {
                                deferred.resolve(angular.element(modSelector).modal(btOPs));
                            }
                            return deferred.promise;
                        };
                        return this;
        }
      ];
            })
            .directive('draggable', function ($document) {
                return function (scope, element) {
                    var backDropHeight = 0;
                    angular.element(".modal-dialog").draggable({
                        handle: ".modal-header",
                        stop: function (event, ui) {
                            var backDropElements = document.getElementsByClassName('modal-backdrop');
                            for (var x = 0; x < backDropElements.length; x++) {
                                backDropHeight = backDropHeight == 0 ? backDropElements[x].clientHeight : backDropHeight;
                                backDropElements[x].style.height = (backDropHeight + ui.offset.top + 2) + "px";
                            }
                        }
                    });
                };
            });
    }(window, document));
}(window, document));
<commit_msg>Fixed header draggable<commit_after>/**
 * ekathuwa
 * @version v0.3.0 - 2015-03-26
 * @link https://github.com/sarath2/ngEkathuwa
 * @author Sarath Ambegoda <sarath2mail@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
(function (window, document, undefined) {
    'use strict';
    angular.module('ngEkathuwa', []);
    (function (window, document, undefined) {
        angular.module('ngEkathuwa', []);
        angular.module('ngEkathuwa', []).run([
      '$rootScope',
      '$ekathuwa',
      function ($rootScope, $ekathuwa) {
                    $rootScope.$ekathuwa = $ekathuwa;
      }
    ]).provider('$ekathuwa', function () {
                this.$get = [
        '$compile',
        '$rootScope',
        '$timeout',
        '$q',
        function ($compile, $rootScope, $timeout, $q) {
                        this.modal = function (op) {
                            var d = {
                                id: 'ekathuwaModalID',
                                scope: $rootScope.$new(),
                                controller: null,
                                backdrop: true,
                                keyboard: true,
                                remote: false,
                                show: true,
                                modalClass: 'fade',
                                role: 'dialog',
                                contentStyle: null,
                                contentCustomSize: 0,
                                contentPreSize: 'df',
                                templateURL: null,
                                templateHTML: null,
                                bodyTemplateURL: null,
                                bodyTemplate: null,
                                header: true,
                                headerText: null,
                                headerClass: '',
                                headerTemplate: null,
                                headerCloseBtn: true,
                                headerDraggable: true,
                                footer: true,
                                footerClass: '',
                                footerTemplate: null,
                                footerCloseBtn: true,
                                footerCloseBtnText: 'Close',
                                footerSaveBtn: false,
                                footerSaveBtnText: 'Save changes'
                            };
                            var t = '',
                                s = '',
                                c = '',
                                b = '',
                                f = '',
                                h = '';
                            op = angular.extend(d, op);
                            var btOPs = {
                                backdrop: op.backdrop,
                                keyboard: op.keyboard,
                                remote: op.remote,
                                show: op.show
                            };
                            var modSelector = '#' + op.id + ' .modal';
                            c = op.controller ? 'data-ng-controller=' + op.controller : '';
                            if (op.templateURL !== null && op.templateURL !== '') {
                                t = '

';
                            } else {
                                var a = '
';
                                if (op.templateHTML !== null && op.templateHTML !== '') {
                                    t = a + op.templateHTML + '
';
                                } else {
                                    if (op.bodyTemplateURL !== null && op.bodyTemplateURL !== '') {
                                        b = '

';
                                    } else {
                                        if (op.bodyTemplate !== null && op.bodyTemplate !== '') {
                                            b = '
' + op.bodyTemplate + '
';
                                        } else {
                                            b = '
Ekathuwa modal body.
';
                                        }
                                    }
                                    if (op.header) {
                                        if (op.headerTemplate !== null && op.headerTemplate !== '') {
                                            h = '
' + op.headerTemplate + '
';
                                        } else {
                                            var ht = '';
                                            if (op.headerText !== null && op.headerText !== '') {
                                                ht = '
' + op.headerText + '
';
                                            }
                                            h = '
<button data-ng-if="' + op.headerCloseBtn + '" aria-hidden="true" data-dismiss="modal" class="close" type="button">\xd7</button>' + ht + '
';
                                        }
                                    }
                                    if (op.footer) {
                                        if (op.footerTemplate !== null && op.footerTemplate !== '') {
                                            f = '
' + op.footerTemplate + '
';
                                        } else {
                                            f = '
<button data-ng-if="' + op.footerCloseBtn + '" data-dismiss="modal" class="btn btn-default" type="button">' + op.footerCloseBtnText + '</button><button data-ng-if="' + op.footerSaveBtn + '" class="btn btn-primary" type="button">' + op.footerSaveBtnText + '</button>
';
                                        }
                                    }
                                    t = a + '

' + h + b + f + '

';
                                }
                            }
                            if (op.contentStyle !== null && op.contentStyle !== '') {
                                s = op.contentStyle;
                            }
                            if (op.contentCustomSize !== 0 && angular.isNumber(op.contentCustomSize) && op.contentCustomSize !== '' && op.contentCustomSize !== null) {
                                s = s + ';width: ' + op.contentCustomSize + '%;';
                            }
                            switch (op.contentPreSize) {
                            case 'sm':
                                s = s + ';width:25%;';
                                break;
                            case 'md':
                                s = s + ';width:50%;';
                                break;
                            case 'lg':
                                s = s + ';width:75%;';
                                break;
                            case 'fl':
                                s = s + ';width:98%;';
                                break;
                            default:
                                break;
                            }
                            var mq = '#' + op.id + ' .modal-dialog { ' + s + '} @media (max-width: 768px) {' + '#' + op.id + ' .modal-dialog {width:90%;}}';
                            angular.element('#ekathuwaSt' + op.id).remove();
                            angular.element('head').append('');
                            angular.element('#' + op.id).remove();
                            var m = angular.element(t);
                            angular.element('body').append(m);
                            var deferred = $q.defer();
                            op.scope.ekathuaLoaded = function () {
                                deferred.resolve(angular.element(modSelector).modal(btOPs));
                            };
                            $compile(m)(op.scope);
                            if (op.templateURL !== null && op.templateURL !== '') {} else {
                                deferred.resolve(angular.element(modSelector).modal(btOPs));
                            }
                            return deferred.promise;
                        };
                        return this;
        }
      ];
            })
            .directive('draggable', function ($document) {
                return function (scope, element) {
                    var backDropHeight = 0;
                    angular.element(".modal-dialog").draggable({
                        handle: ".modal-header",
                        stop: function (event, ui) {
                            var backDropElements = document.getElementsByClassName('modal-backdrop');
                            for (var x = 0; x < backDropElements.length; x++) {
                                backDropHeight = backDropHeight == 0 ? backDropElements[x].clientHeight : backDropHeight;
                                backDropElements[x].style.height = (backDropHeight + ui.offset.top + 2) + "px";
                            }
                        }
                    });
                };
            });
    }(window, document));
}(window, document));
<|endoftext|>


<commit_before>(function() {
  var ERROR_ID, EventEmitter, create_callsite, current_trace_error, filename, format_location, format_method, in_prepare, limit_frames, prepareStackTrace, source_map, wrap_callback, __nextDomainTick, _addListener, _listeners, _nextTick, _on, _ref, _setImmediate, _setInterval, _setTimeout;

  EventEmitter = require('events').EventEmitter;

  if ((_ref = EventEmitter.prototype.on) != null ? _ref['longjohn'] : void 0) {
    return module.exports = EventEmitter.prototype.on['longjohn'];
  }

  source_map = require('source-map-support');

  source_map.install();

  filename = __filename;

  current_trace_error = null;

  in_prepare = 0;

  exports.empty_frame = '---------------------------------------------';

  exports.async_trace_limit = 10;

  format_location = function(frame) {
    var column, file, line;
    if (frame.isNative()) {
      return 'native';
    }
    if (frame.isEval()) {
      return 'eval at ' + frame.getEvalOrigin();
    }
    file = frame.getFileName();
    file = frame.getFileName() || '<anonymous>';
    line = frame.getLineNumber();
    column = frame.getColumnNumber();
    column = column != null ? ':' + column : '';
    line = line != null ? ':' + line : '';
    return file + line + column;
  };

  format_method = function(frame) {
    var function_name, method, type;
    function_name = frame.getFunctionName();
    if (!(frame.isToplevel() || frame.isConstructor())) {
      method = frame.getMethodName();
      type = frame.getTypeName();
      if (function_name == null) {
        return "" + type + "." + (method != null ? method : '<anonymous>');
      }
      if (method === function_name) {
        return "" + type + "." + function_name;
      }
      "" + type + "." + function_name + " [as " + method + "]";
    }
    if (frame.isConstructor()) {
      return "new " + (function_name != null ? function_name : '<anonymous>');
    }
    if (function_name != null) {
      return function_name;
    }
    return null;
  };

  exports.format_stack_frame = function(frame) {
    if (frame.getFileName() === exports.empty_frame) {
      return exports.empty_frame;
    }
    return '    at ' + source_map.wrapCallSite(frame);
  };

  exports.format_stack = function(err, frames) {
    var e, lines;
    lines = [];
    try {
      lines.push(err.toString());
    } catch (_error) {
      e = _error;
      console.log('Caught error in longjohn. Please report this to matt.insler@gmail.com.');
    }
    lines.push.apply(lines, frames.map(exports.format_stack_frame));
    return lines.join('\n');
  };

  create_callsite = function(location) {
    return Object.create({
      getFileName: function() {
        return location;
      },
      getLineNumber: function() {
        return null;
      },
      getFunctionName: function() {
        return null;
      },
      getTypeName: function() {
        return null;
      },
      getMethodName: function() {
        return null;
      },
      getColumnNumber: function() {
        return null;
      },
      isNative: function() {
        return null;
      }
    });
  };

  prepareStackTrace = function(error, structured_stack_trace) {
    var previous_stack, _ref1;
    ++in_prepare;
    if (error.__cached_trace__ == null) {
      Object.defineProperty(error, '__cached_trace__', {
        writable: true,
        enumerable: false,
        configurable: true,
        value: structured_stack_trace.filter(function(f) {
          return f.getFileName() !== filename;
        })
      });
      if ((error.__previous__ == null) && in_prepare === 1) {
        Object.defineProperty(error, '__previous__', {
          writable: true,
          enumerable: false,
          configurable: true,
          value: current_trace_error
        });
      }
      if (error.__previous__ != null) {
        previous_stack = prepareStackTrace(error.__previous__, error.__previous__.__stack__);
        if ((previous_stack != null ? previous_stack.length : void 0) > 0) {
          error.__cached_trace__.push(create_callsite(exports.empty_frame));
          (_ref1 = error.__cached_trace__).push.apply(_ref1, previous_stack);
        }
      }
    }
    --in_prepare;
    if (in_prepare > 0) {
      return error.__cached_trace__;
    }
    return exports.format_stack(error, error.__cached_trace__);
  };

  limit_frames = function(stack) {
    var count, previous;
    if (exports.async_trace_limit <= 0) {
      return;
    }
    count = exports.async_trace_limit - 1;
    previous = stack;
    while ((previous != null) && count > 1) {
      previous = previous.__previous__;
      --count;
    }
    if (previous != null) {
      return delete previous.__previous__;
    }
  };

  ERROR_ID = 1;

  wrap_callback = function(callback, location) {
    var new_callback, orig, trace_error;
    orig = Error.prepareStackTrace;
    Error.prepareStackTrace = function(x, stack) {
      return stack;
    };
    trace_error = new Error();
    Error.captureStackTrace(trace_error, arguments.callee);
    trace_error.__stack__ = trace_error.stack;
    Error.prepareStackTrace = orig;
    trace_error.id = ERROR_ID++;
    if (trace_error.stack[1]) {
      trace_error.location = "" + (trace_error.stack[1].getFunctionName()) + " (" + (trace_error.stack[1].getFileName()) + ":" + (trace_error.stack[1].getLineNumber()) + ")";
    } else {
      trace_error.location = 'bad call_stack_location';
    }
    trace_error.__location__ = location;
    trace_error.__previous__ = current_trace_error;
    trace_error.__trace_count__ = current_trace_error != null ? current_trace_error.__trace_count__ + 1 : 1;
    limit_frames(trace_error);
    new_callback = function() {
      var e;
      current_trace_error = trace_error;
      trace_error = null;
      try {
        return callback.apply(this, arguments);
      } catch (_error) {
        e = _error;
        e.stack;
        throw e;
      } finally {
        current_trace_error = null;
      }
    };
    new_callback.listener = callback;
    return new_callback;
  };

  _on = EventEmitter.prototype.on;

  _addListener = EventEmitter.prototype.addListener;

  _listeners = EventEmitter.prototype.listeners;

  EventEmitter.prototype.addListener = function(event, callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[1] = wrap_callback(callback, 'EventEmitter.addListener');
    return _addListener.apply(this, args);
  };

  EventEmitter.prototype.on = function(event, callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[1] = wrap_callback(callback, 'EventEmitter.on');
    return _on.apply(this, args);
  };

  EventEmitter.prototype.once = function(event, callback) {
    var args, fired, g, wrap;
    args = Array.prototype.slice.call(arguments);
    if (typeof callback !== 'function') {
      throw TypeError('callback must be a function');
    }
    fired = false;
    wrap = wrap_callback(callback, 'EventEmitter.once');
    g = function() {
      this.removeListener(event, g);
      if (!fired) {
        fired = true;
        return wrap.apply(this, arguments);
      }
    };
    g.listener = callback;
    args[1] = g;
    _on.apply(this, args);
    return this;
  };

  EventEmitter.prototype.listeners = function(event) {
    var l, listeners, unwrapped, _i, _len;
    listeners = _listeners.call(this, event);
    unwrapped = [];
    for (_i = 0, _len = listeners.length; _i < _len; _i++) {
      l = listeners[_i];
      if (l.listener) {
        unwrapped.push(l.listener);
      } else {
        unwrapped.push(l);
      }
    }
    return unwrapped;
  };

  Object.defineProperty(EventEmitter.prototype.on, 'longjohn', {
    writable: true,
    enumerable: false,
    configurable: true,
    value: this
  });

  _nextTick = process.nextTick;

  process.nextTick = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'process.nextTick');
    return _nextTick.apply(this, args);
  };

  __nextDomainTick = process._nextDomainTick;

  process._nextDomainTick = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'process.nextDomainTick');
    return __nextDomainTick.apply(this, args);
  };

  _setTimeout = global.setTimeout;

  _setInterval = global.setInterval;

  global.setTimeout = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'global.setTimeout');
    return _setTimeout.apply(this, args);
  };

  global.setInterval = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'global.setInterval');
    return _setInterval.apply(this, args);
  };

  if (global.setImmediate != null) {
    _setImmediate = global.setImmediate;
    global.setImmediate = function(callback) {
      var args;
      args = Array.prototype.slice.call(arguments);
      args[0] = wrap_callback(callback, 'global.setImmediate');
      return _setImmediate.apply(this, args);
    };
  }

  Error.prepareStackTrace = prepareStackTrace;

  if (process.env.NODE_ENV === 'production') {
    console.warn('NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime.\nIt generally should not be used in production applications.');
  }

}).call(this);
<commit_msg>update dist<commit_after>(function() {
  var ERROR_ID, EventEmitter, create_callsite, current_trace_error, filename, format_location, format_method, in_prepare, limit_frames, prepareStackTrace, source_map, wrap_callback, __nextDomainTick, _addListener, _listeners, _nextTick, _on, _ref, _setImmediate, _setInterval, _setTimeout;

  EventEmitter = require('events').EventEmitter;

  if ((_ref = EventEmitter.prototype.on) != null ? _ref['longjohn'] : void 0) {
    return module.exports = EventEmitter.prototype.on['longjohn'];
  }

  source_map = require('source-map-support');

  source_map.install();

  filename = __filename;

  current_trace_error = null;

  in_prepare = 0;

  exports.empty_frame = '---------------------------------------------';

  exports.async_trace_limit = 10;

  format_location = function(frame) {
    var column, file, line;
    if (frame.isNative()) {
      return 'native';
    }
    if (frame.isEval()) {
      return 'eval at ' + frame.getEvalOrigin();
    }
    file = frame.getFileName();
    file = frame.getFileName() || '<anonymous>';
    line = frame.getLineNumber();
    column = frame.getColumnNumber();
    column = column != null ? ':' + column : '';
    line = line != null ? ':' + line : '';
    return file + line + column;
  };

  format_method = function(frame) {
    var function_name, method, type;
    function_name = frame.getFunctionName();
    if (!(frame.isToplevel() || frame.isConstructor())) {
      method = frame.getMethodName();
      type = frame.getTypeName();
      if (function_name == null) {
        return "" + type + "." + (method != null ? method : '<anonymous>');
      }
      if (method === function_name) {
        return "" + type + "." + function_name;
      }
      "" + type + "." + function_name + " [as " + method + "]";
    }
    if (frame.isConstructor()) {
      return "new " + (function_name != null ? function_name : '<anonymous>');
    }
    if (function_name != null) {
      return function_name;
    }
    return null;
  };

  exports.format_stack_frame = function(frame) {
    if (frame.getFileName() === exports.empty_frame) {
      return exports.empty_frame;
    }
    return '    at ' + source_map.wrapCallSite(frame);
  };

  exports.format_stack = function(err, frames) {
    var e, lines;
    lines = [];
    try {
      lines.push(err.toString());
    } catch (_error) {
      e = _error;
      console.log('Caught error in longjohn. Please report this to matt.insler@gmail.com.');
    }
    lines.push.apply(lines, frames.map(exports.format_stack_frame));
    return lines.join('\n');
  };

  create_callsite = function(location) {
    return Object.create({
      getFileName: function() {
        return location;
      },
      getLineNumber: function() {
        return null;
      },
      getFunctionName: function() {
        return null;
      },
      getTypeName: function() {
        return null;
      },
      getMethodName: function() {
        return null;
      },
      getColumnNumber: function() {
        return null;
      },
      isNative: function() {
        return null;
      }
    });
  };

  prepareStackTrace = function(error, structured_stack_trace) {
    var previous_stack, _ref1;
    ++in_prepare;
    if (error.__cached_trace__ == null) {
      Object.defineProperty(error, '__cached_trace__', {
        writable: true,
        enumerable: false,
        configurable: true,
        value: structured_stack_trace.filter(function(f) {
          return f.getFileName() !== filename;
        })
      });
      if ((error.__previous__ == null) && in_prepare === 1) {
        Object.defineProperty(error, '__previous__', {
          writable: true,
          enumerable: false,
          configurable: true,
          value: current_trace_error
        });
      }
      if (error.__previous__ != null) {
        previous_stack = prepareStackTrace(error.__previous__, error.__previous__.__stack__);
        if ((previous_stack != null ? previous_stack.length : void 0) > 0) {
          error.__cached_trace__.push(create_callsite(exports.empty_frame));
          (_ref1 = error.__cached_trace__).push.apply(_ref1, previous_stack);
        }
      }
    }
    --in_prepare;
    if (in_prepare > 0) {
      return error.__cached_trace__;
    }
    return exports.format_stack(error, error.__cached_trace__);
  };

  limit_frames = function(stack) {
    var count, previous;
    if (exports.async_trace_limit <= 0) {
      return;
    }
    count = exports.async_trace_limit - 1;
    previous = stack;
    while ((previous != null) && count > 1) {
      previous = previous.__previous__;
      --count;
    }
    if (previous != null) {
      return delete previous.__previous__;
    }
  };

  ERROR_ID = 1;

  wrap_callback = function(callback, location) {
    var new_callback, orig, trace_error;
    orig = Error.prepareStackTrace;
    Error.prepareStackTrace = function(x, stack) {
      return stack;
    };
    trace_error = new Error();
    Error.captureStackTrace(trace_error, arguments.callee);
    trace_error.__stack__ = trace_error.stack;
    Error.prepareStackTrace = orig;
    trace_error.id = ERROR_ID++;
    if (trace_error.stack[1]) {
      trace_error.location = "" + (trace_error.stack[1].getFunctionName()) + " (" + (trace_error.stack[1].getFileName()) + ":" + (trace_error.stack[1].getLineNumber()) + ")";
    } else {
      trace_error.location = 'bad call_stack_location';
    }
    trace_error.__location__ = location;
    trace_error.__previous__ = current_trace_error;
    trace_error.__trace_count__ = current_trace_error != null ? current_trace_error.__trace_count__ + 1 : 1;
    limit_frames(trace_error);
    new_callback = function() {
      var e;
      current_trace_error = trace_error;
      trace_error = null;
      try {
        return callback.apply(this, arguments);
      } catch (_error) {
        e = _error;
        e.stack;
        throw e;
      } finally {
        current_trace_error = null;
      }
    };
    new_callback.listener = callback;
    return new_callback;
  };

  _on = EventEmitter.prototype.on;

  _addListener = EventEmitter.prototype.addListener;

  _listeners = EventEmitter.prototype.listeners;

  EventEmitter.prototype.addListener = function(event, callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[1] = wrap_callback(callback, 'EventEmitter.addListener');
    return _addListener.apply(this, args);
  };

  EventEmitter.prototype.on = function(event, callback) {
    var args, g, wrap;
    args = Array.prototype.slice.call(arguments);
    if (callback.listener) {
      wrap = wrap_callback(callback.listener, 'EventEmitter.once');
      g = function() {
        var fired;
        this.removeListener(event, g);
        if (!fired) {
          fired = true;
          return wrap.apply(this, arguments);
        }
      };
      g.listener = callback.listener;
    } else {
      g = wrap_callback(callback, 'EventEmitter.on');
    }
    args[1] = g;
    return _on.apply(this, args);
  };

  EventEmitter.prototype.listeners = function(event) {
    var l, listeners, unwrapped, _i, _len;
    listeners = _listeners.call(this, event);
    unwrapped = [];
    for (_i = 0, _len = listeners.length; _i < _len; _i++) {
      l = listeners[_i];
      if (l.listener) {
        unwrapped.push(l.listener);
      } else {
        unwrapped.push(l);
      }
    }
    return unwrapped;
  };

  Object.defineProperty(EventEmitter.prototype.on, 'longjohn', {
    writable: true,
    enumerable: false,
    configurable: true,
    value: this
  });

  _nextTick = process.nextTick;

  process.nextTick = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'process.nextTick');
    return _nextTick.apply(this, args);
  };

  __nextDomainTick = process._nextDomainTick;

  process._nextDomainTick = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'process.nextDomainTick');
    return __nextDomainTick.apply(this, args);
  };

  _setTimeout = global.setTimeout;

  _setInterval = global.setInterval;

  global.setTimeout = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'global.setTimeout');
    return _setTimeout.apply(this, args);
  };

  global.setInterval = function(callback) {
    var args;
    args = Array.prototype.slice.call(arguments);
    args[0] = wrap_callback(callback, 'global.setInterval');
    return _setInterval.apply(this, args);
  };

  if (global.setImmediate != null) {
    _setImmediate = global.setImmediate;
    global.setImmediate = function(callback) {
      var args;
      args = Array.prototype.slice.call(arguments);
      args[0] = wrap_callback(callback, 'global.setImmediate');
      return _setImmediate.apply(this, args);
    };
  }

  Error.prepareStackTrace = prepareStackTrace;

  if (process.env.NODE_ENV === 'production') {
    console.warn('NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime.\nIt generally should not be used in production applications.');
  }

}).call(this);
<|endoftext|>


<commit_before>/**
 * Created by theophy on 06/08/2017.
 */
var generators = require("../lib/generators");
var assert = require('chai').assert;
var expect = require('chai').expect;
var _ = require('lodash');

describe('Generators', function () {

    it('it should be an object', function (done) {
        expect(generators).to.be.an('object');
        done();
    });

    //for tags
    describe('tags', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('tags');
            done();
        });

        it('should generate an array of models which contains name(globalId) and identity', function (done) {
            var models = {
                user: {
                    attributes: {},
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.tags(models)).to.be.an('array').to.have.deep.members([{
                name: models.user.globalId,
                identity: models.user.identity
            }]);

            done();
        });

    });

    //for definitions
    describe('definitions', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('definitions');
            done();
        });

        it('should generate an object of definitions which contains the schemas for each of our model', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string', required: true}
                    },
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.definitions(models)).to.be.an('object').to.have.deep.property('user', {
                properties: {name: {type: 'string'}},
                required: ['name']
            });

            done();
        });

        it('should not generate definition for models with no globalId, Ignoring associative tables', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string', required: true}
                    },
                    identity: 'user'
                }
            };

            expect(generators.definitions(models)).to.not.have.property('user');
            done();
        });

        it('should not allow empty required array, instead it should be out instead of empty array -- avoiding swagger Semantic error ', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string'} //no required this time
                    },
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.definitions(models).user).to.not.have.property('required');
            done();
        });

    });

    //for parameters
    describe('parameters', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('parameters');
            done();
        });

        it('should return default parameters with custom parameters', function (done) {
            var custom_parameters = { //we can add up custom parameters here
                PerPageQueryParam: {
                    in: 'query',
                    name: 'perPage',
                    required: false,
                    type: 'integer',
                    description: 'This helps with pagination and when the limit is known for pagify'
                }
            };

            expect(generators.parameters({
                blueprints: {defaultLimit: 30},
                swaggerDoc: {parameters: custom_parameters}
            }, {configKey: 'swaggerDoc'})).to.have.property('PerPageQueryParam');

            done();
        });

    });

    //for routes
    describe('routes', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('routes');
            done();
        });

        var controllers = {
            user: {
                login: function (req, res) {

                },
                logout: function (req, res) {

                }
            },
            base: {
                clear: function (req, res) { //this is a service that does general stuff so we don't need a model for it

                }
            }
        };
        var models = {
            user: {
                attributes: {},
                identity: 'user',
                globalId: 'User'
            }
        };

        var tags = generators.tags(models);

        it('generated route should have this properties assuming custom route(config/route.js) is empty', function (done) {

            expect(generators.routes(controllers, {}).user[0]).to.have.all.keys('http_method', 'path', 'action', 'keys', 'summary', 'description');
            done();
        });

        it("if controller action in custom route don't generate route for it again, use the one from the custom", function (done) {

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}).user, {
                http_method: 'post',
                action: 'login'
            })).to.be.an('object');

            done();
        });

        it('it should generate default blueprint action routes, create, find, findOne, update, destroy for routes with model or tag', function (done) {

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'find',
                http_method: 'get'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'findOne',
                http_method: 'get'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'update',
                http_method: 'put'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'create',
                http_method: 'post'
            })).to.be.an('object');

            /**
             * should not have any of these since no model for 'base'
             */
            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'find',
                http_method: 'get'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'findOne',
                http_method: 'get'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'update',
                http_method: 'put'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'create',
                http_method: 'post'
            })).to.be.undefined;

            done();
        });

        it('should allow default methods(actions) name in a controller with no model or tag but not the one created by us', function (done) {
            controllers.base['find'] = function (req, res) {

            };
            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'find',
                http_method: 'get'
            })).to.be.an('object');

            done();
        });

    });

    //for paths
    describe('paths', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('paths');
            done();
        });

        var controllers = {
            user: {
                login: function (req, res) {

                },
                logout: function (req, res) {

                },
                list: function (req, res) {

                }
            },
            base: { //a controller without model
                clear: function (req, res) {

                }
            }
        };

        var models = {
            user: {
                attributes: {
                    name: {type: 'string', required: true}
                },
                identity: 'user',
                globalId: 'User'
            }
        };
        var tags = generators.tags(models);
        var generatedRoutes = generators.routes(controllers, {'get /user/phone/:phoneNumber': 'UserController.phone'}, tags);
        var actual = generators.paths(generatedRoutes, tags, {list: [{$ref: '#/parameters/PerPageQueryParam'}]});

        it('should not create default paths like create, find, findOne, update and destroy for routes without models', function (done) {
            expect(actual).to.not.have.property('/base'); //for destroy, find
            expect(actual).to.not.have.property('/base/{id}'); //for findOne, update
            done();
        });

        it('should follow the swagger standardized url format of  "/route instead of /route/ or route/"', function (done) {
            assert.containsAllDeepKeys(actual, ['/user/login', '/user/{id}'], "should have this url pattern");
            expect(actual).to.not.have.property('user/login');
            expect(actual).to.not.have.property('/user/{id}/');

            done();
        });

        it('every route must contain tags which must be the globalId of the model', function (done) {
            assert.deepEqual(actual['/user/login'].get.tags, [models.user.globalId], "The tag must be array of the globalId ");
            done();
        });

        it('all route should produce and consume application/json', function (done) {
            expect(actual['/user/login'].get.produces).to.have.members(['application/json']);
            expect(actual['/user/login'].get.consumes).to.have.members(['application/json']);
            done();
        });

        it('should handle the different types of response', function (done) {
            expect(actual['/user/login'].get.responses).to.have.all.keys(200, 404, 500);
            done();
        });

        it('should custom blueprint mapping should override default parameter mapping', function (done) {
            assert.notIncludeDeepMembers(actual['/user/list'].get.parameters, [{$ref: '#/parameters/TokenHeaderParam'}], "should not contain token header param since it was overridden");
            done();
        });

        it('all route should hold the token header parameter, in case that routes needs authentication, if overridden above test case, it wont add', function (done) {
            expect(actual['/user/logout'].get.parameters).to.have.deep.members([{$ref: '#/parameters/TokenHeaderParam'}]);
            done();
        });

        it('should add form body for default blueprints actions like create and update', function (done) {
            expect(_.find(actual['/user'].post.parameters, {name: 'body', in: 'body'})).to.be.an('object');
            expect(_.find(actual['/user/{id}'].put.parameters, {name: 'body', in: 'body'})).to.be.an('object');
            done();
        });

        it('should make sure every route keys has a corresponding path type of parameter', function (done) {
            expect(_.find(actual['/user/phone/{phoneNumber}'].get.parameters, {
                name: 'phoneNumber',
                in: 'path'
            })).to.be.an('object');
            expect(_.find(actual['/user/{id}'].get.parameters, {$ref: '#/parameters/IDPathParam'})).to.be.an('object');
            done();
        });

    });
})
;<commit_msg>created test case for not allowing sails generator to override default route and http method seen in a controller<commit_after>/**
 * Created by theophy on 06/08/2017.
 */
var generators = require("../lib/generators");
var assert = require('chai').assert;
var expect = require('chai').expect;
var _ = require('lodash');

describe('Generators', function () {

    it('it should be an object', function (done) {
        expect(generators).to.be.an('object');
        done();
    });

    //for tags
    describe('tags', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('tags');
            done();
        });

        it('should generate an array of models which contains name(globalId) and identity', function (done) {
            var models = {
                user: {
                    attributes: {},
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.tags(models)).to.be.an('array').to.have.deep.members([{
                name: models.user.globalId,
                identity: models.user.identity
            }]);

            done();
        });

    });

    //for definitions
    describe('definitions', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('definitions');
            done();
        });

        it('should generate an object of definitions which contains the schemas for each of our model', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string', required: true}
                    },
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.definitions(models)).to.be.an('object').to.have.deep.property('user', {
                properties: {name: {type: 'string'}},
                required: ['name']
            });

            done();
        });

        it('should not generate definition for models with no globalId, Ignoring associative tables', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string', required: true}
                    },
                    identity: 'user'
                }
            };

            expect(generators.definitions(models)).to.not.have.property('user');
            done();
        });

        it('should not allow empty required array, instead it should be out instead of empty array -- avoiding swagger Semantic error ', function (done) {
            var models = {
                user: {
                    attributes: {
                        name: {type: 'string'} //no required this time
                    },
                    identity: 'user',
                    globalId: 'User'
                }
            };

            expect(generators.definitions(models).user).to.not.have.property('required');
            done();
        });

    });

    //for parameters
    describe('parameters', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('parameters');
            done();
        });

        it('should return default parameters with custom parameters', function (done) {
            var custom_parameters = { //we can add up custom parameters here
                PerPageQueryParam: {
                    in: 'query',
                    name: 'perPage',
                    required: false,
                    type: 'integer',
                    description: 'This helps with pagination and when the limit is known for pagify'
                }
            };

            expect(generators.parameters({
                blueprints: {defaultLimit: 30},
                swaggerDoc: {parameters: custom_parameters}
            }, {configKey: 'swaggerDoc'})).to.have.property('PerPageQueryParam');

            done();
        });

    });

    //for routes
    describe('routes', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('routes');
            done();
        });

        var controllers = {
            user: {
                login: function (req, res) {

                },
                logout: function (req, res) {

                }
            },
            base: {
                clear: function (req, res) { //this is a service that does general stuff so we don't need a model for it

                }
            }
        };
        var models = {
            user: {
                attributes: {},
                identity: 'user',
                globalId: 'User'
            }
        };

        var tags = generators.tags(models);

        it('generated route should have this properties assuming custom route(config/route.js) is empty', function (done) {

            expect(generators.routes(controllers, {}).user[0]).to.have.all.keys('http_method', 'path', 'action', 'keys', 'summary', 'description');
            done();
        });

        it("if controller action in custom route don't generate route for it again, use the one from the custom", function (done) {

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}).user, {
                http_method: 'post',
                action: 'login'
            })).to.be.an('object');

            done();
        });

        it('it should generate default blueprint action routes, create, find, findOne, update, destroy for routes with model or tag', function (done) {

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'find',
                http_method: 'get'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'findOne',
                http_method: 'get'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'update',
                http_method: 'put'
            })).to.be.an('object');

            expect(_.find(generators.routes(controllers, {'post /user/login': 'UserController.login'}, tags).user, {
                action: 'create',
                http_method: 'post'
            })).to.be.an('object');

            /**
             * should not have any of these since no model for 'base'
             */
            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'find',
                http_method: 'get'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'findOne',
                http_method: 'get'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'update',
                http_method: 'put'
            })).to.be.undefined;

            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'create',
                http_method: 'post'
            })).to.be.undefined;

            done();
        });

        it('should allow default methods(actions) name in a controller with no model or tag but not the one created by us', function (done) {
            controllers.base['find'] = function (req, res) {

            };
            expect(_.find(generators.routes(controllers, {'post /base/clear': 'BaseController.clear'}, tags).base, {
                action: 'find',
                http_method: 'get'
            })).to.be.an('object');

            done();
        });

        it('should not override default blueprints path, http_method even if found in a controller', function (done) {

            controllers.user['update'] = function (req, res) {

            };

            expect(_.find(generators.routes(controllers, {}, tags).base, {
                action: 'update',
                http_method: 'put'
            })).to.be.an('object');
            done();
        });

    });

    //for paths
    describe('paths', function () {
        it('should contain ', function (done) {
            expect(generators).to.have.property('paths');
            done();
        });

        var controllers = {
            user: {
                login: function (req, res) {

                },
                logout: function (req, res) {

                },
                list: function (req, res) {

                }
            },
            base: { //a controller without model
                clear: function (req, res) {

                }
            }
        };

        var models = {
            user: {
                attributes: {
                    name: {type: 'string', required: true}
                },
                identity: 'user',
                globalId: 'User'
            }
        };
        var tags = generators.tags(models);
        var generatedRoutes = generators.routes(controllers, {'get /user/phone/:phoneNumber': 'UserController.phone'}, tags);
        var actual = generators.paths(generatedRoutes, tags, {list: [{$ref: '#/parameters/PerPageQueryParam'}]});

        it('should not create default paths like create, find, findOne, update and destroy for routes without models', function (done) {
            expect(actual).to.not.have.property('/base'); //for destroy, find
            expect(actual).to.not.have.property('/base/{id}'); //for findOne, update
            done();
        });

        it('should follow the swagger standardized url format of  "/route instead of /route/ or route/"', function (done) {
            assert.containsAllDeepKeys(actual, ['/user/login', '/user/{id}'], "should have this url pattern");
            expect(actual).to.not.have.property('user/login');
            expect(actual).to.not.have.property('/user/{id}/');

            done();
        });

        it('every route must contain tags which must be the globalId of the model', function (done) {
            assert.deepEqual(actual['/user/login'].get.tags, [models.user.globalId], "The tag must be array of the globalId ");
            done();
        });

        it('all route should produce and consume application/json', function (done) {
            expect(actual['/user/login'].get.produces).to.have.members(['application/json']);
            expect(actual['/user/login'].get.consumes).to.have.members(['application/json']);
            done();
        });

        it('should handle the different types of response', function (done) {
            expect(actual['/user/login'].get.responses).to.have.all.keys(200, 404, 500);
            done();
        });

        it('should custom blueprint mapping should override default parameter mapping', function (done) {
            assert.notIncludeDeepMembers(actual['/user/list'].get.parameters, [{$ref: '#/parameters/TokenHeaderParam'}], "should not contain token header param since it was overridden");
            done();
        });

        it('all route should hold the token header parameter, in case that routes needs authentication, if overridden above test case, it wont add', function (done) {
            expect(actual['/user/logout'].get.parameters).to.have.deep.members([{$ref: '#/parameters/TokenHeaderParam'}]);
            done();
        });

        it('should add form body for default blueprints actions like create and update', function (done) {
            expect(_.find(actual['/user'].post.parameters, {name: 'body', in: 'body'})).to.be.an('object');
            expect(_.find(actual['/user/{id}'].put.parameters, {name: 'body', in: 'body'})).to.be.an('object');
            done();
        });

        it('should make sure every route keys has a corresponding path type of parameter', function (done) {
            expect(_.find(actual['/user/phone/{phoneNumber}'].get.parameters, {
                name: 'phoneNumber',
                in: 'path'
            })).to.be.an('object');
            expect(_.find(actual['/user/{id}'].get.parameters, {$ref: '#/parameters/IDPathParam'})).to.be.an('object');
            done();
        });

    });
})
;<|endoftext|>