<commit_before>const expect = require('expect');
const request = require('supertest');
const {ObjectID} = require('mongodb');

const {app} = require('../server/server');
const {Todo} = require('../server/models/todo');

const todos = [
  {
    _id: new ObjectID(),
    text: 'First test todo'
  },
  {
    _id: new ObjectID(),
    text: 'Second test todo'
  }
];

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

describe('Server', () => {
  describe('POST /todos', () => {
    it('should create a new todo', (done) => {
      let text = 'Test todo text';

      request(app)
        .post('/todos')
        .send({text})
        .expect(200)
        .expect((res) =>{
          expect(res.body.text).toBe(text)
        })
        .end((err, res) => {
          if (err) {
            return done(err);
          }

          Todo.find({text}).then((todos) => {
            expect(todos.length).toBe(1);
            expect(todos[0].text).toBe(text);
            done();
          }).catch((err) => done(err));
        });
    });

    it('should not create todo with invalid body data', (done) => {
      request(app)
        .post('/todos')
        .send({})
        .expect(400)
        .end((err, res) => {
          if (err) {
            return done(err);
          }

          Todo.find().then((todos) => {
            expect(todos.length).toBe(2);
            done();
          }).catch((err) => done(err));
        });
    });
  });

  describe('GET /todos', () => {
    it('should get all todos', (done) => {
      request(app)
        .get('/todos')
        .expect(200)
        .expect((res) => {
          expect(res.body.todos.length).toBe(2)
        })
        .end(done);
    });
  });

  describe('GET /todos/:id', () => {
    it('should return todo doc', (done) => {
      request(app)
        .get(`/todos/${todos[0]._id.toHexString()}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.todo.text).toBe(todos[0].text);
        })
        .end(done);
    });

    it('should return 404 if todo not found', (done) => {
      request(app)
        .get(`/todos/${new ObjectID()}`)
        .expect(404)
        .end(done);
    });

    it('should return 400 if the id is not valid', (done) => {
      request(app)
        .get('/todos/123')
        .expect(400)
        .end(done);
    });
  });
});
<commit_msg>Add test for remove todo endpoint<commit_after>const expect = require('expect');
const request = require('supertest');
const {ObjectID} = require('mongodb');

const {app} = require('../server/server');
const {Todo} = require('../server/models/todo');

const todos = [
  {
    _id: new ObjectID(),
    text: 'First test todo'
  },
  {
    _id: new ObjectID(),
    text: 'Second test todo'
  }
];

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

describe('Server', () => {
  describe('POST /todos', () => {
    it('should create a new todo', (done) => {
      let text = 'Test todo text';

      request(app)
        .post('/todos')
        .send({text})
        .expect(200)
        .expect((res) =>{
          expect(res.body.text).toBe(text)
        })
        .end((err, res) => {
          if (err) {
            return done(err);
          }

          Todo.find({text}).then((todos) => {
            expect(todos.length).toBe(1);
            expect(todos[0].text).toBe(text);
            done();
          }).catch((err) => done(err));
        });
    });

    it('should not create todo with invalid body data', (done) => {
      request(app)
        .post('/todos')
        .send({})
        .expect(400)
        .end((err, res) => {
          if (err) {
            return done(err);
          }

          Todo.find().then((todos) => {
            expect(todos.length).toBe(2);
            done();
          }).catch((err) => done(err));
        });
    });
  });

  describe('GET /todos', () => {
    it('should get all todos', (done) => {
      request(app)
        .get('/todos')
        .expect(200)
        .expect((res) => {
          expect(res.body.todos.length).toBe(2)
        })
        .end(done);
    });
  });

  describe('GET /todos/:id', () => {
    it('should return todo doc', (done) => {
      request(app)
        .get(`/todos/${todos[0]._id.toHexString()}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.todo.text).toBe(todos[0].text);
        })
        .end(done);
    });

    it('should return 404 if todo not found', (done) => {
      request(app)
        .get(`/todos/${new ObjectID()}`)
        .expect(404)
        .end(done);
    });

    it('should return 400 if the id is not valid', (done) => {
      request(app)
        .get('/todos/123')
        .expect(400)
        .end(done);
    });
  });

  describe('DELETE /todos/:id', () => {
    it('should remove a todo', (done) => {
      request(app)
        .delete(`/todos/${todos[0]._id.toHexString()}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.todo._id).toBe(todos[0]._id.toHexString());
        })
        .end((err, res) => {
          if (err) {
            return done(err);
          }

          Todo.findById(todos[0]._id.toHexString()).then((todo) => {
            expect(todo).toNotExist();
            done();
          }).catch((err) => done(err));
        });
    });

    it('should return 404 if todo not found', (done) => {
      request(app)
        .delete(`/todos/${new ObjectID()}`)
        .expect(404)
        .end(done);
    });

    it('should return 400 if ID is invalid', (done) => {
      request(app)
        .delete('/todos/123')
        .expect(400)
        .end(done);
    });
  });
});
<|endoftext|>


<commit_before>(function() {

    describe('Sliderbarr', function() {
        var slider = null;
        var testValue = 56;

        beforeEach(function() {
            slider = new SliderBarr({
                el: $('#slider'),
                value: 50,
                step: 1
            });
        });

        afterEach(function() {
            $('#slider-two').empty();
        });

        it ('can construct', function() {
            var fakeValidateHandles = spyOn(SliderBarr.prototype, '_validateHandles').andCallFake(function() {});
            var fakeRender = spyOn(SliderBarr.prototype, '_render').andCallFake(function() {});
            var fakeRenderLabels = spyOn(SliderBarr.prototype, '_renderEdgeLabels').andCallFake(function() {});
            var fakeInitSelectors = spyOn(SliderBarr.prototype, '_initSelectors').andCallFake(function() {});
            var fakeInitEvents = spyOn(SliderBarr.prototype, '_initEvents').andCallFake(function() {});
            var fakeRenderHandleChanges = spyOn(SliderBarr.prototype, '_renderHandleChanges').andCallFake(function() {});

            var slide = new SliderBarr({el: $('#slider')});

            expect(slide._settings.el).toEqual($('#slider'));
            expect(slide._settings.max).toBe(100);
            expect(slide._settings.min).toBe(0);
            expect(slide._settings.value).toBe(25);
            expect(slide._settings.bar).toBeTruthy();
            expect(slide._settings.labels).toBeFalsy();
            expect(slide._settings.step).toBe(1);
            expect(slide._settings.onChange).toBeNull();
            expect(slide._settings.onDrag).toBeNull();

            expect(slide._activeDrag).toBeFalsy();
            expect(slide._sliderAttr).toEqual({});
            expect(slide._cache).toEqual([]);

            expect(fakeValidateHandles).toHaveBeenCalled();
            expect(fakeRender).toHaveBeenCalled();
            expect(fakeRenderLabels).not.toHaveBeenCalled();
            expect(fakeInitSelectors).toHaveBeenCalled();
            expect(fakeInitEvents).toHaveBeenCalled();
            expect(fakeRenderHandleChanges).toHaveBeenCalled();

        });

        describe('Rendering', function() {

            it ('can render', function() {
                // Ensure there is no slider intialised first
                expect($('#slider-two').find('div').length).toBe(0);

                // Initialise slider
                var slide = new SliderBarr({el: $('#slider-two')});

                // Ensure the slider has new DOM elements
                expect($('#slider-two').find('div').length).not.toBe(0);
            });

            it ('can render edge labels', function() {
                // Ensure there is no slider intialised first
                var el = $('#slider-two');
                expect(el.find('div').length).toBe(0);
                expect(el.find('.label').length).toBe(0);

                // Initialise slider
                var slide = new SliderBarr({el: el, labels: true});

                // Ensure the slider has new DOM elements
                expect(el.find('div').length).not.toBe(0);
                expect(el.find('.label').length).not.toBe(0);
            });

        });

        describe('Selectors', function() {

            it ('can initialise jquery selectors', function() {
                $el = $('#slider-two');
                var slide = new SliderBarr({el: $el, labels: true});
                expect($(document)).toEqual(slide._cache.document);
                expect($el).toEqual(slide._cache.slider);
                expect($el.find('.bar')).toEqual(slide._cache.bar);
                expect($el.find('.handle')).toEqual(slide._cache.handle);
                expect($el.find('.current')).toEqual(slide._cache.current);
            });

        });

        describe('Events', function() {

            it ('can initialise events', function() {

            });

            it ('can handle on keydown', function() {
                var e = {
                    keyCode: 37
                };

                var spyChangeHandle = spyOn(slider, '_changeHandle');
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).toHaveBeenCalledWith('l');

                spyChangeHandle.reset();

                e.keyCode = 38;
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).toHaveBeenCalledWith('r');

                spyChangeHandle.reset();

                e.keyCode = 0;
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).not.toHaveBeenCalled();
            });

            it ('can handle on mousedown', function() {

            });

            it ('can handle on mouse move', function() {
                var e = {};

                fakeSetSliderValueOnDrag = createFakeSliderSetOnDrag();

                slider._activeDrag = false;
                slider._onHandleMousemove(e);
                expect(fakeSetSliderValueOnDrag).not.toHaveBeenCalled();

                fakeSetSliderValueOnDrag.reset();

                slider._activeDrag = true;
                slider._onHandleMousemove(e);
                expect(fakeSetSliderValueOnDrag).toHaveBeenCalled();
            });

            it ('can react to slider click', function() {

            });

            it ('can handle mouseup', function() {

            });

            it ('can fire on change', function() {

            });

        });

        describe('Set and Get Values', function() {

            it ('can change handle', function() {
                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandleChanges = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                var val = 22;
                var step = 1;
                slider._settings.step = step;
                slider._settings.value = val;

                slider._changeHandle('r');
                expect(slider._settings.value).toBe(val + step);
                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandleChanges).toHaveBeenCalled();
                expect(fakeFireOnChange).toHaveBeenCalled();

                slider._settings.value = val;

                slider._changeHandle('l');
                expect(slider._settings.value).toBe(val - step);
            });

            it ('can validate value', function() {
                var testValue = 50;
                expect(slider._validateValue(testValue)).toBe(50);
                testValue = 50.33333;
                expect(slider._validateValue(testValue)).toBe(50);

                slider._settings.step = 0.25;
                testValue = 23.75;
                expect(slider._validateValue(testValue)).toBe(23.75);
                testValue = 23.7786534;
                expect(slider._validateValue(testValue)).toBe(23.78);
            });

            it ('can validate handles', function() {
                var val = 9e9;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(slider._settings.max);

                val = -9e9;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(slider._settings.min);

                val = 27;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(val);
            });

            it ('can get value from mouse event', function() {
                var e = {
                    pageX: 500
                };

                slider._sliderAttr.width = 100;
                expect(slider._getValFromMouseEvent(e)).toBe(500);
            });

            it ('can set slider value on drag', function() {
                var testValue = 56;
                var fakeGetValFromMouseEvent = createFakeGetValFromMouseEvent();
                var fakeValidateHandles = createFakeValidateHandles();
                var seenDrag = false;

                slider._settings.onDrag = function() { seenDrag = true; };

                slider._setSliderValueOnDrag({});
                expect(slider._settings.value).toBe(testValue);
                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeGetValFromMouseEvent).toHaveBeenCalled();
                expect(seenDrag).toBeTruthy();
            });

            it ('can get value', function() {
                slider._settings.value = 78;
                expect(slider.getValue()).toBe(78);
            });

            it ('can set value', function() {
                var testValue = 27;
                var fireEvents = false;

                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandles = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                slider.setValue(testValue, fireEvents);
                expect(slider._settings.value).toBe(testValue);

                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandles).toHaveBeenCalled();
                expect(fakeFireOnChange).not.toHaveBeenCalled();
            });

            it ('can set value but not fire events', function() {
                var testValue = 29;
                var fireEvents = true;

                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandles = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                slider.setValue(testValue, fireEvents);
                expect(slider._settings.value).toBe(testValue);

                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandles).toHaveBeenCalled();
                expect(fakeFireOnChange).toHaveBeenCalled();
            });

        });

        function createFakeGetValFromMouseEvent() {
            return spyOn(slider, '_getValFromMouseEvent').andCallFake(function() {
                return testValue;
            });
        };

        function createFakeValidateHandles() {
            return spyOn(slider, '_validateHandles').andCallFake(function() {});
        };

        function createFakeRenderHandles() {
            return spyOn(slider, '_renderHandleChanges').andCallFake(function() {});
        };

        function createFakeFireOnChange() {
            return spyOn(slider, '_fireOnChange').andCallFake(function() {});
        };

        function createFakeHandleKeydown() {
            return spyOn(slider, '_onHandleKeydown').andCallFake(function() {});
        };

        function createFakeHandleMousedown() {
            return spyOn(slider, '_onHandleMousedown').andCallFake(function() {});
        };

        function createFakeSliderClick() {
            return spyOn(slider, '_onSliderClick').andCallFake(function() {});
        };

        function createFakeMouseUp() {
            return spyOn(slider, '_onMouseup').andCallFake(function() {});
        };

        function createFakeSliderSetOnDrag() {
            return spyOn(slider, '_setSliderValueOnDrag').andCallFake(function() {});
        };

    });

})();<commit_msg>added test for slider click<commit_after>(function() {

    describe('Sliderbarr', function() {
        var slider = null;
        var testValue = 56;

        beforeEach(function() {
            slider = new SliderBarr({
                el: $('#slider'),
                value: 50,
                step: 1
            });
        });

        afterEach(function() {
            $('#slider-two').empty();
        });

        it ('can construct', function() {
            var fakeValidateHandles = spyOn(SliderBarr.prototype, '_validateHandles').andCallFake(function() {});
            var fakeRender = spyOn(SliderBarr.prototype, '_render').andCallFake(function() {});
            var fakeRenderLabels = spyOn(SliderBarr.prototype, '_renderEdgeLabels').andCallFake(function() {});
            var fakeInitSelectors = spyOn(SliderBarr.prototype, '_initSelectors').andCallFake(function() {});
            var fakeInitEvents = spyOn(SliderBarr.prototype, '_initEvents').andCallFake(function() {});
            var fakeRenderHandleChanges = spyOn(SliderBarr.prototype, '_renderHandleChanges').andCallFake(function() {});

            var slide = new SliderBarr({el: $('#slider')});

            expect(slide._settings.el).toEqual($('#slider'));
            expect(slide._settings.max).toBe(100);
            expect(slide._settings.min).toBe(0);
            expect(slide._settings.value).toBe(25);
            expect(slide._settings.bar).toBeTruthy();
            expect(slide._settings.labels).toBeFalsy();
            expect(slide._settings.step).toBe(1);
            expect(slide._settings.onChange).toBeNull();
            expect(slide._settings.onDrag).toBeNull();

            expect(slide._activeDrag).toBeFalsy();
            expect(slide._sliderAttr).toEqual({});
            expect(slide._cache).toEqual([]);

            expect(fakeValidateHandles).toHaveBeenCalled();
            expect(fakeRender).toHaveBeenCalled();
            expect(fakeRenderLabels).not.toHaveBeenCalled();
            expect(fakeInitSelectors).toHaveBeenCalled();
            expect(fakeInitEvents).toHaveBeenCalled();
            expect(fakeRenderHandleChanges).toHaveBeenCalled();

        });

        describe('Rendering', function() {

            it ('can render', function() {
                // Ensure there is no slider intialised first
                expect($('#slider-two').find('div').length).toBe(0);

                // Initialise slider
                var slide = new SliderBarr({el: $('#slider-two')});

                // Ensure the slider has new DOM elements
                expect($('#slider-two').find('div').length).not.toBe(0);
            });

            it ('can render edge labels', function() {
                // Ensure there is no slider intialised first
                var el = $('#slider-two');
                expect(el.find('div').length).toBe(0);
                expect(el.find('.label').length).toBe(0);

                // Initialise slider
                var slide = new SliderBarr({el: el, labels: true});

                // Ensure the slider has new DOM elements
                expect(el.find('div').length).not.toBe(0);
                expect(el.find('.label').length).not.toBe(0);
            });

        });

        describe('Selectors', function() {

            it ('can initialise jquery selectors', function() {
                $el = $('#slider-two');
                var slide = new SliderBarr({el: $el, labels: true});
                expect($(document)).toEqual(slide._cache.document);
                expect($el).toEqual(slide._cache.slider);
                expect($el.find('.bar')).toEqual(slide._cache.bar);
                expect($el.find('.handle')).toEqual(slide._cache.handle);
                expect($el.find('.current')).toEqual(slide._cache.current);
            });

        });

        describe('Events', function() {

            it ('can initialise events', function() {

            });

            it ('can handle on keydown', function() {
                var e = {
                    keyCode: 37
                };

                var spyChangeHandle = spyOn(slider, '_changeHandle');
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).toHaveBeenCalledWith('l');

                spyChangeHandle.reset();

                e.keyCode = 38;
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).toHaveBeenCalledWith('r');

                spyChangeHandle.reset();

                e.keyCode = 0;
                slider._onHandleKeydown(e);
                expect(spyChangeHandle).not.toHaveBeenCalled();
            });

            it ('can handle on mousedown', function() {

            });

            it ('can handle on mouse move', function() {
                var e = {};

                fakeSetSliderValueOnDrag = createFakeSliderSetOnDrag();

                slider._activeDrag = false;
                slider._onHandleMousemove(e);
                expect(fakeSetSliderValueOnDrag).not.toHaveBeenCalled();

                fakeSetSliderValueOnDrag.reset();

                slider._activeDrag = true;
                slider._onHandleMousemove(e);
                expect(fakeSetSliderValueOnDrag).toHaveBeenCalled();
            });

            it ('can react to slider click', function() {
                var fakeValFromMouseEvent = createFakeGetValFromMouseEvent();
                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandleChanges = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                var e = {};
                var sliderClickResponse = slider._onSliderClick(e);
                expect(fakeValFromMouseEvent).toHaveBeenCalled();
                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandleChanges).toHaveBeenCalled();
                expect(fakeFireOnChange).toHaveBeenCalled();
                expect(sliderClickResponse).toBeFalsy();
            });

            it ('can handle mouseup', function() {

            });

            it ('can fire on change', function() {

            });

        });

        describe('Set and Get Values', function() {

            it ('can change handle', function() {
                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandleChanges = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                var val = 22;
                var step = 1;
                slider._settings.step = step;
                slider._settings.value = val;

                slider._changeHandle('r');
                expect(slider._settings.value).toBe(val + step);
                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandleChanges).toHaveBeenCalled();
                expect(fakeFireOnChange).toHaveBeenCalled();

                slider._settings.value = val;

                slider._changeHandle('l');
                expect(slider._settings.value).toBe(val - step);
            });

            it ('can validate value', function() {
                var testValue = 50;
                expect(slider._validateValue(testValue)).toBe(50);
                testValue = 50.33333;
                expect(slider._validateValue(testValue)).toBe(50);

                slider._settings.step = 0.25;
                testValue = 23.75;
                expect(slider._validateValue(testValue)).toBe(23.75);
                testValue = 23.7786534;
                expect(slider._validateValue(testValue)).toBe(23.78);
            });

            it ('can validate handles', function() {
                var val = 9e9;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(slider._settings.max);

                val = -9e9;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(slider._settings.min);

                val = 27;
                slider._settings.value = val;
                slider._validateHandles();
                expect(slider._settings.value).toBe(val);
            });

            it ('can get value from mouse event', function() {
                var e = {
                    pageX: 500
                };

                slider._sliderAttr.width = 100;
                expect(slider._getValFromMouseEvent(e)).toBe(500);
            });

            it ('can set slider value on drag', function() {
                var testValue = 56;
                var fakeGetValFromMouseEvent = createFakeGetValFromMouseEvent();
                var fakeValidateHandles = createFakeValidateHandles();
                var seenDrag = false;

                slider._settings.onDrag = function() { seenDrag = true; };

                slider._setSliderValueOnDrag({});
                expect(slider._settings.value).toBe(testValue);
                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeGetValFromMouseEvent).toHaveBeenCalled();
                expect(seenDrag).toBeTruthy();
            });

            it ('can get value', function() {
                slider._settings.value = 78;
                expect(slider.getValue()).toBe(78);
            });

            it ('can set value', function() {
                var testValue = 27;
                var fireEvents = false;

                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandles = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                slider.setValue(testValue, fireEvents);
                expect(slider._settings.value).toBe(testValue);

                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandles).toHaveBeenCalled();
                expect(fakeFireOnChange).not.toHaveBeenCalled();
            });

            it ('can set value but not fire events', function() {
                var testValue = 29;
                var fireEvents = true;

                var fakeValidateHandles = createFakeValidateHandles();
                var fakeRenderHandles = createFakeRenderHandles();
                var fakeFireOnChange = createFakeFireOnChange();

                slider.setValue(testValue, fireEvents);
                expect(slider._settings.value).toBe(testValue);

                expect(fakeValidateHandles).toHaveBeenCalled();
                expect(fakeRenderHandles).toHaveBeenCalled();
                expect(fakeFireOnChange).toHaveBeenCalled();
            });

        });

        function createFakeGetValFromMouseEvent() {
            return spyOn(slider, '_getValFromMouseEvent').andCallFake(function() {
                return testValue;
            });
        };

        function createFakeValidateHandles() {
            return spyOn(slider, '_validateHandles').andCallFake(function() {});
        };

        function createFakeRenderHandles() {
            return spyOn(slider, '_renderHandleChanges').andCallFake(function() {});
        };

        function createFakeFireOnChange() {
            return spyOn(slider, '_fireOnChange').andCallFake(function() {});
        };

        function createFakeHandleKeydown() {
            return spyOn(slider, '_onHandleKeydown').andCallFake(function() {});
        };

        function createFakeHandleMousedown() {
            return spyOn(slider, '_onHandleMousedown').andCallFake(function() {});
        };

        function createFakeSliderClick() {
            return spyOn(slider, '_onSliderClick').andCallFake(function() {});
        };

        function createFakeMouseUp() {
            return spyOn(slider, '_onMouseup').andCallFake(function() {});
        };

        function createFakeSliderSetOnDrag() {
            return spyOn(slider, '_setSliderValueOnDrag').andCallFake(function() {});
        };

    });

})();<|endoftext|>


<commit_before>Meteor.subscribe('reports');
Session.setDefault('easter egg counter', 0);

function getReports() {

  var query = {
    expired: false
  };

  if (viewingFavs()) {
    var favs = getFavs();
    query.line = {
      $in: favs.lines
    };
    query.dir = {
      $in: favs.dirs
    };
  }

  return Reports.find(query, { sort: {createdAt: -1}});
}

Template.now.helpers({
  noReports: function() {
    return getReports().count() === 0;
  },
  reports: getReports,

  duzo: function() {
    return Session.get('easter egg counter') > 6;
  },
});

Template.now.onRendered(function() {

  var reqAnimationFrame = (function () {
    var raf =  window[Hammer.prefixed(window, 'requestAnimationFrame')];
    return raf || function (callback) {
      window.setTimeout(callback, 1000 / 60);
    };
  })();

  var ninja = document.querySelector("#play-ninja");
  var cover = document.querySelector(".cover");

  var ticking = false;
  var transform;
  var timer;

  var mc = new Hammer.Manager(ninja);

  mc.add(new Hammer.Pan({ threshold: 0, pointers: 0 }));
  mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));
  mc.add(new Hammer.Rotate({ threshold: 0 })).recognizeWith(mc.get('pan'));
  mc.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([mc.get('pan'), mc.get('rotate')]);

  mc.on("panstart panmove", onPan);
  mc.on("rotatestart rotatemove", onRotate);
  mc.on("pinchstart pinchmove", onPinch);

  mc.on("hammer.input", function(ev) {
    if (ev.isFinal) {
      resetElement();
    }
  });

  function resetElement() {
    ninja.className = 'animate';
    transform = {
      translate: { x: 0, y: 0 },
      scale: 1,
      rotateX: 0,
      rotateY: 0,
      rotateZ: 0,
    };
    requestElementUpdate();
  }

  function updateElementTransform() {
    var value = [
      'translate3d(' + transform.translate.x + 'px, ' +
        transform.translate.y + 'px, 0)',
      'scale(' + transform.scale + ', ' + transform.scale + ')',
      'rotateX('+ transform.rotateX + 'deg)',
      'rotateY('+ transform.rotateY + 'deg)',
      'rotateZ('+ transform.rotateZ + 'deg)',
    ];

    value = value.join(" ");
    ninja.style.webkitTransform = value;
    ninja.style.mozTransform = value;
    ninja.style.transform = value;
    ticking = false;
  }

  function requestElementUpdate() {
    if(!ticking) {
      reqAnimationFrame(updateElementTransform);
      ticking = true;
    }
  }

  var max = Math.min(cover.offsetWidth / 2, cover.offsetHeight / 2);

  function damp(x, max) {
    var abs = max * (1 - Math.exp(-0.005 * Math.abs(x)));
    return x > 0 ? abs : -abs;
  }

  function onPan(ev) {
    ninja.className = '';
    transform.translate = {
      x: damp(ev.deltaX, max),
      y: damp(ev.deltaY, max)
    };

    transform.rotateX = - damp(ev.deltaY, 90);
    transform.rotateY = damp(ev.deltaX, 90);

    requestElementUpdate();
  }

  var initScale = 1;
  function onPinch(ev) {
    if(ev.type == 'pinchstart') {
      initScale = transform.scale || 1;
    }

    ninja.className = '';
    transform.scale = initScale * ev.scale;

    requestElementUpdate();
  }

  var initAngle = 0;
  function onRotate(ev) {
    if(ev.type == 'rotatestart') {
      initAngle = transform.angle || 0;
    }

    ninja.className = '';
    transform.rz = 1;
    transform.angle = initAngle + ev.rotation;

    requestElementUpdate();
  }

  resetElement();

});

Template.now.events({
    'click .cover': function(event) {
        Session.set('easter egg counter', Session.get('easter egg counter') + 1);
    },
});
<commit_msg>guard against null ninja<commit_after>Meteor.subscribe('reports');
Session.setDefault('easter egg counter', 0);

function getReports() {

  var query = {
    expired: false
  };

  if (viewingFavs()) {
    var favs = getFavs();
    query.line = {
      $in: favs.lines
    };
    query.dir = {
      $in: favs.dirs
    };
  }

  return Reports.find(query, { sort: {createdAt: -1}});
}

Template.now.helpers({
  noReports: function() {
    return getReports().count() === 0;
  },
  reports: getReports,

  duzo: function() {
    return Session.get('easter egg counter') > 6;
  },
});

Template.now.onRendered(function() {

  var reqAnimationFrame = (function () {
    var raf =  window[Hammer.prefixed(window, 'requestAnimationFrame')];
    return raf || function (callback) {
      window.setTimeout(callback, 1000 / 60);
    };
  })();

  var ninja = document.querySelector("#play-ninja");
  var cover = document.querySelector(".cover");

  var ticking = false;
  var transform;
  var timer;

  if (!ninja) {
    return false;
  }

  var mc = new Hammer.Manager(ninja);

  mc.add(new Hammer.Pan({ threshold: 0, pointers: 0 }));
  mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));
  mc.add(new Hammer.Rotate({ threshold: 0 })).recognizeWith(mc.get('pan'));
  mc.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([mc.get('pan'), mc.get('rotate')]);

  mc.on("panstart panmove", onPan);
  mc.on("rotatestart rotatemove", onRotate);
  mc.on("pinchstart pinchmove", onPinch);

  mc.on("hammer.input", function(ev) {
    if (ev.isFinal) {
      resetElement();
    }
  });

  function resetElement() {
    ninja.className = 'animate';
    transform = {
      translate: { x: 0, y: 0 },
      scale: 1,
      rotateX: 0,
      rotateY: 0,
      rotateZ: 0,
    };
    requestElementUpdate();
  }

  function updateElementTransform() {
    var value = [
      'translate3d(' + transform.translate.x + 'px, ' +
        transform.translate.y + 'px, 0)',
      'scale(' + transform.scale + ', ' + transform.scale + ')',
      'rotateX('+ transform.rotateX + 'deg)',
      'rotateY('+ transform.rotateY + 'deg)',
      'rotateZ('+ transform.rotateZ + 'deg)',
    ];

    value = value.join(" ");
    ninja.style.webkitTransform = value;
    ninja.style.mozTransform = value;
    ninja.style.transform = value;
    ticking = false;
  }

  function requestElementUpdate() {
    if(!ticking) {
      reqAnimationFrame(updateElementTransform);
      ticking = true;
    }
  }

  var max = Math.min(cover.offsetWidth / 2, cover.offsetHeight / 2);

  function damp(x, max) {
    var abs = max * (1 - Math.exp(-0.005 * Math.abs(x)));
    return x > 0 ? abs : -abs;
  }

  function onPan(ev) {
    ninja.className = '';
    transform.translate = {
      x: damp(ev.deltaX, max),
      y: damp(ev.deltaY, max)
    };

    transform.rotateX = - damp(ev.deltaY, 90);
    transform.rotateY = damp(ev.deltaX, 90);

    requestElementUpdate();
  }

  var initScale = 1;
  function onPinch(ev) {
    if(ev.type == 'pinchstart') {
      initScale = transform.scale || 1;
    }

    ninja.className = '';
    transform.scale = initScale * ev.scale;

    requestElementUpdate();
  }

  var initAngle = 0;
  function onRotate(ev) {
    if(ev.type == 'rotatestart') {
      initAngle = transform.angle || 0;
    }

    ninja.className = '';
    transform.rz = 1;
    transform.angle = initAngle + ev.rotation;

    requestElementUpdate();
  }

  resetElement();

});

Template.now.events({
    'click .cover': function(event) {
        Session.set('easter egg counter', Session.get('easter egg counter') + 1);
    },
});
<|endoftext|>


<commit_before>/*jshint node:true, strict:false */
/*global describe, it, expect*/
var supertest = require('supertest'),
  http = require('http'),
  express = require('express'),
  app = require('../lib/app.js');

describe('app', function(){
  it('should give a status of 502 for a non-existent page', function(done){
    supertest(app)
      .get('/')
      .query({url: 'http://localhost:8001'})
      .expect(502, done);
  });

  it('should pass the JSON and set the CORS headers', function(done){
    var json = JSON.stringify({ message: 'test' });

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(json);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({url: 'http://localhost:8001'})
        .expect('access-control-allow-origin', '*')
        .expect(json, function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should wrap with callback name, if provided', function(done){
    var json = JSON.stringify({ message: 'test' });

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(json);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({callback: 'foo', url: 'http://localhost:8001'})
        .expect('foo(' + json + ');', function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should escape "raw" requests for JSONP', function(done){
    var destApp = express();
    destApp.get('/', function(req, res){
      res.send('test " \' " </script> escaping');
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({callback: 'foo', url: 'http://localhost:8001', raw: true})
        .expect('foo({"data":"test \\" \' \\" <\\/script> escaping"});', function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should pass the unescaped body for "raw" CORS requests', function(done){
    var body = 'test " \' " escaping';

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(body);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({url: 'http://localhost:8001', raw: true})
        .expect(body, function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });
});
<commit_msg>test for header removal<commit_after>/*jshint node:true, strict:false */
/*global describe, it*/
var supertest = require('supertest'),
  http = require('http'),
  express = require('express'),
  expect = require('expect.js'),
  app = require('../lib/app.js');

describe('app', function(){
  it('should give a status of 502 for a non-existent page', function(done){
    supertest(app)
      .get('/')
      .query({url: 'http://localhost:8001'})
      .expect(502, done);
  });

  it('should pass the JSON and set the CORS headers', function(done){
    var json = JSON.stringify({ message: 'test' });

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(json);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({url: 'http://localhost:8001'})
        .expect('access-control-allow-origin', '*')
        .expect(json, function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should remove particular headers from the server', function(done){
    var json = JSON.stringify({ message: 'test' });

    var destApp = express();
    destApp.get('/', function(req, res){
      res.set({
        'Content-Length': 123,
        'Connection': 'close',
        'Server': 'CERN/3.0 libwww/2.17',
        'X-Frame-Options': 'SAMEORIGIN'
      });
      res.send(json);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({url: 'http://localhost:8001'})
        .expect('access-control-allow-origin', '*')
        .expect('Content-Length', '18')
        .expect('Connection', 'keep-alive')
        .expect(json, function(err, res){
          expect(res.headers.Server).to.be(undefined);
          expect(res.headers['X-Frame-Options']).to.be(undefined);

          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should wrap with callback name, if provided', function(done){
    var json = JSON.stringify({ message: 'test' });

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(json);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({callback: 'foo', url: 'http://localhost:8001'})
        .expect('foo(' + json + ');', function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should escape "raw" requests for JSONP', function(done){
    var destApp = express();
    destApp.get('/', function(req, res){
      res.send('test " \' " </script> escaping');
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({callback: 'foo', url: 'http://localhost:8001', raw: true})
        .expect('foo({"data":"test \\" \' \\" <\\/script> escaping"});', function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });

  it('should pass the unescaped body for "raw" CORS requests', function(done){
    var body = 'test " \' " escaping';

    var destApp = express();
    destApp.get('/', function(req, res){
      res.send(body);
    });
    var server = http.createServer(destApp);
    server.listen(8001, function(){

      supertest(app)
        .get('/')
        .query({url: 'http://localhost:8001', raw: true})
        .expect(body, function(err){
          server.on('close', function(){
            done(err);
          });
          server.close();
        });

    });
  });
});
<|endoftext|>


<commit_before>;
/* main initialization routine */
$.fn.towelFoundation = function() {
    /* onReady */
    $(function() {
        var onReady = window.onReady || [];
        for (var i=0, l=onReady.length; i<l; i++) onReady[i].apply(null, [$]);
    });

    return this;
};

/* various plugins */
$.fn.flash = function() {
    return this.each(function() {
        var $this = $(this),
            opacity = $this.css('opacity');

        $this.css('opacity', 0.3).animate({opacity: opacity});
    });
};

$.fn.autogrow = function() {
    return this.not('.hasAutogrow').addClass('hasAutogrow').elastic();
};

/* gettext dummy
* if you need internationalizations, read here how to activate:
* https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-javascript-code
* */
if (window.gettext === undefined) {
    window.gettext = function(msgid) {
        return msgid
    }
}

/* init forms */
(function($) {
    if (!window.onForm) window.onForm = [];

    var onForm = window.onForm,
        initForms = function(elem) {
            var elem = $(elem || document);
            for (var i=0, len=onForm.length; i<len; ++i)
                onForm[i].apply(null, [elem, $]);
        };

    onForm.push(function(elem, $) {
        if ($.fn.chosen)
            elem.find('select').not('.plain').chosen();
        if ($.fn.datePicker) {
            elem.find('.type-date').each(function() {
                var self = $(this),
                    input = self.find('input[type=text]');

                Date.format = self.data('date-format');
                input.datePicker({
                    horizontalPosition: $.dpConst.POS_RIGHT,
                    displayClose: true,
                    startDate: new Date(1900, 1, 1)
                });

                var lnk = input.parent().find('.dp-choose-date');
                lnk.html('');
            });
        }

        elem.find('textarea.autogrow, .autogrow textarea').autogrow();
    });

    onReady.push(function() { initForms(); });

    /* inject function into the global namespace */
    if (!window.initForms) window.initForms = initForms;

    $(document.body).on('updateLive', function(event, elem) {
        event.stopPropagation();
        elem.flash();
        initForms(elem);
    });
})(jQuery);

/* ajax modals */
(function($) {
    var initModal = function() {
            var modal = this,
                $elem = $(this);

            $elem.find('form').each(function() {
                var $form = $(this),
                    handleResponse = function(data) {
                        window.modalLoad.locked = false;

                        if (typeof(data) == 'string') {
                            $elem.html(data);
                            initModal.call($elem.get(0));
                        } else {
                            updateLive(data);
                            if (!('!keep' in data))
                                $elem.foundation('reveal', 'close');
                        }
                    }

                // set modal to locked: navigating away will be prevented
                // and also closing the modal will prompt the user
                $form.filter('[method="post"]').on('change', function(event) {
                    window.modalLoad.locked = true;
                });

                $form.on('submit', function() {
                    if (this.method.toLowerCase() == 'post') {
                        if ($.fn.ajaxSubmit) {
                            // jquery.form.js is available, XHR file uploads will
                            // work too
                            var $bar = $elem.find('.progress-bar');

                            $(this).ajaxSubmit({
                                uploadProgress: function(evt, pos, total, percComplete) {
                                    $bar.width(percComplete + '%');
                                },
                                beforeSubmit: function() {
                                    $bar.width('0%');
                                },
                                success: handleResponse
                            });
                        } else {
                            $.post(this.action, $form.serialize(), handleResponse);
                        }
                    } else {
                        $.get(this.action, $form.serialize(), handleResponse);
                    }
                    return false;
                });

                // focus the first form element
                (function(form) {
                    setTimeout(function() {
                        initForms(form);
                        $('input:visible, textarea', form).first().focus();
                    }, 150);
                })(this);
            });
        },
        modalLoad = function(url, cls) {
            var modal = $('div.reveal-modal');
            if (!modal.length) {
                /* create div for holding AJAX-loaded modals, once */
                modal = $('
').addClass('reveal-modal').appendTo('body');
                modal.on('close', function(event) {
                    if (event.target != this) {
                        // another element triggered the hide event. Ignore it.
                        return true;
                    }

                    // if the modal is locked (i.e. uploading/submission in progress)
                    if (window.modalLoad.locked) {
                        if (!confirm(gettext('You have unsaved changes. Do you really want to throw them away?'))) {
                            return false;
                        }
                    }

                    // unlock the modal
                    window.modalLoad.locked = false;
                    $('#logo').focus().blur();
                });
            }

            modal.removeClass().addClass('reveal-modal');
            if (cls)
                modal.addClass(cls);

            modal.empty().load(url, function() {
                var $m = $(this),
                    cls = $m.find('[data-reveal-class]').data('reveal-class');
                if (cls)
                    $m.addClass(cls);
                initModal.call(this);
                $m.foundation('reveal', 'open');
            });
        };

    $(document.body).on('click', 'a[data-toggle="ajaxmodal"]', function(e) {
        e.preventDefault();
        modalLoad(this.href, $(this).data('reveal-class'));
    });

    // prevent navigating away without saving:
    $(window).on('beforeunload', function() {
        if (window.modalLoad.locked) {
          return gettext('You have unsaved changes. Do you really want to throw them away?')
        };
    });

    /* inject function into the global namespace */
    if (!window.modalLoad) window.modalLoad = modalLoad;
})(jQuery);

/* jQuery / Django CSRF handling
Thanks, https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax */
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
<commit_msg>Fix the progress bar javascript<commit_after>;
/* main initialization routine */
$.fn.towelFoundation = function() {
    /* onReady */
    $(function() {
        var onReady = window.onReady || [];
        for (var i=0, l=onReady.length; i<l; i++) onReady[i].apply(null, [$]);
    });

    return this;
};

/* various plugins */
$.fn.flash = function() {
    return this.each(function() {
        var $this = $(this),
            opacity = $this.css('opacity');

        $this.css('opacity', 0.3).animate({opacity: opacity});
    });
};

$.fn.autogrow = function() {
    return this.not('.hasAutogrow').addClass('hasAutogrow').elastic();
};

/* gettext dummy
* if you need internationalizations, read here how to activate:
* https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-javascript-code
* */
if (window.gettext === undefined) {
    window.gettext = function(msgid) {
        return msgid
    }
}

/* init forms */
(function($) {
    if (!window.onForm) window.onForm = [];

    var onForm = window.onForm,
        initForms = function(elem) {
            var elem = $(elem || document);
            for (var i=0, len=onForm.length; i<len; ++i)
                onForm[i].apply(null, [elem, $]);
        };

    onForm.push(function(elem, $) {
        if ($.fn.chosen)
            elem.find('select').not('.plain').chosen();
        if ($.fn.datePicker) {
            elem.find('.type-date').each(function() {
                var self = $(this),
                    input = self.find('input[type=text]');

                Date.format = self.data('date-format');
                input.datePicker({
                    horizontalPosition: $.dpConst.POS_RIGHT,
                    displayClose: true,
                    startDate: new Date(1900, 1, 1)
                });

                var lnk = input.parent().find('.dp-choose-date');
                lnk.html('');
            });
        }

        elem.find('textarea.autogrow, .autogrow textarea').autogrow();
    });

    onReady.push(function() { initForms(); });

    /* inject function into the global namespace */
    if (!window.initForms) window.initForms = initForms;

    $(document.body).on('updateLive', function(event, elem) {
        event.stopPropagation();
        elem.flash();
        initForms(elem);
    });
})(jQuery);

/* ajax modals */
(function($) {
    var initModal = function() {
            var modal = this,
                $elem = $(this);

            $elem.find('form').each(function() {
                var $form = $(this),
                    handleResponse = function(data) {
                        window.modalLoad.locked = false;

                        if (typeof(data) == 'string') {
                            $elem.html(data);
                            initModal.call($elem.get(0));
                        } else {
                            updateLive(data);
                            if (!('!keep' in data))
                                $elem.foundation('reveal', 'close');
                        }
                    }

                // set modal to locked: navigating away will be prevented
                // and also closing the modal will prompt the user
                $form.filter('[method="post"]').on('change', function(event) {
                    window.modalLoad.locked = true;
                });

                $form.on('submit', function() {
                    if (this.method.toLowerCase() == 'post') {
                        if ($.fn.ajaxSubmit) {
                            // jquery.form.js is available, XHR file uploads will
                            // work too
                            var $bar = $elem.find('.meter');

                            $(this).ajaxSubmit({
                                uploadProgress: function(evt, pos, total, percComplete) {
                                    $bar.width(percComplete + '%');
                                },
                                beforeSubmit: function() {
                                    $bar.width('0%');
                                },
                                success: handleResponse
                            });
                        } else {
                            $.post(this.action, $form.serialize(), handleResponse);
                        }
                    } else {
                        $.get(this.action, $form.serialize(), handleResponse);
                    }
                    return false;
                });

                // focus the first form element
                (function(form) {
                    setTimeout(function() {
                        initForms(form);
                        $('input:visible, textarea', form).first().focus();
                    }, 150);
                })(this);
            });
        },
        modalLoad = function(url, cls) {
            var modal = $('div.reveal-modal');
            if (!modal.length) {
                /* create div for holding AJAX-loaded modals, once */
                modal = $('
').addClass('reveal-modal').appendTo('body');
                modal.on('close', function(event) {
                    if (event.target != this) {
                        // another element triggered the hide event. Ignore it.
                        return true;
                    }

                    // if the modal is locked (i.e. uploading/submission in progress)
                    if (window.modalLoad.locked) {
                        if (!confirm(gettext('You have unsaved changes. Do you really want to throw them away?'))) {
                            return false;
                        }
                    }

                    // unlock the modal
                    window.modalLoad.locked = false;
                    $('#logo').focus().blur();
                });
            }

            modal.removeClass().addClass('reveal-modal');
            if (cls)
                modal.addClass(cls);

            modal.empty().load(url, function() {
                var $m = $(this),
                    cls = $m.find('[data-reveal-class]').data('reveal-class');
                if (cls)
                    $m.addClass(cls);
                initModal.call(this);
                $m.foundation('reveal', 'open');
            });
        };

    $(document.body).on('click', 'a[data-toggle="ajaxmodal"]', function(e) {
        e.preventDefault();
        modalLoad(this.href, $(this).data('reveal-class'));
    });

    // prevent navigating away without saving:
    $(window).on('beforeunload', function() {
        if (window.modalLoad.locked) {
          return gettext('You have unsaved changes. Do you really want to throw them away?')
        };
    });

    /* inject function into the global namespace */
    if (!window.modalLoad) window.modalLoad = modalLoad;
})(jQuery);

/* jQuery / Django CSRF handling
Thanks, https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax */
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
<|endoftext|>


<commit_before>const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;

describe('rainier-beer server', () => {
  it('should respond to a GET request', (done) => {
    request('localhost:3000')
    .get('/moose')
    .end((err, res) => {
      expect(err).to.eql(null);
      expect(res).to.have.status(210);
      expect(res.text).to.eql('Hello Kat');
      done();
    });
  });

  it('should get a 404 error', (done) => {
    request('localhost:3000')
    .get('/badroute')
    .end((err, res) => {
      expect(err).to.not.eql(null);
      expect(res).to.have.status(404);
      expect(res.text).to.eql('404 Not Found');
      done();
    });
  });
});
<commit_msg>added require to server_test.js<commit_after>const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const request = chai.request;
require(__dirname + '/../lib/server.js');

describe('rainier-beer server', () => {
  it('should respond to a GET request', (done) => {
    request('localhost:3000')
    .get('/moose')
    .end((err, res) => {
      expect(err).to.eql(null);
      expect(res).to.have.status(210);
      expect(res.text).to.eql('Hello Kat');
      done();
    });
  });

  it('should get a 404 error', (done) => {
    request('localhost:3000')
    .get('/badroute')
    .end((err, res) => {
      expect(err).to.not.eql(null);
      expect(res).to.have.status(404);
      expect(res.text).to.eql('404 Not Found');
      done();
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

// This hook automates this:
// https://github.com/cordova-rtc/cordova-plugin-iosrtc/blob/master/docs/Building.md

var
	fs = require("fs"),
	path = require("path"),
	xcode = require('xcode'),
	xmlEntities = new (require('html-entities').XmlEntities)(),

	IPHONEOS_DEPLOYMENT_TARGET = '10.2',
	IPHONEOS_DEPLOYMENT_TARGET_XCODE = '"' + IPHONEOS_DEPLOYMENT_TARGET + '"',
	SWIFT_VERSION = '4.2',
	SWIFT_VERSION_XCODE = '"' + SWIFT_VERSION + '"',
	RUNPATH_SEARCH_PATHS = '@executable_path/Frameworks',
	RUNPATH_SEARCH_PATHS_XCODE = '"' + RUNPATH_SEARCH_PATHS + '"',
	ENABLE_BITCODE = 'NO',
	ENABLE_BITCODE_XCODE = '"' + ENABLE_BITCODE + '"',
	UNIFIED_BRIDGING_HEADER = 'Plugins/Unified-Bridging-Header.h',
	IOSRTC_BRIDGING_HEADER = "cordova-plugin-iosrtc-Bridging-Header.h",
	BRIDGING_HEADER_END = '/Plugins/cordova-plugin-iosrtc/' + IOSRTC_BRIDGING_HEADER,
	TEST_UNIFIED_BRIDGING_HEADER = false; // Set to true to test handling of existing swift bridging header

// Helpers

// Returns the project name
function getProjectName(protoPath) {
	var
		cordovaConfigPath = path.join(protoPath, 'config.xml'),
		content = fs.readFileSync(cordovaConfigPath, 'utf-8');

	var name = /<name>([\s\S]*)<\/name>/mi.exec(content)[1].trim();
	return xmlEntities.decode(name);
}

// Drops the comments
var COMMENT_KEY = /_comment$/;
function nonComments(obj) {
	var
		keys = Object.keys(obj),
		newObj = {},
		i = 0;

	for (i; i < keys.length; i += 1) {
		if (!COMMENT_KEY.test(keys[i])) {
			newObj[keys[i]] = obj[keys[i]];
		}
	}

	return newObj;
}

function matchBuildSettingsValue(value, expectedValue) {
	return value === expectedValue;
}

function hasBuildSettingsValue(value, expectedValue) {
	return value && (matchBuildSettingsValue(value, expectedValue) || value.indexOf(expectedValue) !== -1);
}

function convertToFloat(value) {
	return parseFloat(value.replace(/[^\d.-]/g,''), 10);
}

function matchMinValue(value, minValue) {
	//console.log('matchMinValue', value, minValue)
	return value && convertToFloat(value) >= convertToFloat(minValue);
}

function matchBuildSettingsMinValue(value, expectedValue) {
	return value && (matchBuildSettingsValue(value, expectedValue) || matchMinValue(value, expectedValue));
}

function matchXcconfigPathValue(swiftOptions, path, expectedValue) {
	return swiftOptions.filter(function (swiftOption) {
		return swiftOption === path + ' = ' + expectedValue;
	}).length > 0;
}

function getXcconfigPathValue(swiftOptions, path) {
	var swiftOption = swiftOptions.filter(function (swiftOption) {
		return swiftOption.indexOf(path + ' = ') === 0;
	})[0];

	return swiftOption ? swiftOption.split(' = ')[1] : '';
}

function matchXcconfigMinValue(swiftOptions, path, expectedValue) {
	var swiftOption = swiftOptions.find(function (swiftOption) {
		return swiftOption.split(' = ')[0] === path;
	});

	return swiftOption && matchMinValue(swiftOption.split(' = ')[1], expectedValue);
}

function getRelativeToProjectRootPath(path, projectRoot) {
	return path.replace(projectRoot, '.');
}

function readFileLines(filePath) {
	return fs.readFileSync(filePath).toString().split("\n");
}

function debug(msg) {
	console.log('iosrtc-swift-support.js [INFO] ' + msg);
}

function debugError(msg) {
	console.error('iosrtc-swift-support.js [ERROR] ' + msg);
	process.exit(1);
}

// Starting here

module.exports = function (context) {

	// This script has to be executed depending on the command line arguments, not
  	// on the hook execution cycle.
  	/*
	if (context.hook !== 'before_build' && !context.cmdLine.includes('build')) {
		return;
	}
	*/

	var
		projectRoot = context.opts.projectRoot,
		projectName = getProjectName(projectRoot),
		platformPath = path.join(projectRoot, 'platforms', 'ios'),
		platformProjectPath = path.join(platformPath, projectName),
		xcconfigPath = path.join(platformPath, '/cordova/build.xcconfig'),
		xcodeProjectName = projectName + '.xcodeproj',
		xcodeProjectConfigPath = path.join(platformPath, xcodeProjectName, 'project.pbxproj'),
		swiftBridgingHeaderPath = projectName + BRIDGING_HEADER_END,
		swiftBridgingHeaderPathXcode = '"' + swiftBridgingHeaderPath + '"',
		swiftOptions = [''], // <-- begin to file appending AFTER initial newline
		xcodeProject;

	// Showing info about the tasks to do
	debug('cordova-plugin-iosrtc is checking issues in the generated project files:');
	debug('- Minimum "iOS Deployment Target" and "Deployment Target" to: ' + IPHONEOS_DEPLOYMENT_TARGET_XCODE);
	debug('- "Runpath Search Paths" to: ' + RUNPATH_SEARCH_PATHS_XCODE);
	if (TEST_UNIFIED_BRIDGING_HEADER) {
		debug('- "Objective-C Bridging Header" to: ' + UNIFIED_BRIDGING_HEADER);
	} else {
		debug('- "Objective-C Bridging Header" to: ' + swiftBridgingHeaderPathXcode);
	}
	debug('- "ENABLE_BITCODE" set to: ' + ENABLE_BITCODE_XCODE);
	debug('- "SWIFT_VERSION" set to: ' + SWIFT_VERSION_XCODE);

	// Checking if the project files are in the right place
	if (!fs.existsSync(xcodeProjectConfigPath)) {
		debugError('an error occurred searching the project file at: "' + xcodeProjectConfigPath + '"');

		return;
	}
	debug('".pbxproj" project file found: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));

	if (!fs.existsSync(xcconfigPath)) {
		debugError('an error occurred searching the project file at: "' + xcconfigPath + '"');

		return;
	}
	debug('".xcconfig" project file found: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));

	xcodeProject = xcode.project(xcodeProjectConfigPath);

	// Massaging the files

	// "build.xcconfig"
	debug('checking file: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	var xcconfigPathChanged = false;

	// Parsing it
	var currentSwiftOptions = [];
	if (fs.existsSync(xcconfigPath)) {
		currentSwiftOptions = readFileLines(xcconfigPath);
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'LD_RUNPATH_SEARCH_PATHS', RUNPATH_SEARCH_PATHS)) {
		swiftOptions.push('LD_RUNPATH_SEARCH_PATHS = ' + RUNPATH_SEARCH_PATHS);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigMinValue(currentSwiftOptions, 'IPHONEOS_DEPLOYMENT_TARGET', IPHONEOS_DEPLOYMENT_TARGET)) {
		swiftOptions.push('IPHONEOS_DEPLOYMENT_TARGET = ' + IPHONEOS_DEPLOYMENT_TARGET);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'ENABLE_BITCODE', ENABLE_BITCODE)) {
		swiftOptions.push('ENABLE_BITCODE = ' + ENABLE_BITCODE);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'SWIFT_VERSION', SWIFT_VERSION)) {
		swiftOptions.push('SWIFT_VERSION = ' + SWIFT_VERSION);
		xcconfigPathChanged = true;
	}

	var existingSwiftBridgingHeaderPath;
	if (TEST_UNIFIED_BRIDGING_HEADER) {
		existingSwiftBridgingHeaderPath = path.join(platformProjectPath, UNIFIED_BRIDGING_HEADER);
	} else {
		if (!matchXcconfigPathValue(currentSwiftOptions, 'SWIFT_OBJC_BRIDGING_HEADER', swiftBridgingHeaderPath)) {
			var currentSwiftBridgingHeader = getXcconfigPathValue(currentSwiftOptions, 'SWIFT_OBJC_BRIDGING_HEADER').replace('$(PROJECT_DIR)/$(PROJECT_NAME)/', '');
			if (!existingSwiftBridgingHeaderPath) {
				swiftOptions.push('SWIFT_OBJC_BRIDGING_HEADER = ' + swiftBridgingHeaderPath);
				xcconfigPathChanged = true;
			} else {
				existingSwiftBridgingHeaderPath = path.join(platformProjectPath, currentSwiftBridgingHeader);
			}
		}
	}

	// NOTE: Not needed
	// swiftOptions.push('EMBEDDED_CONTENT_CONTAINS_SWIFT = YES');

	if (xcconfigPathChanged) {
		fs.appendFileSync(xcconfigPath, swiftOptions.join('\n'));
		debug('file correctly fixed: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	} else {
		debug('file is correct: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	}

	// "project.pbxproj"
	debug('checking file: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));

	// Parsing it
	xcodeProject.parse(function (error) {

		if (error) {
			debugError('an error occurred during the parsing of the project file: ' + xcodeProjectConfigPath);

			return;
		}

		// Adding or changing the parameters only if we need
		var buildSettingsChanged = false;
		var hasSwiftBridgingHeaderPathXcodes = [];
		var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection());
		Object.keys(configurations).forEach(function (config) {
			var buildSettings = configurations[config].buildSettings;

			if (!hasBuildSettingsValue(buildSettings.LD_RUNPATH_SEARCH_PATHS, RUNPATH_SEARCH_PATHS_XCODE)) {
				buildSettings.LD_RUNPATH_SEARCH_PATHS = RUNPATH_SEARCH_PATHS_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsMinValue(buildSettings.IPHONEOS_DEPLOYMENT_TARGET, IPHONEOS_DEPLOYMENT_TARGET_XCODE)) {
				buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IPHONEOS_DEPLOYMENT_TARGET_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsValue(buildSettings.ENABLE_BITCODE, ENABLE_BITCODE_XCODE)) {
				buildSettings.ENABLE_BITCODE = ENABLE_BITCODE_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsValue(buildSettings.SWIFT_VERSION, SWIFT_VERSION_XCODE)) {
				buildSettings.SWIFT_VERSION = SWIFT_VERSION_XCODE;
				buildSettingsChanged = true;
			}

			if (TEST_UNIFIED_BRIDGING_HEADER) {
				buildSettings.SWIFT_OBJC_BRIDGING_HEADER = '"' + UNIFIED_BRIDGING_HEADER + '"';
				xcodeProject.addHeaderFile(UNIFIED_BRIDGING_HEADER);
			}

			if (!hasBuildSettingsValue(buildSettings.SWIFT_OBJC_BRIDGING_HEADER, swiftBridgingHeaderPathXcode)) {

				// Play nice with existing Swift Bridging Header value
				if (existingSwiftBridgingHeaderPath) {

					// Sync SWIFT_OBJC_BRIDGING_HEADER with existingSwiftBridgingHeaderPath if do not match
					var existingSwiftBridgingHeaderPathXcode = '"' + existingSwiftBridgingHeaderPath + '"';
					if (buildSettings.SWIFT_OBJC_BRIDGING_HEADER !== existingSwiftBridgingHeaderPathXcode) {
						buildSettings.SWIFT_OBJC_BRIDGING_HEADER = existingSwiftBridgingHeaderPathXcode;
						buildSettingsChanged = true;
					}

					if (hasSwiftBridgingHeaderPathXcodes.indexOf(existingSwiftBridgingHeaderPath) === -1) {

						// Check if existing existingSwiftBridgingHeaderPath exists and get file lines

						debug('checking file: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));

						var existingSwiftBridgingHeaderFileLines = [];
						if (fs.existsSync(existingSwiftBridgingHeaderPath)) {
							existingSwiftBridgingHeaderFileLines = readFileLines(existingSwiftBridgingHeaderPath);
						}

						// Check if existing existingSwiftBridgingHeaderFileLines contains swiftBridgingHeaderPath
						var swiftBridgingHeaderImport = '#import "' + IOSRTC_BRIDGING_HEADER + '"';
						var hasSwiftBridgingHeaderPathXcode = existingSwiftBridgingHeaderFileLines.filter(function (line) {
							return line === swiftBridgingHeaderImport;
						}).length > 0;

						if (!hasSwiftBridgingHeaderPathXcode) {
							debug('updating existing swift bridging header file: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
							existingSwiftBridgingHeaderFileLines.push(swiftBridgingHeaderImport);
							fs.writeFileSync(existingSwiftBridgingHeaderPath, existingSwiftBridgingHeaderFileLines.join('\n'), 'utf-8');
							debug('file correctly fixed: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
						} else {
							debug('file is correct: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
						}

						hasSwiftBridgingHeaderPathXcodes.push(existingSwiftBridgingHeaderPath);
					}

				} else {
					buildSettings.SWIFT_OBJC_BRIDGING_HEADER = swiftBridgingHeaderPathXcode;
					buildSettingsChanged = true;
				}
			}
		});

		// Writing the file only if changed
		if (buildSettingsChanged) {
			fs.writeFileSync(xcodeProjectConfigPath, xcodeProject.writeSync(), 'utf-8');
			debug('file correctly fixed: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));
		} else {
			debug('file is correct: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));
		}
	});
};
<commit_msg>fix Regex in iosrtc-swift-support.js returns wrong value<commit_after>#!/usr/bin/env node

'use strict';

// This hook automates this:
// https://github.com/cordova-rtc/cordova-plugin-iosrtc/blob/master/docs/Building.md

var
	fs = require("fs"),
	path = require("path"),
	xcode = require('xcode'),
	xmlEntities = new (require('html-entities').XmlEntities)(),

	IPHONEOS_DEPLOYMENT_TARGET = '10.2',
	IPHONEOS_DEPLOYMENT_TARGET_XCODE = '"' + IPHONEOS_DEPLOYMENT_TARGET + '"',
	SWIFT_VERSION = '4.2',
	SWIFT_VERSION_XCODE = '"' + SWIFT_VERSION + '"',
	RUNPATH_SEARCH_PATHS = '@executable_path/Frameworks',
	RUNPATH_SEARCH_PATHS_XCODE = '"' + RUNPATH_SEARCH_PATHS + '"',
	ENABLE_BITCODE = 'NO',
	ENABLE_BITCODE_XCODE = '"' + ENABLE_BITCODE + '"',
	UNIFIED_BRIDGING_HEADER = 'Plugins/Unified-Bridging-Header.h',
	IOSRTC_BRIDGING_HEADER = "cordova-plugin-iosrtc-Bridging-Header.h",
	BRIDGING_HEADER_END = '/Plugins/cordova-plugin-iosrtc/' + IOSRTC_BRIDGING_HEADER,
	TEST_UNIFIED_BRIDGING_HEADER = false; // Set to true to test handling of existing swift bridging header

// Helpers

// Returns the project name
function getProjectName(protoPath) {
	var
		cordovaConfigPath = path.join(protoPath, 'config.xml'),
		content = fs.readFileSync(cordovaConfigPath, 'utf-8');

	var name = /<name>([\S]*)<\/name>/mi.exec(content)[1].trim();
	return xmlEntities.decode(name);
}

// Drops the comments
var COMMENT_KEY = /_comment$/;
function nonComments(obj) {
	var
		keys = Object.keys(obj),
		newObj = {},
		i = 0;

	for (i; i < keys.length; i += 1) {
		if (!COMMENT_KEY.test(keys[i])) {
			newObj[keys[i]] = obj[keys[i]];
		}
	}

	return newObj;
}

function matchBuildSettingsValue(value, expectedValue) {
	return value === expectedValue;
}

function hasBuildSettingsValue(value, expectedValue) {
	return value && (matchBuildSettingsValue(value, expectedValue) || value.indexOf(expectedValue) !== -1);
}

function convertToFloat(value) {
	return parseFloat(value.replace(/[^\d.-]/g,''), 10);
}

function matchMinValue(value, minValue) {
	//console.log('matchMinValue', value, minValue)
	return value && convertToFloat(value) >= convertToFloat(minValue);
}

function matchBuildSettingsMinValue(value, expectedValue) {
	return value && (matchBuildSettingsValue(value, expectedValue) || matchMinValue(value, expectedValue));
}

function matchXcconfigPathValue(swiftOptions, path, expectedValue) {
	return swiftOptions.filter(function (swiftOption) {
		return swiftOption === path + ' = ' + expectedValue;
	}).length > 0;
}

function getXcconfigPathValue(swiftOptions, path) {
	var swiftOption = swiftOptions.filter(function (swiftOption) {
		return swiftOption.indexOf(path + ' = ') === 0;
	})[0];

	return swiftOption ? swiftOption.split(' = ')[1] : '';
}

function matchXcconfigMinValue(swiftOptions, path, expectedValue) {
	var swiftOption = swiftOptions.find(function (swiftOption) {
		return swiftOption.split(' = ')[0] === path;
	});

	return swiftOption && matchMinValue(swiftOption.split(' = ')[1], expectedValue);
}

function getRelativeToProjectRootPath(path, projectRoot) {
	return path.replace(projectRoot, '.');
}

function readFileLines(filePath) {
	return fs.readFileSync(filePath).toString().split("\n");
}

function debug(msg) {
	console.log('iosrtc-swift-support.js [INFO] ' + msg);
}

function debugError(msg) {
	console.error('iosrtc-swift-support.js [ERROR] ' + msg);
	process.exit(1);
}

// Starting here

module.exports = function (context) {

	// This script has to be executed depending on the command line arguments, not
  	// on the hook execution cycle.
  	/*
	if (context.hook !== 'before_build' && !context.cmdLine.includes('build')) {
		return;
	}
	*/

	var
		projectRoot = context.opts.projectRoot,
		projectName = getProjectName(projectRoot),
		platformPath = path.join(projectRoot, 'platforms', 'ios'),
		platformProjectPath = path.join(platformPath, projectName),
		xcconfigPath = path.join(platformPath, '/cordova/build.xcconfig'),
		xcodeProjectName = projectName + '.xcodeproj',
		xcodeProjectConfigPath = path.join(platformPath, xcodeProjectName, 'project.pbxproj'),
		swiftBridgingHeaderPath = projectName + BRIDGING_HEADER_END,
		swiftBridgingHeaderPathXcode = '"' + swiftBridgingHeaderPath + '"',
		swiftOptions = [''], // <-- begin to file appending AFTER initial newline
		xcodeProject;

	// Showing info about the tasks to do
	debug('cordova-plugin-iosrtc is checking issues in the generated project files:');
	debug('- Minimum "iOS Deployment Target" and "Deployment Target" to: ' + IPHONEOS_DEPLOYMENT_TARGET_XCODE);
	debug('- "Runpath Search Paths" to: ' + RUNPATH_SEARCH_PATHS_XCODE);
	if (TEST_UNIFIED_BRIDGING_HEADER) {
		debug('- "Objective-C Bridging Header" to: ' + UNIFIED_BRIDGING_HEADER);
	} else {
		debug('- "Objective-C Bridging Header" to: ' + swiftBridgingHeaderPathXcode);
	}
	debug('- "ENABLE_BITCODE" set to: ' + ENABLE_BITCODE_XCODE);
	debug('- "SWIFT_VERSION" set to: ' + SWIFT_VERSION_XCODE);

	// Checking if the project files are in the right place
	if (!fs.existsSync(xcodeProjectConfigPath)) {
		debugError('an error occurred searching the project file at: "' + xcodeProjectConfigPath + '"');

		return;
	}
	debug('".pbxproj" project file found: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));

	if (!fs.existsSync(xcconfigPath)) {
		debugError('an error occurred searching the project file at: "' + xcconfigPath + '"');

		return;
	}
	debug('".xcconfig" project file found: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));

	xcodeProject = xcode.project(xcodeProjectConfigPath);

	// Massaging the files

	// "build.xcconfig"
	debug('checking file: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	var xcconfigPathChanged = false;

	// Parsing it
	var currentSwiftOptions = [];
	if (fs.existsSync(xcconfigPath)) {
		currentSwiftOptions = readFileLines(xcconfigPath);
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'LD_RUNPATH_SEARCH_PATHS', RUNPATH_SEARCH_PATHS)) {
		swiftOptions.push('LD_RUNPATH_SEARCH_PATHS = ' + RUNPATH_SEARCH_PATHS);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigMinValue(currentSwiftOptions, 'IPHONEOS_DEPLOYMENT_TARGET', IPHONEOS_DEPLOYMENT_TARGET)) {
		swiftOptions.push('IPHONEOS_DEPLOYMENT_TARGET = ' + IPHONEOS_DEPLOYMENT_TARGET);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'ENABLE_BITCODE', ENABLE_BITCODE)) {
		swiftOptions.push('ENABLE_BITCODE = ' + ENABLE_BITCODE);
		xcconfigPathChanged = true;
	}

	if (!matchXcconfigPathValue(currentSwiftOptions, 'SWIFT_VERSION', SWIFT_VERSION)) {
		swiftOptions.push('SWIFT_VERSION = ' + SWIFT_VERSION);
		xcconfigPathChanged = true;
	}

	var existingSwiftBridgingHeaderPath;
	if (TEST_UNIFIED_BRIDGING_HEADER) {
		existingSwiftBridgingHeaderPath = path.join(platformProjectPath, UNIFIED_BRIDGING_HEADER);
	} else {
		if (!matchXcconfigPathValue(currentSwiftOptions, 'SWIFT_OBJC_BRIDGING_HEADER', swiftBridgingHeaderPath)) {
			var currentSwiftBridgingHeader = getXcconfigPathValue(currentSwiftOptions, 'SWIFT_OBJC_BRIDGING_HEADER').replace('$(PROJECT_DIR)/$(PROJECT_NAME)/', '');
			if (!existingSwiftBridgingHeaderPath) {
				swiftOptions.push('SWIFT_OBJC_BRIDGING_HEADER = ' + swiftBridgingHeaderPath);
				xcconfigPathChanged = true;
			} else {
				existingSwiftBridgingHeaderPath = path.join(platformProjectPath, currentSwiftBridgingHeader);
			}
		}
	}

	// NOTE: Not needed
	// swiftOptions.push('EMBEDDED_CONTENT_CONTAINS_SWIFT = YES');

	if (xcconfigPathChanged) {
		fs.appendFileSync(xcconfigPath, swiftOptions.join('\n'));
		debug('file correctly fixed: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	} else {
		debug('file is correct: ' + getRelativeToProjectRootPath(xcconfigPath, projectRoot));
	}

	// "project.pbxproj"
	debug('checking file: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));

	// Parsing it
	xcodeProject.parse(function (error) {

		if (error) {
			debugError('an error occurred during the parsing of the project file: ' + xcodeProjectConfigPath);

			return;
		}

		// Adding or changing the parameters only if we need
		var buildSettingsChanged = false;
		var hasSwiftBridgingHeaderPathXcodes = [];
		var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection());
		Object.keys(configurations).forEach(function (config) {
			var buildSettings = configurations[config].buildSettings;

			if (!hasBuildSettingsValue(buildSettings.LD_RUNPATH_SEARCH_PATHS, RUNPATH_SEARCH_PATHS_XCODE)) {
				buildSettings.LD_RUNPATH_SEARCH_PATHS = RUNPATH_SEARCH_PATHS_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsMinValue(buildSettings.IPHONEOS_DEPLOYMENT_TARGET, IPHONEOS_DEPLOYMENT_TARGET_XCODE)) {
				buildSettings.IPHONEOS_DEPLOYMENT_TARGET = IPHONEOS_DEPLOYMENT_TARGET_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsValue(buildSettings.ENABLE_BITCODE, ENABLE_BITCODE_XCODE)) {
				buildSettings.ENABLE_BITCODE = ENABLE_BITCODE_XCODE;
				buildSettingsChanged = true;
			}

			if (!matchBuildSettingsValue(buildSettings.SWIFT_VERSION, SWIFT_VERSION_XCODE)) {
				buildSettings.SWIFT_VERSION = SWIFT_VERSION_XCODE;
				buildSettingsChanged = true;
			}

			if (TEST_UNIFIED_BRIDGING_HEADER) {
				buildSettings.SWIFT_OBJC_BRIDGING_HEADER = '"' + UNIFIED_BRIDGING_HEADER + '"';
				xcodeProject.addHeaderFile(UNIFIED_BRIDGING_HEADER);
			}

			if (!hasBuildSettingsValue(buildSettings.SWIFT_OBJC_BRIDGING_HEADER, swiftBridgingHeaderPathXcode)) {

				// Play nice with existing Swift Bridging Header value
				if (existingSwiftBridgingHeaderPath) {

					// Sync SWIFT_OBJC_BRIDGING_HEADER with existingSwiftBridgingHeaderPath if do not match
					var existingSwiftBridgingHeaderPathXcode = '"' + existingSwiftBridgingHeaderPath + '"';
					if (buildSettings.SWIFT_OBJC_BRIDGING_HEADER !== existingSwiftBridgingHeaderPathXcode) {
						buildSettings.SWIFT_OBJC_BRIDGING_HEADER = existingSwiftBridgingHeaderPathXcode;
						buildSettingsChanged = true;
					}

					if (hasSwiftBridgingHeaderPathXcodes.indexOf(existingSwiftBridgingHeaderPath) === -1) {

						// Check if existing existingSwiftBridgingHeaderPath exists and get file lines

						debug('checking file: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));

						var existingSwiftBridgingHeaderFileLines = [];
						if (fs.existsSync(existingSwiftBridgingHeaderPath)) {
							existingSwiftBridgingHeaderFileLines = readFileLines(existingSwiftBridgingHeaderPath);
						}

						// Check if existing existingSwiftBridgingHeaderFileLines contains swiftBridgingHeaderPath
						var swiftBridgingHeaderImport = '#import "' + IOSRTC_BRIDGING_HEADER + '"';
						var hasSwiftBridgingHeaderPathXcode = existingSwiftBridgingHeaderFileLines.filter(function (line) {
							return line === swiftBridgingHeaderImport;
						}).length > 0;

						if (!hasSwiftBridgingHeaderPathXcode) {
							debug('updating existing swift bridging header file: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
							existingSwiftBridgingHeaderFileLines.push(swiftBridgingHeaderImport);
							fs.writeFileSync(existingSwiftBridgingHeaderPath, existingSwiftBridgingHeaderFileLines.join('\n'), 'utf-8');
							debug('file correctly fixed: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
						} else {
							debug('file is correct: ' + getRelativeToProjectRootPath(existingSwiftBridgingHeaderPath, projectRoot));
						}

						hasSwiftBridgingHeaderPathXcodes.push(existingSwiftBridgingHeaderPath);
					}

				} else {
					buildSettings.SWIFT_OBJC_BRIDGING_HEADER = swiftBridgingHeaderPathXcode;
					buildSettingsChanged = true;
				}
			}
		});

		// Writing the file only if changed
		if (buildSettingsChanged) {
			fs.writeFileSync(xcodeProjectConfigPath, xcodeProject.writeSync(), 'utf-8');
			debug('file correctly fixed: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));
		} else {
			debug('file is correct: ' + getRelativeToProjectRootPath(xcodeProjectConfigPath, projectRoot));
		}
	});
};
<|endoftext|>