<commit_before>'use strict';

//region Imports

var EditableRootModel = require('./editable-root-model.js');
var EditableChildModel = require('./editable-child-model.js');
var EditableRootCollection = require('./editable-root-collection.js');
var EditableChildCollection = require('./editable-child-collection.js');
var ReadOnlyRootModel = require('./read-only-root-model.js');
var ReadOnlyChildModel = require('./read-only-child-model.js');
var ReadOnlyRootCollection = require('./read-only-root-collection.js');
var ReadOnlyChildCollection = require('./read-only-child-collection.js');
var CommandObject = require('./command-object.js');

//var EditableRootModelSync = require('./editable-root-model-sync.js');
//var EditableChildModelSync = require('./editable-child-model-sync.js');
//var EditableRootCollectionSync = require('./editable-root-collection-sync.js');
//var EditableChildCollectionSync = require('./editable-child-collection-sync.js');
//var ReadOnlyRootModelSync = require('./read-only-root-model-sync.js');
//var ReadOnlyChildModelSync = require('./read-only-child-model-sync.js');
//var ReadOnlyRootCollectionSync = require('./read-only-root-collection-sync.js');
//var ReadOnlyChildCollectionSync = require('./read-only-child-collection-sync.js');
//var CommandObjectSync = require('./command-object-sync.js');

var PropertyManager = require('./shared/property-manager.js');
var RuleManager = require('./rules/rule-manager.js');
var ExtensionManager = require('./shared/extension-manager.js');
//var ExtensionManagerSync = require('./shared/extension-manager-sync.js');

var PropertyInfo = require('./shared/property-info.js');
var dt = require('./data-types/index.js');

//endregion

function ModelComposerFactory (modelName) {
  return new ModelComposer (modelName);
}

var ArgsType = {
  businessObject: 0,
  rootCollection: 1,
  childCollection: 2
};

function ModelComposer (modelName) {

  var modelType = null;
  var itemsType = null;
  var argsType = null;
  var properties = null;
  var rules = null;
  var extensions = null;
  var currentProperty = null;

  //region Model types

  this.editableRootModel = function (dataSource, modelPath) {
    modelType = EditableRootModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.editableChildModel = function (dataSource, modelPath) {
    modelType = EditableChildModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyRootModel = function (dataSource, modelPath) {
    modelType = ReadOnlyRootModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyChildModel = function (dataSource, modelPath) {
    modelType = ReadOnlyChildModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.editableRootCollection = function (dataSource, modelPath) {
    modelType = EditableRootCollection;
    argsType = ArgsType.rootCollection;
    return initialize(dataSource, modelPath);
  };

  this.editableChildCollection = function (dataSource, modelPath) {
    modelType = EditableChildCollection;
    argsType = ArgsType.childCollection;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyRootCollection = function (dataSource, modelPath) {
    modelType = ReadOnlyRootCollection;
    argsType = ArgsType.rootCollection;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyChildCollection = function (dataSource, modelPath) {
    modelType = ReadOnlyChildCollection;
    argsType = ArgsType.childCollection;
    return initialize(dataSource, modelPath);
  };

  this.commandObject = function (dataSource, modelPath) {
    modelType = CommandObject;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  function initialize (dataSource, modelPath) {
    properties = new PropertyManager();
    rules = new RuleManager();
    extensions = new ExtensionManager(dataSource, modelPath);
    return this;
  }

  //endregion

  this.itemType = function (itemType) {
    itemsType = itemType;
    return this;
  };

  //region Properties

  this.boolean = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Boolean, flags, getter, setter);
  };

  this.text = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Text, flags, getter, setter);
  };

  this.email = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Email, flags, getter, setter);
  };

  this.integer = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Integer, flags, getter, setter);
  };

  this.decimal = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Decimal, flags, getter, setter);
  };

  this.enum = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Enum, flags, getter, setter);
  };

  this.dateTime = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.DateTime, flags, getter, setter);
  };

  this.property = function (propertyName, typeCtor, flags, getter, setter) {
    return addProperty(propertyName, new typeCtor(), flags, getter, setter);
  };

  function addProperty (propertyName, propertyType, flags, getter, setter) {
    var property = new PropertyInfo(propertyName, propertyType, flags, getter, setter);
    properties.add(property);
    currentProperty = property;
    return this;
  }

  //endregion

  //region Property rules

  function addValidation () {
    if (!currentProperty)
      throw new Error('The current property is not determined.');
  }

  //endregion

  //region Object rules

  //endregion

  //region Extensions

  this.daoBuilder = function (daoBuilder) {
    extensions.daoBuilder = daoBuilder;
    return nonProperty();
  };

  this.toDto = function (toDto) {
    extensions.toDto = toDto;
    return nonProperty();
  };

  this.fromDto = function (fromDto) {
    extensions.fromDto = fromDto;
    return nonProperty();
  };

  this.toCto = function (toCto) {
    extensions.toCto = toCto;
    return nonProperty();
  };

  this.fromCto = function (fromCto) {
    extensions.fromCto = fromCto;
    return nonProperty();
  };

  this.dataCreate = function (dataCreate) {
    extensions.dataCreate = dataCreate;
    return nonProperty();
  };

  this.dataFetch = function (dataFetch) {
    extensions.dataFetch = dataFetch;
    return nonProperty();
  };

  this.dataInsert = function (dataInsert) {
    extensions.dataInsert = dataInsert;
    return nonProperty();
  };

  this.dataUpdate = function (dataUpdate) {
    extensions.dataUpdate = dataUpdate;
    return nonProperty();
  };

  this.dataRemove = function (dataRemove) {
    extensions.dataRemove = dataRemove;
    return nonProperty();
  };

  this.dataExecute = function (dataExecute) {
    extensions.dataExecute = dataExecute;
    return nonProperty();
  };

  //endregion

  function nonProperty () {
    currentProperty = null;
    return this;
  }

  this.compose = function () {
    switch (argsType) {
      case ArgsType.businessObject:
        return new modelType(modelName, properties, rules, extensions);
      case ArgsType.rootCollection:
        return new modelType(modelName, itemsType, rules, extensions);
      case ArgsType.childCollection:
        return new modelType(modelName, itemsType);
    }
  };
}
//util.inherits(ModelComposer, ComposerBase);

module.exports = ModelBase;
<commit_msg>Developing model composer.<commit_after>'use strict';

//region Imports

var EditableRootModel = require('./editable-root-model.js');
var EditableChildModel = require('./editable-child-model.js');
var EditableRootCollection = require('./editable-root-collection.js');
var EditableChildCollection = require('./editable-child-collection.js');
var ReadOnlyRootModel = require('./read-only-root-model.js');
var ReadOnlyChildModel = require('./read-only-child-model.js');
var ReadOnlyRootCollection = require('./read-only-root-collection.js');
var ReadOnlyChildCollection = require('./read-only-child-collection.js');
var CommandObject = require('./command-object.js');

//var EditableRootModelSync = require('./editable-root-model-sync.js');
//var EditableChildModelSync = require('./editable-child-model-sync.js');
//var EditableRootCollectionSync = require('./editable-root-collection-sync.js');
//var EditableChildCollectionSync = require('./editable-child-collection-sync.js');
//var ReadOnlyRootModelSync = require('./read-only-root-model-sync.js');
//var ReadOnlyChildModelSync = require('./read-only-child-model-sync.js');
//var ReadOnlyRootCollectionSync = require('./read-only-root-collection-sync.js');
//var ReadOnlyChildCollectionSync = require('./read-only-child-collection-sync.js');
//var CommandObjectSync = require('./command-object-sync.js');

var PropertyManager = require('./shared/property-manager.js');
var RuleManager = require('./rules/rule-manager.js');
var ExtensionManager = require('./shared/extension-manager.js');
//var ExtensionManagerSync = require('./shared/extension-manager-sync.js');

var Action = require('./rules/authorization-action.js');
var cr = require('./common-rules/index.js');

var PropertyInfo = require('./shared/property-info.js');
var dt = require('./data-types/index.js');

//endregion

function ModelComposerFactory (modelName) {
  return new ModelComposer (modelName);
}

var ArgsType = {
  businessObject: 0,
  rootCollection: 1,
  childCollection: 2
};

