<commit_before>$(function(){
  var search_sidebar_template = JST['templates/search_sidebar'],

      search_project_template = JST['templates/search/project'],
      search_story_template = JST['templates/search/story'],
      search_task_template = JST['templates/search/task'],
      search_comment_template = JST['templates/search/comment'],
      search_attachment_template = JST['templates/search/attachment'],

      search_animation_speed = 500,
      search_timeout = false;

  // clicking outside the search sidebar closes it
  $(document).on("click", function() {
    closeSearchSidebar();
  });
  $(document).on("click", "#search-sidebar", function(ev) {
    ev.stopPropagation();
  });

  // open the sidebar
  $(document).on('click', '.ui-dropdown-menu.search', function(ev){
    openSearchSidebar();
  });
  $(document).on('search:open', function(){
    openSearchSidebar();
  });

  // pressing esc key
  $(document).on('dialogs:close', function(){
    closeSearchSidebar();
  });

  // do the search when typing in the search field
  $(document).on('keyup', '#search-sidebar input[name=q]', function(ev){
    // esc key
    if (ev.keyCode == 27) {
      closeSearchSidebar();

    } else {
      $('#search-sidebar').addClass('searching');
      $('#search-sidebar .no-results').hide();
      $('#search-sidebar .search-results').hide();
      $('#search-sidebar .search-results ul').html('');

      clearTimeout(search_timeout);
      search_timeout = setTimeout(function() {
        performSearch();
      }, 500);
    }
  });

  // do not actually submit the form
  $(document).on('submit', '#search-sidebar form', function(ev){
    ev.preventDefault();
  });

  function openSearchSidebar(){
    $('body').addClass('search-sidebar-open');
    $('body').append(search_sidebar_template());
    $('#search-sidebar input').focus();
    $('#search-sidebar').animate({right: 0}, search_animation_speed);
  }

  function closeSearchSidebar(){
    $('body').removeClass('search-sidebar-open');
    $('#search-sidebar').animate({right: '-400px'}, search_animation_speed, function(){
      $('#search-sidebar').remove();
    });
  }

  // does the actual search
  function performSearch(){
    var $form = $('#search-sidebar form'),
        term = $form.find('input[name=q]').val();

    if (term.length) {
      $.ajax({
        dataType: "json",
        url: $form.attr('action'),
        method: "GET",
        data: $form.serialize()
      })

      .done(function(resp){
        if (resp.search.length) {
          $('#search-sidebar .search-results span.count').html(resp.search.length);
          $('#search-sidebar .search-results span.term').html(term);
          $('#search-sidebar .search-results').show();

          _.each(resp.search, function(result){
            addSearchResult(result);
          });

        } else {
          $('#search-sidebar .no-results span').html(term);
          $('#search-sidebar .no-results').show();
        }
      })

      .fail(function(){
        console.error('something went wrong with the search');
      })

      .always(function(){
        $('#search-sidebar').removeClass('searching');
      });
    } else {
      $('#search-sidebar').removeClass('searching');
      $('#search-sidebar .no-results').hide();
      $('#search-sidebar .search-results').hide();
    }
  }

  // generates the html and adds it to the search results
  function addSearchResult(result) {
    var result_html;

    switch(result.searchable_type) {
      case "Project":
      result_html = search_project_template({ result: result });
      break;

      case "Story":
      result_html = search_story_template({ result: result });
      break;

      case "Task":
      result_html = search_task_template({ result: result });
      break;

      case "Comment":
      result_html = search_comment_template({ result: result });
      break;

      case "Attachment":
      result_html = search_attachment_template({ result: result });
      break;
    }

    $('#search-sidebar .search-results ul').append("
"+result_html+"
");
  }
});<commit_msg>abort xhr calls instead of using a timeout<commit_after>$(function(){
  var search_sidebar_template = JST['templates/search_sidebar'],

      search_project_template = JST['templates/search/project'],
      search_story_template = JST['templates/search/story'],
      search_task_template = JST['templates/search/task'],
      search_comment_template = JST['templates/search/comment'],
      search_attachment_template = JST['templates/search/attachment'],

      search_animation_speed = 500,
      search_xhr, current_search_xhr;

  // clicking outside the search sidebar closes it
  $(document).on("click", function() {
    closeSearchSidebar();
  });
  $(document).on("click", "#search-sidebar", function(ev) {
    ev.stopPropagation();
  });

  // open the sidebar
  $(document).on('click', '.ui-dropdown-menu.search', function(ev){
    openSearchSidebar();
  });
  $(document).on('search:open', function(){
    openSearchSidebar();
  });

  // pressing esc key
  $(document).on('dialogs:close', function(){
    closeSearchSidebar();
  });

  // do the search when typing in the search field
  $(document).on('keyup', '#search-sidebar input[name=q]', function(ev){
    // esc key
    if (ev.keyCode == 27) {
      closeSearchSidebar();
    } else {
      performSearch();
    }
  });

  // do not actually submit the form
  $(document).on('submit', '#search-sidebar form', function(ev){
    ev.preventDefault();
  });

  function openSearchSidebar(){
    $('body').addClass('search-sidebar-open');
    $('body').append(search_sidebar_template());
    $('#search-sidebar input').focus();
    $('#search-sidebar').animate({right: 0}, search_animation_speed);
  }

  function closeSearchSidebar(){
    $('body').removeClass('search-sidebar-open');
    $('#search-sidebar').animate({right: '-400px'}, search_animation_speed, function(){
      $('#search-sidebar').remove();
    });
  }

  // does the actual search
  function performSearch(){
    if (current_search_xhr) current_search_xhr.abort();

    $('#search-sidebar').addClass('searching');
    $('#search-sidebar .no-results').hide();
    $('#search-sidebar .search-results').hide();
    $('#search-sidebar .search-results ul').html('');

    var $form = $('#search-sidebar form'),
        term = $form.find('input[name=q]').val();

    if (term.length) {
      search_xhr = $.ajax({
        dataType: "json",
        url: $form.attr('action'),
        method: "GET",
        data: $form.serialize()
      });

      current_search_xhr = search_xhr;

      current_search_xhr.done(function(resp){
        if (resp.search.length) {
          $('#search-sidebar .search-results span.count').html(resp.search.length);
          $('#search-sidebar .search-results span.term').html(term);
          $('#search-sidebar .search-results').show();

          _.each(resp.search, function(result){
            addSearchResult(result);
          });

        } else {
          $('#search-sidebar .no-results span').html(term);
          $('#search-sidebar .no-results').show();
        }
      })

      current_search_xhr.fail(function(){
        console.error('something went wrong with the search');
      })

      current_search_xhr.always(function(){
        $('#search-sidebar').removeClass('searching');
      });
    } else {
      $('#search-sidebar').removeClass('searching');
      $('#search-sidebar .no-results').hide();
      $('#search-sidebar .search-results').hide();
    }
  }

  // generates the html and adds it to the search results
  function addSearchResult(result) {
    var result_html;

    switch(result.searchable_type) {
      case "Project":
      result_html = search_project_template({ result: result });
      break;

      case "Story":
      result_html = search_story_template({ result: result });
      break;

      case "Task":
      result_html = search_task_template({ result: result });
      break;

      case "Comment":
      result_html = search_comment_template({ result: result });
      break;

      case "Attachment":
      result_html = search_attachment_template({ result: result });
      break;
    }

    $('#search-sidebar .search-results ul').append("
"+result_html+"
");
  }
});<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable no-unused-expressions */

const { expect } = require('chai');
const fs = require('fs');
const path = require('path');
const { exportApplication, exportApplications } = require('../../../jdl/exporters/jhipster-application-exporter');
const { MONOLITH } = require('../../../jdl/jhipster/application-types');
const { createJDLApplication } = require('../../../jdl/models/jdl-application-factory');

describe('JHipsterApplicationExporter', () => {
    describe('exportApplication', () => {
        context('when passing invalid parameters', () => {
            context('such as undefined', () => {
                it('should fail', () => {
                    expect(() => {
                        exportApplication();
                    }).to.throw('An application has to be passed to be exported.');
                });
            });
        });
        context('when passing valid arguments', () => {
            context('when exporting an application to JSON', () => {
                let content;
                let returned;

                before(done => {
                    returned = exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                            creationTimestamp: 'new',
                        })
                    );
                    fs.readFile(path.join('.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                        if (err) {
                            return done(err);
                        }
                        content = JSON.parse(data);
                        return done();
                    });
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should return the exported application', () => {
                    expect(returned).to.deep.equal({
                        entities: [],
                        'generator-jhipster': {
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableHibernateCache: true,
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            otherModules: ['MyModule'],
                            packageFolder: 'com/mathieu/sample',
                            packageName: 'com.mathieu.sample',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                            creationTimestamp: 'new',
                        },
                    });
                });
                it('should export it', () => {
                    expect(content).not.to.be.undefined;
                });
                it('should format it', () => {
                    expect(content['generator-jhipster']).not.to.be.undefined;
                    const config = content['generator-jhipster'];
                    expect(config).to.deep.equal({
                        applicationType: 'monolith',
                        authenticationType: 'jwt',
                        baseName: 'toto',
                        buildTool: 'maven',
                        cacheProvider: 'ehcache',
                        clientFramework: 'angularX',
                        clientTheme: 'none',
                        clientThemeVariant: '',
                        clientPackageManager: 'npm',
                        databaseType: 'sql',
                        devDatabaseType: 'h2Disk',
                        enableSwaggerCodegen: false,
                        enableTranslation: false,
                        enableHibernateCache: true,
                        jhiPrefix: 'jhi',
                        jhipsterVersion: '4.9.0',
                        languages: ['en', 'fr'],
                        messageBroker: false,
                        nativeLanguage: 'en',
                        otherModules: ['MyModule'],
                        packageFolder: 'com/mathieu/sample',
                        packageName: 'com.mathieu.sample',
                        prodDatabaseType: 'mysql',
                        searchEngine: false,
                        serverPort: '8080',
                        serviceDiscoveryType: false,
                        skipClient: false,
                        skipServer: false,
                        skipUserManagement: false,
                        testFrameworks: [],
                        useSass: true,
                        websocket: false,
                        creationTimestamp: 'new',
                    });
                });
            });
            context('when exporting an application to JSON with skipFileGeneration', () => {
                before(() => {
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                        }),
                        { skipFileGeneration: true }
                    );
                });

                it('should not create the .yo-rc.json in the current folder', () => {
                    expect(() => fs.statSync('.yo-rc.json')).to.throw();
                });
            });
            context('when exporting an application to JSON with creationTimestampConfig', () => {
                let content;
                before(() => {
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                        }),
                        { creationTimestampConfig: 1546300800000 }
                    );
                    content = JSON.parse(fs.readFileSync(path.join('.yo-rc.json'), { encoding: 'utf8' }));
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('sets creationTimestamp on .yo-rc.json', () => {
                    expect(content['generator-jhipster']).not.to.be.undefined;
                    expect(content['generator-jhipster'].creationTimestamp).to.equal(1546300800000);
                });
            });
            context('when exporting an existing application to JSON', () => {
                let content;

                before(() => {
                    fs.writeFileSync(
                        '.yo-rc.json',
                        JSON.stringify(
                            {
                                'generator-jhipster': {
                                    jwtSecretKey: '1234',
                                    creationTimestamp: 'old',
                                },
                                test: 1234,
                            },
                            null,
                            2
                        )
                    );
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            creationTimestamp: 'new',
                        })
                    );
                    content = JSON.parse(fs.readFileSync(path.join('.yo-rc.json'), { encoding: 'utf8' }));
                });
                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should not override the creationTimestamp value', () => {
                    expect(content['generator-jhipster'].creationTimestamp).to.equal('old');
                });

                it('should add the read content to the exported application', () => {
                    expect(content).to.deep.equal({
                        entities: [],
                        test: 1234,
                        'generator-jhipster': {
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableHibernateCache: true,
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/sample',
                            packageName: 'com.mathieu.sample',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                            jwtSecretKey: '1234',
                            creationTimestamp: 'old',
                        },
                    });
                });
            });
            context('when the application has the blueprints option', () => {
                let returned;

                before(() => {
                    returned = exportApplication(
                        createJDLApplication({
                            baseName: 'toto',
                            blueprints: ['generator-jhipster-vuejs', 'generator-jhipster-nodejs'],
                        })
                    );
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should format it', () => {
                    expect(returned['generator-jhipster'].blueprints).to.deep.equal([
                        {
                            name: 'generator-jhipster-vuejs',
                        },
                        {
                            name: 'generator-jhipster-nodejs',
                        },
                    ]);
                });
            });
        });
    });
    describe('exportApplications', () => {
        context('when passing invalid parameters', () => {
            context('such as undefined', () => {
                it('should fail', () => {
                    expect(() => {
                        exportApplications();
                    }).to.throw('Applications have to be passed to be exported.');
                });
            });
        });
        context('when passing valid arguments', () => {
            context('when exporting applications to JSON with skipFileGeneration', () => {
                let returned;

                before('common setup for both applications', () => {
                    returned = exportApplications(
                        {
                            toto: createJDLApplication({
                                applicationType: MONOLITH,
                                baseName: 'toto',
                                packageName: 'com.mathieu.toto',
                                enableTranslation: false,
                                languages: ['en', 'fr'],
                                jhipsterVersion: '4.9.0',
                            }),
                            titi: createJDLApplication({
                                applicationType: MONOLITH,
                                baseName: 'titi',
                                packageName: 'com.mathieu.titi',
                                enableTranslation: false,
                                languages: ['en', 'fr'],
                                jhipsterVersion: '4.9.0',
                            }),
                        },
                        { skipFileGeneration: true }
                    );
                });

                it('should return the exported applications', () => {
                    expect(returned).to.have.lengthOf(2);
                });
                it('should not save config files', () => {
                    const baseNames = returned.map(application => application['generator-jhipster'].baseName);
                    expect(baseNames).to.be.eql(['toto', 'titi']);
                    baseNames.forEach(baseName => {
                        expect(fs.existsSync(path.join(baseName, '.yo-rc.json'))).to.be.false;
                        expect(fs.existsSync(path.join(baseName, '.jhipster'))).to.be.false;
                    });
                });
            });
            context('when exporting applications to JSON', () => {
                let returned;

                before('common setup for both applications', () => {
                    returned = exportApplications({
                        toto: createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.toto',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                        }),
                        titi: createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'titi',
                            packageName: 'com.mathieu.titi',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                        }),
                    });
                });

                it('should return the exported applications', () => {
                    expect(returned).to.have.lengthOf(2);
                });
                context('for the first application', () => {
                    let content;

                    before('setup for the first application', done => {
                        fs.readFile(path.join('toto', '.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                            if (err) {
                                return done(err);
                            }
                            content = JSON.parse(data);
                            return done();
                        });
                    });

                    after('cleanup for the fist application', () => {
                        fs.unlinkSync(path.join('toto', '.yo-rc.json'));
                        fs.rmdirSync('toto');
                    });

                    it('should export it', done => {
                        fs.readFile(path.join('toto', '.yo-rc.json'), { encoding: 'utf8' }, done);
                    });

                    it('should format it', () => {
                        expect(content['generator-jhipster']).not.to.be.undefined;
                        const config = content['generator-jhipster'];
                        expect(config).to.deep.equal({
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            enableHibernateCache: true,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/toto',
                            packageName: 'com.mathieu.toto',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                        });
                    });
                });
                context('for the second application', () => {
                    let content;

                    before('setup for the first application', done => {
                        fs.readFile(path.join('titi', '.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                            if (err) {
                                return done(err);
                            }
                            content = JSON.parse(data);
                            return done();
                        });
                    });

                    after('cleanup for the fist application', () => {
                        fs.unlinkSync(path.join('titi', '.yo-rc.json'));
                        fs.rmdirSync('titi');
                    });

                    it('should export it', done => {
                        fs.readFile(path.join('titi', '.yo-rc.json'), { encoding: 'utf8' }, done);
                    });

                    it('should format it', () => {
                        expect(content['generator-jhipster']).not.to.be.undefined;
                        const config = content['generator-jhipster'];
                        expect(config).to.deep.equal({
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'titi',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            enableHibernateCache: true,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/titi',
                            packageName: 'com.mathieu.titi',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                        });
                    });
                });
            });
        });
    });
});
<commit_msg>Move baseNames to before callback.<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable no-unused-expressions */

