<commit_before>/**
* Copyright 2012 Microsoft Corporation
*
* 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.
*/

/**
* Copyright 2012 Microsoft Corporation
*
* 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.
*/

var should = require('should');
var cli = require('../cli');
var capture = require('../util').capture;

var siteName1 = 'cliuttestsiteconfig1';
var siteName2 = 'cliuttestsiteconfig2';

var siteNames = [ siteName1, siteName2 ];

suite('cli', function(){
  suite('siteconfig', function() {
    setup(function (done) {

      var removeSites = function (sites, cb) {
        if (sites.length === 0) {
          cb();
        } else {
          var siteName = sites.pop();
          // Delete created site
          var cmd = ('node cli.js site delete ' + siteName + ' --json --quiet').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            removeSites(sites, cb);
          });
        }
      };

      // List sites
      var cmd = ('node cli.js site list --json').split(' ');
      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        var siteList = JSON.parse(result.text);
        var filteredSites = siteNames.filter(function (site) {
          return siteList.some(function (s) {
            return site === s.Name;
          });
        });

        removeSites(filteredSites, done);
      });
    });

    test('siteconfig list', function(done) {
      // Create site
      var cmd = ('node cli.js site create ' + siteName1 + ' --json --location').split(' ');
      cmd.push('East US');

      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        result.text.should.equal('');
        result.exitStatus.should.equal(0);

        // List sites
        cmd = ('node cli.js site config list ' + siteName1 + ' --json ').split(' ');
        capture(function() {
          cli.parse(cmd);
        }, function (result) {
          // there should be not settings yet as the site was just created
          result.text.should.equal('');
          result.exitStatus.should.equal(0);

          // add a setting
          var cmd = ('node cli.js site config add mysetting=myvalue ' + siteName1 + ' --json').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            result.text.should.equal('');
            result.exitStatus.should.equal(0);

            cmd = ('node cli.js site config list ' + siteName1 + ' --json').split(' ');
            capture(function() {
              cli.parse(cmd);
            }, function (result) {
              var settingsList = JSON.parse(result.text);

              // Listing should return 1 setting now
              settingsList.length.should.equal(1);

              // add another setting
              var cmd = ('node cli.js site config add mysetting2=myvalue ' + siteName1 + ' --json').split(' ');
              capture(function() {
                cli.parse(cmd);
              }, function (result) {
                result.text.should.equal('');
                result.exitStatus.should.equal(0);

                cmd = ('node cli.js site config list ' + siteName1 + ' --json').split(' ');
                capture(function() {
                  cli.parse(cmd);
                }, function (result) {
                  var settingsList = JSON.parse(result.text);

                  // Listing should return 2 setting now
                  settingsList.length.should.equal(2);

                  done();
                });
              });
            });
          });
        });
      });
    });

    test('siteconfig add get clear', function(done) {
      var siteName = 'cliuttestsiteconfig2';

      // Create site
      var cmd = ('node cli.js site create ' + siteName2 + ' --json --location').split(' ');
      cmd.push('East US');

      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        result.text.should.equal('');
        result.exitStatus.should.equal(0);

        // List sites
        cmd = ('node cli.js site config list ' + siteName2 + ' --json ').split(' ');
        capture(function() {
          cli.parse(cmd);
        }, function (result) {
          // there should be not settings yet as the site was just created
          result.text.should.equal('');
          result.exitStatus.should.equal(0);

          // add a setting
          var cmd = ('node cli.js site config add mysetting=myvalue ' + siteName2 + ' --json').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            result.text.should.equal('');
            result.exitStatus.should.equal(0);

            cmd = ('node cli.js site config get mysetting ' + siteName2 + ' --json').split(' ');
            capture(function() {
              cli.parse(cmd);
            }, function (result) {
              result.text.should.equal('"myvalue"\n');
              result.exitStatus.should.equal(0);

              // add another setting
              var cmd = ('node cli.js site config clear mysetting ' + siteName2 + ' --json').split(' ');
              capture(function() {
                cli.parse(cmd);
              }, function (result) {
                result.text.should.equal('');
                result.exitStatus.should.equal(0);

                cmd = ('node cli.js site config list ' + siteName2 + ' --json').split(' ');
                capture(function() {
                  cli.parse(cmd);
                }, function (result) {
                  result.text.should.equal('');
                  result.exitStatus.should.equal(0);

                  done();
                });
              });
            });
          });
        });
      });
    });
  });
});<commit_msg>Removing dead code.<commit_after>/**
* Copyright 2012 Microsoft Corporation
*
* 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.
*/

var should = require('should');
var cli = require('../cli');
var capture = require('../util').capture;

var siteName1 = 'cliuttestsiteconfig1';
var siteName2 = 'cliuttestsiteconfig2';

var siteNames = [ siteName1, siteName2 ];

suite('cli', function(){
  suite('siteconfig', function() {
    setup(function (done) {

      var removeSites = function (sites, cb) {
        if (sites.length === 0) {
          cb();
        } else {
          var siteName = sites.pop();
          // Delete created site
          var cmd = ('node cli.js site delete ' + siteName + ' --json --quiet').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            removeSites(sites, cb);
          });
        }
      };

      // List sites
      var cmd = ('node cli.js site list --json').split(' ');
      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        var siteList = JSON.parse(result.text);
        var filteredSites = siteNames.filter(function (site) {
          return siteList.some(function (s) {
            return site === s.Name;
          });
        });

        removeSites(filteredSites, done);
      });
    });

    test('siteconfig list', function(done) {
      // Create site
      var cmd = ('node cli.js site create ' + siteName1 + ' --json --location').split(' ');
      cmd.push('East US');

      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        result.text.should.equal('');
        result.exitStatus.should.equal(0);

        // List sites
        cmd = ('node cli.js site config list ' + siteName1 + ' --json ').split(' ');
        capture(function() {
          cli.parse(cmd);
        }, function (result) {
          // there should be not settings yet as the site was just created
          result.text.should.equal('');
          result.exitStatus.should.equal(0);

          // add a setting
          var cmd = ('node cli.js site config add mysetting=myvalue ' + siteName1 + ' --json').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            result.text.should.equal('');
            result.exitStatus.should.equal(0);

            cmd = ('node cli.js site config list ' + siteName1 + ' --json').split(' ');
            capture(function() {
              cli.parse(cmd);
            }, function (result) {
              var settingsList = JSON.parse(result.text);

              // Listing should return 1 setting now
              settingsList.length.should.equal(1);

              // add another setting
              var cmd = ('node cli.js site config add mysetting2=myvalue ' + siteName1 + ' --json').split(' ');
              capture(function() {
                cli.parse(cmd);
              }, function (result) {
                result.text.should.equal('');
                result.exitStatus.should.equal(0);

                cmd = ('node cli.js site config list ' + siteName1 + ' --json').split(' ');
                capture(function() {
                  cli.parse(cmd);
                }, function (result) {
                  var settingsList = JSON.parse(result.text);

                  // Listing should return 2 setting now
                  settingsList.length.should.equal(2);

                  done();
                });
              });
            });
          });
        });
      });
    });

    test('siteconfig add get clear', function(done) {
      // Create site
      var cmd = ('node cli.js site create ' + siteName2 + ' --json --location').split(' ');
      cmd.push('East US');

      capture(function() {
        cli.parse(cmd);
      }, function (result) {
        result.text.should.equal('');
        result.exitStatus.should.equal(0);

        // List sites
        cmd = ('node cli.js site config list ' + siteName2 + ' --json ').split(' ');
        capture(function() {
          cli.parse(cmd);
        }, function (result) {
          // there should be not settings yet as the site was just created
          result.text.should.equal('');
          result.exitStatus.should.equal(0);

          // add a setting
          var cmd = ('node cli.js site config add mysetting=myvalue ' + siteName2 + ' --json').split(' ');
          capture(function() {
            cli.parse(cmd);
          }, function (result) {
            result.text.should.equal('');
            result.exitStatus.should.equal(0);

            cmd = ('node cli.js site config get mysetting ' + siteName2 + ' --json').split(' ');
            capture(function() {
              cli.parse(cmd);
            }, function (result) {
              result.text.should.equal('"myvalue"\n');
              result.exitStatus.should.equal(0);

              // add another setting
              var cmd = ('node cli.js site config clear mysetting ' + siteName2 + ' --json').split(' ');
              capture(function() {
                cli.parse(cmd);
              }, function (result) {
                result.text.should.equal('');
                result.exitStatus.should.equal(0);

                cmd = ('node cli.js site config list ' + siteName2 + ' --json').split(' ');
                capture(function() {
                  cli.parse(cmd);
                }, function (result) {
                  result.text.should.equal('');
                  result.exitStatus.should.equal(0);

                  done();
                });
              });
            });
          });
        });
      });
    });
  });
});<|endoftext|>


