<commit_before>/*
Name:         tk102
Description:  TK102 GPS server for Node.js
Author:       Franklin van de Meent (https://frankl.in)
Source:       https://github.com/fvdm/nodejs-tk102
Feedback:     https://github.com/fvdm/nodejs-tk102/issues
License:      Unlicense / Public Domain (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-tk102/raw/master/UNLICENSE)
*/

var net = require ('net');
var EventEmitter = require ('events') .EventEmitter;
var tk102 = new EventEmitter ();

// device data
var specs = [
  function (raw) {
    // 1203292316,0031698765432,GPRMC,211657.000,A,5213.0247,N,00516.7757,E,0.00,273.30,290312,,,A*62,F,imei:123456789012345,123
    var result = null;
    var str = [];
    var datetime = '';
    var gpsdate = '';
    var gpstime = '';

    try {
      raw = raw.trim ();
      str = raw.split (',');

      if (str.length === 18 && str [2] === 'GPRMC') {
        datetime = str [0] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, y, m, d, h, i) {
          return '20' + y + '-' + m + '-' + d + ' ' + h + ':' + i;
        });

        gpsdate = str [11] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, d, m, y) {
          return '20' + y + '-' + m + '-' + d;
        });

        gpstime = str [3] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})\.([0-9]{3})/, function (s0, h, i, s, ms) {
          return h + ':' + i + ':' + s + '.' + ms;
        });

        result = {
          raw: raw,
          datetime: datetime,
          phone: str [1],
          gps: {
            date: gpsdate,
            time: gpstime,
            signal: str [15] === 'F' ? 'full' : 'low',
            fix: str [4] === 'A' ? 'active' : 'invalid'
          },
          geo: {
            latitude: tk102.fixGeo (str [5], str [6]),
            longitude: tk102.fixGeo (str [7], str [8]),
            bearing: parseInt (str [10], 10)
          },
          speed: {
            knots: Math.round (str [9] * 1000) / 1000,
            kmh: Math.round (str [9] * 1.852 * 1000) / 1000,
            mph: Math.round (str [9] * 1.151 * 1000) / 1000
          },
          imei: str [16] .replace ('imei:', ''),
          checksum: tk102.checksum (raw)
        };
      }
    } catch (e) {
      result = null;
    }

    return result;
  }
];

// defaults
tk102.settings = {
  ip: '0.0.0.0',
  port: 0,
  connections: 10,
  timeout: 10
};

// Catch uncaught exceptions (server kill)
process.on ('uncaughtException', function (err) {
  var error = new Error ('uncaught exception');

  error.error = err;
  console.trace (error);
});

// Create server
tk102.createServer = function (vars) {
  var key;

  // override settings
  if (typeof vars === 'object' && Object.keys (vars) .length >= 1) {
    for (key in vars) {
      tk102.settings [key] = vars [key];
    }
  }

  // start server
  tk102.server = net.createServer (function (socket) {
    // socket idle timeout
    if (tk102.settings.timeout > 0) {
      socket.setTimeout (parseInt (tk102.settings.timeout * 1000, 10), function () {
        tk102.emit ('timeout', socket);
        socket.end ();
      });
    }
  }) .listen (tk102.settings.port, tk102.settings.ip, function () {
    // server ready
    tk102.emit ('listening', tk102.server.address ());
  });

  // maximum number of slots
  tk102.server.maxConnections = tk102.settings.connections;

  // inbound connection
  tk102.server.on ('connection', function (socket) {
    var data = [];
    var size = 0;

    tk102.emit ('connection', socket);
    socket.setEncoding ('utf8');

    socket.on ('data', function (ch) {
      tk102.emit ('data', ch);
      data.push (ch);
      size += ch.length;
    });

    socket.on ('close', function () {
      var gps = {};
      var err = null;

      data = Buffer.concat (data, size).toString ('utf8');

      if (data !== '') {
        gps = tk102.parse (data);

        if (gps) {
          tk102.emit ('track', gps);
        } else {
          err = new Error ('Cannot parse GPS data from device');
          err.reason = err.message;
          err.socket = socket;
          err.input = data;

          tk102.emit ('fail', err);
        }
      }
    });

    // error
    socket.on ('error', function (error) {
      var err = new Error ('Socket error');

      err.reason = err.message;
      err.socket = socket;
      err.settings = tk102.settings;

      tk102.emit ('error', err);
    });
  });

  tk102.server.on ('error', function (error) {
    var err = new Error ('Server error');

    if (error === 'EADDRNOTAVAIL') {
      err = new Error ('IP or port not available');
    }

    err.reason = err.message;
    err.input = tk102.settings;

    tk102.emit ('error', err);
  });
};

// Parse GPRMC string
tk102.parse = function (raw) {
  var data = null;
  var i = 0;

  while (data === null && i < specs.length) {
    data = specs [i] (raw);
    i++;
  }

  return data;
};

// Clean geo positions, with 6 decimals
tk102.fixGeo = function (one, two) {
  var minutes = one.substr (-7, 7);
  var degrees = parseInt (one.replace (minutes, ''), 10);

  one = degrees + (minutes / 60);
  one = parseFloat ((two === 'S' || two === 'W' ? '-' : '') + one);

  return Math.round (one * 1000000) / 1000000;
};

// Check checksum in raw string
tk102.checksum = function (raw) {
  var str = raw.trim () .split (/[,*#]/);
  var strsum = parseInt (str [15], 10);
  var strchk = str.slice (2, 15) .join (',');
  var check = 0;
  var i;

  for (i = 0; i < strchk.length; i++) {
    check ^= strchk.charCodeAt (i);
  }

  check = parseInt (check.toString (16), 10);
  return (check === strsum);
};

// ready
module.exports = tk102;
<commit_msg>Reduced complexity of createServer()<commit_after>/*
Name:         tk102
Description:  TK102 GPS server for Node.js
Author:       Franklin van de Meent (https://frankl.in)
Source:       https://github.com/fvdm/nodejs-tk102
Feedback:     https://github.com/fvdm/nodejs-tk102/issues
License:      Unlicense / Public Domain (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-tk102/raw/master/UNLICENSE)
*/

var net = require ('net');
var EventEmitter = require ('events') .EventEmitter;
var tk102 = new EventEmitter ();

// device data
var specs = [
  function (raw) {
    // 1203292316,0031698765432,GPRMC,211657.000,A,5213.0247,N,00516.7757,E,0.00,273.30,290312,,,A*62,F,imei:123456789012345,123
    var result = null;
    var str = [];
    var datetime = '';
    var gpsdate = '';
    var gpstime = '';

    try {
      raw = raw.trim ();
      str = raw.split (',');

      if (str.length === 18 && str [2] === 'GPRMC') {
        datetime = str [0] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, y, m, d, h, i) {
          return '20' + y + '-' + m + '-' + d + ' ' + h + ':' + i;
        });

        gpsdate = str [11] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, d, m, y) {
          return '20' + y + '-' + m + '-' + d;
        });

        gpstime = str [3] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})\.([0-9]{3})/, function (s0, h, i, s, ms) {
          return h + ':' + i + ':' + s + '.' + ms;
        });

        result = {
          raw: raw,
          datetime: datetime,
          phone: str [1],
          gps: {
            date: gpsdate,
            time: gpstime,
            signal: str [15] === 'F' ? 'full' : 'low',
            fix: str [4] === 'A' ? 'active' : 'invalid'
          },
          geo: {
            latitude: tk102.fixGeo (str [5], str [6]),
            longitude: tk102.fixGeo (str [7], str [8]),
            bearing: parseInt (str [10], 10)
          },
          speed: {
            knots: Math.round (str [9] * 1000) / 1000,
            kmh: Math.round (str [9] * 1.852 * 1000) / 1000,
            mph: Math.round (str [9] * 1.151 * 1000) / 1000
          },
          imei: str [16] .replace ('imei:', ''),
          checksum: tk102.checksum (raw)
        };
      }
    } catch (e) {
      result = null;
    }

    return result;
  }
];

// defaults
tk102.settings = {
  ip: '0.0.0.0',
  port: 0,
  connections: 10,
  timeout: 10
};

// Catch uncaught exceptions (server kill)
process.on ('uncaughtException', function (err) {
  var error = new Error ('uncaught exception');

  error.error = err;
  console.trace (error);
});

