<commit_before>;(function($B) {
  var _b_=$B.builtins
      // Static binding in function closure needed for import hooks
      // to stick to builtin cache even if module is overriden in sys.modules
      //$sys = $B.imported['sys'];

  /**
   * [Import spec] [PEP 302] Brython import machinery
   *
   * @param mod_name        {string}    name of module to load
   * @param origin          {string}    name of module context invoking the import
   * @param _path           {list}      Brython's None for top-level modules
   *                                    Value of parent package's __path__
   * @param module          {module}    [Optional] Existing module, for reload only
   */
  function import_hooks(mod_name, _path, module, blocking) {
    // Default argument binding
    if ($B.is_none(module)) {
        module = undefined;
    }

    var _meta_path=$B.meta_path;

    var spec = undefined;
    for (var i=0, _len_i = _meta_path.length; i < _len_i && $B.is_none(spec); i++) {
        var _finder=_meta_path[i],
            find_spec = _b_.getattr(_finder, 'find_spec', null)
        if(find_spec !== null){
            spec=_b_.getattr(find_spec, '__call__')(mod_name, _path, undefined, blocking);
            spec.blocking = blocking
        }
    } //for

    if ($B.is_none(spec)) {
        // No import spec found
        throw _b_.ImportError('No module named '+mod_name);
    }

    var _loader = _b_.getattr(spec, 'loader', _b_.None),
        _sys_modules = $B.imported,
        _spec_name = _b_.getattr(spec, 'name');

    // Import spec represents a match
    if ($B.is_none(module)) {
        // Create module object
        if (!$B.is_none(_loader)) {
            var create_module = _b_.getattr(_loader, 'create_module', _b_.None);
            if (!$B.is_none(create_module)) {
                module = _b_.getattr(create_module, '__call__')(spec);
            }
        }
        if(module===undefined){throw _b_.ImportError(mod_name)}
        if ($B.is_none(module)) {
            // FIXME : Initialize __doc__ and __package__
            module = $B.$ModuleDict.$factory(mod_name);
            var mod_desc = _b_.getattr(spec, 'origin');
            if (_b_.getattr(spec, 'has_location')) {
                mod_desc = "from '" + mod_desc + "'";
            }
            else {
                mod_desc = '(' + mod_desc + ')';
            }
            module.toString = module.__repr__ = module.__str__ =
                    function(){return "<module '" + mod_name + "' " + mod_desc + ">"}
        }
    }
    module.__name__ = _spec_name;
    module.__loader__ = _loader;
    module.__package__ = _b_.getattr(spec, 'parent', '');
    module.__spec__ = spec;

    var locs = _b_.getattr(spec, 'submodule_search_locations');
    // Brython-specific var
    if (module.$is_package = !$B.is_none(locs)) {
        module.__path__ = locs;
    }
    if (_b_.getattr(spec, 'has_location')) {
        module.__file__ = _b_.getattr(spec, 'origin')
        $B.$py_module_path[module.__name__] = module.__file__;
    }
    var cached = _b_.getattr(spec, 'cached');
    if (!$B.is_none(cached)) {
        module.__cached__ = cached;
    }

    if ($B.is_none(_loader)) {
        if (!$B.is_none(locs)) {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
        }
        else {
            throw _b_.ImportError(mod_name);
        }
    }
    else {
        var exec_module = _b_.getattr(_loader, 'exec_module', _b_.None);
        if ($B.is_none(exec_module)) {
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_b_.getattr(_loader, 'load_module'),
                                 '__call__')(_spec_name);
        }
        else {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
            try { _b_.getattr(exec_module, '__call__')(module, blocking) }
            catch (e) {
                delete $B.modules[_spec_name];
                delete _sys_modules[_spec_name];
                throw e;
           }
        }
    }

    return _sys_modules[_spec_name];
  }

$B.import_hooks=import_hooks
})(__BRYTHON__)
<commit_msg>Remove attribute "toString" of module objects<commit_after>;(function($B) {
  var _b_=$B.builtins
      // Static binding in function closure needed for import hooks
      // to stick to builtin cache even if module is overriden in sys.modules
      //$sys = $B.imported['sys'];

  /**
   * [Import spec] [PEP 302] Brython import machinery
   *
   * @param mod_name        {string}    name of module to load
   * @param origin          {string}    name of module context invoking the import
   * @param _path           {list}      Brython's None for top-level modules
   *                                    Value of parent package's __path__
   * @param module          {module}    [Optional] Existing module, for reload only
   */
  function import_hooks(mod_name, _path, module, blocking) {
    // Default argument binding
    if ($B.is_none(module)) {
        module = undefined;
    }

    var _meta_path=$B.meta_path;

    var spec = undefined;
    for (var i=0, _len_i = _meta_path.length; i < _len_i && $B.is_none(spec); i++) {
        var _finder=_meta_path[i],
            find_spec = _b_.getattr(_finder, 'find_spec', null)
        if(find_spec !== null){
            spec=_b_.getattr(find_spec, '__call__')(mod_name, _path, undefined, blocking);
            spec.blocking = blocking
        }
    } //for

    if ($B.is_none(spec)) {
        // No import spec found
        throw _b_.ImportError('No module named '+mod_name);
    }

    var _loader = _b_.getattr(spec, 'loader', _b_.None),
        _sys_modules = $B.imported,
        _spec_name = _b_.getattr(spec, 'name');

    // Import spec represents a match
    if ($B.is_none(module)) {
        // Create module object
        if (!$B.is_none(_loader)) {
            var create_module = _b_.getattr(_loader, 'create_module', _b_.None);
            if (!$B.is_none(create_module)) {
                module = _b_.getattr(create_module, '__call__')(spec);
            }
        }
        if(module===undefined){throw _b_.ImportError(mod_name)}
        if ($B.is_none(module)) {
            // FIXME : Initialize __doc__ and __package__
            module = $B.$ModuleDict.$factory(mod_name);
            var mod_desc = _b_.getattr(spec, 'origin');
            if (_b_.getattr(spec, 'has_location')) {
                mod_desc = "from '" + mod_desc + "'";
            }
            else {
                mod_desc = '(' + mod_desc + ')';
            }
        }
    }
    module.__name__ = _spec_name;
    module.__loader__ = _loader;
    module.__package__ = _b_.getattr(spec, 'parent', '');
    module.__spec__ = spec;

    var locs = _b_.getattr(spec, 'submodule_search_locations');
    // Brython-specific var
    if (module.$is_package = !$B.is_none(locs)) {
        module.__path__ = locs;
    }
    if (_b_.getattr(spec, 'has_location')) {
        module.__file__ = _b_.getattr(spec, 'origin')
        $B.$py_module_path[module.__name__] = module.__file__;
    }
    var cached = _b_.getattr(spec, 'cached');
    if (!$B.is_none(cached)) {
        module.__cached__ = cached;
    }

    if ($B.is_none(_loader)) {
        if (!$B.is_none(locs)) {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
        }
        else {
            throw _b_.ImportError(mod_name);
        }
    }
    else {
        var exec_module = _b_.getattr(_loader, 'exec_module', _b_.None);
        if ($B.is_none(exec_module)) {
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_b_.getattr(_loader, 'load_module'),
                                 '__call__')(_spec_name);
        }
        else {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
            try { _b_.getattr(exec_module, '__call__')(module, blocking) }
            catch (e) {
                delete $B.modules[_spec_name];
                delete _sys_modules[_spec_name];
                throw e;
           }
        }
    }

    return _sys_modules[_spec_name];
  }

$B.import_hooks=import_hooks
})(__BRYTHON__)
<|endoftext|>