<commit_before>// Demonstation of integration
var oauthshim = require('oauth-shim'),
    express = require('express'),
    request = require('request');
var config = require('../custom_configFile.json');
if (!config.twitterConsumerKey || !config.twitterConsumerSecret || !config.twitterCallbackUrl) {
    config.twitterConsumerKey = "placeholder";
    config.twitterConsumerSecret = "placeholder";
    config.twitterCallbackUrl = "placeholder";
}
var app = express();

// Set application to list on PORT
app.listen(config.oauthProxyPort);

console.log("OAuth Shim listening on " + config.oauthProxyPort);

// Create a key value list of {client_id => client_secret, ...}
var creds = {};

// Set credentials
creds[config.twitterConsumerKey] = config.twitterConsumerSecret;

// Initiate the shim with Client ID's and secret, e.g.
oauthshim.init(creds);

// Define a path where to put this OAuth Shim
app.all('/oauthproxy',
    oauthshim.interpret,
    customHandler,
    oauthshim.proxy,
    oauthshim.redirect,
    oauthshim.unhandled);

function customHandler(req, res, next) {

    // Check that this is a login redirect with an access_token (not a RESTful API call via proxy)
    if (req.oauthshim &&
        req.oauthshim.redirect &&
        req.oauthshim.data &&
        req.oauthshim.data.access_token &&
        req.oauthshim.options &&
        !req.oauthshim.options.path) {
        //The access token is of the form "oauth_token:oauth_token_secret@app_id". Need to separate
        var splitted = req.oauthshim.data.access_token.split(":");
        var oauth_token = splitted[0];
        var oauth_token_secret = splitted[1].split("@")[0];
        var userObject = {};
        userObject['screen_name'] = req.oauthshim.data.screen_name;
        userObject['oauth_token'] = oauth_token;
        userObject['oauth_token_secret'] = oauth_token_secret;
        userObject['source_type'] = "TWITTER";
        var requestJSON = JSON.stringify(userObject);
        console.log(requestJSON);
        //got it. Now send to backend
        request(config.apiUrl + 'account.json?action=update&data=' + requestJSON, function(error, response, body) {
            console.log(requestJSON);
            if (!error && response.statusCode == 200) {
                console.log("user saved");
            } else {
                console.log("The user was not saved in loklak_server. Handle this error");
            }
        });
    }

    // Call next to complete the operation
    next();
}
<commit_msg>Updated oauth-proxy to send user details to localhost everytime<commit_after>// Demonstation of integration
var oauthshim = require('oauth-shim'),
    express = require('express'),
    request = require('request');
var config = require('../custom_configFile.json');
if (!config.twitterConsumerKey || !config.twitterConsumerSecret || !config.twitterCallbackUrl) {
    config.twitterConsumerKey = "placeholder";
    config.twitterConsumerSecret = "placeholder";
    config.twitterCallbackUrl = "placeholder";
}
var app = express();

// Set application to list on PORT
app.listen(config.oauthProxyPort);

console.log("OAuth Shim listening on " + config.oauthProxyPort);

// Create a key value list of {client_id => client_secret, ...}
var creds = {};

// Set credentials
creds[config.twitterConsumerKey] = config.twitterConsumerSecret;

// Initiate the shim with Client ID's and secret, e.g.
oauthshim.init(creds);

// Define a path where to put this OAuth Shim
app.all('/oauthproxy',
    oauthshim.interpret,
    customHandler,
    oauthshim.proxy,
    oauthshim.redirect,
    oauthshim.unhandled);

function customHandler(req, res, next) {

    // Check that this is a login redirect with an access_token (not a RESTful API call via proxy)
    if (req.oauthshim &&
        req.oauthshim.redirect &&
        req.oauthshim.data &&
        req.oauthshim.data.access_token &&
        req.oauthshim.options &&
        !req.oauthshim.options.path) {
        //The access token is of the form "oauth_token:oauth_token_secret@app_id". Need to separate
        var splitted = req.oauthshim.data.access_token.split(":");
        var oauth_token = splitted[0];
        var oauth_token_secret = splitted[1].split("@")[0];
        var userObject = {};
        userObject['screen_name'] = req.oauthshim.data.screen_name;
        userObject['oauth_token'] = oauth_token;
        userObject['oauth_token_secret'] = oauth_token_secret;
        userObject['source_type'] = "TWITTER";
        var requestJSON = JSON.stringify(userObject);
        console.log(requestJSON);
        //got it. Now send to backend
        request('http://localhost:9000/api/account.json?action=update&data=' + requestJSON, function(error, response, body) {
            console.log(requestJSON);
            if (!error && response.statusCode == 200) {
                console.log("user saved");
            } else {
                console.log("The user was not saved in loklak_server. Handle this error");
            }
        });
    }

    // Call next to complete the operation
    next();
}
<|endoftext|>


<commit_before>/*global describe, it*/
var expect = require('../unexpected-with-plugins'),
    AssetGraph = require('../../lib/AssetGraph');

describe('relations/HtmlApplicationManifest', function () {
    it('should handle a test case with an existing <link rel="manifest">', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate()
            .queue(function (assetGraph) {
                expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 1);
                expect(assetGraph, 'to contain assets', 'ApplicationManifest', 1);
            })
            .run(done);
    });

    it('should read the link href correctly', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate()
            .queue(function (assetGraph) {
                var relation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

                expect(relation, 'to satisfy', {
                    href: 'manifest.json'
                });
            })
            .run(done);
    });

    it('should write the link href correctly', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate()
            .queue(function (assetGraph) {
                var relation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

                relation.to.url = 'foo.json';

                expect(relation, 'to satisfy', {
                    href: 'foo.json'
                });

                relation.href = 'bar.json';

                expect(relation, 'to satisfy', {
                    href: 'bar.json'
                });
            })
            .run(done);
    });

    it('should append <link rel="manifest"> to a containing document', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate()
            .queue(function (assetGraph) {
                const html = assetGraph.findAssets({ type: 'Html' })[0];
                const adjacentRelation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

                html.addRelation({
                    type: 'HtmlApplicationManifest',
                    to: new AssetGraph.ApplicationManifest({
                        url: 'attach.json',
                        text: '{"name":"attach"}'
                    })
                }, 'before', adjacentRelation);

                expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 2);
            })
            .run(done);
    });

    it('should warn when there are multiple application manifests linked from the same document', function (done) {
        var html = new AssetGraph.Html({
            text: '<link rel="manifest" href="manifest.json"><link rel="manifest" href="manifest.json">'
        });

        var warns = [];

        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .on('warn', function (warning) {
                warns.push(warning);
            })
            .loadAssets(html)
            .populate()
            .queue(function (assetGraph) {
                expect(warns, 'to satisfy', [
                    {
                        message: /^Multiple ApplicationManifest relations/
                    }
                ]);
            })
            .run(done);
    });
});
<commit_msg>es6ify/simplify the HtmlApplicationManifest test [ci skip]<commit_after>/*global describe, it*/
const expect = require('../unexpected-with-plugins');
const AssetGraph = require('../../lib/AssetGraph');
const sinon = require('sinon');