// Create server
tk102.createServer = function (vars) {
  var key;

  // override settings
  if (typeof vars === 'object' && Object.keys (vars) .length >= 1) {
    for (key in vars) {
      tk102.settings [key] = vars [key];
    }
  }

  // start server
  tk102.server = net.createServer ();

  // maximum number of slots
  tk102.server.maxConnections = tk102.settings.connections;

  // server started
  tk102.server.on ('listening', function () {
    tk102.emit ('listening', tk102.server.address ());
  });

  // inbound connection
  tk102.server.on ('connection', function (socket) {
    var data = [];
    var size = 0;

    tk102.emit ('connection', socket);
    socket.setEncoding ('utf8');

    if (tk102.settings.timeout > 0) {
      socket.setTimeout (parseInt (tk102.settings.timeout * 1000, 10));
    }

    socket.on ('timeout', function () {
      tk102.emit ('timeout', socket);
      socket.destroy ();
    });

    socket.on ('data', function (ch) {
      tk102.emit ('data', ch);
      data.push (ch);
      size += ch.length;
    });

    socket.on ('close', function () {
      var gps = {};
      var err = null;

      data = Buffer.concat (data, size) .toString ('utf8');

      if (data !== '') {
        gps = tk102.parse (data);

        if (gps) {
          tk102.emit ('track', gps);
        } else {
          err = new Error ('Cannot parse GPS data from device');
          err.reason = err.message;
          err.socket = socket;
          err.input = data;

          tk102.emit ('fail', err);
        }
      }
    });

    // error
    socket.on ('error', function (error) {
      var err = new Error ('Socket error');

      err.reason = error.message;
      err.socket = socket;
      err.settings = tk102.settings;

      tk102.emit ('error', err);
    });
  });

  tk102.server.on ('error', function (error) {
    var err = new Error ('Server error');

    if (error === 'EADDRNOTAVAIL') {
      err = new Error ('IP or port not available');
    }

    err.reason = error.message;
    err.input = tk102.settings;

    tk102.emit ('error', err);
  });

  // Start listening
  tk102.server.listen (tk102.settings.port, tk102.settings.ip);
};

// Parse GPRMC string
tk102.parse = function (raw) {
  var data = null;
  var i = 0;

  while (data === null && i < specs.length) {
    data = specs [i] (raw);
    i++;
  }

  return data;
};

// Clean geo positions, with 6 decimals
tk102.fixGeo = function (one, two) {
  var minutes = one.substr (-7, 7);
  var degrees = parseInt (one.replace (minutes, ''), 10);

  one = degrees + (minutes / 60);
  one = parseFloat ((two === 'S' || two === 'W' ? '-' : '') + one);

  return Math.round (one * 1000000) / 1000000;
};