<commit_before>(function () {

  var querystring = __meteor_bootstrap__.require('querystring');

  Accounts.oauth.registerService('facebook', 2, function(query) {

    var response = getTokens(query);
    var accessToken = response.accessToken;
    var identity = getIdentity(accessToken);

    var serviceData = {
      id: identity.id,
      accessToken: accessToken,
      email: identity.email,
      expiresAt: (+new Date) + (1000 * response.expiresIn)
    };

    return {
      serviceData: serviceData,
      options: {profile: {name: identity.name}}
    };
  });

  // returns an object containing:
  // - accessToken
  // - expiresIn: lifetime of token in seconds
  var getTokens = function (query) {
    var config = Accounts.loginServiceConfiguration.findOne({service: 'facebook'});
    if (!config)
      throw new Accounts.ConfigError("Service not configured");

    // Request an access token
    var result = Meteor.http.get(
      "https://graph.facebook.com/oauth/access_token", {
        params: {
          client_id: config.appId,
          redirect_uri: Meteor.absoluteUrl("_oauth/facebook?close"),
          client_secret: config.secret,
          code: query.code
        }
      });

    if (result.error)
      throw result.error;
    var response = result.content;

    // Errors come back as JSON but success looks like a query encoded
    // in a url
    var error_response;
    try {
      // Just try to parse so that we know if we failed or not,
      // while storing the parsed results
      error_response = JSON.parse(response);
    } catch (e) {
      error_response = null;
    }

    if (error_response) {
      throw new Meteor.Error(500, "Error trying to get access token from Facebook", error_response);
    } else {
      // Success!  Extract the facebook access token and expiration
      // time from the response
      var parsedResponse = querystring.parse(response);
      var fbAccessToken = parsedResponse.access_token;
      var fbExpires = parsedResponse.expires;

      if (!fbAccessToken)
        throw new Meteor.Error(500, "Couldn't find access token in HTTP response.");
      return {
        accessToken: fbAccessToken,
        expiresIn: fbExpires
      };
    }
  };

  var getIdentity = function (accessToken) {
    var result = Meteor.http.get("https://graph.facebook.com/me", {
      params: {access_token: accessToken}});

    if (result.error)
      throw result.error;
    return result.data;
  };
}) ();
<commit_msg>minor rename<commit_after>(function () {

  var querystring = __meteor_bootstrap__.require('querystring');

  Accounts.oauth.registerService('facebook', 2, function(query) {

    var response = getTokenResponse(query);
    var accessToken = response.accessToken;
    var identity = getIdentity(accessToken);

    var serviceData = {
      id: identity.id,
      accessToken: accessToken,
      email: identity.email,
      expiresAt: (+new Date) + (1000 * response.expiresIn)
    };

    return {
      serviceData: serviceData,
      options: {profile: {name: identity.name}}
    };
  });

  // returns an object containing:
  // - accessToken
  // - expiresIn: lifetime of token in seconds
  var getTokenResponse = function (query) {
    var config = Accounts.loginServiceConfiguration.findOne({service: 'facebook'});
    if (!config)
      throw new Accounts.ConfigError("Service not configured");

    // Request an access token
    var result = Meteor.http.get(
      "https://graph.facebook.com/oauth/access_token", {
        params: {
          client_id: config.appId,
          redirect_uri: Meteor.absoluteUrl("_oauth/facebook?close"),
          client_secret: config.secret,
          code: query.code
        }
      });

    if (result.error)
      throw result.error;
    var response = result.content;

    // Errors come back as JSON but success looks like a query encoded
    // in a url
    var error_response;
    try {
      // Just try to parse so that we know if we failed or not,
      // while storing the parsed results
      error_response = JSON.parse(response);
    } catch (e) {
      error_response = null;
    }

    if (error_response) {
      throw new Meteor.Error(500, "Error trying to get access token from Facebook", error_response);
    } else {
      // Success!  Extract the facebook access token and expiration
      // time from the response
      var parsedResponse = querystring.parse(response);
      var fbAccessToken = parsedResponse.access_token;
      var fbExpires = parsedResponse.expires;

      if (!fbAccessToken)
        throw new Meteor.Error(500, "Couldn't find access token in HTTP response.");
      return {
        accessToken: fbAccessToken,
        expiresIn: fbExpires
      };
    }
  };

  var getIdentity = function (accessToken) {
    var result = Meteor.http.get("https://graph.facebook.com/me", {
      params: {access_token: accessToken}});

    if (result.error)
      throw result.error;
    return result.data;
  };
}) ();
<|endoftext|>


<commit_before>import {
  assertNodeType,
  assertValueType,
  arrayOfType,
  chain,
  assertEach
} from "@babel/types/lib/definitions/utils";

import { functionCommon } from "@babel/types/lib/definitions/core";
const valueFieldCommon = {
  value: {
    validate: assertValueType("string")
  }
};

const MarkoDefinitions = {
  MarkoDocumentType: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    visitor: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoDeclaration: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    visitor: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoCDATA: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    visitor: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoComment: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    visitor: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoText: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    visitor: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoPlaceholder: {
    aliases: ["Marko", "Statement"],
    builder: ["value", "escape"],
    visitor: ["value"],
    fields: {
      value: {
        validate: assertNodeType("Expression")
      },
      escape: {
        validate: assertValueType("boolean"),
        default: true
      }
    }
  },

  MarkoScriptlet: {
    aliases: ["Marko", "Statement"],
    builder: ["body", "static"],
    visitor: ["body"],
    fields: {
      body: {
        validate: arrayOfType(["Statement"])
      },
      static: {
        validate: assertValueType("boolean"),
        default: false
      }
    }
  },

  MarkoClass: {
    aliases: ["Marko", "Statement"],
    builder: ["body"],
    visitor: ["body"],
    fields: {
      body: {
        validate: assertNodeType("ClassBody")
      }
    }
  },

  MarkoAttribute: {
    aliases: ["Marko"],
    builder: ["name", "value", "modifier", "arguments", "default"],
    visitor: ["value", "arguments"],
    fields: {
      name: {
        validate: assertValueType("string")
      },
      value: {
        validate: assertNodeType("Expression"),
        optional: true
      },
      modifier: {
        validate: assertValueType("string"),
        optional: true
      },
      arguments: {
        validate: chain(
          assertValueType("array"),
          assertEach(assertNodeType("Expression", "SpreadElement"))
        ),
        optional: true
      },
      default: {
        validate: assertValueType("boolean"),
        optional: true
      }
    }
  },

  MarkoSpreadAttribute: {
    aliases: ["Marko"],
    builder: ["value"],
    visitor: ["value"],
    fields: {
      value: {
        validate: assertNodeType("Expression"),
        optional: true
      }
    }
  },

  MarkoTagBody: {
    aliases: ["Marko", "Block", "BlockParent", "Scope", "Scopable"],
    builder: ["body"],
    visitor: ["body"],
    fields: {
      body: {
        validate: arrayOfType([
          "MarkoTag",
          "MarkoCDATA",
          "MarkoText",
          "MarkoPlaceholder",
          "MarkoScriptlet",
          "MarkoComment"
        ]),
        default: []
      }
    }
  },

  MarkoTag: {
    aliases: ["Marko", "Statement"],
    builder: [
      "name",
      "attributes",
      "body",
      "params",
      "arguments",
      "var",
      "properties",
      "runtimeFlags"
    ],
    visitor: ["name", "attributes", "body", "params", "arguments", "var"],
    fields: {
      name: {
        validate: assertNodeType("Expression")
      },
      attributes: {
        validate: arrayOfType(["MarkoAttribute", "MarkoSpreadAttribute"]),
        default: []
      },
      body: {
        validate: assertNodeType("MarkoTagBody")
      },
      params: {
        ...functionCommon.params,
        optional: true
      },
      arguments: {
        validate: chain(
          assertValueType("array"),
          assertEach(assertNodeType("Expression", "SpreadElement"))
        ),
        optional: true
      },
      properties: {
        validate: arrayOfType(["ObjectProperty"]),
        default: []
      },
      handlers: {
        validate: assertEach(assertNodeType("Expression")),
        optional: true
      },
      rawValue: {
        validate: assertValueType("string"),
        optional: true
      },
      runtimeFlags: {
        validate: assertValueType("number"),
        default: 0
      },
      key: {
        validate: assertNodeType("Expression"),
        optional: true
      },
      var: {
        validate: assertNodeType("LVal"),
        optional: true
      }
    }
  }
};

export default MarkoDefinitions;
export const MARKO_TYPES = Object.keys(MarkoDefinitions);
export const MARKO_ALIAS_TYPES = Array.from(
  new Set(
    MARKO_TYPES.reduce((all, t) => all.concat(MarkoDefinitions[t].aliases), [])
  )
);
<commit_msg>fix(babel-types): remove invalid visitors<commit_after>import {
  assertNodeType,
  assertValueType,
  arrayOfType,
  chain,
  assertEach
} from "@babel/types/lib/definitions/utils";

import { functionCommon } from "@babel/types/lib/definitions/core";
const valueFieldCommon = {
  value: {
    validate: assertValueType("string")
  }
};