describe('relations/HtmlApplicationManifest', function () {
    it('should handle a test case with an existing <link rel="manifest">', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate();

        expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 1);
        expect(assetGraph, 'to contain assets', 'ApplicationManifest', 1);
    });

    it('should read the link href correctly', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate();

        const relation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

        expect(relation, 'to satisfy', { href: 'manifest.json' });
    });

    it('should write the link href correctly', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate();

        const relation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

        relation.to.url = 'foo.json';

        expect(relation, 'to satisfy', { href: 'foo.json' });

        relation.href = 'bar.json';

        expect(relation, 'to satisfy', { href: 'bar.json' });
    });

    it('should append <link rel="manifest"> to a containing document', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .loadAssets('index.html')
            .populate();

        const html = assetGraph.findAssets({ type: 'Html' })[0];
        const adjacentRelation = assetGraph.findRelations({ type: 'HtmlApplicationManifest' })[0];

        html.addRelation({
            type: 'HtmlApplicationManifest',
            to: {
                type: 'ApplicationManifest',
                url: 'attach.json',
                parseTree: { name: 'attach' }
            }
        }, 'before', adjacentRelation);

        expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 2);
    });

    it('should warn when there are multiple application manifests linked from the same document', async function () {
        const warnSpy = sinon.spy().named('warn');

        await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlApplicationManifest/'})
            .on('warn', warnSpy)
            .loadAssets({
                type: 'Html',
                text: '<link rel="manifest" href="manifest.json"><link rel="manifest" href="manifest.json">'
            })
            .populate();

        expect(warnSpy, 'to have calls satisfying', () => {
            warnSpy({message: /^Multiple ApplicationManifest relations/});
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

import chai, { expect } from 'chai';
import sinon from 'sinon';
import { default as sinonChai } from 'sinon-chai';
import Installer from 'browser/model/helpers/installer';
import mockfs from 'mock-fs';
import path from 'path';
import Logger from 'browser/services/logger';
import fs from 'fs-extra';
import child_process from 'child_process';
import unzip from 'unzip';
chai.use(sinonChai);

describe('Installer', function() {
  let sandbox;
  let infoStub, errorStub;

  let fakeProgress = {
    setStatus: function () {},
    setCurrent: function () {},
    setLabel: function () {},
    setComplete: function() {},
    setTotalDownloadSize: function() {},
    downloaded: function() {}
  };
  let failureCallback = (err) => { return err; };
  let installer = new Installer('test', fakeProgress, () => { return 'success'; }, failureCallback);

  before(function() {
    infoStub = sinon.stub(Logger, 'info');
    errorStub = sinon.stub(Logger, 'error');

    mockfs({
      someTempFolder: {
        somefile: 'empty'
      },
      anInstallFolder: {}
    }, {
      createCwd: false,
      createTmp: false
    });
  });

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  after(function() {
    infoStub.restore();
    errorStub.restore();
    mockfs.restore();
  });

  describe('exec', function() {
    let command = 'command';
    let args = ['arg1', 'arg2', 'arg3'];

    it('should call child_process#exec with the correct parameters', function() {
      let stub = sandbox.stub(child_process, 'exec').yields();

      return installer.exec(command, args)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(command, args);
      });
    });

    it('should resolve as true if no error occurs', function() {
      sandbox.stub(child_process, 'exec').yields(undefined, 'stdout', 'stderr');
      infoStub.reset();
      return installer.exec(command, args)
      .then(function(result) {
        expect(result).to.equal(true);
        expect(infoStub).to.be.calledWith('test - stdout');
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(child_process, 'exec').yields(err);

      return installer.exec(command, args)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('execFile', function() {
    let args = ['arg1', 'arg2', 'arg3'];
    let file = path.join('someTempFolder', 'somefile');

    it('should call child_process#execFile with the correct parameters', function() {
      let stub = sandbox.stub(child_process, 'execFile').yields();

      return installer.execFile(file, args)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(file, args);
      });
    });

    it('should resolve as true if no error occurs' , function() {
      let stub = sandbox.stub(child_process, 'execFile').yields(undefined, 'stdout', 'stderr');
      infoStub.reset();

      return installer.execFile(file, args)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(child_process, 'execFile').yields(err);

      return installer.execFile(file, args)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('unzip', function() {
    let dir = 'anInstallFolder';
    let file = path.join('someTempFolder', 'somefile');

    it('should read the specified file', function() {
      sandbox.stub(unzip, 'Extract').throws('done');
      let spy = sandbox.spy(fs, 'createReadStream');

      return installer.unzip(file, dir)
      .catch(function() {
        expect(spy).to.have.been.calledOnce;
        expect(spy).to.have.been.calledWith(file);
      });
    });

    it('should call unzip#Extract into a correct folder', function() {
      let stub = sandbox.stub(unzip, 'Extract').throws('done');

      return installer.unzip(file, dir)
      .catch(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith({ path: dir });
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(unzip, 'Extract').throws(err);

      return installer.unzip(file, dir)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('moveFile', function() {
    let source = path.join('.', 'someTempFolder', 'somefile');
    let target = path.join('anInstallFolder', 'target');

    it('should call fs#move with correct arguments', function() {
      let stub = sandbox.stub(fs, 'move').yields();

      return installer.moveFile(source, target)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(source, target);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'move').yields();

      return installer.moveFile(source, target)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'move').yields(err);

      return installer.moveFile(source, target)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('copyFile', function() {
    let source = path.join('.', 'someTempFolder', 'somefile');
    let target = path.join('anInstallFolder', 'target');

    it('should call fs#copy with correct arguments', function() {
      let stub = sandbox.stub(fs, 'copy').yields();

      return installer.copyFile(source, target)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(source, target);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'copy').yields();

      return installer.copyFile(source, target)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'copy').yields(err);

      return installer.copyFile(source, target)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('writeFile', function() {
    let file = path.join('someTempFolder', 'somefile');
    let data = 'data';

    it('should call fs#writeFile with correct arguments', function() {
      let stub = sandbox.stub(fs, 'writeFile').yields();

      return installer.writeFile(file, data)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(file, data);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'writeFile').yields();

      return installer.writeFile(file, data)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'writeFile').yields(err);

      return installer.writeFile(file, data)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('succeed', function() {
    it('should set progress to complete when the input is truthy', function() {
      let spy = sandbox.spy(fakeProgress, 'setComplete');
      installer.succeed(true);

      expect(spy).to.have.been.calledOnce;
    });

    it('should not succeed with a falsey input', function() {
      let spy = sandbox.spy(fakeProgress, 'setComplete');
      installer.succeed(false);

      expect(spy).to.have.not.been.called;
    });
  });

  describe('fail', function() {
    it('should set progress to Failed', function() {
      let spy = sandbox.spy(fakeProgress, 'setStatus');
      installer.fail(new Error('Failed'));

      expect(spy).to.have.been.calledOnce;
      expect(spy).to.have.been.calledWith('Failed');
    });

    it('should call the fail callback with the error', function() {
      let err = new Error('Failed');
      let spy = sandbox.spy(installer, 'failure');
      installer.fail(err);

      expect(spy).to.have.been.calledOnce;
      expect(spy).to.have.been.calledWith(err);
    });
  });
});
<commit_msg>Clean up eslint violations in installer-test.js<commit_after>'use strict';

import chai, { expect } from 'chai';
import sinon from 'sinon';
import { default as sinonChai } from 'sinon-chai';
import Installer from 'browser/model/helpers/installer';
import mockfs from 'mock-fs';
import path from 'path';
import Logger from 'browser/services/logger';
import fs from 'fs-extra';
import child_process from 'child_process';
import unzip from 'unzip';
chai.use(sinonChai);

describe('Installer', function() {
  let sandbox;
  let infoStub, errorStub;

  let fakeProgress = {
    setStatus: function () {},
    setCurrent: function () {},
    setLabel: function () {},
    setComplete: function() {},
    setTotalDownloadSize: function() {},
    downloaded: function() {}
  };
  let failureCallback = (err) => { return err; };
  let installer = new Installer('test', fakeProgress, () => { return 'success'; }, failureCallback);

  before(function() {
    infoStub = sinon.stub(Logger, 'info');
    errorStub = sinon.stub(Logger, 'error');

    mockfs({
      someTempFolder: {
        somefile: 'empty'
      },
      anInstallFolder: {}
    }, {
      createCwd: false,
      createTmp: false
    });
  });

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  after(function() {
    infoStub.restore();
    errorStub.restore();
    mockfs.restore();
  });

  describe('exec', function() {
    let command = 'command';
    let args = ['arg1', 'arg2', 'arg3'];

    it('should call child_process#exec with the correct parameters', function() {
      let stub = sandbox.stub(child_process, 'exec').yields();

      return installer.exec(command, args)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(command, args);
      });
    });

    it('should resolve as true if no error occurs', function() {
      sandbox.stub(child_process, 'exec').yields(undefined, 'stdout', 'stderr');
      infoStub.reset();
      return installer.exec(command, args)
      .then(function(result) {
        expect(result).to.equal(true);
        expect(infoStub).to.be.calledWith('test - stdout');
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(child_process, 'exec').yields(err);

      return installer.exec(command, args)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('execFile', function() {
    let args = ['arg1', 'arg2', 'arg3'];
    let file = path.join('someTempFolder', 'somefile');

    it('should call child_process#execFile with the correct parameters', function() {
      let stub = sandbox.stub(child_process, 'execFile').yields();

      return installer.execFile(file, args)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(file, args);
      });
    });

    it('should resolve as true if no error occurs', function() {
      sandbox.stub(child_process, 'execFile').yields(undefined, 'stdout', 'stderr');
      infoStub.reset();
      return installer.execFile(file, args)
      .then(function(result) {
        expect(result).to.equal(true);
        expect(infoStub).to.be.calledWith('test - stdout');
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(child_process, 'execFile').yields(err);

      return installer.execFile(file, args)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('unzip', function() {
    let dir = 'anInstallFolder';
    let file = path.join('someTempFolder', 'somefile');

    it('should read the specified file', function() {
      sandbox.stub(unzip, 'Extract').throws('done');
      let spy = sandbox.spy(fs, 'createReadStream');

      return installer.unzip(file, dir)
      .catch(function() {
        expect(spy).to.have.been.calledOnce;
        expect(spy).to.have.been.calledWith(file);
      });
    });

    it('should call unzip#Extract into a correct folder', function() {
      let stub = sandbox.stub(unzip, 'Extract').throws('done');

      return installer.unzip(file, dir)
      .catch(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith({ path: dir });
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(unzip, 'Extract').throws(err);

      return installer.unzip(file, dir)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('moveFile', function() {
    let source = path.join('.', 'someTempFolder', 'somefile');
    let target = path.join('anInstallFolder', 'target');

    it('should call fs#move with correct arguments', function() {
      let stub = sandbox.stub(fs, 'move').yields();

      return installer.moveFile(source, target)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(source, target);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'move').yields();

      return installer.moveFile(source, target)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'move').yields(err);

      return installer.moveFile(source, target)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('copyFile', function() {
    let source = path.join('.', 'someTempFolder', 'somefile');
    let target = path.join('anInstallFolder', 'target');

    it('should call fs#copy with correct arguments', function() {
      let stub = sandbox.stub(fs, 'copy').yields();

      return installer.copyFile(source, target)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(source, target);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'copy').yields();

      return installer.copyFile(source, target)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'copy').yields(err);

      return installer.copyFile(source, target)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('writeFile', function() {
    let file = path.join('someTempFolder', 'somefile');
    let data = 'data';

    it('should call fs#writeFile with correct arguments', function() {
      let stub = sandbox.stub(fs, 'writeFile').yields();

      return installer.writeFile(file, data)
      .then(function() {
        expect(stub).to.have.been.calledOnce;
        expect(stub).to.have.been.calledWith(file, data);
      });
    });

    it('should resolve as true when no error occurs', function() {
      sandbox.stub(fs, 'writeFile').yields();

      return installer.writeFile(file, data)
      .then(function(result) {
        expect(result).to.equal(true);
      });
    });

    it('should reject when an error occurs', function() {
      let err = new Error('fatal error');
      sandbox.stub(fs, 'writeFile').yields(err);

      return installer.writeFile(file, data)
      .then(function() {
        expect.fail('it did not reject');
      })
      .catch(function(error) {
        expect(error).to.equal(err);
      });
    });
  });

  describe('succeed', function() {
    it('should set progress to complete when the input is truthy', function() {
      let spy = sandbox.spy(fakeProgress, 'setComplete');
      installer.succeed(true);

      expect(spy).to.have.been.calledOnce;
    });

    it('should not succeed with a falsey input', function() {
      let spy = sandbox.spy(fakeProgress, 'setComplete');
      installer.succeed(false);

      expect(spy).to.have.not.been.called;
    });
  });

  describe('fail', function() {
    it('should set progress to Failed', function() {
      let spy = sandbox.spy(fakeProgress, 'setStatus');
      installer.fail(new Error('Failed'));

      expect(spy).to.have.been.calledOnce;
      expect(spy).to.have.been.calledWith('Failed');
    });

    it('should call the fail callback with the error', function() {
      let err = new Error('Failed');
      let spy = sandbox.spy(installer, 'failure');
      installer.fail(err);

      expect(spy).to.have.been.calledOnce;
      expect(spy).to.have.been.calledWith(err);
    });
  });
});
<|endoftext|>


<commit_before>import $ from 'jquery';
import { skip, test } from 'qunit';
import { blur, click, fillIn, find, visit } from 'ember-native-dom-helpers';
import moduleForAcceptance from '../helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | ember-x-editable');

test('text is initially TestString', async function(assert) {
  assert.expect(2);

  await visit('/');

  assert.equal(find('.ember-x-editable-text').classList.contains('is-not-editing'), true, 'is-not-editing class initially');
  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text is initially TestString');
});

test('is-editing class applied', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');

  assert.equal(find('.ember-x-editable-text').classList.contains('is-editing'), true, 'is-editing class after clicking');
});

skip('text is saved', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'New test string');
  await click('.editable-buttons .editable-submit');

  assert.equal(find('.ember-x-editable-text').value, 'New test string', 'text is saved');
});

test('text is cancelled, cancel button', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'Cancelled text');
  await click('.editable-buttons .editable-cancel');

  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text cancelled');
});

test('text is cancelled, focusOut', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'Cancelled text');
  await blur('.ember-x-editable-text');

  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text cancelled');
});

test('x-select save change', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-select');
  $('.ember-x-editable-select option:nth-child(3)').prop('selected', true).trigger('change');
  andThen(function() {
    $('.editable-buttons .editable-save').click();
  });
  andThen(function() {
    const select = find('.ember-x-editable-select');
    assert.equal(select.options[select.selectedIndex].text, 'ReallyReallyLongTestString', 'selection saved');
  });
});

test('x-select cancel change', async function(assert) {
  assert.expect(1);

  await visit('/');

  await click('.ember-x-editable-select');
  $('.ember-x-editable-select option:nth-child(1)').prop('selected', true).trigger('change');
  andThen(function() {
    $('.editable-buttons .editable-cancel').click();
  });
  andThen(function() {
    const select = find('.ember-x-editable-select');
    assert.equal(select.options[select.selectedIndex].text, 'LongerTestString', 'selection cancelled');
  });
});
<commit_msg>Fix test, but keep jQuery :(<commit_after>import $ from 'jquery';
import { test } from 'qunit';
import { blur, click, fillIn, find, visit } from 'ember-native-dom-helpers';
import moduleForAcceptance from '../helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | ember-x-editable');

test('text is initially TestString', async function(assert) {
  assert.expect(2);

  await visit('/');

  assert.equal(find('.ember-x-editable-text').classList.contains('is-not-editing'), true, 'is-not-editing class initially');
  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text is initially TestString');
});

test('is-editing class applied', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');

  assert.equal(find('.ember-x-editable-text').classList.contains('is-editing'), true, 'is-editing class after clicking');
});

test('text is saved', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'New test string');
  $('.editable-buttons .editable-submit').click();
  andThen(function() {
    assert.equal(find('.ember-x-editable-text', 'html').value, 'New test string', 'text is saved');
  });
});

test('text is cancelled, cancel button', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'Cancelled text');
  await click('.editable-buttons .editable-cancel');

  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text cancelled');
});

test('text is cancelled, focusOut', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-text');
  await fillIn('.ember-x-editable-text', 'Cancelled text');
  await blur('.ember-x-editable-text');

  assert.equal(find('.ember-x-editable-text').value, 'TestString', 'text cancelled');
});

test('x-select save change', async function(assert) {
  assert.expect(1);

  await visit('/');
  await click('.ember-x-editable-select');
  $('.ember-x-editable-select option:nth-child(3)').prop('selected', true).trigger('change');
  andThen(function() {
    $('.editable-buttons .editable-save').click();
  });
  andThen(function() {
    const select = find('.ember-x-editable-select');
    assert.equal(select.options[select.selectedIndex].text, 'ReallyReallyLongTestString', 'selection saved');
  });
});

test('x-select cancel change', async function(assert) {
  assert.expect(1);

  await visit('/');

  await click('.ember-x-editable-select');
  $('.ember-x-editable-select option:nth-child(1)').prop('selected', true).trigger('change');
  andThen(function() {
    $('.editable-buttons .editable-cancel').click();
  });
  andThen(function() {
    const select = find('.ember-x-editable-select');
    assert.equal(select.options[select.selectedIndex].text, 'LongerTestString', 'selection cancelled');
  });
});
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = lessTokenize;
var SINGLE_QUOTE = 39; // `''
var DOUBLE_QUOTE = 34; // `"'
var BACKSLASH = 92; // `\'
var SLASH = 47; // `/'
var NEWLINE = 10; // `\n'
var SPACE = 32; // ` '
var FEED = 12; // `\f'
var TAB = 9; // `\t'
var CR = 13; // `\r'
var OPEN_PARENTHESES = 40; // `('
var CLOSE_PARENTHESES = 41; // `)'
var OPEN_CURLY = 123; // `{'
var CLOSE_CURLY = 125; // `}'
var SEMICOLON = 59; // `;'
var ASTERICK = 42; // `*'
var AMPERSAND = 38; // `&'
var COLON = 58; // `:'
var COMMA = 44; // ','
var DOT = 46; // '.'
var AT = 64; // `@'
var HASH = 35; // `#'
var RE_AT_END = /[ \n\t\r\{\(\)'"\\;/]/g;
var RE_WORD_END = /[ \n\t\r\(\)\{\}:;@!'"\\#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
var extendSelector = ':extend';
var extendSelectorLength = extendSelector.length;

function lessTokenize(input) {
    var tokens = [];
    var css = input.css.valueOf();
    var length = css.length;

    var offset = -1;
    var line = 1;
    var pos = 0;
    var openedBlocksCount = 0;
    var openedParenthesesCount = 0;

    function unclosed(what) {
        throw input.error('Unclosed ' + what, line, pos - offset);
    }

    while (pos < length) {
        var code = css.charCodeAt(pos);
        var prev = undefined;
        var next = undefined;
        var ch = undefined;
        var escaped = undefined;
        var quote = undefined;
        var lines = undefined;
        var last = undefined;
        var content = undefined;
        var escape = undefined;
        var nextLine = undefined;
        var nextOffset = undefined;
        var escapePos = undefined;
        var token = undefined;
        var part = undefined;

        if (code === NEWLINE) {
            offset = pos;
            line += 1;
        }

        switch (code) {
            case NEWLINE:
            case SPACE:
            case TAB:
            case CR:
            case FEED:
                next = pos;

                do {
                    next += 1;
                    code = css.charCodeAt(next);

                    if (code === NEWLINE) {
                        offset = next;
                        line += 1;
                    }
                } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);

                tokens.push(['space', css.slice(pos, next)]);
                pos = next - 1;
                break;

            case OPEN_CURLY:
                openedBlocksCount++;
                tokens.push(['{', '{', line, pos - offset]);
                break;

            case CLOSE_CURLY:
                openedBlocksCount--;
                tokens.push(['}', '}', line, pos - offset]);
                break;

            case COLON:
                tokens.push([':', ':', line, pos - offset]);
                break;

            case SEMICOLON:
                tokens.push([';', ';', line, pos - offset]);
                break;

            case COMMA:
                tokens.push(['word', ',', line, pos - offset, line, pos - offset + 1]);
                break;

            case OPEN_PARENTHESES:
                openedParenthesesCount++;
                prev = tokens.length ? tokens[tokens.length - 1][1] : '';
                ch = css.charCodeAt(pos + 1);
                if (prev === 'url' && ch !== SINGLE_QUOTE && ch !== DOUBLE_QUOTE && ch !== SPACE && ch !== NEWLINE && ch !== TAB && ch !== FEED && ch !== CR) {
                    next = pos;
                    do {
                        escaped = false;
                        next = css.indexOf(')', next + 1);
                        if (next === -1) unclosed('bracket');
                        escapePos = next;
                        while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                            escapePos -= 1;
                            escaped = !escaped;
                        }
                    } while (escaped);

                    tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                    pos = next;
                } else {
                    next = css.indexOf(')', pos + 1);
                    content = css.slice(pos, next + 1);

                    if (next === -1 || RE_BAD_BRACKET.test(content)) {
                        tokens.push(['(', '(', line, pos - offset]);
                    } else {
                        tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
                        pos = next;
                    }
                }

                break;

            case CLOSE_PARENTHESES:
                openedParenthesesCount--;
                tokens.push([')', ')', line, pos - offset]);
                break;

            case SINGLE_QUOTE:
            case DOUBLE_QUOTE:
                quote = code === SINGLE_QUOTE ? '\'' : '"';
                next = pos;
                do {
                    escaped = false;
                    next = css.indexOf(quote, next + 1);
                    if (next === -1) unclosed('quote');
                    escapePos = next;
                    while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                        escapePos -= 1;
                        escaped = !escaped;
                    }
                } while (escaped);

                tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                pos = next;
                break;

            case AT:
                RE_AT_END.lastIndex = pos + 1;
                RE_AT_END.test(css);
                if (RE_AT_END.lastIndex === 0) {
                    next = css.length - 1;
                } else {
                    next = RE_AT_END.lastIndex - 2;
                }

                tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);

                pos = next;
                break;

            case BACKSLASH:
                next = pos;
                escape = true;
                while (css.charCodeAt(next + 1) === BACKSLASH) {
                    next += 1;
                    escape = !escape;
                }
                code = css.charCodeAt(next + 1);
                if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
                    next += 1;
                }
                tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                pos = next;
                break;

            default:
                ch = css.charCodeAt(pos + 1);

                if (code === DOT || code === HASH) {

                    // look for inner mixin
                    if (openedBlocksCount > 0) {
                        next = pos;
                        ch = css[next];
                        var skip = true;
                        var openedMixinBracketsCount = 0;
                        var linesCount = 0;

                        do {
                            next++;
                            ch = css[next];

                            if (ch === '(') {
                                openedMixinBracketsCount++;
                            } else if (ch === ')') {
                                openedMixinBracketsCount--;
                            } else if (ch === '{' && !openedMixinBracketsCount) {
                                skip = false;
                                break;
                            } else if (ch === '\r\n' || ch === '\n') {
                                linesCount++;
                            }
                        } while (openedMixinBracketsCount || ch && ch !== ';');

                        //skip inner mixin
                        if (skip) {
                            tokens.push(['mixin', css.slice(pos, next), line, pos - offset, line + linesCount, next - offset]);

                            line += linesCount;
                            pos = next;
                            break;
                        }
                    }
                } else if (code === AMPERSAND) {
                    next = pos + 1;

                    // look for inner extend
                    if (openedBlocksCount > 0 && css.slice(next, next + extendSelectorLength) === extendSelector) {

                        //skip inner extend
                        next = css.indexOf(String.fromCharCode(SEMICOLON), next + extendSelectorLength) + 1;

                        tokens.push(['extend', css.slice(pos, next), line, pos - offset, line + 1, next - offset]);

                        line++;
                        pos = next;
                        break;
                    }
                } else if (code === HASH && ch === OPEN_CURLY) {
                    next = css.indexOf('}', pos + 2);
                    if (next === -1) unclosed('interpolation');

                    content = css.slice(pos, next + 1);
                    lines = content.split('\n');
                    last = lines.length - 1;

                    if (last > 0) {
                        nextLine = line + last;
                        nextOffset = next - lines[last].length;
                    } else {
                        nextLine = line;
                        nextOffset = offset;
                    }

                    tokens.push(['word', content, line, pos - offset, nextLine, next - nextOffset]);

                    offset = nextOffset;
                    line = nextLine;
                    pos = next;
                } else if (code === SLASH && ch === ASTERICK) {
                    next = css.indexOf('*/', pos + 2) + 1;
                    if (next === 0) unclosed('comment');

                    content = css.slice(pos, next + 1);
                    lines = content.split('\n');
                    last = lines.length - 1;

                    if (last > 0) {
                        nextLine = line + last;
                        nextOffset = next - lines[last].length;
                    } else {
                        nextLine = line;
                        nextOffset = offset;
                    }

                    tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);

                    offset = nextOffset;
                    line = nextLine;
                    pos = next;
                } else if (code === SLASH && ch === SLASH) {
                    next = css.indexOf('\n', pos + 2) - 1;
                    if (next === -2) next = css.length - 1;

                    content = css.slice(pos, next + 1);

                    tokens.push(['comment', content, line, pos - offset, line, next - offset, 'inline']);

                    pos = next;
                } else {
                    RE_WORD_END.lastIndex = pos + 1;
                    RE_WORD_END.test(css);
                    if (RE_WORD_END.lastIndex === 0) {
                        next = css.length - 1;
                    } else {
                        next = RE_WORD_END.lastIndex - 2;
                    }

                    tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);

                    pos = next;
                }

                break;
        }

        pos++;
    }

    return tokens;
}<commit_msg>Update less-tokenize.js<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = lessTokenize;
var SINGLE_QUOTE = 39; // `''
var DOUBLE_QUOTE = 34; // `"'
var BACKSLASH = 92; // `\'
var SLASH = 47; // `/'
var NEWLINE = 10; // `\n'
var SPACE = 32; // ` '
var FEED = 12; // `\f'
var TAB = 9; // `\t'
var CR = 13; // `\r'
var OPEN_PARENTHESES = 40; // `('
var CLOSE_PARENTHESES = 41; // `)'
var OPEN_CURLY = 123; // `{'
var CLOSE_CURLY = 125; // `}'
var SEMICOLON = 59; // `;'
var ASTERICK = 42; // `*'
var AMPERSAND = 38; // `&'
var COLON = 58; // `:'
var COMMA = 44; // ','
var DOT = 46; // '.'
var AT = 64; // `@'
var HASH = 35; // `#'
var RE_AT_END = /[ \n\t\r\{\(\)'"\\;/]/g;
var RE_WORD_END = /[ \n\t\r\(\)\{\}:;@!'"\\#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
var extendSelector = ':extend';
var extendSelectorLength = extendSelector.length;

function lessTokenize(input) {
    var tokens = [];
    var css = input.css.valueOf();
    var length = css.length;

    var offset = -1;
    var line = 1;
    var pos = 0;
    var openedBlocksCount = 0;
    var openedParenthesesCount = 0;

    function unclosed(what) {
        throw input.error('Unclosed ' + what, line, pos - offset);
    }

    while (pos < length) {
        var code = css.charCodeAt(pos);
        var prev = undefined;
        var next = undefined;
        var ch = undefined;
        var escaped = undefined;
        var quote = undefined;
        var lines = undefined;
        var last = undefined;
        var content = undefined;
        var escape = undefined;
        var nextLine = undefined;
        var nextOffset = undefined;
        var escapePos = undefined;
        var token = undefined;
        var part = undefined;

        if (code === NEWLINE) {
            offset = pos;
            line += 1;
        }

        switch (code) {
            case NEWLINE:
            case SPACE:
            case TAB:
            case CR:
            case FEED:
                next = pos;

                do {
                    next += 1;
                    code = css.charCodeAt(next);

                    if (code === NEWLINE) {
                        offset = next;
                        line += 1;
                    }
                } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);

                tokens.push(['space', css.slice(pos, next)]);
                pos = next - 1;
                break;

            case OPEN_CURLY:
                openedBlocksCount++;
                tokens.push(['{', '{', line, pos - offset]);
                break;

            case CLOSE_CURLY:
                openedBlocksCount--;
                tokens.push(['}', '}', line, pos - offset]);
                break;

            case COLON:
                tokens.push([':', ':', line, pos - offset]);
                break;

            case SEMICOLON:
                tokens.push([';', ';', line, pos - offset]);
                break;

            case COMMA:
                tokens.push(['word', ',', line, pos - offset, line, pos - offset + 1]);
                break;

            case OPEN_PARENTHESES:
                openedParenthesesCount++;
                prev = tokens.length ? tokens[tokens.length - 1][1] : '';
                ch = css.charCodeAt(pos + 1);
                if (prev === 'url' && ch !== SINGLE_QUOTE && ch !== DOUBLE_QUOTE && ch !== SPACE && ch !== NEWLINE && ch !== TAB && ch !== FEED && ch !== CR) {
                    next = pos;
                    do {
                        escaped = false;
                        next = css.indexOf(')', next + 1);
                        if (next === -1) unclosed('bracket');
                        escapePos = next;
                        while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                            escapePos -= 1;
                            escaped = !escaped;
                        }
                    } while (escaped);

                    tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                    pos = next;
                } else {
                    next = css.indexOf(')', pos + 1);
                    content = css.slice(pos, next + 1);

                    if (next === -1 || RE_BAD_BRACKET.test(content)) {
                        tokens.push(['(', '(', line, pos - offset]);
                    } else {
                        tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
                        pos = next;
                    }
                }

                break;

            case CLOSE_PARENTHESES:
                openedParenthesesCount--;
                tokens.push([')', ')', line, pos - offset]);
                break;

            case SINGLE_QUOTE:
            case DOUBLE_QUOTE:
                quote = code === SINGLE_QUOTE ? '\'' : '"';
                next = pos;
                do {
                    escaped = false;
                    next = css.indexOf(quote, next + 1);
                    if (next === -1) unclosed('quote');
                    escapePos = next;
                    while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
                        escapePos -= 1;
                        escaped = !escaped;
                    }
                } while (escaped);

                tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                pos = next;
                break;

            case AT:
                RE_AT_END.lastIndex = pos + 1;
                RE_AT_END.test(css);
                if (RE_AT_END.lastIndex === 0) {
                    next = css.length - 1;
                } else {
                    next = RE_AT_END.lastIndex - 2;
                }

                tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);

                pos = next;
                break;

            case BACKSLASH:
                next = pos;
                escape = true;
                while (css.charCodeAt(next + 1) === BACKSLASH) {
                    next += 1;
                    escape = !escape;
                }
                code = css.charCodeAt(next + 1);
                if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
                    next += 1;
                }
                tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
                pos = next;
                break;

            default:
                ch = css.charCodeAt(pos + 1);

                if (code === DOT || code === HASH) {

                    // look for inner mixin
                    if (openedBlocksCount > 0) {
                        next = pos;
                        ch = css[next];
                        var skip = true;
                        var openedMixinBracketsCount = 0;
                        var linesCount = 0;

                        do {
                            next++;
                            ch = css[next];

                            if (ch === '(') {
                                openedMixinBracketsCount++;
                            } else if (ch === ')') {
                                openedMixinBracketsCount--;
                            } else if (ch === '{' && !openedMixinBracketsCount) {
                                skip = false;
                                break;
                            } else if (ch === '\r\n' || ch === '\n') {
                                linesCount++;
                            }
                        } while (openedMixinBracketsCount || ch && ch !== ';');

                        //skip inner mixin
                        if (skip) {
                            tokens.push(['mixin', css.slice(pos, next), line, pos - offset, line + linesCount, next - offset]);

                            line += linesCount;
                            pos = next;
                            break;
                        }
                    }
                } else if (code === AMPERSAND) {
                    next = pos + 1;

                    // look for inner extend
                    if (openedBlocksCount > 0 && css.slice(next, next + extendSelectorLength) === extendSelector) {

                        //skip inner extend
                        next = css.indexOf(String.fromCharCode(SEMICOLON), next + extendSelectorLength) + 1;

                        tokens.push(['extend', css.slice(pos, next), line, pos - offset, line, next - offset]);

                        pos = next;
                        break;
                    }
                } else if (code === HASH && ch === OPEN_CURLY) {
                    next = css.indexOf('}', pos + 2);
                    if (next === -1) unclosed('interpolation');

                    content = css.slice(pos, next + 1);
                    lines = content.split('\n');
                    last = lines.length - 1;

                    if (last > 0) {
                        nextLine = line + last;
                        nextOffset = next - lines[last].length;
                    } else {
                        nextLine = line;
                        nextOffset = offset;
                    }

                    tokens.push(['word', content, line, pos - offset, nextLine, next - nextOffset]);

                    offset = nextOffset;
                    line = nextLine;
                    pos = next;
                } else if (code === SLASH && ch === ASTERICK) {
                    next = css.indexOf('*/', pos + 2) + 1;
                    if (next === 0) unclosed('comment');

                    content = css.slice(pos, next + 1);
                    lines = content.split('\n');
                    last = lines.length - 1;

                    if (last > 0) {
                        nextLine = line + last;
                        nextOffset = next - lines[last].length;
                    } else {
                        nextLine = line;
                        nextOffset = offset;
                    }

                    tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);

                    offset = nextOffset;
                    line = nextLine;
                    pos = next;
                } else if (code === SLASH && ch === SLASH) {
                    next = css.indexOf('\n', pos + 2) - 1;
                    if (next === -2) next = css.length - 1;

                    content = css.slice(pos, next + 1);

                    tokens.push(['comment', content, line, pos - offset, line, next - offset, 'inline']);

                    pos = next;
                } else {
                    RE_WORD_END.lastIndex = pos + 1;
                    RE_WORD_END.test(css);
                    if (RE_WORD_END.lastIndex === 0) {
                        next = css.length - 1;
                    } else {
                        next = RE_WORD_END.lastIndex - 2;
                    }

                    tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);

                    pos = next;
                }

                break;
        }

        pos++;
    }

    return tokens;
}
<|endoftext|>


<commit_before>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function wrap(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function await(value) { return new AwaitValue(value); } }; }();

	exports.default = function (_ref) {

	  /**
	   * @method queue
	   * @param {Function} createTask
	   * @param {Object} [props]
	   * @yield {void}
	   */
	  var queue = function () {
	    var _ref2 = _asyncGenerator.wrap(regeneratorRuntime.mark(function _callee() {
	      var createTask = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialTask;
	      var props = arguments[1];
	      var task;
	      return regeneratorRuntime.wrap(function _callee$(_context) {
	        while (1) {
	          switch (_context.prev = _context.next) {
	            case 0:
	              _context.prev = 0;
	              _context.next = 3;
	              return _asyncGenerator.await(createTask(props));

	            case 3:
	              task = _context.sent;

	              // Publish the resolved value of the task to the subscription.
	              next(task);

	              // Recursively invoke the generator, passing in the props received from the last
	              // invocation.
	              _context.next = 7;
	              return task;

	            case 7:
	              _context.t0 = _context.sent;
	              _context.t1 = task;
	              _context.t2 = queue(_context.t0, _context.t1);
	              _context.t3 = _asyncIterator(_context.t2);
	              _context.t4 = _asyncGenerator.await;
	              return _context.delegateYield(_asyncGeneratorDelegate(_context.t3, _context.t4), "t5", 13);

	            case 13:
	              _context.next = 26;
	              break;

	            case 15:
	              _context.prev = 15;
	              _context.t6 = _context["catch"](0);

	              // Publish the rejected value of the task to the subscription.
	              error(_context.t6);

	              // Any further invocations will simply continue from the last successful task, which
	              // allows recovery from any promise rejections.
	              _context.next = 20;
	              return _context.t6;

	            case 20:
	              _context.t7 = _context.sent;
	              _context.t8 = props;
	              _context.t9 = queue(_context.t7, _context.t8);
	              _context.t10 = _asyncIterator(_context.t9);
	              _context.t11 = _asyncGenerator.await;
	              return _context.delegateYield(_asyncGeneratorDelegate(_context.t10, _context.t11), "t12", 26);

	            case 26:
	            case "end":
	              return _context.stop();
	          }
	        }
	      }, _callee, this, [[0, 15]]);
	    }));

	    return function queue(_x, _x2) {
	      return _ref2.apply(this, arguments);
	    };
	  }();

	  // Initiate the async generator, and move the cursor to the first yield.

	  var value = _ref.value,
	      _ref$next = _ref.next,
	      next = _ref$next === undefined ? fn : _ref$next,
	      _ref$error = _ref.error,
	      error = _ref$error === undefined ? fn : _ref$error;

	  /**
	   * Initial task the yields the value that was passed in upon instantiation.
	   *
	   * @method initialTask
	   * @return {Promise}
	   */
	  var initialTask = function initialTask() {
	    return Promise.resolve(value);
	  };var iterator = queue();
	  iterator.next();

	  /**
	   * @method process
	   * @param {Function} promiseFn
	   * @return {Promise}
	   */
	  var process = function process(promiseFn) {
	    return iterator.next(promiseFn);
	  };

	  return { process: process, iterator: iterator };
	};

	function _asyncIterator(iterable) { if (typeof Symbol === "function") { if (Symbol.asyncIterator) { var method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { return iterable[Symbol.iterator](); } } throw new TypeError("Object is not async iterable"); }

	function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; } ; if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function () { return this; }; } iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { return pump("return", value); }; } return iter; }

	/**
	 * @method fn
	 * @return {void}
	 */
	var fn = Function.prototype;

	/**
	 * @param {Object} [value]
	 * @param {Function} [next]
	 * @param {Function} [error]
	 * @return {Object}
	 */

/***/ }
/******/ ]);<commit_msg>Build<commit_after>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function wrap(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function await(value) { return new AwaitValue(value); } }; }();

	exports.default = function (_ref) {

	  /**
	   * @method queue
	   * @param {Function} createTask
	   * @param {Object} [props]
	   * @yield {void}
	   */
	  var queue = function () {
	    var _ref2 = _asyncGenerator.wrap(regeneratorRuntime.mark(function _callee() {
	      var createTask = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialTask;
	      var props = arguments[1];
	      var task;
	      return regeneratorRuntime.wrap(function _callee$(_context) {
	        while (1) {
	          switch (_context.prev = _context.next) {
	            case 0:
	              _context.prev = 0;
	              _context.next = 3;
	              return _asyncGenerator.await(createTask(props));

	            case 3:
	              task = _context.sent;

	              // Publish the resolved value of the task to the subscription.
	              next(task);

	              // Recursively invoke the generator, passing in the props received from the last
	              // invocation.
	              _context.next = 7;
	              return task;

	            case 7:
	              _context.t0 = _context.sent;
	              _context.t1 = task;
	              _context.t2 = queue(_context.t0, _context.t1);
	              _context.t3 = _asyncIterator(_context.t2);
	              _context.t4 = _asyncGenerator.await;
	              return _context.delegateYield(_asyncGeneratorDelegate(_context.t3, _context.t4), "t5", 13);

	            case 13:
	              _context.next = 26;
	              break;

	            case 15:
	              _context.prev = 15;
	              _context.t6 = _context["catch"](0);

	              // Publish the rejected value of the task to the subscription.
	              error(_context.t6);

	              // Any further invocations will simply continue from the last successful task, which
	              // allows recovery from any promise rejections.
	              _context.next = 20;
	              return _context.t6;

	            case 20:
	              _context.t7 = _context.sent;
	              _context.t8 = props;
	              _context.t9 = queue(_context.t7, _context.t8);
	              _context.t10 = _asyncIterator(_context.t9);
	              _context.t11 = _asyncGenerator.await;
	              return _context.delegateYield(_asyncGeneratorDelegate(_context.t10, _context.t11), "t12", 26);

	            case 26:
	            case "end":
	              return _context.stop();
	          }
	        }
	      }, _callee, this, [[0, 15]]);
	    }));

	    return function queue(_x, _x2) {
	      return _ref2.apply(this, arguments);
	    };
	  }();

	  // Initiate the async generator, and move the cursor to the first yield.

	  var value = _ref.value,
	      _ref$next = _ref.next,
	      next = _ref$next === undefined ? fn : _ref$next,
	      _ref$error = _ref.error,
	      error = _ref$error === undefined ? fn : _ref$error;

	  /**
	   * Initial task the yields the value that was passed in upon instantiation.
	   *
	   * @method initialTask
	   * @return {Promise}
	   */
	  var initialTask = function initialTask() {
	    return Promise.resolve(value);
	  };var iterator = queue();
	  iterator.next();

	  /**
	   * @method process
	   * @param {Function} promiseFn
	   * @return {Promise}
	   */
	  var process = function process(promiseFn) {
	    return iterator.next(promiseFn);
	  };

	  return { process: process, stop: function stop() {
	      return iterator.return();
	    } };
	};

	function _asyncIterator(iterable) { if (typeof Symbol === "function") { if (Symbol.asyncIterator) { var method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { return iterable[Symbol.iterator](); } } throw new TypeError("Object is not async iterable"); }

	function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; } ; if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function () { return this; }; } iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { return pump("return", value); }; } return iter; }

	/**
	 * @method fn
	 * @return {void}
	 */
	var fn = Function.prototype;

	/**
	 * @param {Object} [value]
	 * @param {Function} [next]
	 * @param {Function} [error]
	 * @return {Object}
	 */

/***/ }
/******/ ]);<|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import {
	activatePlugin,
	loginUser,
	createURL,
	visitAdminPage,
} from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	logoutUser,
	setAuthToken,
	setSearchConsoleProperty,
	setSiteVerification,
	useRequestInterception,
	wpApiFetch,
} from '../utils';

