<commit_before>window.cls || (window.cls = {});

/**
  * @constructor
  * @extends ViewBase
  */

cls.BreakpointsView = function(id, name, container_class)
{
  /* interface */

  this.show_and_edit_condition = function(script_id, line_no, event, target){};

  /* inherits from ViewBase */
  /* implements action handler interface */

  const JS_SOURCE_ID = 'js_source';

  const
  MODE_DEFAULT = "default",
  MODE_EDIT = "edit";

  /* action handler interface */

  ActionHandlerInterface.apply(this);

  this.onclick = function(event)
  {
    if (this.mode == MODE_EDIT)
    {
      if (this._editor.onclick(event))
      {
        this.mode = MODE_DEFAULT;
        return true;
      }
      return false;
    }
    return true;
  };

  this._handlers['toggle-breakpoint'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      this._toggle_bp(bp, event.target.checked);
    }
  }.bind(this);

  this._handlers['show-breakpoint-in-script-source'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      var js_source_view = window.views[JS_SOURCE_ID];
      if (!js_source_view.isvisible())
      {
        this._ui.show_view(JS_SOURCE_ID);
      }
      js_source_view.show_and_flash_line(bp.script_id, bp.line_nr);
    }
  }.bind(this);

  this._handlers['delete'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      this._delete_bp(bp);
    }
  }.bind(this);

  this._handlers['disable-all'] = function(event, target)
  {
    this._bps.get_active_breakpoints().forEach(function(bp)
    {
      if (bp.is_enabled)
      {
        this._toggle_bp(bp, false);
      }
    }, this);
  }.bind(this);

  this._handlers['delete-all'] = function(event, target)
  {
    this._bps.get_active_breakpoints().forEach(this._delete_bp, this);
  }.bind(this);

  this._handlers['add-or-edit-condition'] = function(event, target)
  {
    if (this.mode != MODE_EDIT)
    {
      var bp_ele = event.target.has_attr('parent-node-chain', 'data-breakpoint-id');
      this.mode = MODE_EDIT;
      var ele = bp_ele.getElementsByClassName('condition')[0] ||
                bp_ele.render(this._tmpls.breakpoint_condition());
      this._editor.edit(event, ele.firstElementChild);
    }
  }.bind(this);

  this._handlers['delete-condition'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    this._bps.set_condition("", bp_id);
  }.bind(this);

  this._handlers['submit'] = function(event, target)
  {
    if (this.mode == MODE_EDIT)
    {
      this._editor.submit();
      this.mode = MODE_DEFAULT;
      return false;
    }
  }.bind(this);

  this._handlers['cancel'] = function(event, target)
  {
    if (this.mode == MODE_EDIT)
    {
      this._editor.cancel();
      this.mode = MODE_DEFAULT;
      return false;
    }
  }.bind(this);

  this._toggle_bp = function(bp, is_checked)
  {
    if (bp.script_id)
    {
      if (is_checked)
      {
        bp.is_enabled = true;
        this._bps.add_breakpoint(bp.script_id, bp.line_nr, bp.id);
      }
      else
      {
        bp.is_enabled = false;
        this._bps.remove_breakpoint(bp.script_id, bp.line_nr);
      }
    }
    else if(bp.event_type)
    {
      bp.is_enabled = is_checked;
      this._ev_bps.handle_breakpoint_with_name(bp.event_type, is_checked);
    }
  };

  this._delete_bp = function(bp)
  {
    if (bp.is_enabled)
    {
      this._toggle_bp(bp, false);
    }
    this._bps.delete_breakpoint(bp.id);
  };

  /* rightclick menu */

  this._menu_common_items =
  [
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_BREAKPOINT,
      handler: this._handlers['delete'],
    },
    ContextMenu.separator,
    {
      label: ui_strings.M_CONTEXTMENU_DISABLE_ALL_BREAKPOINTS,
      handler: this._handlers['disable-all'],
    },
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_ALL_BREAKPOINTS,
      handler: this._handlers['delete-all'],
    }
  ];

  this._menu_add_condition =
  [
    {
      label: ui_strings.M_CONTEXTMENU_ADD_CONDITION,
      handler: this._handlers['add-or-edit-condition'],
    }
  ]
  .concat(this._menu_common_items);

  this._menu_edit_condition =
  [
    {
      label: ui_strings.M_CONTEXTMENU_EDIT_CONDITION,
      handler: this._handlers['add-or-edit-condition'],
    },
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_CONDITION,
      handler: this._handlers['delete-condition']
    }
  ]
  .concat(this._menu_common_items);

  this._menu =
  [
    {
      callback: function(event, target)
      {
        var bp_ele = event.target.has_attr('parent-node-chain',
                                           'data-breakpoint-id');
        var has_condition = bp_ele && bp_ele.getElementsByClassName('condition')[0];
        return bp_ele
             ? (has_condition
               ? this._menu_edit_condition
               : this._menu_add_condition)
             : null;
      }.bind(this)
    }
  ];

  this._init = function(id, name, container_class)
  {
    this.init(id, name, container_class, null, null, 'breakpoints-edit');
    this._editor = new window.cls.ConditionEditor(this);
    this._bps = cls.Breakpoints.get_instance();
    this._ev_bps = cls.EventBreakpoints.get_instance();
    this._tmpls = window.templates;
    var ev_hs = window.eventHandlers;
    ev_hs.change['toggle-breakpoint'] = this._handlers['toggle-breakpoint'];
    ev_hs.click['show-breakpoint-in-script-source'] = this._handlers['show-breakpoint-in-script-source'];
    ev_hs.click['disable-all-breakpoints'] =  this._handlers['disable-all'];
    ev_hs.click['delete-all-breakpoints'] =  this._handlers['delete-all'];
    ev_hs.dblclick['edit-condition'] =  this._handlers['add-or-edit-condition'];
    ActionBroker.get_instance().register_handler(this);
    ContextMenu.get_instance().register("breakpoints", this._menu);
    window.messages.addListener('breakpoint-updated', function(){this.update()}.bind(this));
  };

  /* implementation */

  this.createView = function(container)
  {
    var bps = this._bps.get_active_breakpoints();
    if (bps.length)
    {
      container.clearAndRender(bps.map(this._tmpls.breakpoint, this._tmpls));
    }
    else
    {
      container.clearAndRender(this._tmpls.no_breakpoints());
    }
  };

  this.ondestroy = function()
  {

  };

  this.add_condition = function(condition, bp_id)
  {
    this._bps.set_condition(condition, bp_id);
    this.update();
  }

  this.show_and_edit_condition = function(script_id, line_no, event, target)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      var bp_id = script.breakpoints[line_no];
      var broker = ActionBroker.get_instance();
      if (!this.isvisible())
      {
        window.topCell.showView(this.id);
      }
      var container = this.get_container();
      var bp_ele = container &&
                   container.querySelector("[data-breakpoint-id='" + bp_id + "']");
      if (bp_ele)
      {
        var event = {target: bp_ele.getElementsByTagName('div')[0]};
        this._handlers['add-or-edit-condition'](event, bp_ele);
      }
    }
  };

  this._init(id, name, container_class);

};

cls.BreakpointsView.create_ui_widgets = function()
{
  new ToolbarConfig
  (
    'breakpoints',
    [
      {
        handler: 'disable-all-breakpoints',
        title: "Disable all breakpoints",
      },
      {
        handler: 'delete-all-breakpoints',
        title: "Delete all breakpoints",
      },
    ]
  );
}
<commit_msg>Fixed hardcoded strings, used M_CONTEXTMENU_DISABLE_ALL_BREAKPOINTS and M_CONTEXTMENU_DELETE_ALL_BREAKPOINTS instead.<commit_after>window.cls || (window.cls = {});

/**
  * @constructor
  * @extends ViewBase
  */