const MarkoDefinitions = {
  MarkoDocumentType: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoDeclaration: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoCDATA: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoComment: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoText: {
    aliases: ["Marko", "Statement"],
    builder: ["value"],
    fields: { ...valueFieldCommon }
  },

  MarkoPlaceholder: {
    aliases: ["Marko", "Statement"],
    builder: ["value", "escape"],
    visitor: ["value"],
    fields: {
      value: {
        validate: assertNodeType("Expression")
      },
      escape: {
        validate: assertValueType("boolean"),
        default: true
      }
    }
  },

  MarkoScriptlet: {
    aliases: ["Marko", "Statement"],
    builder: ["body", "static"],
    visitor: ["body"],
    fields: {
      body: {
        validate: arrayOfType(["Statement"])
      },
      static: {
        validate: assertValueType("boolean"),
        default: false
      }
    }
  },

  MarkoClass: {
    aliases: ["Marko", "Statement"],
    builder: ["body"],
    visitor: ["body"],
    fields: {
      body: {
        validate: assertNodeType("ClassBody")
      }
    }
  },

  MarkoAttribute: {
    aliases: ["Marko"],
    builder: ["name", "value", "modifier", "arguments", "default"],
    visitor: ["value", "arguments"],
    fields: {
      name: {
        validate: assertValueType("string")
      },
      value: {
        validate: assertNodeType("Expression"),
        optional: true
      },
      modifier: {
        validate: assertValueType("string"),
        optional: true
      },
      arguments: {
        validate: chain(
          assertValueType("array"),
          assertEach(assertNodeType("Expression", "SpreadElement"))
        ),
        optional: true
      },
      default: {
        validate: assertValueType("boolean"),
        optional: true
      }
    }
  },

  MarkoSpreadAttribute: {
    aliases: ["Marko"],
    builder: ["value"],
    visitor: ["value"],
    fields: {
      value: {
        validate: assertNodeType("Expression"),
        optional: true
      }
    }
  },

  MarkoTagBody: {
    aliases: ["Marko", "Block", "BlockParent", "Scope", "Scopable"],
    builder: ["body"],
    visitor: ["body"],
    fields: {
      body: {
        validate: arrayOfType([
          "MarkoTag",
          "MarkoCDATA",
          "MarkoText",
          "MarkoPlaceholder",
          "MarkoScriptlet",
          "MarkoComment"
        ]),
        default: []
      }
    }
  },

  MarkoTag: {
    aliases: ["Marko", "Statement"],
    builder: [
      "name",
      "attributes",
      "body",
      "params",
      "arguments",
      "var",
      "properties",
      "runtimeFlags"
    ],
    visitor: ["name", "attributes", "body", "params", "arguments", "var"],
    fields: {
      name: {
        validate: assertNodeType("Expression")
      },
      attributes: {
        validate: arrayOfType(["MarkoAttribute", "MarkoSpreadAttribute"]),
        default: []
      },
      body: {
        validate: assertNodeType("MarkoTagBody")
      },
      params: {
        ...functionCommon.params,
        optional: true
      },
      arguments: {
        validate: chain(
          assertValueType("array"),
          assertEach(assertNodeType("Expression", "SpreadElement"))
        ),
        optional: true
      },
      properties: {
        validate: arrayOfType(["ObjectProperty"]),
        default: []
      },
      handlers: {
        validate: assertEach(assertNodeType("Expression")),
        optional: true
      },
      rawValue: {
        validate: assertValueType("string"),
        optional: true
      },
      runtimeFlags: {
        validate: assertValueType("number"),
        default: 0
      },
      key: {
        validate: assertNodeType("Expression"),
        optional: true
      },
      var: {
        validate: assertNodeType("LVal"),
        optional: true
      }
    }
  }
};

export default MarkoDefinitions;
export const MARKO_TYPES = Object.keys(MarkoDefinitions);
export const MARKO_ALIAS_TYPES = Array.from(
  new Set(
    MARKO_TYPES.reduce((all, t) => all.concat(MarkoDefinitions[t].aliases), [])
  )
);
<|endoftext|>


<commit_before>var path = require('path');

module.exports = function(grunt) {
  var electronVer = '0.30.1'; // Electron build version

  // Load the plugins...
  grunt.loadNpmTasks('grunt-electron');
  if (process.platform === 'win32') grunt.loadNpmTasks('grunt-electron-installer');
  if (process.platform === 'darwin') grunt.loadNpmTasks('grunt-appdmg');

  // Load the tasks in '/tasks'
  grunt.loadTasks('tasks');

  // Set all subsequent paths to the relative to the root of the repo
  grunt.file.setBase(path.resolve('..'));

  var appInfo = grunt.file.readJSON('package.json');
  var version = appInfo.version;
  var buildIgnore = './build';

  // Project configuration.
  grunt.initConfig({
    name: appInfo.name,
    pkg: appInfo,
    electron: {
      macbuild: {
        options: {
          name: appInfo.name,
          dir: './',
          out: 'build/dist',
          icon: 'resources/darwin/app.icns',
          version: electronVer,
          platform: 'darwin',
          arch: 'x64',
          ignore: buildIgnore,
          'app-version': version,
          overwrite: true,
          prune: true,
          'app-bundle-id': 'pancakecreator-main',
          'helper-bundle-id': 'pancakecreator-helper'
        }
      },
      winbuild: {
        options: {
          name: appInfo.name,
          dir: './',
          out: 'build/dist',
          icon: 'resources/win32/app.ico',
          version: electronVer,
          platform: 'win32',
          arch: 'x64,ia32',
          ignore: buildIgnore,
          'app-version': version,
          overwrite: true,
          prune: true,
          'version-string': {
            CompanyName: 'PancakeBot Inc.',
            LegalCopyright: 'Copyright (C) PancakeBot Inc., all rights reserved. Code under Apache v2.0 free and open source license.',
            FileDescription: appInfo.name,
            OriginalFilename: appInfo.name + '.exe',
            FileVersion: electronVer,
            ProductVersion: version,
            ProductName: appInfo.name,
            InternalName: appInfo.name
          }
        }
      }
    }
  });

  // Default task(s).
  grunt.registerTask('default', ['pre-build']);
};
<commit_msg>Properly fix build folder issue<commit_after>var path = require('path');

module.exports = function(grunt) {
  var electronVer = '0.30.1'; // Electron build version

  // Load the plugins...
  grunt.loadNpmTasks('grunt-electron');
  if (process.platform === 'win32') grunt.loadNpmTasks('grunt-electron-installer');
  if (process.platform === 'darwin') grunt.loadNpmTasks('grunt-appdmg');

  // Load the tasks in '/tasks'
  grunt.loadTasks('tasks');

  // Set all subsequent paths to the relative to the root of the repo
  grunt.file.setBase(path.resolve('..'));

  var appInfo = grunt.file.readJSON('package.json');
  var version = appInfo.version;
  var buildIgnore = 'build/dist|build/node_modules|build/tasks|build/package.json|build/Gruntfile.js';

  // Project configuration.
  grunt.initConfig({
    name: appInfo.name,
    pkg: appInfo,
    electron: {
      macbuild: {
        options: {
          name: appInfo.name,
          dir: './',
          out: 'build/dist',
          icon: 'resources/darwin/app.icns',
          version: electronVer,
          platform: 'darwin',
          arch: 'x64',
          ignore: buildIgnore,
          'app-version': version,
          overwrite: true,
          prune: true,
          'app-bundle-id': 'pancakecreator-main',
          'helper-bundle-id': 'pancakecreator-helper'
        }
      },
      winbuild: {
        options: {
          name: appInfo.name,
          dir: './',
          out: 'build/dist',
          icon: 'resources/win32/app.ico',
          version: electronVer,
          platform: 'win32',
          arch: 'x64,ia32',
          ignore: buildIgnore,
          'app-version': version,
          overwrite: true,
          prune: true,
          'version-string': {
            CompanyName: 'PancakeBot Inc.',
            LegalCopyright: 'Copyright (C) PancakeBot Inc., all rights reserved. Code under Apache v2.0 free and open source license.',
            FileDescription: appInfo.name,
            OriginalFilename: appInfo.name + '.exe',
            FileVersion: electronVer,
            ProductVersion: version,
            ProductName: appInfo.name,
            InternalName: appInfo.name
          }
        }
      }
    }
  });

  // Default task(s).
  grunt.registerTask('default', ['pre-build']);
};
<|endoftext|>


<commit_before>/* global cozy */

import konnectors from './konnectors'
import AUTHORIZED_CATEGORIES from 'config/categories'