describe( 'the set up flow for the second administrator', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().startsWith( 'https://accounts.google.com/o/oauth2/auth' ) ) {
				request.respond( {
					status: 302,
					headers: {
						location: createURL( '/', 'oauth2callback=1&code=valid-test-code' ),
					},
				} );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		await activatePlugin( 'e2e-tests-oauth-callback-plugin' );
		await activatePlugin( 'e2e-tests-site-verification-api-mock' );
		await setAuthToken();
		await setSiteVerification();
		await setSearchConsoleProperty();
		await logoutUser();
	} );

	afterEach( async () => {
		await logoutUser();

		// Restore the default/admin user
		// (switchToAdmin will not work as it is not aware of the current user)
		await loginUser();
	} );

	it( 'admin 2', async () => {
		await loginUser( 'admin-2', 'password' );
		// Ensure we're logged in with the correct user.
		await expect( page ).toMatchElement( '#wp-admin-bar-user-info .display-name', { text: 'admin-2' } );

		// Simulate that the user is already verified.
		await wpApiFetch( {
			path: 'google-site-kit/v1/e2e/verify-site',
			method: 'post',
		} );
		await visitAdminPage( 'admin.php', 'page=googlesitekit-splash' );

		await expect( page ).toMatchElement( '.googlesitekit-wizard-step__title', { text: /Authenticate with Google/i } );

		await Promise.all( [
			expect( page ).toClick( '.googlesitekit-wizard-step button', { text: /sign in with google/i } ),
			page.waitForNavigation(),
		] );

		await page.waitForSelector( '.googlesitekit-wizard-step button' );
		await expect( page ).toMatchElement( '.googlesitekit-wizard-step__title', { text: /congratulations!/i } );

		await Promise.all( [
			expect( page ).toClick( '.googlesitekit-wizard-step button', { text: /go to dashboard/i } ),
			page.waitForNavigation(),
		] );

		await expect( page ).toMatchElement( '#js-googlesitekit-dashboard' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Site Kit!/i } );
	} );
} );