cls.BreakpointsView = function(id, name, container_class)
{
  /* interface */

  this.show_and_edit_condition = function(script_id, line_no, event, target){};

  /* inherits from ViewBase */
  /* implements action handler interface */

  const JS_SOURCE_ID = 'js_source';

  const
  MODE_DEFAULT = "default",
  MODE_EDIT = "edit";

  /* action handler interface */

  ActionHandlerInterface.apply(this);

  this.onclick = function(event)
  {
    if (this.mode == MODE_EDIT)
    {
      if (this._editor.onclick(event))
      {
        this.mode = MODE_DEFAULT;
        return true;
      }
      return false;
    }
    return true;
  };

  this._handlers['toggle-breakpoint'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      this._toggle_bp(bp, event.target.checked);
    }
  }.bind(this);

  this._handlers['show-breakpoint-in-script-source'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      var js_source_view = window.views[JS_SOURCE_ID];
      if (!js_source_view.isvisible())
      {
        this._ui.show_view(JS_SOURCE_ID);
      }
      js_source_view.show_and_flash_line(bp.script_id, bp.line_nr);
    }
  }.bind(this);

  this._handlers['delete'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    var bp = this._bps.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      this._delete_bp(bp);
    }
  }.bind(this);

  this._handlers['disable-all'] = function(event, target)
  {
    this._bps.get_active_breakpoints().forEach(function(bp)
    {
      if (bp.is_enabled)
      {
        this._toggle_bp(bp, false);
      }
    }, this);
  }.bind(this);

  this._handlers['delete-all'] = function(event, target)
  {
    this._bps.get_active_breakpoints().forEach(this._delete_bp, this);
  }.bind(this);

  this._handlers['add-or-edit-condition'] = function(event, target)
  {
    if (this.mode != MODE_EDIT)
    {
      var bp_ele = event.target.has_attr('parent-node-chain', 'data-breakpoint-id');
      this.mode = MODE_EDIT;
      var ele = bp_ele.getElementsByClassName('condition')[0] ||
                bp_ele.render(this._tmpls.breakpoint_condition());
      this._editor.edit(event, ele.firstElementChild);
    }
  }.bind(this);

  this._handlers['delete-condition'] = function(event, target)
  {
    var bp_id = parseInt(event.target.get_attr('parent-node-chain',
                                               'data-breakpoint-id'));
    this._bps.set_condition("", bp_id);
  }.bind(this);

  this._handlers['submit'] = function(event, target)
  {
    if (this.mode == MODE_EDIT)
    {
      this._editor.submit();
      this.mode = MODE_DEFAULT;
      return false;
    }
  }.bind(this);

  this._handlers['cancel'] = function(event, target)
  {
    if (this.mode == MODE_EDIT)
    {
      this._editor.cancel();
      this.mode = MODE_DEFAULT;
      return false;
    }
  }.bind(this);

  this._toggle_bp = function(bp, is_checked)
  {
    if (bp.script_id)
    {
      if (is_checked)
      {
        bp.is_enabled = true;
        this._bps.add_breakpoint(bp.script_id, bp.line_nr, bp.id);
      }
      else
      {
        bp.is_enabled = false;
        this._bps.remove_breakpoint(bp.script_id, bp.line_nr);
      }
    }
    else if(bp.event_type)
    {
      bp.is_enabled = is_checked;
      this._ev_bps.handle_breakpoint_with_name(bp.event_type, is_checked);
    }
  };

  this._delete_bp = function(bp)
  {
    if (bp.is_enabled)
    {
      this._toggle_bp(bp, false);
    }
    this._bps.delete_breakpoint(bp.id);
  };

  /* rightclick menu */

  this._menu_common_items =
  [
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_BREAKPOINT,
      handler: this._handlers['delete'],
    },
    ContextMenu.separator,
    {
      label: ui_strings.M_CONTEXTMENU_DISABLE_ALL_BREAKPOINTS,
      handler: this._handlers['disable-all'],
    },
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_ALL_BREAKPOINTS,
      handler: this._handlers['delete-all'],
    }
  ];

  this._menu_add_condition =
  [
    {
      label: ui_strings.M_CONTEXTMENU_ADD_CONDITION,
      handler: this._handlers['add-or-edit-condition'],
    }
  ]
  .concat(this._menu_common_items);

  this._menu_edit_condition =
  [
    {
      label: ui_strings.M_CONTEXTMENU_EDIT_CONDITION,
      handler: this._handlers['add-or-edit-condition'],
    },
    {
      label: ui_strings.M_CONTEXTMENU_DELETE_CONDITION,
      handler: this._handlers['delete-condition']
    }
  ]
  .concat(this._menu_common_items);

  this._menu =
  [
    {
      callback: function(event, target)
      {
        var bp_ele = event.target.has_attr('parent-node-chain',
                                           'data-breakpoint-id');
        var has_condition = bp_ele && bp_ele.getElementsByClassName('condition')[0];
        return bp_ele
             ? (has_condition
               ? this._menu_edit_condition
               : this._menu_add_condition)
             : null;
      }.bind(this)
    }
  ];

  this._init = function(id, name, container_class)
  {
    this.init(id, name, container_class, null, null, 'breakpoints-edit');
    this._editor = new window.cls.ConditionEditor(this);
    this._bps = cls.Breakpoints.get_instance();
    this._ev_bps = cls.EventBreakpoints.get_instance();
    this._tmpls = window.templates;
    var ev_hs = window.eventHandlers;
    ev_hs.change['toggle-breakpoint'] = this._handlers['toggle-breakpoint'];
    ev_hs.click['show-breakpoint-in-script-source'] = this._handlers['show-breakpoint-in-script-source'];
    ev_hs.click['disable-all-breakpoints'] =  this._handlers['disable-all'];
    ev_hs.click['delete-all-breakpoints'] =  this._handlers['delete-all'];
    ev_hs.dblclick['edit-condition'] =  this._handlers['add-or-edit-condition'];
    ActionBroker.get_instance().register_handler(this);
    ContextMenu.get_instance().register("breakpoints", this._menu);
    window.messages.addListener('breakpoint-updated', function(){this.update()}.bind(this));
  };

  /* implementation */

  this.createView = function(container)
  {
    var bps = this._bps.get_active_breakpoints();
    if (bps.length)
    {
      container.clearAndRender(bps.map(this._tmpls.breakpoint, this._tmpls));
    }
    else
    {
      container.clearAndRender(this._tmpls.no_breakpoints());
    }
  };

  this.ondestroy = function()
  {

  };

  this.add_condition = function(condition, bp_id)
  {
    this._bps.set_condition(condition, bp_id);
    this.update();
  }

  this.show_and_edit_condition = function(script_id, line_no, event, target)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      var bp_id = script.breakpoints[line_no];
      var broker = ActionBroker.get_instance();
      if (!this.isvisible())
      {
        window.topCell.showView(this.id);
      }
      var container = this.get_container();
      var bp_ele = container &&
                   container.querySelector("[data-breakpoint-id='" + bp_id + "']");
      if (bp_ele)
      {
        var event = {target: bp_ele.getElementsByTagName('div')[0]};
        this._handlers['add-or-edit-condition'](event, bp_ele);
      }
    }
  };

  this._init(id, name, container_class);

};

cls.BreakpointsView.create_ui_widgets = function()
{
  new ToolbarConfig
  (
    'breakpoints',
    [
      {
        handler: 'disable-all-breakpoints',
        title: ui_strings.M_CONTEXTMENU_DISABLE_ALL_BREAKPOINTS,
      },
      {
        handler: 'delete-all-breakpoints',
        title: ui_strings.M_CONTEXTMENU_DELETE_ALL_BREAKPOINTS,
      },
    ]
  );
}
<|endoftext|>


<commit_before><commit_msg>Creating setRoutesUrl method<commit_after><|endoftext|>


<commit_before>/** @jsx React.DOM */
'use strict';
var React = require('react');
var FetchedData = require('./fetched').FetchedData;
var Form = require('./form').Form;
var globals = require('./globals');

    var Item = module.exports.Item = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-item');
            var title = globals.listing_titles.lookup(context)({context: context});
            var panel = globals.panel_views.lookup(context)();

            // Make string of alternate accessions
            var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

            this.transferPropsTo(panel);
            return (

{title}

                            {altacc ?
Replaces {altacc}
 : null}

                    {context.description ?
{context.description}
 : null}
                    {panel}

            );
        }
    });

    globals.content_views.register(Item, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.content_views.fallback = function () {
        return Item;
    };

    var Panel = module.exports.Panel = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-detail panel');
            return (

{JSON.stringify(context, null, 4)}

            );
        }
    });

    globals.panel_views.register(Panel, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.panel_views.fallback = function () {
        return Panel;
    };

    var title = module.exports.title = function (props) {
        var context = props.context;
        return context.title || context.name || context.accession || context['@id'];
    };

    globals.listing_titles.register(title, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.listing_titles.fallback = function () {
        return title;
    };

    var ItemEdit = module.exports.ItemEdit = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-item');
            var title = globals.listing_titles.lookup(context)({context: context});
            var action, form;
            if (context['@type'][0].indexOf('_collection') !== -1) {  // add form
                title = 'Add ' + title;
                action = this.props.context['@id'];
                form = <Form schema={this.props.schema} action={action} value={this.props.defaultValue} method="POST" />;
            } else {  // edit form
                title = 'Edit ' + title;
                var url = this.props.context['@id'] + '?frame=edit';
                action = this.props.context['@id'];
                form = <FetchedData fetched_prop_name="value" Component={Form} url={url} schema={this.props.schema} action={action} method="PUT" />;
            }
            return (

{title}

                    {this.transferPropsTo(form)}

            );
        }
    });
<commit_msg>Use defaultValue rather than value to fix form.<commit_after>/** @jsx React.DOM */
'use strict';
var React = require('react');
var FetchedData = require('./fetched').FetchedData;
var Form = require('./form').Form;
var globals = require('./globals');

    var Item = module.exports.Item = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-item');
            var title = globals.listing_titles.lookup(context)({context: context});
            var panel = globals.panel_views.lookup(context)();

            // Make string of alternate accessions
            var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

            this.transferPropsTo(panel);
            return (

{title}

                            {altacc ?
Replaces {altacc}
 : null}

                    {context.description ?
{context.description}
 : null}
                    {panel}

            );
        }
    });

    globals.content_views.register(Item, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.content_views.fallback = function () {
        return Item;
    };

    var Panel = module.exports.Panel = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-detail panel');
            return (

{JSON.stringify(context, null, 4)}

            );
        }
    });

    globals.panel_views.register(Panel, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.panel_views.fallback = function () {
        return Panel;
    };

    var title = module.exports.title = function (props) {
        var context = props.context;
        return context.title || context.name || context.accession || context['@id'];
    };

    globals.listing_titles.register(title, 'item');

    // Also use this view as a fallback for anything we haven't registered
    globals.listing_titles.fallback = function () {
        return title;
    };

    var ItemEdit = module.exports.ItemEdit = React.createClass({
        render: function() {
            var context = this.props.context;
            var itemClass = globals.itemClass(context, 'view-item');
            var title = globals.listing_titles.lookup(context)({context: context});
            var action, form;
            if (context['@type'][0].indexOf('_collection') !== -1) {  // add form
                title = 'Add ' + title;
                action = this.props.context['@id'];
                form = <Form schema={this.props.schema} action={action} defaultValue={this.props.defaultValue} method="POST" />;
            } else {  // edit form
                title = 'Edit ' + title;
                var url = this.props.context['@id'] + '?frame=edit';
                action = this.props.context['@id'];
                form = <FetchedData fetched_prop_name="defaultValue" Component={Form} url={url} schema={this.props.schema} action={action} method="PUT" />;
            }
            return (

{title}

                    {this.transferPropsTo(form)}

            );
        }
    });
<|endoftext|>


<commit_before>import promiseAllProperties from 'promise-all-properties';
import { flatten } from 'lodash';
import { getDefault } from '../../shared/util/ModuleUtil';
import logger from '../../shared/logger';
import isPojo from '../util/is-pojo';
import { Symbols } from './decorators/provider';
import createAsyncInjectors from './create-async-injectors';

export default function createRoutes(store) {

  const routeLoader = require.context('@@directories.routes', true, /\.js$/);
  const fileNames = routeLoader.keys();

  if (fileNames.length === 0) {
    logger.warn('Your framework does not contain any route. Add your route descriptions in the directory specified by the "directories.routes" entry of your framework configuration file.');
  }

  const injectors = createAsyncInjectors(store);

  return fileNames
    .map(file => {
      const route = getDefault(routeLoader(file));

      if (route.status === 404) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER + 1;
        route.path = route.path || '*';
      }

      if (route.status && Math.floor(route.status / 100) !== 2) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER;
        route.path = route.path || '*';
      }

      return route;
    })
    .sort((a, b) => (b.priority || 0) - (a.priority || 0))
    .map((route, i) => sanitizeRoute(route, injectors, store, fileNames[i]));
}

function assertUnique(singularMethodName, routeData, fileName) {
  const pluralMethodName = `${singularMethodName}s`;

  if (routeData[singularMethodName] && routeData[pluralMethodName]) {
    throw new TypeError(`Route ${JSON.stringify(fileName)}: cannot have both methods ${singularMethodName} and ${pluralMethodName} in the same route description.`);
  }
}