// Check checksum in raw string
tk102.checksum = function (raw) {
  var str = raw.trim () .split (/[,*#]/);
  var strsum = parseInt (str [15], 10);
  var strchk = str.slice (2, 15) .join (',');
  var check = 0;
  var i;

  for (i = 0; i < strchk.length; i++) {
    check ^= strchk.charCodeAt (i);
  }

  check = parseInt (check.toString (16), 10);
  return (check === strsum);
};

// ready
module.exports = tk102;
<|endoftext|>


<commit_before>var quip = require('../lib/quip');

exports.status = function(test){
    test.expect(4);
    var res = quip.update({});
    test.same(res.status(200), res);
    test.equals(res._quip_status, 200);
    test.same(res.status(404), res);
    test.equals(res._quip_status, 404);
    test.done();
};

var statusTest = function(code, name){
    return function(test){
        test.expect(6);

        var res = quip.update({});
        test.same(res[name](), res);
        test.equals(res._quip_status, code);

        var res2 = quip.update({});
        res2.send = function(data){
            test.equals(res2._quip_status, code);
            test.same(res2._quip_headers, {'Content-Type':'text/html'});
            test.equals(data, 'content');
        };
        test.equals(res2[name]('content'), null);
        test.done();
    };
};

// success codes
exports.ok = statusTest(200, 'ok');
exports.created = statusTest(201, 'created');
exports.accepted = statusTest(202, 'accepted'); // remove this ???

// client error code
exports.badRequest = statusTest(400, 'badRequest');
exports.forbidden = statusTest(403, 'forbidden');
exports.notFound = statusTest(404, 'notFound');
exports.conflict = statusTest(409, 'conflict');
exports.gone = statusTest(410, 'gone');
exports.notAllowed = statusTest(405, 'notAllowed');

// server error codes
exports.error = statusTest(500, 'error');

var redirectionTest = function(code, name, body){
    return function(test){
        test.expect(5);
        var res = quip.update({});
        res.send = function(data){
            test.equals(res._quip_status, code);
            test.equals(res._quip_headers.Location, 'loc');
            test.equals(res._quip_headers['Content-Type'], 'text/html');
            test.equals(data, body);
        };
        test.equals(res[name]('loc'), null);
        test.done();
    };
};

// redirection codes
exports.moved = redirectionTest(301, 'moved',
    '' +
        '<title>301 Moved Permanently</title>' +
        '
Moved Permanently: loc
' +
    '');
exports.redirect = redirectionTest(302, 'redirect',
    '' +
        '<title>302 Found</title>' +
        '
Found: loc
' +
    '');
exports.found = redirectionTest(302, 'found',
    '' +
        '<title>302 Found</title>' +
        '
Found: loc
' +
    '');

exports.notModified = function(test){
    test.expect(8);
    var res = quip.update({});
    res.send = function(data){
        test.equals(res._quip_status, 304);
        test.same(res._quip_headers, {'Content-Type':'text/html'});
        // 304 must not return body
        test.equals(data, null);
    };
    test.equals(res.notModified(), null);
    test.equals(res.notModified('content'), null);
    test.done();
};

var mimeTypeTest = function(type, name){
    return function(test){
        test.expect(6);

        var res = quip.update({});
        res.send = function(data){
            test.ok(true, 'send called');
            test.equals(res._quip_headers['Content-Type'], type);
            test.equals(data, 'content');
        };
        test.equals(res[name]('content'), null);

        var res2 = quip.update({});
        res2.send = function(data){
            test.ok(false, 'send should not be called');
        };
        test.equals(res2[name](), res2);
        test.equals(res2._quip_headers['Content-Type'], type);
        test.done();
    };
};

exports.text = mimeTypeTest('text/plain', 'plain');
exports.plain = mimeTypeTest('text/plain', 'text');
exports.html = mimeTypeTest('text/html', 'html');
exports.xhtml = mimeTypeTest('application/xhtml+xml', 'xhtml');
exports.css = mimeTypeTest('text/css', 'css');
exports.xml = mimeTypeTest('text/xml', 'xml');
exports.atom = mimeTypeTest('application/atom+xml', 'atom');
exports.rss = mimeTypeTest('application/rss+xml', 'rss');
exports.javascript = mimeTypeTest('text/javascript', 'javascript');
exports.json = mimeTypeTest('application/json', 'json');

exports.jsonp = function(test){
    test.expect(7);
    var res = quip.update({});
    res.send = function(data){
        test.equals(data, 'mycallback({"some":"data"});');
        test.equals(res._quip_status, 200);
        test.same(res._quip_headers, {'Content-Type':'text/javascript'});
    };
    var r = res.jsonp('mycallback', {'some':'data'});
    test.equals(r, null); //should not allow further chaining

    // status code should be overridden
    res.error().jsonp('mycallback', {'some':'data'});
    test.done();
};

exports.send = function(test){
    test.expect(4);
    var res = quip.update({
        writeHead: function(code, headers){
            test.same(headers, {
                headers: 'test',
                'Content-Length': 4
            });
            test.equals(code, 404);
        },
        write: function(data){
            test.equals(data, 'data');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res._quip_headers = {headers: 'test'};
    res._quip_status = 404;
    res.send('data');
    test.done();
};

exports['send defaults'] = function(test){
    test.expect(3);
    var res = quip.update({
        writeHead: function(code, headers){
            test.same(headers, {'Content-Type': 'text/html'});
            test.equals(code, 200);
        },
        write: function(data){
            test.ok(false, 'should not be called if no data');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res.send();
    test.done();
};

exports['send object literal as json'] = function(test){
    test.expect(6);
    var res = quip.update({
        writeHead: function(code, headers){
            test.ok(true, 'writeHead called');
        },
        write: function(data){
            test.equals(data, '{"test":"object"}');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res.json({test:'object'});
    res.json().ok({test:'object'});
    test.done();
};

exports.headers = function(test){
    test.expect(3);
    var res = quip.update({});
    test.equals(res.headers({some:'header',test:'test'}), res);
    test.same(res._quip_headers, {
        'Content-Type':'text/html',
        some:'header',
        test:'test'
    });
    res.headers({'Content-Type':'test'});
    test.same(res._quip_headers, {
        'Content-Type':'test',
        some:'header',
        test:'test'
    });
    test.done();
};

exports.filter = function(test){
    test.expect(2);

    var res = {test:'response'};
    var _update = quip.update;
    quip.update = function(r){
        test.equals(r, res);
    };
    quip()(null, res, function(){
        test.ok(true, 'next called');
    });

    quip.update = _update;
    test.done();
};
<commit_msg>rename filter test to middleware and change implementation to stop relying on quip.update<commit_after>var quip = require('../lib/quip');

exports.status = function(test){
    test.expect(4);
    var res = quip.update({});
    test.same(res.status(200), res);
    test.equals(res._quip_status, 200);
    test.same(res.status(404), res);
    test.equals(res._quip_status, 404);
    test.done();
};

var statusTest = function(code, name){
    return function(test){
        test.expect(6);

        var res = quip.update({});
        test.same(res[name](), res);
        test.equals(res._quip_status, code);

        var res2 = quip.update({});
        res2.send = function(data){
            test.equals(res2._quip_status, code);
            test.same(res2._quip_headers, {'Content-Type':'text/html'});
            test.equals(data, 'content');
        };
        test.equals(res2[name]('content'), null);
        test.done();
    };
};

// success codes
exports.ok = statusTest(200, 'ok');
exports.created = statusTest(201, 'created');
exports.accepted = statusTest(202, 'accepted'); // remove this ???

// client error code
exports.badRequest = statusTest(400, 'badRequest');
exports.forbidden = statusTest(403, 'forbidden');
exports.notFound = statusTest(404, 'notFound');
exports.conflict = statusTest(409, 'conflict');
exports.gone = statusTest(410, 'gone');
exports.notAllowed = statusTest(405, 'notAllowed');

// server error codes
exports.error = statusTest(500, 'error');

var redirectionTest = function(code, name, body){
    return function(test){
        test.expect(5);
        var res = quip.update({});
        res.send = function(data){
            test.equals(res._quip_status, code);
            test.equals(res._quip_headers.Location, 'loc');
            test.equals(res._quip_headers['Content-Type'], 'text/html');
            test.equals(data, body);
        };
        test.equals(res[name]('loc'), null);
        test.done();
    };
};

// redirection codes
exports.moved = redirectionTest(301, 'moved',
    '' +
        '<title>301 Moved Permanently</title>' +
        '
Moved Permanently: loc
' +
    '');
exports.redirect = redirectionTest(302, 'redirect',
    '' +
        '<title>302 Found</title>' +
        '
Found: loc
' +
    '');
exports.found = redirectionTest(302, 'found',
    '' +
        '<title>302 Found</title>' +
        '
Found: loc
' +
    '');

exports.notModified = function(test){
    test.expect(8);
    var res = quip.update({});
    res.send = function(data){
        test.equals(res._quip_status, 304);
        test.same(res._quip_headers, {'Content-Type':'text/html'});
        // 304 must not return body
        test.equals(data, null);
    };
    test.equals(res.notModified(), null);
    test.equals(res.notModified('content'), null);
    test.done();
};

var mimeTypeTest = function(type, name){
    return function(test){
        test.expect(6);

        var res = quip.update({});
        res.send = function(data){
            test.ok(true, 'send called');
            test.equals(res._quip_headers['Content-Type'], type);
            test.equals(data, 'content');
        };
        test.equals(res[name]('content'), null);

        var res2 = quip.update({});
        res2.send = function(data){
            test.ok(false, 'send should not be called');
        };
        test.equals(res2[name](), res2);
        test.equals(res2._quip_headers['Content-Type'], type);
        test.done();
    };
};

exports.text = mimeTypeTest('text/plain', 'plain');
exports.plain = mimeTypeTest('text/plain', 'text');
exports.html = mimeTypeTest('text/html', 'html');
exports.xhtml = mimeTypeTest('application/xhtml+xml', 'xhtml');
exports.css = mimeTypeTest('text/css', 'css');
exports.xml = mimeTypeTest('text/xml', 'xml');
exports.atom = mimeTypeTest('application/atom+xml', 'atom');
exports.rss = mimeTypeTest('application/rss+xml', 'rss');
exports.javascript = mimeTypeTest('text/javascript', 'javascript');
exports.json = mimeTypeTest('application/json', 'json');

exports.jsonp = function(test){
    test.expect(7);
    var res = quip.update({});
    res.send = function(data){
        test.equals(data, 'mycallback({"some":"data"});');
        test.equals(res._quip_status, 200);
        test.same(res._quip_headers, {'Content-Type':'text/javascript'});
    };
    var r = res.jsonp('mycallback', {'some':'data'});
    test.equals(r, null); //should not allow further chaining

    // status code should be overridden
    res.error().jsonp('mycallback', {'some':'data'});
    test.done();
};

exports.send = function(test){
    test.expect(4);
    var res = quip.update({
        writeHead: function(code, headers){
            test.same(headers, {
                headers: 'test',
                'Content-Length': 4
            });
            test.equals(code, 404);
        },
        write: function(data){
            test.equals(data, 'data');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res._quip_headers = {headers: 'test'};
    res._quip_status = 404;
    res.send('data');
    test.done();
};

exports['send defaults'] = function(test){
    test.expect(3);
    var res = quip.update({
        writeHead: function(code, headers){
            test.same(headers, {'Content-Type': 'text/html'});
            test.equals(code, 200);
        },
        write: function(data){
            test.ok(false, 'should not be called if no data');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res.send();
    test.done();
};

exports['send object literal as json'] = function(test){
    test.expect(6);
    var res = quip.update({
        writeHead: function(code, headers){
            test.ok(true, 'writeHead called');
        },
        write: function(data){
            test.equals(data, '{"test":"object"}');
        },
        end: function(){
            test.ok(true, 'end called');
        }
    });
    res.json({test:'object'});
    res.json().ok({test:'object'});
    test.done();
};

exports.headers = function(test){
    test.expect(3);
    var res = quip.update({});
    test.equals(res.headers({some:'header',test:'test'}), res);
    test.same(res._quip_headers, {
        'Content-Type':'text/html',
        some:'header',
        test:'test'
    });
    res.headers({'Content-Type':'test'});
    test.same(res._quip_headers, {
        'Content-Type':'test',
        some:'header',
        test:'test'
    });
    test.done();
};

exports.middleware = function(test){
    test.expect(3);
    var res = {test:'response'};
    quip()(null, res, function(){
        test.ok(res.json);
        test.ok(res.jsonp);
        test.ok(true, 'next called');
    });
    test.done();
};
<|endoftext|>


<commit_before>var urlTools = require('urltools'),
    AssetGraph = require('../'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs,
    uglifyAst = AssetGraph.JavaScript.uglifyAst;

module.exports = function (options) {
    options = options || {};
    return function registerRequireJsConfig(assetGraph) {
        var requireJsConfig = (assetGraph.requireJsConfig = assetGraph.requireJsConfig || {});

        requireJsConfig.paths = requireJsConfig.paths || {};
        requireJsConfig.shim = {};
        requireJsConfig.foundConfig = false;
        requireJsConfig.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound = !!options.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound;

        requireJsConfig.findLongestPathsPrefix = function (moduleName) {
            var fragments = moduleName.split('/');

            for (var i = fragments.length ; i > 0 ; i -= 1) {
                var prefix = fragments.slice(0, i).join('/');
                if (prefix in this.paths) {
                    return prefix;
                }
            }
        };

        requireJsConfig.resolveModuleName = function (moduleName) {
            var longestPathsPrefix = this.findLongestPathsPrefix(moduleName);
            if (longestPathsPrefix) {
                if (longestPathsPrefix === moduleName) {
                    return this.paths[longestPathsPrefix];
                } else {
                    return urlTools.resolveUrl(this.paths[longestPathsPrefix].replace(/\/?$/, '/'), moduleName.replace(longestPathsPrefix + '/', ''));
                }
            } else {
                return moduleName;
            }
        };

        requireJsConfig.getModuleNames = function (asset, fallbackBaseUrl) {
            if (asset.isInline) {
                return null;
            }

            var baseUrl = (requireJsConfig.baseUrl && requireJsConfig.baseUrl) || fallbackBaseUrl,
                modulePrefixByPath = {},
                modulePaths = [];

            // TODO: Cache the below
            Object.keys(requireJsConfig.paths).forEach(function (modulePrefix) {
                var modulePath = requireJsConfig.paths[modulePrefix].replace(baseUrl, '').replace(/\/$/, '');
                modulePrefixByPath[modulePath] = modulePrefix;
                modulePaths.push(modulePath);
            });
            var modulePathsOrderedByLengthDesc = modulePaths.sort(function (a, b) {
                return b.length - a.length;
            });

            var canonicalModuleName = urlTools.buildRelativeUrl(baseUrl, asset.url).replace(/\.js$/, ''),
                moduleNames = [canonicalModuleName];
            for (var i = 0 ; i < modulePathsOrderedByLengthDesc.length ; i += 1) {
                var path = modulePathsOrderedByLengthDesc[i];
                if (canonicalModuleName.indexOf(path + '/') === 0) {
                    moduleNames.push(canonicalModuleName.replace(path, modulePrefixByPath[path]));
                }
            }
            return moduleNames;
        };

        requireJsConfig.getModuleName = function (asset, fallbackBaseUrl) {
            if (asset.isInline) {
                return null;
            }
            return requireJsConfig.getModuleNames(asset, fallbackBaseUrl)[0];
        };

        function registerShimArray(moduleName, arrayNode, javaScript) {
            requireJsConfig.shim[moduleName] = requireJsConfig.shim[moduleName] || {};
            var deps = (requireJsConfig.shim[moduleName].deps = requireJsConfig.shim[moduleName].deps || []);
            arrayNode.elements.forEach(function (elementNode) {
                if (elementNode instanceof uglifyJs.AST_String) {
                    if (deps.indexOf(elementNode.value) === -1) {
                        deps.push(elementNode.value);
                    }
                } else {
                    assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: [...]}}) syntax: ' + arrayNode.print_to_string()));
                }
            });
        }

        requireJsConfig.registerConfigInJavaScript = function (javaScript, htmlAsset) {
            if (!htmlAsset) {
                var incomingRelationsFromHtml = assetGraph.findRelations({to: javaScript, from: {type: 'Html'}});
                if (incomingRelationsFromHtml.length > 0) {
                    htmlAsset = incomingRelationsFromHtml[0].from.nonInlineAncestor; // Could be a conditional comment.
                }
            }
            if (htmlAsset) {
                var htmlUrl = htmlAsset.url,
                    extractRequireJsConfig = function (objAst) {
                        objAst.properties.forEach(function (keyValueNode) {
                            if (keyValueNode.key === 'baseUrl' && keyValueNode.value instanceof uglifyJs.AST_String) {
                                requireJsConfig.baseUrl = assetGraph.resolveUrl(htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''),
                                                                                keyValueNode.value.value.replace(/\/?$/, '/'));
                            } else if (keyValueNode.key === 'paths' && keyValueNode.value instanceof uglifyJs.AST_Object) {
                                keyValueNode.value.properties.forEach(function (pathNode) {
                                    if (pathNode.value instanceof uglifyJs.AST_String) {
                                        requireJsConfig.paths[pathNode.key] = pathNode.value.value;
                                    } else {
                                        assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({path: ...}) syntax: ' + pathNode.print_to_string()));
                                    }
                                });
                            } else if (keyValueNode.key === 'shim' && keyValueNode.value instanceof uglifyJs.AST_Object) {
                                keyValueNode.value.properties.forEach(function (shimNode) {
                                    var moduleName = shimNode.key;
                                    if (shimNode.value instanceof uglifyJs.AST_Array) {
                                        registerShimArray(moduleName, shimNode.value, javaScript);
                                    } else if (shimNode.value instanceof uglifyJs.AST_Object) {
                                        shimNode.value.properties.forEach(function (shimKeyValueNode) {
                                            if (shimKeyValueNode.key === 'deps') {
                                                if (shimKeyValueNode.value instanceof uglifyJs.AST_Array) {
                                                    registerShimArray(moduleName, shimKeyValueNode.value, javaScript);
                                                } else {
                                                    assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: {deps: ...}}) syntax: ' + objAst.print_to_string()));
                                                }
                                            } else {
                                                requireJsConfig.shim[moduleName] = requireJsConfig.shim[moduleName] || {};
                                                requireJsConfig.shim[moduleName][shimKeyValueNode.key] = uglifyAst.astToObj(shimKeyValueNode.value);
                                            }
                                        });
                                    } else {
                                        assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: ...}) syntax: ' + shimNode.print_to_string()));
                                    }
                                });
                            }
                        });
                    };

                javaScript.parseTree.walk(new uglifyJs.TreeWalker(function (node) {
                    if (node instanceof uglifyJs.AST_SimpleStatement &&
                        node.body instanceof uglifyJs.AST_Call &&
                        node.body.expression instanceof uglifyJs.AST_Dot &&
                        node.body.expression.property === 'config' &&
                        node.body.expression.expression instanceof uglifyJs.AST_SymbolRef &&
                        (node.body.expression.expression.name === 'require' || node.body.expression.expression.name === 'requirejs')) {

                        requireJsConfig.foundConfig = true;
                        extractRequireJsConfig(node.body.args[0]);
                    } else if (node instanceof uglifyJs.AST_Var) {
                        node.definitions.forEach(function (varDefNode) {
                            if (varDefNode.name.name === 'require' && varDefNode.value instanceof uglifyJs.AST_Object) {
                                requireJsConfig.foundConfig = true;
                                extractRequireJsConfig(varDefNode.value);
                            }
                        });
                    }
                }));
            }
        };

        assetGraph.on('addAsset', function (asset) {
            if (asset.type === 'JavaScript' && !requireJsConfig.foundConfig) {
                if (requireJsConfig.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound) {
                    asset.keepUnpopulated = true;
                }
                if (asset.isLoaded) {
                    requireJsConfig.registerConfigInJavaScript(asset);
                } else {
                    asset.on('load', function () {
                        requireJsConfig.registerConfigInJavaScript(asset);
                    });
                }
            }
        });
    };
};
<commit_msg>registerRequireJsConfig transform: Don't try to dive into non-object arguments to require and requirejs. Related to #157.<commit_after>var urlTools = require('urltools'),
    AssetGraph = require('../'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs,
    uglifyAst = AssetGraph.JavaScript.uglifyAst;

module.exports = function (options) {
    options = options || {};
    return function registerRequireJsConfig(assetGraph) {
        var requireJsConfig = (assetGraph.requireJsConfig = assetGraph.requireJsConfig || {});

        requireJsConfig.paths = requireJsConfig.paths || {};
        requireJsConfig.shim = {};
        requireJsConfig.foundConfig = false;
        requireJsConfig.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound = !!options.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound;

        requireJsConfig.findLongestPathsPrefix = function (moduleName) {
            var fragments = moduleName.split('/');

            for (var i = fragments.length ; i > 0 ; i -= 1) {
                var prefix = fragments.slice(0, i).join('/');
                if (prefix in this.paths) {
                    return prefix;
                }
            }
        };

        requireJsConfig.resolveModuleName = function (moduleName) {
            var longestPathsPrefix = this.findLongestPathsPrefix(moduleName);
            if (longestPathsPrefix) {
                if (longestPathsPrefix === moduleName) {
                    return this.paths[longestPathsPrefix];
                } else {
                    return urlTools.resolveUrl(this.paths[longestPathsPrefix].replace(/\/?$/, '/'), moduleName.replace(longestPathsPrefix + '/', ''));
                }
            } else {
                return moduleName;
            }
        };

        requireJsConfig.getModuleNames = function (asset, fallbackBaseUrl) {
            if (asset.isInline) {
                return null;
            }

            var baseUrl = (requireJsConfig.baseUrl && requireJsConfig.baseUrl) || fallbackBaseUrl,
                modulePrefixByPath = {},
                modulePaths = [];

            // TODO: Cache the below
            Object.keys(requireJsConfig.paths).forEach(function (modulePrefix) {
                var modulePath = requireJsConfig.paths[modulePrefix].replace(baseUrl, '').replace(/\/$/, '');
                modulePrefixByPath[modulePath] = modulePrefix;
                modulePaths.push(modulePath);
            });
            var modulePathsOrderedByLengthDesc = modulePaths.sort(function (a, b) {
                return b.length - a.length;
            });

            var canonicalModuleName = urlTools.buildRelativeUrl(baseUrl, asset.url).replace(/\.js$/, ''),
                moduleNames = [canonicalModuleName];
            for (var i = 0 ; i < modulePathsOrderedByLengthDesc.length ; i += 1) {
                var path = modulePathsOrderedByLengthDesc[i];
                if (canonicalModuleName.indexOf(path + '/') === 0) {
                    moduleNames.push(canonicalModuleName.replace(path, modulePrefixByPath[path]));
                }
            }
            return moduleNames;
        };

        requireJsConfig.getModuleName = function (asset, fallbackBaseUrl) {
            if (asset.isInline) {
                return null;
            }
            return requireJsConfig.getModuleNames(asset, fallbackBaseUrl)[0];
        };

        function registerShimArray(moduleName, arrayNode, javaScript) {
            requireJsConfig.shim[moduleName] = requireJsConfig.shim[moduleName] || {};
            var deps = (requireJsConfig.shim[moduleName].deps = requireJsConfig.shim[moduleName].deps || []);
            arrayNode.elements.forEach(function (elementNode) {
                if (elementNode instanceof uglifyJs.AST_String) {
                    if (deps.indexOf(elementNode.value) === -1) {
                        deps.push(elementNode.value);
                    }
                } else {
                    assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: [...]}}) syntax: ' + arrayNode.print_to_string()));
                }
            });
        }

        requireJsConfig.registerConfigInJavaScript = function (javaScript, htmlAsset) {
            if (!htmlAsset) {
                var incomingRelationsFromHtml = assetGraph.findRelations({to: javaScript, from: {type: 'Html'}});
                if (incomingRelationsFromHtml.length > 0) {
                    htmlAsset = incomingRelationsFromHtml[0].from.nonInlineAncestor; // Could be a conditional comment.
                }
            }
            if (htmlAsset) {
                var htmlUrl = htmlAsset.url,
                    extractRequireJsConfig = function (objAst) {
                        objAst.properties.forEach(function (keyValueNode) {
                            if (keyValueNode.key === 'baseUrl' && keyValueNode.value instanceof uglifyJs.AST_String) {
                                requireJsConfig.baseUrl = assetGraph.resolveUrl(htmlUrl.replace(/[^\/]+([\?#].*)?$/, ''),
                                                                                keyValueNode.value.value.replace(/\/?$/, '/'));
                            } else if (keyValueNode.key === 'paths' && keyValueNode.value instanceof uglifyJs.AST_Object) {
                                keyValueNode.value.properties.forEach(function (pathNode) {
                                    if (pathNode.value instanceof uglifyJs.AST_String) {
                                        requireJsConfig.paths[pathNode.key] = pathNode.value.value;
                                    } else {
                                        assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({path: ...}) syntax: ' + pathNode.print_to_string()));
                                    }
                                });
                            } else if (keyValueNode.key === 'shim' && keyValueNode.value instanceof uglifyJs.AST_Object) {
                                keyValueNode.value.properties.forEach(function (shimNode) {
                                    var moduleName = shimNode.key;
                                    if (shimNode.value instanceof uglifyJs.AST_Array) {
                                        registerShimArray(moduleName, shimNode.value, javaScript);
                                    } else if (shimNode.value instanceof uglifyJs.AST_Object) {
                                        shimNode.value.properties.forEach(function (shimKeyValueNode) {
                                            if (shimKeyValueNode.key === 'deps') {
                                                if (shimKeyValueNode.value instanceof uglifyJs.AST_Array) {
                                                    registerShimArray(moduleName, shimKeyValueNode.value, javaScript);
                                                } else {
                                                    assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: {deps: ...}}) syntax: ' + objAst.print_to_string()));
                                                }
                                            } else {
                                                requireJsConfig.shim[moduleName] = requireJsConfig.shim[moduleName] || {};
                                                requireJsConfig.shim[moduleName][shimKeyValueNode.key] = uglifyAst.astToObj(shimKeyValueNode.value);
                                            }
                                        });
                                    } else {
                                        assetGraph.emit('warn', new Error(javaScript.urlOrDescription + ': Unsupported require.config({shim: ...}) syntax: ' + shimNode.print_to_string()));
                                    }
                                });
                            }
                        });
                    };

                javaScript.parseTree.walk(new uglifyJs.TreeWalker(function (node) {
                    if (node instanceof uglifyJs.AST_SimpleStatement &&
                        node.body instanceof uglifyJs.AST_Call &&
                        node.body.expression instanceof uglifyJs.AST_Dot &&
                        node.body.expression.property === 'config' &&
                        node.body.expression.expression instanceof uglifyJs.AST_SymbolRef &&
                        node.body.args[0] instanceof uglifyJs.AST_Object &&
                        (node.body.expression.expression.name === 'require' || node.body.expression.expression.name === 'requirejs')) {

                        requireJsConfig.foundConfig = true;
                        extractRequireJsConfig(node.body.args[0]);
                    } else if (node instanceof uglifyJs.AST_Var) {
                        node.definitions.forEach(function (varDefNode) {
                            if (varDefNode.name.name === 'require' && varDefNode.value instanceof uglifyJs.AST_Object) {
                                requireJsConfig.foundConfig = true;
                                extractRequireJsConfig(varDefNode.value);
                            }
                        });
                    }
                }));
            }
        };

        assetGraph.on('addAsset', function (asset) {
            if (asset.type === 'JavaScript' && !requireJsConfig.foundConfig) {
                if (requireJsConfig.preventPopulationOfJavaScriptAssetsUntilConfigHasBeenFound) {
                    asset.keepUnpopulated = true;
                }
                if (asset.isLoaded) {
                    requireJsConfig.registerConfigInJavaScript(asset);
                } else {
                    asset.on('load', function () {
                        requireJsConfig.registerConfigInJavaScript(asset);
                    });
                }
            }
        });
    };
};
<|endoftext|>


<commit_before>const _ = require('underscore');
const layersFilter = require('../../utils/layer_filter');

const RendererParams = require('../renderer_params');

const Renderer = require('./renderer');
const BaseAdaptor = require('../base_adaptor');

/**
 * API: initializes the renderer, it should be called once
 *
 * @param {Object} options
 *      - dbPoolParams: database connection pool params
 *          - size: maximum number of resources to create at any given time
 *          - idleTimeout: max milliseconds a resource can go unused before it should be destroyed
 *          - reapInterval: frequency to check for idle resources
 */
function PgMvtFactory(options) {
    this.options = options || {};
}

module.exports = PgMvtFactory;
const NAME = 'pg-mvt';
const MVT_FORMAT = 'mvt';
module.exports.NAME = NAME;

PgMvtFactory.prototype = {
    /// API: renderer name, use for information purposes
    name: NAME,

    /// API: tile formats this module is able to render
    supported_formats: [MVT_FORMAT],

    getName: function () {
        return this.name;
    },

    supportsFormat: function (format) {
        return format === MVT_FORMAT;
    },

    getAdaptor: function (renderer, format, onTileErrorStrategy) {
        return new BaseAdaptor(renderer, format, onTileErrorStrategy);
    },

    getRenderer: function (mapConfig, format, options, callback) {
        if (mapConfig.isVectorOnlyMapConfig() && format !== MVT_FORMAT) {
            const error = new Error(`Unsupported format: 'cartocss' option is missing for ${format}`);
            error.http_status = 400;
            error.type = 'tile';
            return callback(error);
        }

        if (!this.supportsFormat(format)) {
            return callback(new Error("format not supported: " + format));
        }

        const mapLayers = mapConfig.getLayers();
        mapLayers.forEach((layer, layerIndex) => {
            layer.id = mapConfig.getLayerId(layerIndex);
        });

        const filteredLayers = layersFilter(mapConfig, options.layer);
        if (filteredLayers.length < 1) {
            return callback(new Error("no mapnik layer in mapConfig"));
        }

        const layers = filteredLayers.map(layerIndex => mapConfig.getLayer(layerIndex));
        let dbParams = RendererParams.dbParamsFromReqParams(options.params);
        _.extend(dbParams, mapConfig.getLayerDatasource(options.layer));

        if (Number.isFinite(mapConfig.getBufferSize(MVT_FORMAT))) {
            this.options.bufferSize = mapConfig.getBufferSize(MVT_FORMAT);
        }

        let map_extents = {};
        try {
            map_extents = mapConfig.getMVTExtents();
        } catch(err) {
            return callback(err);
        }

        this.options.vector_extent = map_extents.extent;
        this.options.vector_simplify_extent = map_extents.simplify_extent;

        const mvt_renderer = new Renderer(layers, this.options, dbParams);
        mvt_renderer.initDB((err, renderer) => {
            if (err) {
                return callback(err);
            }
            return callback(null, renderer);
        });
    }
};
<commit_msg>pg-mvt: Simplify renderer callback<commit_after>const _ = require('underscore');
const layersFilter = require('../../utils/layer_filter');

const RendererParams = require('../renderer_params');

const Renderer = require('./renderer');
const BaseAdaptor = require('../base_adaptor');

/**
 * API: initializes the renderer, it should be called once
 *
 * @param {Object} options
 *      - dbPoolParams: database connection pool params
 *          - size: maximum number of resources to create at any given time
 *          - idleTimeout: max milliseconds a resource can go unused before it should be destroyed
 *          - reapInterval: frequency to check for idle resources
 */
function PgMvtFactory(options) {
    this.options = options || {};
}

module.exports = PgMvtFactory;
const NAME = 'pg-mvt';
const MVT_FORMAT = 'mvt';
module.exports.NAME = NAME;

PgMvtFactory.prototype = {
    /// API: renderer name, use for information purposes
    name: NAME,

    /// API: tile formats this module is able to render
    supported_formats: [MVT_FORMAT],

    getName: function () {
        return this.name;
    },

    supportsFormat: function (format) {
        return format === MVT_FORMAT;
    },

    getAdaptor: function (renderer, format, onTileErrorStrategy) {
        return new BaseAdaptor(renderer, format, onTileErrorStrategy);
    },

    getRenderer: function (mapConfig, format, options, callback) {
        if (mapConfig.isVectorOnlyMapConfig() && format !== MVT_FORMAT) {
            const error = new Error(`Unsupported format: 'cartocss' option is missing for ${format}`);
            error.http_status = 400;
            error.type = 'tile';
            return callback(error);
        }

        if (!this.supportsFormat(format)) {
            return callback(new Error("format not supported: " + format));
        }

        const mapLayers = mapConfig.getLayers();
        mapLayers.forEach((layer, layerIndex) => {
            layer.id = mapConfig.getLayerId(layerIndex);
        });

        const filteredLayers = layersFilter(mapConfig, options.layer);
        if (filteredLayers.length < 1) {
            return callback(new Error("no mapnik layer in mapConfig"));
        }

        const layers = filteredLayers.map(layerIndex => mapConfig.getLayer(layerIndex));
        let dbParams = RendererParams.dbParamsFromReqParams(options.params);
        _.extend(dbParams, mapConfig.getLayerDatasource(options.layer));

        if (Number.isFinite(mapConfig.getBufferSize(MVT_FORMAT))) {
            this.options.bufferSize = mapConfig.getBufferSize(MVT_FORMAT);
        }

        let map_extents = {};
        try {
            map_extents = mapConfig.getMVTExtents();
        } catch(err) {
            return callback(err);
        }

        this.options.vector_extent = map_extents.extent;
        this.options.vector_simplify_extent = map_extents.simplify_extent;

        const mvt_renderer = new Renderer(layers, this.options, dbParams);
        mvt_renderer.initDB(callback);
    }
};
<|endoftext|>


<commit_before>const is = require('@sindresorhus/is');
const {
  getManagerConfig,
  mergeChildConfig,
  filterConfig,
} = require('../../../config');
const { applyPackageRules } = require('../../../util/package-rules');
const { get } = require('../../../manager');

module.exports = {
  flattenUpdates,
};

// Return only rules that contain an updateType
function getUpdateTypeRules(packageRules) {
  return packageRules.filter(rule => is.nonEmptyArray(rule.updateTypes));
}

function flattenUpdates(config, packageFiles) {
  const updates = [];
  const updateTypes = [
    'major',
    'minor',
    'patch',
    'pin',
    'digest',
    'lockFileMaintenance',
  ];
  for (const [manager, files] of Object.entries(packageFiles)) {
    const managerConfig = getManagerConfig(config, manager);
    for (const packageFile of files) {
      const packageFileConfig = mergeChildConfig(managerConfig, packageFile);
      for (const dep of packageFile.deps) {
        if (dep.updates.length) {
          const depConfig = mergeChildConfig(packageFileConfig, dep);
          delete depConfig.deps;
          for (const update of dep.updates) {
            let updateConfig = mergeChildConfig(depConfig, update);
            delete updateConfig.updates;
            updateConfig = applyPackageRules(updateConfig);
            // Keep only rules that haven't been applied yet (with updateTypes)
            updateConfig.packageRules = getUpdateTypeRules(
              updateConfig.packageRules
            );
            // apply major/minor/patch/pin/digest
            updateConfig = mergeChildConfig(
              updateConfig,
              updateConfig[updateConfig.updateType]
            );
            for (const updateType of updateTypes) {
              delete updateConfig[updateType];
            }
            // Apply again in case any were added by the updateType config
            updateConfig = applyPackageRules(updateConfig);
            delete updateConfig.packageRules;
            updateConfig.depNameSanitized = updateConfig.depName
              ? updateConfig.depName
                  .replace('@types/', '')
                  .replace('@', '')
                  .replace('/', '-')
                  .replace(/\s+/g, '-')
                  .toLowerCase()
              : undefined;
            if (
              updateConfig.language === 'docker' &&
              updateConfig.depName.match(/(^|\/)node$/) &&
              updateConfig.depName !== 'calico/node'
            ) {
              updateConfig.managerBranchPrefix = '';
              updateConfig.depNameSanitized = 'node';
            }
            delete updateConfig.repoIsOnboarded;
            delete updateConfig.renovateJsonPresent;
            updates.push(updateConfig);
          }
        }
      }
      if (
        get(manager, 'supportsLockFileMaintenance') &&
        packageFileConfig.lockFileMaintenance.enabled
      ) {
        // Apply lockFileMaintenance config before packageRules
        let lockFileConfig = mergeChildConfig(
          packageFileConfig,
          packageFileConfig.lockFileMaintenance
        );
        lockFileConfig.updateType = 'lockFileMaintenance';
        lockFileConfig = applyPackageRules(lockFileConfig);
        // Apply lockFileMaintenance and packageRules again
        lockFileConfig = mergeChildConfig(
          lockFileConfig,
          lockFileConfig.lockFileMaintenance
        );
        lockFileConfig = applyPackageRules(lockFileConfig);
        // Remove unnecessary objects
        for (const updateType of updateTypes) {
          delete lockFileConfig[updateType];
        }
        delete lockFileConfig.packageRules;
        delete lockFileConfig.deps;
        updates.push(lockFileConfig);
      }
    }
  }
  return updates
    .filter(update => update.enabled)
    .map(update => filterConfig(update, 'branch'));
}
<commit_msg>fix(branchName): replace all forward slashes<commit_after>const is = require('@sindresorhus/is');
const {
  getManagerConfig,
  mergeChildConfig,
  filterConfig,
} = require('../../../config');
const { applyPackageRules } = require('../../../util/package-rules');
const { get } = require('../../../manager');

module.exports = {
  flattenUpdates,
};

// Return only rules that contain an updateType
function getUpdateTypeRules(packageRules) {
  return packageRules.filter(rule => is.nonEmptyArray(rule.updateTypes));
}

function flattenUpdates(config, packageFiles) {
  const updates = [];
  const updateTypes = [
    'major',
    'minor',
    'patch',
    'pin',
    'digest',
    'lockFileMaintenance',
  ];
  for (const [manager, files] of Object.entries(packageFiles)) {
    const managerConfig = getManagerConfig(config, manager);
    for (const packageFile of files) {
      const packageFileConfig = mergeChildConfig(managerConfig, packageFile);
      for (const dep of packageFile.deps) {
        if (dep.updates.length) {
          const depConfig = mergeChildConfig(packageFileConfig, dep);
          delete depConfig.deps;
          for (const update of dep.updates) {
            let updateConfig = mergeChildConfig(depConfig, update);
            delete updateConfig.updates;
            updateConfig = applyPackageRules(updateConfig);
            // Keep only rules that haven't been applied yet (with updateTypes)
            updateConfig.packageRules = getUpdateTypeRules(
              updateConfig.packageRules
            );
            // apply major/minor/patch/pin/digest
            updateConfig = mergeChildConfig(
              updateConfig,
              updateConfig[updateConfig.updateType]
            );
            for (const updateType of updateTypes) {
              delete updateConfig[updateType];
            }
            // Apply again in case any were added by the updateType config
            updateConfig = applyPackageRules(updateConfig);
            delete updateConfig.packageRules;
            updateConfig.depNameSanitized = updateConfig.depName
              ? updateConfig.depName
                  .replace('@types/', '')
                  .replace('@', '')
                  .replace(/\//g, '-')
                  .replace(/\s+/g, '-')
                  .toLowerCase()
              : undefined;
            if (
              updateConfig.language === 'docker' &&
              updateConfig.depName.match(/(^|\/)node$/) &&
              updateConfig.depName !== 'calico/node'
            ) {
              updateConfig.managerBranchPrefix = '';
              updateConfig.depNameSanitized = 'node';
            }
            delete updateConfig.repoIsOnboarded;
            delete updateConfig.renovateJsonPresent;
            updates.push(updateConfig);
          }
        }
      }
      if (
        get(manager, 'supportsLockFileMaintenance') &&
        packageFileConfig.lockFileMaintenance.enabled
      ) {
        // Apply lockFileMaintenance config before packageRules
        let lockFileConfig = mergeChildConfig(
          packageFileConfig,
          packageFileConfig.lockFileMaintenance
        );
        lockFileConfig.updateType = 'lockFileMaintenance';
        lockFileConfig = applyPackageRules(lockFileConfig);
        // Apply lockFileMaintenance and packageRules again
        lockFileConfig = mergeChildConfig(
          lockFileConfig,
          lockFileConfig.lockFileMaintenance
        );
        lockFileConfig = applyPackageRules(lockFileConfig);
        // Remove unnecessary objects
        for (const updateType of updateTypes) {
          delete lockFileConfig[updateType];
        }
        delete lockFileConfig.packageRules;
        delete lockFileConfig.deps;
        updates.push(lockFileConfig);
      }
    }
  }
  return updates
    .filter(update => update.enabled)
    .map(update => filterConfig(update, 'branch'));
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /**
     * A component to render the pop up search field
     */
    var umbSearch = {
        templateUrl: 'views/components/application/umb-search.html',
        controllerAs: 'vm',
        controller: umbSearchController,
        bindings: {
            onClose: "&"
        }
    };

    function umbSearchController($scope, backdropService, searchService) {

        var vm = this;

        vm.$onInit = onInit;
        vm.search = search;
        vm.closeSearch = closeSearch;

        function onInit() {

            vm.searchResults = [];
            vm.hasResults = false;

            console.log("init search thingy");
            backdropService.open();
        }

        /**
         * Used to proxy a callback
         */
        function closeSearch() {
            if(vm.onClose) {
                vm.onClose();
            }
        }

        /**
         * Used to search
         * @param {string} searchQuery
         */
        function search(searchQuery) {
            console.log(searchQuery);
            if(searchQuery.length > 0) {
                var search = {"term": searchQuery};
                searchService.searchAll(search).then(function(result){

                    //result is a dictionary of group Title and it's results
                    var filtered = {};
                    _.each(result, function (value, key) {
                        if (value.results.length > 0) {
                            filtered[key] = value;
                        }
                    });

                    vm.searchResults = filtered;
                    // check if search has results
                    vm.hasResults = Object.keys(vm.searchResults).length > 0;
                    console.log("results", vm.searchResults);
                    console.log("has results", vm.hasResults);
                });

            } else {
                vm.searchResults = [];
                vm.hasResults = false;
            }
        }

    }

    angular.module('umbraco.directives').component('umbSearch', umbSearch);

})();<commit_msg>make sure the close the overlay when the component gets destroyed.<commit_after>(function () {
    'use strict';

    /**
     * A component to render the pop up search field
     */
    var umbSearch = {
        templateUrl: 'views/components/application/umb-search.html',
        controllerAs: 'vm',
        controller: umbSearchController,
        bindings: {
            onClose: "&"
        }
    };

    function umbSearchController($scope, backdropService, searchService) {

        var vm = this;

        vm.$onInit = onInit;
        vm.$onDestroy = onDestroy;
        vm.search = search;
        vm.closeSearch = closeSearch;

        function onInit() {

            vm.searchResults = [];
            vm.hasResults = false;

            console.log("init search thingy");
            backdropService.open();
        }

        function onDestroy() {
            backdropService.close();
        }

        /**
         * Used to proxy a callback
         */
        function closeSearch() {
            if(vm.onClose) {
                vm.onClose();
            }
        }

        /**
         * Used to search
         * @param {string} searchQuery
         */
        function search(searchQuery) {
            console.log(searchQuery);
            if(searchQuery.length > 0) {
                var search = {"term": searchQuery};
                searchService.searchAll(search).then(function(result){

                    //result is a dictionary of group Title and it's results
                    var filtered = {};
                    _.each(result, function (value, key) {
                        if (value.results.length > 0) {
                            filtered[key] = value;
                        }
                    });

                    vm.searchResults = filtered;
                    // check if search has results
                    vm.hasResults = Object.keys(vm.searchResults).length > 0;
                    console.log("results", vm.searchResults);
                    console.log("has results", vm.hasResults);
                });

            } else {
                vm.searchResults = [];
                vm.hasResults = false;
            }
        }

    }

    angular.module('umbraco.directives').component('umbSearch', umbSearch);

})();<|endoftext|>


<commit_before>import Vue from 'vue';
import { shallowMount } from '@vue/test-utils';
import DappsContainer from '@/layouts/InterfaceLayout/containers/DappsContainer/DappsContainer.vue';
import DappButtons from '@/layouts/InterfaceLayout/components/DappButtons/DappButtons.vue';
import languages from '@/translations';
import { Tooling } from '@@/helpers';

const RouterLinkStub = {
  name: 'router-link',
  template:
    '
<slot> </slot>
{{to}}

',
  props: ['to']
};

function translate(lang) {
  const arrLang = lang.split('.');
  let langObj = languages.en_US;
  for (let i = 0; i < arrLang.length; i++) {
    langObj = langObj[arrLang[i]];
  }
  return langObj;
}

describe('DappsContainer.vue', () => {
  let localVue, i18n, wrapper, store;
  const address = 'DappsContainer address';
  beforeAll(() => {
    const baseSetup = Tooling.createLocalVueInstance();
    localVue = baseSetup.localVue;
    i18n = baseSetup.i18n;
    store = baseSetup.store;

    Vue.config.warnHandler = () => {};
  });

  beforeEach(() => {
    wrapper = shallowMount(DappsContainer, {
      localVue,
      i18n,
      store,
      attachToDocument: true,
      propsData: {
        address: address
      },
      stubs: {
        'dapp-buttons': DappButtons,
        'router-link': RouterLinkStub
      }
    });
  });

  it('should render correct registerDomain title', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[0].querySelector('h4').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.registerDomain.title)
    );
  });

  it('should render correct registerDomain description', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[0].querySelector('p').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.registerDomain.desc)
    );
  });

  it('should render correct domainSale title', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[1].querySelector('h4').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.domainSale.title)
    );
  });

  it('should render correct domainSale description', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[1].querySelector('p').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.domainSale.desc)
    );
  });

  it('should render correct registerDomain route', () => {
    expect(
      wrapper.vm.$el.querySelectorAll('.param')[0].textContent.trim()
    ).toEqual(wrapper.vm.$data.localDapps.registerDomain.route);
  });

  it('should render correct domainSale route', () => {
    expect(
      wrapper.vm.$el.querySelectorAll('.param')[1].textContent.trim()
    ).toEqual(wrapper.vm.$data.localDapps.domainSale.route);
  });
});
<commit_msg>fixes tests<commit_after>import Vue from 'vue';
import { shallowMount } from '@vue/test-utils';
import DappsContainer from '@/layouts/InterfaceLayout/containers/DappsContainer/DappsContainer.vue';
import DappButtons from '@/layouts/InterfaceLayout/components/DappButtons/DappButtons.vue';
import languages from '@/translations';
import { Tooling } from '@@/helpers';