// constant
const FETCH_REGISTRY_KONNECTORS = 'FETCH_REGISTRY_KONNECTORS'
const FETCH_REGISTRY_KONNECTORS_ERROR = 'FETCH_REGISTRY_KONNECTORS_ERROR'
const FETCH_REGISTRY_KONNECTORS_SUCCESS = 'FETCH_REGISTRY_KONNECTORS_SUCCESS'

export const OTHERS_CATEGORY = 'others'

const getUncategorizedKonnectors = (list, categories) =>
  list.reduce((uncategorized, konnector) => {
    if (
      konnector.categories &&
      !konnector.categories.every(category => categories.includes(category))
    ) {
      uncategorized.push(konnector)
    }
    return uncategorized
  }, [])

// reducers

const reducer = (state = {}, action) => {
  switch (action.type) {
    case FETCH_REGISTRY_KONNECTORS:
    case FETCH_REGISTRY_KONNECTORS_SUCCESS:
      return {
        konnectors: konnectors(state.konnectors, action)
      }
    default:
      return state
  }
}

export default reducer

// selectors
export const getRegistryKonnectors = state =>
  Object.values(state.konnectors.data) || []

export const getRegistryKonnectorsByCategory = (state, category) => {
  const stateKonnectors = getRegistryKonnectors(state)
  return category
    ? category === OTHERS_CATEGORY
      ? getUncategorizedKonnectors(stateKonnectors, AUTHORIZED_CATEGORIES)
      : stateKonnectors.filter(konnector =>
          konnector.categories.includes(category)
        )
    : stateKonnectors
}

export const getRegistryKonnectorsByDataType = (state, dataType) =>
  dataType
    ? Object.values(state.konnectors.data).filter(
        konnector =>
          Array.isArray(konnector.dataType) &&
          konnector.dataType.includes(dataType)
      )
    : []

export const getRegistryKonnectorsFromSlugs = (state, slugs = []) => {
  return slugs.reduce((returnedKonnectors, slug) => {
    if (
      state.konnectors &&
      state.konnectors.data &&
      state.konnectors.data[slug]
    ) {
      return returnedKonnectors.concat([state.konnectors.data[slug]])
    }
    return returnedKonnectors
  }, [])
}

export const getRegistryKonnector = (state, slug) => {
  return state.konnectors.data[slug]
}

export const getSlugs = state => {
  return Object.keys(state.konnectors.data)
}

export const isFetchingRegistryKonnector = state => {
  return state.konnectors.fetchStatus === 'loading'
}

// action creators sync

export const initializeRegistry = konnectors => {
  return (dispatch, getState) => {
    dispatch({ type: FETCH_REGISTRY_KONNECTORS })
    return cozy.client
      .fetchJSON('GET', '/settings/context')
      .catch(error => {
        console.warn &&
          console.warn(`Cannot get Cozy context : ${error.message}`)
        return {}
      })
      .then(context => {
        const konnectorsToExclude =
          !!context.attributes && context.attributes.exclude_konnectors
        const filteredKonnectors =
          context.attributes && context.attributes.debug
            ? konnectors
            : konnectors.filter(
                k => k.slug !== 'creditagricole' && k.slug !== 'debug'
              )

        if (konnectorsToExclude && konnectorsToExclude.length) {
          return dispatch({
            type: FETCH_REGISTRY_KONNECTORS_SUCCESS,
            konnectors: filteredKonnectors.filter(
              k => !konnectorsToExclude.includes(k.slug)
            )
          })
        }
        return dispatch({
          type: FETCH_REGISTRY_KONNECTORS_SUCCESS,
          konnectors: filteredKonnectors
        })
      })
      .catch(() => {
        dispatch({ type: FETCH_REGISTRY_KONNECTORS_ERROR, konnectors: [] })
      })
  }
}
<commit_msg>refacto: rewrite getUncategorizedKonnectors with filter 🔨<commit_after>/* global cozy */

import konnectors from './konnectors'
import AUTHORIZED_CATEGORIES from 'config/categories'

// constant
const FETCH_REGISTRY_KONNECTORS = 'FETCH_REGISTRY_KONNECTORS'
const FETCH_REGISTRY_KONNECTORS_ERROR = 'FETCH_REGISTRY_KONNECTORS_ERROR'
const FETCH_REGISTRY_KONNECTORS_SUCCESS = 'FETCH_REGISTRY_KONNECTORS_SUCCESS'

export const OTHERS_CATEGORY = 'others'

// helpers
const getUncategorizedKonnectors = (konnectors, categories) =>
  konnectors.filter(
    konnector =>
      konnector.categories &&
      !konnector.categories.every(category => categories.includes(category))
  )

// reducers

const reducer = (state = {}, action) => {
  switch (action.type) {
    case FETCH_REGISTRY_KONNECTORS:
    case FETCH_REGISTRY_KONNECTORS_SUCCESS:
      return {
        konnectors: konnectors(state.konnectors, action)
      }
    default:
      return state
  }
}

export default reducer

// selectors
export const getRegistryKonnectors = state =>
  Object.values(state.konnectors.data) || []

export const getRegistryKonnectorsByCategory = (state, category) => {
  const stateKonnectors = getRegistryKonnectors(state)
  return category
    ? category === OTHERS_CATEGORY
      ? getUncategorizedKonnectors(stateKonnectors, AUTHORIZED_CATEGORIES)
      : stateKonnectors.filter(konnector =>
          konnector.categories.includes(category)
        )
    : stateKonnectors
}

export const getRegistryKonnectorsByDataType = (state, dataType) =>
  dataType
    ? Object.values(state.konnectors.data).filter(
        konnector =>
          Array.isArray(konnector.dataType) &&
          konnector.dataType.includes(dataType)
      )
    : []

export const getRegistryKonnectorsFromSlugs = (state, slugs = []) => {
  return slugs.reduce((returnedKonnectors, slug) => {
    if (
      state.konnectors &&
      state.konnectors.data &&
      state.konnectors.data[slug]
    ) {
      return returnedKonnectors.concat([state.konnectors.data[slug]])
    }
    return returnedKonnectors
  }, [])
}

export const getRegistryKonnector = (state, slug) => {
  return state.konnectors.data[slug]
}

export const getSlugs = state => {
  return Object.keys(state.konnectors.data)
}

export const isFetchingRegistryKonnector = state => {
  return state.konnectors.fetchStatus === 'loading'
}

// action creators sync