function sanitizeRoute(routeData, injectors, store, fileName) {

  assertUnique('getComponent', routeData, fileName);
  assertUnique('getSaga', routeData, fileName);
  assertUnique('getProvider', routeData, fileName);
  assertUnique('getReducer', routeData, fileName);

  // Add other possible sanitizations here.
  const route = Object.assign({}, routeData);

  if (route.getComponent) {
    route.getComponent = hookGetComponent(routeData, injectors, store, fileName);
  } else if (route.getComponents) {
    route.getComponents = hookGetComponent(routeData, injectors, store, fileName);
  } else {
    throw new TypeError(`Missing method getComponent(s) on route ${JSON.stringify(fileName)}`);
  }

  // onEnter(nextState, replace, callback?)
  // onChange(prevState, nextState, replace, callback?)
  // onLeave(prevState)
  if (route.onEnter) {
    const oldOnEnter = route.onEnter;
    route.onEnter = function onEnter(nextState, replace) {
      return oldOnEnter.call(this, nextState, replace, store);
    };
  }

  if (route.onChange) {
    const oldOnChange = route.onChange;
    route.onChange = function onChange(prevState, nextState, replace) {
      return oldOnChange.call(this, prevState, nextState, replace, store);
    };
  }

  if (route.onLeave) {
    const oldOnLeave = route.onLeave;
    route.onLeave = function onLeave(prevState) {
      return oldOnLeave.call(this, prevState, store);
    };
  }

  delete route.getSaga;
  delete route.getSagas;
  delete route.getReducer;
  delete route.getReducers;
  delete route.getProvider;
  delete route.getProviders;
  delete route.priority;

  if (route.children && route.childRoutes) {
    throw new TypeError(`Route ${JSON.stringify(fileName)} declares children twice (.children & .childRoutes), please use either methods.`);
  }

  if (route.children) {
    route.childRoutes = route.children;
    delete route.children;
  }

  if (route.childRoutes) {
    if (Array.isArray(route.childRoutes)) {
      route.childRoutes = route.childRoutes.map(subRoute => sanitizeRoute(subRoute, injectors, store, fileName));
    } else {
      route.childRoutes = [sanitizeRoute(route.childRoutes, injectors, store, fileName)];
    }
  }

  if (route.indexRoute) {
    route.indexRoute = sanitizeRoute(route.indexRoute, injectors, store, fileName);
  }

  return route;
}

function hookGetComponent(route, injectors, store, fileName) {
  return async function callbackGetComponent(nextState) {

    try {
      const [component, sagas, reducers, providers] = await Promise.all([
        callComponentLoader(route, nextState, store, fileName),
        callSagaLoader(route, nextState, store),
        callReducerLoader(route, nextState, store),
        callProviderLoader(route, nextState, store),
      ]);

      injectSagas(injectors, sagas);
      injectReducers(injectors, reducers);

      if (providers) {
        for (const provider of providers) {
          injectSagas(injectors, provider[Symbols.sagas]);
          injectReducers(injectors, provider[Symbols.reducer]);
        }
      }

      return component;
    } catch (e) {
      logger.error(`Error while loading route ${JSON.stringify(fileName)}`, e);
      throw e;
    }
  };
}

function injectSagas(injectors, sagas) {
  if (sagas && sagas.length > 0) {
    injectors.injectSagas(sagas);
  }
}

function injectReducers(injectors, reducers) {
  if (!reducers) {
    return;
  }

  if (!Array.isArray(reducers)) {
    injectors.injectReducer(reducers);
    return;
  }

  for (const reducer of reducers) {
    injectors.injectReducer(reducer);
  }
}

async function callComponentLoader(route, nextState, store, fileName) {
  const method = route.getComponent || route.getComponents;

  const components = await callLoader(method, route, nextState, store);

  if (!components) {
    throw new TypeError(`${JSON.stringify(fileName)}: getComponent(s) returned an invalid module.`);
  }

  if (!isPojo(components)) {
    return components;
  }

  return promiseAllProperties(components);
}

async function callSagaLoader(route, nextState, store) {
  const method = route.getSaga || route.getSagas;
  const sagas = toArray(await callLoader(method, route, nextState, store));

  return sagas ? flatten(sagas) : sagas;
}

async function callProviderLoader(route, nextState, store) {
  const method = route.getProvider || route.getProviders;
  const providers = toArray(await callLoader(method, route, nextState, store));

  return providers ? flatten(providers) : providers;
}

/*
 * Unifies the possible outputs of route.getReducer-s
 */
async function callReducerLoader(route, nextState, store) {
  const method = route.getReducer || route.getReducers;
  return toArray(await callLoader(method, route, nextState, store));
}

async function callLoader(loader, route, nextState, store) {
  if (!loader) {
    return null;
  }

  const rawOutput = await loader.call(route, nextState, store);

  if (rawOutput == null) {
    return null;
  }

  if (Array.isArray(rawOutput)) {
    if (rawOutput.length === 0) {
      return null;
    }

    const arrayOutput = await Promise.all(rawOutput);
    const arrayResult = [];
    for (let i = 0; i < arrayOutput.length; i++) {
      const item = arrayOutput[i];
      if (item != null) {
        arrayResult.push(getDefault(item));
      }
    }

    return arrayResult;
  }

  return getDefault(rawOutput);
}

function toArray(obj) {
  if (obj == null) {
    return [];
  }

  if (Array.isArray(obj)) {
    return obj;
  }

  return [obj];
}
<commit_msg>Inject all reducers & sagas in one batch (routes)<commit_after>import promiseAllProperties from 'promise-all-properties';
import { flatten } from 'lodash';
import { getDefault } from '../../shared/util/ModuleUtil';
import logger from '../../shared/logger';
import isPojo from '../util/is-pojo';
import { Symbols } from './decorators/provider';
import createAsyncInjectors from './create-async-injectors';

export default function createRoutes(store) {

  const routeLoader = require.context('@@directories.routes', true, /\.js$/);
  const fileNames = routeLoader.keys();

  if (fileNames.length === 0) {
    logger.warn('Your framework does not contain any route. Add your route descriptions in the directory specified by the "directories.routes" entry of your framework configuration file.');
  }

  const injectors = createAsyncInjectors(store);

  return fileNames
    .map(file => {
      const route = getDefault(routeLoader(file));

      if (route.status === 404) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER + 1;
        route.path = route.path || '*';
      }

      if (route.status && Math.floor(route.status / 100) !== 2) {
        route.priority = route.priority || Number.MIN_SAFE_INTEGER;
        route.path = route.path || '*';
      }

      return route;
    })
    .sort((a, b) => (b.priority || 0) - (a.priority || 0))
    .map((route, i) => sanitizeRoute(route, injectors, store, fileNames[i]));
}

function assertUnique(singularMethodName, routeData, fileName) {
  const pluralMethodName = `${singularMethodName}s`;

  if (routeData[singularMethodName] && routeData[pluralMethodName]) {
    throw new TypeError(`Route ${JSON.stringify(fileName)}: cannot have both methods ${singularMethodName} and ${pluralMethodName} in the same route description.`);
  }
}

function sanitizeRoute(routeData, injectors, store, fileName) {

  assertUnique('getComponent', routeData, fileName);
  assertUnique('getSaga', routeData, fileName);
  assertUnique('getProvider', routeData, fileName);
  assertUnique('getReducer', routeData, fileName);

  // Add other possible sanitizations here.
  const route = Object.assign({}, routeData);

  if (route.getComponent) {
    route.getComponent = hookGetComponent(routeData, injectors, store, fileName);
  } else if (route.getComponents) {
    route.getComponents = hookGetComponent(routeData, injectors, store, fileName);
  } else {
    throw new TypeError(`Missing method getComponent(s) on route ${JSON.stringify(fileName)}`);
  }

  // onEnter(nextState, replace, callback?)
  // onChange(prevState, nextState, replace, callback?)
  // onLeave(prevState)
  if (route.onEnter) {
    const oldOnEnter = route.onEnter;
    route.onEnter = function onEnter(nextState, replace) {
      return oldOnEnter.call(this, nextState, replace, store);
    };
  }

  if (route.onChange) {
    const oldOnChange = route.onChange;
    route.onChange = function onChange(prevState, nextState, replace) {
      return oldOnChange.call(this, prevState, nextState, replace, store);
    };
  }

  if (route.onLeave) {
    const oldOnLeave = route.onLeave;
    route.onLeave = function onLeave(prevState) {
      return oldOnLeave.call(this, prevState, store);
    };
  }

  delete route.getSaga;
  delete route.getSagas;
  delete route.getReducer;
  delete route.getReducers;
  delete route.getProvider;
  delete route.getProviders;
  delete route.priority;

  if (route.children && route.childRoutes) {
    throw new TypeError(`Route ${JSON.stringify(fileName)} declares children twice (.children & .childRoutes), please use either methods.`);
  }

  if (route.children) {
    route.childRoutes = route.children;
    delete route.children;
  }

  if (route.childRoutes) {
    if (Array.isArray(route.childRoutes)) {
      route.childRoutes = route.childRoutes.map(subRoute => sanitizeRoute(subRoute, injectors, store, fileName));
    } else {
      route.childRoutes = [sanitizeRoute(route.childRoutes, injectors, store, fileName)];
    }
  }

  if (route.indexRoute) {
    route.indexRoute = sanitizeRoute(route.indexRoute, injectors, store, fileName);
  }

  return route;
}

function hookGetComponent(route, injectors, store, fileName) {
  return async function callbackGetComponent(nextState) {

    try {
      const [component, sagas, reducers, providers] = await Promise.all([
        callComponentLoader(route, nextState, store, fileName),
        callSagaLoader(route, nextState, store),
        callReducerLoader(route, nextState, store),
        callProviderLoader(route, nextState, store),
      ]);

      if (providers) {
        for (const provider of providers) {
          const newSagas = provider[Symbols.sagas];
          if (newSagas) {
            sagas.push(...newSagas);
          }

          const newReducer = provider[Symbols.reducer];
          if (newReducer) {
            reducers.push(newReducer);
          }
        }
      }

      injectors.injectSagas(sagas);
      injectors.injectReducer(reducers);

      return component;
    } catch (e) {
      logger.error(`Error while loading route ${JSON.stringify(fileName)}`, e);
      throw e;
    }
  };
}

async function callComponentLoader(route, nextState, store, fileName) {
  const method = route.getComponent || route.getComponents;

  const components = await callLoader(method, route, nextState, store);

  if (!components) {
    throw new TypeError(`${JSON.stringify(fileName)}: getComponent(s) returned an invalid module.`);
  }

  if (!isPojo(components)) {
    return components;
  }

  return promiseAllProperties(components);
}

async function callSagaLoader(route, nextState, store) {
  const method = route.getSaga || route.getSagas;
  const sagas = toArray(await callLoader(method, route, nextState, store));

  return sagas ? flatten(sagas) : sagas;
}