const RouterLinkStub = {
  name: 'router-link',
  template:
    '
<slot> </slot>
{{to}}

',
  props: ['to']
};

function translate(lang) {
  const arrLang = lang.split('.');
  let langObj = languages.en_US;
  for (let i = 0; i < arrLang.length; i++) {
    langObj = langObj[arrLang[i]];
  }
  return langObj;
}

describe('DappsContainer.vue', () => {
  let localVue, i18n, wrapper, store;
  const address = 'DappsContainer address';
  beforeAll(() => {
    const baseSetup = Tooling.createLocalVueInstance();
    localVue = baseSetup.localVue;
    i18n = baseSetup.i18n;
    store = baseSetup.store;

    Vue.config.warnHandler = () => {};
  });

  beforeEach(() => {
    wrapper = shallowMount(DappsContainer, {
      localVue,
      i18n,
      store,
      attachToDocument: true,
      propsData: {
        address: address
      },
      stubs: {
        'dapp-buttons': DappButtons,
        'router-link': RouterLinkStub
      }
    });
  });

  it('should render correct registerDomain title', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[1].querySelector('h4').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.registerDomain.title)
    );
  });

  it('should render correct registerDomain description', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[1].querySelector('p').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.registerDomain.desc)
    );
  });

  it('should render correct domainSale title', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[2].querySelector('h4').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.domainSale.title)
    );
  });

  it('should render correct domainSale description', () => {
    const dappsButtons = wrapper.vm.$el.querySelectorAll('.dapps-button');
    expect(dappsButtons[2].querySelector('p').textContent.trim()).toEqual(
      translate(wrapper.vm.$data.localDapps.domainSale.desc)
    );
  });

  it('should render correct registerDomain route', () => {
    expect(
      wrapper.vm.$el.querySelectorAll('.param')[1].textContent.trim()
    ).toEqual(wrapper.vm.$data.localDapps.registerDomain.route);
  });

  it('should render correct domainSale route', () => {
    expect(
      wrapper.vm.$el.querySelectorAll('.param')[2].textContent.trim()
    ).toEqual(wrapper.vm.$data.localDapps.domainSale.route);
  });
});
<|endoftext|>


