<commit_before>import {WebGLRenderer} from "three";

/**
 * AR class handles all the agumented reality related tasks.
 *
 * Can be used to detect if the host system is capable of displaying AR content and checks for the availability of WebXR with the required modes.
 *
 * @class ARHandler
 */
function ARHandler(){}

/**
 * Flag checking if there is support for XR immersive AR mode.
 *
 * @attribute webXRSupported
 * @type {boolean}
 */
ARHandler.webXRAvailable = false;

/**
 * WebXR session if there is one active.
 *
 * @attribute webXRSession
 * @type {XRSession}
 */
ARHandler.webXRSession = null;

/**
 * Check if there is any AR API available, on the device.
 *
 * Checks if there is support for WebAR or WebXR.
 *
 * @method arAvailable
 * @return {boolean} True if the browser supports AR.
 */
ARHandler.arAvailable = function()
{
	return ARHandler.webXRAvailable;
};

/**
 * Enter virtual reality mode using WebXR or WebAR depending on the API available.
 *
 * If booth API are available the WebXR API is used.
 *
 * When displaying AR content the display.requestAnimationFrame should be used to call the render method.
 *
 * @method enterAR
 * @param {WebGLRenderer} renderer Renderer used to draw the scene.
 * @param {Function} onSuccess Method called if the application entered AR successfully.
 */
ARHandler.enterAR = function(renderer, onSuccess)
{
	if(ARHandler.webXRAvailable)
	{
		ARHandler.getWebXRSession().then(function(session)
		{
			renderer.xr.enabled = true;
			renderer.xr.setReferenceSpaceType("local");
			renderer.xr.setSession(session);

			ARHandler.webXRSession = session;

			if(onSuccess !== undefined)
			{
				onSuccess();
			}
		});
	}
	else
	{
		console.warn("nunuStudio: AR support is not available.");
	}
};

/**
 * Enter virtual reality mode, if the application is not running on AR mode does not do anything.
 *
 * @method exitAR
 * @param {WebGLRenderer} renderer Renderer used to draw the scene.
 */
ARHandler.exitAR = function(renderer)
{
	if(ARHandler.webXRAvailable && ARHandler.webXRSession !== null)
	{
		renderer.xr.enabled = false;
		renderer.xr.setSession(null);

		ARHandler.webXRSession.end();
		ARHandler.webXRSession = null;
	}
};

/**
 * Get WebXR session.
 *
 * @method getXRSession
 * @return {Promise} Promise used to get the XR session, receives the session as argument.
 */
ARHandler.getWebXRSession = function()
{
	if(!ARHandler.webXRAvailable)
	{
		return Promise.reject("WebXR support is not available.");
	}

	return navigator.xr.requestSession("immersive-ar", {});
};

// Look into WebXR support with AR extensions (chrome, edge, ...)
if(navigator.xr !== undefined && navigator.xr.isSessionSupported !== undefined)
{
	navigator.xr.isSessionSupported("immersive-ar").then(function(supported)
	{
		ARHandler.webXRAvailable = true; // supported;
	});
}

export {ARHandler};<commit_msg>Fix flag<commit_after>import {WebGLRenderer} from "three";

/**
 * AR class handles all the agumented reality related tasks.
 *
 * Can be used to detect if the host system is capable of displaying AR content and checks for the availability of WebXR with the required modes.
 *
 * @class ARHandler
 */
function ARHandler(){}

/**
 * Flag checking if there is support for XR immersive AR mode.
 *
 * @attribute webXRSupported
 * @type {boolean}
 */
ARHandler.webXRAvailable = false;

/**
 * WebXR session if there is one active.
 *
 * @attribute webXRSession
 * @type {XRSession}
 */
ARHandler.webXRSession = null;

/**
 * Check if there is any AR API available, on the device.
 *
 * Checks if there is support for WebAR or WebXR.
 *
 * @method arAvailable
 * @return {boolean} True if the browser supports AR.
 */
ARHandler.arAvailable = function()
{
	return ARHandler.webXRAvailable;
};

/**
 * Enter virtual reality mode using WebXR or WebAR depending on the API available.
 *
 * If booth API are available the WebXR API is used.
 *
 * When displaying AR content the display.requestAnimationFrame should be used to call the render method.
 *
 * @method enterAR
 * @param {WebGLRenderer} renderer Renderer used to draw the scene.
 * @param {Function} onSuccess Method called if the application entered AR successfully.
 */
ARHandler.enterAR = function(renderer, onSuccess)
{
	if(ARHandler.webXRAvailable)
	{
		ARHandler.getWebXRSession().then(function(session)
		{
			renderer.xr.enabled = true;
			renderer.xr.setReferenceSpaceType("local");
			renderer.xr.setSession(session);

			ARHandler.webXRSession = session;

			if(onSuccess !== undefined)
			{
				onSuccess();
			}
		});
	}
	else
	{
		console.warn("nunuStudio: AR support is not available.");
	}
};

/**
 * Enter virtual reality mode, if the application is not running on AR mode does not do anything.
 *
 * @method exitAR
 * @param {WebGLRenderer} renderer Renderer used to draw the scene.
 */
ARHandler.exitAR = function(renderer)
{
	if(ARHandler.webXRAvailable && ARHandler.webXRSession !== null)
	{
		renderer.xr.enabled = false;
		renderer.xr.setSession(null);

		ARHandler.webXRSession.end();
		ARHandler.webXRSession = null;
	}
};

/**
 * Get WebXR session.
 *
 * @method getXRSession
 * @return {Promise} Promise used to get the XR session, receives the session as argument.
 */
ARHandler.getWebXRSession = function()
{
	if(!ARHandler.webXRAvailable)
	{
		return Promise.reject("WebXR support is not available.");
	}

	return navigator.xr.requestSession("immersive-ar", {});
};

// Look into WebXR support with AR extensions (chrome, edge, ...)
if(navigator.xr !== undefined && navigator.xr.isSessionSupported !== undefined)
{
	navigator.xr.isSessionSupported("immersive-ar").then(function(supported)
	{
		ARHandler.webXRAvailable = supported;
	});
}

export {ARHandler};<|endoftext|>


<commit_before>const temp = require('temp').track()
const StyleManager = require('../src/style-manager')