async function callProviderLoader(route, nextState, store) {
  const method = route.getProvider || route.getProviders;
  const providers = toArray(await callLoader(method, route, nextState, store));

  return providers ? flatten(providers) : providers;
}

/*
 * Unifies the possible outputs of route.getReducer-s
 */
async function callReducerLoader(route, nextState, store) {
  const method = route.getReducer || route.getReducers;
  return toArray(await callLoader(method, route, nextState, store));
}

async function callLoader(loader, route, nextState, store) {
  if (!loader) {
    return null;
  }

  const rawOutput = await loader.call(route, nextState, store);

  if (rawOutput == null) {
    return null;
  }

  if (Array.isArray(rawOutput)) {
    if (rawOutput.length === 0) {
      return null;
    }

    const arrayOutput = await Promise.all(rawOutput);
    const arrayResult = [];
    for (let i = 0; i < arrayOutput.length; i++) {
      const item = arrayOutput[i];
      if (item != null) {
        arrayResult.push(getDefault(item));
      }
    }

    if (arrayResult.length === 0) {
      return null;
    }

    return arrayResult;
  }

  return getDefault(rawOutput);
}

function toArray(obj) {
  if (obj == null) {
    return [];
  }

  if (Array.isArray(obj)) {
    return obj;
  }

  return [obj];
}
<|endoftext|>


<commit_before>var spawnSync = require('child_process').spawnSync;

function checkSuccess(result) {
  var stderr = result.stderr;
  if (stderr && stderr.length) {
    throw new Error(stderr + '');
  }
}

function getKeyChain() {
  var result = spawnSync('security', ['default-keychain']);
  checkSuccess(result);
  return (result.stdout + '').split('"')[1];
}

function installMac(certPath) {
  var result = spawnSync('security', ['add-trusted-cert', '-k', getKeyChain(), certPath]);
  checkSuccess(result);
  var msg = result.stdout + '';
  if (/Error:/i.test(msg)) {
    throw new Error(msg);
  }
}

function installWin(certFile) {
  var result = spawnSync('certutil', ['-addstore', '-user', 'Root', certFile]);
  checkSuccess(result);
  if (/ERROR_CANCELLED/i.test(result.stdout + '')) {
    throw new Error('The authorization was canceled by the user.');
  }
}

module.exports = function(certFile) {
  var platform = process.platform;
  if (platform === 'darwin') {
    return installMac(certFile);
  }
  if (platform === 'win32') {
    return installWin(certFile);
  }
  throw new Error('Platform ' + platform + ' is unsupported to install Root CA for now.');
};
<commit_msg>chore: refine wording<commit_after>var spawnSync = require('child_process').spawnSync;

function checkSuccess(result) {
  var stderr = result.stderr;
  if (stderr && stderr.length) {
    throw new Error(stderr + '');
  }
}

function getKeyChain() {
  var result = spawnSync('security', ['default-keychain']);
  checkSuccess(result);
  return (result.stdout + '').split('"')[1];
}

function installMac(certPath) {
  var result = spawnSync('security', ['add-trusted-cert', '-k', getKeyChain(), certPath]);
  checkSuccess(result);
  var msg = result.stdout + '';
  if (/Error:/i.test(msg)) {
    throw new Error(msg);
  }
}

function installWin(certFile) {
  var result = spawnSync('certutil', ['-addstore', '-user', 'Root', certFile]);
  checkSuccess(result);
  if (/ERROR_CANCELLED/i.test(result.stdout + '')) {
    throw new Error('The authorization was canceled by the user.');
  }
}

module.exports = function(certFile) {
  var platform = process.platform;
  if (platform === 'darwin') {
    return installMac(certFile);
  }
  if (platform === 'win32') {
    return installWin(certFile);
  }
  throw new Error('Platform ' + platform + ' is unsupported to install root CA for now.');
};
<|endoftext|>


<commit_before>'use strict';

const request = require('request'); // "Request" library
const querystring = require('querystring');
const Promise = require('bluebird');

const randomSessionID = function randomSessionID() {
  let text = '';
  const possible = '0123456789';

  for (let i = 0; i < 6; i += 1) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return text;
};

function authInit(body, code, req, res, stateKey, spotifyApi, sessions) {
  spotifyApi.setAccessToken(body.access_token);

  let persistentSessionID = '';

  // get the user's data
  const sessionPromise = spotifyApi.getMe()
    .then((data) => {
      // create a session ID for the session
      let sessionID = randomSessionID();
      while (Object.keys(sessions).indexOf(sessionID) !== -1) {
        sessionID = randomSessionID();
      }

      // find the display name and user ID of the session
      const displayName = data.body.display_name;
      const userID = data.body.id;

      // create the session in sessions and attach a reference to it
      sessions[sessionID] = {
        sessionID,
        displayName,
        userID,
        playlistTracks: [],
        queuedTracks: [],
        guests: {},
        hostIP: req.ip,
        lastQueuedPosition: -1,
        accessToken: body.access_token,
        refresh_token: body.refresh_token,
      };
      const thisSession = sessions[sessionID];
      persistentSessionID = sessionID;

      // return the current session so that future promises can use it
      return thisSession;
    })
    .catch((err) => {
      console.error(err);
    });

  const getAllPlaylistsPromise = sessionPromise
    .then((session) => {
      return spotifyApi.getUserPlaylists(session.userID);
    })
    .catch(err => console.log('error: ' + err));

  getAllPlaylistsPromise
    .then((playlists) => {
      const sanitizedPlaylists = playlists.body.items.map(
        playlist => ({ name: playlist.name, uri: playlist.uri }));
      const queryPlaylists = {};
      for (let i = 0; i < 10; i += 1) {
        queryPlaylists['playlist_' + i + '_name'] = sanitizedPlaylists[i].name;
        queryPlaylists['playlist_' + i + '_uri'] = sanitizedPlaylists[i].uri;
      }
      queryPlaylists.session_id = persistentSessionID;
      res.redirect(
        '/playlist.html#' + querystring.stringify(queryPlaylists));
    })
    .catch(err => console.log(err));

}

function initializeAuxify(code, req, res, stateKey, spotifyApi, sessions, connectionConfig) {
  const clientId = connectionConfig.clientId;
  const clientSecret = connectionConfig.clientSecret;
  const redirectUri = connectionConfig.redirectUri;
  // here we go
  res.clearCookie(stateKey);

  const authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    form: {
      code,
      redirect_uri: redirectUri,
      grant_type: 'authorization_code',
    },
    headers: {
      Authorization: 'Basic ' + (new Buffer(clientId + ':' + clientSecret).toString('base64')),
    },
    json: true,
  };

  request.post(authOptions, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      authInit(body, code, req, res, stateKey, spotifyApi, sessions);
    } else {
      res.redirect(`/#${
        querystring.stringify({
          error,
        })}`);
    }
  });
}

module.exports = function callback(req, res, stateKey, spotifyApi, sessions, connectionConfig) {
  // the application requests refresh and access tokens
  // after checking the state parameter

  const code = req.query.code || null;
  const state = req.query.state || null;
  const storedState = req.cookies ? req.cookies[stateKey] : null;

  if (state === null || state !== storedState) {
    res.redirect(`/#${
      querystring.stringify({
        error: 'state_mismatch',
        state: JSON.stringify(state),
      })}`);
  } else {
    initializeAuxify(code, req, res, stateKey, spotifyApi, sessions, connectionConfig);
  }
};
<commit_msg>commented out state checks<commit_after>'use strict';

const request = require('request'); // "Request" library
const querystring = require('querystring');
const Promise = require('bluebird');

const randomSessionID = function randomSessionID() {
  let text = '';
  const possible = '0123456789';

  for (let i = 0; i < 6; i += 1) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return text;
};

function authInit(body, code, req, res, stateKey, spotifyApi, sessions) {
  spotifyApi.setAccessToken(body.access_token);

  let persistentSessionID = '';

  // get the user's data
  const sessionPromise = spotifyApi.getMe()
    .then((data) => {
      // create a session ID for the session
      let sessionID = randomSessionID();
      while (Object.keys(sessions).indexOf(sessionID) !== -1) {
        sessionID = randomSessionID();
      }

      // find the display name and user ID of the session
      const displayName = data.body.display_name;
      const userID = data.body.id;

      // create the session in sessions and attach a reference to it
      sessions[sessionID] = {
        sessionID,
        displayName,
        userID,
        playlistTracks: [],
        queuedTracks: [],
        guests: {},
        hostIP: req.ip,
        lastQueuedPosition: -1,
        accessToken: body.access_token,
        refresh_token: body.refresh_token,
      };
      const thisSession = sessions[sessionID];
      persistentSessionID = sessionID;

      // return the current session so that future promises can use it
      return thisSession;
    })
    .catch((err) => {
      console.error(err);
    });

  const getAllPlaylistsPromise = sessionPromise
    .then((session) => {
      return spotifyApi.getUserPlaylists(session.userID);
    })
    .catch(err => console.log('error: ' + err));

  getAllPlaylistsPromise
    .then((playlists) => {
      const sanitizedPlaylists = playlists.body.items.map(
        playlist => ({ name: playlist.name, uri: playlist.uri }));
      const queryPlaylists = {};
      for (let i = 0; i < 10; i += 1) {
        queryPlaylists['playlist_' + i + '_name'] = sanitizedPlaylists[i].name;
        queryPlaylists['playlist_' + i + '_uri'] = sanitizedPlaylists[i].uri;
      }
      queryPlaylists.session_id = persistentSessionID;
      res.redirect(
        '/playlist.html#' + querystring.stringify(queryPlaylists));
    })
    .catch(err => console.log(err));

}

function initializeAuxify(code, req, res, stateKey, spotifyApi, sessions, connectionConfig) {
  const clientId = connectionConfig.clientId;
  const clientSecret = connectionConfig.clientSecret;
  const redirectUri = connectionConfig.redirectUri;
  // here we go
  res.clearCookie(stateKey);

  const authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    form: {
      code,
      redirect_uri: redirectUri,
      grant_type: 'authorization_code',
    },
    headers: {
      Authorization: 'Basic ' + (new Buffer(clientId + ':' + clientSecret).toString('base64')),
    },
    json: true,
  };

  request.post(authOptions, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      authInit(body, code, req, res, stateKey, spotifyApi, sessions);
    } else {
      res.redirect(`/#${
        querystring.stringify({
          error,
        })}`);
    }
  });
}

