<commit_before>'use strict';

var Firebase = require("firebase");
var secrets = require("./secrets");

var userListRef = new Firebase(secrets.firebaseUrl + '/userList');
var usersRef = new Firebase(secrets.firebaseUrl + '/users');
var conversationsRef = new Firebase(secrets.firebaseUrl + '/conversations');
var messagesRef = new Firebase(secrets.firebaseUrl + '/messages');

var CONVERSATIONS_SENT_PER_TIME = 10;
var MESSAGES_SENT_PER_TIME = 20;

var getConversations = function(username, latestTime, callbacks) {
  var user = usersRef.child(username);
  user.orderByChild('time').endAt(latestTime).limitToLast(
    CONVERSATIONS_SENT_PER_TIME).on('child_added',
    function(snapshot) {
      console.log('got con key from db');
      console.log(snapshot.val());
      if (snapshot.val() != null) {
        conversationsRef.child(snapshot.val().conKey).once('value',
          function(conSnapshot) {
            console.log('got conversation from db');
            console.log(conSnapshot.val());
            callbacks.conversation(conSnapshot.val());
        });
        var messageRequest = {conversationId: snapshot.val().conKey,
                              latestTime: latestTime
                             };
        getMessages(messageRequest, callbacks.message);
      }
    }
  );
};

var getMessages = function(request, callback) {
  var messages = messagesRef.child(request.conversationId);
  messages.orderByChild('time').endAt(request.latestTime).limitToLast(
    MESSAGES_SENT_PER_TIME).on('child_added',
    function(snapshot) {
      console.log('got message from db');
      console.log(snapshot.val());
      if (snapshot.val() != null) {
        var message = {conversationId: request.conversationId,
                       message: snapshot.val()
                      };
        callback(message);
      }
    }
  );
};

var addUser = function(username) {
  userListRef.push({
    username: username
  });
}

var getUserListSetup = function(callback) {
  // Attach an asynchronous callback to read the data at our posts reference
  userListRef.on("value", function(snapshot) {
    console.log(snapshot.val());
    var userObject = snapshot.val();
    var userList = []
    for (var key in userObject) {
      console.log(userObject[key].username);
      userList.push(userObject[key].username);
    }
    console.log(userList);
    callback(userList);
  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
  });
}

var storeConversation = function(conversation, messages) {
  var sender = conversation.origSender;
  var recipient = conversation.origRecipient;

  var conRef = conversationsRef.push(conversation);
  var conRefInUser = {'conKey' : conRef.key(), 'time' : messages.time};

  usersRef.child(sender).child(recipient).update(conRefInUser);
  usersRef.child(recipient).child(sender).update(conRefInUser);

  messagesRef.child(conRef.key()).push(messages);
  console.log('conversation stored');
};

var storeMessage = function(message, conversationId) {
  //what if conversation not created yet?
  console.log(conversationId);

  var conRef = conversationsRef.child(conversationId);

  var time = {'time': message.time};
  conRef.update(time);

  messagesRef.child(conversationId).push(message);

  conRef.child('origSender').once('value', function (sender) {
    conRef.child('origRecipient').once('value', function(recipient) {
      sender = sender.val();
      recipient = recipient.val();
      usersRef.child(sender).child(recipient).update(time);
      usersRef.child(recipient).child(sender).update(time);
      var recipientUnread;
      if (sender == message.sender) {
        recipientUnread = 'origRecipientUnread';
      } else {
        recipientUnread = 'origSenderUnread';
      }
      conRef.child(recipientUnread).transaction(function(currValue) {
        return (currValue || 0) + 1;
      }, function() {}, false);
    });
  });
};

module.exports = {
  getConversations: getConversations,
  getMessages: getMessages,
  addUser: addUser,
  getUserListSetup: getUserListSetup,
  storeConversation: storeConversation,
  storeMessage: storeMessage
};
<commit_msg>now including conversation id with when sending conversations from server to client<commit_after>'use strict';

var Firebase = require("firebase");
var secrets = require("./secrets");

var userListRef = new Firebase(secrets.firebaseUrl + '/userList');
var usersRef = new Firebase(secrets.firebaseUrl + '/users');
var conversationsRef = new Firebase(secrets.firebaseUrl + '/conversations');
var messagesRef = new Firebase(secrets.firebaseUrl + '/messages');

var CONVERSATIONS_SENT_PER_TIME = 10;
var MESSAGES_SENT_PER_TIME = 20;

var getConversations = function(username, latestTime, callbacks) {
  var user = usersRef.child(username);
  user.orderByChild('time').endAt(latestTime).limitToLast(
    CONVERSATIONS_SENT_PER_TIME).on('child_added',
    function(snapshot) {
      console.log('got con key from db');
      console.log(snapshot.val());
      if (snapshot.val() != null) {
        conversationsRef.child(snapshot.val().conKey).once('value',
          function(conSnapshot) {
            console.log('got conversation from db');
            console.log(conSnapshot.val());
            var conversation = conSnapshot.val();
            conversation.id = snapshot.val().conKey;
            callbacks.conversation(conversation);
        });
        var messageRequest = {conversationId: snapshot.val().conKey,
                              latestTime: latestTime
                             };
        getMessages(messageRequest, callbacks.message);
      }
    }
  );
};

var getMessages = function(request, callback) {
  var messages = messagesRef.child(request.conversationId);
  messages.orderByChild('time').endAt(request.latestTime).limitToLast(
    MESSAGES_SENT_PER_TIME).on('child_added',
    function(snapshot) {
      console.log('got message from db');
      console.log(snapshot.val());
      if (snapshot.val() != null) {
        var message = {conversationId: request.conversationId,
                       message: snapshot.val()
                      };
        callback(message);
      }
    }
  );
};

var addUser = function(username) {
  userListRef.push({
    username: username
  });
}

var getUserListSetup = function(callback) {
  // Attach an asynchronous callback to read the data at our posts reference
  userListRef.on("value", function(snapshot) {
    console.log(snapshot.val());
    var userObject = snapshot.val();
    var userList = []
    for (var key in userObject) {
      console.log(userObject[key].username);
      userList.push(userObject[key].username);
    }
    console.log(userList);
    callback(userList);
  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
  });
}

var storeConversation = function(conversation, messages) {
  var sender = conversation.origSender;
  var recipient = conversation.origRecipient;

  var conRef = conversationsRef.push(conversation);
  var conRefInUser = {'conKey' : conRef.key(), 'time' : messages.time};

  usersRef.child(sender).child(recipient).update(conRefInUser);
  usersRef.child(recipient).child(sender).update(conRefInUser);

  messagesRef.child(conRef.key()).push(messages);
  console.log('conversation stored');
};

var storeMessage = function(message, conversationId) {
  //what if conversation not created yet?
  console.log(conversationId);

  var conRef = conversationsRef.child(conversationId);
  var time = {'time': message.time};
  conRef.update(time);

  messagesRef.child(conversationId).push(message);

  conRef.child('origSender').once('value', function (sender) {
    conRef.child('origRecipient').once('value', function(recipient) {
      sender = sender.val();
      recipient = recipient.val();
      usersRef.child(sender).child(recipient).update(time);
      usersRef.child(recipient).child(sender).update(time);
      var recipientUnread;
      if (sender == message.sender) {
        recipientUnread = 'origRecipientUnread';
      } else {
        recipientUnread = 'origSenderUnread';
      }
      conRef.child(recipientUnread).transaction(function(currValue) {
        return (currValue || 0) + 1;
      }, function() {}, false);
    });
  });
};

module.exports = {
  getConversations: getConversations,
  getMessages: getMessages,
  addUser: addUser,
  getUserListSetup: getUserListSetup,
  storeConversation: storeConversation,
  storeMessage: storeMessage
};
<|endoftext|>


<commit_before>define(['crud', 'ajax', 'dialog'], function (crud, ajax, dialog) {

    function indexationDialog(repositoryId) {
        ajax.get({
            url: 'ui/extension/svn/indexation/{0}'.format(repositoryId),
            successFn: function (lastRevisionInfo) {
                dialog.show({
                    title: 'subversion.indexation'.loc(),
                    templateId: 'extension/subversion-indexation-dialog',
                    data: {
                        lastRevisionInfo: lastRevisionInfo
                    },
                    buttons: [{
                        text: 'general.cancel'.loc(),
                        action: 'cancel'
                    }]
                })
            }
        })
    }

    return crud.create({
        url: 'ui/extension/svn/configuration',
        itemName: 'subversion.configuration'.loc(),
        itemTemplateId: 'extension/subversion-repository-row',
        itemNewFn: function () {
            return {
                branchPattern: '.*/branches/.*',
                tagPattern: '.*/tags/.*',
                indexationInterval: 0,
                indexationStart: 1
            }
        },
        itemDialogTemplateId: 'extension/subversion-repository-dialog',
        itemDialogWidth: 800,
        itemDialogFieldPrefix: 'subversion-repository-',
        itemFields: [ 'name', 'url', 'user', 'password', 'branchPattern', 'tagPattern', 'tagFilterPattern', 'browserForPath', 'browserForRevision', 'browserForChange', 'indexationInterval', 'indexationStart' ],
        commands: [ crud.createCommand('subversion.configuration.create'.loc()) ],
        itemCommands: [
            crud.updateItemCommand(),
            crud.deleteItemCommand(),
            {
                iconCls: 'icon-time',
                title: 'subversion.indexation'.loc(),
                action: function (btn, dynamicConfig, cfg, itemId) {
                    // Indexation dialog
                    indexationDialog(itemId)
                }
            }
        ],
        itemDeletePromptKey: 'subversion.configuration.delete.prompt'
    })

});<commit_msg>#306 Indexation dialog - wip - call to the full reindexation<commit_after>define(['crud', 'ajax', 'dialog', 'common'], function (crud, ajax, dialog, common) {

    function indexationDialog(repositoryId) {
        ajax.get({
            url: 'ui/extension/svn/indexation/{0}'.format(repositoryId),
            successFn: function (lastRevisionInfo) {
                dialog.show({
                    title: 'subversion.indexation'.loc(),
                    templateId: 'extension/subversion-indexation-dialog',
                    data: {
                        lastRevisionInfo: lastRevisionInfo
                    },
                    buttons: [
                        {
                            text: 'general.cancel'.loc(),
                            action: 'cancel'
                        }
                    ],
                    initFn: function (dialog) {
                        // TODO Indexation from latest
                        // TODO Range indexation
                        // Full indexation
                        dialog.form.find('#subversion-indexation-dialog-full-submit').click(function () {
                            common.confirmAndCall(
                                'subversion.indexation.full.confirmation'.loc(),
                                function () {
                                    ajax.post({
                                        url: 'ui/extension/svn/indexation/{0}/full'.format(repositoryId),
                                        successFn: dialog.closeFn,
                                        errorFn: ajax.simpleAjaxErrorFn(dialog.errorFn)
                                    })
                                }
                            )
                        })
                    }
                })
            }
        })
    }

    return crud.create({
        url: 'ui/extension/svn/configuration',
        itemName: 'subversion.configuration'.loc(),
        itemTemplateId: 'extension/subversion-repository-row',
        itemNewFn: function () {
            return {
                branchPattern: '.*/branches/.*',
                tagPattern: '.*/tags/.*',
                indexationInterval: 0,
                indexationStart: 1
            }
        },
        itemDialogTemplateId: 'extension/subversion-repository-dialog',
        itemDialogWidth: 800,
        itemDialogFieldPrefix: 'subversion-repository-',
        itemFields: [ 'name', 'url', 'user', 'password', 'branchPattern', 'tagPattern', 'tagFilterPattern', 'browserForPath', 'browserForRevision', 'browserForChange', 'indexationInterval', 'indexationStart' ],
        commands: [ crud.createCommand('subversion.configuration.create'.loc()) ],
        itemCommands: [
            crud.updateItemCommand(),
            crud.deleteItemCommand(),
            {
                iconCls: 'icon-time',
                title: 'subversion.indexation'.loc(),
                action: function (btn, dynamicConfig, cfg, itemId) {
                    // Indexation dialog
                    indexationDialog(itemId)
                }
            }
        ],
        itemDeletePromptKey: 'subversion.configuration.delete.prompt'
    })

});<|endoftext|>