function ModelComposer (modelName) {

  var modelType = null;
  var itemsType = null;
  var argsType = null;
  var properties = null;
  var rules = null;
  var extensions = null;
  var currentProperty = null;

  //region Model types

  this.editableRootModel = function (dataSource, modelPath) {
    modelType = EditableRootModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.editableChildModel = function (dataSource, modelPath) {
    modelType = EditableChildModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyRootModel = function (dataSource, modelPath) {
    modelType = ReadOnlyRootModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyChildModel = function (dataSource, modelPath) {
    modelType = ReadOnlyChildModel;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  this.editableRootCollection = function (dataSource, modelPath) {
    modelType = EditableRootCollection;
    argsType = ArgsType.rootCollection;
    return initialize(dataSource, modelPath);
  };

  this.editableChildCollection = function (dataSource, modelPath) {
    modelType = EditableChildCollection;
    argsType = ArgsType.childCollection;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyRootCollection = function (dataSource, modelPath) {
    modelType = ReadOnlyRootCollection;
    argsType = ArgsType.rootCollection;
    return initialize(dataSource, modelPath);
  };

  this.readOnlyChildCollection = function (dataSource, modelPath) {
    modelType = ReadOnlyChildCollection;
    argsType = ArgsType.childCollection;
    return initialize(dataSource, modelPath);
  };

  this.commandObject = function (dataSource, modelPath) {
    modelType = CommandObject;
    argsType = ArgsType.businessObject;
    return initialize(dataSource, modelPath);
  };

  function initialize (dataSource, modelPath) {
    properties = new PropertyManager();
    rules = new RuleManager();
    extensions = new ExtensionManager(dataSource, modelPath);
    return this;
  }

  //endregion

  this.itemType = function (itemType) {
    itemsType = itemType;
    return this;
  };

  //region Properties

  this.boolean = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Boolean, flags, getter, setter);
  };

  this.text = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Text, flags, getter, setter);
  };

  this.email = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Email, flags, getter, setter);
  };

  this.integer = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Integer, flags, getter, setter);
  };

  this.decimal = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Decimal, flags, getter, setter);
  };

  this.enum = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.Enum, flags, getter, setter);
  };

  this.dateTime = function (propertyName, flags, getter, setter) {
    return addProperty(propertyName, dt.DateTime, flags, getter, setter);
  };

  this.property = function (propertyName, typeCtor, flags, getter, setter) {
    return addProperty(propertyName, new typeCtor(), flags, getter, setter);
  };

  function addProperty (propertyName, propertyType, flags, getter, setter) {
    var property = new PropertyInfo(propertyName, propertyType, flags, getter, setter);
    properties.add(property);
    currentProperty = property;
    return this;
  }

  //endregion

  //region Property rules

  this.required = function (/* message, priority, stopsProcessing */) {
    return addValidation(cr.required, arguments);
  };

  function addValidation (ruleFactory, parameters) {
    if (!currentProperty)
      throw new Error('The current property is undefinable.');
    var args = Array.prototype.slice.call(parameters);
    args.unshift(currentProperty);
    rules.add(ruleFactory.apply(args));
    return this;
  }

  //endregion

  //region Object rules

  this.canCreate = function (/* ruleFactory, [params], methodName, message, priority, stopsProcessing */) {
    return addRule1(Action.createObject, arguments);
  };

  this.canUpdate = function (/* ruleFactory, [params], methodName, message, priority, stopsProcessing */) {
    return addRule1(Action.updateObject, arguments);
  };

  this.canRemove = function (/* ruleFactory, [params], methodName, message, priority, stopsProcessing */) {
    return addRule1(Action.removeObject, arguments);
  };

  function addRule1 (action, parameters) {
    var args = Array.prototype.slice.call(parameters);
    var ruleFactory = args.shift();
    args.unshift(action, null);
    rules.add(ruleFactory.apply(args));
    return nonProperty();
  }

  this.canFetch = function (/* [methodName], ruleFactory, [params], message, priority, stopsProcessing */) {
    return addRule2(Action.fetchObject, 'fetch', arguments);
  };

  this.canExecute = function (/* [methodName], ruleFactory, [params], message, priority, stopsProcessing */) {
    return addRule2(Action.fetchObject, 'execute', arguments);
  };

  function addRule2 (action, defaultMethod, parameters) {
    var args = Array.prototype.slice.call(parameters);
    var methodName = typeof args[0] === 'string' ? args.shift() : defaultMethod;
    var ruleFactory = args.shift();
    args.unshift(action, methodName);
    rules.add(ruleFactory.apply(args));
    return nonProperty();
  }

  //endregion

  //region Extensions

  this.daoBuilder = function (daoBuilder) {
    extensions.daoBuilder = daoBuilder;
    return nonProperty();
  };

  this.toDto = function (toDto) {
    extensions.toDto = toDto;
    return nonProperty();
  };

  this.fromDto = function (fromDto) {
    extensions.fromDto = fromDto;
    return nonProperty();
  };

  this.toCto = function (toCto) {
    extensions.toCto = toCto;
    return nonProperty();
  };

  this.fromCto = function (fromCto) {
    extensions.fromCto = fromCto;
    return nonProperty();
  };

  this.dataCreate = function (dataCreate) {
    extensions.dataCreate = dataCreate;
    return nonProperty();
  };

  this.dataFetch = function (dataFetch) {
    extensions.dataFetch = dataFetch;
    return nonProperty();
  };

  this.dataInsert = function (dataInsert) {
    extensions.dataInsert = dataInsert;
    return nonProperty();
  };

  this.dataUpdate = function (dataUpdate) {
    extensions.dataUpdate = dataUpdate;
    return nonProperty();
  };

  this.dataRemove = function (dataRemove) {
    extensions.dataRemove = dataRemove;
    return nonProperty();
  };

  this.dataExecute = function (dataExecute) {
    extensions.dataExecute = dataExecute;
    return nonProperty();
  };

  //endregion

  function nonProperty () {
    currentProperty = null;
    return this;
  }

  this.compose = function () {
    switch (argsType) {
      case ArgsType.businessObject:
        return new modelType(modelName, properties, rules, extensions);
      case ArgsType.rootCollection:
        return new modelType(modelName, itemsType, rules, extensions);
      case ArgsType.childCollection:
        return new modelType(modelName, itemsType);
    }
  };
}
//util.inherits(ModelComposer, ComposerBase);

module.exports = ModelBase;
<|endoftext|>


<commit_before>import './app/index';
import '../main/index';
<commit_msg>[DDW-169] Remove main index load from rendering process<commit_after>import './app/index';
<|endoftext|>


<commit_before>/*
	While the session contains a list of every ImportantEvent that happens inside of it,
	THIS object contains a list of every ImportantEvent the Observer has decided to change.

	it can also compare two important events to see if they are the same.

	TODO: ~~~~~~~~~~~~~~~~~ HAVE AB COMMENT ON SESSIONS THAT HAVE THIS AVAILABLE. " Shit. That went south fast. I better tell JR."

	When I described this to a friend they said "aren't you worried this will turn into a bucket of spiders?".
	(.i.e become intractably complicated and impossible to debug)
	My response: "This has always been a bucket of spidres, I just decided to dump the whole thing on my head and do a little dance with it."

	This is such a stupid idea. So many things can go wrong.  But it's so irresistable. I NEED to make ridiculous ground hog day time shenanigans possible. It is my destiny.

	hrmm...if time playered triggered, maybe can add evil actions, like Damara was doing.
	dirupt ectobiology. kill players, etc. could trigger some godtiers
*/
var yyrEventsGlobalVar = [];

function YellowYardResultController(){
    this.eventsToUndo = [];

    this.doesEventNeedToBeUndone = function(e){
    //  console.log("Does: " + e.humanLabel() + " need to be undone?")
        for(var i = 0; i<this.eventsToUndo.length; i++){
          var e2 = this.eventsToUndo[i];
		 // console.log("checking if needs to be undone")
          if(doEventsMatch(e,e2,true)){
          //  console.log("retunning event that will provide alternate scene, " + e2.humanLabel())
              return e2;
          }
        }
        return null;
    }

}
/*
	This is not perfecct.  A player can, for example, die multiple times with the same mvp power level.
	But i figure if multiple mind-influenced time players warp into save them multiple times (even from one decision), well...time shenanigans.
	it is not unreasonable to imagien 2 timelines that are extremely similar where the Observer made the same choice.
*/
function doEventsMatch(newEvent, storedEvent,spawn){
  console.log("Should I spawn a doomed time clone (if i find a mtach)???: " + spawn)
	//console.log("comparing: '" + newEvent.humanLabel() + "' to '" + storedEvent.humanLabel() + "'")
	if(!newEvent || !storedEvent) return false //can't match if one of them doesn't exist.
  if(newEvent.session.session_id != storedEvent.session.session_id){
    //  console.log("session id did not match.")
      return false;
  }
  //are they the same kind of event
  if(newEvent.constructor.name != storedEvent.constructor.name){
  //  console.log("constructor did not match.")
    return false;
  }
  if(newEvent.mvp_value != storedEvent.mvp_value){
    //  console.log("mvp did not match")
      return false;
  }
  if(newEvent.player && storedEvent.player){
	  //should work even if player is supposed to be null
	  if(newEvent.player.class_name != storedEvent.player.class_name){
		 //console.log("player class did not match")
		  return false;
	  }

	    if(newEvent.player.aspect != storedEvent.player.aspect){
    //  console.log("player aspect did not match")
		return false;
		}
    console.log("yes, there is a match.");
    return true;
  }
  if(spawn){ //don't spawn a time cloen if i'm checking for afterlife stuff.
    spawnDoomedTimeClone(newEvent, storedEvent);
  }
  return true;
}

function spawnDoomedTimeClone(newEvent,storedEvent){

    //since i know the events match, make sure my player is up to date with the current session.
    //had a stupidly tragic bug where I was bringing players back in the DEAD SESSION instead of this new version of it.
    storedEvent.player = newEvent.player;
    storedEvent.session = newEvent.session; //cant get space players otherwise
    //trigger the new sessions timePlayer.  time shenanigans wear on sanaity.
    var alphaTimePlayer = findAspectPlayer(newEvent.session.players, "Time");
    alphaTimePlayer.triggerLevel += 1; //how many re-dos does this give me before they snap?
    console.log("pushing a doomed time clone, before size: " + alphaTimePlayer.doomedTimeClones.length )
    alphaTimePlayer.doomedTimeClones.push(storedEvent.doomedTimeClone);
    this.timePlayer.flipOut("their own doomed time clones that seem to be mind controlled or something")
    if(storedEvent.secondTimeClone){
        console.log("think there is a second time clone")
        alphaTimePlayer.doomedTimeClones.push(storedEvent.secondTimeClone);
    }
    console.log("done a doomed time clone, after size: " + alphaTimePlayer.doomedTimeClones.length )
}