describe('StyleManager', () => {
  let [styleManager, addEvents, removeEvents, updateEvents] = []

  beforeEach(() => {
    styleManager = new StyleManager({configDirPath: temp.mkdirSync('atom-config')})
    addEvents = []
    removeEvents = []
    updateEvents = []
    styleManager.onDidAddStyleElement((event) => { addEvents.push(event) })
    styleManager.onDidRemoveStyleElement((event) => { removeEvents.push(event) })
    styleManager.onDidUpdateStyleElement((event) => { updateEvents.push(event) })
  })

  afterEach(() => {
    try {
      temp.cleanupSync()
    } catch (e) {
      // Do nothing
    }
  })

  describe('::addStyleSheet(source, params)', () => {
    it('adds a style sheet based on the given source and returns a disposable allowing it to be removed', () => {
      const disposable = styleManager.addStyleSheet('a {color: red}')
      expect(addEvents.length).toBe(1)
      expect(addEvents[0].textContent).toBe('a {color: red}')
      const styleElements = styleManager.getStyleElements()
      expect(styleElements.length).toBe(1)
      expect(styleElements[0].textContent).toBe('a {color: red}')
      disposable.dispose()
      expect(removeEvents.length).toBe(1)
      expect(removeEvents[0].textContent).toBe('a {color: red}')
      expect(styleManager.getStyleElements().length).toBe(0)
    })

    describe('atom-text-editor shadow DOM selectors upgrades', () => {
      beforeEach(() => {
        // attach styles element to the DOM to parse CSS rules
        styleManager.onDidAddStyleElement((styleElement) => { jasmine.attachToDOM(styleElement) })
      })

      it('removes the ::shadow pseudo-element from atom-text-editor selectors', () => {
        styleManager.addStyleSheet(`
          atom-text-editor::shadow .class-1, atom-text-editor::shadow .class-2 { color: red }
          atom-text-editor::shadow > .class-3 { color: yellow }
          atom-text-editor .class-4 { color: blue }
          another-element::shadow .class-5 { color: white }
          atom-text-editor[data-grammar*=\"js\"]::shadow .class-6 { color: green; }
          atom-text-editor[mini].is-focused::shadow .class-7 { color: green; }
        `)
        expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          'atom-text-editor.editor .class-1, atom-text-editor.editor .class-2',
          'atom-text-editor.editor > .class-3',
          'atom-text-editor .class-4',
          'another-element::shadow .class-5',
          'atom-text-editor[data-grammar*=\"js\"].editor .class-6',
          'atom-text-editor[mini].is-focused.editor .class-7'
        ])
      })

      describe('when a selector targets the atom-text-editor shadow DOM', () => {
        it('prepends "--syntax" to class selectors matching a grammar scope name and not already starting with "syntax--"', () => {
          styleManager.addStyleSheet(`
            .class-1 { color: red }
            .source > .js, .source.coffee { color: green }
            .syntax--source { color: gray }
            #id-1 { color: blue }
          `, {context: 'atom-text-editor'})
          expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
            '.class-1',
            '.syntax--source > .syntax--js, .syntax--source.syntax--coffee',
            '.syntax--source',
            '#id-1'
          ])

          styleManager.addStyleSheet(`
            .source > .js, .source.coffee { color: green }
            atom-text-editor::shadow .source > .js { color: yellow }
            atom-text-editor[mini].is-focused::shadow .source > .js { color: gray }
            atom-text-editor .source > .js { color: red }
          `)
          expect(Array.from(styleManager.getStyleElements()[1].sheet.cssRules).map((r) => r.selectorText)).toEqual([
            '.source > .js, .source.coffee',
            'atom-text-editor.editor .syntax--source > .syntax--js',
            'atom-text-editor[mini].is-focused.editor .syntax--source > .syntax--js',
            'atom-text-editor .source > .js'
          ])
        })
      })

      it('replaces ":host" with "atom-text-editor" only when the context of a style sheet is "atom-text-editor"', () => {
        styleManager.addStyleSheet(':host .class-1, :host .class-2 { color: red; }')
        expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          ':host .class-1, :host .class-2'
        ])
        styleManager.addStyleSheet(':host .class-1, :host .class-2 { color: red; }', {context: 'atom-text-editor'})
        expect(Array.from(styleManager.getStyleElements()[1].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          'atom-text-editor .class-1, atom-text-editor .class-2'
        ])
      })

      it('does not transform CSS rules with invalid syntax', () => {
        styleManager.addStyleSheet("atom-text-editor::shadow .class-1 { font-family: inval'id }")
        expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          'atom-text-editor::shadow .class-1'
        ])
      })

      it('does not throw exceptions on rules with no selectors', () => {
        styleManager.addStyleSheet('@media screen {font-size: 10px}', {context: 'atom-text-editor'})
      })
    })

    describe('when a sourcePath parameter is specified', () => {
      it('ensures a maximum of one style element for the given source path, updating a previous if it exists', () => {
        const disposable1 = styleManager.addStyleSheet('a {color: red}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(addEvents[0].getAttribute('source-path')).toBe('/foo/bar')

        const disposable2 = styleManager.addStyleSheet('a {color: blue}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(updateEvents.length).toBe(1)
        expect(updateEvents[0].getAttribute('source-path')).toBe('/foo/bar')
        expect(updateEvents[0].textContent).toBe('a {color: blue}')
        disposable2.dispose()

        addEvents = []
        styleManager.addStyleSheet('a {color: yellow}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(addEvents[0].getAttribute('source-path')).toBe('/foo/bar')
        expect(addEvents[0].textContent).toBe('a {color: yellow}')
      })
    })

    describe('when a priority parameter is specified', () => {
      it('inserts the style sheet based on the priority', () => {
        styleManager.addStyleSheet('a {color: red}', {priority: 1})
        styleManager.addStyleSheet('a {color: blue}', {priority: 0})
        styleManager.addStyleSheet('a {color: green}', {priority: 2})
        styleManager.addStyleSheet('a {color: yellow}', {priority: 1})
        expect(styleManager.getStyleElements().map((elt) => elt.textContent)).toEqual([
          'a {color: blue}',
          'a {color: red}',
          'a {color: yellow}',
          'a {color: green}'
        ])
      })
    })
  })
})
<commit_msg>Update StyleManager specs to address deprecated ::shadow selectors<commit_after>const temp = require('temp').track()
const StyleManager = require('../src/style-manager')