<commit_before>var moment = require('moment'),
    slug = require('slug'),
    fs = require('fs'),
    path = require('path'),
    mkdirp = require('mkdirp'),
    crypto = require('crypto'),
    mongoose = require('mongoose'),
    ObjectId = mongoose.Types.ObjectId,
    mmm = require('mmmagic'),
    Magic = mmm.Magic,
    config = require('../settings'),
    File = require('../models/files').File;

module.exports.h2b64 = function(hex){
    return new Buffer(hex, 'hex').toString('base64').replace('+', '-').replace('/', '_');
};

module.exports.b642h = function(b64){
    return new Buffer(b64.replace('-','+').replace('_','/'), 'base64').toString('hex');
};

module.exports.slug = function (text) {
    return slug(text.toLowerCase());
};
module.exports.isodate = function(date) {
    if (date) {
        return moment(date).format();
    }
};

module.exports.shortdate = function (date) {
    if (date) {
        return moment(date).format('ll');
    } else {
        return date;
    }
};

module.exports.longdate = function (date) {
    if (date) {
        return moment(date).format('LLL');
    }
};

module.exports.ago = function (date) {
    if (date) {
        return moment(date).fromNow();
    }
};

module.exports.set_permissions = function (permissions) {
    var permissions_obj = { 'public': false, groups: [], users: []};
    if (permissions) {
        if (Array.isArray(permissions)) {
            _.each(permissions, function (perm) {
                if (perm === "p") {
                    permissions_obj.public = true;
                } else {
                    var type_id = perm.split("-"),
                        type = type_id[0],
                        object_id = type_id[1];

                    if (type === "g") {
                        permissions_obj.groups.push(object_id);
                    } else if (type === "u") {
                        permissions_obj.users.push(object_id);
                    }
                }
            });
        } else {
            var perm = permissions;
            if (perm === "p") {
                permissions_obj.public = true;
            } else {
                var type_id = perm.split("-"),
                    type = type_id[0],
                    object_id = type_id[1];

                if (type === "g") {
                    permissions_obj.groups.push(object_id);
                } else if (type === "u") {
                    permissions_obj.users.push(object_id);
                }
            }
        }
    }
    return permissions_obj;
};

module.exports.upload_file = function (tmp_path, filename, prefix, user, permissions, tags, callback) {
    fs.readFile(tmp_path, function (err, data) {
        var shasum, hex, new_dir, new_symlink, new_file, lookup_path;

        var magic = new Magic(mmm.MAGIC_MIME_TYPE);

        magic.detectFile(tmp_path, function(err, mimetype) {
            if (err) throw err;

            shasum = crypto.createHash('sha1');
            shasum.update('blob ' + data.length +'%s\0');
            shasum.update(data);
            hex = shasum.digest('hex');

            new_dir = path.join(prefix, hex.substr(0,2), hex.substr(2,2), hex);
            if (prefix[0] !== '/') {
                // TODO: Check upon installation / debug that this is writable
                new_dir = path.join(__dirname, '..', '..', new_dir);
            }
            new_file = path.join(new_dir, hex);
            new_symlink = path.join(new_dir, filename);

            // for database
            lookup_path = path.join(hex, filename);

            mkdirp(new_dir, function (err) {
                if (err) { throw err; }
                fs.writeFile(new_file, data, function (err) {
                    if (err) { throw err; }
                    fs.unlink(tmp_path);
                    fs.symlink(new_file, new_symlink, function (err) {

                        // 47: Already exists
                        if (err && err.errno !== 47) {
                            res.json(500, { error: err });
                        }
                        var file = new File();
                        file.filename = filename;
                        file.path = lookup_path;
                        file.mimetype = mimetype;
                        file.creator = user;
                        if (permissions) {
                            file.permissions = permissions;
                        }
                        if (tags) {
                            file.tags.push(tags);
                        }
                        file.save(function (err) {
                            callback(err, file);
                        });
                    });
                });
            });
        });
    });
};
<commit_msg>Make compile<commit_after>var moment = require('moment'),
    slug = require('slug'),
    fs = require('fs'),
    path = require('path'),
    mkdirp = require('mkdirp'),
    crypto = require('crypto'),
    mongoose = require('mongoose'),
    ObjectId = mongoose.Types.ObjectId,
    mmm = require('mmmagic'),
    Magic = mmm.Magic,
    config = require('../settings'),
    File = require('../models/files').File;

module.exports.h2b64 = function(hex){
    return new Buffer(hex, 'hex').toString('base64').replace('+', '-').replace('/', '_');
};

module.exports.b642h = function(b64){
    return new Buffer(b64.replace('-','+').replace('_','/'), 'base64').toString('hex');
};

module.exports.slug = function (text) {
    return slug(text.toLowerCase());
};
module.exports.isodate = function(date) {
    if (date) {
        return moment(date).format();
    }
};

module.exports.shortdate = function (date) {
    if (date) {
        return moment(date).format('ll');
    } else {
        return date;
    }
};

module.exports.longdate = function (date) {
    if (date) {
        return moment(date).format('LLL');
    }
};

module.exports.ago = function (date) {
    if (date) {
        return moment(date).fromNow();
    }
};

module.exports.set_permissions = function (permissions) {
    var permissions_obj = { 'public': false, groups: [], users: []};
    if (permissions) {
        if (Array.isArray(permissions)) {
            _.each(permissions, function (perm) {
                if (perm === "p") {
                    permissions_obj.public = true;
                } else {
                    var type_id = perm.split("-"),
                        type = type_id[0],
                        object_id = type_id[1];

                    if (type === "g") {
                        permissions_obj.groups.push(object_id);
                    } else if (type === "u") {
                        permissions_obj.users.push(object_id);
                    }
                }
            });
        } else {
            var perm = permissions;
            if (perm === "p") {
                permissions_obj.public = true;
            } else {
                var type_id = perm.split("-"),
                    type = type_id[0],
                    object_id = type_id[1];

                if (type === "g") {
                    permissions_obj.groups.push(object_id);
                } else if (type === "u") {
                    permissions_obj.users.push(object_id);
                }
            }
        }
    }
    return permissions_obj;
};

module.exports.upload_file = function (tmp_path, filename, prefix, user, permissions, tags, callback) {
    fs.readFile(tmp_path, function (err, data) {
        var shasum, hex, new_dir, new_symlink, new_file, lookup_path;

        var magic = new Magic(mmm.MAGIC_MIME_TYPE);

        magic.detectFile(tmp_path, function(err, mimetype) {
            if (err) { throw err; }

            shasum = crypto.createHash('sha1');
            shasum.update('blob ' + data.length +'%s\0');
            shasum.update(data);
            hex = shasum.digest('hex');

            new_dir = path.join(prefix, hex.substr(0,2), hex.substr(2,2), hex);
            if (prefix[0] !== '/') {
                // TODO: Check upon installation / debug that this is writable
                new_dir = path.join(__dirname, '..', '..', new_dir);
            }
            new_file = path.join(new_dir, hex);
            new_symlink = path.join(new_dir, filename);

            // for database
            lookup_path = path.join(hex, filename);

            mkdirp(new_dir, function (err) {
                if (err) { throw err; }
                fs.writeFile(new_file, data, function (err) {
                    if (err) { throw err; }
                    fs.unlink(tmp_path);
                    fs.symlink(new_file, new_symlink, function (err) {

                        // 47: Already exists
                        if (err && err.errno !== 47) {
                            res.json(500, { error: err });
                        }
                        var file = new File();
                        file.filename = filename;
                        file.path = lookup_path;
                        file.mimetype = mimetype;
                        file.creator = user;
                        if (permissions) {
                            file.permissions = permissions;
                        }
                        if (tags) {
                            file.tags.push(tags);
                        }
                        file.save(function (err) {
                            callback(err, file);
                        });
                    });
                });
            });
        });
    });
};
<|endoftext|>