module.exports = function callback(req, res, stateKey, spotifyApi, sessions, connectionConfig) {
  // the application requests refresh and access tokens
  // after checking the state parameter

  const code = req.query.code || null;
  // const state = req.query.state || null;
  // const storedState = req.cookies ? req.cookies[stateKey] : null;

  // if (state === null || state !== storedState) {
  //   res.redirect(`/#${
  //     querystring.stringify({
  //       error: 'state_mismatch',
  //       state: JSON.stringify(state),
  //     })}`);
  // } else {
  initializeAuxify(code, req, res, stateKey, spotifyApi, sessions, connectionConfig);
  // }
};
<|endoftext|>


<commit_before>(function() {
  var module = QUnit.module;
  var test = QUnit.test;

  module("2D");

  test("position", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x += 50;
    _.strictEqual(player._x, 50, "X moved");

    player.y += 50;
    _.strictEqual(player._y, 50, "Y moved");

    player.w += 50;
    _.strictEqual(player._w, 100, "Width increase");

    player.h += 50;
    _.strictEqual(player._h, 100, "Height increase");

    _.strictEqual(player._globalZ, player[0], "Global Z, Before");

    player.z = 1;
    _.strictEqual(player._z, 1, "Z index");

    var global_z_guess;
    if (player[0] < 10) {
      global_z_guess = parseInt('10000' + player[0], 10);
    } else {
      global_z_guess = parseInt('1000' + player[0], 10);
    }
    _.strictEqual(player._globalZ, global_z_guess, "Global Z, After");

  });

  test("intersect", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.intersect(0, 0, 100, 50), true, "Intersected");

    _.strictEqual(player.intersect({
      _x: 0,
      _y: 0,
      _w: 100,
      _h: 50
    }), true, "Intersected Again");

    _.strictEqual(player.intersect(100, 100, 100, 50), false, "Didn't intersect");

  });

  test("within", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.within(0, 0, 50, 50), true, "Within");

    _.strictEqual(player.within(-1, -1, 51, 51), true, "Within");

    _.strictEqual(player.within({
      _x: 0,
      _y: 0,
      _w: 50,
      _h: 50
    }), true, "Within Again");

    _.strictEqual(player.within(0, 0, 40, 50), false, "Wasn't within");

    player.rotation = 90; // Once rotated, the entity should no longer be within the rectangle

    _.strictEqual(player.within(0, 0, 50, 50), false, "Rotated, Not within");
    _.strictEqual(player.within(-50, 0, 50, 50), true, "Rotated, within rotated area");

  });

  test("contains", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.contains(0, 0, 50, 50), true, "Contains");

    _.strictEqual(player.contains(1, 1, 49, 49), true, "Contains");

    _.strictEqual(player.contains({
      _x: 0,
      _y: 0,
      _w: 50,
      _h: 50
    }), true, "Contains");

    _.strictEqual(player.contains(1, 1, 51, 51), false, "Doesn't contain");

    player.rotation = 90;

    _.strictEqual(player.contains(0, 0, 50, 50), false, "Rotated, no longer contains");
    _.strictEqual(player.within(-50, 0, 50, 50), true, "Rotated, contains rotated area");

  });

  test("pos", function(_) {
    var player = Crafty.e("2D").attr({
      x: 0,
      y: 50,
      w: 100,
      h: 150
    });

    var posObject = {};

    player.pos(posObject);

    _.strictEqual(player.pos()._x, 0, "X value");
    _.strictEqual(posObject._x, 0, "X value");

    _.strictEqual(player.pos()._y, 50, "Y value");
    _.strictEqual(posObject._y, 50, "Y value");

    _.strictEqual(player.pos()._w, 100, "W value");
    _.strictEqual(posObject._w, 100, "W value");

    _.strictEqual(player.pos()._h, 150, "H value");
    _.strictEqual(posObject._h, 150, "H value");
  });

  test("mbr", function(_) {
    var player = Crafty.e("2D").attr({
      x: 0,
      y: 50,
      w: 100,
      h: 150
    });

    var mbrObject = {};

    player.mbr(mbrObject);

    _.strictEqual(player.mbr()._x, 0, "X value");
    _.strictEqual(mbrObject._x, 0, "X value");

    _.strictEqual(player.mbr()._y, 50, "Y value");
    _.strictEqual(mbrObject._y, 50, "Y value");

    _.strictEqual(player.mbr()._w, 100, "W value");
    _.strictEqual(mbrObject._w, 100, "W value");

    _.strictEqual(player.mbr()._h, 150, "H value");
    _.strictEqual(mbrObject._h, 150, "H value");
  });

  test("circle", function(_) {
    Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    var circle = new Crafty.circle(0, 0, 10);

    _.strictEqual(circle.containsPoint(1, 2), true, "Contained the point");
    _.strictEqual(circle.containsPoint(8, 9), false, "Didn't contain the point");

    circle.shift(1, 0);

    _.strictEqual(circle.x, 1, "Shifted of one pixel on the x axis");
    _.strictEqual(circle.y, 0, "circle.y didn't change");
    _.strictEqual(circle.radius, 10, "circle.radius didn't change");

  });

  test("child", function(_) {
    var parent0 = Crafty.e("2D").attr({
      x: 0,
      y: 0,
      w: 50,
      h: 50
    });
    var child0 = Crafty.e("2D").attr({
      x: 1,
      y: 1,
      w: 50,
      h: 50
    });
    var child1 = Crafty.e("2D").attr({
      x: 2,
      y: 2,
      w: 50,
      h: 50
    });
    var child2 = Crafty.e("2D").attr({
      x: 3,
      y: 3,
      w: 50,
      h: 50
    });
    var child3 = Crafty.e("2D").attr({
      x: 4,
      y: 4,
      w: 50,
      h: 50
    });
    parent0.attach(child0);
    parent0.attach(child1);
    parent0.attach(child2);
    parent0.attach(child3);
    parent0.x += 50;
    _.strictEqual(child0._x, 51, 'child0 shifted when parent did');
    _.strictEqual(child1._x, 52, 'child1 shifted when parent did');
    child0.x += 1;
    child1.x += 1;
    _.strictEqual(parent0._x, 50, 'child shifts do not move the parent');
    child1.destroy();
    _.deepEqual(parent0._children, [child0, child2, child3], 'child1 cleared itself from parent0._children when destroyed');
    parent0.destroy();
    _.strictEqual(Crafty(child0[0]).length, 0, 'destruction of parent killed child0');
    _.strictEqual(Crafty(child2[0]).length, 0, 'destruction of parent killed child2');
    _.strictEqual(Crafty(child3[0]).length, 0, 'destruction of parent killed child3');

  });

  test("child_rotate", function(_) {
    var parent = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50,
        rotation: 10
      });
    var child = Crafty.e("2D")
      .attr({
        x: 10,
        y: 10,
        w: 50,
        h: 50,
        rotation: 15
      });
    parent.attach(child);

    parent.rotation += 20;
    _.strictEqual(parent.rotation, 30, 'parent rotates normally');
    _.strictEqual(child.rotation, 35, 'child follows parent rotation');

    child.rotation += 22;
    _.strictEqual(parent.rotation, 30, 'parent ignores child rotation');
    _.strictEqual(child.rotation, 57, 'child rotates normally');

    parent.rotation = 100; // Rotation by 90 degrees from initial position
    _.strictEqual(Round(child.x), -10, "Child moved around parent upon rotation (x).");
    _.strictEqual(Round(child.y), 10, "Child moved around parent upon rotation (y).");
  });

  test("child rotate 90deg", function (_) {
    var parent = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50
      });
    var child = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50
      });

    parent.origin("center");
    child.origin("center");

    parent.attach(child);

    parent.rotation = 90;
    _.strictEqual(parent._rotation, 90, "parent rotates 90deg");
    _.strictEqual(child._rotation, 90, "child also rotates 90deg");
  });

  module("Geometric");

  var EAST = new Crafty.math.Vector2D(1, 0).normalize();
  var SOUTH_EAST = new Crafty.math.Vector2D(1, 1).normalize();
  var NORTH_EAST = new Crafty.math.Vector2D(1, -1).normalize();
  var NORTH_WEST = new Crafty.math.Vector2D(-1, -1).normalize();

  test("Polygon intersection", function(_) {
    var poly, distance,
        origin, direction;

    poly = new Crafty.polygon([0,0, 50,0, 50,50, 0,50]);

    // intersection with ray slightly outside entity edge
    origin = {_x: -1, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 1, "ray intersects polygon on its left edge");

    // intersection with ray origin at entity edge
    origin = {_x: 0, _y: 0};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon on its left edge");

    // intersection with ray origin inside entity
    origin = {_x: 25, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 25, "ray intersects polygon on its right edge");

    // intersection with ray origin at entity edge
    origin = {_x: 50, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon on its right edge");

    // no intersection with ray going away
    origin = {_x: 51, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    poly = new Crafty.polygon([-75,-75, -150,-150]);

    // intersection with ray at crossing
    origin = {_x: -150, _y: -75};
    direction = NORTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (37.5 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at the crossing");

    // no intersection with parallel ray
    origin = {_x: -76, _y: -75};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    // intersection with colinear ray starting before polygon
    origin = {_x: -25, _y: -25};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (50 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at polygon's start point");

    // intersection with colinear ray starting at polygon start
    origin = {_x: -75, _y: -75};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's start point");

    // intersection with colinear ray starting inside polygon
    origin = {_x: -100, _y: -100};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (50 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at ray's origin");

    // intersection with colinear ray starting at polygon end
    origin = {_x: -150, _y: -150};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's end point");

    // no intersection with colinear ray starting outside polygon
    origin = {_x: -151, _y: -151};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    // intersection with colinear ray starting at polygon end, going opposite direction
    origin = {_x: -150, _y: -150};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's end point");

    // intersection with colinear ray starting inside polygon, going opposite direction
    origin = {_x: -100, _y: -100};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (25 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at ray's origin");

    // intersection with colinear ray starting at polygon start, going opposite direction
    origin = {_x: -75, _y: -75};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's start point");

    // no intersection with colinear ray going opposite direction
    origin = {_x: -74, _y: -74};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");
  });

})();
<commit_msg>Fix test of globalZ<commit_after>(function() {
  var module = QUnit.module;
  var test = QUnit.test;

  module("2D");

  test("position", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x += 50;
    _.strictEqual(player._x, 50, "X moved");

    player.y += 50;
    _.strictEqual(player._y, 50, "Y moved");

    player.w += 50;
    _.strictEqual(player._w, 100, "Width increase");

    player.h += 50;
    _.strictEqual(player._h, 100, "Height increase");

    _.strictEqual(player._globalZ, player[0], "Global Z, Before");

    player.z = 1;
    _.strictEqual(player._z, 1, "Z index");

    _.strictEqual(player._globalZ, player._z * 1e5 + player[0], "Global Z, After");

    // test global order of entities depending on which was created last
    var player2 = Crafty.e("2D");
    var player3 = Crafty.e("2D");
    _.ok(player3._globalZ > player2._globalZ, "player3 should be in front of player2");

    // test global order of entities on same z level, depending on which was created last
    player2.z = 1;
    _.ok(player2._globalZ > player._globalZ, "player2 should be in front of player1");

    // test global order of entities on different z level
    player3.z = -1;
    _.ok(player2._globalZ > player3._globalZ, "player2 should be in front of player3");
  });

  test("intersect", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.intersect(0, 0, 100, 50), true, "Intersected");

    _.strictEqual(player.intersect({
      _x: 0,
      _y: 0,
      _w: 100,
      _h: 50
    }), true, "Intersected Again");

    _.strictEqual(player.intersect(100, 100, 100, 50), false, "Didn't intersect");

  });

  test("within", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.within(0, 0, 50, 50), true, "Within");

    _.strictEqual(player.within(-1, -1, 51, 51), true, "Within");

    _.strictEqual(player.within({
      _x: 0,
      _y: 0,
      _w: 50,
      _h: 50
    }), true, "Within Again");

    _.strictEqual(player.within(0, 0, 40, 50), false, "Wasn't within");

    player.rotation = 90; // Once rotated, the entity should no longer be within the rectangle

    _.strictEqual(player.within(0, 0, 50, 50), false, "Rotated, Not within");
    _.strictEqual(player.within(-50, 0, 50, 50), true, "Rotated, within rotated area");

  });

  test("contains", function(_) {
    var player = Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    player.x = 0;
    player.y = 0;
    player.w = 50;
    player.h = 50;

    _.strictEqual(player.contains(0, 0, 50, 50), true, "Contains");

    _.strictEqual(player.contains(1, 1, 49, 49), true, "Contains");

    _.strictEqual(player.contains({
      _x: 0,
      _y: 0,
      _w: 50,
      _h: 50
    }), true, "Contains");

    _.strictEqual(player.contains(1, 1, 51, 51), false, "Doesn't contain");

    player.rotation = 90;

    _.strictEqual(player.contains(0, 0, 50, 50), false, "Rotated, no longer contains");
    _.strictEqual(player.within(-50, 0, 50, 50), true, "Rotated, contains rotated area");

  });

  test("pos", function(_) {
    var player = Crafty.e("2D").attr({
      x: 0,
      y: 50,
      w: 100,
      h: 150
    });

    var posObject = {};

    player.pos(posObject);

    _.strictEqual(player.pos()._x, 0, "X value");
    _.strictEqual(posObject._x, 0, "X value");

    _.strictEqual(player.pos()._y, 50, "Y value");
    _.strictEqual(posObject._y, 50, "Y value");

    _.strictEqual(player.pos()._w, 100, "W value");
    _.strictEqual(posObject._w, 100, "W value");

    _.strictEqual(player.pos()._h, 150, "H value");
    _.strictEqual(posObject._h, 150, "H value");
  });

  test("mbr", function(_) {
    var player = Crafty.e("2D").attr({
      x: 0,
      y: 50,
      w: 100,
      h: 150
    });

    var mbrObject = {};

    player.mbr(mbrObject);

    _.strictEqual(player.mbr()._x, 0, "X value");
    _.strictEqual(mbrObject._x, 0, "X value");

    _.strictEqual(player.mbr()._y, 50, "Y value");
    _.strictEqual(mbrObject._y, 50, "Y value");

    _.strictEqual(player.mbr()._w, 100, "W value");
    _.strictEqual(mbrObject._w, 100, "W value");

    _.strictEqual(player.mbr()._h, 150, "H value");
    _.strictEqual(mbrObject._h, 150, "H value");
  });

  test("circle", function(_) {
    Crafty.e("2D").attr({
      w: 50,
      h: 50
    });
    var circle = new Crafty.circle(0, 0, 10);

    _.strictEqual(circle.containsPoint(1, 2), true, "Contained the point");
    _.strictEqual(circle.containsPoint(8, 9), false, "Didn't contain the point");

    circle.shift(1, 0);

    _.strictEqual(circle.x, 1, "Shifted of one pixel on the x axis");
    _.strictEqual(circle.y, 0, "circle.y didn't change");
    _.strictEqual(circle.radius, 10, "circle.radius didn't change");

  });

  test("child", function(_) {
    var parent0 = Crafty.e("2D").attr({
      x: 0,
      y: 0,
      w: 50,
      h: 50
    });
    var child0 = Crafty.e("2D").attr({
      x: 1,
      y: 1,
      w: 50,
      h: 50
    });
    var child1 = Crafty.e("2D").attr({
      x: 2,
      y: 2,
      w: 50,
      h: 50
    });
    var child2 = Crafty.e("2D").attr({
      x: 3,
      y: 3,
      w: 50,
      h: 50
    });
    var child3 = Crafty.e("2D").attr({
      x: 4,
      y: 4,
      w: 50,
      h: 50
    });
    parent0.attach(child0);
    parent0.attach(child1);
    parent0.attach(child2);
    parent0.attach(child3);
    parent0.x += 50;
    _.strictEqual(child0._x, 51, 'child0 shifted when parent did');
    _.strictEqual(child1._x, 52, 'child1 shifted when parent did');
    child0.x += 1;
    child1.x += 1;
    _.strictEqual(parent0._x, 50, 'child shifts do not move the parent');
    child1.destroy();
    _.deepEqual(parent0._children, [child0, child2, child3], 'child1 cleared itself from parent0._children when destroyed');
    parent0.destroy();
    _.strictEqual(Crafty(child0[0]).length, 0, 'destruction of parent killed child0');
    _.strictEqual(Crafty(child2[0]).length, 0, 'destruction of parent killed child2');
    _.strictEqual(Crafty(child3[0]).length, 0, 'destruction of parent killed child3');

  });

  test("child_rotate", function(_) {
    var parent = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50,
        rotation: 10
      });
    var child = Crafty.e("2D")
      .attr({
        x: 10,
        y: 10,
        w: 50,
        h: 50,
        rotation: 15
      });
    parent.attach(child);

    parent.rotation += 20;
    _.strictEqual(parent.rotation, 30, 'parent rotates normally');
    _.strictEqual(child.rotation, 35, 'child follows parent rotation');

    child.rotation += 22;
    _.strictEqual(parent.rotation, 30, 'parent ignores child rotation');
    _.strictEqual(child.rotation, 57, 'child rotates normally');

    parent.rotation = 100; // Rotation by 90 degrees from initial position
    _.strictEqual(Round(child.x), -10, "Child moved around parent upon rotation (x).");
    _.strictEqual(Round(child.y), 10, "Child moved around parent upon rotation (y).");
  });

  test("child rotate 90deg", function (_) {
    var parent = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50
      });
    var child = Crafty.e("2D")
      .attr({
        x: 0,
        y: 0,
        w: 50,
        h: 50
      });

    parent.origin("center");
    child.origin("center");

    parent.attach(child);

    parent.rotation = 90;
    _.strictEqual(parent._rotation, 90, "parent rotates 90deg");
    _.strictEqual(child._rotation, 90, "child also rotates 90deg");
  });

  module("Geometric");

  var EAST = new Crafty.math.Vector2D(1, 0).normalize();
  var SOUTH_EAST = new Crafty.math.Vector2D(1, 1).normalize();
  var NORTH_EAST = new Crafty.math.Vector2D(1, -1).normalize();
  var NORTH_WEST = new Crafty.math.Vector2D(-1, -1).normalize();

  test("Polygon intersection", function(_) {
    var poly, distance,
        origin, direction;

    poly = new Crafty.polygon([0,0, 50,0, 50,50, 0,50]);

    // intersection with ray slightly outside entity edge
    origin = {_x: -1, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 1, "ray intersects polygon on its left edge");

    // intersection with ray origin at entity edge
    origin = {_x: 0, _y: 0};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon on its left edge");

    // intersection with ray origin inside entity
    origin = {_x: 25, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 25, "ray intersects polygon on its right edge");

    // intersection with ray origin at entity edge
    origin = {_x: 50, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon on its right edge");

    // no intersection with ray going away
    origin = {_x: 51, _y: 25};
    direction = EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    poly = new Crafty.polygon([-75,-75, -150,-150]);

    // intersection with ray at crossing
    origin = {_x: -150, _y: -75};
    direction = NORTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (37.5 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at the crossing");

    // no intersection with parallel ray
    origin = {_x: -76, _y: -75};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    // intersection with colinear ray starting before polygon
    origin = {_x: -25, _y: -25};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (50 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at polygon's start point");

    // intersection with colinear ray starting at polygon start
    origin = {_x: -75, _y: -75};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's start point");

    // intersection with colinear ray starting inside polygon
    origin = {_x: -100, _y: -100};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (50 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at ray's origin");

    // intersection with colinear ray starting at polygon end
    origin = {_x: -150, _y: -150};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's end point");

    // no intersection with colinear ray starting outside polygon
    origin = {_x: -151, _y: -151};
    direction = NORTH_WEST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");

    // intersection with colinear ray starting at polygon end, going opposite direction
    origin = {_x: -150, _y: -150};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's end point");

    // intersection with colinear ray starting inside polygon, going opposite direction
    origin = {_x: -100, _y: -100};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance.toFixed(4), (25 * Math.sqrt(2)).toFixed(4),
      "ray intersects polygon at ray's origin");

    // intersection with colinear ray starting at polygon start, going opposite direction
    origin = {_x: -75, _y: -75};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, 0, "ray intersects polygon at polygon's start point");

    // no intersection with colinear ray going opposite direction
    origin = {_x: -74, _y: -74};
    direction = SOUTH_EAST;
    distance = poly.intersectRay(origin, direction);
    _.strictEqual(distance, Infinity, "ray does not intersect polygon");
  });

})();
<|endoftext|>