export const initializeRegistry = konnectors => {
  return (dispatch, getState) => {
    dispatch({ type: FETCH_REGISTRY_KONNECTORS })
    return cozy.client
      .fetchJSON('GET', '/settings/context')
      .catch(error => {
        console.warn &&
          console.warn(`Cannot get Cozy context : ${error.message}`)
        return {}
      })
      .then(context => {
        const konnectorsToExclude =
          !!context.attributes && context.attributes.exclude_konnectors
        const filteredKonnectors =
          context.attributes && context.attributes.debug
            ? konnectors
            : konnectors.filter(
                k => k.slug !== 'creditagricole' && k.slug !== 'debug'
              )

        if (konnectorsToExclude && konnectorsToExclude.length) {
          return dispatch({
            type: FETCH_REGISTRY_KONNECTORS_SUCCESS,
            konnectors: filteredKonnectors.filter(
              k => !konnectorsToExclude.includes(k.slug)
            )
          })
        }
        return dispatch({
          type: FETCH_REGISTRY_KONNECTORS_SUCCESS,
          konnectors: filteredKonnectors
        })
      })
      .catch(() => {
        dispatch({ type: FETCH_REGISTRY_KONNECTORS_ERROR, konnectors: [] })
      })
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import styled from 'styled-components'
import PropTypes from 'prop-types'
import Button from '../../content/Button/Button'
import Icon from '../../content/Icon/Icon'

const FlatButton = styled(({ className, children, ...props }) => (
  <Button {...props} className={className} flat>
    {children}
  </Button>
))`
  min-width: 0 !important;
  padding: 0 8px !important;
  font-size: 11px !important;
  ${props => props.color && `
    color: ${props.color} !important;
  `}
`

FlatButton.displayName = 'FlatButton'

class IconButton extends React.Component {
  state = { color: '#000000' }

  handleColorMouseEnter = () => this.setState({ color: '#424242' })
  handleColorMouseLeave = () => this.setState({ color: '#000000' })
  handleColorMouseDown = () => this.setState({ color: '#9b9b9b' })
  handleColorMouseUp = () => this.setState({ color: '#000000' })

  render () {
    const { disabled } = this.props

    return (
      <FlatButton
        onClick={this.props.onClick}
        onMouseEnter={this.handleColorMouseEnter}
        onMouseLeave={this.handleColorMouseLeave}
        onMouseDown={this.handleColorMouseDown}
        onMouseUp={this.handleColorMouseUp}
        disabled={disabled}
      >
        <Icon
          name={this.props.name}
          size='11'
          margin='-2px 5px 0'
          color={!disabled ? this.state.color : '#aaaaaa'}
        />
      </FlatButton>
    )
  }
}

/**
 * The only true `Pagination` component.
 */
class Pagination extends React.Component {
  state = {
    activeIndex: this.props.activeIndex,
  }

  handleActiveIndex = activeIndex => {
    this.setState({ activeIndex })
    return activeIndex
  }

  render () {
    const {
      pages,
      activeColor,
      onClickFirst,
      onClickPrev,
      onClickNext,
      onClickLast,
      onClickItem,
      textPrev,
      textNext,
      iconFirst,
      iconLast,
    } = this.props

    const { activeIndex } = this.state
    const isFirst = activeIndex === 0
    const isLast = activeIndex === pages -1

    return (

        <IconButton
          onClick={() => onClickFirst(this.handleActiveIndex(0))}
          disabled={isFirst}
          name={iconFirst}
        />
        <FlatButton
          onClick={() => onClickPrev(this.handleActiveIndex(activeIndex -1))}
          disabled={isFirst}
        >
          {textPrev}
        </FlatButton>

        {Array(pages).fill().map((o, index) => (
          <FlatButton
            key={Math.random()}
            onClick={f => onClickItem(this.handleActiveIndex(index))}
            color={activeIndex === index ? activeColor : ''}
            disabled={activeIndex === index}
          >
            {index + 1}
          </FlatButton>
        ))}

        <FlatButton
          onClick={() => onClickNext(this.handleActiveIndex(activeIndex +1))}
          disabled={isLast}
        >
          {textNext}
        </FlatButton>
        <IconButton
          onClick={() => onClickLast(this.handleActiveIndex(pages -1))}
          disabled={isLast}
          name={iconLast}
        />

    )
  }
}

const { oneOfType, number, func, node, string } = PropTypes

Pagination.propTypes = {
  /** Number of total pages. */
  pages: number,
  /** Active index. e.g. If the active page is 1, the index is 0. */
  activeIndex: number.isRequired,
  /** Active item color. */
  activeColor: string.isRequired,
  /** Callback when clicks the icon to take to the first page. */
  onClickFirst: func,
  /** Callback when clicks the button to take to the previous page. */
  onClickPrev: func,
  /** Callback when clicks the button to take to the next page. */
  onClickNext: func,
  /** Callback when clicks the icon to take to the last page. */
  onClickLast: func,
  /** Callback when clicks the button to take to the specific page. */
  onClickItem: func,
  /** Previous button text. */
  textPrev: oneOfType([node, func]),
  /** Next button text. */
  textNext: oneOfType([node, func]),
  /** First Icon name. */
  iconFirst: string,
  /** Last Icon name. */
  iconLast: string,
}

Pagination.defaultProps = {
  pages: 1,
  activeIndex: 0,
  activeColor: '#ee0099',
  onClickFirst: f => f,
  onClickPrev: f => f,
  onClickNext: f => f,
  onClickLast: f => f,
  onClickItem: f => f,
  textPrev: 'Prev',
  textNext: 'Next',
  iconFirst: 'double-arrow-left',
  iconLast: 'double-arrow-right',
}

Pagination.displayName = 'Pagination'

/* @component */
export default Pagination
<commit_msg>fix(styleguide): use only onChangePage in Pagination<commit_after>import React from 'react'
import styled from 'styled-components'
import PropTypes from 'prop-types'
import Button from '../../content/Button/Button'
import Icon from '../../content/Icon/Icon'

const FlatButton = styled(({ className, children, ...props }) => (
  <Button {...props} className={className} flat>
    {children}
  </Button>
))`
  min-width: 0 !important;
  padding: 0 8px !important;
  font-size: 11px !important;
  ${props => props.color && `
    color: ${props.color} !important;
  `}
`

FlatButton.displayName = 'FlatButton'

class IconButton extends React.Component {
  state = { color: '#000000' }

  handleColorMouseEnter = () => this.setState({ color: '#424242' })
  handleColorMouseLeave = () => this.setState({ color: '#000000' })
  handleColorMouseDown = () => this.setState({ color: '#9b9b9b' })
  handleColorMouseUp = () => this.setState({ color: '#000000' })

  render () {
    const { disabled } = this.props

    return (
      <FlatButton
        onClick={this.props.onClick}
        onMouseEnter={this.handleColorMouseEnter}
        onMouseLeave={this.handleColorMouseLeave}
        onMouseDown={this.handleColorMouseDown}
        onMouseUp={this.handleColorMouseUp}
        disabled={disabled}
      >
        <Icon
          name={this.props.name}
          size='11'
          margin='-2px 5px 0'
          color={!disabled ? this.state.color : '#aaaaaa'}
        />
      </FlatButton>
    )
  }
}

/**
 * The only true `Pagination` component.
 */
class Pagination extends React.Component {

  handleActiveIndex = activeIndex => {
    this.props.onChangePage(activeIndex)
  }

  render () {
    const {
      pageIndex,
      pages,
      activeColor,
      textPrev,
      textNext,
      iconFirst,
      iconLast,
    } = this.props

    const isFirst = pageIndex === 0
    const isLast = pageIndex === pages -1

    return (

        <IconButton
          onClick={() => this.handleActiveIndex(0)}
          disabled={isFirst}
          name={iconFirst}
        />
        <FlatButton
          onClick={() => this.handleActiveIndex(pageIndex - 1)}
          disabled={isFirst}
        >
          {textPrev}
        </FlatButton>
        {Array(pages).fill().map((o, index) => (
          <FlatButton
            key={Math.random()}
            onClick={() => this.handleActiveIndex(index)}
            color={pageIndex === index ? activeColor : ''}
            disabled={pageIndex === index}
          >
            {index + 1}
          </FlatButton>
        ))}
        <FlatButton
          onClick={() => this.handleActiveIndex(pageIndex + 1)}
          disabled={isLast}
        >
          {textNext}
        </FlatButton>
        <IconButton
          onClick={() => this.handleActiveIndex(pages - 1)}
          disabled={isLast}
          name={iconLast}
        />

    )
  }
}

const { oneOfType, number, func, node, string } = PropTypes

Pagination.propTypes = {
  /** Number of total pages. */
  pages: number,
  /** Active page index */
  pageIndex: number.isRequired,
  /** Active item color. */
  activeColor: string.isRequired,
  /** Callback when clicks the button to take to the specific page. */
  onChangePage: func.isRequired,
  /** Previous button text. */
  textPrev: oneOfType([node, func]),
  /** Next button text. */
  textNext: oneOfType([node, func]),
  /** First Icon name. */
  iconFirst: string,
  /** Last Icon name. */
  iconLast: string,
}

Pagination.defaultProps = {
  pages: 1,
  pageIndex: 0,
  activeColor: '#ee0099',
  textPrev: 'Prev',
  textNext: 'Next',
  iconFirst: 'double-arrow-left',
  iconLast: 'double-arrow-right',
}

Pagination.displayName = 'Pagination'

/* @component */
export default Pagination
<|endoftext|>


<commit_before>'use strict';

// Hold the local variables
var $game = 'm';
var $match = '2';

/*
 *  Either update, show, hide
 */
// Act upon the button presses
nodecg.listenFor('updateCMatch', function (data) {
    // Update local variables
    $game = data.game;
    $match = data.match;

    // Act upon the current settings
    if ($game === 'm') {        // Melee
        nodecg.sendMessage('updateTitle-melee', data);
        nodecg.sendMessage('updateBaseName-melee', data);

        if ($match === '2') {   // 1v1
            nodecg.sendMessage('updateCamName-melee1Cam', data);
        } else if ($match === '4') { // 2v2
            nodecg.sendMessage('updateCamName-melee2Cam', data);
        } else {                // Error
            alert("Match was " + $match);
        }
    } else if ($game === '4') { // Smash 4
        nodecg.sendMessage('updateTitle-smash4', data);
        nodecg.sendMessage('updateBaseName-smash4', data);
        nodecg.sendMessage('updateCamName-smash4', data);

        if ($match === '2') {   // 1v1

        } else if ($match === '4') { // 2v2

        } else {                // Error
            alert("Match was " + $match);
        }
    } else {
        alert("Game was " + $game);
    }
});

nodecg.listenFor('showCMatch', function () {
    // Act upon the current settings
    if ($game === 'm') {        // Melee
        if ($match === '2') {   // 1v1
            nodecg.sendMessage('showCamName-melee1Cam');
        } else if ($match === '4') { // 2v2
            nodecg.sendMessage('showCamName-melee2Cam');
        } else {                // Error
            alert("Match was " + $match);
        }

        nodecg.sendMessage('showTitle');
        nodecg.sendMessage('showBaseName');
    } else if ($game === '4') { // Smash 4
        if ($match === '2') {   // 1v1

        } else if ($match === '4') { // 2v2

        } else {                // Error
            alert("Match was " + $match);
        }

        nodecg.sendMessage('showCamName-smash4');
        nodecg.sendMessage('showTitle');
        nodecg.sendMessage('showBaseName');
    } else {
        alert("Game was " + $game);
    }
});

nodecg.listenFor('hideCMatch', function () {
    nodecg.sendMessage('hideTitle');
    nodecg.sendMessage('hideBaseName');
    nodecg.sendMessage('hideCameName');
});<commit_msg>Fixed cMatch to how the proper showCamName<commit_after>'use strict';

// Hold the local variables
var $game = 'm';
var $match = '2';

/*
 *  Either update, show, hide
 */
// Act upon the button presses
nodecg.listenFor('updateCMatch', function (data) {
    // Update local variables
    $game = data.game;
    $match = data.match;

    // Act upon the current settings
    if ($game === 'm') {        // Melee
        nodecg.sendMessage('updateTitle-melee', data);
        nodecg.sendMessage('updateBaseName-melee', data);

        if ($match === '2') {   // 1v1
            nodecg.sendMessage('updateCamName-melee1Cam', data);
        } else if ($match === '4') { // 2v2
            nodecg.sendMessage('updateCamName-melee2Cam', data);
        } else {                // Error
            alert("Match was " + $match);
        }
    } else if ($game === '4') { // Smash 4
        nodecg.sendMessage('updateTitle-smash4', data);
        nodecg.sendMessage('updateBaseName-smash4', data);
        nodecg.sendMessage('updateCamName-smash4', data);

        if ($match === '2') {   // 1v1

        } else if ($match === '4') { // 2v2

        } else {                // Error
            alert("Match was " + $match);
        }
    } else {
        alert("Game was " + $game);
    }
});

nodecg.listenFor('showCMatch', function () {
    // Act upon the current settings
    if ($game === 'm') {        // Melee
        if ($match === '2') {   // 1v1

        } else if ($match === '4') { // 2v2

        } else {                // Error
            alert("Match was " + $match);
        }

        nodecg.sendMessage('showCamName');
        nodecg.sendMessage('showTitle');
        nodecg.sendMessage('showBaseName');
    } else if ($game === '4') { // Smash 4
        if ($match === '2') {   // 1v1

        } else if ($match === '4') { // 2v2

        } else {                // Error
            alert("Match was " + $match);
        }

        nodecg.sendMessage('showCamName');
        nodecg.sendMessage('showTitle');
        nodecg.sendMessage('showBaseName');
    } else {
        alert("Game was " + $game);
    }
});

nodecg.listenFor('hideCMatch', function () {
    nodecg.sendMessage('hideTitle');
    nodecg.sendMessage('hideBaseName');
    nodecg.sendMessage('hideCameName');
});<|endoftext|>


<commit_before>/*
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Mick Hakobyan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

(function (global, exporter) {

    // export
    if (typeof module !== 'undefined') {
        // Node.js
        module.exports = exporter();
    } else {
        // <script />
        (global.chnobean = global.chnobean || {}).Promise = exporter();
    }

})(this, function () {
    "use strict";

    /**
    * @const
    * Should thenables be detected and converter automatically. This does impacts performance.
    */
    var CONVERT_THENABLES = true;

    /**
    * @const
    * Spec says we should dispatch the calls to func(onResolved, onRejected),
    * so it runs only after client code is done.
    * We can gain perf by not having to setTimeout.
    */
    var ALWAYS_RESOLVE_SYNCHRONIOUSLY = false;

    /**
    * Guard against variable named "undefined" being declared in global context.
    */
    var undefined;

    /**
    * @constructor
    * @param {function(function(*=), function(*=))} resolver
    */
    function Promise(resolver) {
        var promise = this;
        if (resolver) {
            try {
                resolver(
                    function fulfill(result) {
                        Promise_fulfill(promise, result);
                    },
                    function reject(result) {
                        Promise_reject(promise, result);
                    }
                );
            } catch(e) {
                Promise_reject(this, e);
            }
        }
    }

    /**
    * @param {function(*=)=} onFulfilled is executed when this promise is fulfilled
    * @param {function(*=)=} onRejected is executed when this promise is rejected
    */
    Promise.prototype.then = function Promise_then(onFulfilled, onRejected) {
        var promise = Promise_create();
        if (typeof onFulfilled === 'function') {
            promise._onFulfilled = onFulfilled;
        }
        if (typeof onRejected === 'function') {
            promise._onRejected = onRejected;
        }
        Promise_when(this, promise);
        return promise;
    };

    /**
    * @param {function()} onRejected
    *
    * Sugar for promise.then(undefined, onRejected)
    */
    Promise.prototype.catch = function Promise_catch(onRejected) {
        return this.then(undefined, onRejected);
    };

    /**
    * @param {*=} result
    *
    * Creates a promise resolved for result.
    */
    Promise.resolve = function Promise_createFulfilled(result) {
        var promise = Promise_create();
        Promise_fulfill(promise, result);
        return promise;
    };

    /**
    * @param {*=} result
    *
    * Creates a promise rejected with result.
    */
    Promise.reject = function Promise_createRejected(result) {
        var promise = Promise_create();
        Promise_reject(promise, result);
        return promise;
    };

    /**
    * @param {Array.<*>} promises
    *
    * Given array of promises or results, either resolves to array of results,
    * or rejects if any of the promises reject.
    */
    Promise.all = function Promise_all(promises) {
        var promise = Promise_create(),
            length = promises.length,
            results = [],
            // start +1, so we handle when there are no promises
            remaining = 1,
            result,
            i;

        function onFulfilled(index, result) {
            results[index] = result;
            if (!(--remaining)) {
                Promise_fulfill(promise, results, true);
            }
        }

        function onRejected(result) {
            Promise_reject(promise, result, true);
        }

        // TODO: handle CONVERT_THENABLES
        for(i = 0; i < length; i++) {
            result = promises[i];
            if (result && result._isPromise) {
                // it's a promise
                remaining++;
                result.then(
                    onFulfilled.bind(undefined, i),
                    onRejected
                );
            } else {
                results[i] = result;
            }
        }

        if (!(--remaining)) {
            // all were resolved before we even got here
            promise._fulfilled = true;
            promise._result = results;
        }

        return promise;
    };

    // --------------------------------------------------------------------------------
    // -- private implementation
    // --------------------------------------------------------------------------------

    /**
    * Used instead of "instanceof" for performance reasons.
    */
    Promise.prototype._isPromise = true;

    /**
    * Creates a promise without running the constructor function.
    */
    function Promise_create() {
        return Object.create(Promise.prototype);
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Fulfill the promise and resolve deferrals
    */
    function Promise_fulfill(promise, result, allowSynchResolution) {
        if (promise._fulfilled === undefined) {
            if (CONVERT_THENABLES) {
                Promise_fulfillThenable(promise, result);
            } else {
                promise._fulfilled = true;
                promise._result = result;
            }
            Promise_resolveDeferred(promise, allowSynchResolution);
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Reject the promise and resolve deferrals
    */
    function Promise_reject(promise, result, allowSynchResolution) {
        if (promise._fulfilled === undefined) {
            promise._fulfilled = false;
            promise._result = result;
            Promise_resolveDeferred(promise, allowSynchResolution);
        }
    }

    /**
    * Fulfill the promise, but check for result to be a thenable.
    * Thenable is an object that has obj.then(function resolve(){}, function reject(){}),
    * such as this or any other Promise implementations.
    */
    function Promise_fulfillThenable(promise, result) {
        var then;
        if (!result || typeof result === 'number' || typeof result === 'boolean' || result._isPromise) {
            // if the result is a primitive type,
            // or is a promise, use it as it is
            promise._fulfilled = true;
            promise._result = result;
        } else {
            try {
                // is this a then-able (has a ['then'] function), convert it to a Promise
                // handle "then" accessor throwing
                then = result.then;
                promise._fulfilled = true;
                if (typeof then !== 'function') {
                    // not a thenable, just use the result
                    promise._result = result;
                } else {
                    // convert the thenable to a promise
                    promise._result = new Promise(function (resolve, reject) {
                        then.call(result, resolve, reject);
                    });
                }
            } catch(e) {
                promise._fulfilled = false;
                promise._result = e;
            }
        }
    }

    /**
    * Once promise is resolved, resolve nextPromise
    */
    function Promise_when(promise, nextPromise) {
        if (promise._fulfilled !== undefined) {
            // we are resolved, resolve the given promise
            Promise_resolve(nextPromise, promise._fulfilled, promise._result);
        } else {
            // defer the resolution
            if (!promise._deferred) {
                promise._deferred = [];
            }
            promise._deferred.push(nextPromise);
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Resolves deffered promises
    */
    function Promise_resolveDeferred(promise, allowSynchResolution) {
        // assert(promise._fulfilled !== undefined)
        var deferred = promise._deferred,
            deferredLength,
            i;
        if (deferred) {
            promise._deferred = undefined;
            deferredLength = deferred.length;
            for(i = 0; i < deferredLength; i++) {
                Promise_resolve(deferred[i], promise._fulfilled, promise._result, allowSynchResolution);
            }
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Resolves promise (called by the one before, when it's resolved)
    */
    function Promise_resolve(promise, fulfilled, result, allowSynchResolution) {
        // assert(fulfilled !== undefined)
        var handler;

        if (fulfilled && result && result._isPromise) {
            // previous promise resolved to a promise, forward the promose
            Promise_when(result, promise);
        } else {
            // resolve promise
            // what handler will we use: onFulfilled or onRejected?
            if (fulfilled) {
                handler = promise._onFulfilled;
            } else {
                handler = promise._onRejected;
            }
            // kill the onFulfilled and onRejected we got from .then(onFulfilled, onRejected)
            promise._onFulfilled = undefined;
            promise._onRejected = undefined;
            // if there is a handler, dispatch... otherwise just settle in-line
            if (handler) {
                if (allowSynchResolution || ALWAYS_RESOLVE_SYNCHRONIOUSLY) {
                    // this flag indicates that this stack originated from the setTimeout
                    // no need to set another Timeout, and just run in same stack
                    Promise_handleResolution(promise, handler, result);
                } else {
                    // stack starts from user code, setTimeout so we start a new stack with only our code
                    // Spec quote: onFulfilled or onRejected must not be called until the
                    //             execution context stack contains only platform code.
                    setTimeout(Promise_handleResolution.bind(undefined, promise, handler, result), 0);
                }
            } else {
                if (fulfilled) {
                    Promise_fulfill(promise, result, allowSynchResolution);
                } else {
                    Promise_reject(promise, result, allowSynchResolution);
                }
            }
        }
    }

    /**
    * Call the handler: onFulfilled(result) or onRejected(result). And fulfill or reject based on outcome.
    */
    function Promise_handleResolution(promise, handler, result) {
        try {
            var newResult = handler(result);
            if (newResult === promise) {
                throw new TypeError();
            }
            Promise_fulfill(promise, newResult, true);
        } catch(e) {
            Promise_reject(promise, e, true);
        }
    }

    return Promise;
});<commit_msg>renamed Promise_when<commit_after>/*
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Mick Hakobyan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

(function (global, exporter) {

    // export
    if (typeof module !== 'undefined') {
        // Node.js
        module.exports = exporter();
    } else {
        // <script />
        (global.chnobean = global.chnobean || {}).Promise = exporter();
    }

})(this, function () {
    "use strict";

    /**
    * @const
    * Should thenables be detected and converter automatically. This does impacts performance.
    */
    var CONVERT_THENABLES = true;

    /**
    * @const
    * Spec says we should dispatch the calls to func(onResolved, onRejected),
    * so it runs only after client code is done.
    * We can gain perf by not having to setTimeout.
    */
    var ALWAYS_RESOLVE_SYNCHRONIOUSLY = false;

    /**
    * Guard against variable named "undefined" being declared in global context.
    */
    var undefined;

    /**
    * @constructor
    * @param {function(function(*=), function(*=))} resolver
    */
    function Promise(resolver) {
        var promise = this;
        if (resolver) {
            try {
                resolver(
                    function fulfill(result) {
                        Promise_fulfill(promise, result);
                    },
                    function reject(result) {
                        Promise_reject(promise, result);
                    }
                );
            } catch(e) {
                Promise_reject(this, e);
            }
        }
    }

    /**
    * @param {function(*=)=} onFulfilled is executed when this promise is fulfilled
    * @param {function(*=)=} onRejected is executed when this promise is rejected
    */
    Promise.prototype.then = function Promise_then(onFulfilled, onRejected) {
        var promise = Promise_create();
        if (typeof onFulfilled === 'function') {
            promise._onFulfilled = onFulfilled;
        }
        if (typeof onRejected === 'function') {
            promise._onRejected = onRejected;
        }
        Promise_whenResolved(this, promise);
        return promise;
    };

    /**
    * @param {function()} onRejected
    *
    * Sugar for promise.then(undefined, onRejected)
    */
    Promise.prototype.catch = function Promise_catch(onRejected) {
        return this.then(undefined, onRejected);
    };

    /**
    * @param {*=} result
    *
    * Creates a promise resolved for result.
    */
    Promise.resolve = function Promise_createFulfilled(result) {
        var promise = Promise_create();
        Promise_fulfill(promise, result);
        return promise;
    };

    /**
    * @param {*=} result
    *
    * Creates a promise rejected with result.
    */
    Promise.reject = function Promise_createRejected(result) {
        var promise = Promise_create();
        Promise_reject(promise, result);
        return promise;
    };

    /**
    * @param {Array.<*>} promises
    *
    * Given array of promises or results, either resolves to array of results,
    * or rejects if any of the promises reject.
    */
    Promise.all = function Promise_all(promises) {
        var promise = Promise_create(),
            length = promises.length,
            results = [],
            // start +1, so we handle when there are no promises
            remaining = 1,
            result,
            i;

        function onFulfilled(index, result) {
            results[index] = result;
            if (!(--remaining)) {
                Promise_fulfill(promise, results, true);
            }
        }

        function onRejected(result) {
            Promise_reject(promise, result, true);
        }

        // TODO: handle CONVERT_THENABLES
        for(i = 0; i < length; i++) {
            result = promises[i];
            if (result && result._isPromise) {
                // it's a promise
                remaining++;
                result.then(
                    onFulfilled.bind(undefined, i),
                    onRejected
                );
            } else {
                results[i] = result;
            }
        }

        if (!(--remaining)) {
            // all were resolved before we even got here
            promise._fulfilled = true;
            promise._result = results;
        }

        return promise;
    };

    // --------------------------------------------------------------------------------
    // -- private implementation
    // --------------------------------------------------------------------------------

    /**
    * Used instead of "instanceof" for performance reasons.
    */
    Promise.prototype._isPromise = true;

    /**
    * Creates a promise without running the constructor function.
    */
    function Promise_create() {
        return Object.create(Promise.prototype);
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Fulfill the promise and resolve deferrals
    */
    function Promise_fulfill(promise, result, allowSynchResolution) {
        if (promise._fulfilled === undefined) {
            if (CONVERT_THENABLES) {
                Promise_fulfillThenable(promise, result);
            } else {
                promise._fulfilled = true;
                promise._result = result;
            }
            Promise_resolveDeferred(promise, allowSynchResolution);
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Reject the promise and resolve deferrals
    */
    function Promise_reject(promise, result, allowSynchResolution) {
        if (promise._fulfilled === undefined) {
            promise._fulfilled = false;
            promise._result = result;
            Promise_resolveDeferred(promise, allowSynchResolution);
        }
    }

    /**
    * Fulfill the promise, but check for result to be a thenable.
    * Thenable is an object that has obj.then(function resolve(){}, function reject(){}),
    * such as this or any other Promise implementations.
    */
    function Promise_fulfillThenable(promise, result) {
        var then;
        if (!result || typeof result === 'number' || typeof result === 'boolean' || result._isPromise) {
            // if the result is a primitive type,
            // or is a promise, use it as it is
            promise._fulfilled = true;
            promise._result = result;
        } else {
            try {
                // is this a then-able (has a ['then'] function), convert it to a Promise
                // handle "then" accessor throwing
                then = result.then;
                promise._fulfilled = true;
                if (typeof then !== 'function') {
                    // not a thenable, just use the result
                    promise._result = result;
                } else {
                    // convert the thenable to a promise
                    promise._result = new Promise(function (resolve, reject) {
                        then.call(result, resolve, reject);
                    });
                }
            } catch(e) {
                promise._fulfilled = false;
                promise._result = e;
            }
        }
    }

    /**
    * Once promise is resolved, resolve nextPromise
    */
    function Promise_whenResolved(promise, nextPromise) {
        if (promise._fulfilled !== undefined) {
            // we are resolved, resolve the given promise
            Promise_resolve(nextPromise, promise._fulfilled, promise._result);
        } else {
            // defer the resolution
            if (!promise._deferred) {
                promise._deferred = [];
            }
            promise._deferred.push(nextPromise);
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Resolves deffered promises
    */
    function Promise_resolveDeferred(promise, allowSynchResolution) {
        // assert(promise._fulfilled !== undefined)
        var deferred = promise._deferred,
            deferredLength,
            i;
        if (deferred) {
            promise._deferred = undefined;
            deferredLength = deferred.length;
            for(i = 0; i < deferredLength; i++) {
                Promise_resolve(deferred[i], promise._fulfilled, promise._result, allowSynchResolution);
            }
        }
    }

    /**
    * @param {boolean=} allowSynchResolution
    * Resolves promise (called by the one before, when it's resolved)
    */
    function Promise_resolve(promise, fulfilled, result, allowSynchResolution) {
        // assert(fulfilled !== undefined)
        var handler;

        if (fulfilled && result && result._isPromise) {
            // previous promise resolved to a promise, forward the promose
            Promise_whenResolved(result, promise);
        } else {
            // resolve promise
            // what handler will we use: onFulfilled or onRejected?
            if (fulfilled) {
                handler = promise._onFulfilled;
            } else {
                handler = promise._onRejected;
            }
            // kill the onFulfilled and onRejected we got from .then(onFulfilled, onRejected)
            promise._onFulfilled = undefined;
            promise._onRejected = undefined;
            // if there is a handler, dispatch... otherwise just settle in-line
            if (handler) {
                if (allowSynchResolution || ALWAYS_RESOLVE_SYNCHRONIOUSLY) {
                    // this flag indicates that this stack originated from the setTimeout
                    // no need to set another Timeout, and just run in same stack
                    Promise_handleResolution(promise, handler, result);
                } else {
                    // stack starts from user code, setTimeout so we start a new stack with only our code
                    // Spec quote: onFulfilled or onRejected must not be called until the
                    //             execution context stack contains only platform code.
                    setTimeout(Promise_handleResolution.bind(undefined, promise, handler, result), 0);
                }
            } else {
                if (fulfilled) {
                    Promise_fulfill(promise, result, allowSynchResolution);
                } else {
                    Promise_reject(promise, result, allowSynchResolution);
                }
            }
        }
    }

    /**
    * Call the handler: onFulfilled(result) or onRejected(result). And fulfill or reject based on outcome.
    */
    function Promise_handleResolution(promise, handler, result) {
        try {
            var newResult = handler(result);
            if (newResult === promise) {
                throw new TypeError();
            }
            Promise_fulfill(promise, newResult, true);
        } catch(e) {
            Promise_reject(promise, e, true);
        }
    }

    return Promise;
});<|endoftext|>


<commit_before>/* global cozy */
import { getList, createFetchAction, createFetchIfNeededAction, insertAction, deleteAction } from '../lists'
import Toolbar from './components/Toolbar'
import DeleteConfirm from './components/DeleteConfirm'
import { hideSelectionBar } from '../selection'
import { FILE_DOCTYPE, FETCH_LIMIT } from '../../constants/config'

// constants
const TIMELINE = 'timeline'

// selectors
export const getTimelineList = state => getList(state, TIMELINE)

// components
export { Toolbar }
export { DeleteConfirm }

// async actions
export const addPhotosToTimeline = photos => async dispatch => {
  dispatch(insertAction(TIMELINE, { entries: photos }))
}

export const deletePhotos = ids => async dispatch => {
  for (const id of ids) {
    try {
      await cozy.client.files.trashById(id)
      dispatch(deleteAction(TIMELINE, id))
    } catch (e) {
      console.log(e)
    }
    dispatch(hideSelectionBar())
  }
}

// list
const indexFilesByDate = async () => {
  const fields = [ 'class', 'trashed', 'metadata.datetime' ]
  return await cozy.client.data.defineIndex(FILE_DOCTYPE, fields)
}

const fetchPhotos = async (index, skip = 0) => {
  const options = {
    selector: {
      class: 'image',
      trashed: false
    },
    // TODO: type and class should not be necessary, it's just a temp fix for a stack bug
    fields: ['_id', 'dir_id', 'name', 'size', 'updated_at', 'metadata', 'type', 'class'],
    descending: true,
    limit: FETCH_LIMIT,
    skip,
    wholeResponse: true
  }
  const { data, meta } = await cozy.client.files.query(index, options)
  return {
    entries: data.map(p => Object.assign({ _id: p.id }, p, p.attributes)),
    next: meta.count > skip + FETCH_LIMIT,
    index,
    skip
  }
}

export const fetchIfNeededPhotos = createFetchIfNeededAction(TIMELINE, (index, skip = 0) => {
  return index
    ? fetchPhotos(index, skip)
    : indexFilesByDate().then(index => fetchPhotos(index, skip))
})

export const fetchMorePhotos = createFetchAction(TIMELINE, fetchPhotos)
<commit_msg>feat: Remove relation of photos :fire:<commit_after>/* global cozy */
import { getList, createFetchAction, createFetchIfNeededAction, insertAction, deleteAction } from '../lists'
import Toolbar from './components/Toolbar'
import DeleteConfirm from './components/DeleteConfirm'
import { hideSelectionBar } from '../selection'
import { FILE_DOCTYPE, FETCH_LIMIT, ALBUM_DOCTYPE } from '../../constants/config'

// constants
const TIMELINE = 'timeline'

// selectors
export const getTimelineList = state => getList(state, TIMELINE)

// components
export { Toolbar }
export { DeleteConfirm }

// async actions
export const addPhotosToTimeline = photos => async dispatch => {
  dispatch(insertAction(TIMELINE, { entries: photos }))
}

export const deletePhotos = ids => async dispatch => {
  for (const id of ids) {
    try {
      await cozy.client.files.trashById(id)
      dispatch(deleteAction(TIMELINE, id))
      const file = await cozy.client.data.find(FILE_DOCTYPE, id)
      for (const ref of file.referenced_by) {
        if (ref.type === ALBUM_DOCTYPE) {
          await cozy.client.data.removeReferencedFiles({ _id: ref.id, _type: ref.type }, id)
        }
      }
    } catch (e) {
      console.log(e)
    }
    dispatch(hideSelectionBar())
  }
}

// list
const indexFilesByDate = async () => {
  const fields = [ 'class', 'trashed', 'metadata.datetime' ]
  return await cozy.client.data.defineIndex(FILE_DOCTYPE, fields)
}

const fetchPhotos = async (index, skip = 0) => {
  const options = {
    selector: {
      class: 'image',
      trashed: false
    },
    // TODO: type and class should not be necessary, it's just a temp fix for a stack bug
    fields: ['_id', 'dir_id', 'name', 'size', 'updated_at', 'metadata', 'type', 'class'],
    descending: true,
    limit: FETCH_LIMIT,
    skip,
    wholeResponse: true
  }
  const { data, meta } = await cozy.client.files.query(index, options)
  return {
    entries: data.map(p => Object.assign({ _id: p.id }, p, p.attributes)),
    next: meta.count > skip + FETCH_LIMIT,
    index,
    skip
  }
}

export const fetchIfNeededPhotos = createFetchIfNeededAction(TIMELINE, (index, skip = 0) => {
  return index
    ? fetchPhotos(index, skip)
    : indexFilesByDate().then(index => fetchPhotos(index, skip))
})

export const fetchMorePhotos = createFetchAction(TIMELINE, fetchPhotos)
<|endoftext|>