const { expect } = require('chai');
const fs = require('fs');
const path = require('path');
const { exportApplication, exportApplications } = require('../../../jdl/exporters/jhipster-application-exporter');
const { MONOLITH } = require('../../../jdl/jhipster/application-types');
const { createJDLApplication } = require('../../../jdl/models/jdl-application-factory');

describe('JHipsterApplicationExporter', () => {
    describe('exportApplication', () => {
        context('when passing invalid parameters', () => {
            context('such as undefined', () => {
                it('should fail', () => {
                    expect(() => {
                        exportApplication();
                    }).to.throw('An application has to be passed to be exported.');
                });
            });
        });
        context('when passing valid arguments', () => {
            context('when exporting an application to JSON', () => {
                let content;
                let returned;

                before(done => {
                    returned = exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                            creationTimestamp: 'new',
                        })
                    );
                    fs.readFile(path.join('.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                        if (err) {
                            return done(err);
                        }
                        content = JSON.parse(data);
                        return done();
                    });
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should return the exported application', () => {
                    expect(returned).to.deep.equal({
                        entities: [],
                        'generator-jhipster': {
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableHibernateCache: true,
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            otherModules: ['MyModule'],
                            packageFolder: 'com/mathieu/sample',
                            packageName: 'com.mathieu.sample',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                            creationTimestamp: 'new',
                        },
                    });
                });
                it('should export it', () => {
                    expect(content).not.to.be.undefined;
                });
                it('should format it', () => {
                    expect(content['generator-jhipster']).not.to.be.undefined;
                    const config = content['generator-jhipster'];
                    expect(config).to.deep.equal({
                        applicationType: 'monolith',
                        authenticationType: 'jwt',
                        baseName: 'toto',
                        buildTool: 'maven',
                        cacheProvider: 'ehcache',
                        clientFramework: 'angularX',
                        clientTheme: 'none',
                        clientThemeVariant: '',
                        clientPackageManager: 'npm',
                        databaseType: 'sql',
                        devDatabaseType: 'h2Disk',
                        enableSwaggerCodegen: false,
                        enableTranslation: false,
                        enableHibernateCache: true,
                        jhiPrefix: 'jhi',
                        jhipsterVersion: '4.9.0',
                        languages: ['en', 'fr'],
                        messageBroker: false,
                        nativeLanguage: 'en',
                        otherModules: ['MyModule'],
                        packageFolder: 'com/mathieu/sample',
                        packageName: 'com.mathieu.sample',
                        prodDatabaseType: 'mysql',
                        searchEngine: false,
                        serverPort: '8080',
                        serviceDiscoveryType: false,
                        skipClient: false,
                        skipServer: false,
                        skipUserManagement: false,
                        testFrameworks: [],
                        useSass: true,
                        websocket: false,
                        creationTimestamp: 'new',
                    });
                });
            });
            context('when exporting an application to JSON with skipFileGeneration', () => {
                before(() => {
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                        }),
                        { skipFileGeneration: true }
                    );
                });

                it('should not create the .yo-rc.json in the current folder', () => {
                    expect(() => fs.statSync('.yo-rc.json')).to.throw();
                });
            });
            context('when exporting an application to JSON with creationTimestampConfig', () => {
                let content;
                before(() => {
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            otherModules: ['MyModule'],
                        }),
                        { creationTimestampConfig: 1546300800000 }
                    );
                    content = JSON.parse(fs.readFileSync(path.join('.yo-rc.json'), { encoding: 'utf8' }));
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('sets creationTimestamp on .yo-rc.json', () => {
                    expect(content['generator-jhipster']).not.to.be.undefined;
                    expect(content['generator-jhipster'].creationTimestamp).to.equal(1546300800000);
                });
            });
            context('when exporting an existing application to JSON', () => {
                let content;

                before(() => {
                    fs.writeFileSync(
                        '.yo-rc.json',
                        JSON.stringify(
                            {
                                'generator-jhipster': {
                                    jwtSecretKey: '1234',
                                    creationTimestamp: 'old',
                                },
                                test: 1234,
                            },
                            null,
                            2
                        )
                    );
                    exportApplication(
                        createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.sample',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                            creationTimestamp: 'new',
                        })
                    );
                    content = JSON.parse(fs.readFileSync(path.join('.yo-rc.json'), { encoding: 'utf8' }));
                });
                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should not override the creationTimestamp value', () => {
                    expect(content['generator-jhipster'].creationTimestamp).to.equal('old');
                });

                it('should add the read content to the exported application', () => {
                    expect(content).to.deep.equal({
                        entities: [],
                        test: 1234,
                        'generator-jhipster': {
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableHibernateCache: true,
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/sample',
                            packageName: 'com.mathieu.sample',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                            jwtSecretKey: '1234',
                            creationTimestamp: 'old',
                        },
                    });
                });
            });
            context('when the application has the blueprints option', () => {
                let returned;

                before(() => {
                    returned = exportApplication(
                        createJDLApplication({
                            baseName: 'toto',
                            blueprints: ['generator-jhipster-vuejs', 'generator-jhipster-nodejs'],
                        })
                    );
                });

                after(() => {
                    fs.unlinkSync(path.join('.yo-rc.json'));
                });

                it('should format it', () => {
                    expect(returned['generator-jhipster'].blueprints).to.deep.equal([
                        {
                            name: 'generator-jhipster-vuejs',
                        },
                        {
                            name: 'generator-jhipster-nodejs',
                        },
                    ]);
                });
            });
        });
    });
    describe('exportApplications', () => {
        context('when passing invalid parameters', () => {
            context('such as undefined', () => {
                it('should fail', () => {
                    expect(() => {
                        exportApplications();
                    }).to.throw('Applications have to be passed to be exported.');
                });
            });
        });
        context('when passing valid arguments', () => {
            context('when exporting applications to JSON with skipFileGeneration', () => {
                let returned;
                let baseNames;

                before('common setup for both applications', () => {
                    returned = exportApplications(
                        {
                            toto: createJDLApplication({
                                applicationType: MONOLITH,
                                baseName: 'toto',
                                packageName: 'com.mathieu.toto',
                                enableTranslation: false,
                                languages: ['en', 'fr'],
                                jhipsterVersion: '4.9.0',
                            }),
                            titi: createJDLApplication({
                                applicationType: MONOLITH,
                                baseName: 'titi',
                                packageName: 'com.mathieu.titi',
                                enableTranslation: false,
                                languages: ['en', 'fr'],
                                jhipsterVersion: '4.9.0',
                            }),
                        },
                        { skipFileGeneration: true }
                    );
                    baseNames = returned.map(application => application['generator-jhipster'].baseName);
                });

                it('should return the exported applications', () => {
                    expect(returned).to.have.lengthOf(2);
                });
                it('should not save config files', () => {
                    expect(baseNames).to.be.eql(['toto', 'titi']);
                    baseNames.forEach(baseName => {
                        expect(fs.existsSync(path.join(baseName, '.yo-rc.json'))).to.be.false;
                        expect(fs.existsSync(path.join(baseName, '.jhipster'))).to.be.false;
                    });
                });
            });
            context('when exporting applications to JSON', () => {
                let returned;

                before('common setup for both applications', () => {
                    returned = exportApplications({
                        toto: createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'toto',
                            packageName: 'com.mathieu.toto',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                        }),
                        titi: createJDLApplication({
                            applicationType: MONOLITH,
                            baseName: 'titi',
                            packageName: 'com.mathieu.titi',
                            enableTranslation: false,
                            languages: ['en', 'fr'],
                            jhipsterVersion: '4.9.0',
                        }),
                    });
                });

                it('should return the exported applications', () => {
                    expect(returned).to.have.lengthOf(2);
                });
                context('for the first application', () => {
                    let content;

                    before('setup for the first application', done => {
                        fs.readFile(path.join('toto', '.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                            if (err) {
                                return done(err);
                            }
                            content = JSON.parse(data);
                            return done();
                        });
                    });

                    after('cleanup for the fist application', () => {
                        fs.unlinkSync(path.join('toto', '.yo-rc.json'));
                        fs.rmdirSync('toto');
                    });

                    it('should export it', done => {
                        fs.readFile(path.join('toto', '.yo-rc.json'), { encoding: 'utf8' }, done);
                    });

                    it('should format it', () => {
                        expect(content['generator-jhipster']).not.to.be.undefined;
                        const config = content['generator-jhipster'];
                        expect(config).to.deep.equal({
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'toto',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            enableHibernateCache: true,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/toto',
                            packageName: 'com.mathieu.toto',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                        });
                    });
                });
                context('for the second application', () => {
                    let content;

                    before('setup for the first application', done => {
                        fs.readFile(path.join('titi', '.yo-rc.json'), { encoding: 'utf8' }, (err, data) => {
                            if (err) {
                                return done(err);
                            }
                            content = JSON.parse(data);
                            return done();
                        });
                    });

                    after('cleanup for the fist application', () => {
                        fs.unlinkSync(path.join('titi', '.yo-rc.json'));
                        fs.rmdirSync('titi');
                    });

                    it('should export it', done => {
                        fs.readFile(path.join('titi', '.yo-rc.json'), { encoding: 'utf8' }, done);
                    });

                    it('should format it', () => {
                        expect(content['generator-jhipster']).not.to.be.undefined;
                        const config = content['generator-jhipster'];
                        expect(config).to.deep.equal({
                            applicationType: 'monolith',
                            authenticationType: 'jwt',
                            baseName: 'titi',
                            buildTool: 'maven',
                            cacheProvider: 'ehcache',
                            clientFramework: 'angularX',
                            clientTheme: 'none',
                            clientThemeVariant: '',
                            clientPackageManager: 'npm',
                            databaseType: 'sql',
                            devDatabaseType: 'h2Disk',
                            enableSwaggerCodegen: false,
                            enableTranslation: false,
                            enableHibernateCache: true,
                            jhiPrefix: 'jhi',
                            jhipsterVersion: '4.9.0',
                            languages: ['en', 'fr'],
                            messageBroker: false,
                            nativeLanguage: 'en',
                            packageFolder: 'com/mathieu/titi',
                            packageName: 'com.mathieu.titi',
                            prodDatabaseType: 'mysql',
                            searchEngine: false,
                            serverPort: '8080',
                            serviceDiscoveryType: false,
                            skipClient: false,
                            skipServer: false,
                            skipUserManagement: false,
                            testFrameworks: [],
                            useSass: true,
                            websocket: false,
                        });
                    });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
 * createPreloadingMiddleware tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { addQueryArgs } from '@wordpress/url';

/**
 * Internal dependencies
 */
import createPreloadingMiddleware from './preloading';

describe( 'Preloading Middleware', () => {
	it( 'should return cached data for the first request only.', async () => {
		const body = {
			status: 'this is the preloaded response',
		};

		const requestURI = 'google-site-kit/v1/core/user/authentication';

		const preloadedData = {
			[ requestURI ]: {
				method: 'GET',
				body,
			},
		};
		const preloadingMiddleware = createPreloadingMiddleware(
			preloadedData
		);

		const requestOptions = {
			method: 'GET',
			path: addQueryArgs( requestURI, { timestamp: Date.now() } ),
		};

		const firstRequest = await preloadingMiddleware( requestOptions, () => {} );
		expect( firstRequest ).toEqual( body );

		const secondRequest = await preloadingMiddleware( requestOptions, () => {} );
		expect( secondRequest ).toEqual( undefined );
	} );
} );
<commit_msg>Add more test cases to middleware.<commit_after>/**
 * createPreloadingMiddleware tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { addQueryArgs } from '@wordpress/url';

/**
 * Internal dependencies
 */
import createPreloadingMiddleware from './preloading';

const requestURI = 'google-site-kit/v1/core/user/authentication';
const body = {
	status: 'this is the preloaded response',
};
const preloadedData = {
	[ requestURI ]: {
		method: 'GET',
		body,
	},
};

describe( 'Preloading Middleware', () => {
	it( 'returns a preloaded response when present', async () => {
		const preloadingMiddleware = createPreloadingMiddleware(
			preloadedData
		);

		const requestOptions = {
			method: 'GET',
			path: requestURI,
		};

		const firstRequest = await preloadingMiddleware( requestOptions, jest.fn() );
		expect( firstRequest ).toEqual( body );
	} );

	it( 'does nothing and calls next middleware when no preloaded response exists for the request', async () => {
		const next = jest.fn();
		const preloadingMiddleware = createPreloadingMiddleware( {} );
		const requestOptions = {
			method: 'GET',
			path: requestURI,
		};
		await preloadingMiddleware( requestOptions, next );
		expect( next ).toHaveBeenCalled();
	} );

	it( 'returns a preloaded response only once for each preloaded request', async () => {
		const preloadingMiddleware = createPreloadingMiddleware(
			preloadedData
		);

		const requestOptions = {
			method: 'GET',
			path: requestURI,
		};
		const firstRequest = await preloadingMiddleware( requestOptions, jest.fn() );
		expect( firstRequest ).toEqual( body );

		const secondRequest = await preloadingMiddleware( requestOptions, jest.fn() );
		expect( secondRequest ).toBeUndefined();
	} );
	it( 'deletes a preloaded response from the cache when requested with a timestamp query paramater', async () => {
		const preloadingMiddleware = createPreloadingMiddleware(
			preloadedData
		);

		const requestOptions = {
			method: 'GET',
			path: addQueryArgs( requestURI, { timestamp: Date.now() } ),
		};
		const firstRequest = await preloadingMiddleware( requestOptions, jest.fn() );
		expect( firstRequest ).toBeUndefined();
	} );
} );
<|endoftext|>


<commit_before>var _ = require('underscore');
var cdb = require('@carto/carto.js');
var Dashboard = require('deep-insights/api/dashboard.js');
var DashboardView = require('deep-insights/dashboard-view');
var WidgetsCollection = require('deep-insights/widgets/widgets-collection');
var WidgetsService = require('deep-insights/widgets-service');
var URLHelper = require('deep-insights/api/url-helper');

/**
 * Translates a vizJSON v3 datastructure into a working dashboard which will be rendered in given selector.
 *
 * @param {String} selector e.g. "#foobar-id", ".some-class"
 * @param {Object} vizJSON JSON datastructure
 * @param {Object} opts (Optional) flags, see 3rd param for cdb.createVis for available ones. Keys used here:
 *   renderMenu: {Boolean} If true (default), render a top-level menu on the left side.
 * @return {Object} with keys:
 *   dashboardView: root (backbone) view of the dashboard
 *   vis: the instantiated vis map, same result as given from cdb.createVis()
 */
var createDashboard = function (selector, vizJSON, opts, callback) {
  var dashboardEl = document.querySelector(selector);
  if (!dashboardEl) throw new Error('no element found with selector ' + selector);

  // Default options
  opts = opts || {};
  opts.renderMenu = _.isBoolean(opts.renderMenu)
    ? opts.renderMenu
    : true;
  opts.autoStyle = _.isBoolean(opts.autoStyle)
    ? opts.autoStyle
    : false;

  var widgets = new WidgetsCollection();

  var model = new cdb.core.Model({
    title: vizJSON.title,
    description: vizJSON.description,
    updatedAt: vizJSON.updated_at,
    userName: vizJSON.user.fullname,
    userProfileURL: vizJSON.user.profile_url,
    userAvatarURL: vizJSON.user.avatar_url,
    renderMenu: opts.renderMenu,
    autoStyle: opts.autoStyle,
    showLogo: opts.cartodb_logo,
    initialPosition: {
      bounds: vizJSON.bounds
    }
  });
  var dashboardView = new DashboardView({
    el: dashboardEl,
    widgets: widgets,
    model: model
  });
  var dashboardState = opts.state || URLHelper.getStateFromCurrentURL();
  if (dashboardState && !_.isEmpty(dashboardState.map)) {
    if (_.isArray(dashboardState.map.center)) {
      vizJSON.center = dashboardState.map.center;
    }
    if (_.isNumber(dashboardState.map.zoom)) {
      vizJSON.zoom = dashboardState.map.zoom;
    }
    if (dashboardState.map.ne && dashboardState.map.sw) {
      vizJSON.bounds = [dashboardState.map.ne, dashboardState.map.sw];
    }
  }

  var vis = cdb.createVis(dashboardView.$('#map'), vizJSON, _.extend(opts, {
    skipMapInstantiation: true
  }));

  vis.once('load', function (vis) {
    var widgetsState = (dashboardState && dashboardState.widgets) || {};

    // Create widgets
    var widgetsService = new WidgetsService(widgets, vis.dataviews);

    var widgetModelsMap = {
      formula: widgetsService.createFormulaModel.bind(widgetsService),
      histogram: widgetsService.createHistogramModel.bind(widgetsService),
      'time-series': widgetsService.createTimeSeriesModel.bind(widgetsService),
      category: widgetsService.createCategoryModel.bind(widgetsService)
    };
    vizJSON.widgets.forEach(function (widget) {
      // Flatten the data structure given in vizJSON, the widgetsService will use whatever it needs and ignore the rest
      var attrs = _.extend({}, widget, widget.options);
      var newWidgetModel = widgetModelsMap[widget.type];
      var state = widgetsState[widget.id];

      if (_.isFunction(newWidgetModel)) {
        // Find the Layer that the Widget should be created for.
        var layer;
        var source;
        if (widget.layer_id) {
          layer = vis.map.layers.get(widget.layer_id);
        } else if (Number.isInteger(widget.layerIndex)) {
          // TODO Since namedmap doesn't have ids we need to map in another way, here using index
          //   should we solve this in another way?
          layer = vis.map.layers.at(widget.layerIndex);
        }
        if (widget.source && widget.source.id) {
          source = vis.analysis.findNodeById(widget.source.id);
          attrs.source = source;
        }

        newWidgetModel(attrs, layer, state);
      } else {
        cdb.log.error('No widget found for type ' + widget.type);
      }
    });

    dashboardView.render();

    var callbackObj = {
      dashboardView: dashboardView,
      widgets: widgetsService,
      areWidgetsInitialised: function () {
        var widgetsCollection = widgetsService.getCollection();
        if (widgetsCollection.size() > 0) {
          return widgetsCollection.hasInitialState();
        }
        return true;
      },
      vis: vis
    };

    vis.instantiateMap({
      success: function () {
        callback && callback(null, callbackObj);
      },
      error: function (errorMessage) {
        callback && callback(new Error(errorMessage), callbackObj);
      }
    });
  });
};

module.exports = function (selector, vizJSON, opts, callback) {
  var args = arguments;
  var fn = args[args.length - 1];

  if (_.isFunction(fn)) {
    callback = fn;
  }

  function _load (vizJSON) {
    createDashboard(selector, vizJSON, opts, function (error, dashboard) {
      var _dashboard = new Dashboard(dashboard);

      if (opts.share_urls) {
        _dashboard.onStateChanged(
          _.debounce(
            function (state, url) {
              window.history.replaceState('Object', 'Title', url);
            },
            500
          )
        );
      }

      callback && callback(error, _dashboard);
    });
  }

  if (typeof vizJSON === 'string') {
    cdb.core.Loader.get(vizJSON, function (data) {
      if (data) {
        _load(data, opts);
      } else {
        callback && callback(new Error('Error fetching viz.json file: ' + vizJSON));
      }
    });
  } else {
    _load(vizJSON, opts);
  }
};
<commit_msg>Minor refactor<commit_after>var _ = require('underscore');
var cdb = require('@carto/carto.js');
var Dashboard = require('deep-insights/api/dashboard.js');
var DashboardView = require('deep-insights/dashboard-view');
var WidgetsCollection = require('deep-insights/widgets/widgets-collection');
var WidgetsService = require('deep-insights/widgets-service');
var URLHelper = require('deep-insights/api/url-helper');

/**
 * Translates a vizJSON v3 datastructure into a working dashboard which will be rendered in given selector.
 *
 * @param {String} selector e.g. "#foobar-id", ".some-class"
 * @param {Object} vizJSON JSON datastructure
 * @param {Object} opts (Optional) flags, see 3rd param for cdb.createVis for available ones. Keys used here:
 *   renderMenu: {Boolean} If true (default), render a top-level menu on the left side.
 * @return {Object} with keys:
 *   dashboardView: root (backbone) view of the dashboard
 *   vis: the instantiated vis map, same result as given from cdb.createVis()
 */
var createDashboard = function (selector, vizJSON, opts, callback) {
  var dashboardEl = document.querySelector(selector);
  if (!dashboardEl) throw new Error('no element found with selector ' + selector);

  // Default options
  opts = opts || {};
  opts.renderMenu = _.isBoolean(opts.renderMenu)
    ? opts.renderMenu
    : true;
  opts.autoStyle = _.isBoolean(opts.autoStyle)
    ? opts.autoStyle
    : false;

  var widgets = new WidgetsCollection();

  var model = new cdb.core.Model({
    title: vizJSON.title,
    description: vizJSON.description,
    updatedAt: vizJSON.updated_at,
    userName: vizJSON.user.fullname,
    userProfileURL: vizJSON.user.profile_url,
    userAvatarURL: vizJSON.user.avatar_url,
    renderMenu: opts.renderMenu,
    autoStyle: opts.autoStyle,
    showLogo: opts.cartodb_logo,
    initialPosition: {
      bounds: vizJSON.bounds
    }
  });
  var dashboardView = new DashboardView({
    el: dashboardEl,
    widgets: widgets,
    model: model
  });
  var dashboardState = opts.state || URLHelper.getStateFromCurrentURL();
  if (dashboardState && !_.isEmpty(dashboardState.map)) {
    if (_.isArray(dashboardState.map.center)) {
      vizJSON.center = dashboardState.map.center;
    }
    if (_.isNumber(dashboardState.map.zoom)) {
      vizJSON.zoom = dashboardState.map.zoom;
    }
    if (dashboardState.map.ne && dashboardState.map.sw) {
      vizJSON.bounds = [dashboardState.map.ne, dashboardState.map.sw];
    }
  }

  var vis = cdb.createVis(dashboardView.$('#map'), vizJSON, _.extend(opts, {
    skipMapInstantiation: true
  }));

  vis.once('load', function (vis) {
    var widgetsState = (dashboardState && dashboardState.widgets) || {};

    // Create widgets
    var widgetsService = new WidgetsService(widgets, vis.dataviews);

    var widgetModelsMap = {
      formula: widgetsService.createFormulaModel.bind(widgetsService),
      histogram: widgetsService.createHistogramModel.bind(widgetsService),
      'time-series': widgetsService.createTimeSeriesModel.bind(widgetsService),
      category: widgetsService.createCategoryModel.bind(widgetsService)
    };
    vizJSON.widgets.forEach(function (widget) {
      // Flatten the data structure given in vizJSON, the widgetsService will use whatever it needs and ignore the rest
      var attrs = _.extend({}, widget, widget.options);
      var newWidgetModel = widgetModelsMap[widget.type];
      var state = widgetsState[widget.id];

      if (!_.isFunction(newWidgetModel)) {
        cdb.log.error('No widget found for type ' + widget.type);
        return;
      }
      // Find the Layer that the Widget should be created for.
      var layer;
      var source;
      if (widget.layer_id) {
        layer = vis.map.layers.get(widget.layer_id);
      } else if (Number.isInteger(widget.layerIndex)) {
        // TODO Since namedmap doesn't have ids we need to map in another way, here using index
        //   should we solve this in another way?
        layer = vis.map.layers.at(widget.layerIndex);
      }
      if (widget.source && widget.source.id) {
        source = vis.analysis.findNodeById(widget.source.id);
        attrs.source = source;
      }

      newWidgetModel(attrs, layer, state);
    });

    dashboardView.render();

    var callbackObj = {
      dashboardView: dashboardView,
      widgets: widgetsService,
      areWidgetsInitialised: function () {
        var widgetsCollection = widgetsService.getCollection();
        if (widgetsCollection.size() > 0) {
          return widgetsCollection.hasInitialState();
        }
        return true;
      },
      vis: vis
    };

    vis.instantiateMap({
      success: function () {
        callback && callback(null, callbackObj);
      },
      error: function (errorMessage) {
        callback && callback(new Error(errorMessage), callbackObj);
      }
    });
  });
};

module.exports = function (selector, vizJSON, opts, callback) {
  var args = arguments;
  var fn = args[args.length - 1];

  if (_.isFunction(fn)) {
    callback = fn;
  }

  function _load (vizJSON) {
    createDashboard(selector, vizJSON, opts, function (error, dashboard) {
      var _dashboard = new Dashboard(dashboard);

      if (opts.share_urls) {
        _dashboard.onStateChanged(
          _.debounce(
            function (state, url) {
              window.history.replaceState('Object', 'Title', url);
            },
            500
          )
        );
      }

      callback && callback(error, _dashboard);
    });
  }

  if (typeof vizJSON === 'string') {
    cdb.core.Loader.get(vizJSON, function (data) {
      if (data) {
        _load(data, opts);
      } else {
        callback && callback(new Error('Error fetching viz.json file: ' + vizJSON));
      }
    });
  } else {
    _load(vizJSON, opts);
  }
};
<|endoftext|>


<commit_before>import Link from 'next/link';
import markdown from 'markdown-in-js';
import Layout from '../../components/layout';

const Content = () => markdown`
# Using HTML Tags in Idyll

Idyll supports a variety of HTML tags, although the syntax for using these tags in Idyll differs a bit from plain HTML.

#### Contents
* [General Syntax Changes](#General)
  * [Tag Syntax](#Tags)
    * [Singular Tags](#Singular)
  * [Attribute Assignment](#Attributes)
    * [Hyphenated Attributes & Properties](#Hyphenated)
    * [Attributes Allowing Multiple Properties](#Multiple)
    * [Calling Classes](#Calling)
* [Creating and Calling Classes](#Classes)
  * [Where to Define Classes](#Where)
  * [CSS Syntax](#CSS)
    * [Useful Properties](#Properties)
* [Inline Styles](#Inline)
* [Other Tags](#Other)
  * [Text Formatting](#Text)
  * [Lists](#Lists)
  * [Other Formatting](#Misc)

## General Syntax Changes

For those familiar with HTML, below is a summary of changes from normal HTML syntax.

### Tag Syntax

Enclose tags in square brackets instead of angular ones:

\`\`\`
[i]This text will be italicized using HTML italicization.[/i]
\`\`\`

Renders: *This text will be italicized using HTML italicization.*

#### Singular Tags

If you are using a tag that does not have separate opening and a closing tags —
for instance, the \`\<br\>\` tag to force a line break —
put a slash at the end, as in \`\[br /\]\`.

### Attribute Assignment

Replace any \`=\` you might normally use when assigning attributes with a \`:\`, as below:

\`\`\`
[a href:'http://google.com']Google[/a]
\`\`\`
Renders: Google

#### Hyphenated Attributes & Properties

Any attribute or property that would be hyphenated in HTML —
\`background-color\`, for example —
now has the second word capitalized and the hyphen removed (\`backgroundColor\`).

#### Attributes Allowing Multiple Properties

Attributes which allow multiple properties have several differences.
First, instead of using "quotes," surround the list of properties with backticks, then, within that, list them inside curly braces.
Separate properties with commas instead of semicolons,
and pass in all individual values as strings (with single or double quotes).

For instance, use:

\`\`\`
[div style:\\\`{backgroundColor: 'green', padding: '20px'}\\\`]Some text[/div]
\`\`\`

to generate a div with a green background and 20 pixels of padding on each side:

Some text

#### Calling Classes

If calling a class in, for example, a div, Idyll prefers calling a \`className\` over simply using \`class\`:

~~~shell
[p className:'myclass']Some other text[/p]
~~~

## Creating and Calling Classes

While Idyll supports inline styles,
it is often both easier to read and write the source for a page by defining a class.
A class, in HTML or CSS,
is essentially a collection of style attributes that will be used in multiple divs, spans, or paragraph blocks.
The class is assigned a name so that it can easily be called multiple times.

### Where to Define Classes

Idyll posts are pre-configured to read an editable \`styles.css\` file,
and this file can be found in the top level of the idyll post (the same location as \`index.idyll\`).
You can also use a style section, enclosed in the \`[style]...[/style]\` tags,
which comes after the \`[Header /]\` and before the page's contents.

### CSS Syntax

Where the use of inline styles in Idyll differs from HTML,
the syntax for defining classes is the same as it is in CSS.

Define as follows:

~~~shell
.myclass {
    property: value;
    property: value;
}
~~~

The above will apply the properties it was given to all elements whose class name is \`myclass\`.
You can assign the class to an object using the \`className\` property, treating the value as a string.
The \`className\` property can be assigned when using \`[div]\`, \`[span]\`, or \`[p]\`.

For example, say you want a style that contrasts with your black text on a white background
and puts some extra space around your text.
You could call that class "contrast" and define it like so:

~~~shell
.contrast {
    background-color: black;
    color: white;
    margin: 20px;
    padding: 20px;
}
~~~

Then you could make a div that uses that class by simply writing:

~~~shell
[div className:'contrast']Some text.[/div]
~~~

And you will see:

Some text

This can be done with a paragraph (\`[p]\`) or span (\`[span]\`) as well, using the same method.

#### Useful Properties

**\`color\`** - Sets the color of the text. Values can be a name (example: \`green\`) or a hex code (example: \`#00ff00\` or \`#0f0\`)

**\`background-color\`** - Sets the background color of the box. Values can be a name (example: \`black\`) or a hex code (example: \`#000000\` or \`#000\`).

**\`margin\`** - Sets a margin between the outside of the box and the other contents. Values can be a number of pixels (example: \`20px\`) or a percentage of the element (example: \`5%\`).
Individual margins can be set using \`margin-top\`, \`margin-bottom\`, \`margin-right\`, and \`margin-left\`. These properties' values otherwise function the same as they do for \`margin\`.

**\`padding\`** - Sets padding between the outside of the box and the box's contents.

**\`font-size\`** - Sets the size of the font. Values can be in pixels (ex: \`14px\`), percentage of a parent element's size (example: \`150%\`), or size category (ex: \`xx-small\`).

**\`font-weight\`** - Sets the weight of the font. While you likely won't be using the values \`normal\` or \`bold\` often, because this can easily be handled through markdown syntax, values can be set to numbers, where the normal weight is 400 and the bold weight is 700.

## Inline Styles

There may be cases where you only need to use a certain style once,
and it therefore ends up being easier to use that style "inline" in the tag itself without calling a style.
As in an example above, you can do so like this:

\`\`\`
[div style:\\\`{property: 'value', property: 'value'}\\\`]Some text[/div]
\`\`\`

For example,

\`\`\`
[div style:\\\`{backgroundColor: 'green', padding: '20px'}\\\`]Some text[/div]
\`\`\`

The properties available are the same as those listed [above](#Properties) for CSS,
although any hyphenated properties have the hyphen removed and the second word capitalized
(e.g. \`font-size\` becomes \`fontSize\` when used with inline styling).

## Other Tags

Below are some other tags that you may find useful.

### Text Formatting

In the rare case that markdown's asterisks are proving difficult to use,
the \`[i]\` tag can be used to italicize text
and the \`[b]\` tag can be used to bold text.

To underline text, use the \`[u]\` tag.

Use \`[sup]\` to create superscripts and \`[sub]\` to create subscripts.

Use \`[del]\` to strikethrough.

#### Lists

Currently, markdown syntax in Idyll does not support multiple levels of lists.
HTML's list syntax, however, does allow sub-items in Idyll.
An HTML-style list can be made by:

1. Putting one of these tags at the front of the list:
    * \`[ol]\` to generate ordered lists, like the main one
    * \`[ul]\` to generate unordered lists, like this sub-list
    * (And to nest lists, just put a new list where a list item would go!)
2. Putting the \`[li]\` tag before each list item and the \`[/li]\` tag after,
3. And putting closing the list with an \`[/ol]\` or \`[/ul]\` at the end.

To make the above example in Idyll (Indentation is optional):
~~~shell
An HTML-style list can be made by:
[ol]
  [li]Putting one of these tags at the front of the list:[/li]
  [ul]
    [li] \\\`[ol]\\\` to generate ordered lists, like the main one[/li]
    [li] \\\`[ul]\\\` to generate unordered lists, like this sub-list[/li]
    [li] (And to nest lists, just put a new list where a list item would go!) [/li]
  [/ul]
  [li]Putting the \\\`[li]\\\` tag before each list item and the \\\`[/li]\\\` tag after[/li]
  [li]And putting closing the list with an \\\`[/ol]\\\` (or \\\`[/ul]\\\`) at the end.[/li]
[/ol]
~~~

### Other Formatting

You can force a line
break with \`[br /]\`.

Make horizontal lines with \`[hr /]\`.

---

Both of these tags have a \`/\` at the end of them, indicating that they do not need a closing tag — just write \`[br /]\`, not \`[br /][/br]\`!
`;

export default ({ url }) => (
  <Layout
    url={url}
    title={'Idyll Documentation | Installation and Getting Started'}
  >
    <Content />
  </Layout>
);
<commit_msg>Finished own proofreading and revisions. After I get another set of eyes on this I should be ready to submit.<commit_after>import Link from 'next/link';
import markdown from 'markdown-in-js';
import Layout from '../../components/layout';

const Content = () => markdown`
# Using HTML Tags in Idyll

Idyll supports a variety of HTML tags, although the syntax for using these tags in Idyll differs a bit from plain HTML.

#### Contents
* [General Syntax Changes](#General)
  * [Tag Syntax](#Tags)
    * [Singular Tags](#Singular)
  * [Attribute Assignment](#Attributes)
    * [Hyphenated Attributes & Properties](#Hyphenated)
    * [Attributes Allowing Multiple Properties](#Multiple)
    * [Calling Classes](#Calling)
* [Creating and Calling Classes](#Classes)
  * [Where to Define Classes](#Where)
  * [CSS Syntax](#CSS)
    * [Useful Properties](#Properties)
* [Inline Styles](#Inline)
* [Other Tags](#Other)
  * [Text Formatting](#Text)
  * [Lists](#Lists)
  * [Other Formatting](#Misc)

## General Syntax Changes

For those familiar with HTML, below is a summary of changes from normal HTML syntax.

### Tag Syntax

Enclose tags in square brackets instead of angular ones:

\`\`\`
[i]This text will be italicized using HTML italicization.[/i]
\`\`\`

Renders: *This text will be italicized using HTML italicization.*

#### Singular Tags

If you are using a tag that does not have separate opening and a closing tags —
for instance, the \`\<br\>\` tag to force a line break —
put a slash at the end, as in \`\[br /\]\`.

### Attribute Assignment

Replace any \`=\` you might normally use when assigning attributes with a \`:\`, as below:

\`\`\`
[a href:'http://google.com']Google[/a]
\`\`\`
Renders: Google

#### Hyphenated Attributes & Properties

Any attribute or property that would be hyphenated in HTML —
\`background-color\`, for example —
now has the second word capitalized and the hyphen removed (\`backgroundColor\`).

#### Attributes Allowing Multiple Properties

Attributes which allow multiple properties have several differences.
First, instead of using "quotes," surround the list of properties with backticks, then, within that, list them inside curly braces.
Separate properties with commas instead of semicolons,
and pass in all individual values as strings (with single or double quotes).

For instance, use:

\`\`\`
[div style:\\\`{backgroundColor: 'green', padding: '20px'}\\\`]Some text[/div]
\`\`\`

to generate a div with a green background and 20 pixels of padding on each side:

Some text

#### Calling Classes

If calling a class in, for example, a div, Idyll prefers calling a \`className\` over simply using \`class\`:

~~~shell
[p className:'myclass']Some other text[/p]
~~~

## Creating and Calling Classes

While Idyll supports inline styles,
it is often both easier to read and write the source for a page by defining a class.
A class, in HTML or CSS,
is essentially a collection of style attributes that will be used in multiple divs, spans, or paragraph blocks.
The class is assigned a name so that it can easily be called multiple times.

### Where to Define Classes

Idyll posts are pre-configured to read an editable \`styles.css\` file,
and this file can be found in the top level of the idyll post (the same location as \`index.idyll\`).
You can also use a style section, enclosed in the \`[style]...[/style]\` tags,
which comes after the \`[Header /]\` and before the page's contents.

### CSS Syntax

Where the use of inline styles in Idyll differs from HTML,
the syntax for defining classes is the same as it is in CSS.

Define a class by preceding its name with a period,
listing property-value pairs in curly braces,
assigning properties with a colon,
and delimiting property-value pairs with a semicolon:

~~~shell
.myclass {
    property: value;
    property: value;
}
~~~

The above will apply the properties it was given to all elements whose class name is \`myclass\`.
You can assign the class to an object using the \`className\` property, treating the value as a string.
The \`className\` property can be assigned when using \`[div]\`, \`[span]\`, or \`[p]\`.

For example, say you want a style that contrasts with your black text on a white background
and puts some extra space around your text.
You could call that class "contrast" and define it like so:

~~~shell
.contrast {
    background-color: black;
    color: white;
    margin: 20px;
    padding: 20px;
}
~~~

Then you could make a div that uses that class by simply writing:

~~~shell
[div className:'contrast']Some text.[/div]
~~~

And you will see:

Some text

This can be done with a paragraph (\`[p]\`) or span (\`[span]\`) as well, using the same method.

#### Useful Properties

**\`color\`** - Sets the color of the text. Values can be a name (example: \`green\`) or a hex code (example: \`#00ff00\` or \`#0f0\`)

**\`background-color\`** - Sets the background color of the box. Values can be a name (example: \`black\`) or a hex code (example: \`#000000\` or \`#000\`).

**\`margin\`** - Sets a margin between the outside of the box and the other contents. Values can be a number of pixels (example: \`20px\`) or a percentage of the element (example: \`5%\`).
Individual margins can be set using \`margin-top\`, \`margin-bottom\`, \`margin-right\`, and \`margin-left\`. These properties' values otherwise function the same as they do for \`margin\`.

**\`padding\`** - Sets padding between the outside of the box and the box's contents.

**\`font-size\`** - Sets the size of the font. Values can be in pixels (ex: \`14px\`), percentage of a parent element's size (example: \`150%\`), or size category (ex: \`xx-small\`).

**\`font-weight\`** - Sets the weight of the font. While you likely won't be using the values \`normal\` or \`bold\` often, because this can easily be handled through markdown syntax, values can be set to numbers, where the normal weight is 400 and the bold weight is 700.

## Inline Styles

There may be cases where you only need to use a certain style once,
and it therefore ends up being easier to use that style "inline" in the tag itself without calling a style.
As in an example above, you can do so like this:

\`\`\`
[div style:\\\`{property: 'value', property: 'value'}\\\`]Some text[/div]
\`\`\`

For example,

\`\`\`
[div style:\\\`{backgroundColor: 'green', padding: '20px'}\\\`]Some text[/div]
\`\`\`

The properties available are the same as those listed [above](#Properties) for CSS,
although any hyphenated properties have the hyphen removed and the second word capitalized
(e.g. \`font-size\` becomes \`fontSize\` when used with inline styling).

## Other Tags

Below are some other tags that you may find useful.

### Text Formatting

In the rare case that markdown's asterisks are proving difficult to use,
the \`[i]\` tag can be used to italicize text
and the \`[b]\` tag can be used to bold text.

To underline text, use the \`[u]\` tag.

Use \`[sup]\` to create superscripts and \`[sub]\` to create subscripts.

The \`[del]\` tag can be used to strikethrough.

#### Lists

Currently, markdown syntax in Idyll does not support multiple levels of lists.
HTML's list syntax, however, does allow sub-items in Idyll.
An HTML-style list can be made by:

1. Putting one of these tags at the front of the list:
    * \`[ol]\` to generate ordered lists, like the main one
    * \`[ul]\` to generate unordered lists, like this sub-list
    * (To nest lists, just put a new list where a list item would go!)
2. Putting the \`[li]\` tag before each list item (and \`[/li]\` after)
3. And putting closing the list with an \`[/ol]\` or \`[/ul]\` at the end.

To make the above example in Idyll (Indentation is optional):
~~~shell
An HTML-style list can be made by:
[ol]
  [li]Putting one of these tags at the front of the list:[/li]
  [ul]
    [li] \\\`[ol]\\\` to generate ordered lists, like the main one [/li]
    [li] \\\`[ul]\\\` to generate unordered lists, like this sub-list [/li]
    [li] (To nest lists, just put a new list where a list item would go!) [/li]
  [/ul]
  [li]Putting the \\\`[li]\\\` tag before each list item (and \\\`[/li]\\\` after) [/li]
  [li]And putting closing the list with an \\\`[/ol]\\\` (or \\\`[/ul]\\\`) at the end. [/li]
[/ol]
~~~

### Other Formatting

You can force a line
break with \`[br /]\`.

Make horizontal lines with \`[hr /]\`.

---

Both of these tags have a \`/\` at the end of them, indicating that they do not need a closing tag — just write \`[br /]\`, not \`[br /][/br]\`!
`;

export default ({ url }) => (
  <Layout
    url={url}
    title={'Idyll Documentation | Installation and Getting Started'}
  >
    <Content />
  </Layout>
);
<|endoftext|>


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

/**
 * # nodegame-client build script
 *
 */

/**
 * Export build
 */

module.exports.build = build;

var smoosh = require('smoosh'),
    path = require('path'),
    J = require('JSUS').JSUS;

var pkg = require('../package.json'),
    version = pkg.version;

function build(options) {

	if (!options.bare && !options.JSUS && !options.NDDB && !options.shelf && !options.all && !options.cycle) {
		options.standard = true;
	}

	var out = options.output || "nodegame-client";

	if (path.extname(out) === '.js') {
		out = path.basename(out, '.js');
	}

	console.log('Building nodeGame-client v.' + version + ' with:');

	// Defining variables

	var re = new RegExp('node_modules.+');

	var rootDir = path.resolve(__dirname, '..') + '/';
	var distDir =  rootDir + 'build/';

	// nodegame-client
	var ng_client = [
	 	rootDir + "index.js",
	 // lib
	 	rootDir + "lib/EventEmitter.js",
	 	rootDir + "lib/GameState.js",
	 	rootDir + "lib/PlayerList.js",
	 	rootDir + "lib/GameMsg.js",
	 	rootDir + "lib/GameLoop.js",
	 	rootDir + "lib/GameMsgGenerator.js",
	 	rootDir + "lib/GameSocketClient.js",
	 	rootDir + "lib/GameDB.js",
	 	rootDir + "lib/Game.js",
	 // nodeGame
	 	rootDir + "nodeGame.js",
	];

	// ng-addons
	var ng_addons = [
	 	rootDir + "addons/GameTimer.js",
	 	rootDir + "addons/TriggerManager.js",
	 	rootDir + "addons/GameSession.js",
	//  rootDir + "node_modules/nodegame-client/addons/WaitingRoom.js",
	];

	// jsus
	var JSUSdir = J.resolveModuleDir('JSUS');

	var ng_jsus = [
		JSUSdir + "jsus.js",
		JSUSdir + "lib/array.js",
		JSUSdir + "lib/dom.js",
		JSUSdir + "lib/eval.js",
		JSUSdir + "lib/obj.js",
		JSUSdir + "lib/random.js",
		JSUSdir + "lib/time.js",
		JSUSdir + "lib/parse.js",
	];

	// nddb
	var NDDBdir = J.resolveModuleDir('NDDB');
	var ng_nddb = [
		NDDBdir + "nddb.js",
	];

	// nodegame-window
	var ngWdir = J.resolveModuleDir('nodegame-window');

	var ng_window = [
		ngWdir + "GameWindow.js",
		ngWdir + "Canvas.js",
		ngWdir + "HTMLRenderer.js",
		ngWdir + "List.js",
		ngWdir + "Table.js",
	];

	// nodegame-widgets
	var ngWdgdir = J.resolveModuleDir('nodegame-widgets');

	var ng_widgets = [
		ngWdgdir + "ChernoffFaces.js",
		ngWdgdir + "Controls.js",
		ngWdgdir + "DataBar.js",
		ngWdgdir + "DynamicTable.js",
		ngWdgdir + "EventButton.js",
		ngWdgdir + "GameBoard.js",
		ngWdgdir + "GameSummary.js",
		ngWdgdir + "GameTable.js",
		ngWdgdir + "MsgBar.js",
		ngWdgdir + "NDDBBrowser.js",
		ngWdgdir + "NextPreviousState.js",
		ngWdgdir + "ServerInfoDisplay.js",
		ngWdgdir + "StateBar.js",
		ngWdgdir + "StateDisplay.js",
		ngWdgdir + "VisualState.js",
		ngWdgdir + "VisualTimer.js",
		ngWdgdir + "WaitScreen.js",
		ngWdgdir + "Wall.js",
		ngWdgdir + "MoneyTalks.js",
	];

	// es5-shim

	// es5-shim
	var es5Dir = J.resolveModuleDir('es5-shim');
	var ng_es5 = [
	  es5Dir + "es5-shim.js",
	];

	//shelf.js
	var shelfDir = J.resolveModuleDir('shelf.js');
	var ng_shelf = [
	  shelfDir + "/build/shelf.js",
	];

	// CREATING build array
	var files = [];

	// 0. ES5-shim
	if (options.es5 || options.all) {
		if (!path.existsSync(es5Dir)) {
			console.log('  - ERR: es5-shim not found!');
		}
		else {
			console.log('  - es5-shim');
			files = files.concat(ng_es5);
		}

	}

	// 0. Shelf.js
	if (options.shelf || options.all) {
		if (!path.existsSync(shelfDir)) {
			console.log('  - ERR: shelf.js not found!');
		}
		else {
			var shelfjs = shelfDir + 'build/shelf.js';
			// Build custom shelf.js if not existing
			if (!path.existsSync(shelfjs)) {
				var shelfjs_build = shelfDir + 'bin/build.js';
				console.log("\n  - building custom shelf.js")
				var buildShelf = require(shelfjs_build);
				buildShelf.build({cycle: true});
			}

			console.log('  - shelf.js');
			files = files.concat(ng_shelf);
		}
	}

	// 1. JSUS
	if (options.JSUS || options.all || options.standard) {
		console.log('  - JSUS');
		files = files.concat(ng_jsus);
	}

	// 2. NDDB
	if (options.NDDB || options.all || options.standard) {
		console.log('  - NDDB');
		files = files.concat(ng_nddb);
	}

	// 3. nodegame-client core: always built
	console.log('  - nodegame-client core');
	files = files.concat(ng_client);

	// 4. nodegame-client addons
	if (options.addons || options.all || options.standard) {
		console.log('  - nodegame-client addons');
		files = files.concat(ng_addons);
	}

	// 5. nodegame-window
	if (options.window || options.all) {
		if (!path.existsSync(ngWdir)) {
			console.log('  - ERR: nodegame-window not found!');
		}
		else {
			console.log('  - nodegame-window');
			files = files.concat(ng_window);
		}

	}

	//5. nodegame-widgets
	if (options.widgets || options.all) {
		if (!path.existsSync(ngWdgdir)) {
			console.log('  - ERR: nodegame-widgets not found!');
		}
		else {
			console.log('  - nodegame-widgets');
			files = files.concat(ng_widgets);
		}
	}

	console.log("\n");

	// Configurations for file smooshing.
	var config = {
	    // VERSION : "0.0.1",

	    // Use JSHINT to spot code irregularities.
	    JSHINT_OPTS: {
	        boss: true,
	        forin: true,
	        browser: true,
	    },

	    JAVASCRIPT: {
	        DIST_DIR: '/' + distDir,
	    }
	};

	config.JAVASCRIPT[out] = files;

	var run_it = function(){
	    // https://github.com/fat/smoosh
		// hand over configurations made above
	    var smooshed = smoosh.config(config);

	    // removes all files from the build folder
	    if (options.clean) {
	    	smooshed.clean();
	    }

	    // builds both uncompressed and compressed files
	    smooshed.build();

    	if (options.analyse) {
    		smooshed.run(); // runs jshint on full build
    		smooshed.analyze(); // analyzes everything
    	}

	    console.log('nodeGame-client build created!');
	}

	run_it();
}<commit_msg>resolve with basedir<commit_after>#!/usr/bin/env node

/**
 * # nodegame-client build script
 *
 */

/**
 * Export build
 */

module.exports.build = build;

var smoosh = require('smoosh'),
    path = require('path'),
    J = require('JSUS').JSUS;

var pkg = require('../package.json'),
    version = pkg.version;

function build(options) {

	if (!options.bare && !options.JSUS && !options.NDDB && !options.shelf && !options.all && !options.cycle) {
		options.standard = true;
	}

	var out = options.output || "nodegame-client";

	if (path.extname(out) === '.js') {
		out = path.basename(out, '.js');
	}

	console.log('Building nodeGame-client v.' + version + ' with:');

	// Defining variables

	var re = new RegExp('node_modules.+');

	var rootDir = path.resolve(__dirname, '..') + '/';
	var distDir =  rootDir + 'build/';

	// nodegame-client
	var ng_client = [
	 	rootDir + "index.js",
	 // lib
	 	rootDir + "lib/EventEmitter.js",
	 	rootDir + "lib/GameState.js",
	 	rootDir + "lib/PlayerList.js",
	 	rootDir + "lib/GameMsg.js",
	 	rootDir + "lib/GameLoop.js",
	 	rootDir + "lib/GameMsgGenerator.js",
	 	rootDir + "lib/GameSocketClient.js",
	 	rootDir + "lib/GameDB.js",
	 	rootDir + "lib/Game.js",
	 // nodeGame
	 	rootDir + "nodeGame.js",
	];

	// ng-addons
	var ng_addons = [
	 	rootDir + "addons/GameTimer.js",
	 	rootDir + "addons/TriggerManager.js",
	 	rootDir + "addons/GameSession.js",
	//  rootDir + "node_modules/nodegame-client/addons/WaitingRoom.js",
	];

	// jsus
	var JSUSdir = J.resolveModuleDir('JSUS');

	var ng_jsus = [
		JSUSdir + "jsus.js",
		JSUSdir + "lib/array.js",
		JSUSdir + "lib/dom.js",
		JSUSdir + "lib/eval.js",
		JSUSdir + "lib/obj.js",
		JSUSdir + "lib/random.js",
		JSUSdir + "lib/time.js",
		JSUSdir + "lib/parse.js",
	];

	// nddb
	var NDDBdir = J.resolveModuleDir('NDDB', __dirname);
	var ng_nddb = [
		NDDBdir + "nddb.js",
	];

	// nodegame-window
	var ngWdir = J.resolveModuleDir('nodegame-window', __dirname);

	var ng_window = [
		ngWdir + "GameWindow.js",
		ngWdir + "Canvas.js",
		ngWdir + "HTMLRenderer.js",
		ngWdir + "List.js",
		ngWdir + "Table.js",
	];

	// nodegame-widgets
	var ngWdgdir = J.resolveModuleDir('nodegame-widgets', __dirname);

	var ng_widgets = [
		ngWdgdir + "ChernoffFaces.js",
		ngWdgdir + "Controls.js",
		ngWdgdir + "DataBar.js",
		ngWdgdir + "DynamicTable.js",
		ngWdgdir + "EventButton.js",
		ngWdgdir + "GameBoard.js",
		ngWdgdir + "GameSummary.js",
		ngWdgdir + "GameTable.js",
		ngWdgdir + "MsgBar.js",
		ngWdgdir + "NDDBBrowser.js",
		ngWdgdir + "NextPreviousState.js",
		ngWdgdir + "ServerInfoDisplay.js",
		ngWdgdir + "StateBar.js",
		ngWdgdir + "StateDisplay.js",
		ngWdgdir + "VisualState.js",
		ngWdgdir + "VisualTimer.js",
		ngWdgdir + "WaitScreen.js",
		ngWdgdir + "Wall.js",
		ngWdgdir + "MoneyTalks.js",
	];

	// es5-shim

	// es5-shim
	var es5Dir = J.resolveModuleDir('es5-shim',__dirname);
	var ng_es5 = [
	  es5Dir + "es5-shim.js",
	];

	//shelf.js
	var shelfDir = J.resolveModuleDir('shelf.js', __dirname);
	var ng_shelf = [
	  shelfDir + "/build/shelf.js",
	];

	// CREATING build array
	var files = [];

	// 0. ES5-shim
	if (options.es5 || options.all) {
		if (!path.existsSync(es5Dir)) {
			console.log('  - ERR: es5-shim not found!');
		}
		else {
			console.log('  - es5-shim');
			files = files.concat(ng_es5);
		}

	}

	// 0. Shelf.js
	if (options.shelf || options.all) {
		if (!path.existsSync(shelfDir)) {
			console.log('  - ERR: shelf.js not found!');
		}
		else {
			var shelfjs = shelfDir + 'build/shelf.js';
			// Build custom shelf.js if not existing
			if (!path.existsSync(shelfjs)) {
				var shelfjs_build = shelfDir + 'bin/build.js';
				console.log("\n  - building custom shelf.js")
				var buildShelf = require(shelfjs_build);
				buildShelf.build({cycle: true});
			}

			console.log('  - shelf.js');
			files = files.concat(ng_shelf);
		}
	}

	// 1. JSUS
	if (options.JSUS || options.all || options.standard) {
		console.log('  - JSUS');
		files = files.concat(ng_jsus);
	}

	// 2. NDDB
	if (options.NDDB || options.all || options.standard) {
		console.log('  - NDDB');
		files = files.concat(ng_nddb);
	}

	// 3. nodegame-client core: always built
	console.log('  - nodegame-client core');
	files = files.concat(ng_client);

	// 4. nodegame-client addons
	if (options.addons || options.all || options.standard) {
		console.log('  - nodegame-client addons');
		files = files.concat(ng_addons);
	}

	// 5. nodegame-window
	if (options.window || options.all) {
		if (!path.existsSync(ngWdir)) {
			console.log('  - ERR: nodegame-window not found!');
		}
		else {
			console.log('  - nodegame-window');
			files = files.concat(ng_window);
		}

	}

	//5. nodegame-widgets
	if (options.widgets || options.all) {
		if (!path.existsSync(ngWdgdir)) {
			console.log('  - ERR: nodegame-widgets not found!');
		}
		else {
			console.log('  - nodegame-widgets');
			files = files.concat(ng_widgets);
		}
	}

	console.log("\n");

	// Configurations for file smooshing.
	var config = {
	    // VERSION : "0.0.1",

	    // Use JSHINT to spot code irregularities.
	    JSHINT_OPTS: {
	        boss: true,
	        forin: true,
	        browser: true,
	    },

	    JAVASCRIPT: {
	        DIST_DIR: '/' + distDir,
	    }
	};

	config.JAVASCRIPT[out] = files;

	var run_it = function(){
	    // https://github.com/fat/smoosh
		// hand over configurations made above
	    var smooshed = smoosh.config(config);

	    // removes all files from the build folder
	    if (options.clean) {
	    	smooshed.clean();
	    }

	    // builds both uncompressed and compressed files
	    smooshed.build();

    	if (options.analyse) {
    		smooshed.run(); // runs jshint on full build
    		smooshed.analyze(); // analyzes everything
    	}

	    console.log('nodeGame-client build created!');
	}

	run_it();
}<|endoftext|>