function decision(){
  var a =$("input[name='decision']:checked").val()
  var index = parseInt(a);
  if(a<yyrEventsGlobalVar.length){
    var eventDecided = yyrEventsGlobalVar[parseInt(a)];
    //alert(eventDecided.humanLabel());
    curSessionGlobalVar.addEventToUndoAndReset(eventDecided);
  }else{
    //undoing undoing an event.
    index = index - yyrEventsGlobalVar.length
    var eventToUndo2x = curSessionGlobalVar.yellowYardController.eventsToUndo[index];
    eventToUndo2x.secondTimeClone = curSessionGlobalVar.importantEvents[0].doomedTimeClone;
    curSessionGlobalVar.addEventToUndoAndReset(null);
  }

}
<commit_msg>okay, having doomed time clones help with boss fights again seems an easy fix, i think i can do a hot fix to the main branch even<commit_after>/*
	While the session contains a list of every ImportantEvent that happens inside of it,
	THIS object contains a list of every ImportantEvent the Observer has decided to change.

	it can also compare two important events to see if they are the same.

	TODO: ~~~~~~~~~~~~~~~~~ HAVE AB COMMENT ON SESSIONS THAT HAVE THIS AVAILABLE. " Shit. That went south fast. I better tell JR."

	When I described this to a friend they said "aren't you worried this will turn into a bucket of spiders?".
	(.i.e become intractably complicated and impossible to debug)
	My response: "This has always been a bucket of spidres, I just decided to dump the whole thing on my head and do a little dance with it."

	This is such a stupid idea. So many things can go wrong.  But it's so irresistable. I NEED to make ridiculous ground hog day time shenanigans possible. It is my destiny.

	hrmm...if time playered triggered, maybe can add evil actions, like Damara was doing.
	dirupt ectobiology. kill players, etc. could trigger some godtiers
*/
var yyrEventsGlobalVar = [];

function YellowYardResultController(){
    this.eventsToUndo = [];

    this.doesEventNeedToBeUndone = function(e){
    //  console.log("Does: " + e.humanLabel() + " need to be undone?")
        for(var i = 0; i<this.eventsToUndo.length; i++){
          var e2 = this.eventsToUndo[i];
		 // console.log("checking if needs to be undone")
          if(doEventsMatch(e,e2,true)){
          //  console.log("retunning event that will provide alternate scene, " + e2.humanLabel())
              return e2;
          }
        }
        return null;
    }

}
/*
	This is not perfecct.  A player can, for example, die multiple times with the same mvp power level.
	But i figure if multiple mind-influenced time players warp into save them multiple times (even from one decision), well...time shenanigans.
	it is not unreasonable to imagien 2 timelines that are extremely similar where the Observer made the same choice.
*/
function doEventsMatch(newEvent, storedEvent,spawn){
	//console.log("comparing: '" + newEvent.humanLabel() + "' to '" + storedEvent.humanLabel() + "'")
	if(!newEvent || !storedEvent) return false //can't match if one of them doesn't exist.
  if(newEvent.session.session_id != storedEvent.session.session_id){
    //  console.log("session id did not match.")
      return false;
  }
  //are they the same kind of event
  if(newEvent.constructor.name != storedEvent.constructor.name){
  //  console.log("constructor did not match.")
    return false;
  }
  if(newEvent.mvp_value != storedEvent.mvp_value){
    //  console.log("mvp did not match")
      return false;
  }
  if(newEvent.player && storedEvent.player){
	  //should work even if player is supposed to be null
	  if(newEvent.player.class_name != storedEvent.player.class_name){
		 //console.log("player class did not match")
		  return false;
	  }

	    if(newEvent.player.aspect != storedEvent.player.aspect){
    //  console.log("player aspect did not match")
		return false;
		}
    console.log("yes, there is a match.");
    if(spawn){ //don't spawn a time cloen if i'm checking for afterlife stuff.
      spawnDoomedTimeClone(newEvent, storedEvent);
    }
    return true;
  }
  if(spawn){ //don't spawn a time cloen if i'm checking for afterlife stuff.
    spawnDoomedTimeClone(newEvent, storedEvent);
  }
  return true;
}

function spawnDoomedTimeClone(newEvent,storedEvent){
    console.log("spawning a doomed time clone")
    //since i know the events match, make sure my player is up to date with the current session.
    //had a stupidly tragic bug where I was bringing players back in the DEAD SESSION instead of this new version of it.
    storedEvent.player = newEvent.player;
    storedEvent.session = newEvent.session; //cant get space players otherwise
    //trigger the new sessions timePlayer.  time shenanigans wear on sanaity.
    var alphaTimePlayer = findAspectPlayer(newEvent.session.players, "Time");
    alphaTimePlayer.triggerLevel += 1; //how many re-dos does this give me before they snap?
    console.log("pushing a doomed time clone, before size: " + alphaTimePlayer.doomedTimeClones.length )
    alphaTimePlayer.doomedTimeClones.push(storedEvent.doomedTimeClone);
    alphaTimePlayer.flipOut("their own doomed time clones that seem to be mind controlled or something")
    if(storedEvent.secondTimeClone){
        console.log("think there is a second time clone")
        alphaTimePlayer.doomedTimeClones.push(storedEvent.secondTimeClone);
    }
    console.log("done a doomed time clone, after size: " + alphaTimePlayer.doomedTimeClones.length )
}

function decision(){
  var a =$("input[name='decision']:checked").val()
  var index = parseInt(a);
  if(a<yyrEventsGlobalVar.length){
    var eventDecided = yyrEventsGlobalVar[parseInt(a)];
    //alert(eventDecided.humanLabel());
    curSessionGlobalVar.addEventToUndoAndReset(eventDecided);
  }else{
    //undoing undoing an event.
    index = index - yyrEventsGlobalVar.length
    var eventToUndo2x = curSessionGlobalVar.yellowYardController.eventsToUndo[index];
    eventToUndo2x.secondTimeClone = curSessionGlobalVar.importantEvents[0].doomedTimeClone;
    curSessionGlobalVar.addEventToUndoAndReset(null);
  }

}
<|endoftext|>


<commit_before>'use strict';

jest.disableAutomock();

import * as actions from '../../../actions/ideaActions';
import * as types from '../../../actions/actionTypes';

describe('idea actions', function() {

  it('should be find an actions file', function() {
    expect(actions).toBeDefined();
  });

  it('should create an action to add an idea', function() {
    const idea = 'My first idea';
    const expectedAction = {
      type: types.ADD,
      data: idea
    };
    expect(actions.add(idea)).toEqual(expectedAction);
  });

  it('should create an action to save an idea', function() {
    const index = 1;
    const idea = 'My second idea';
    const expectedAction = {
      type: types.SAVE,
      data: {
        idea,
        index
      }
    };
    expect(actions.save(idea, index)).toEqual(expectedAction);
  });

  it('should create an action to remove an idea', function() {
    const index = 1;
    const expectedAction = {
      type: types.REMOVE,
      data: index
    };
    expect(actions.remove(index)).toEqual(expectedAction);
  });

  it('should create an action to reset the idea list', function() {
    const expectedAction = {
      type: types.RESET
    };
    expect(actions.reset()).toEqual(expectedAction);
  });
});
<commit_msg>Fix typo<commit_after>'use strict';

jest.disableAutomock();

import * as actions from '../../../actions/ideaActions';
import * as types from '../../../actions/actionTypes';