<commit_before>const path = require('path');
const replaceLib = require('@ant-design/tools/lib/replaceLib');
const getWebpackConfig = require('@ant-design/tools/lib/getWebpackConfig');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
const { version } = require('../package.json');
const themeConfig = require('./themeConfig');

const { webpack } = getWebpackConfig;

const isDev = process.env.NODE_ENV === 'development';

function alertBabelConfig(rules) {
  rules.forEach(rule => {
    if (rule.loader && rule.loader === 'babel-loader') {
      if (rule.options.plugins.indexOf(replaceLib) === -1) {
        rule.options.plugins.push(replaceLib);
      }
      rule.options.plugins = rule.options.plugins.filter(
        plugin => !plugin.indexOf || plugin.indexOf('babel-plugin-add-module-exports') === -1,
      );
      // Add babel-plugin-add-react-displayname
      rule.options.plugins.push(require.resolve('babel-plugin-add-react-displayname'));
    } else if (rule.use) {
      alertBabelConfig(rule.use);
    }
  });
}

module.exports = {
  port: 8001,
  hash: true,
  source: {
    components: './components',
    docs: './docs',
    changelog: ['CHANGELOG.zh-CN.md', 'CHANGELOG.en-US.md'],
    'components/form/v3': ['components/form/v3.zh-CN.md', 'components/form/v3.en-US.md'],
    'docs/resources': ['./docs/resources.zh-CN.md', './docs/resources.en-US.md'],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig,
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
  },
  lessConfig: {
    javascriptEnabled: true,
  },
  webpackConfig(config) {
    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      'antd/es': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      'react-router-dom': 'ReactRouterDOM',
    };

    if (isDev) {
      config.devtool = 'source-map';

      // Resolve use react hook fail when yarn link or npm link
      // https://github.com/webpack/webpack/issues/8607#issuecomment-453068938
      config.resolve.alias = {
        ...config.resolve.alias,
        'react/jsx-runtime': require.resolve('react/jsx-runtime'),
        react: require.resolve('react'),
      };
    } else if (process.env.ESBUILD) {
      // use esbuild
      config.optimization.minimizer = [
        new ESBuildMinifyPlugin({
          target: 'es2015',
        }),
        new CssMinimizerPlugin(),
      ];
    }

    alertBabelConfig(config.module.rules);

    config.module.rules.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto',
    });

    config.plugins.push(
      new webpack.DefinePlugin({
        antdReproduceVersion: JSON.stringify(version),
      }),
    );

    delete config.module.noParse;

    return config;
  },

  devServerConfig: {
    public: process.env.DEV_HOST || 'localhost',
    disableHostCheck: !!process.env.DEV_HOST,
  },

  htmlTemplateExtraData: {
    isDev,
  },
};
<commit_msg>chore: use filesystem cache (#30503)<commit_after>const path = require('path');
const replaceLib = require('@ant-design/tools/lib/replaceLib');
const getWebpackConfig = require('@ant-design/tools/lib/getWebpackConfig');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
const { version } = require('../package.json');
const themeConfig = require('./themeConfig');

const { webpack } = getWebpackConfig;

const isDev = process.env.NODE_ENV === 'development';

function alertBabelConfig(rules) {
  rules.forEach(rule => {
    if (rule.loader && rule.loader === 'babel-loader') {
      if (rule.options.plugins.indexOf(replaceLib) === -1) {
        rule.options.plugins.push(replaceLib);
      }
      rule.options.plugins = rule.options.plugins.filter(
        plugin => !plugin.indexOf || plugin.indexOf('babel-plugin-add-module-exports') === -1,
      );
      // Add babel-plugin-add-react-displayname
      rule.options.plugins.push(require.resolve('babel-plugin-add-react-displayname'));
    } else if (rule.use) {
      alertBabelConfig(rule.use);
    }
  });
}

module.exports = {
  port: 8001,
  hash: true,
  source: {
    components: './components',
    docs: './docs',
    changelog: ['CHANGELOG.zh-CN.md', 'CHANGELOG.en-US.md'],
    'components/form/v3': ['components/form/v3.zh-CN.md', 'components/form/v3.en-US.md'],
    'docs/resources': ['./docs/resources.zh-CN.md', './docs/resources.en-US.md'],
  },
  theme: './site/theme',
  htmlTemplate: './site/theme/static/template.html',
  themeConfig,
  filePathMapper(filePath) {
    if (filePath === '/index.html') {
      return ['/index.html', '/index-cn.html'];
    }
    if (filePath.endsWith('/index.html')) {
      return [filePath, filePath.replace(/\/index\.html$/, '-cn/index.html')];
    }
    if (filePath !== '/404.html' && filePath !== '/index-cn.html') {
      return [filePath, filePath.replace(/\.html$/, '-cn.html')];
    }
    return filePath;
  },
  doraConfig: {
    verbose: true,
  },
  lessConfig: {
    javascriptEnabled: true,
  },
  webpackConfig(config) {
    config.cache = {
      type: 'filesystem',
    };

    config.resolve.alias = {
      'antd/lib': path.join(process.cwd(), 'components'),
      'antd/es': path.join(process.cwd(), 'components'),
      antd: path.join(process.cwd(), 'index'),
      site: path.join(process.cwd(), 'site'),
      'react-router': 'react-router/umd/ReactRouter',
    };

    config.externals = {
      'react-router-dom': 'ReactRouterDOM',
    };

    if (isDev) {
      config.devtool = 'source-map';

      // Resolve use react hook fail when yarn link or npm link
      // https://github.com/webpack/webpack/issues/8607#issuecomment-453068938
      config.resolve.alias = {
        ...config.resolve.alias,
        'react/jsx-runtime': require.resolve('react/jsx-runtime'),
        react: require.resolve('react'),
      };
    } else if (process.env.ESBUILD) {
      // use esbuild
      config.optimization.minimizer = [
        new ESBuildMinifyPlugin({
          target: 'es2015',
        }),
        new CssMinimizerPlugin(),
      ];
    }

    alertBabelConfig(config.module.rules);

    config.module.rules.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto',
    });

    config.plugins.push(
      new webpack.DefinePlugin({
        antdReproduceVersion: JSON.stringify(version),
      }),
    );

    delete config.module.noParse;

    return config;
  },

  devServerConfig: {
    public: process.env.DEV_HOST || 'localhost',
    disableHostCheck: !!process.env.DEV_HOST,
  },

  htmlTemplateExtraData: {
    isDev,
  },
};
<|endoftext|>