<commit_before>!function(){

  // State Variables
  var trayOpen = false;
  var spConfig = window.superpedestrianConfig || {};

  /*
    function performOnElement
  */
  function performOnElement(name, func) {
    var item = document.getElementById(name);
    func(item);
  }

  var hideElement = function(element) {
    element.style.visibility = "hidden";
    element.style.display = "none";
  };

  var showElement = function(element) {
    element.style.visibility = "";
    element.style.display = "block";
  };

  var clickTray = function(button) {
    button.onclick = function() {
      trayOpen = !trayOpen;
      if(trayOpen){
        performOnElement('arrow-menu', showElement);
        document.getElementById('account-caret').className = "glyphicon glyphicon-triangle-top";
      }
      else {
        performOnElement('arrow-menu', hideElement);
        document.getElementById('account-caret').className = "glyphicon glyphicon-triangle-bottom";
      }
    }
  };

  var setLinks = function () {
    var loginURL = spConfig.loginURL || 'https://account.superpedestrian.com/login?redirect=https://superpedestrian.com';
    var profileURL = spConfig.profileURL || 'https://account.superpedestrian.com/profile';
    var ordersURL = spConfig.ordersURL || 'https://shop.superpedestrian.com/account';
    var logoutURL = spConfig.logoutURL || 'https://account.superpedestrian.com/logout';
    var logoutNext = spConfig.logoutNext || 'https://superpedestrian.com';

    document.getElementById('sp-login-url').href = loginURL;
    document.getElementById('sp-profile-url').href = profileURL;
    document.getElementById('sp-orders-url').href = ordersURL;
    document.getElementById('sp-logout-url').href = logoutURL + '?next=' + logoutNext;
  }

  var setCartCount = function(cookies) {
    var cartCount = 0;
    if(cookies.indexOf('item_count=') > -1){
      var splitCookies = cookies.split('; ');
      for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
        var key = splitCookies[cookieIndex].split('=')[0].trim();
        var value = splitCookies[cookieIndex].split('=')[1];
        if(key === 'item_count') {
          cartCount = value;
        }
      }

      document.getElementById('shop-badge').innerHTML= (cartCount > 9) ? '9+': cartCount;
      performOnElement('shop-badge', showElement);
    }
  };

  var setCountryIcon = function(cookies) {
    var countryCode = 'us';

    var localeParam = getQueryVariable("locale");

    if(localeParam) {
      var splitLocale = localeParam.split('-');
      if( splitLocale[1] ) {
        countryCode = splitLocale[1];
      }
    } else if(cookies.indexOf('locale=') > -1) {
      var splitCookies = cookies.split(';');
      for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
        var key = splitCookies[cookieIndex].split('=')[0].trim();
        var value = splitCookies[cookieIndex].split('=')[1];
        if(key === 'locale') {
          countryCode = value.split('-')[1];
        }
      }
    }

    document.getElementById('country-badge').className = "flag-icon flag-icon-squared flag-icon-" + countryCode;
  };

  function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split('=');
          if (decodeURIComponent(pair[0]) === variable) {
              return decodeURIComponent(pair[1]);
          }
      }
      console.log('Query variable %s not found', variable);
  }

  function init() {
    var cookies = document.cookie;
    performOnElement('arrow-menu', hideElement);
    // Allow dropdown area to be shown after we've hidden the submenu
    document.getElementById('dropdown-area').className = '';

    setLinks();
    setCartCount(cookies);
    setCountryIcon(cookies);

    if((cookies.indexOf('_sp_sso=') > -1) && (cookies.indexOf('_sp_user=') > -1)){
      // Cookies found display My Account
      performOnElement('login-button', hideElement);
      performOnElement('account-button', clickTray);
    }
    else {
      // Show login button
      performOnElement('account-button', hideElement);
    }

    // Show cookie banner if cookie isn't set and the locale is not en-US
    if(!(cookies.indexOf('cookies-accepted=') > -1)) {
      var banner = document.getElementById("cookie-banner");
      var localeParam = getQueryVariable("locale");
      if(localeParam) {
        var splitLocale = localeParam.split('-');
        if( splitLocale[1] !== 'us') {
          banner.style.display = "block";
        }
      }
      else if(cookies.indexOf('locale=') > -1) {
        var splitCookies = cookies.split(';');
        for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
          var key = splitCookies[cookieIndex].split('=')[0].trim();
          var value = splitCookies[cookieIndex].split('=')[1];
          if(key === 'locale' && value.split('-')[1] !== 'us') {
            banner.style.display = "block";
          }
        }
      }
      else {
        banner.style.display = "block";
      }
    }
  }

  init();
}();
<commit_msg>use browser locale for cookie banner<commit_after>!function(){

  // State Variables
  var trayOpen = false;
  var spConfig = window.superpedestrianConfig || {};

  /*
    function performOnElement
  */
  function performOnElement(name, func) {
    var item = document.getElementById(name);
    func(item);
  }

  var hideElement = function(element) {
    element.style.visibility = "hidden";
    element.style.display = "none";
  };

  var showElement = function(element) {
    element.style.visibility = "";
    element.style.display = "block";
  };

  var clickTray = function(button) {
    button.onclick = function() {
      trayOpen = !trayOpen;
      if(trayOpen){
        performOnElement('arrow-menu', showElement);
        document.getElementById('account-caret').className = "glyphicon glyphicon-triangle-top";
      }
      else {
        performOnElement('arrow-menu', hideElement);
        document.getElementById('account-caret').className = "glyphicon glyphicon-triangle-bottom";
      }
    }
  };

  var setLinks = function () {
    var loginURL = spConfig.loginURL || 'https://account.superpedestrian.com/login?redirect=https://superpedestrian.com';
    var profileURL = spConfig.profileURL || 'https://account.superpedestrian.com/profile';
    var ordersURL = spConfig.ordersURL || 'https://shop.superpedestrian.com/account';
    var logoutURL = spConfig.logoutURL || 'https://account.superpedestrian.com/logout';
    var logoutNext = spConfig.logoutNext || 'https://superpedestrian.com';

    document.getElementById('sp-login-url').href = loginURL;
    document.getElementById('sp-profile-url').href = profileURL;
    document.getElementById('sp-orders-url').href = ordersURL;
    document.getElementById('sp-logout-url').href = logoutURL + '?next=' + logoutNext;
  }

  var setCartCount = function(cookies) {
    var cartCount = 0;
    if(cookies.indexOf('item_count=') > -1){
      var splitCookies = cookies.split('; ');
      for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
        var key = splitCookies[cookieIndex].split('=')[0].trim();
        var value = splitCookies[cookieIndex].split('=')[1];
        if(key === 'item_count') {
          cartCount = value;
        }
      }

      document.getElementById('shop-badge').innerHTML= (cartCount > 9) ? '9+': cartCount;
      performOnElement('shop-badge', showElement);
    }
  };

  var setCountryIcon = function(cookies) {
    var countryCode = 'us';

    var localeParam = getQueryVariable("locale");

    if(localeParam) {
      var splitLocale = localeParam.split('-');
      if( splitLocale[1] ) {
        countryCode = splitLocale[1];
      }
    } else if(cookies.indexOf('locale=') > -1) {
      var splitCookies = cookies.split(';');
      for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
        var key = splitCookies[cookieIndex].split('=')[0].trim();
        var value = splitCookies[cookieIndex].split('=')[1];
        if(key === 'locale') {
          countryCode = value.split('-')[1];
        }
      }
    }

    document.getElementById('country-badge').className = "flag-icon flag-icon-squared flag-icon-" + countryCode;
  };

  function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split('=');
          if (decodeURIComponent(pair[0]) === variable) {
              return decodeURIComponent(pair[1]);
          }
      }
      console.log('Query variable %s not found', variable);
  }

  function init() {
    var cookies = document.cookie;
    performOnElement('arrow-menu', hideElement);
    // Allow dropdown area to be shown after we've hidden the submenu
    document.getElementById('dropdown-area').className = '';

    setLinks();
    setCartCount(cookies);
    setCountryIcon(cookies);

    if((cookies.indexOf('_sp_sso=') > -1) && (cookies.indexOf('_sp_user=') > -1)){
      // Cookies found display My Account
      performOnElement('login-button', hideElement);
      performOnElement('account-button', clickTray);
    }
    else {
      // Show login button
      performOnElement('account-button', hideElement);
    }

    // Show cookie banner if cookie isn't set and the locale is not en-US
    if(!(cookies.indexOf('cookies-accepted=') > -1)) {
      var banner = document.getElementById("cookie-banner");
      var localeParam = getQueryVariable("locale");
      if(localeParam) {
        var splitLocale = localeParam.split('-');
        if( splitLocale[1] !== 'us') {
          banner.style.display = "block";
        }
      }
      // Check for locale cookie and show banner for non-US locale
      else if(cookies.indexOf('locale=') > -1) {
        var splitCookies = cookies.split(';');
        for(cookieIndex = 0; cookieIndex < splitCookies.length; cookieIndex++) {
          var key = splitCookies[cookieIndex].split('=')[0].trim();
          var value = splitCookies[cookieIndex].split('=')[1];
          if(key === 'locale' && value.split('-')[1] !== 'us') {
            banner.style.display = "block";
          }
        }
      }
      // Check for browser locale
      else if(navigator.language.split('-')[1] === 'US' || navigator.userLanguage.split('-')[1] === 'US'){
        banner.style.display = "none";
      }
      // Display banner if none of those exist and we don't know anything about their locale
      else {
        banner.style.display = "block";
      }
    }
  }

  init();
}();
<|endoftext|>


<commit_before>
/* jQuery */

// @ @include('../components/popup/popup.js')

// @ @include('../components/light-gallery/light-gallery.jquery.js')
// $('.js-light-gallery').lightGallery();

// $(document).ready(function() {
//
// });

// $("*").on("click", function() {
//
// });
<commit_msg>hoppas.js eslint<commit_after>
/* jQuery */

// @ @include('../components/popup/popup.js')

// @ @include('../components/light-gallery/light-gallery.jquery.js')
// $('.js-light-gallery').lightGallery();

// $(document).ready(function() {
//
// });

// $('*').on('click', function() {
//
// });
<|endoftext|>