<commit_before>require.paths.unshift(__dirname + '/../lib/node', __dirname + '/../');
var assert = require('assert');
var fs = require('fs');
var _ = require('underscore')._;

var app = require('tilemill');
var inspect = require('inspect');

var project = '';
var project2 = '';
module.exports = {
    'abilities': function() {
        assert.response(app, { url: '/abilities' }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.ok(data.fonts, 'Available fonts');
            assert.ok(data.datasources, 'Available datasources');
        });
    },
    'version': function() {
        assert.response(app, {
            url: '/api',
        }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.api, 'basic', 'API');
            assert.equal(data.version, 1, 'API Version');
        });
    },
    'project manipulation': function() {
        fs.readFile('./test/fixtures/project1.json', 'utf8', function(err, project) {
            // Create project
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: project
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
            });
            // Get all projects
            assert.response(app, {
                url: '/api/Project',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body).pop(), JSON.parse(project));
            });
            // Get project
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
            });
            // Validation: Name must contain specified characters.
            var invalid = _.extend(JSON.parse(project), { id: 'Bad !@!ID' });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'Name must contain only letters, numbers, dashes, and underscores.');
            });
            // Validation: No stylesheets found.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: []
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'No stylesheets found.');
            });
            // Validation: Stylesheet IDs must be unique.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: [
                    { id: 'foo', data: '' },
                    { id: 'foo', data: '' }
                ]
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'Stylesheet IDs must be unique.');
            });
            // Validation: Stylesheet syntax validation.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: [
                    { id: 'style.mss', data: '#world {  polygon-fill: eee; }' },
                ]
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(JSON.parse(res.body)[0].message, 'Invalid value for polygon-fill, a color is expected');
            });
            fs.readFile('./test/fixtures/project2.json', 'utf8', function(err, project) {
                // Update project
                assert.response(app, {
                    url: '/api/Project/Test',
                    method: 'PUT',
                    headers: {
                        'content-type': 'application/json'
                    },
                    data: project
                }, {
                    status: 200
                }, function(res) {
                    assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
                });
                // Load layer
                assert.response(app, {url: '/aHR0cDovL2xvY2FsaG9zdDo4ODg5L2FwaS9Qcm9qZWN0L1Rlc3Q_MmE5ZWFj/world'}, {
                    status: 200
                }, function(res) {
                    var data = JSON.parse(res.body);
                    assert.equal(data.id, 'world', 'Unexpected layer id');
                    assert.equal(data.features.length, 245, 'Feature count mismatch');
                });
                // Delete project
                assert.response(app, {
                    url: '/api/Project/Test',
                    method: 'DELETE'
                }, {
                    status: 200
                }, function(res) {
                    assert.equal(res.body, '{}');
                });
            });
        });
    },
    'invalid map': function() {
        assert.response(app, { url: '/foobar' }, {
            status: 500
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.message, 'Error loading map file', 'Unexpected error message');
        });
    }
};