describe('idea actions', function() {
  it('should be find an actions file', function() {
    expect(actions).toBeDefined();
  });

  it('should create an action to add an idea', function() {
    const idea = 'My first idea';
    const expectedAction = {
      type: types.ADD,
      data: idea
    };
    expect(actions.add(idea)).toEqual(expectedAction);
  });

  it('should create an action to save an idea', function() {
    const index = 1;
    const idea = 'My second idea';
    const expectedAction = {
      type: types.SAVE,
      data: {
        idea,
        index
      }
    };
    expect(actions.save(idea, index)).toEqual(expectedAction);
  });

  it('should create an action to remove an idea', function() {
    const index = 1;
    const expectedAction = {
      type: types.REMOVE,
      data: index
    };
    expect(actions.remove(index)).toEqual(expectedAction);
  });

  it('should create an action to reset the idea list', function() {
    const expectedAction = {
      type: types.RESET
    };
    expect(actions.reset()).toEqual(expectedAction);
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/* global define, WorldWind */

/**
 * A ShapefileLayer.
 *
 * @exports ShapefileLayer
 * @author Bruce Schubert
 */
define(['worldwind'],
    function (ww) {
        "use strict";
        /**
         * Constructs a layer for a shapefile.
         * @constructor
         */
        var ShapefileLayer = function (shapefileUrl, layerName, shapeConfigurationCallback) {

                WorldWind.RenderableLayer.call(this, layerName || shapefileUrl);

                this._opacity = 0.25;

                var shapefilePath = shapefileUrl,
                    shapefile = new WorldWind.Shapefile(shapefilePath);

                if (shapeConfigurationCallback === undefined) {
                    shapeConfigurationCallback = function (attributes, record) {
                        var configuration = {};
                        configuration.name = attributes.values.name || attributes.values.Name || attributes.values.NAME;
                        configuration.attributes = new WorldWind.ShapeAttributes(null);
                        // Fill the polygon with a random pastel color.
                        configuration.attributes.interiorColor = new WorldWind.Color(
                            0.375 + 0.5 * Math.random(),
                            0.375 + 0.5 * Math.random(),
                            0.375 + 0.5 * Math.random(),
                            0.25);

                        // Paint the outline in a darker variant of the interior color.
                        configuration.attributes.outlineColor = new WorldWind.Color(
                            0.5 * configuration.attributes.interiorColor.red,
                            0.5 * configuration.attributes.interiorColor.green,
                            0.5 * configuration.attributes.interiorColor.blue,
                            0.5);

                        // Make the DBaseRecord and Layer available to picked objects
                        configuration.userProperties = {record: attributes, layer: record.shapefile.layer};

                        return configuration;
                    };
                }

                // Create renderables for all the features in the shapefile
                // and add them to this layer.
                shapefile.load(null, shapeConfigurationCallback, this);

            }
            ;

        // Inherit the RenderableLayer methods
        ShapefileLayer.prototype = Object.create(WorldWind.RenderableLayer.prototype);

        /**
         * Overrides the RenderableLayer opacity member to set the alpha channel on the shapefile's feature colors.
         */
        Object.defineProperties(ShapefileLayer.prototype, {
            opacity: {
                get: function () {
                    return this._opacity;
                },
                set: function (value) {
                    this._opacity = value;
                    if (this.renderables) {
                        for (var i = 0, len = this.renderables.length; i < len; i++) {
                            if (this.renderables[i].attributes) {
                                this.renderables[i].attributes.interiorColor.alpha = this._opacity;
                                // We must set the SurfaceShape's stateKeyInvalid flag to true when attributes change
                                this.renderables[i].attributes.stateKeyInvalid = true;
                            }
                        }
                    }

                }
            }

        });

        return ShapefileLayer;
    }
);<commit_msg>Minor code formatting.<commit_after>/*
 * Copyright (c) 2016 Bruce Schubert.
 * The MIT License
 * http://www.opensource.org/licenses/mit-license
 */

/* global define, WorldWind */

/**
 * A ShapefileLayer.
 *
 * @exports ShapefileLayer
 * @author Bruce Schubert
 */
define(['worldwind'],
    function (ww) {
        "use strict";
        /**
         * Constructs a layer for a shapefile.
         * @constructor
         */
        var ShapefileLayer = function (shapefileUrl, layerName, shapeConfigurationCallback) {

            WorldWind.RenderableLayer.call(this, layerName || shapefileUrl);

            this._opacity = 0.25;

            var shapefilePath = shapefileUrl,
                shapefile = new WorldWind.Shapefile(shapefilePath);

            if (shapeConfigurationCallback === undefined) {
                shapeConfigurationCallback = function (attributes, record) {
                    var configuration = {};
                    configuration.name = attributes.values.name || attributes.values.Name || attributes.values.NAME;
                    configuration.attributes = new WorldWind.ShapeAttributes(null);
                    // Fill the polygon with a random pastel color.
                    configuration.attributes.interiorColor = new WorldWind.Color(
                        0.375 + 0.5 * Math.random(),
                        0.375 + 0.5 * Math.random(),
                        0.375 + 0.5 * Math.random(),
                        0.25);

                    // Paint the outline in a darker variant of the interior color.
                    configuration.attributes.outlineColor = new WorldWind.Color(
                        0.5 * configuration.attributes.interiorColor.red,
                        0.5 * configuration.attributes.interiorColor.green,
                        0.5 * configuration.attributes.interiorColor.blue,
                        0.5);

                    // Make the DBaseRecord and Layer available to picked objects
                    configuration.userProperties = {record: attributes, layer: record.shapefile.layer};

                    return configuration;
                };
            }

            // Create renderables for all the features in the shapefile
            // and add them to this layer.
            shapefile.load(null, shapeConfigurationCallback, this);

        };

        // Inherit the RenderableLayer methods
        ShapefileLayer.prototype = Object.create(WorldWind.RenderableLayer.prototype);

        /**
         * Overrides the RenderableLayer opacity member to set the alpha channel on the shapefile's feature colors.
         */
        Object.defineProperties(ShapefileLayer.prototype, {
            opacity: {
                get: function () {
                    return this._opacity;
                },
                set: function (value) {
                    this._opacity = value;
                    if (this.renderables) {
                        for (var i = 0, len = this.renderables.length; i < len; i++) {
                            if (this.renderables[i].attributes) {
                                this.renderables[i].attributes.interiorColor.alpha = this._opacity;
                                // We must set the SurfaceShape's stateKeyInvalid flag to true when attributes change
                                this.renderables[i].attributes.stateKeyInvalid = true;
                            }
                        }
                    }
                }
            }

        });

        return ShapefileLayer;
    }
);<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var config=require('../tsconfig.json');
var qs = require('querystring');

var mongoose = require ('mongoose');

var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
// we're connected! Create your schemas and models here
});

var db=mongoose.connect(config.connectionString);
console.log("db connected!");

var songsSchema = require('../DataBase/songModel');
var songsList = mongoose.model('songs',songsSchema);

/*songsList.find({},function(err,songs){
    console.log(songs);
});*/

//routing

router.get('/loadSongs/:name', loadSongs);
router.get('/loadChords/:name', loadChords);
router.post('/addsong', addsong);
router.get('/loadAllSongs', loadAllSongs);
router.post('/deleteSong', deleteSong);
router.get('/loadType/:name', loadType);
router.get('/loadSort/:name', loadSort);
router.post('/loadSongByNames', loadSongByNames);

module.exports = router;

//for admin page
function loadAllSongs(req, res) {
    console.log("in loadallsongs functiom");
    //Getting all songs from database in songs array
    songsList.find({}, function (err, all) {
        if (err)
            res.send(err);
        //console.log(all);
        res.json(all); // return the songs in JSON format
    });
}
function deleteSong(req, res){
    console.log("in delete server")
    var body = '';
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {

        var POST = qs.parse(body);
        console.log(POST);
        songsList.remove({'name': POST.name,'artistsName': POST.artistName},function(err, result) {
            if (err) {
                res.send(err);
            }
            console.log("song deleted");
            res.send("האקורדים לשיר "+" '"+POST.name+"' "+"של "+POST.artistName+" נמחקו מהמאגר");
        });
    });
}
function loadSongByNames(req, res) {
    console.log("in loadSongByNames")
    var body = '';
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {

        var POST = qs.parse(body);
        console.log(POST);
        songsList.find({'name':POST.name ,'artistsName': POST.artistName}, function (err, songs) {
            if (err)
                res.send(err);
            console.log(songs);
            res.json(songs); // return the songs in JSON format
        });

    });
}

//*************************************************************************
function loadSongs(req, res) {
    //Getting all songs from artist collection and put in songs array
    var name = req.params.name;
    songsList.find({'artistsName': name}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadType(req, res) {
    //Getting all songs from artist collection and put in songs array
    var type = req.params.name;
    songsList.find({'type': type}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadSort(req, res) {
    //Getting all songs from artist collection and put in songs array
    var char = req.params.name;
    songsList.find({}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadChords(req, res) {
    //Getting song data from songs collection and put in songs array
    var name = req.params.name;
    var artistName = req.params.artistName;
    songsList.find({'name': name}, function (err, song) {
        if (err)
            res.send(err);
        console.log(song);
        res.json(song); // return the songs in JSON format
    });
}

function addsong(req,res) {
    //add song to database
    console.log("get post request in server side");
    var body = '';
    req.on('data', function (data) {
        body += data;
    });

    req.on('end', function () {
        var POST = qs.parse(body);
        var artist=POST.artistName;
        var parsLines=JSON.parse(POST.lines);
        console.log(parsLines);
        var lines=[];

        var link=getId(POST.link);

        //validation and save in database
        songsList.find({'name': POST.name,'artistsName': artist}, function (err, song) {
            if (err)
                res.send(err);
            if(song[0]!=null) {
                console.log("song already exist");
                res.send("אתה מנסה להוסיף אקורדים לשיר שכבר קיימים לו אקורדים במאגר.");
            }
            else {
                newSong.save();

                console.log("song added");
                res.send("האקורדים לשיר "+" '"+POST.name+"' "+"של "+artist+" התווספו בהצלחה!");

                }
        });

    });

}

function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);

    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return 'error';
    }
}

<commit_msg>link change<commit_after>var express = require('express');
var router = express.Router();
var config=require('../tsconfig.json');
var qs = require('querystring');

var mongoose = require ('mongoose');

var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
// we're connected! Create your schemas and models here
});

var db=mongoose.connect(config.connectionString);
console.log("db connected!");

var songsSchema = require('../DataBase/songModel');
var songsList = mongoose.model('songs',songsSchema);

/*songsList.find({},function(err,songs){
    console.log(songs);
});*/

//routing

router.get('/loadSongs/:name', loadSongs);
router.get('/loadChords/:name', loadChords);
router.post('/addsong', addsong);
router.get('/loadAllSongs', loadAllSongs);
router.post('/deleteSong', deleteSong);
router.get('/loadType/:name', loadType);
router.get('/loadSort/:name', loadSort);
router.post('/loadSongByNames', loadSongByNames);

module.exports = router;

//for admin page
function loadAllSongs(req, res) {
    console.log("in loadallsongs functiom");
    //Getting all songs from database in songs array
    songsList.find({}, function (err, all) {
        if (err)
            res.send(err);
        //console.log(all);
        res.json(all); // return the songs in JSON format
    });
}
function deleteSong(req, res){
    console.log("in delete server")
    var body = '';
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {

        var POST = qs.parse(body);
        console.log(POST);
        songsList.remove({'name': POST.name,'artistsName': POST.artistName},function(err, result) {
            if (err) {
                res.send(err);
            }
            console.log("song deleted");
            res.send("האקורדים לשיר "+" '"+POST.name+"' "+"של "+POST.artistName+" נמחקו מהמאגר");
        });
    });
}
function loadSongByNames(req, res) {
    console.log("in loadSongByNames")
    var body = '';
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {

        var POST = qs.parse(body);
        console.log(POST);
        songsList.find({'name':POST.name ,'artistsName': POST.artistName}, function (err, songs) {
            if (err)
                res.send(err);
            console.log(songs);
            res.json(songs); // return the songs in JSON format
        });

    });
}