describe('StyleManager', () => {
  let [styleManager, addEvents, removeEvents, updateEvents] = []

  beforeEach(() => {
    styleManager = new StyleManager({configDirPath: temp.mkdirSync('atom-config')})
    addEvents = []
    removeEvents = []
    updateEvents = []
    styleManager.onDidAddStyleElement((event) => { addEvents.push(event) })
    styleManager.onDidRemoveStyleElement((event) => { removeEvents.push(event) })
    styleManager.onDidUpdateStyleElement((event) => { updateEvents.push(event) })
  })

  afterEach(() => {
    try {
      temp.cleanupSync()
    } catch (e) {
      // Do nothing
    }
  })

  describe('::addStyleSheet(source, params)', () => {
    it('adds a style sheet based on the given source and returns a disposable allowing it to be removed', () => {
      const disposable = styleManager.addStyleSheet('a {color: red}')
      expect(addEvents.length).toBe(1)
      expect(addEvents[0].textContent).toBe('a {color: red}')
      const styleElements = styleManager.getStyleElements()
      expect(styleElements.length).toBe(1)
      expect(styleElements[0].textContent).toBe('a {color: red}')
      disposable.dispose()
      expect(removeEvents.length).toBe(1)
      expect(removeEvents[0].textContent).toBe('a {color: red}')
      expect(styleManager.getStyleElements().length).toBe(0)
    })

    describe('atom-text-editor shadow DOM selectors upgrades', () => {
      beforeEach(() => {
        // attach styles element to the DOM to parse CSS rules
        styleManager.onDidAddStyleElement((styleElement) => { jasmine.attachToDOM(styleElement) })
      })

      it('removes the ::shadow pseudo-element from atom-text-editor selectors', () => {
        styleManager.addStyleSheet(`
          atom-text-editor::shadow .class-1, atom-text-editor::shadow .class-2 { color: red }
          atom-text-editor::shadow > .class-3 { color: yellow }
          atom-text-editor .class-4 { color: blue }
          atom-text-editor[data-grammar*=\"js\"]::shadow .class-6 { color: green; }
          atom-text-editor[mini].is-focused::shadow .class-7 { color: green; }
        `)
        expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          'atom-text-editor.editor .class-1, atom-text-editor.editor .class-2',
          'atom-text-editor.editor > .class-3',
          'atom-text-editor .class-4',
          'atom-text-editor[data-grammar*=\"js\"].editor .class-6',
          'atom-text-editor[mini].is-focused.editor .class-7'
        ])
      })

      describe('when a selector targets the atom-text-editor shadow DOM', () => {
        it('prepends "--syntax" to class selectors matching a grammar scope name and not already starting with "syntax--"', () => {
          styleManager.addStyleSheet(`
            .class-1 { color: red }
            .source > .js, .source.coffee { color: green }
            .syntax--source { color: gray }
            #id-1 { color: blue }
          `, {context: 'atom-text-editor'})
          expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
            '.class-1',
            '.syntax--source > .syntax--js, .syntax--source.syntax--coffee',
            '.syntax--source',
            '#id-1'
          ])

          styleManager.addStyleSheet(`
            .source > .js, .source.coffee { color: green }
            atom-text-editor::shadow .source > .js { color: yellow }
            atom-text-editor[mini].is-focused::shadow .source > .js { color: gray }
            atom-text-editor .source > .js { color: red }
          `)
          expect(Array.from(styleManager.getStyleElements()[1].sheet.cssRules).map((r) => r.selectorText)).toEqual([
            '.source > .js, .source.coffee',
            'atom-text-editor.editor .syntax--source > .syntax--js',
            'atom-text-editor[mini].is-focused.editor .syntax--source > .syntax--js',
            'atom-text-editor .source > .js'
          ])
        })
      })

      it('replaces ":host" with "atom-text-editor" only when the context of a style sheet is "atom-text-editor"', () => {
        styleManager.addStyleSheet(':host .class-1, :host .class-2 { color: red; }')
        expect(Array.from(styleManager.getStyleElements()[0].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          ':host .class-1, :host .class-2'
        ])
        styleManager.addStyleSheet(':host .class-1, :host .class-2 { color: red; }', {context: 'atom-text-editor'})
        expect(Array.from(styleManager.getStyleElements()[1].sheet.cssRules).map((r) => r.selectorText)).toEqual([
          'atom-text-editor .class-1, atom-text-editor .class-2'
        ])
      })

      it('does not throw exceptions on rules with no selectors', () => {
        styleManager.addStyleSheet('@media screen {font-size: 10px}', {context: 'atom-text-editor'})
      })
    })

    describe('when a sourcePath parameter is specified', () => {
      it('ensures a maximum of one style element for the given source path, updating a previous if it exists', () => {
        const disposable1 = styleManager.addStyleSheet('a {color: red}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(addEvents[0].getAttribute('source-path')).toBe('/foo/bar')

        const disposable2 = styleManager.addStyleSheet('a {color: blue}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(updateEvents.length).toBe(1)
        expect(updateEvents[0].getAttribute('source-path')).toBe('/foo/bar')
        expect(updateEvents[0].textContent).toBe('a {color: blue}')
        disposable2.dispose()

        addEvents = []
        styleManager.addStyleSheet('a {color: yellow}', {sourcePath: '/foo/bar'})
        expect(addEvents.length).toBe(1)
        expect(addEvents[0].getAttribute('source-path')).toBe('/foo/bar')
        expect(addEvents[0].textContent).toBe('a {color: yellow}')
      })
    })

    describe('when a priority parameter is specified', () => {
      it('inserts the style sheet based on the priority', () => {
        styleManager.addStyleSheet('a {color: red}', {priority: 1})
        styleManager.addStyleSheet('a {color: blue}', {priority: 0})
        styleManager.addStyleSheet('a {color: green}', {priority: 2})
        styleManager.addStyleSheet('a {color: yellow}', {priority: 1})
        expect(styleManager.getStyleElements().map((elt) => elt.textContent)).toEqual([
          'a {color: blue}',
          'a {color: red}',
          'a {color: yellow}',
          'a {color: green}'
        ])
      })
    })
  })
})
<|endoftext|>


<commit_before>/*
    FILE STRUCTURE ------------------------------------------------------------
    assets
    -- distribution
    ---- images
    ---- markup
    ---- scripts
    ---- styles
    -- source
    ---- images
    ---- markup
    ---- scripts
    ---- styles
    -- controllers
    ---- node_modules
*/

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cleancss = require('gulp-clean-css'),
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    kit = require('gulp-kit'),
    plumber = require('gulp-plumber'),
    del = require('del');

var distribution = {
        destination: "../assets/distribution/"
    },
    styles = {
        destination: "../assets/distribution/styles/",
        source: "../assets/source/styles/**/*.scss",
        output: "min.css"
    },
    scripts = {
        destination: "../assets/distribution/scripts/",
        source: "../assets/source/scripts/**/*.js",
        output: "min.js"
    },
    markup = {
        destination: "../assets/distribution/markup/",
        source: "../assets/source/markup/**/*.kit"
    },
    index = {
        destination: "../../assets/",
        source: "../../assets/source/markup/index.kit"
    },
    images = {
        destination: "../assets/distribution/images/",
        source: "../assets/source/images/**/*"
    };

gulp.task('scripts', function () {
    return gulp.src(scripts.source)
        .pipe(plumber())
        .pipe(concat(scripts.output))
        .pipe(uglify())
        .pipe(gulp.dest(scripts.destination));
});

gulp.task('styles', function () {
    return gulp.src(styles.source)
        .pipe(plumber())
        .pipe(sass.sync())
        .pipe(autoprefixer())
        // .pipe(cleancss())
        .pipe(concat(styles.output))
        .pipe(gulp.dest(styles.destination));
});

gulp.task('markup', function() {
    return gulp.src(markup.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(markup.destination));
});

gulp.task('index', function() {
    return gulp.src(index.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(index.destination));
});

gulp.task('images', function() {
    return gulp.src(images.source)
        .pipe(imagemin())
        .pipe(gulp.dest(images.destination));
});

gulp.task('clean', function() {
    console.log('deleting distribution folder');
    return del(gulp.dest(distribution.destination));
});

gulp.task('watch', function () {
    gulp.watch(scripts.source, ['scripts']);
    gulp.watch(styles.source, ['styles']);
    gulp.watch(markup.source, ['markup']);
    gulp.watch(index.source, ['index']);
});

gulp.task('default', ['watch']);
<commit_msg>Update gulpfile.js<commit_after>/*
    FILE STRUCTURE ------------------------------------------------------------
    assets
    -- distribution
    ---- images
    ---- markup
    ---- scripts
    ---- styles
    -- source
    ---- images
    ---- markup
    ---- scripts
    ---- styles
    -- controllers
    ---- node_modules
*/

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cleancss = require('gulp-clean-css'),
    autoprefixer = require('gulp-autoprefixer'),
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    kit = require('gulp-kit'),
    plumber = require('gulp-plumber'),
    del = require('del');