<commit_before>/**
 * @license RequireJS text 2.0.12 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/requirejs/text for details
 */
/*jslint regexp: true */
/*global require, XMLHttpRequest, ActiveXObject,
  define, window, process, Packages,
  java, location, Components, FileUtils */

define(['module'], function (module) {
    'use strict';

    var text, fs, Cc, Ci, xpcIsWindows,
        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
        xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
        hasLocation = typeof location !== 'undefined' && location.href,
        defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
        defaultHostName = hasLocation && location.hostname,
        defaultPort = hasLocation && (location.port || undefined),
        buildMap = {},
        masterConfig = (module.config && module.config()) || {};

    text = {
        version: '2.0.12',

        strip: function (content) {
            //Strips <?xml ...?> declarations so that external SVG and XML
            //documents can be added to a document without worry. Also, if the string
            //is an HTML document, only the part inside the body tag is returned.
            if (content) {
                content = content.replace(xmlRegExp, "");
                var matches = content.match(bodyRegExp);
                if (matches) {
                    content = matches[1];
                }
            } else {
                content = "";
            }
            return content;
        },

        jsEscape: function (content) {
            return content.replace(/(['\\])/g, '\\$1')
                .replace(/[\f]/g, "\\f")
                .replace(/[\b]/g, "\\b")
                .replace(/[\n]/g, "\\n")
                .replace(/[\t]/g, "\\t")
                .replace(/[\r]/g, "\\r")
                .replace(/[\u2028]/g, "\\u2028")
                .replace(/[\u2029]/g, "\\u2029");
        },

        createXhr: masterConfig.createXhr || function () {
            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
            var xhr, i, progId;
            if (typeof XMLHttpRequest !== "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject !== "undefined") {
                for (i = 0; i < 3; i += 1) {
                    progId = progIds[i];
                    try {
                        xhr = new ActiveXObject(progId);
                    } catch (e) {}

                    if (xhr) {
                        progIds = [progId];  // so faster next time
                        break;
                    }
                }
            }

            return xhr;
        },

        /**
         * Parses a resource name into its component parts. Resource names
         * look like: module/name.ext!strip, where the !strip part is
         * optional.
         * @param {String} name the resource name
         * @returns {Object} with properties "moduleName", "ext" and "strip"
         * where strip is a boolean.
         */
        parseName: function (name) {
            var modName, ext, temp,
                strip = false,
                index = name.indexOf("."),
                isRelative = name.indexOf('./') === 0 ||
                             name.indexOf('../') === 0;

            if (index !== -1 && (!isRelative || index > 1)) {
                modName = name.substring(0, index);
                ext = name.substring(index + 1, name.length);
            } else {
                modName = name;
            }

            temp = ext || modName;
            index = temp.indexOf("!");
            if (index !== -1) {
                //Pull off the strip arg.
                strip = temp.substring(index + 1) === "strip";
                temp = temp.substring(0, index);
                if (ext) {
                    ext = temp;
                } else {
                    modName = temp;
                }
            }

            return {
                moduleName: modName,
                ext: ext,
                strip: strip
            };
        },

        xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,

        /**
         * Is an URL on another domain. Only works for browser use, returns
         * false in non-browser environments. Only used to know if an
         * optimized .js version of a text resource should be loaded
         * instead.
         * @param {String} url
         * @returns Boolean
         */
        useXhr: function (url, protocol, hostname, port) {
            var uProtocol, uHostName, uPort,
                match = text.xdRegExp.exec(url);
            if (!match) {
                return true;
            }
            uProtocol = match[2];
            uHostName = match[3];

            uHostName = uHostName.split(':');
            uPort = uHostName[1];
            uHostName = uHostName[0];

            return (!uProtocol || uProtocol === protocol) &&
                   (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
                   ((!uPort && !uHostName) || uPort === port);
        },

        finishLoad: function (name, strip, content, onLoad) {
            content = strip ? text.strip(content) : content;
            if (masterConfig.isBuild) {
                buildMap[name] = content;
            }
            onLoad(content);
        },

        load: function (name, req, onLoad, config) {
            //Name has format: some.module.filext!strip
            //The strip part is optional.
            //if strip is present, then that means only get the string contents
            //inside a body tag in an HTML string. For XML/SVG content it means
            //removing the <?xml ...?> declarations so the content can be inserted
            //into the current doc without problems.

            // Do not bother with the work if a build and text will
            // not be inlined.
            if (config && config.isBuild && !config.inlineText) {
                onLoad();
                return;
            }

            masterConfig.isBuild = config && config.isBuild;

            var parsed = text.parseName(name),
                nonStripName = parsed.moduleName +
                    (parsed.ext ? '.' + parsed.ext : ''),
                url = req.toUrl(nonStripName),
                useXhr = (masterConfig.useXhr) ||
                         text.useXhr;

            // Do not load if it is an empty: url
            if (url.indexOf('empty:') === 0) {
                onLoad();
                return;
            }

            //Load the text. Use XHR if possible and in a browser.
            if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
                text.get(url, function (content) {
                    text.finishLoad(name, parsed.strip, content, onLoad);
                }, function (err) {
                    if (onLoad.error) {
                        onLoad.error(err);
                    }
                });
            } else {
                //Need to fetch the resource across domains. Assume
                //the resource has been optimized into a JS module. Fetch
                //by the module name + extension, but do not include the
                //!strip part to avoid file system issues.
                req([nonStripName], function (content) {
                    text.finishLoad(parsed.moduleName + '.' + parsed.ext,
                                    parsed.strip, content, onLoad);
                });
            }
        },

        write: function (pluginName, moduleName, write, config) {
            if (buildMap.hasOwnProperty(moduleName)) {
                var content = text.jsEscape(buildMap[moduleName]);
                write.asModule(pluginName + "!" + moduleName,
                               "define(function () { return '" +
                                   content +
                               "';});\n");
            }
        },

        writeFile: function (pluginName, moduleName, req, write, config) {
            var parsed = text.parseName(moduleName),
                extPart = parsed.ext ? '.' + parsed.ext : '',
                nonStripName = parsed.moduleName + extPart,
                //Use a '.js' file name so that it indicates it is a
                //script that can be loaded across domains.
                fileName = req.toUrl(parsed.moduleName + extPart) + '.js';

            //Leverage own load() method to load plugin value, but only
            //write out values that do not have the strip argument,
            //to avoid any potential issues with ! in file names.
            text.load(nonStripName, req, function (value) {
                //Use own write() method to construct full module value.
                //But need to create shell that translates writeFile's
                //write() to the right interface.
                var textWrite = function (contents) {
                    return write(fileName, contents);
                };
                textWrite.asModule = function (moduleName, contents) {
                    return write.asModule(moduleName, fileName, contents);
                };

                text.write(pluginName, nonStripName, textWrite, config);
            }, config);
        }
    };

    if (masterConfig.env === 'node' || (!masterConfig.env &&
            typeof process !== "undefined" &&
            process.versions &&
            !!process.versions.node &&
            !process.versions['node-webkit'])) {
        //Using special require.nodeRequire, something added by r.js.
        fs = require.nodeRequire('fs');

        text.get = function (url, callback, errback) {
            try {
                var file = fs.readFileSync(url, 'utf8');
                //Remove BOM (Byte Mark Order) from utf8 files if it is there.
                if (file.indexOf('\uFEFF') === 0) {
                    file = file.substring(1);
                }
                callback(file);
            } catch (e) {
                if (errback) {
                    errback(e);
                }
            }
        };
    } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
            text.createXhr())) {
        text.get = function (url, callback, errback, headers) {
            var xhr = text.createXhr(), header;
            xhr.open('GET', url, true);

            //Allow plugins direct access to xhr headers
            if (headers) {
                for (header in headers) {
                    if (headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header.toLowerCase(), headers[header]);
                    }
                }
            }

            //Allow overrides specified in config
            if (masterConfig.onXhr) {
                masterConfig.onXhr(xhr, url);
            }

            xhr.onreadystatechange = function (evt) {
                var status, err;
                //Do not explicitly handle errors, those should be
                //visible via console output in the browser.
                if (xhr.readyState === 4) {
                    status = xhr.status || 0;
                    if (status > 399 && status < 600) {
                        //An http 4xx or 5xx error. Signal an error.
                        err = new Error(url + ' HTTP status: ' + status);
                        err.xhr = xhr;
                        if (errback) {
                            errback(err);
                        }
                    } else {
                        callback(xhr.responseText);
                    }

                    if (masterConfig.onXhrComplete) {
                        masterConfig.onXhrComplete(xhr, url);
                    }
                }
            };
            xhr.send(null);
        };
    } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
            typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
        //Why Java, why is this so awkward?
        text.get = function (url, callback) {
            var stringBuffer, line,
                encoding = "utf-8",
                file = new java.io.File(url),
                lineSeparator = java.lang.System.getProperty("line.separator"),
                input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
                content = '';
            try {
                stringBuffer = new java.lang.StringBuffer();
                line = input.readLine();

                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
                // http://www.unicode.org/faq/utf_bom.html

                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
                if (line && line.length() && line.charAt(0) === 0xfeff) {
                    // Eat the BOM, since we've already found the encoding on this file,
                    // and we plan to concatenating this buffer with others; the BOM should
                    // only appear at the top of a file.
                    line = line.substring(1);
                }

                if (line !== null) {
                    stringBuffer.append(line);
                }

                while ((line = input.readLine()) !== null) {
                    stringBuffer.append(lineSeparator);
                    stringBuffer.append(line);
                }
                //Make sure we return a JavaScript string and not a Java string.
                content = String(stringBuffer.toString()); //String
            } finally {
                input.close();
            }
            callback(content);
        };
    } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env &&
            typeof Components !== 'undefined' && Components.classes &&
            Components.interfaces)) {
        //Avert your gaze!
        Cc = Components.classes;
        Ci = Components.interfaces;
        Components.utils['import']('resource://gre/modules/FileUtils.jsm');
        xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);

        text.get = function (url, callback) {
            var inStream, convertStream, fileObj,
                readData = {};

            if (xpcIsWindows) {
                url = url.replace(/\//g, '\\');
            }

            fileObj = new FileUtils.File(url);

            //XPCOM, you so crazy
            try {
                inStream = Cc['@mozilla.org/network/file-input-stream;1']
                           .createInstance(Ci.nsIFileInputStream);
                inStream.init(fileObj, 1, 0, false);

                convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
                                .createInstance(Ci.nsIConverterInputStream);
                convertStream.init(inStream, "utf-8", inStream.available(),
                Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);

                convertStream.readString(inStream.available(), readData);
                convertStream.close();
                inStream.close();
                callback(readData.value);
            } catch (e) {
                throw new Error((fileObj && fileObj.path || '') + ': ' + e);
            }
        };
    }
    return text;
});
<commit_msg>Delete text.js<commit_after><|endoftext|>