//*************************************************************************
function loadSongs(req, res) {
    //Getting all songs from artist collection and put in songs array
    var name = req.params.name;
    songsList.find({'artistsName': name}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadType(req, res) {
    //Getting all songs from artist collection and put in songs array
    var type = req.params.name;
    songsList.find({'type': type}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadSort(req, res) {
    //Getting all songs from artist collection and put in songs array
    var char = req.params.name;
    songsList.find({}, function (err, songs) {
        if (err)
            res.send(err);
        console.log(songs);
        res.json(songs); // return the songs in JSON format
    });
}

function loadChords(req, res) {
    //Getting song data from songs collection and put in songs array
    var name = req.params.name;
    var artistName = req.params.artistName;
    songsList.find({'name': name}, function (err, song) {
        if (err)
            res.send(err);
        console.log(song);
        res.json(song); // return the songs in JSON format
    });
}

function addsong(req,res) {
    //add song to database
    console.log("get post request in server side");
    var body = '';
    req.on('data', function (data) {
        body += data;
    });

    req.on('end', function () {
        var POST = qs.parse(body);
        var artist=POST.artistName;
        var parsLines=JSON.parse(POST.lines);
        console.log(parsLines);
        var lines=[];

        var link=getId(POST.link);

        //validation and save in database
        songsList.find({'name': POST.name,'artistsName': artist}, function (err, song) {
            if (err)
                res.send(err);
            if(song[0]!=null) {
                console.log("song already exist");
                res.send("אתה מנסה להוסיף אקורדים לשיר שכבר קיימים לו אקורדים במאגר.");
            }
            else {
                var newSong = new songsList({name: POST.name, artistsName: artist, type:POST.type, link: link, lines: parsLines});
                newSong.save();

                console.log("song added");
                res.send("האקורדים לשיר "+" '"+POST.name+"' "+"של "+artist+" התווספו בהצלחה!");

                }
        });

    });

}

function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);

    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return 'error';
    }
}

<|endoftext|>


<commit_before>var net = require('net');
require('js-yaml');

// Import settings file
var settings = require('./config/server.yaml');

var server = net.createServer(function(c) { //'connection' listener
  console.log('server connected');
  c.on('end', function() {
    console.log('server disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});

server.listen(settings.port, function() { //'listening' listener
  console.log('server bound');
});<commit_msg>HTTP module for AXIS Camera<commit_after>var http = require('http');
var net  = require('net');

require('js-yaml');

// Import settings file
var settings = require('./config/server.yaml');

var server = net.createServer(function(c) { //'connection' listener
	console.log('server connected');
	c.on('end', function() {
		console.log('server disconnected');
	});
	c.write('hello\r\n');
	c.pipe(c);
});

server.listen(settings.port, function() { //'listening' listener
	console.log('server bound');
});<|endoftext|>


<commit_before>/***
 This will reset the preferences that have been removed completely from the ghacks user.js.

 Last updated: 30-Jan-2019

 For instructions see:
 https://github.com/ghacksuserjs/ghacks-user.js/wiki/3.1-Resetting-Inactive-Prefs-[Scripts]
***/

(function() {
  let ops = [
    /* removed in ghacks user.js v52-57 */
    /* 52-alpha */
    'browser.search.reset.enabled',
    'browser.search.reset.whitelist',
    /* 54-alpha */
    'browser.migrate.automigrate.enabled',
    'services.sync.enabled',
    'webextensions.storage.sync.enabled',
    'webextensions.storage.sync.serverURL',
    /* 55-alpha */
    'dom.keyboardevent.dispatch_during_composition', // default is false anyway
    'dom.vr.oculus.enabled', // covered by dom.vr.enabled
    'dom.vr.openvr.enabled', // ditto
    'dom.vr.osvr.enabled', // ditto
    'extensions.pocket.api', // covered by extensions.pocket.enabled
    'extensions.pocket.oAuthConsumerKey', // ditto
    'extensions.pocket.site', // ditto
    /* 56-alpha: none */
    /* 57-alpha */
    'geo.wifi.xhr.timeout', // covered by geo.enabled
    'browser.search.geoip.timeout', // ditto
    'media.webspeech.recognition.enable', // default is false anyway
    'gfx.layerscope.enabled', // default is false anyway
    /* 58-alpha */
    //  excluding these e10 settings
       // 'browser.tabs.remote.autostart',
       // 'browser.tabs.remote.autostart.2',
       // 'browser.tabs.remote.force-enable',
       // 'browser.tabs.remote.separateFileUriProcess',
       // 'extensions.e10sBlocksEnabling',
       // 'extensions.webextensions.remote',
       // 'dom.ipc.processCount',
       // 'dom.ipc.shims.enabledWarnings',
       // 'dom.ipc.processCount.extension',
       // 'dom.ipc.processCount.file',
       // 'security.sandbox.content.level',
       // 'dom.ipc.plugins.sandbox-level.default',
       // 'dom.ipc.plugins.sandbox-level.flash',
       // 'security.sandbox.logging.enabled',
    'dom.presentation.controller.enabled',
    'dom.presentation.discoverable',
    'dom.presentation.discovery.enabled',
    'dom.presentation.enabled',
    'dom.presentation.receiver.enabled',
    'dom.presentation.session_transport.data_channel.enable',
    /* 59-alpha */
    'browser.stopReloadAnimation.enabled',
    'browser.tabs.insertRelatedAfterCurrent',
    'browser.tabs.loadDivertedInBackground',
    'browser.tabs.loadInBackground',
    'browser.tabs.selectOwnerOnClose',
    'browser.urlbar.clickSelectsAll',
    'browser.urlbar.doubleClickSelectsAll',
    'media.flac.enabled',
    'media.mediasource.enabled',
    'media.mediasource.mp4.enabled',
    'media.mediasource.webm.audio.enabled',
    'media.mediasource.webm.enabled',
    'media.mp4.enabled',
    'media.ogg.enabled',
    'media.ogg.flac.enabled',
    'media.opus.enabled',
    'media.raw.enabled',
    'media.wave.enabled',
    'media.webm.enabled',
    'media.wmf.amd.vp9.enabled',
    'media.wmf.enabled',
    'media.wmf.vp9.enabled',
    'ui.submenuDelay',
    /* 60-beta - these were all at default anyway */
    'device.storage.enabled',
    'general.useragent.compatMode.firefox',
    'network.dns.blockDotOnion',
    'network.stricttransportsecurity.preloadlist',
    'security.block_script_with_wrong_mime',
    'security.fileuri.strict_origin_policy',
    'security.sri.enable',
    /* 61-beta */
    'browser.laterrun.enabled',
    'browser.offline-apps.notify',
    'browser.rights.3.shown',
    'browser.slowStartup.maxSamples',
    'browser.slowStartup.notificationDisabled',
    'browser.slowStartup.samples',
    'browser.storageManager.enabled',
    'dom.allow_scripts_to_close_windows',
    'dom.disable_window_flip',
    'network.http.fast-fallback-to-IPv4',
    'offline-apps.quota.warn',
    'services.blocklist.signing.enforced',
    /* 62-beta */
    'browser.urlbar.autoFill.typed',
    'security.tls.version.fallback-limit',
    /* 63-beta */
    'extensions.webextensions.keepStorageOnUninstall',
    'extensions.webextensions.keepUuidOnUninstall',
    'privacy.trackingprotection.ui.enabled',
    /* 64-beta */
    'browser.eme.ui.enabled',
    'browser.sessionstore.max_windows_undo',
    'network.auth.subresource-img-cross-origin-http-auth-allow',
    'media.peerconnection.ice.tcp',
    'media.peerconnection.identity.enabled',
    'media.peerconnection.identity.timeout',
    'media.peerconnection.turn.disable',
    'media.peerconnection.use_document_iceservers',
    'media.peerconnection.video.enabled',
    'media.navigator.video.enabled',
    /* 65-beta */
    'browser.contentblocking.enabled',
    'browser.urlbar.maxHistoricalSearchSuggestions',
    /* reset parrot: check your open about:config after running the script */
    '_user.js.parrot'
  ]

  if("undefined" === typeof(Services)) {
    alert("about:config needs to be the active tab!");
    return;
  }

  let c = 0;
  for (let i = 0, len = ops.length; i < len; i++) {
    if (Services.prefs.prefHasUserValue(ops[i])) {
      Services.prefs.clearUserPref(ops[i]);
      if (!Services.prefs.prefHasUserValue(ops[i])) {
        console.log("reset", ops[i]);
        c++;
      } else { console.log("failed to reset", ops[i]); }
    }
  }

  focus();

  let d = (c==1) ? " pref" : " prefs";
  if (c > 0) {
    alert("successfully reset " + c + d + "\n\nfor details check the Browser Console (Ctrl+Shift+J)");
  } else { alert("nothing to reset"); }

})();
<commit_msg>canvas.capturestream.enabled<commit_after>/***
 This will reset the preferences that have been removed completely from the ghacks user.js.

 Last updated: 22-Apr-2019

 For instructions see:
 https://github.com/ghacksuserjs/ghacks-user.js/wiki/3.1-Resetting-Inactive-Prefs-[Scripts]
***/

(function() {
  let ops = [
    /* removed in ghacks user.js v52-57 */
    /* 52-alpha */
    'browser.search.reset.enabled',
    'browser.search.reset.whitelist',
    /* 54-alpha */
    'browser.migrate.automigrate.enabled',
    'services.sync.enabled',
    'webextensions.storage.sync.enabled',
    'webextensions.storage.sync.serverURL',
    /* 55-alpha */
    'dom.keyboardevent.dispatch_during_composition', // default is false anyway
    'dom.vr.oculus.enabled', // covered by dom.vr.enabled
    'dom.vr.openvr.enabled', // ditto
    'dom.vr.osvr.enabled', // ditto
    'extensions.pocket.api', // covered by extensions.pocket.enabled
    'extensions.pocket.oAuthConsumerKey', // ditto
    'extensions.pocket.site', // ditto
    /* 56-alpha: none */
    /* 57-alpha */
    'geo.wifi.xhr.timeout', // covered by geo.enabled
    'browser.search.geoip.timeout', // ditto
    'media.webspeech.recognition.enable', // default is false anyway
    'gfx.layerscope.enabled', // default is false anyway
    /* 58-alpha */
    //  excluding these e10 settings
       // 'browser.tabs.remote.autostart',
       // 'browser.tabs.remote.autostart.2',
       // 'browser.tabs.remote.force-enable',
       // 'browser.tabs.remote.separateFileUriProcess',
       // 'extensions.e10sBlocksEnabling',
       // 'extensions.webextensions.remote',
       // 'dom.ipc.processCount',
       // 'dom.ipc.shims.enabledWarnings',
       // 'dom.ipc.processCount.extension',
       // 'dom.ipc.processCount.file',
       // 'security.sandbox.content.level',
       // 'dom.ipc.plugins.sandbox-level.default',
       // 'dom.ipc.plugins.sandbox-level.flash',
       // 'security.sandbox.logging.enabled',
    'dom.presentation.controller.enabled',
    'dom.presentation.discoverable',
    'dom.presentation.discovery.enabled',
    'dom.presentation.enabled',
    'dom.presentation.receiver.enabled',
    'dom.presentation.session_transport.data_channel.enable',
    /* 59-alpha */
    'browser.stopReloadAnimation.enabled',
    'browser.tabs.insertRelatedAfterCurrent',
    'browser.tabs.loadDivertedInBackground',
    'browser.tabs.loadInBackground',
    'browser.tabs.selectOwnerOnClose',
    'browser.urlbar.clickSelectsAll',
    'browser.urlbar.doubleClickSelectsAll',
    'media.flac.enabled',
    'media.mediasource.enabled',
    'media.mediasource.mp4.enabled',
    'media.mediasource.webm.audio.enabled',
    'media.mediasource.webm.enabled',
    'media.mp4.enabled',
    'media.ogg.enabled',
    'media.ogg.flac.enabled',
    'media.opus.enabled',
    'media.raw.enabled',
    'media.wave.enabled',
    'media.webm.enabled',
    'media.wmf.amd.vp9.enabled',
    'media.wmf.enabled',
    'media.wmf.vp9.enabled',
    'ui.submenuDelay',
    /* 60-beta - these were all at default anyway */
    'device.storage.enabled',
    'general.useragent.compatMode.firefox',
    'network.dns.blockDotOnion',
    'network.stricttransportsecurity.preloadlist',
    'security.block_script_with_wrong_mime',
    'security.fileuri.strict_origin_policy',
    'security.sri.enable',
    /* 61-beta */
    'browser.laterrun.enabled',
    'browser.offline-apps.notify',
    'browser.rights.3.shown',
    'browser.slowStartup.maxSamples',
    'browser.slowStartup.notificationDisabled',
    'browser.slowStartup.samples',
    'browser.storageManager.enabled',
    'dom.allow_scripts_to_close_windows',
    'dom.disable_window_flip',
    'network.http.fast-fallback-to-IPv4',
    'offline-apps.quota.warn',
    'services.blocklist.signing.enforced',
    /* 62-beta */
    'browser.urlbar.autoFill.typed',
    'security.tls.version.fallback-limit',
    /* 63-beta */
    'extensions.webextensions.keepStorageOnUninstall',
    'extensions.webextensions.keepUuidOnUninstall',
    'privacy.trackingprotection.ui.enabled',
    /* 64-beta */
    'browser.eme.ui.enabled',
    'browser.sessionstore.max_windows_undo',
    'network.auth.subresource-img-cross-origin-http-auth-allow',
    'media.peerconnection.ice.tcp',
    'media.peerconnection.identity.enabled',
    'media.peerconnection.identity.timeout',
    'media.peerconnection.turn.disable',
    'media.peerconnection.use_document_iceservers',
    'media.peerconnection.video.enabled',
    'media.navigator.video.enabled',
    /* 65-beta */
    'browser.contentblocking.enabled',
    'browser.urlbar.maxHistoricalSearchSuggestions',
    /* 67-beta */
    'canvas.capturestream.enabled',
    /* reset parrot: check your open about:config after running the script */
    '_user.js.parrot'
  ]

  if("undefined" === typeof(Services)) {
    alert("about:config needs to be the active tab!");
    return;
  }

  let c = 0;
  for (let i = 0, len = ops.length; i < len; i++) {
    if (Services.prefs.prefHasUserValue(ops[i])) {
      Services.prefs.clearUserPref(ops[i]);
      if (!Services.prefs.prefHasUserValue(ops[i])) {
        console.log("reset", ops[i]);
        c++;
      } else { console.log("failed to reset", ops[i]); }
    }
  }

  focus();

  let d = (c==1) ? " pref" : " prefs";
  if (c > 0) {
    alert("successfully reset " + c + d + "\n\nfor details check the Browser Console (Ctrl+Shift+J)");
  } else { alert("nothing to reset"); }

})();
<|endoftext|>


<commit_before>
var Args = require('args-js');
var _ = require('lodash');

var $message = require('./message');

exports.middleware = function(app) {
    return $message.defaultMw(app, function(body, cb) {
        app.peers = app.peers.filter(function(peer) {
            return peer.id != body.id;
        });
        cb(null, {
            status: 'removed'
        });
    });
};

exports.method = function(cb) {
    var args = Args([
        {cb: Args.FUNCTION | Args.Optional, _default: _.noop}
    ], arguments);
    cb = args.cb;

    this.broadcast('left', {
        id: this.id
    }, cb);
};
<commit_msg>remove own peerlist on leave (in case of broadcast, etc)<commit_after>
var Args = require('args-js');
var _ = require('lodash');

var $message = require('./message');

exports.middleware = function(app) {
    return $message.defaultMw(app, function(body, cb) {
        app.peers = app.peers.filter(function(peer) {
            return peer.id != body.id;
        });
        cb(null, {
            status: 'removed'
        });
    });
};

exports.method = function(cb) {
    var args = Args([
        {cb: Args.FUNCTION | Args.Optional, _default: _.noop}
    ], arguments);
    cb = args.cb;

    this.peers = [];
    this.broadcast('left', {
        id: this.id
    }, cb);
};
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')
const exists = fs.existsSync
const esbuild = require('esbuild')
const exec = require('child_process').exec
const glob = require('glob-promise')
const crypto = require('crypto')
const branch = require('git-branch')

const loader = require('./setup/loaders')
const shims = require('./setup/shims')

function execShellCommand(cmd) {
  console.log(cmd)
  return new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        console.warn(error)
      }
      resolve(stdout? stdout : stderr)
    })
  })
}

class Gradient {
  constructor(start, end, min, max) {
    this.min = min
    this.max = max
    this.start = this.hexToRgb(start)
    this.end = this.hexToRgb(end)
    this.diff = {
      r: this.end.r - this.start.r,
      g: this.end.g - this.start.g,
      b: this.end.b - this.start.b,
    }
  }

  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  fade(value) {
    return (value - this.min) / (this.max - this.min)
  }

  getColor(value) {
    if (value < this.min) throw new Error(`${value} < ${this.min}`)
    if (value > this.max) throw new Error(`${value} > ${this.max}`)
    const fade = this.fade(value)

    const r = (this.diff.r * fade) + this.start.r
    const g = (this.diff.g * fade) + this.start.g
    const b = (this.diff.b * fade) + this.start.b

    return '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('')
  }
}

function humansize(v) {
  const units = ['b', 'k', 'M', 'G']
  while (units.length > 1 && v > 1024) {
    units.shift()
    v = v / 1024
  }
  return `${Math.round(v)}${units[0]}`
}
function dependencyGraph(metafile) {
  const graph = { nodes: '', edges: '' }
  const node = {}
  function nodeid(module) {
    if (typeof node[module] !== 'number') node[module] = Object.keys(node).length
    return node[module]
  }
  const Wrap = 5000
  let X = 0
  let Y = 0
  let H = 0
  const size = { }
  for (const [module, data] of Object.entries(metafile.inputs)) {
    if (typeof size.min === 'undefined' || data.bytes < size.min) size.min = data.bytes
    if (typeof size.max === 'undefined' || data.bytes > size.max) size.max = data.bytes
  }
  const gradient = new Gradient('#00FF00', '#FF0000', 0, size.max)
  for (const [module, data] of Object.entries(metafile.inputs)) {
    let label = `${module.replace(/^node_modules\//, ':')} (${humansize(data.bytes)})`
    label = JSON.stringify(label)
    const w = 60
    const h = 30
    graph.nodes += `
      node [
        id ${nodeid(module)}
        label ${label}
        graphics [
          x ${X}
          y ${Y}
          w ${w}
          h ${h}
          fill "${gradient.getColor(data.bytes)}"
          outline "#000000"
        ]
      ]
    `
    X += w
    H = h > H ? h : H
    if (X > Wrap) {
      Y += H
      X = 0
      H = 0
    }

    for (const dep of data.imports) {
      graph.edges += `
        edge [
          source ${nodeid(module)}
          target ${nodeid(dep.path)}
        ]
      `
    }
  }
  return `
    graph [
	    hierarchic	1
	    directed	1
      ${graph.nodes}
      ${graph.edges}
    ]
  `
}

function js(src) {
  return src.replace(/[.]ts$/, '.js')
}

async function bundle(config) {
  config = {
    bundle: true,
    format: 'iife',
    // define: { BigInt: 'Number' },
    target: ['firefox60'],
    inject: [],
    treeShaking: true,
    ...config,
  }

  config.inject.push('./setup/loaders/globals.js')

  let target
  if (config.outfile) {
    target = config.outfile
  }
  else if (config.entryPoints.length === 1 && config.outdir) {
    target = path.join(config.outdir, js(path.basename(config.entryPoints[0])))
  }
  else {
    target = `${config.outdir} [${config.entryPoints.map(js).join(', ')}]`
  }

  const exportGlobals = config.exportGlobals
  delete config.exportGlobals
  if (exportGlobals) {
    const esm = await esbuild.build({ ...config, logLevel: 'silent', format: 'esm', metafile: true, write: false })
    if (process.env.GML) {
      console.log('  generating dependency graph', target + '.gml')
      fs.writeFileSync(target + '.gml', dependencyGraph(esm.metafile))
    }
    for (const output of Object.values(esm.metafile.outputs)) {
      if (output.entryPoint) {
        const sep = '$$'
        config.globalName = escape(`{ ${output.exports.sort().join(', ')} }`).replace(/%/g, '$')
        // make these var, not const, so they get hoisted and are available in the global scope.
      }
    }
  }

  const metafile = config.metafile
  config.metafile = true

  console.log('* bundling', target)
  // console.log('  aliasing BigInt to Number for https://github.com/benjamn/ast-types/issues/750')
  const meta = (await esbuild.build(config)).metafile
  if (typeof metafile === 'string') await fs.promises.writeFile(metafile, JSON.stringify(meta, null, 2))
  if (exportGlobals) {
    await fs.promises.writeFile(
      target,
      (await fs.promises.readFile(target, 'utf-8')).replace(config.globalName, unescape(config.globalName.replace(/[$]/g, '%')))
    )
  }
}

async function rebuild() {
  // plugin code
  await bundle({
    entryPoints: [ 'content/better-bibtex.ts' ],
    plugins: [
      loader.trace('plugin'),
      loader.patcher('setup/patches'),
      loader.bibertool,
      loader.bib,
      loader.peggy,
      loader.__dirname,
      shims
    ],
    outdir: 'build/content',
    banner: { js: 'if (!Zotero.BetterBibTeX) {\n' },
    footer: { js: '\n}' },
    metafile: 'gen/plugin.json',
    external: [
      'zotero/itemTree',
    ]
  })

  // worker code
  await bundle({
    entryPoints: [ 'content/worker/zotero.ts' ],
    plugins: [
      loader.trace('worker'),
      loader.patcher('setup/patches'),
      loader.bibertool,
      loader.bib,
      // loader.peggy,
      loader.__dirname,
      shims
    ],
    outdir: 'build/content/worker',
    exportGlobals: true,
    metafile: 'gen/worker.json',
    external: [ 'jsdom' ],
    banner: { js: '\ndump("\\nloading BBT chromeworker\\n")\ntry {\n' },
    footer: { js: '} catch ($$err$$) { dump("\\nerror: failed loading BBT chromeworker: " + $$err$$.message  + "\\n" + $$err$$.stack + "\\n") }\ndump("\\nloaded BBT chromeworker\\n")\n' },
  })

  // translators
  for (const translator of (await glob('translators/*.json')).map(tr => path.parse(tr))) {
    const header = require('./' + path.join(translator.dir, translator.name + '.json'))
    const outfile = path.join('build/resource', translator.name + '.js')

    // https://esbuild.github.io/api/#write
    // https://esbuild.github.io/api/#outbase
    // https://esbuild.github.io/api/#working-directory
    await bundle({
      entryPoints: [path.join(translator.dir, translator.name + '.ts')],
      plugins: [
        // loader.trace('translators'),
        loader.bibertool,
        // loader.peggy,
        loader.__dirname,
        shims
      ],
      outfile,
      banner: { js: `
        if (typeof ZOTERO_TRANSLATOR_INFO === 'undefined') var ZOTERO_TRANSLATOR_INFO = {}; // declare if not declared
        Object.assign(ZOTERO_TRANSLATOR_INFO, ${JSON.stringify(header)}); // assign new data
      `},
      exportGlobals: true,
      metafile: `gen/${translator.name}.json`,
    })

    const source = await fs.promises.readFile(outfile, 'utf-8')
    const checksum = crypto.createHash('sha256')
    checksum.update(source)
    if (!header.configOptions) header.configOptions = {}
    header.configOptions.hash = checksum.digest('hex')
    header.lastUpdated = (new Date).toISOString().replace(/T.*/, '')
    await fs.promises.writeFile(path.join('build/resource', translator.name + '.json'), JSON.stringify(header, null, 2))
  }

  if (await branch() === 'headless') {
    let node_modules = loader.node_modules('setup/patches')
    await bundle({
      platform: 'node',
      // target: ['node12'],
      // inject: [ './headless/inject.js' ],
      plugins: [node_modules.plugin, loader.patcher('setup/patches'), loader.bibertool, loader.peggy ],
      bundle: true,
      globalName: 'Headless',
      entryPoints: [ 'headless/zotero.ts' ],
      outfile: 'gen/headless/zotero.js',
      banner: {
        js: 'var ZOTERO_CONFIG = { GUID: "zotero@" };\n',
      },
      exportGlobals: true,
      metafile: 'gen/headless/zotero.json',
    })
    let external = node_modules.external

    node_modules = loader.node_modules('setup/patches')
    await bundle({
      platform: 'node',
      // target: ['node12'],
      // inject: [ './headless/inject.js' ],
      plugins: [node_modules.plugin, loader.patcher('setup/patches'), loader.bibertool, loader.peggy ],
      bundle: true,
      globalName: 'Headless',
      entryPoints: [ 'headless/index.ts' ],
      outfile: 'gen/headless/index.js',
      metafile: 'gen/headless/index.json',
      banner: {
        js: await fs.promises.readFile('gen/headless/zotero.js', 'utf-8')
      }
    })
    external = [...new Set(external.concat(node_modules.external))].sort()

    const package_json = JSON.parse(await fs.promises.readFile('package.json', 'utf-8'))
    const move = Object.keys(package_json.dependencies).filter(pkg => !external.includes(pkg))
    if (move.length) {
      console.log('  the following packages should be moved to devDependencies')
      for (const pkg of move.sort()) {
        console.log('  *', pkg)
      }
    }
  }
}

rebuild().catch(err => {
  console.log(err)
  process.exit(1)
})
<commit_msg>strip globals from translators<commit_after>const path = require('path')
const fs = require('fs')
const exists = fs.existsSync
const esbuild = require('esbuild')
const exec = require('child_process').exec
const glob = require('glob-promise')
const crypto = require('crypto')
const branch = require('git-branch')

const loader = require('./setup/loaders')
const shims = require('./setup/shims')

function execShellCommand(cmd) {
  console.log(cmd)
  return new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        console.warn(error)
      }
      resolve(stdout? stdout : stderr)
    })
  })
}