<commit_before>Tridion.Type.registerNamespace("DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings");

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings = function Settings() {
    Tridion.OO.enableInterface(this, "DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings");

    this.addInterface("Tridion.Controls.ModalPopupView");
    this.addInterface("Tridion.Web.UI.Editors.Base.Views.ViewBase");

    var p = this.properties;

    p.buttons = {
        close: null,
        save: null
    };

    p.fields = {};

    this.initializeControls();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.enableControls = function Settings$enableControls() {
    var p = this.properties;

    p.buttons.save.enable();
};
DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.disableControls = function Settings$disableControls() {
    var p = this.properties;

    p.buttons.save.disable();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.initializeControls = function Settings$initializeControls() {
    var p = this.properties;

    p.buttons.close = $controls.getControl($("#BtnClose"), "Tridion.Controls.Button");
    $evt.addEventHandler(p.buttons.close, "click", this.getDelegate(this.onCloseClick));

    p.buttons.save = $controls.getControl($("#BtnSave"), "Tridion.Controls.Button");
    $evt.addEventHandler(p.buttons.save, "click", this.getDelegate(this.onSaveClick));

    var f = p.fields;
    f.recurseDepth = $("#cr-recurse-depth");
    $evt.addEventHandler(f.recurseDepth, "valuepropertychange", this.getDelegate(this.onFieldChange));

    f.recurseDepth && f.recurseDepth.focus();

};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.initialize = function Settings$initialize() {
    this.callBase("Tridion.Web.UI.Editors.Base.Views.ViewBase", "initialize");
    var item = this.getItem();

    if (item) {
        $evt.addEventHandler(item, "load", this.getDelegate(this.onItemLoaded));
        $evt.addEventHandler(item, "loading", this.getDelegate(this.onItemLoading));
        $evt.addEventHandler(item, "loadfailed", this.getDelegate(this.onItemLoadFailed));
        $evt.addEventHandler(item, "validate", this.getDelegate(this.onValidate));

        $evt.addEventHandler(item, "collectdata", this.getDelegate(this.onCollectData));
        $evt.addEventHandler(item, "save", this.getDelegate(this.onItemSaved));
        $evt.addEventHandler(item, "savefailed", this.getDelegate(this.onItemSaveFailed));

        item.load(true)
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoading = function Settings$onItemLoading() {
    this.disableControls();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onValidate = function Settings$onValidate() {
    var p = this.properties;

    var fields = p.fields;
    var val = fields.recurseDepth.value;
    if(val){
        if(val.trim() === "") {
            $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_RecurseDepthCanNotBeEmpty"));
            return false;
        }

        var reg = new RegExp("^\\d+$");
        if(!reg.test(val.trim())) {
            $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_RecurseDepthShouldBeNumeric"));
            return false;
        }
    }

    return true;
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoaded = function Settings$onItemLoaded() {
    var item = this.getItem();
    var p = this.properties;

    if (item && item.isLoaded()) {
        var fields = p.fields;

        fields.recurseDepth.value = item.getRecurseDepth();
        this.disableControls();
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemSaved = function Settings$onItemSaved() {
    this.disableControls();
    $messages.registerNotification($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationSaved"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemSaveFailed = function Settings$onItemSaveFailed() {
    this.enableControls();
    $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationSaveFailed"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoadFailed = function Settings$onItemLoadFailed() {
    this.enableControls();
    $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationLoadFailed"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.getItem = function Settings$getItem() {
    return $models.$dcr.getItem(DXA.CM.Extensions.CustomResolver.Models.Constants.CUSTOM_RESOLVER_CONFIGURATION_ID);
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onCloseClick = function Settings$onCloseClick() {

    this.fireEvent("close");
    window.close();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onFieldChange = function Settings$onFieldChange(event) {
    var item = this.getItem();
    var input = event && event.source;
    var val = input && input.value;
    var p = this.properties;
    if (val.trim() === "" || item.getRecurseDepth() == val.trim()) {
        p.buttons.save.disable()
    } else if (p.buttons.save.isDisabled()) {
        p.buttons.save.enable();
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onCollectData = function Settings$onFieldChange(event) {
    var item = this.getItem();
    var p = this.properties;
    var val = p.fields.recurseDepth.value;

    if (val.trim() !== "") {
        item.setRecurseDepth(val.trim())
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onSaveClick = function Settings$onSaveClick() {
    this.fireEvent("save");

    var item = this.getItem();
    if (item) {
        item.save(true);
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.disposeInterface = Tridion.OO.nonInheritable(function Settings$disposeInterface() {
    var item = this.getItem();

    if (item) {
        $evt.removeEventHandler(item, "load", this.getDelegate(this.onItemLoaded));
        $evt.removeEventHandler(item, "loading", this.getDelegate(this.onItemLoading));
        $evt.removeEventHandler(item, "loadfailed", this.getDelegate(this.onItemLoadFailed));
        $evt.removeEventHandler(item, "validate", this.getDelegate(this.onValidate));

        $evt.removeEventHandler(item, "collectdata", this.getDelegate(this.onCollectData));
        $evt.removeEventHandler(item, "save", this.getDelegate(this.onItemSaved));
        $evt.removeEventHandler(item, "savefailed", this.getDelegate(this.onItemSaveFailed));
    }
});

$display.registerView(DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings);<commit_msg>TSI-2945 > Mixed alpha-numeric values get invalid characters stripped off. Fixed case with -1<commit_after>Tridion.Type.registerNamespace("DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings");

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings = function Settings() {
    Tridion.OO.enableInterface(this, "DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings");

    this.addInterface("Tridion.Controls.ModalPopupView");
    this.addInterface("Tridion.Web.UI.Editors.Base.Views.ViewBase");

    var p = this.properties;

    p.buttons = {
        close: null,
        save: null
    };

    p.fields = {};

    this.initializeControls();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.enableControls = function Settings$enableControls() {
    var p = this.properties;

    p.buttons.save.enable();
};
DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.disableControls = function Settings$disableControls() {
    var p = this.properties;

    p.buttons.save.disable();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.initializeControls = function Settings$initializeControls() {
    var p = this.properties;

    p.buttons.close = $controls.getControl($("#BtnClose"), "Tridion.Controls.Button");
    $evt.addEventHandler(p.buttons.close, "click", this.getDelegate(this.onCloseClick));

    p.buttons.save = $controls.getControl($("#BtnSave"), "Tridion.Controls.Button");
    $evt.addEventHandler(p.buttons.save, "click", this.getDelegate(this.onSaveClick));

    var f = p.fields;
    f.recurseDepth = $("#cr-recurse-depth");
    $evt.addEventHandler(f.recurseDepth, "valuepropertychange", this.getDelegate(this.onFieldChange));

    f.recurseDepth && f.recurseDepth.focus();

};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.initialize = function Settings$initialize() {
    this.callBase("Tridion.Web.UI.Editors.Base.Views.ViewBase", "initialize");
    var item = this.getItem();

    if (item) {
        $evt.addEventHandler(item, "load", this.getDelegate(this.onItemLoaded));
        $evt.addEventHandler(item, "loading", this.getDelegate(this.onItemLoading));
        $evt.addEventHandler(item, "loadfailed", this.getDelegate(this.onItemLoadFailed));
        $evt.addEventHandler(item, "validate", this.getDelegate(this.onValidate));

        $evt.addEventHandler(item, "collectdata", this.getDelegate(this.onCollectData));
        $evt.addEventHandler(item, "save", this.getDelegate(this.onItemSaved));
        $evt.addEventHandler(item, "savefailed", this.getDelegate(this.onItemSaveFailed));

        item.load(true)
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoading = function Settings$onItemLoading() {
    this.disableControls();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onValidate = function Settings$onValidate() {
    var p = this.properties;

    var fields = p.fields;
    var val = fields.recurseDepth.value;
    if(val){
        if(val.trim() === "") {
            $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_RecurseDepthCanNotBeEmpty"));
            return false;
        }

        var reg = new RegExp("^\-{0,1}\\d+$");
        if(!reg.test(val.trim())) {
            $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_RecurseDepthShouldBeNumeric"));
            return false;
        }
    }

    return true;
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoaded = function Settings$onItemLoaded() {
    var item = this.getItem();
    var p = this.properties;

    if (item && item.isLoaded()) {
        var fields = p.fields;

        fields.recurseDepth.value = item.getRecurseDepth();
        this.disableControls();
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemSaved = function Settings$onItemSaved() {
    this.disableControls();
    $messages.registerNotification($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationSaved"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemSaveFailed = function Settings$onItemSaveFailed() {
    this.enableControls();
    $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationSaveFailed"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onItemLoadFailed = function Settings$onItemLoadFailed() {
    this.enableControls();
    $messages.registerError($localization.getResource("DXA.CM.Extensions.CustomResolver.Editors.Strings", "CR_ConfigurationLoadFailed"))
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.getItem = function Settings$getItem() {
    return $models.$dcr.getItem(DXA.CM.Extensions.CustomResolver.Models.Constants.CUSTOM_RESOLVER_CONFIGURATION_ID);
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onCloseClick = function Settings$onCloseClick() {

    this.fireEvent("close");
    window.close();
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onFieldChange = function Settings$onFieldChange(event) {
    var item = this.getItem();
    var input = event && event.source;
    var val = input && input.value;
    var p = this.properties;
    if (val.trim() === "" || item.getRecurseDepth() == val.trim()) {
        p.buttons.save.disable()
    } else if (p.buttons.save.isDisabled()) {
        p.buttons.save.enable();
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onCollectData = function Settings$onFieldChange(event) {
    var item = this.getItem();
    var p = this.properties;
    var val = p.fields.recurseDepth.value;

    if (val.trim() !== "") {
        item.setRecurseDepth(val.trim())
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.onSaveClick = function Settings$onSaveClick() {
    this.fireEvent("save");

    var item = this.getItem();
    if (item) {
        item.save(true);
    }
};

DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings.prototype.disposeInterface = Tridion.OO.nonInheritable(function Settings$disposeInterface() {
    var item = this.getItem();

    if (item) {
        $evt.removeEventHandler(item, "load", this.getDelegate(this.onItemLoaded));
        $evt.removeEventHandler(item, "loading", this.getDelegate(this.onItemLoading));
        $evt.removeEventHandler(item, "loadfailed", this.getDelegate(this.onItemLoadFailed));
        $evt.removeEventHandler(item, "validate", this.getDelegate(this.onValidate));

        $evt.removeEventHandler(item, "collectdata", this.getDelegate(this.onCollectData));
        $evt.removeEventHandler(item, "save", this.getDelegate(this.onItemSaved));
        $evt.removeEventHandler(item, "savefailed", this.getDelegate(this.onItemSaveFailed));
    }
});

$display.registerView(DXA.CM.Extensions.CustomResolver.Editors.Views.Popups.Settings);<|endoftext|>


<commit_before>var fw = require('knockout/build/output/knockout-latest');
var _ = require('lodash');

var util = require('./util');
var resultBound = util.resultBound;
var promiseIsFulfilled = util.promiseIsFulfilled;
var isPromise = util.isPromise;

var privateDataSymbol = require('./config').privateDataSymbol;

require('../collection/collection-tools');

// Map from CRUD to HTTP for our default `fw.sync` implementation.
var methodMap = {
  'create': 'POST',
  'update': 'PUT',
  'patch':  'PATCH',
  'delete': 'DELETE',
  'read':   'GET'
};

var parseURLRegex = /^(http[s]*:\/\/[a-zA-Z0-9:\.]*)*([\/]{0,1}[\w\.:\/-]*)$/;
var parseParamsRegex = /(:[\w\.]+)/g;
var trailingSlashRegex = /\/$/;

function noURLError () {
  throw new Error('A "url" property or function must be specified');
};

/**
 * Creates or returns a promise based on the request specified in requestInfo.
 * This function also manages a requestRunning observable on the entity which indicates when the request finishes.
 * Note that there is an optional requestLull which will make the requestRunning observable stay 'true' for
 * atleast the specified duration. If multiple requests are in progress, then it will wait for all to finish.
 *
 * @param  {string} operationType The type of operation being made, used as key to cache running requests
 * @param  {object} requestInfo   Description of the request to make including a createRequest callback to make a new request
 * @return {Promise}              Ajax Promise
 */
function makeOrGetRequest (operationType, requestInfo) {
  var requestRunning = requestInfo.requestRunning;
  var requestLull = requestInfo.requestLull;
  var entity = requestInfo.entity;
  var createRequest = requestInfo.createRequest;
  var promiseName = operationType + 'Promise';
  var allowConcurrent = requestInfo.allowConcurrent;
  var requests = entity[privateDataSymbol][promiseName] || [];
  var theRequest = _.last(requests);

  if ((allowConcurrent || !fw.isObservable(requestRunning) || !requestRunning()) || !requests.length) {
    theRequest = createRequest();

    if (!isPromise(theRequest)) {
      // returned value from createRequest() is a value not a promise, lets return the value in a promise
      theRequest = makePromiseQueryable(Promise.resolve(theRequest));
    }

    requests.push(theRequest);
    entity[privateDataSymbol][promiseName] = requests;

    requestRunning(true);

    var lullFinished = fw.observable(false);
    var requestFinished = fw.observable(false);
    var requestWatcher = fw.computed(function () {
      if (lullFinished() && requestFinished()) {
        requestRunning(false);
        requestWatcher.dispose();
      }
    });

    requestLull = (_.isFunction(requestLull) ? requestLull(operationType) : requestLull);
    if (requestLull) {
      setTimeout(function () {
        lullFinished(true);
      }, requestLull);
    } else {
      lullFinished(true);
    }

    if (isPromise(theRequest)) {
      theRequest.then(function () {
        if (_.every(requests, promiseIsFulfilled)) {
          requestFinished(true);
          entity[privateDataSymbol].promiseName = [];
        }
      });
    }
  }

  return theRequest;
}

/**
 * Create an xmlhttprequest based on the desired action (read/write/etc), concern (dataModel/collection), and optional params.
 *
 * @param {string} action
 * @param {object} concern
 * @param {object} params
 * @returns {object} htr
 */
function sync (action, concern, params) {
  params = params || {};
  action = action || 'noAction';

  if (!fw.isDataModel(concern) && !fw.isCollection(concern)) {
    throw new Error('Must supply a dataModel or collection to fw.sync()');
  }

  if (!_.isString(methodMap[action])) {
    throw new Error('Invalid action (' + action + ') specified for sync operation');
  }

  var configParams = concern[privateDataSymbol].configParams;
  var url = configParams.url;
  if (_.isFunction(url)) {
    url = url.call(concern, action);
  } else if (!_.isString(url)) {
    noURLError();
  }

  if (fw.isDataModel(concern)) {
    var pkIsSpecifiedByUser = !_.isNull(url.match(':' + configParams.idAttribute));
    var hasQueryString = !_.isNull(url.match(/\?/));
    if (_.includes(['read', 'update', 'patch', 'delete'], action) && configParams.useKeyInUrl && !pkIsSpecifiedByUser && !hasQueryString) {
      // need to append /:id to url
      url = url.replace(trailingSlashRegex, '') + '/:' + configParams.idAttribute;
    }
  }

  var urlPieces = (url || noURLError()).match(parseURLRegex);
  if (!_.isNull(urlPieces)) {
    var baseURL = urlPieces[1] || '';
    url = baseURL + _.last(urlPieces);
  }

  if (fw.isDataModel(concern)) {
    // replace any interpolated parameters
    var urlParams = url.match(parseParamsRegex);
    if (urlParams) {
      _.each(urlParams, function (param) {
        url = url.replace(param, concern.get(param.substr(1)));
      });
    }
  }

  var options = _.extend({
      method: methodMap[action].toUpperCase(),
      body: null,
      headers: {}
    },
    resultBound(fw, 'fetchOptions', concern, [params]) || {},
    resultBound(configParams, 'fetchOptions', concern, [params]) || {},
    params);

  if (!_.isString(options.method)) {
    throw new Error('Invalid action (' + action + ') specified for sync operation');
  }

  if (_.isNull(options.body) && concern && _.includes(['create', 'update', 'patch'], action)) {
    options.contentType = 'application/json';
    options.body = JSON.stringify(options.attrs || concern.get());
  }

  var xhr = options.xhr = makePromiseQueryable(fetch(url, options));
  concern.$namespace.publish('_.request', { dataModel: concern, xhr: xhr, options: options });
  return xhr;
};

/**
 * Place isFulfilled/isRejected/isResolved hooks onto a promise which can be used to syncronously determine a promises state.
 *
 * @param {promise} promise
 * @returns {promise} the instrumented promise
 */
function makePromiseQueryable (promise) {
  if (promise.isResolved) {
    return promise;
  }

  var isResolved = false;
  var isRejected = false;

  // Observe the promise, saving the fulfillment in a closure scope.
  var result = promise.then(
    function (v) { isResolved = true; return v; },
    function (e) { isRejected = true; throw e; });
  result.isFulfilled = function () { return isResolved || isRejected; };
  result.isResolved = function () { return isResolved; }
  result.isRejected = function () { return isRejected; }
  return result;
}

/**
 * Take a fetch'd xmlhttprequest and handle the response. Takes into account valid 200-299 response codes.
 * Also handles parse errors in the response which is supposed to be valid JSON.
 *
 * @param {object} xhr
 * @returns {object} xhr with parsed JSON response result
 */
function handleJsonResponse (xhr) {
  return xhr.then(function (response) {
      return _.inRange(response.status, 200, 400) ? response.clone().json() : false;
    })
    .catch( /* istanbul ignore next */ function (parseError) {
      console.error(parseError);
      return false;
    });
}

fw.fetchOptions = {};

module.exports = {
  sync: sync,
  makeOrGetRequest: makeOrGetRequest,
  handleJsonResponse: handleJsonResponse,
  makePromiseQueryable: makePromiseQueryable
}
<commit_msg>added a couple comments to ajax<commit_after>var fw = require('knockout/build/output/knockout-latest');
var _ = require('lodash');

var util = require('./util');
var resultBound = util.resultBound;
var promiseIsFulfilled = util.promiseIsFulfilled;
var isPromise = util.isPromise;

var privateDataSymbol = require('./config').privateDataSymbol;

require('../collection/collection-tools');

// Map from CRUD to HTTP for our default `fw.sync` implementation.
var methodMap = {
  'create': 'POST',
  'update': 'PUT',
  'patch':  'PATCH',
  'delete': 'DELETE',
  'read':   'GET'
};

var parseURLRegex = /^(http[s]*:\/\/[a-zA-Z0-9:\.]*)*([\/]{0,1}[\w\.:\/-]*)$/;
var parseParamsRegex = /(:[\w\.]+)/g;
var trailingSlashRegex = /\/$/;

function noURLError () {
  throw new Error('A "url" property or function must be specified');
};

/**
 * Creates or returns a promise based on the request specified in requestInfo.
 * This function also manages a requestRunning observable on the entity which indicates when the request finishes.
 * Note that there is an optional requestLull which will make the requestRunning observable stay 'true' for
 * atleast the specified duration. If multiple requests are in progress, then it will wait for all to finish.
 *
 * @param  {string} operationType The type of operation being made, used as key to cache running requests
 * @param  {object} requestInfo   Description of the request to make including a createRequest callback to make a new request
 * @return {Promise}              Ajax Promise
 */
function makeOrGetRequest (operationType, requestInfo) {
  var requestRunning = requestInfo.requestRunning;
  var requestLull = requestInfo.requestLull;
  var entity = requestInfo.entity;
  var createRequest = requestInfo.createRequest;
  var promiseName = operationType + 'Promise';
  var allowConcurrent = requestInfo.allowConcurrent;
  var requests = entity[privateDataSymbol][promiseName] || [];
  var theRequest = _.last(requests);

  if ((allowConcurrent || !fw.isObservable(requestRunning) || !requestRunning()) || !requests.length) {
    theRequest = createRequest();

    if (!isPromise(theRequest)) {
      // returned value from createRequest() is a value not a promise, lets return the value in a promise
      theRequest = makePromiseQueryable(Promise.resolve(theRequest));
    }

    requests.push(theRequest);
    entity[privateDataSymbol][promiseName] = requests;

    requestRunning(true);

    var lullFinished = fw.observable(false);
    var requestFinished = fw.observable(false);
    var requestWatcher = fw.computed(function () {
      if (lullFinished() && requestFinished()) {
        requestRunning(false);
        requestWatcher.dispose();
      }
    });

    requestLull = (_.isFunction(requestLull) ? requestLull(operationType) : requestLull);
    if (requestLull) {
      setTimeout(function () {
        lullFinished(true);
      }, requestLull);
    } else {
      lullFinished(true);
    }

    if (isPromise(theRequest)) {
      theRequest.then(function () {
        if (_.every(requests, promiseIsFulfilled)) {
          requestFinished(true);
          entity[privateDataSymbol].promiseName = [];
        }
      });
    }
  }

  return theRequest;
}

/**
 * Create an xmlhttprequest based on the desired action (read/write/etc), concern (dataModel/collection), and optional params.
 *
 * @param {string} action
 * @param {object} concern
 * @param {object} params
 * @returns {object} htr
 */
function sync (action, concern, params) {
  params = params || {};
  action = action || 'noAction';

  if (!fw.isDataModel(concern) && !fw.isCollection(concern)) {
    throw new Error('Must supply a dataModel or collection to fw.sync()');
  }

  if (!_.isString(methodMap[action])) {
    throw new Error('Invalid action (' + action + ') specified for sync operation');
  }

  var configParams = concern[privateDataSymbol].configParams;

  // grab the url
  var url = configParams.url;
  if (_.isFunction(url)) {
    url = url.call(concern, action);
  } else if (!_.isString(url)) {
    noURLError();
  }

  // add the :id to the url if needed
  if (fw.isDataModel(concern)) {
    var pkIsSpecifiedByUser = !_.isNull(url.match(':' + configParams.idAttribute));
    var hasQueryString = !_.isNull(url.match(/\?/));
    if (_.includes(['read', 'update', 'patch', 'delete'], action) && configParams.useKeyInUrl && !pkIsSpecifiedByUser && !hasQueryString) {
      // need to append /:id to url
      url = url.replace(trailingSlashRegex, '') + '/:' + configParams.idAttribute;
    }
  }

  // make sure it begins with the baseUrl
  var urlPieces = (url || noURLError()).match(parseURLRegex);
  if (!_.isNull(urlPieces)) {
    var baseURL = urlPieces[1] || '';
    url = baseURL + _.last(urlPieces);
  }

  // replace any interpolated parameters
  if (fw.isDataModel(concern)) {
    var urlParams = url.match(parseParamsRegex);
    if (urlParams) {
      _.each(urlParams, function (param) {
        url = url.replace(param, concern.get(param.substr(1)));
      });
    }
  }

  // construct the fetch options object
  var options = _.extend({
      method: methodMap[action].toUpperCase(),
      body: null,
      headers: {}
    },
    resultBound(fw, 'fetchOptions', concern, [params]) || {},
    resultBound(configParams, 'fetchOptions', concern, [params]) || {},
    params);

  if (!_.isString(options.method)) {
    throw new Error('Invalid action (' + action + ') specified for sync operation');
  }

  if (_.isNull(options.body) && concern && _.includes(['create', 'update', 'patch'], action)) {
    options.contentType = 'application/json';
    options.body = JSON.stringify(options.attrs || concern.get());
  }

  var xhr = options.xhr = makePromiseQueryable(fetch(url, options));
  concern.$namespace.publish('_.request', { dataModel: concern, xhr: xhr, options: options });
  return xhr;
};

/**
 * Place isFulfilled/isRejected/isResolved hooks onto a promise which can be used to syncronously determine a promises state.
 *
 * @param {promise} promise
 * @returns {promise} the instrumented promise
 */
function makePromiseQueryable (promise) {
  if (promise.isResolved) {
    return promise;
  }

  var isResolved = false;
  var isRejected = false;

  // Observe the promise, saving the fulfillment in a closure scope.
  var result = promise.then(
    function (v) { isResolved = true; return v; },
    function (e) { isRejected = true; throw e; });
  result.isFulfilled = function () { return isResolved || isRejected; };
  result.isResolved = function () { return isResolved; }
  result.isRejected = function () { return isRejected; }
  return result;
}

/**
 * Take a fetch'd xmlhttprequest and handle the response. Takes into account valid 200-299 response codes.
 * Also handles parse errors in the response which is supposed to be valid JSON.
 *
 * @param {object} xhr
 * @returns {object} xhr with parsed JSON response result
 */
function handleJsonResponse (xhr) {
  return xhr.then(function (response) {
      return _.inRange(response.status, 200, 400) ? response.clone().json() : false;
    })
    .catch( /* istanbul ignore next */ function (parseError) {
      console.error(parseError);
      return false;
    });
}

fw.fetchOptions = {};

module.exports = {
  sync: sync,
  makeOrGetRequest: makeOrGetRequest,
  handleJsonResponse: handleJsonResponse,
  makePromiseQueryable: makePromiseQueryable
}
<|endoftext|>


<commit_before>let Proback = require('proback.js')
module.exports = {
	name: 'Lina',
	init: function (options) {
		console.log('Init...', options)
		return Proback.quicker('ok')
	},
	marieChanged: function ( payload ) {
		this.hasMarieChanged = true
		return Proback.quicker( 'OK' )
	},
	flying: function ( ) {
		return Proback.quicker( 'Flying in the clouds...' )
	}
}
<commit_msg>removed console printing<commit_after>let Proback = require('proback.js')
module.exports = {
	name: 'Lina',
	init: function (options) {
		console.log('Init_NEW...', options)
		return Proback.quicker('ok')
	},
	marieChanged: function ( payload ) {
		this.hasMarieChanged = true
		return Proback.quicker( 'OK' )
	},
	flying: function ( ) {
		return Proback.quicker( 'Flying in the clouds...' )
	}
}
<|endoftext|>


<commit_before>var Router = require('routes-router');
var jsonBody = require('body/json');
var sendJson = require('send-data/json');

var Session = require('../lib/session');

var sessionRoutes = new Router();

var sessions = {};

sessionRoutes.addRoute('/all', function(req, res, opts, done) {
    var keys = Object.keys(sessions).sort();
    sendJson(req, res, keys, done);
});

sessionRoutes.addRoute('/create', {
    PUT: function(req, res, opts, done) {
        var session = new Session();
        sessions[session.id] = session;
        sendJson(req, res, session.getData(), done);
    }
});

function loadSession(func) {
    return function(req, res, opts, done) {
        var session = sessions[opts.key];
        if (!session) return done({statusCode: 404, message: 'no such session'});
        opts.session = session;
        return func.call(this, req, res, opts, done);
    };
}

sessionRoutes.addRoute('/:key', loadSession(function(req, res, opts, done) {
    sendJson(req, res, opts.session.getData(), done);
}));

sessionRoutes.addRoute('/:key/result', {
    PUT: loadSession(function(req, res, opts, done) {
        jsonBody(req, res, function(err, resultOrResults) {
            if (err) return done(err);
            if (Array.isArray(resultOrResults)) {
                resultOrResults.forEach(function(result) {
                    opts.session.addResult(result);
                });
            } else {
                opts.session.addResult(resultOrResults);
            }
            res.end();
        });
    })
});

sessionRoutes.addRoute('/:key/events', loadSession(function(req, res, opts) {
    opts.session.handleEventStream(req, res, {
        hello: 'listening to session ' + opts.session.id,
        keepalive: 5000
    });
}));

module.exports = sessionRoutes;
<commit_msg>server: trivial move<commit_after>var Router = require('routes-router');
var jsonBody = require('body/json');
var sendJson = require('send-data/json');

var Session = require('../lib/session');

var sessions = {};

var sessionRoutes = new Router();

sessionRoutes.addRoute('/all', function(req, res, opts, done) {
    var keys = Object.keys(sessions).sort();
    sendJson(req, res, keys, done);
});

sessionRoutes.addRoute('/create', {
    PUT: function(req, res, opts, done) {
        var session = new Session();
        sessions[session.id] = session;
        sendJson(req, res, session.getData(), done);
    }
});

function loadSession(func) {
    return function(req, res, opts, done) {
        var session = sessions[opts.key];
        if (!session) return done({statusCode: 404, message: 'no such session'});
        opts.session = session;
        return func.call(this, req, res, opts, done);
    };
}

sessionRoutes.addRoute('/:key', loadSession(function(req, res, opts, done) {
    sendJson(req, res, opts.session.getData(), done);
}));

sessionRoutes.addRoute('/:key/result', {
    PUT: loadSession(function(req, res, opts, done) {
        jsonBody(req, res, function(err, resultOrResults) {
            if (err) return done(err);
            if (Array.isArray(resultOrResults)) {
                resultOrResults.forEach(function(result) {
                    opts.session.addResult(result);
                });
            } else {
                opts.session.addResult(resultOrResults);
            }
            res.end();
        });
    })
});

sessionRoutes.addRoute('/:key/events', loadSession(function(req, res, opts) {
    opts.session.handleEventStream(req, res, {
        hello: 'listening to session ' + opts.session.id,
        keepalive: 5000
    });
}));

module.exports = sessionRoutes;
<|endoftext|>


<commit_before>/**
 * Created by lega on 8/12/2015.
 */
var Sequelize = require("sequelize");
var pg_connection = require("./creds").pg_connection;
var _ = require("lodash");

var sequelize = new Sequelize(pg_connection);

var d = sequelize.define;

sequelize.define = function(name,def,opts){
    _.forEach(def,function(column,colName){
        column.field = _.snakeCase(colName);
    });

    opts = opts||{};

    opts.underscored = true;
    opts.underscoredAll = true;

    return d.call(this,name,def,opts);
};

var Fact = sequelize.define('fact', {
    id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
    text: {
        type: Sequelize.TEXT
    },
    html: {
        type: Sequelize.TEXT
    },
    hidden: {
        type: Sequelize.BOOLEAN
    }
});

var Category = sequelize.define('category', {
    id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
    title: {
        type: Sequelize.TEXT
    },
    epicKey: {
        type:Sequelize.STRING(10)
    }
});

//var FactCategory = sequelize.define('fact_category', {});

//    fact_id: {
//        type: Sequelize.INTEGER,
//        primaryKey: true,
//        //references: {
//        //    model: Fact,
//        //    key: 'id',
//        //    deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
//        //}
//    },
//    category_id: {
//        type: Sequelize.INTEGER,
//        primaryKey: true,
//        //references: {
//        //    model: Category,
//        //    key: 'id',
//        //    deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
//        //}
//    }
//}, {
//    underscored: true,
//    freezeTableName: true // Model tableName will be the same as the model name
//});

Category.belongsToMany(Fact, {through: 'fact_category'});
Fact.belongsToMany(Category, {through: 'fact_category'});

//FactCategory.belongsTo(Fact);
//
//FactCategory.belongsTo(Category);

var Issue = sequelize.define('issue', {
    id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
    text: {
        type: Sequelize.TEXT
    },
    title: {
        type: Sequelize.TEXT
    },
    key:{
        type:Sequelize.STRING(10)
    },
    epicKey:{
        type:Sequelize.STRING(10)
    }

});

//var FactIssue = sequelize.define('fact_issue', {
//    fact_id: {
//        type: Sequelize.INTEGER,
//        primaryKey: true,
//        references: {
//            model: Fact,
//            key: 'id',
//            deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
//        }
//    },
//    issue_id: {
//        type: Sequelize.INTEGER,
//        primaryKey: true,
//        references: {
//            model: Issue,
//            key: 'id',
//            deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
//        }
//    }
//}, {
//    freezeTableName: true // Model tableName will be the same as the model name
//});

Issue.belongsToMany(Fact, {through: "fact_issue"});
Fact.belongsToMany(Issue, {through: "fact_issue"});

sequelize.sync();

//Fact.sync({force: true}).then(function () {
//    return Category.sync({force:true});
//}).then(function(){
//    return Issue.sync({force:true});
//})
//    .then(function(){
//    return s.sync({force:true});
//})
//    .then(function(){
//    return FactCategory.sync({force:true});
//})

module.exports.Issue = Issue;
module.errors.Fact = Fact;<commit_msg>removed sequelize test code<commit_after><|endoftext|>


<commit_before>'use strict';
var mockFiles = [{
            "title": "Alice of in Wonderland",
            "text": "Alice falls into a rabbit shit hole and enters a world full of imagination."
        },

        {
            "title": "The Lord of the zip Rings: The Fellowship of the Ring.",
            "text": "An unusual alliance of man, elf, dwarf, oobit wizard and hobbit seek to destroy a powerful ring."
        }
];

//write test to read book data
describe("Read book data", function () {
    it("should verify that the files are not empty", function () {
        expect(mockFiles.length > 0).toBeTruthy();
    });

    it("should check if all properties in the file are strings", function () {
        mockFiles.forEach(function (document) {
            expect(typeof document.title === "string").toBeTruthy();
            expect(typeof document.text === "string").toBeTruthy();
        });
    });

    it("should verify that the file content is a JSON array", function () {
        expect(Array.isArray(mockFiles)).toBeTruthy();
    });
});

describe("Check Class properties", function () {

    beforeEach(function() {
        this.indexInstance = new Index();
    });

    it("should have get index property", function () {
        expect(typeof this.indexInstance.getIndex ==='function').toBeTruthy();
    });

    it("should have create index property", function () {
        expect(typeof this.indexInstance.createIndex ==='function').toBeTruthy();
    });
    it("should have search property", function () {
        expect(typeof this.indexInstance.searchIndex ==='function').toBeTruthy();
    });
});

describe("Populate Index", function () {
    beforeEach(function() {
    this.indexInstance = new Index();
  });

    it("should create an index of documents as an object", function () {
        let data = {
            name:'book.json',
            docs:mockFiles
        };
        let indexArray = this.indexInstance;
        expect(typeof indexArray.getIndex(data)).toBe('object');
    });

    it("should create index and return a valid result", function(){
        let creates = this.indexInstance;
        let result = {
            a:[0,1],
            alice:[0],
            alliance:[1],
            an:[1],
            and:[0,1],
            destroy:[1],
            dwarf:[1],
            elf:[1],
            enters:[0],
            falls:[0],
            full:[0],
            hobbit:[1],
            hole:[0],
            imagination:[0],
            into:[0],
            man:[1],
            of:[0,1],
            oobit:[1],
            powerful:[1],
            rabbit:[0],
            ring:[1],
            seek:[1],
            shit:[0],
            to:[1],
            unusual:[1],
            wizard:[1],
            world:[0]
        };
        expect(creates.createIndex(mockFiles)).toEqual(result);
    });

});<commit_msg>Test Suite Update<commit_after>'use strict';
var mockFiles = [{
            "title": "Alice of in Wonderland",
            "text": "Alice falls into a rabbit shit hole and enters a world full of imagination."
        },

        {
            "title": "The Lord of the zip Rings: The Fellowship of the Ring.",
            "text": "An unusual alliance of man, elf, dwarf, oobit wizard and hobbit seek to destroy a powerful ring."
        }
];

//write test to read book data
describe("Read book data", function () {
    it("should verify that the files are not empty", function () {
        expect(mockFiles.length > 0).toBeTruthy();
    });

    it("should check if all properties in the file are strings", function () {
        mockFiles.forEach(function (document) {
            expect(typeof document.title === "string").toBeTruthy();
            expect(typeof document.text === "string").toBeTruthy();
        });
    });

    it("should verify that the file content is a JSON array", function () {
        expect(Array.isArray(mockFiles)).toBeTruthy();
    });
});

describe("Check Class properties", function () {

    beforeEach(function() {
        this.indexInstance = new Index();
    });

    it("should have get index property", function () {
        expect(typeof this.indexInstance.getIndex ==='function').toBeTruthy();
    });

    it("should have create index property", function () {
        expect(typeof this.indexInstance.createIndex ==='function').toBeTruthy();
    });
    it("should have search property", function () {
        expect(typeof this.indexInstance.searchIndex ==='function').toBeTruthy();
    });
});

describe("Populate Index", function () {
    beforeEach(function() {
    this.indexInstance = new Index();
  });

    it("should create an index of documents as an object", function () {
        let data = {
            name:'book.json',
            docs:mockFiles
        };
        let indexArray = this.indexInstance;
        expect(typeof indexArray.getIndex(data)).toBe('object');
    });

    it("should create index and return a valid result", function(){
        let creates = this.indexInstance;
        let result = {
            a:[0,1],
            alice:[0],
            alliance:[1],
            an:[1],
            and:[0,1],
            destroy:[1],
            dwarf:[1],
            elf:[1],
            enters:[0],
            falls:[0],
            full:[0],
            hobbit:[1],
            hole:[0],
            imagination:[0],
            into:[0],
            man:[1],
            of:[0,1],
            oobit:[1],
            powerful:[1],
            rabbit:[0],
            ring:[1],
            seek:[1],
            shit:[0],
            to:[1],
            unusual:[1],
            wizard:[1],
            world:[0]
        };
        expect(creates.createIndex(mockFiles)).toEqual(result);
    });

});

describe('Search Index', function() {

    beforeEach(function() {
        this.indexInstance = new Index();
    });

    it('should search and return an object that contains result', function() {
        const term = 'We are very unusual in alliance';
        expect(typeof this.indexInstance.searchIndex(term,this.indexInstance.createIndex(mockFiles))).toBe('object')
    });

    it('should return accurate search result', function() {
        const term = 'We are very unusual in alliance';
        const resultObj = {
            unusual:[1],
            alliance:[1]
        };
        expect(this.indexInstance.searchIndex(term,this.indexInstance.createIndex(mockFiles))).toEqual(resultObj);
    });

});<|endoftext|>


<commit_before>describe('indexObj', function(){
	var testObj = new Index();

  beforeEach(function(done){
    testObj.createIndex().then(function(data){
			testObj.arr = data;
      done();
    });
  });

	describe('createIndex', function(){

		it('reads json file and asserts file is not empty', function(){
			//console.log(arr);
			expect(arr.length).not.toBe(0);
			// expect(arr.indexOf("joy")).toBe(-1);
		});
	});

 // describe('getIndex',function(){
 //    indexObj.createIndex();
 //
 // 	it('returns an object of file contents',function(){
 // 		expect(typeof indexObj.getIndex().toBe('string'));
 // 	})
 //
 // });
// indexObj.searchIndex(["alice", "governor", "wonderland", "lord", "rings"]);

})
<commit_msg>Add getIndex test<commit_after>describe('indexObj', function(){
	var testObj = new Index(), filepath = "/jasmine/books.json";

	beforeEach(function(done){
    testObj.createIndex(filepath).then(function(data){
			testObj.arr = data;
      done();
    });
	});

	describe('createIndex', function(){

		it('reads json file and asserts file is not empty', function(){
			expect(testObj.arr.length).not.toBe(0);
		});
	});

 describe('getIndex', function(){

 	it('returns an object of file contents',function(){
 		expect(typeof testObj.getIndex()).toBe('object');
 	});

});
// indexObj.searchIndex(["alice", "governor", "wonderland", "lord", "rings"]);

})
<|endoftext|>


<commit_before>/*global require:true*/
/*global __dirname:true*/
/*global Buffer:true*/
(function( exports ){
	'use strict';

	var path = require( "path" );
	var os = require( "os" );
	var fs = require( "fs-extra" );

	var Grunticon = require( path.join( __dirname, "..", "..", "lib", "grunticon-lib.js" ) );

	/*
		======== A Handy Little Nodeunit Reference ========
		https://github.com/caolan/nodeunit

		Test methods:
			test.expect(numAssertions)
			test.done()
		Test assertions:
			test.ok(value, [message])
			test.equal(actual, expected, [message])
			test.notEqual(actual, expected, [message])
			test.deepEqual(actual, expected, [message])
			test.notDeepEqual(actual, expected, [message])
			test.strictEqual(actual, expected, [message])
			test.notStrictEqual(actual, expected, [message])
			test.throws(block, [error], [message])
			test.doesNotThrow(block, [error], [message])
			test.ifError(value)
	*/

	exports.constructor = {
		setUp: function(done) {
			// setup here if necessary
			done();
		},
		noargs: function(test) {
			test.expect(1);

			test.throws(function(){
				new Grunticon();
			}, "No arguments should throw an error" );

			test.done();
		},
		twoargsFirstNotArray: function(test) {
			test.expect(1);

			test.throws(function(){
				new Grunticon("foo", "bar");
			}, "There needs to be two arguments. The first needs to be an Array" );

			test.done();
		},
		twoArgs: function( test ){
			test.expect(22);
			var grunticon = new Grunticon([path.join( __dirname, "files", "bear.svg")], path.join( __dirname, "output" ));

			// Required
			test.equal( grunticon.files[0], path.join( __dirname, "files", "bear.svg" ), "File should be set" );
			test.equal( grunticon.output, path.join( __dirname, "output" ), "Output should be set properly" );

			// Options Defaults
			test.equal( grunticon.options.datasvgcss, "icons.data.svg.css" );
			test.equal( grunticon.options.datapngcss, "icons.data.png.css" );
			test.equal( grunticon.options.urlpngcss, "icons.fallback.css" );
			test.equal( grunticon.options.previewhtml, "preview.html" );
			test.equal( grunticon.options.loadersnippet, "grunticon.loader.js" );
			test.equal( grunticon.options.cssbasepath, path.sep );
			test.equal( grunticon.options.cssprefix, ".icon-" );
			test.equal( grunticon.options.defaultWidth, "400px" );
			test.equal( grunticon.options.defaultHeight, "300px" );
			test.equal( grunticon.options.dynamicColorOnly, false );
			test.equal( grunticon.options.pngfolder, "png" );
			test.equal( grunticon.options.pngpath, "" );
			test.equal( grunticon.options.template, "" );
			test.equal( grunticon.options.tmpPath, os.tmpDir() );
			test.equal( grunticon.options.tmpDir, "grunticon-tmp" );
			test.equal( grunticon.options.previewTemplate, path.join( __dirname, "..", "..", "static", "preview.hbs" ) );
			test.equal( grunticon.options.compressPNG, false );
			test.equal( grunticon.options.optimizationLevel, 3 );
			test.equal( grunticon.options.enhanceSVG, false );
			test.equal( grunticon.options.corsEmbed, false );

			test.done();
		}
	};

	exports.process = {
		setUp: function(done) {
			// setup here if necessary
			done();
		},
		tearDown: function( done ){
			var output = path.join( __dirname, "output" );
			var files = fs.readdirSync( output )
			.map(function( filename ){
				return path.join( output, filename );
			});

			var notFiles = files.filter(function(file){
				return !fs.lstatSync( file ).isFile();
			});

			files.filter(function(file){
				return fs.lstatSync( file ).isFile();
			})
			.forEach(fs.unlinkSync);

			notFiles.filter(function(file){
				return fs.lstatSync( file ).isDirectory();
			})
			.forEach(fs.removeSync);

			done();
		},
		onefileFilesExist: function( test ){
			test.expect(6);
			var files = [path.join( __dirname, "files", "bear.svg" )];
			var output = path.join( __dirname, "output" );
			var grunticon = new Grunticon( files, output );

			grunticon.process(function(status){
				if( status === false ){
					test.ok( status, "status was bad" );
					test.done();
				}

				test.ok( fs.existsSync( path.join( output, "preview.html" ),				"preview should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "grunticon.loader.js" ), "loader file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.data.svg.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.data.png.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.fallback.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "png", "bear.png" ),			"png file should have been created" ) );

				test.done();
			});
		},
		onefileContents: function( test ){
			test.expect(6);
			var files = [path.join( __dirname, "files", "bear.svg" )];
			var output = path.join( __dirname, "output" );
			var expected = path.join( __dirname, "expected" );

			var expectedContents = {
				preview:		 fs.readFileSync( path.join( expected, "preview.html" ) ).toString( "utf-8" ),
				loader:			 fs.readFileSync( path.join( expected, "grunticon.loader.js" ) ).toString( "utf-8" ),
				svgcss:			 fs.readFileSync( path.join( expected, "icons.data.svg.css" ) ).toString( "utf-8" ),
				pngcss:			 fs.readFileSync( path.join( expected, "icons.data.png.css" ) ).toString( "utf-8" ),
				fallbackcss: fs.readFileSync( path.join( expected, "icons.fallback.css" ) ).toString( "utf-8" ),
				png:				 fs.readFileSync( path.join( expected, "png", "bear.png" ) )
			};

			var grunticon = new Grunticon( files, output );

			grunticon.process(function(status){
				if( status === false ){
					test.ok( status, "status was bad" );
					test.done();
				}

				console.log( "before actual contents object" );

				var actualContents = {
					preview:		 fs.readFileSync( path.join( output, "preview.html" ) ).toString( "utf-8" ),
					loader:			 fs.readFileSync( path.join( output, "grunticon.loader.js" ) ).toString( "utf-8" ),
					svgcss:			 fs.readFileSync( path.join( output, "icons.data.svg.css" ) ).toString( "utf-8" ),
					pngcss:			 fs.readFileSync( path.join( output, "icons.data.png.css" ) ).toString( "utf-8" ),
					fallbackcss: fs.readFileSync( path.join( output, "icons.fallback.css" ) ).toString( "utf-8" ),
					png:				 fs.readFileSync( path.join( output, "png", "bear.png" ) )
				};

				console.log( "before deep equal" );

				test.deepEqual( actualContents.preview,			expectedContents.preview, "preview should have been created" );
				test.deepEqual( actualContents.loader,			expectedContents.loader, "loader's contents should match" );
				test.deepEqual( actualContents.svgcss,			expectedContents.svgcss, "icon svg css file should match" );
				test.deepEqual( actualContents.pngcss,			expectedContents.pngcss, "icon png css file should match" );
				test.deepEqual( actualContents.fallbackcss, expectedContents.fallbackcss, "icon fallback file should match" );
				test.deepEqual( Buffer.compare( actualContents.png, expectedContents.png ), 0, "png file should match" );

				console.log( "before test done" );

				test.done();
			});
		}
	};

}(typeof exports === 'object' && exports || this));
<commit_msg>dat print debug<commit_after>/*global require:true*/
/*global __dirname:true*/
/*global Buffer:true*/
(function( exports ){
	'use strict';

	var path = require( "path" );
	var os = require( "os" );
	var fs = require( "fs-extra" );

	var Grunticon = require( path.join( __dirname, "..", "..", "lib", "grunticon-lib.js" ) );

	/*
		======== A Handy Little Nodeunit Reference ========
		https://github.com/caolan/nodeunit

		Test methods:
			test.expect(numAssertions)
			test.done()
		Test assertions:
			test.ok(value, [message])
			test.equal(actual, expected, [message])
			test.notEqual(actual, expected, [message])
			test.deepEqual(actual, expected, [message])
			test.notDeepEqual(actual, expected, [message])
			test.strictEqual(actual, expected, [message])
			test.notStrictEqual(actual, expected, [message])
			test.throws(block, [error], [message])
			test.doesNotThrow(block, [error], [message])
			test.ifError(value)
	*/

	exports.constructor = {
		setUp: function(done) {
			// setup here if necessary
			done();
		},
		noargs: function(test) {
			test.expect(1);

			test.throws(function(){
				new Grunticon();
			}, "No arguments should throw an error" );

			test.done();
		},
		twoargsFirstNotArray: function(test) {
			test.expect(1);

			test.throws(function(){
				new Grunticon("foo", "bar");
			}, "There needs to be two arguments. The first needs to be an Array" );

			test.done();
		},
		twoArgs: function( test ){
			test.expect(22);
			var grunticon = new Grunticon([path.join( __dirname, "files", "bear.svg")], path.join( __dirname, "output" ));

			// Required
			test.equal( grunticon.files[0], path.join( __dirname, "files", "bear.svg" ), "File should be set" );
			test.equal( grunticon.output, path.join( __dirname, "output" ), "Output should be set properly" );

			// Options Defaults
			test.equal( grunticon.options.datasvgcss, "icons.data.svg.css" );
			test.equal( grunticon.options.datapngcss, "icons.data.png.css" );
			test.equal( grunticon.options.urlpngcss, "icons.fallback.css" );
			test.equal( grunticon.options.previewhtml, "preview.html" );
			test.equal( grunticon.options.loadersnippet, "grunticon.loader.js" );
			test.equal( grunticon.options.cssbasepath, path.sep );
			test.equal( grunticon.options.cssprefix, ".icon-" );
			test.equal( grunticon.options.defaultWidth, "400px" );
			test.equal( grunticon.options.defaultHeight, "300px" );
			test.equal( grunticon.options.dynamicColorOnly, false );
			test.equal( grunticon.options.pngfolder, "png" );
			test.equal( grunticon.options.pngpath, "" );
			test.equal( grunticon.options.template, "" );
			test.equal( grunticon.options.tmpPath, os.tmpDir() );
			test.equal( grunticon.options.tmpDir, "grunticon-tmp" );
			test.equal( grunticon.options.previewTemplate, path.join( __dirname, "..", "..", "static", "preview.hbs" ) );
			test.equal( grunticon.options.compressPNG, false );
			test.equal( grunticon.options.optimizationLevel, 3 );
			test.equal( grunticon.options.enhanceSVG, false );
			test.equal( grunticon.options.corsEmbed, false );

			test.done();
		}
	};

	exports.process = {
		setUp: function(done) {
			// setup here if necessary
			done();
		},
		tearDown: function( done ){
			var output = path.join( __dirname, "output" );
			var files = fs.readdirSync( output )
			.map(function( filename ){
				return path.join( output, filename );
			});

			var notFiles = files.filter(function(file){
				return !fs.lstatSync( file ).isFile();
			});

			files.filter(function(file){
				return fs.lstatSync( file ).isFile();
			})
			.forEach(fs.unlinkSync);

			notFiles.filter(function(file){
				return fs.lstatSync( file ).isDirectory();
			})
			.forEach(fs.removeSync);

			done();
		},
		onefileFilesExist: function( test ){
			test.expect(6);
			var files = [path.join( __dirname, "files", "bear.svg" )];
			var output = path.join( __dirname, "output" );
			var grunticon = new Grunticon( files, output );

			grunticon.process(function(status){
				if( status === false ){
					test.ok( status, "status was bad" );
					test.done();
				}

				test.ok( fs.existsSync( path.join( output, "preview.html" ),				"preview should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "grunticon.loader.js" ), "loader file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.data.svg.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.data.png.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "icons.fallback.css" ),	"icon css file should have been created" ) );
				test.ok( fs.existsSync( path.join( output, "png", "bear.png" ),			"png file should have been created" ) );

				test.done();
			});
		},
		onefileContents: function( test ){
			test.expect(6);
			var files = [path.join( __dirname, "files", "bear.svg" )];
			var output = path.join( __dirname, "output" );
			var expected = path.join( __dirname, "expected" );

			var expectedContents = {
				preview:		 fs.readFileSync( path.join( expected, "preview.html" ) ).toString( "utf-8" ),
				loader:			 fs.readFileSync( path.join( expected, "grunticon.loader.js" ) ).toString( "utf-8" ),
				svgcss:			 fs.readFileSync( path.join( expected, "icons.data.svg.css" ) ).toString( "utf-8" ),
				pngcss:			 fs.readFileSync( path.join( expected, "icons.data.png.css" ) ).toString( "utf-8" ),
				fallbackcss: fs.readFileSync( path.join( expected, "icons.fallback.css" ) ).toString( "utf-8" ),
				png:				 fs.readFileSync( path.join( expected, "png", "bear.png" ) )
			};

			var grunticon = new Grunticon( files, output );

			grunticon.process(function(status){
				if( status === false ){
					test.ok( status, "status was bad" );
					test.done();
				}

				console.log( "before actual contents object" );

				var actualContents = {
					preview:		 fs.readFileSync( path.join( output, "preview.html" ) ).toString( "utf-8" ),
					loader:			 fs.readFileSync( path.join( output, "grunticon.loader.js" ) ).toString( "utf-8" ),
					svgcss:			 fs.readFileSync( path.join( output, "icons.data.svg.css" ) ).toString( "utf-8" ),
					pngcss:			 fs.readFileSync( path.join( output, "icons.data.png.css" ) ).toString( "utf-8" ),
					fallbackcss: fs.readFileSync( path.join( output, "icons.fallback.css" ) ).toString( "utf-8" ),
					png:				 fs.readFileSync( path.join( output, "png", "bear.png" ) )
				};

				console.log( "before deep equal" );

				test.deepEqual( actualContents.preview,			expectedContents.preview, "preview should have been created" );

        console.log( "before loader" );
				test.deepEqual( actualContents.loader,			expectedContents.loader, "loader's contents should match" );
        console.log( "before svgcss" );
				test.deepEqual( actualContents.svgcss,			expectedContents.svgcss, "icon svg css file should match" );
        console.log( "before pngcss" );
				test.deepEqual( actualContents.pngcss,			expectedContents.pngcss, "icon png css file should match" );
        console.log( "before fallback css" );
				test.deepEqual( actualContents.fallbackcss, expectedContents.fallbackcss, "icon fallback file should match" );
        console.log( "before png buffer compare" );
				test.deepEqual( Buffer.compare( actualContents.png, expectedContents.png ), 0, "png file should match" );

				test.done();
			});
		}
	};

}(typeof exports === 'object' && exports || this));
<|endoftext|>