<commit_before>"use strict";
const fs = require('fs');
const jscodefmt = require("../");
const recast = require("recast");
const types = require("ast-types");

const RUN_AST_TESTS = process.env["AST_COMPARE"];

// Ignoring empty statements that are added into the output removes a
// lot of noise from test failures and let's us focus on the real
// failures when comparing asts
function removeEmptyStatements(ast) {
  return types.visit(ast, {
    visitEmptyStatement: function(path) {
      path.prune();
      return false;
    }
  });
}

function run_spec(dirname) {
  fs.readdirSync(dirname).forEach(filename => {
    if (filename.endsWith('.js') && filename !== 'jsfmt.spec.js') {
      const path = dirname + '/' + filename;

      if (!RUN_AST_TESTS) {
        const source = read(path).replace(/\r\n/g, '\n');
        const output = prettyprint(source, path);
        test(filename, () => {
          expect(source + '~'.repeat(80) + '\n' + output).toMatchSnapshot();
        });
      }

      if (RUN_AST_TESTS) {
        const source = read(dirname + '/' + filename);
        const ast = removeEmptyStatements(parse(source));
        let prettyprinted = false;
        let ppast;
        let pperr = null;
        try {
          ppast = removeEmptyStatements(parse(prettyprint(source, path)));
        }
        catch(e) {
          pperr = e.stack;
        }

        test(path + ' parse', () => {
          expect(pperr).toBe(null);
          expect(ppast).toBeDefined();
          if(ast.errors.length === 0) {
            expect(ast).toEqual(ppast);
          }
        });
      }

    }
  });
}
global.run_spec = run_spec;

function stripLocation(ast) {
  if (Array.isArray(ast)) {
    return ast.map(e => stripLocation(e));
  }
  if (typeof ast === 'object') {
    const newObj = {};
    for (var key in ast) {
      if (key === 'loc' || key === 'range' || key === 'raw' || key === 'comments') {
        continue;
      }
      newObj[key] = stripLocation(ast[key]);
    }
    return newObj;
  }
  return ast;
}

function parse(string) {
  const flowParser = require('flow-parser');
  return stripLocation(flowParser.parse(string));
}

function prettyprint(src, filename) {
  return jscodefmt.format(src, { filename, useFlowParser: true, printWidth: 80 });
}

function read(filename) {
  return fs.readFileSync(filename, 'utf8');
}
<commit_msg>remove unused recast ref<commit_after>"use strict";
const fs = require('fs');
const jscodefmt = require("../");
const types = require("ast-types");

const RUN_AST_TESTS = process.env["AST_COMPARE"];

// Ignoring empty statements that are added into the output removes a
// lot of noise from test failures and let's us focus on the real
// failures when comparing asts
function removeEmptyStatements(ast) {
  return types.visit(ast, {
    visitEmptyStatement: function(path) {
      path.prune();
      return false;
    }
  });
}

function run_spec(dirname) {
  fs.readdirSync(dirname).forEach(filename => {
    if (filename.endsWith('.js') && filename !== 'jsfmt.spec.js') {
      const path = dirname + '/' + filename;

      if (!RUN_AST_TESTS) {
        const source = read(path).replace(/\r\n/g, '\n');
        const output = prettyprint(source, path);
        test(filename, () => {
          expect(source + '~'.repeat(80) + '\n' + output).toMatchSnapshot();
        });
      }

      if (RUN_AST_TESTS) {
        const source = read(dirname + '/' + filename);
        const ast = removeEmptyStatements(parse(source));
        let prettyprinted = false;
        let ppast;
        let pperr = null;
        try {
          ppast = removeEmptyStatements(parse(prettyprint(source, path)));
        }
        catch(e) {
          pperr = e.stack;
        }

        test(path + ' parse', () => {
          expect(pperr).toBe(null);
          expect(ppast).toBeDefined();
          if(ast.errors.length === 0) {
            expect(ast).toEqual(ppast);
          }
        });
      }

    }
  });
}
global.run_spec = run_spec;

function stripLocation(ast) {
  if (Array.isArray(ast)) {
    return ast.map(e => stripLocation(e));
  }
  if (typeof ast === 'object') {
    const newObj = {};
    for (var key in ast) {
      if (key === 'loc' || key === 'range' || key === 'raw' || key === 'comments') {
        continue;
      }
      newObj[key] = stripLocation(ast[key]);
    }
    return newObj;
  }
  return ast;
}

function parse(string) {
  const flowParser = require('flow-parser');
  return stripLocation(flowParser.parse(string));
}

function prettyprint(src, filename) {
  return jscodefmt.format(src, { filename, useFlowParser: true, printWidth: 80 });
}

function read(filename) {
  return fs.readFileSync(filename, 'utf8');
}
<|endoftext|>