class Gradient {
  constructor(start, end, min, max) {
    this.min = min
    this.max = max
    this.start = this.hexToRgb(start)
    this.end = this.hexToRgb(end)
    this.diff = {
      r: this.end.r - this.start.r,
      g: this.end.g - this.start.g,
      b: this.end.b - this.start.b,
    }
  }

  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  fade(value) {
    return (value - this.min) / (this.max - this.min)
  }

  getColor(value) {
    if (value < this.min) throw new Error(`${value} < ${this.min}`)
    if (value > this.max) throw new Error(`${value} > ${this.max}`)
    const fade = this.fade(value)

    const r = (this.diff.r * fade) + this.start.r
    const g = (this.diff.g * fade) + this.start.g
    const b = (this.diff.b * fade) + this.start.b

    return '#' + [r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('')
  }
}

function humansize(v) {
  const units = ['b', 'k', 'M', 'G']
  while (units.length > 1 && v > 1024) {
    units.shift()
    v = v / 1024
  }
  return `${Math.round(v)}${units[0]}`
}
function dependencyGraph(metafile) {
  const graph = { nodes: '', edges: '' }
  const node = {}
  function nodeid(module) {
    if (typeof node[module] !== 'number') node[module] = Object.keys(node).length
    return node[module]
  }
  const Wrap = 5000
  let X = 0
  let Y = 0
  let H = 0
  const size = { }
  for (const [module, data] of Object.entries(metafile.inputs)) {
    if (typeof size.min === 'undefined' || data.bytes < size.min) size.min = data.bytes
    if (typeof size.max === 'undefined' || data.bytes > size.max) size.max = data.bytes
  }
  const gradient = new Gradient('#00FF00', '#FF0000', 0, size.max)
  for (const [module, data] of Object.entries(metafile.inputs)) {
    let label = `${module.replace(/^node_modules\//, ':')} (${humansize(data.bytes)})`
    label = JSON.stringify(label)
    const w = 60
    const h = 30
    graph.nodes += `
      node [
        id ${nodeid(module)}
        label ${label}
        graphics [
          x ${X}
          y ${Y}
          w ${w}
          h ${h}
          fill "${gradient.getColor(data.bytes)}"
          outline "#000000"
        ]
      ]
    `
    X += w
    H = h > H ? h : H
    if (X > Wrap) {
      Y += H
      X = 0
      H = 0
    }

    for (const dep of data.imports) {
      graph.edges += `
        edge [
          source ${nodeid(module)}
          target ${nodeid(dep.path)}
        ]
      `
    }
  }
  return `
    graph [
	    hierarchic	1
	    directed	1
      ${graph.nodes}
      ${graph.edges}
    ]
  `
}

function js(src) {
  return src.replace(/[.]ts$/, '.js')
}

async function bundle(config) {
  config = {
    bundle: true,
    format: 'iife',
    // define: { BigInt: 'Number' },
    target: ['firefox60'],
    inject: [],
    treeShaking: true,
    ...config,
  }

  let target
  if (config.outfile) {
    target = config.outfile
  }
  else if (config.entryPoints.length === 1 && config.outdir) {
    target = path.join(config.outdir, js(path.basename(config.entryPoints[0])))
  }
  else {
    target = `${config.outdir} [${config.entryPoints.map(js).join(', ')}]`
  }

  const exportGlobals = config.exportGlobals
  delete config.exportGlobals
  if (exportGlobals) {
    const esm = await esbuild.build({ ...config, logLevel: 'silent', format: 'esm', metafile: true, write: false })
    if (process.env.GML) {
      console.log('  generating dependency graph', target + '.gml')
      fs.writeFileSync(target + '.gml', dependencyGraph(esm.metafile))
    }
    for (const output of Object.values(esm.metafile.outputs)) {
      if (output.entryPoint) {
        const sep = '$$'
        config.globalName = escape(`{ ${output.exports.sort().join(', ')} }`).replace(/%/g, '$')
        // make these var, not const, so they get hoisted and are available in the global scope.
      }
    }
  }

  const metafile = config.metafile
  config.metafile = true

  console.log('* bundling', target)
  // console.log('  aliasing BigInt to Number for https://github.com/benjamn/ast-types/issues/750')
  const meta = (await esbuild.build(config)).metafile
  if (typeof metafile === 'string') await fs.promises.writeFile(metafile, JSON.stringify(meta, null, 2))
  if (exportGlobals) {
    await fs.promises.writeFile(
      target,
      (await fs.promises.readFile(target, 'utf-8')).replace(config.globalName, unescape(config.globalName.replace(/[$]/g, '%')))
    )
  }
}

async function rebuild() {
  // plugin code
  await bundle({
    entryPoints: [ 'content/better-bibtex.ts' ],
    plugins: [
      loader.trace('plugin'),
      loader.patcher('setup/patches'),
      loader.bibertool,
      loader.bib,
      loader.peggy,
      loader.__dirname,
      shims
    ],
    inject: ['./setup/loaders/globals.js'],
    outdir: 'build/content',
    banner: { js: 'if (!Zotero.BetterBibTeX) {\n' },
    footer: { js: '\n}' },
    metafile: 'gen/plugin.json',
    external: [
      'zotero/itemTree',
    ]
  })

  // worker code
  await bundle({
    entryPoints: [ 'content/worker/zotero.ts' ],
    plugins: [
      loader.trace('worker'),
      loader.patcher('setup/patches'),
      loader.bibertool,
      loader.bib,
      // loader.peggy,
      loader.__dirname,
      shims
    ],
    inject: ['./setup/loaders/globals.js'],
    outdir: 'build/content/worker',
    exportGlobals: true,
    metafile: 'gen/worker.json',
    external: [ 'jsdom' ],
    banner: { js: '\ndump("\\nloading BBT chromeworker\\n")\ntry {\n' },
    footer: { js: '} catch ($$err$$) { dump("\\nerror: failed loading BBT chromeworker: " + $$err$$.message  + "\\n" + $$err$$.stack + "\\n") }\ndump("\\nloaded BBT chromeworker\\n")\n' },
  })

  // translators
  for (const translator of (await glob('translators/*.json')).map(tr => path.parse(tr))) {
    const header = require('./' + path.join(translator.dir, translator.name + '.json'))
    const outfile = path.join('build/resource', translator.name + '.js')

    // https://esbuild.github.io/api/#write
    // https://esbuild.github.io/api/#outbase
    // https://esbuild.github.io/api/#working-directory
    await bundle({
      entryPoints: [path.join(translator.dir, translator.name + '.ts')],
      plugins: [
        // loader.trace('translators'),
        loader.bibertool,
        // loader.peggy,
        loader.__dirname,
        shims
      ],
      outfile,
      banner: { js: `
        if (typeof ZOTERO_TRANSLATOR_INFO === 'undefined') var ZOTERO_TRANSLATOR_INFO = {}; // declare if not declared
        Object.assign(ZOTERO_TRANSLATOR_INFO, ${JSON.stringify(header)}); // assign new data
      `},
      exportGlobals: true,
      metafile: `gen/${translator.name}.json`,
    })

    const source = await fs.promises.readFile(outfile, 'utf-8')
    const checksum = crypto.createHash('sha256')
    checksum.update(source)
    if (!header.configOptions) header.configOptions = {}
    header.configOptions.hash = checksum.digest('hex')
    header.lastUpdated = (new Date).toISOString().replace(/T.*/, '')
    await fs.promises.writeFile(path.join('build/resource', translator.name + '.json'), JSON.stringify(header, null, 2))
  }

  if (await branch() === 'headless') {
    let node_modules = loader.node_modules('setup/patches')
    await bundle({
      platform: 'node',
      // target: ['node12'],
      // inject: [ './headless/inject.js' ],
      plugins: [node_modules.plugin, loader.patcher('setup/patches'), loader.bibertool, loader.peggy ],
      inject: ['./setup/loaders/globals.js'],
      bundle: true,
      globalName: 'Headless',
      entryPoints: [ 'headless/zotero.ts' ],
      outfile: 'gen/headless/zotero.js',
      banner: {
        js: 'var ZOTERO_CONFIG = { GUID: "zotero@" };\n',
      },
      exportGlobals: true,
      metafile: 'gen/headless/zotero.json',
    })
    let external = node_modules.external

    node_modules = loader.node_modules('setup/patches')
    await bundle({
      platform: 'node',
      // target: ['node12'],
      // inject: [ './headless/inject.js' ],
      plugins: [node_modules.plugin, loader.patcher('setup/patches'), loader.bibertool, loader.peggy ],
      bundle: true,
      globalName: 'Headless',
      entryPoints: [ 'headless/index.ts' ],
      outfile: 'gen/headless/index.js',
      metafile: 'gen/headless/index.json',
      banner: {
        js: await fs.promises.readFile('gen/headless/zotero.js', 'utf-8')
      }
    })
    external = [...new Set(external.concat(node_modules.external))].sort()

    const package_json = JSON.parse(await fs.promises.readFile('package.json', 'utf-8'))
    const move = Object.keys(package_json.dependencies).filter(pkg => !external.includes(pkg))
    if (move.length) {
      console.log('  the following packages should be moved to devDependencies')
      for (const pkg of move.sort()) {
        console.log('  *', pkg)
      }
    }
  }
}

rebuild().catch(err => {
  console.log(err)
  process.exit(1)
})
<|endoftext|>