var loadFixture = function(file, callback) {
    require('fs').readfile('./test/fixtures/' + file, callback);
}
<commit_msg>Use POST for creating a project.<commit_after>require.paths.unshift(__dirname + '/../lib/node', __dirname + '/../');
var assert = require('assert');
var fs = require('fs');
var _ = require('underscore')._;

var app = require('tilemill');
var inspect = require('inspect');

var project = '';
var project2 = '';
module.exports = {
    'abilities': function() {
        assert.response(app, { url: '/abilities' }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.ok(data.fonts, 'Available fonts');
            assert.ok(data.datasources, 'Available datasources');
        });
    },
    'version': function() {
        assert.response(app, {
            url: '/api',
        }, {
            status: 200
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.api, 'basic', 'API');
            assert.equal(data.version, 1, 'API Version');
        });
    },
    'project manipulation': function() {
        fs.readFile('./test/fixtures/project1.json', 'utf8', function(err, project) {
            // Create project
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'POST',
                headers: {
                    'content-type': 'application/json'
                },
                data: project
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
            });
            // Get all projects
            assert.response(app, {
                url: '/api/Project',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body).pop(), JSON.parse(project));
            });
            // Get project
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'GET',
            }, {
                status: 200
            }, function(res) {
                assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
            });
            // Validation: Name must contain specified characters.
            var invalid = _.extend(JSON.parse(project), { id: 'Bad !@!ID' });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'Name must contain only letters, numbers, dashes, and underscores.');
            });
            // Validation: No stylesheets found.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: []
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'No stylesheets found.');
            });
            // Validation: Stylesheet IDs must be unique.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: [
                    { id: 'foo', data: '' },
                    { id: 'foo', data: '' }
                ]
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(res.body, 'Stylesheet IDs must be unique.');
            });
            // Validation: Stylesheet syntax validation.
            var invalid = _.extend(JSON.parse(project), {
                Stylesheet: [
                    { id: 'style.mss', data: '#world {  polygon-fill: eee; }' },
                ]
            });
            assert.response(app, {
                url: '/api/Project/Test',
                method: 'PUT',
                headers: {
                    'content-type': 'application/json'
                },
                data: JSON.stringify(invalid)
            }, {
                status: 500
            }, function(res) {
                assert.equal(JSON.parse(res.body)[0].message, 'Invalid value for polygon-fill, a color is expected');
            });
            fs.readFile('./test/fixtures/project2.json', 'utf8', function(err, project) {
                // Update project
                assert.response(app, {
                    url: '/api/Project/Test',
                    method: 'PUT',
                    headers: {
                        'content-type': 'application/json'
                    },
                    data: project
                }, {
                    status: 200
                }, function(res) {
                    assert.deepEqual(JSON.parse(res.body), JSON.parse(project));
                });
                // Load layer
                assert.response(app, {url: '/aHR0cDovL2xvY2FsaG9zdDo4ODg5L2FwaS9Qcm9qZWN0L1Rlc3Q_MmE5ZWFj/world'}, {
                    status: 200
                }, function(res) {
                    var data = JSON.parse(res.body);
                    assert.equal(data.id, 'world', 'Unexpected layer id');
                    assert.equal(data.features.length, 245, 'Feature count mismatch');
                });
                // Delete project
                assert.response(app, {
                    url: '/api/Project/Test',
                    method: 'DELETE'
                }, {
                    status: 200
                }, function(res) {
                    assert.equal(res.body, '{}');
                });
            });
        });
    },
    'invalid map': function() {
        assert.response(app, { url: '/foobar' }, {
            status: 500
        }, function(res) {
            var data = JSON.parse(res.body);
            assert.equal(data.message, 'Error loading map file', 'Unexpected error message');
        });
    }
};

var loadFixture = function(file, callback) {
    require('fs').readfile('./test/fixtures/' + file, callback);
}
<|endoftext|>