var distribution = {
        destination: "../assets/distribution/";
    },
    styles = {
        destination: "../assets/distribution/styles/",
        source: "../assets/source/styles/**/*.scss",
        output: "min.css";
    },
    scripts = {
        destination: "../assets/distribution/scripts/",
        source: "../assets/source/scripts/**/*.js",
        output: "min.js";
    },
    markup = {
        destination: "../assets/distribution/markup/",
        source: "../assets/source/markup/**/*.kit";
    },
    index = {
        destination: "../../assets/",
        source: "../../assets/source/markup/index.kit";
    },
    images = {
        destination: "../assets/distribution/images/",
        source: "../assets/source/images/**/*";
    };

gulp.task('scripts', function () {
    return gulp.src(scripts.source)
        .pipe(plumber())
        .pipe(concat(scripts.output))
        .pipe(uglify())
        .pipe(gulp.dest(scripts.destination));
});

gulp.task('styles', function () {
    return gulp.src(styles.source)
        .pipe(plumber())
        .pipe(sass.sync())
        .pipe(autoprefixer())
        // .pipe(cleancss())
        .pipe(concat(styles.output))
        .pipe(gulp.dest(styles.destination));
});

gulp.task('markup', function() {
    return gulp.src(markup.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(markup.destination));
});

gulp.task('index', function() {
    return gulp.src(index.source)
        .pipe(plumber())
        .pipe(kit())
        .pipe(gulp.dest(index.destination));
});

gulp.task('images', function() {
    return gulp.src(images.source)
        .pipe(imagemin())
        .pipe(gulp.dest(images.destination));
});

gulp.task('clean', function() {
    console.log('deleting distribution folder');
    return del(gulp.dest(distribution.destination));
});

gulp.task('watch', function () {
    gulp.watch(scripts.source, ['scripts']);
    gulp.watch(styles.source, ['styles']);
    gulp.watch(markup.source, ['markup']);
    gulp.watch(index.source, ['index']);
});

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>'use strict';

var Colors = require('../colors');
var ColorManipulator = require('../../utils/color-manipulator');
var Spacing = require('../spacing');

/*
 *  Light Theme is the default theme used in material-ui. It is guaranteed to
 *  have all theme variables needed for every component. Variables not defined
 *  in a custom theme will default to these values.
 */

module.exports = {
  spacing: Spacing,
  fontFamily: 'Roboto, sans-serif',
  palette: {
    primary1Color: Colors.cyan500,
    primary2Color: Colors.cyan700,
    primary3Color: Colors.grey400,
    accent1Color: Colors.pinkA200,
    accent2Color: Colors.grey100,
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
    disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3)
  }
};<commit_msg>MUI changes<commit_after>'use strict';

var Colors = require('../colors');
var ColorManipulator = require('../../utils/color-manipulator');
var Spacing = require('../spacing');

/*
 *  Light Theme is the default theme used in material-ui. It is guaranteed to
 *  have all theme variables needed for every component. Variables not defined
 *  in a custom theme will default to these values.
 */