<commit_msg>Retry logging in as admin-2 if first attempt fails.<commit_after>/**
 * WordPress dependencies
 */
import {
	activatePlugin,
	loginUser,
	createURL,
	visitAdminPage,
} from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	logoutUser,
	setAuthToken,
	setSearchConsoleProperty,
	setSiteVerification,
	useRequestInterception,
	wpApiFetch,
} from '../utils';

let loginAttempts;
const MAX_LOGIN_RETRIES = 3;
async function safeLoginUser( username, password ) {
	loginAttempts = 0;

	do {
		await loginUser( username, password );
		loginAttempts++;
	} while ( page.url().includes( 'wp-login.php' ) && loginAttempts < MAX_LOGIN_RETRIES );

	if ( page.url().includes( 'wp-login.php' ) && loginAttempts >= MAX_LOGIN_RETRIES ) {
		throw new Error( `Failed to login as ${ username } after ${ loginAttempts } attempts` );
	}
}

describe( 'the set up flow for the second administrator', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().startsWith( 'https://accounts.google.com/o/oauth2/auth' ) ) {
				request.respond( {
					status: 302,
					headers: {
						location: createURL( '/', 'oauth2callback=1&code=valid-test-code' ),
					},
				} );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		await activatePlugin( 'e2e-tests-oauth-callback-plugin' );
		await activatePlugin( 'e2e-tests-site-verification-api-mock' );
		await setAuthToken();
		await setSiteVerification();
		await setSearchConsoleProperty();
		await logoutUser();
	} );

	afterEach( async () => {
		await logoutUser();

		// Restore the default/admin user
		// (switchToAdmin will not work as it is not aware of the current user)
		await loginUser();
	} );

	it( 'admin 2', async () => {
		await safeLoginUser( 'admin-2', 'password' );
		// Ensure we're logged in with the correct user.
		await expect( page ).toMatchElement( '#wp-admin-bar-user-info .display-name', { text: 'admin-2' } );

		// Simulate that the user is already verified.
		await wpApiFetch( {
			path: 'google-site-kit/v1/e2e/verify-site',
			method: 'post',
		} );
		await visitAdminPage( 'admin.php', 'page=googlesitekit-splash' );

		await expect( page ).toMatchElement( '.googlesitekit-wizard-step__title', { text: /Authenticate with Google/i } );

		await Promise.all( [
			expect( page ).toClick( '.googlesitekit-wizard-step button', { text: /sign in with google/i } ),
			page.waitForNavigation(),
		] );

		await page.waitForSelector( '.googlesitekit-wizard-step button' );
		await expect( page ).toMatchElement( '.googlesitekit-wizard-step__title', { text: /congratulations!/i } );

		await Promise.all( [
			expect( page ).toClick( '.googlesitekit-wizard-step button', { text: /go to dashboard/i } ),
			page.waitForNavigation(),
		] );

		await expect( page ).toMatchElement( '#js-googlesitekit-dashboard' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Site Kit!/i } );
	} );
} );

<|endoftext|>