module.exports = {
  spacing: Spacing,
  fontFamily: 'Roboto, sans-serif',
  palette: {
    primary1Color: Colors.lightBlue900,
    primary2Color: Colors.lightBlue700,
    primary3Color: Colors.grey400,
    accent1Color: Colors.lightBlue100,
    accent2Color: Colors.grey100,
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
  }
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 "Fronteer LTD"
 * Grasshopper Event Engine
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var _ = require('lodash');
var assert = require('assert');

var AuthTestsUtil = require('gh-auth/tests/util');
var TestsUtil = require('gh-tests/lib/util');

var AdminsTestsUtil = require('./util');

var anonymousGlobalAdminClient = null;
var globalAdminClient = null;

beforeEach(function(callback) {
    // Get the anonymous and authenticated global admin clients
    TestsUtil.getAnonymousGlobalAdminRestClient(function(_anonymousGlobalAdminClient) {
        anonymousGlobalAdminClient = _anonymousGlobalAdminClient;
        TestsUtil.getGlobalAdminRestClient(function(_globalAdminClient) {
            globalAdminClient = _globalAdminClient;
            return callback();
        });
    });
});

describe('Admins', function() {

    describe('Get Global Admins', function() {

        it('verify a list of global admins can be fetched', function(callback) {
            // Ensure we have more than 1 global admin to test with
            AdminsTestsUtil.assertGetMe(globalAdminClient, function(globalAdmin) {
                var username = TestsUtil.generateTestUserId();
                AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {
                    // Get all global admins in pages, ensuring each page contains just 1 global
                    // admin, including the initial one and the created one
                    AdminsTestsUtil.assertGetAllGlobalAdmins(globalAdminClient, {'batchSize': 1}, function(allGlobalAdmins, responses) {
                        assert.ok(responses.length > 1);

                        // When fetching with size 1, we'll always have one extra request for the
                        // empty response. So subtract `responses.length` by 1 for the assertion
                        assert.strictEqual(allGlobalAdmins.length, responses.length - 1);
                        AdminsTestsUtil.assertGlobalAdmin(_.findWhere(allGlobalAdmins, {'id': globalAdmin.id}), {'exists': true});
                        AdminsTestsUtil.assertGlobalAdmin(_.findWhere(allGlobalAdmins, {'id': createdGlobalAdmin.id}), {'exists': true});
                        return callback();
                    });
                });
            });
        });

        it('verify authorization of getting a list of global admins', function(callback) {
            // Ensure anonymous user cannot get global admin list
            return AdminsTestsUtil.assertGetGlobalAdminsFails(anonymousGlobalAdminClient, null, 401, callback);
        });
    });

    describe('Me', function() {

        it('verify the "me" feed will be anonymous for anonymous users', function(callback) {
            TestsUtil.getAnonymousGlobalAdminRestClient(function(anonymousGlobalAdminClient) {
                AdminsTestsUtil.assertGetMe(anonymousGlobalAdminClient, function(me) {
                    AdminsTestsUtil.assertMe(me, {'authenticated': false});
                    return callback();
                });
            });
        });

        it('verify the "me" feed will specify the expected admins profile information', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure the Me feed indicates the admin is logged in
                AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                    AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});
                    return callback();
                });
            });
        });
    });

    describe('Create', function() {

        it('verify validation of creating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();

            // Ensure parameter validation
            AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, '', username, username, 400, function() {
                AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, '', username, 400, function() {
                    AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, username, '', 400, function() {

                        // Sanity check creation succeeds
                        AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                            // Ensure we cannot create an admin with the same username
                            return AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, username, username, 400, callback);
                        });
                    });
                });
            });
        });

        it('verify authorization of creating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            TestsUtil.getAnonymousGlobalAdminRestClient(function(anonymousGlobalAdminClient) {

                // Ensure anonymous can't create a global admin
                AdminsTestsUtil.assertCreateGlobalAdminFails(anonymousGlobalAdminClient, username, username, username, 401, function(createdGlobalAdmin) {

                    // Sanity check global admin can create one
                    AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {
                        return callback();
                    });
                });
            });
        });
    });

    describe('Update', function() {

        it('verify updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure a global admin can update their own properties, as well as another
                AdminsTestsUtil.assertUpdateGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                    AdminsTestsUtil.assertUpdateGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, username, function() {
                        return callback();
                    });
                });
            });
        });

        it('verify validation of updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure valid global admin id
                AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, '', 'display name', 400, function() {
                    AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, 'not an id', 'display name', 400, function() {

                        // Ensure valid display name
                        AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, createdGlobalAdmin.id, '', 400, function() {

                            // Ensure the display name hasn't changed
                            AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                                AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});

                                // Sanity check we can udpate the display name
                                AdminsTestsUtil.assertUpdateGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                                    return callback();
                                });
                            });
                        });
                    });
                });
            });
        });

        it('verify authorization of updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure anonymous user can't update a global admin
                TestsUtil.getAnonymousGlobalAdminRestClient(function(anonymousGlobalAdminClient) {
                    AdminsTestsUtil.assertUpdateGlobalAdminFails(anonymousGlobalAdminClient, createdGlobalAdmin.id, 'display name', 401, function() {

                        // Ensure the created global admin hasn't changed
                        AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                            AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});

                            // Sanity check we can update the created global admin
                            AdminsTestsUtil.assertUpdateGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                                return callback();
                            });
                        });
                    });
                });
            });
        });
    });

    describe('Delete', function() {

        /**
         * Test that verifies a global admin can delete another global admin
         */
        it('verify a global admin can delete another global admin', function(callback) {
            // Create a global admin user that we can delete
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                // Delete the global admin, ensuring they no longer exist
                return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
            });
        });

        /**
         * Test that verifies a global admin can delete their own user account
         */
        it('verify a global admin can delete their own user account', function(callback) {
            // Create a global admin to try and delete
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {
                return AdminsTestsUtil.assertDeleteGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, callback);
            });
        });

        /**
         * Test that verifies the last global admin cannot be deleted
         */
        it('verify we cannot be left with no global admins', function(callback) {
            // Get the main global admin to try and delete
            AdminsTestsUtil.assertGetMe(globalAdminClient, function(globalAdminMe) {

                // Compile a list of all global admin ids except for the main one
                AdminsTestsUtil.assertGetAllGlobalAdmins(globalAdminClient, null, function(globalAdmins) {

                    // Delete all global admins except for the main one
                    var globalAdminIds = _.chain(globalAdmins)
                        .pluck('id')
                        .without(globalAdminMe.id)
                        .value();
                    AdminsTestsUtil.assertDeleteGlobalAdmins(globalAdminClient, globalAdminIds, function() {

                        // Ensure that the global admin now trying to delete themself (the only
                        // remaining global admin) fails
                        return AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, globalAdminMe.id, 400, callback);
                    });
                });
            });
        });

        /**
         * Test that verifies validation of the delete global admin parameters
         */
        it('verify validation of deleting a global admin', function(callback) {
            // Create a global administrator to sanity check deletes with
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, 'not an id', 400, function() {
                    AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, '-1', 404, function() {

                        // Sanity check we can delete a global admin
                        return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
                    });
                });
            });
        });

        it('verify authorization of deleting a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                // Ensure anonymous cannot delete a global admin
                TestsUtil.getAnonymousGlobalAdminRestClient(function(anonymousGlobalAdminClient) {
                    AdminsTestsUtil.assertDeleteGlobalAdminFails(anonymousGlobalAdminClient, createdGlobalAdmin.id, 401, function() {

                        // Sanity check we can delete the global admin
                        return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
                    });
                });
            });
        });
    });
});
<commit_msg>(Issue 91) Remove unnecessary uses of getAnonymousGlobalAdminClient()<commit_after>/**
 * Copyright (c) 2015 "Fronteer LTD"
 * Grasshopper Event Engine
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var _ = require('lodash');
var assert = require('assert');

var AuthTestsUtil = require('gh-auth/tests/util');
var TestsUtil = require('gh-tests/lib/util');

var AdminsTestsUtil = require('./util');

var anonymousGlobalAdminClient = null;
var globalAdminClient = null;

beforeEach(function(callback) {
    // Get the anonymous and authenticated global admin clients
    TestsUtil.getAnonymousGlobalAdminRestClient(function(_anonymousGlobalAdminClient) {
        anonymousGlobalAdminClient = _anonymousGlobalAdminClient;
        TestsUtil.getGlobalAdminRestClient(function(_globalAdminClient) {
            globalAdminClient = _globalAdminClient;
            return callback();
        });
    });
});

describe('Admins', function() {

    describe('Get Global Admins', function() {

        it('verify a list of global admins can be fetched', function(callback) {
            // Ensure we have more than 1 global admin to test with
            AdminsTestsUtil.assertGetMe(globalAdminClient, function(globalAdmin) {
                var username = TestsUtil.generateTestUserId();
                AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {
                    // Get all global admins in pages, ensuring each page contains just 1 global
                    // admin, including the initial one and the created one
                    AdminsTestsUtil.assertGetAllGlobalAdmins(globalAdminClient, {'batchSize': 1}, function(allGlobalAdmins, responses) {
                        assert.ok(responses.length > 1);

                        // When fetching with size 1, we'll always have one extra request for the
                        // empty response. So subtract `responses.length` by 1 for the assertion
                        assert.strictEqual(allGlobalAdmins.length, responses.length - 1);
                        AdminsTestsUtil.assertGlobalAdmin(_.findWhere(allGlobalAdmins, {'id': globalAdmin.id}), {'exists': true});
                        AdminsTestsUtil.assertGlobalAdmin(_.findWhere(allGlobalAdmins, {'id': createdGlobalAdmin.id}), {'exists': true});
                        return callback();
                    });
                });
            });
        });

        it('verify authorization of getting a list of global admins', function(callback) {
            // Ensure anonymous user cannot get global admin list
            return AdminsTestsUtil.assertGetGlobalAdminsFails(anonymousGlobalAdminClient, null, 401, callback);
        });
    });

    describe('Me', function() {

        it('verify the "me" feed will be anonymous for anonymous users', function(callback) {
            AdminsTestsUtil.assertGetMe(anonymousGlobalAdminClient, function(me) {
                AdminsTestsUtil.assertMe(me, {'authenticated': false});
                return callback();
            });
        });

        it('verify the "me" feed will specify the expected admins profile information', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure the Me feed indicates the admin is logged in
                AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                    AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});
                    return callback();
                });
            });
        });
    });

    describe('Create', function() {

        it('verify validation of creating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();

            // Ensure parameter validation
            AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, '', username, username, 400, function() {
                AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, '', username, 400, function() {
                    AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, username, '', 400, function() {

                        // Sanity check creation succeeds
                        AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                            // Ensure we cannot create an admin with the same username
                            return AdminsTestsUtil.assertCreateGlobalAdminFails(globalAdminClient, username, username, username, 400, callback);
                        });
                    });
                });
            });
        });

        it('verify authorization of creating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();

            // Ensure anonymous can't create a global admin
            AdminsTestsUtil.assertCreateGlobalAdminFails(anonymousGlobalAdminClient, username, username, username, 401, function(createdGlobalAdmin) {

                // Sanity check global admin can create one
                AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {
                    return callback();
                });
            });
        });
    });

    describe('Update', function() {

        it('verify updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure a global admin can update their own properties, as well as another
                AdminsTestsUtil.assertUpdateGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                    AdminsTestsUtil.assertUpdateGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, username, function() {
                        return callback();
                    });
                });
            });
        });

        it('verify validation of updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure valid global admin id
                AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, '', 'display name', 400, function() {
                    AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, 'not an id', 'display name', 400, function() {

                        // Ensure valid display name
                        AdminsTestsUtil.assertUpdateGlobalAdminFails(globalAdminClient, createdGlobalAdmin.id, '', 400, function() {

                            // Ensure the display name hasn't changed
                            AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                                AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});

                                // Sanity check we can udpate the display name
                                AdminsTestsUtil.assertUpdateGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                                    return callback();
                                });
                            });
                        });
                    });
                });
            });
        });

        it('verify authorization of updating a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {

                // Ensure anonymous user can't update a global admin
                AdminsTestsUtil.assertUpdateGlobalAdminFails(anonymousGlobalAdminClient, createdGlobalAdmin.id, 'display name', 401, function() {

                    // Ensure the created global admin hasn't changed
                    AdminsTestsUtil.assertGetMe(createdGlobalAdminClient, function(me) {
                        AdminsTestsUtil.assertMe(me, {'authenticated': createdGlobalAdmin});

                        // Sanity check we can update the created global admin
                        AdminsTestsUtil.assertUpdateGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, 'display name', function() {
                            return callback();
                        });
                    });
                });
            });
        });
    });

    describe('Delete', function() {

        /**
         * Test that verifies a global admin can delete another global admin
         */
        it('verify a global admin can delete another global admin', function(callback) {
            // Create a global admin user that we can delete
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                // Delete the global admin, ensuring they no longer exist
                return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
            });
        });

        /**
         * Test that verifies a global admin can delete their own user account
         */
        it('verify a global admin can delete their own user account', function(callback) {
            // Create a global admin to try and delete
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin, createdGlobalAdminClient) {
                return AdminsTestsUtil.assertDeleteGlobalAdmin(createdGlobalAdminClient, createdGlobalAdmin.id, callback);
            });
        });

        /**
         * Test that verifies the last global admin cannot be deleted
         */
        it('verify we cannot be left with no global admins', function(callback) {
            // Get the main global admin to try and delete
            AdminsTestsUtil.assertGetMe(globalAdminClient, function(globalAdminMe) {

                // Compile a list of all global admin ids except for the main one
                AdminsTestsUtil.assertGetAllGlobalAdmins(globalAdminClient, null, function(globalAdmins) {

                    // Delete all global admins except for the main one
                    var globalAdminIds = _.chain(globalAdmins)
                        .pluck('id')
                        .without(globalAdminMe.id)
                        .value();
                    AdminsTestsUtil.assertDeleteGlobalAdmins(globalAdminClient, globalAdminIds, function() {

                        // Ensure that the global admin now trying to delete themself (the only
                        // remaining global admin) fails
                        return AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, globalAdminMe.id, 400, callback);
                    });
                });
            });
        });

        /**
         * Test that verifies validation of the delete global admin parameters
         */
        it('verify validation of deleting a global admin', function(callback) {
            // Create a global administrator to sanity check deletes with
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, 'not an id', 400, function() {
                    AdminsTestsUtil.assertDeleteGlobalAdminFails(globalAdminClient, '-1', 404, function() {

                        // Sanity check we can delete a global admin
                        return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
                    });
                });
            });
        });

        it('verify authorization of deleting a global admin', function(callback) {
            var username = TestsUtil.generateTestUserId();
            AdminsTestsUtil.assertCreateGlobalAdmin(globalAdminClient, username, username, username, function(createdGlobalAdmin) {

                // Ensure anonymous cannot delete a global admin
                AdminsTestsUtil.assertDeleteGlobalAdminFails(anonymousGlobalAdminClient, createdGlobalAdmin.id, 401, function() {

                    // Sanity check we can delete the global admin
                    return AdminsTestsUtil.assertDeleteGlobalAdmin(globalAdminClient, createdGlobalAdmin.id, callback);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>var http = require("http")
var port = parseInt(process.env.PORT, 10)
var server = http.createServer(function(req, res){
  console.log(req.url)
  switch (req.url) {
    case "/ok":
      res.statusCode = 200
      res.setHeader("Content-Type", "text/plain")
      res.end("ok")
      return
    break
    case "/fail":
      if(req.method == "POST") {
        res.statusCode = 405
        res.setHeader("Content-Type", "text/plain")
        var body = ""
        req.on("data", function(chunk){
          body += chunk
        })
        req.on("end", function(){
          res.end(body)
        })
        return
      }
      req.statusCode = 200
      res.setHeader("Content-Type", "text/plain")
      res.end("nok")
      return
    break
  }
})

server.listen(port)
console.log("listening to " + port)
<commit_msg>removed console.log in test server<commit_after>var http = require("http")
var port = parseInt(process.env.PORT, 10)
var server = http.createServer(function(req, res){
  switch (req.url) {
    case "/ok":
      res.statusCode = 200
      res.setHeader("Content-Type", "text/plain")
      res.end("ok")
      return
    break
    case "/fail":
      if(req.method == "POST") {
        res.statusCode = 405
        res.setHeader("Content-Type", "text/plain")
        var body = ""
        req.on("data", function(chunk){
          body += chunk
        })
        req.on("end", function(){
          res.end(body)
        })
        return
      }
      req.statusCode = 200
      res.setHeader("Content-Type", "text/plain")
      res.end("nok")
      return
    break
  }
})

server.listen(port)
console.log("listening to " + port)
<|endoftext|>


<commit_before>// Github.js 0.6.2
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // Util
    // =======

    function _request(method, path, data, cb, raw) {
      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json"}
      xhr.open(method, API_URL + path);
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : JSON.parse(this.responseText));
          } else {
            cb(this.status);
          }
        }
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      }

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // List all user gists
      // This will return all public gists if user is not authenticated
      // -------

      this.userGists = function(username,cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef(branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/heads/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef(branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        var data = {
          "content": content,
          "encoding": "utf-8"
        };
        _request("POST", repoPath + "/git/blobs", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, function(err, info) {
          cb(null, info);
        });
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, cb);
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.postBlob(content, function(err, blob) {
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              that.commit(latestCommit, tree, message, function(err, commit) {
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var that = this;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.show = function(cb) {
        _request("GET", gistPath, null, function(err,info) {
          cb(err,info);
        });
      };

      // Star the gist
      // --------

      this.star = function(cb) {
        _request("PUT", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      }

      // Check if the Gist is starred
      // --------

      this.isStarred = function(cb) {
        _request("GET", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      };

      // Unstar the gist
      // --------

      this.unstar = function(cb) {
        _request("DELETE", gistPath+"/star", null, function(err,res) {
          cb(err,res);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.edit = function(cb,options) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };

      // Update Gist Description
      // --------

      this.updateDescription = function(cb,description) {
        that.edit(cb,{description: description});
      };

      // Rename a file in the gist
      // --------

      this.renameFile = function(oldName, newName, cb) {
        var options = {files:{}};
        options.files[oldName] = newName;
        that.edit(cb, options);
      };

      // Delete a file in the gist
      // --------

      this.deleteFile = function(fileName, cb) {
        var options = {files:{}};
        options.files[fileName] = null;
        that.edit(cb,options);
      };

      // Update a particular file in the gist
      this.updateFile = function(filename, contents, cb) {
        var options = {files:{}};
        options.files[filename] = {content: contents};
        that.edit(cb,options);
      }
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<commit_msg>Improved Gist API.<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // Util
    // =======

    function _request(method, path, data, cb, raw) {
      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json"}
      xhr.open(method, API_URL + path);
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : JSON.parse(this.responseText));
          } else {
            cb(this.status);
          }
        }
      }
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      }

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef(branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/heads/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef(branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, function(err, info) {
          cb(null, info);
        });
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, cb);
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.postBlob(content, function(err, blob) {
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              that.commit(latestCommit, tree, message, function(err, commit) {
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var that = this;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<|endoftext|>


<commit_before>import path from 'path';
import postcss from 'postcss';
import cosmiconfig from 'cosmiconfig';
import isResolvable from 'is-resolvable';
import defaultPreset from 'lerna:cssnano-preset-default';

const cssnano = 'cssnano';

function initializePlugin (plugin, css, result) {
    if (Array.isArray(plugin)) {
        const [processor, opts] = plugin;
        if (
            typeof opts === 'undefined' ||
            (typeof opts === 'object' && !opts.exclude) ||
            (typeof opts === 'boolean' && opts === true)
        ) {
            return Promise.resolve(
                processor(opts)(css, result)
            );
        }
    } else {
        return Promise.resolve(
            plugin()(css, result)
        );
    }
    // Handle excluded plugins
    return Promise.resolve();
}

/*
 * preset can be one of four possibilities:
 * preset = 'default'
 * preset = ['default', {}]
 * preset = function <- to be invoked
 * preset = {plugins: []} <- already invoked function
 */

function resolvePreset (preset) {
    let fn, options;
    if (Array.isArray(preset)) {
        fn = preset[0];
        options = preset[1];
    } else {
        fn = preset;
        options = {};
    }
    // For JS setups where we invoked the preset already
    if (preset.plugins) {
        return Promise.resolve(preset.plugins);
    }
    // Provide an alias for the default preset, as it is built-in.
    if (fn === 'default') {
        return Promise.resolve(defaultPreset(options).plugins);
    }
    // For non-JS setups; we'll need to invoke the preset ourselves.
    if (typeof fn === 'function') {
        return Promise.resolve(fn(options).plugins);
    }
    // Try loading a preset from node_modules
    if (isResolvable(fn)) {
        return Promise.resolve(require(fn)(options).plugins);
    }
    const sugar = `cssnano-preset-${fn}`;
    // Try loading a preset from node_modules (sugar)
    if (isResolvable(sugar)) {
        return Promise.resolve(require(sugar)(options).plugins);
    }
    // If all else fails, we probably have a typo in the config somewhere
    throw new Error(`Cannot load preset "${fn}". Please check your configuration for errors and try again.`);
}

/*
 * cssnano will look for configuration firstly as options passed
 * directly to it, and failing this it will use cosmiconfig to
 * load an external file.
 */

function resolveConfig (css, result, options) {
    if (options.preset) {
        return resolvePreset(options.preset);
    }

    const inputFile = css.source && css.source.input && css.source.input.file;
    let searchPath = inputFile ? path.dirname(inputFile) : process.cwd();
    let configPath = null;

    if (options.configFile) {
        searchPath = null;
        configPath = path.resolve(process.cwd(), options.configFile);
    }

    const configExplorer = cosmiconfig(cssnano);
    const searchForConfig = configPath
        ? configExplorer.load(configPath)
        : configExplorer.search(searchPath);

    return searchForConfig.then(config => {
        if (config === null) {
            return resolvePreset('default');
        }
        return resolvePreset(config.config.preset || config.config);
    });
}

export default postcss.plugin(cssnano, (options = {}) => {
    return (css, result) => {
        return resolveConfig(css, result, options).then((plugins) => {
            return plugins.reduce((promise, plugin) => {
                return promise.then(initializePlugin.bind(null, plugin, css, result));
            }, Promise.resolve());
        });
    };
});
<commit_msg>fix: initial loading time (#654)<commit_after>import path from 'path';
import postcss from 'postcss';
import cosmiconfig from 'cosmiconfig';
import isResolvable from 'is-resolvable';

const cssnano = 'cssnano';

function initializePlugin (plugin, css, result) {
    if (Array.isArray(plugin)) {
        const [processor, opts] = plugin;
        if (
            typeof opts === 'undefined' ||
            (typeof opts === 'object' && !opts.exclude) ||
            (typeof opts === 'boolean' && opts === true)
        ) {
            return Promise.resolve(
                processor(opts)(css, result)
            );
        }
    } else {
        return Promise.resolve(
            plugin()(css, result)
        );
    }
    // Handle excluded plugins
    return Promise.resolve();
}

/*
 * preset can be one of four possibilities:
 * preset = 'default'
 * preset = ['default', {}]
 * preset = function <- to be invoked
 * preset = {plugins: []} <- already invoked function
 */

function resolvePreset (preset) {
    let fn, options;
    if (Array.isArray(preset)) {
        fn = preset[0];
        options = preset[1];
    } else {
        fn = preset;
        options = {};
    }
    // For JS setups where we invoked the preset already
    if (preset.plugins) {
        return Promise.resolve(preset.plugins);
    }
    // Provide an alias for the default preset, as it is built-in.
    if (fn === 'default') {
        return Promise.resolve(require('cssnano-preset-default')(options).plugins);
    }
    // For non-JS setups; we'll need to invoke the preset ourselves.
    if (typeof fn === 'function') {
        return Promise.resolve(fn(options).plugins);
    }
    // Try loading a preset from node_modules
    if (isResolvable(fn)) {
        return Promise.resolve(require(fn)(options).plugins);
    }
    const sugar = `cssnano-preset-${fn}`;
    // Try loading a preset from node_modules (sugar)
    if (isResolvable(sugar)) {
        return Promise.resolve(require(sugar)(options).plugins);
    }
    // If all else fails, we probably have a typo in the config somewhere
    throw new Error(`Cannot load preset "${fn}". Please check your configuration for errors and try again.`);
}

/*
 * cssnano will look for configuration firstly as options passed
 * directly to it, and failing this it will use cosmiconfig to
 * load an external file.
 */

function resolveConfig (css, result, options) {
    if (options.preset) {
        return resolvePreset(options.preset);
    }

    const inputFile = css.source && css.source.input && css.source.input.file;
    let searchPath = inputFile ? path.dirname(inputFile) : process.cwd();
    let configPath = null;

    if (options.configFile) {
        searchPath = null;
        configPath = path.resolve(process.cwd(), options.configFile);
    }

    const configExplorer = cosmiconfig(cssnano);
    const searchForConfig = configPath
        ? configExplorer.load(configPath)
        : configExplorer.search(searchPath);

    return searchForConfig.then(config => {
        if (config === null) {
            return resolvePreset('default');
        }
        return resolvePreset(config.config.preset || config.config);
    });
}

export default postcss.plugin(cssnano, (options = {}) => {
    return (css, result) => {
        return resolveConfig(css, result, options).then((plugins) => {
            return plugins.reduce((promise, plugin) => {
                return promise.then(initializePlugin.bind(null, plugin, css, result));
            }, Promise.resolve());
        });
    };
});
<|endoftext|>


<commit_before>/*jshint node:true*/
/* global require, module */
var path = require('path');
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
    var config = require('./config/environment')(process.env.EMBER_ENV);

    var app = new EmberApp(defaults, {
        vendorFiles: {
            'jquery.js': false,
            'ember.js': false
        },
        'ember-bootstrap': {
            importBootstrapCSS: false
        },
        sassOptions: {
            includePaths: [
                'node_modules/ember-osf/addon/styles',
                'bower_components/bootstrap-sass/assets/stylesheets',
                'bower_components/osf-style/sass',
                'bower_components/hint.css'
            ]
        },
        inlineContent: {
            raven: {
                enabled: process.env.EMBER_ENV !== 'development',
                content: `
                    <script src="https://cdn.ravenjs.com/3.5.1/ember/raven.min.js"></script>
                    <script>Raven.config("${config.sentryDSN}", {}).install();</script>`
            }
        },
        postcssOptions: {
            compile: {
                enabled: false
            },
            filter: {
                enabled: true,
                plugins: [{
                    module: require('autoprefixer'),
                    options: {
                        browsers: ['last 4 versions'],
                        cascade: false
                    }
                }, {
                    // Wrap progid declarations with double-quotes
                    module: require('postcss').plugin('progid-wrapper', () => {
                        return css =>
                            css.walkDecls(declaration => {
                                if (declaration.value.startsWith('progid')) {
                                    return declaration.value = `"${declaration.value}"`;
                                }
                            });
                    })
                }]
            }
        },
        // bable options included to fix issue with testing discover controller
        // http://stackoverflow.com/questions/32231773/ember-tests-passing-in-chrome-not-in-phantomjs
        babel: {
            optional: ['es6.spec.symbols'],
            includePolyfill: true
        }
    });

    // Use `app.import` to add additional libraries to the generated
    // output files.
    //
    // If you need to use different assets in different
    // environments, specify an object as the first parameter. That
    // object's keys should be the environment name and the values
    // should be the asset to use in that environment.
    //
    // If the library that you are including contains AMD or ES6
    // modules that you would like to import into your application
    // please specify an object with the list of modules as keys
    // along with the exports of each module as its value.

    // osf-style
    app.import(path.join(app.bowerDirectory, 'osf-style/vendor/prism/prism.css'));
    app.import(path.join(app.bowerDirectory, 'osf-style/page.css'));
    app.import(path.join(app.bowerDirectory, 'osf-style/css/base.css'));

    app.import(path.join(app.bowerDirectory, 'osf-style/img/cos-white2.png'), {
        destDir: 'img'
    });

    // app.import('bower_components/dropzone/dist/dropzone.js');
    app.import({
        development: path.join(app.bowerDirectory, 'dropzone/dist/dropzone.css'),
        production: path.join(app.bowerDirectory, 'dropzone/dist/min/dropzone.min.css')
    });

    app.import(path.join(app.bowerDirectory, 'jquery.tagsinput/src/jquery.tagsinput.js'));

     app.import({
        development: path.join(app.bowerDirectory, 'hint.css/hint.css'),
        production: path.join(app.bowerDirectory, 'hint.css/hint.css')
    });

    // Import component styles from addon
    app.import('vendor/assets/ember-osf.css');

    return app.toTree();
};
<commit_msg>add sourcemaps<commit_after>/*jshint node:true*/
/* global require, module */
var path = require('path');
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
    var config = require('./config/environment')(process.env.EMBER_ENV);

    var app = new EmberApp(defaults, {
        vendorFiles: {
            'jquery.js': false,
            'ember.js': false
        },
        sourcemaps: {
            enabled: true
        },
        'ember-bootstrap': {
            importBootstrapCSS: false
        },
        sassOptions: {
            includePaths: [
                'node_modules/ember-osf/addon/styles',
                'bower_components/bootstrap-sass/assets/stylesheets',
                'bower_components/osf-style/sass',
                'bower_components/hint.css'
            ]
        },
        inlineContent: {
            raven: {
                enabled: process.env.EMBER_ENV !== 'development',
                content: `
                    <script src="https://cdn.ravenjs.com/3.5.1/ember/raven.min.js"></script>
                    <script>Raven.config("${config.sentryDSN}", {}).install();</script>`
            }
        },
        postcssOptions: {
            compile: {
                enabled: false
            },
            filter: {
                enabled: true,
                plugins: [{
                    module: require('autoprefixer'),
                    options: {
                        browsers: ['last 4 versions'],
                        cascade: false
                    }
                }, {
                    // Wrap progid declarations with double-quotes
                    module: require('postcss').plugin('progid-wrapper', () => {
                        return css =>
                            css.walkDecls(declaration => {
                                if (declaration.value.startsWith('progid')) {
                                    return declaration.value = `"${declaration.value}"`;
                                }
                            });
                    })
                }]
            }
        },
        // bable options included to fix issue with testing discover controller
        // http://stackoverflow.com/questions/32231773/ember-tests-passing-in-chrome-not-in-phantomjs
        babel: {
            optional: ['es6.spec.symbols'],
            includePolyfill: true
        }
    });

    // Use `app.import` to add additional libraries to the generated
    // output files.
    //
    // If you need to use different assets in different
    // environments, specify an object as the first parameter. That
    // object's keys should be the environment name and the values
    // should be the asset to use in that environment.
    //
    // If the library that you are including contains AMD or ES6
    // modules that you would like to import into your application
    // please specify an object with the list of modules as keys
    // along with the exports of each module as its value.

    // osf-style
    app.import(path.join(app.bowerDirectory, 'osf-style/vendor/prism/prism.css'));
    app.import(path.join(app.bowerDirectory, 'osf-style/page.css'));
    app.import(path.join(app.bowerDirectory, 'osf-style/css/base.css'));

    app.import(path.join(app.bowerDirectory, 'osf-style/img/cos-white2.png'), {
        destDir: 'img'
    });

    // app.import('bower_components/dropzone/dist/dropzone.js');
    app.import({
        development: path.join(app.bowerDirectory, 'dropzone/dist/dropzone.css'),
        production: path.join(app.bowerDirectory, 'dropzone/dist/min/dropzone.min.css')
    });

    app.import(path.join(app.bowerDirectory, 'jquery.tagsinput/src/jquery.tagsinput.js'));

     app.import({
        development: path.join(app.bowerDirectory, 'hint.css/hint.css'),
        production: path.join(app.bowerDirectory, 'hint.css/hint.css')
    });

    // Import component styles from addon
    app.import('vendor/assets/ember-osf.css');

    return app.toTree();
};
<|endoftext|>