<commit_before>/* eslint-env browser */

/* global Webex */

/* eslint-disable camelcase */
/* eslint-disable max-nested-callbacks */
/* eslint-disable no-alert */
/* eslint-disable no-console */
/* eslint-disable require-jsdoc */
/* eslint-disable arrow-body-style */
/* eslint-disable max-len */

// Declare some globals that we'll need throughout
let activeMeeting, webex;

// First, let's wire our form fields up to localStorage so we don't have to
// retype things everytime we reload the page.

[
  'access-token',
  'invitee'
].forEach((id) => {
  const el = document.getElementById(id);

  el.value = localStorage.getItem(id);
  el.addEventListener('change', (event) => {
    localStorage.setItem(id, event.target.value);
  });
});

// There's a few different events that'll let us know we should initialize
// Webex and start listening for incoming calls, so we'll wrap a few things
// up in a function.
function connect() {
  return new Promise((resolve) => {
    if (!webex) {
      // eslint-disable-next-line no-multi-assign
      webex = window.webex = Webex.init({
        config: {
          meetings: {
            deviceType: 'WEB'
          }
          // Any other sdk config we need
        },
        credentials: {
          access_token: document.getElementById('access-token').value
        }
      });
    }

    // Listen for added meetings
    webex.meetings.on('meeting:added', (addedMeetingEvent) => {
      if (addedMeetingEvent.type === 'INCOMING' || addedMeetingEvent.type === 'JOIN') {
        const addedMeeting = addedMeetingEvent.meeting;

        // Acknowledge to the server that we received the call on our device
        addedMeeting.acknowledge(addedMeetingEvent.type)
          .then(() => {
            if (confirm('Answer incoming call')) {
              joinMeeting(addedMeeting);
              bindMeetingEvents(addedMeeting);
            }
            else {
              addedMeeting.decline();
            }
          });
      }
    });

    // Register our device with Webex cloud
    if (!webex.meetings.registered) {
      webex.meetings.register()
        // Sync our meetings with existing meetings on the server
        .then(() => webex.meetings.syncMeetings())
        .then(() => {
          // This is just a little helper for our selenium tests and doesn't
          // really matter for the example
          document.body.classList.add('listening');
          document.getElementById('connection-status').innerHTML = 'connected';
          // Our device is now connected
          resolve();
        })
        // This is a terrible way to handle errors, but anything more specific is
        // going to depend a lot on your app
        .catch((err) => {
          console.error(err);
          // we'll rethrow here since we didn't really *handle* the error, we just
          // reported it
          throw err;
        });
    }
    else {
      // Device was already connected
      resolve();
    }
  });
}

// Similarly, there are a few different ways we'll get a meeting Object, so let's
// put meeting handling inside its own function.
function bindMeetingEvents(meeting) {
  // call is a call instance, not a promise, so to know if things break,
  // we'll need to listen for the error event. Again, this is a rather naive
  // handler.
  meeting.on('error', (err) => {
    console.error(err);
  });

  // Handle media streams changes to ready state
  meeting.on('media:ready', (media) => {
    if (!media) {
      return;
    }
    if (media.type === 'local') {
      document.getElementById('self-view').srcObject = media.stream;
    }
    if (media.type === 'remoteVideo') {
      document.getElementById('remote-view-video').srcObject = media.stream;
    }
    if (media.type === 'remoteAudio') {
      document.getElementById('remote-view-audio').srcObject = media.stream;
    }
  });

  // Handle media streams stopping
  meeting.on('media:stopped', (media) => {
    // Remove media streams
    if (media.type === 'local') {
      document.getElementById('self-view').srcObject = null;
    }
    if (media.type === 'remoteVideo') {
      document.getElementById('remote-view-video').srcObject = null;
    }
    if (media.type === 'remoteAudio') {
      document.getElementById('remote-view-audio').srcObject = null;
    }
  });

  // Update participant info
  meeting.members.on('members:update', (delta) => {
    const {full: membersData} = delta;
    const memberIDs = Object.keys(membersData);
    let memberTableHTML = '';

    memberIDs.forEach((memberID) => {
      const memberObject = membersData[memberID];

      // Devices are listed in the memberships object.
      // We are not concerned with them in this demo
      if (memberObject.isUser) {
        const personId = memberObject.participant.person.id;
        const memberTableRowHTML = `

        ${memberObject.name}
        ${memberObject.status}
        ${memberObject.isSelf}

`;

        memberTableHTML = memberTableHTML.concat(memberTableRowHTML);
      }
    });

    document.getElementById('call-members').innerHTML = memberTableHTML;
  });

  // Of course, we'd also like to be able to leave the meeting:
  document.getElementById('hangup').addEventListener('click', () => {
    meeting.leave();
  });

  meeting.on('all', (event) => {
    console.log(event);
  });
}

// Join the meeting and add media
function joinMeeting(meeting) {
  console.log('joinMeeting', meeting);

  return meeting.join().then(() => {
    return meeting.getSupportedDevices({sendAudio: true, sendVideo: true})
      .then(({sendAudio, sendVideo}) => {
        const mediaSettings = {
          receiveVideo: true,
          receiveAudio: true,
          receiveShare: false,
          sendShare: false,
          sendVideo,
          sendAudio
        };

        return meeting.getMediaStreams(mediaSettings).then((mediaStreams) => {
          const [localStream, localShare] = mediaStreams;

          meeting.addMedia({
            localShare,
            localStream,
            mediaSettings
          });
        });
      });
  });
}

// In order to simplify the state management needed to keep track of our button
// handlers, we'll rely on the current meeting global object and only hook up event
// handlers once.

document.getElementById('hangup').addEventListener('click', () => {
  if (activeMeeting) {
    activeMeeting.leave();
  }
});

// Now, let's set up incoming call handling
document.getElementById('credentials').addEventListener('submit', (event) => {
  // let's make sure we don't reload the page when we submit the form
  event.preventDefault();

  // The rest of the incoming call setup happens in connect();
  connect();
});

// And finally, let's wire up dialing
document.getElementById('dialer').addEventListener('submit', (event) => {
  // again, we don't want to reload when we try to dial
  event.preventDefault();

  const destination = document.getElementById('invitee').value;

  // we'll use `connect()` (even though we might already be connected or
  // connecting) to make sure we've got a functional webex instance.
  connect()
    .then(() => {
      // Create the meeting
      return webex.meetings.create(destination).then((meeting) => {
        // Save meeting
        activeMeeting = meeting;

        // Call our helper function for binding events to meetings
        bindMeetingEvents(meeting);

        // Pass the meeting to our join meeting helper
        return joinMeeting(meeting);
      });
    })
    .catch((error) => {
      // Report the error
      console.error(error);

      // Implement error handling here
    });
});
<commit_msg>feat(samples): add enumaratedevices on page load<commit_after>/* eslint-env browser */

/* global Webex */

/* eslint-disable camelcase */
/* eslint-disable max-nested-callbacks */
/* eslint-disable no-alert */
/* eslint-disable no-console */
/* eslint-disable require-jsdoc */
/* eslint-disable arrow-body-style */
/* eslint-disable max-len */

// Declare some globals that we'll need throughout
let activeMeeting, webex;

// First, let's wire our form fields up to localStorage so we don't have to
// retype things everytime we reload the page.

[
  'access-token',
  'invitee'
].forEach((id) => {
  const el = document.getElementById(id);

  el.value = localStorage.getItem(id);
  el.addEventListener('change', (event) => {
    localStorage.setItem(id, event.target.value);
  });
});

// There's a few different events that'll let us know we should initialize
// Webex and start listening for incoming calls, so we'll wrap a few things
// up in a function.
function connect() {
  return new Promise((resolve) => {
    if (!webex) {
      // eslint-disable-next-line no-multi-assign
      webex = window.webex = Webex.init({
        config: {
          meetings: {
            deviceType: 'WEB'
          }
          // Any other sdk config we need
        },
        credentials: {
          access_token: document.getElementById('access-token').value
        }
      });
    }

    // Listen for added meetings
    webex.meetings.on('meeting:added', (addedMeetingEvent) => {
      if (addedMeetingEvent.type === 'INCOMING' || addedMeetingEvent.type === 'JOIN') {
        const addedMeeting = addedMeetingEvent.meeting;

        // Acknowledge to the server that we received the call on our device
        addedMeeting.acknowledge(addedMeetingEvent.type)
          .then(() => {
            if (confirm('Answer incoming call')) {
              joinMeeting(addedMeeting);
              bindMeetingEvents(addedMeeting);
            }
            else {
              addedMeeting.decline();
            }
          });
      }
    });

    // Register our device with Webex cloud
    if (!webex.meetings.registered) {
      webex.meetings.register()
        // Sync our meetings with existing meetings on the server
        .then(() => webex.meetings.syncMeetings())
        .then(() => {
          // This is just a little helper for our selenium tests and doesn't
          // really matter for the example
          document.body.classList.add('listening');
          document.getElementById('connection-status').innerHTML = 'connected';
          // Our device is now connected
          resolve();
        })
        // This is a terrible way to handle errors, but anything more specific is
        // going to depend a lot on your app
        .catch((err) => {
          console.error(err);
          // we'll rethrow here since we didn't really *handle* the error, we just
          // reported it
          throw err;
        });
    }
    else {
      // Device was already connected
      resolve();
    }
  });
}

// Similarly, there are a few different ways we'll get a meeting Object, so let's
// put meeting handling inside its own function.
function bindMeetingEvents(meeting) {
  // call is a call instance, not a promise, so to know if things break,
  // we'll need to listen for the error event. Again, this is a rather naive
  // handler.
  meeting.on('error', (err) => {
    console.error(err);
  });

  // Handle media streams changes to ready state
  meeting.on('media:ready', (media) => {
    if (!media) {
      return;
    }
    if (media.type === 'local') {
      document.getElementById('self-view').srcObject = media.stream;
    }
    if (media.type === 'remoteVideo') {
      document.getElementById('remote-view-video').srcObject = media.stream;
    }
    if (media.type === 'remoteAudio') {
      document.getElementById('remote-view-audio').srcObject = media.stream;
    }
  });

  // Handle media streams stopping
  meeting.on('media:stopped', (media) => {
    // Remove media streams
    if (media.type === 'local') {
      document.getElementById('self-view').srcObject = null;
    }
    if (media.type === 'remoteVideo') {
      document.getElementById('remote-view-video').srcObject = null;
    }
    if (media.type === 'remoteAudio') {
      document.getElementById('remote-view-audio').srcObject = null;
    }
  });

  // Update participant info
  meeting.members.on('members:update', (delta) => {
    const {full: membersData} = delta;
    const memberIDs = Object.keys(membersData);
    let memberTableHTML = '';

    memberIDs.forEach((memberID) => {
      const memberObject = membersData[memberID];

      // Devices are listed in the memberships object.
      // We are not concerned with them in this demo
      if (memberObject.isUser) {
        const personId = memberObject.participant.person.id;
        const memberTableRowHTML = `

        ${memberObject.name}
        ${memberObject.status}
        ${memberObject.isSelf}

`;

        memberTableHTML = memberTableHTML.concat(memberTableRowHTML);
      }
    });

    document.getElementById('call-members').innerHTML = memberTableHTML;
  });

  // Of course, we'd also like to be able to leave the meeting:
  document.getElementById('hangup').addEventListener('click', () => {
    meeting.leave();
  });

  meeting.on('all', (event) => {
    console.log(event);
  });
}

// Join the meeting and add media
function joinMeeting(meeting) {
  return meeting.join().then(() => {
    return meeting.getSupportedDevices({sendAudio: true, sendVideo: true})
      .then(({sendAudio, sendVideo}) => {
        const mediaSettings = {
          receiveVideo: true,
          receiveAudio: true,
          receiveShare: false,
          sendShare: false,
          sendVideo,
          sendAudio
        };

        return meeting.getMediaStreams(mediaSettings).then((mediaStreams) => {
          const [localStream, localShare] = mediaStreams;

          meeting.addMedia({
            localShare,
            localStream,
            mediaSettings
          });
        });
      });
  });
}

// In order to simplify the state management needed to keep track of our button
// handlers, we'll rely on the current meeting global object and only hook up event
// handlers once.

document.getElementById('hangup').addEventListener('click', () => {
  if (activeMeeting) {
    activeMeeting.leave();
  }
});

// Now, let's set up incoming call handling
document.getElementById('credentials').addEventListener('submit', (event) => {
  // let's make sure we don't reload the page when we submit the form
  event.preventDefault();

  // The rest of the incoming call setup happens in connect();
  connect();
});

// And finally, let's wire up dialing
document.getElementById('dialer').addEventListener('submit', (event) => {
  // again, we don't want to reload when we try to dial
  event.preventDefault();

  const destination = document.getElementById('invitee').value;

  // we'll use `connect()` (even though we might already be connected or
  // connecting) to make sure we've got a functional webex instance.
  connect()
    .then(() => {
      // Create the meeting
      return webex.meetings.create(destination).then((meeting) => {
        // Save meeting
        activeMeeting = meeting;

        // Call our helper function for binding events to meetings
        bindMeetingEvents(meeting);

        // Pass the meeting to our join meeting helper
        return joinMeeting(meeting);
      });
    })
    .catch((error) => {
      // Report the error
      console.error(error);

      // Implement error handling here
    });
});
<|endoftext|>


<commit_before>// @remove-file-on-eject
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

const chalk = require('react-dev-utils/chalk');
const fs = require('fs');
const resolve = require('resolve');
const path = require('path');
const paths = require('../../config/paths');
const os = require('os');
const semver = require('semver');
const immer = require('react-dev-utils/immer').produce;
const globby = require('react-dev-utils/globby').sync;

const hasJsxRuntime = (() => {
  if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
    return false;
  }

  try {
    require.resolve('react/jsx-runtime', { paths: [paths.appPath] });
    return true;
  } catch (e) {
    return false;
  }
})();

function writeJson(fileName, object) {
  fs.writeFileSync(
    fileName,
    JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL
  );
}

function verifyNoTypeScript() {
  const typescriptFiles = globby(
    ['**/*.(ts|tsx)', '!**/node_modules', '!**/*.d.ts'],
    { cwd: paths.appSrc }
  );
  if (typescriptFiles.length > 0) {
    console.warn(
      chalk.yellow(
        `We detected TypeScript in your project (${chalk.bold(
          `src${path.sep}${typescriptFiles[0]}`
        )}) and created a ${chalk.bold('tsconfig.json')} file for you.`
      )
    );
    console.warn();
    return false;
  }
  return true;
}

function verifyTypeScriptSetup() {
  let firstTimeSetup = false;

  if (!fs.existsSync(paths.appTsConfig)) {
    if (verifyNoTypeScript()) {
      return;
    }
    writeJson(paths.appTsConfig, {});
    firstTimeSetup = true;
  }

  const isYarn = fs.existsSync(paths.yarnLockFile);

  // Ensure typescript is installed
  let ts;
  try {
    // TODO: Remove this hack once `globalThis` issue is resolved
    // https://github.com/jsdom/jsdom/issues/2961
    const globalThisWasDefined = !!global.globalThis;

    ts = require(resolve.sync('typescript', {
      basedir: paths.appNodeModules,
    }));

    if (!globalThisWasDefined && !!global.globalThis) {
      delete global.globalThis;
    }
  } catch (_) {
    console.error(
      chalk.bold.red(
        `It looks like you're trying to use TypeScript but do not have ${chalk.bold(
          'typescript'
        )} installed.`
      )
    );
    console.error(
      chalk.bold(
        'Please install',
        chalk.cyan.bold('typescript'),
        'by running',
        chalk.cyan.bold(
          isYarn ? 'yarn add typescript' : 'npm install typescript'
        ) + '.'
      )
    );
    console.error(
      chalk.bold(
        'If you are not trying to use TypeScript, please remove the ' +
          chalk.cyan('tsconfig.json') +
          ' file from your package root (and any TypeScript files).'
      )
    );
    console.error();
    process.exit(1);
  }

  const compilerOptions = {
    // These are suggested values and will be set when not present in the
    // tsconfig.json
    // 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
    target: {
      parsedValue: ts.ScriptTarget.ES5,
      suggested: 'es5',
    },
    lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
    allowJs: { suggested: true },
    skipLibCheck: { suggested: true },
    esModuleInterop: { suggested: true },
    allowSyntheticDefaultImports: { suggested: true },
    strict: { suggested: true },
    forceConsistentCasingInFileNames: { suggested: true },
    noFallthroughCasesInSwitch: { suggested: true },

    // These values are required and cannot be changed by the user
    // Keep this in sync with the webpack config
    module: {
      parsedValue: ts.ModuleKind.ESNext,
      value: 'esnext',
      reason: 'for import() and import/export',
    },
    moduleResolution: {
      parsedValue: ts.ModuleResolutionKind.NodeJs,
      value: 'node',
      reason: 'to match webpack resolution',
    },
    resolveJsonModule: { value: true, reason: 'to match webpack loader' },
    isolatedModules: { value: true, reason: 'implementation limitation' },
    noEmit: { value: true },
    jsx: {
      parsedValue:
        hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
          ? ts.JsxEmit.ReactJsx
          : ts.JsxEmit.React,
      value:
        hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
          ? 'react-jsx'
          : 'react',
      reason: 'to support the new JSX transform in React 17',
    },
    paths: { value: undefined, reason: 'aliased imports are not supported' },
  };

  const formatDiagnosticHost = {
    getCanonicalFileName: fileName => fileName,
    getCurrentDirectory: ts.sys.getCurrentDirectory,
    getNewLine: () => os.EOL,
  };

  const messages = [];
  let appTsConfig;
  let parsedTsConfig;
  let parsedCompilerOptions;
  try {
    const { config: readTsConfig, error } = ts.readConfigFile(
      paths.appTsConfig,
      ts.sys.readFile
    );

    if (error) {
      throw new Error(ts.formatDiagnostic(error, formatDiagnosticHost));
    }

    appTsConfig = readTsConfig;

    // Get TS to parse and resolve any "extends"
    // Calling this function also mutates the tsconfig above,
    // adding in "include" and "exclude", but the compilerOptions remain untouched
    let result;
    parsedTsConfig = immer(readTsConfig, config => {
      result = ts.parseJsonConfigFileContent(
        config,
        ts.sys,
        path.dirname(paths.appTsConfig)
      );
    });

    if (result.errors && result.errors.length) {
      throw new Error(
        ts.formatDiagnostic(result.errors[0], formatDiagnosticHost)
      );
    }

    parsedCompilerOptions = result.options;
  } catch (e) {
    if (e && e.name === 'SyntaxError') {
      console.error(
        chalk.red.bold(
          'Could not parse',
          chalk.cyan('tsconfig.json') + '.',
          'Please make sure it contains syntactically correct JSON.'
        )
      );
    }

    console.log(e && e.message ? `${e.message}` : '');
    process.exit(1);
  }

  if (appTsConfig.compilerOptions == null) {
    appTsConfig.compilerOptions = {};
    firstTimeSetup = true;
  }

  for (const option of Object.keys(compilerOptions)) {
    const { parsedValue, value, suggested, reason } = compilerOptions[option];

    const valueToCheck = parsedValue === undefined ? value : parsedValue;
    const coloredOption = chalk.cyan('compilerOptions.' + option);

    if (suggested != null) {
      if (parsedCompilerOptions[option] === undefined) {
        appTsConfig.compilerOptions[option] = suggested;
        messages.push(
          `${coloredOption} to be ${chalk.bold(
            'suggested'
          )} value: ${chalk.cyan.bold(suggested)} (this can be changed)`
        );
      }
    } else if (parsedCompilerOptions[option] !== valueToCheck) {
      appTsConfig.compilerOptions[option] = value;
      messages.push(
        `${coloredOption} ${chalk.bold(
          valueToCheck == null ? 'must not' : 'must'
        )} be ${valueToCheck == null ? 'set' : chalk.cyan.bold(value)}` +
          (reason != null ? ` (${reason})` : '')
      );
    }
  }

  // tsconfig will have the merged "include" and "exclude" by this point
  if (parsedTsConfig.include == null) {
    appTsConfig.include = ['src'];
    messages.push(
      `${chalk.cyan('include')} should be ${chalk.cyan.bold('src')}`
    );
  }

  if (messages.length > 0) {
    if (firstTimeSetup) {
      console.log(
        chalk.bold(
          'Your',
          chalk.cyan('tsconfig.json'),
          'has been populated with default values.'
        )
      );
      console.log();
    } else {
      console.warn(
        chalk.bold(
          'The following changes are being made to your',
          chalk.cyan('tsconfig.json'),
          'file:'
        )
      );
      messages.forEach(message => {
        console.warn('  - ' + message);
      });
      console.warn();
    }
    writeJson(paths.appTsConfig, appTsConfig);
  }

  // Reference `react-scripts` types
  if (!fs.existsSync(paths.appTypeDeclarations)) {
    fs.writeFileSync(
      paths.appTypeDeclarations,
      `/// <reference types="react-scripts" />${os.EOL}`
    );
  }
}

module.exports = verifyTypeScriptSetup;
<commit_msg>Fix react-jsx error (#9869)<commit_after>// @remove-file-on-eject
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

'use strict';

const chalk = require('react-dev-utils/chalk');
const fs = require('fs');
const resolve = require('resolve');
const path = require('path');
const paths = require('../../config/paths');
const os = require('os');
const semver = require('semver');
const immer = require('react-dev-utils/immer').produce;
const globby = require('react-dev-utils/globby').sync;

const hasJsxRuntime = (() => {
  if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
    return false;
  }

  try {
    require.resolve('react/jsx-runtime', { paths: [paths.appPath] });
    return true;
  } catch (e) {
    return false;
  }
})();

function writeJson(fileName, object) {
  fs.writeFileSync(
    fileName,
    JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL
  );
}

function verifyNoTypeScript() {
  const typescriptFiles = globby(
    ['**/*.(ts|tsx)', '!**/node_modules', '!**/*.d.ts'],
    { cwd: paths.appSrc }
  );
  if (typescriptFiles.length > 0) {
    console.warn(
      chalk.yellow(
        `We detected TypeScript in your project (${chalk.bold(
          `src${path.sep}${typescriptFiles[0]}`
        )}) and created a ${chalk.bold('tsconfig.json')} file for you.`
      )
    );
    console.warn();
    return false;
  }
  return true;
}

function verifyTypeScriptSetup() {
  let firstTimeSetup = false;

  if (!fs.existsSync(paths.appTsConfig)) {
    if (verifyNoTypeScript()) {
      return;
    }
    writeJson(paths.appTsConfig, {});
    firstTimeSetup = true;
  }

  const isYarn = fs.existsSync(paths.yarnLockFile);

  // Ensure typescript is installed
  let ts;
  try {
    // TODO: Remove this hack once `globalThis` issue is resolved
    // https://github.com/jsdom/jsdom/issues/2961
    const globalThisWasDefined = !!global.globalThis;

    ts = require(resolve.sync('typescript', {
      basedir: paths.appNodeModules,
    }));

    if (!globalThisWasDefined && !!global.globalThis) {
      delete global.globalThis;
    }
  } catch (_) {
    console.error(
      chalk.bold.red(
        `It looks like you're trying to use TypeScript but do not have ${chalk.bold(
          'typescript'
        )} installed.`
      )
    );
    console.error(
      chalk.bold(
        'Please install',
        chalk.cyan.bold('typescript'),
        'by running',
        chalk.cyan.bold(
          isYarn ? 'yarn add typescript' : 'npm install typescript'
        ) + '.'
      )
    );
    console.error(
      chalk.bold(
        'If you are not trying to use TypeScript, please remove the ' +
          chalk.cyan('tsconfig.json') +
          ' file from your package root (and any TypeScript files).'
      )
    );
    console.error();
    process.exit(1);
  }

  const compilerOptions = {
    // These are suggested values and will be set when not present in the
    // tsconfig.json
    // 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
    target: {
      parsedValue: ts.ScriptTarget.ES5,
      suggested: 'es5',
    },
    lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
    allowJs: { suggested: true },
    skipLibCheck: { suggested: true },
    esModuleInterop: { suggested: true },
    allowSyntheticDefaultImports: { suggested: true },
    strict: { suggested: true },
    forceConsistentCasingInFileNames: { suggested: true },
    noFallthroughCasesInSwitch: { suggested: true },

    // These values are required and cannot be changed by the user
    // Keep this in sync with the webpack config
    module: {
      parsedValue: ts.ModuleKind.ESNext,
      value: 'esnext',
      reason: 'for import() and import/export',
    },
    moduleResolution: {
      parsedValue: ts.ModuleResolutionKind.NodeJs,
      value: 'node',
      reason: 'to match webpack resolution',
    },
    resolveJsonModule: { value: true, reason: 'to match webpack loader' },
    isolatedModules: { value: true, reason: 'implementation limitation' },
    noEmit: { value: true },
    jsx: {
      parsedValue:
        hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
          ? ts.JsxEmit.ReactJSX
          : ts.JsxEmit.React,
      value:
        hasJsxRuntime && semver.gte(ts.version, '4.1.0-beta')
          ? 'react-jsx'
          : 'react',
      reason: 'to support the new JSX transform in React 17',
    },
    paths: { value: undefined, reason: 'aliased imports are not supported' },
  };

  const formatDiagnosticHost = {
    getCanonicalFileName: fileName => fileName,
    getCurrentDirectory: ts.sys.getCurrentDirectory,
    getNewLine: () => os.EOL,
  };

  const messages = [];
  let appTsConfig;
  let parsedTsConfig;
  let parsedCompilerOptions;
  try {
    const { config: readTsConfig, error } = ts.readConfigFile(
      paths.appTsConfig,
      ts.sys.readFile
    );

    if (error) {
      throw new Error(ts.formatDiagnostic(error, formatDiagnosticHost));
    }

    appTsConfig = readTsConfig;

    // Get TS to parse and resolve any "extends"
    // Calling this function also mutates the tsconfig above,
    // adding in "include" and "exclude", but the compilerOptions remain untouched
    let result;
    parsedTsConfig = immer(readTsConfig, config => {
      result = ts.parseJsonConfigFileContent(
        config,
        ts.sys,
        path.dirname(paths.appTsConfig)
      );
    });

    if (result.errors && result.errors.length) {
      throw new Error(
        ts.formatDiagnostic(result.errors[0], formatDiagnosticHost)
      );
    }

    parsedCompilerOptions = result.options;
  } catch (e) {
    if (e && e.name === 'SyntaxError') {
      console.error(
        chalk.red.bold(
          'Could not parse',
          chalk.cyan('tsconfig.json') + '.',
          'Please make sure it contains syntactically correct JSON.'
        )
      );
    }

    console.log(e && e.message ? `${e.message}` : '');
    process.exit(1);
  }

  if (appTsConfig.compilerOptions == null) {
    appTsConfig.compilerOptions = {};
    firstTimeSetup = true;
  }

  for (const option of Object.keys(compilerOptions)) {
    const { parsedValue, value, suggested, reason } = compilerOptions[option];

    const valueToCheck = parsedValue === undefined ? value : parsedValue;
    const coloredOption = chalk.cyan('compilerOptions.' + option);

    if (suggested != null) {
      if (parsedCompilerOptions[option] === undefined) {
        appTsConfig.compilerOptions[option] = suggested;
        messages.push(
          `${coloredOption} to be ${chalk.bold(
            'suggested'
          )} value: ${chalk.cyan.bold(suggested)} (this can be changed)`
        );
      }
    } else if (parsedCompilerOptions[option] !== valueToCheck) {
      appTsConfig.compilerOptions[option] = value;
      messages.push(
        `${coloredOption} ${chalk.bold(
          valueToCheck == null ? 'must not' : 'must'
        )} be ${valueToCheck == null ? 'set' : chalk.cyan.bold(value)}` +
          (reason != null ? ` (${reason})` : '')
      );
    }
  }

  // tsconfig will have the merged "include" and "exclude" by this point
  if (parsedTsConfig.include == null) {
    appTsConfig.include = ['src'];
    messages.push(
      `${chalk.cyan('include')} should be ${chalk.cyan.bold('src')}`
    );
  }

  if (messages.length > 0) {
    if (firstTimeSetup) {
      console.log(
        chalk.bold(
          'Your',
          chalk.cyan('tsconfig.json'),
          'has been populated with default values.'
        )
      );
      console.log();
    } else {
      console.warn(
        chalk.bold(
          'The following changes are being made to your',
          chalk.cyan('tsconfig.json'),
          'file:'
        )
      );
      messages.forEach(message => {
        console.warn('  - ' + message);
      });
      console.warn();
    }
    writeJson(paths.appTsConfig, appTsConfig);
  }

  // Reference `react-scripts` types
  if (!fs.existsSync(paths.appTypeDeclarations)) {
    fs.writeFileSync(
      paths.appTypeDeclarations,
      `/// <reference types="react-scripts" />${os.EOL}`
    );
  }
}

module.exports = verifyTypeScriptSetup;
<|endoftext|>


<commit_before>define(['jquery','jquery/rest','history','history/adapter'], function ($) {

var superdesk =
{
    apiUrl: typeof config !== 'undefined' ? config.api_url : '',
	/*!
	 * repository for templates
	 */
	tmplRepo: $('
'),
	/*!
	 * Loads template files via ajax and extracts the templates
	 *
	 * @param string path
	 * 	the url from which to load templates
	 * @param string selector
	 * 	optional, selector to use to match templates in loaded file
	 * @returns $.Deferred
	 */
	getTmpl: function(path)
	{
		var tplSelector = typeof arguments[1] != 'undefined' ? arguments[2] : "script[type='text/x-jQuery-tmpl']",
			dfd = new $.Deferred;
		$.ajax(path, {dataType: 'html'}).done(function(html)
		{
			var templates = [];
			$(html).each(function(i, elem){ if($(elem).is(tplSelector)) templates.push(elem); });
			superdesk.tmplRepo.append(templates);
			dfd.resolve(templates);
		});
		return dfd;
	},
	layouts: {},
	/*!
	 * load layout to superdesk object layouts
	 * @param string path
	 * 	layout path
	 * @param string name
	 * 	layout name
	 */
	loadLayout: function(path, name)
	{
		return $.ajax( superdesk.apiUrl+path, {dataType: 'html'})
			.done(function(data)
			{
				// need to wrap it in a
 tag for $ selector to work
				var layoutObject = $('
'+data+'
');
				if( typeof name == 'string')
					superdesk.layouts[name] = layoutObject;
				else
					name = layoutObject;

				return layoutObject;
			});
	},

	loaderTO: null,
	showLoader: function()
	{
	    $('#navbar-top .loader').css('display', 'block');
        this.loaderTO = setTimeout(function(){ $('#navbar-top .loader').css('display', 'none'); }, 20000);
	},
	hideLoader: function()
	{
	    $('#navbar-top .loader').css('display', 'none');
	    clearTimeout(this.loaderTO);
	},

	layoutPlaceholder: '#area-main',
	applyLayout: function(tmpl, data, callback)
	{
	    /*$(this.layoutPlaceholder).nextAll().each(function()
	    {
	        console.log(this);
	    });*/
	    return $(this.layoutPlaceholder).tmpl(tmpl, data, callback);
	},
	/*!
	 * cache repo
	 */
	cache: {actions: {}, scripts: {}, test: {}},
	ACTIONS_PATH_SEP: '.',
	/*!
	 * @param string path
	 * @returns $.Deferred()
	 */
	getActions: function(path)
	{
	    var dfd = $.Deferred(),
	    searchCache = function()
	    {
	        var results = [], searchForSubs = false, searchPath = path;
	        if( path.lastIndexOf('*') === path.length-1 )
	            searchPath = path.substr(0, path.length-1);

	        for( var i in superdesk.cache.actions )
                if( superdesk.cache.actions[i].Path.indexOf(searchPath) === 0 )
                    results.push(superdesk.cache.actions[i]);

	        return results;
	    };
	    var cachedResults = searchCache();
	    if( cachedResults.length === 0 )
		{
			new $.rest('GUI/Action?path='+path)
				.done(function(actions)
				{
				    for(var i in actions)
                        superdesk.cache.actions[actions[i].Path] = actions[i];
					dfd.resolve(searchCache());
				});
			return dfd;
		}
		return dfd.resolve(cachedResults);
	},

	getAction: function(path)
	{
	    var dfd = $.Deferred();
        if( !superdesk.cache.actions[path] )
        {
            var searchPath = path.substr(0, path.lastIndexOf(superdesk.ACTIONS_PATH_SEP));
            new $.rest('GUI/Action?path='+searchPath+'.*')
                .done(function(actions)
                {
                    for(var i in actions)
                        superdesk.cache.actions[actions[i].Path] = actions[i];
                    dfd.resolve(superdesk.cache.actions[path]);
                });
            return dfd;
        }
        return dfd.resolve(superdesk.cache.actions[path]);
	},
	/*!
	 *
	 */
	navigation:
	{
	    _repository: {},
	    _base: '',
	    _startPathname: '',
	    _titlePrefix: '',
	    getBase: function()
	    {
	        return this._base;
	    },
	    getStartPathname: function()
        {
            return this._startPathname;
        },
        /*!
         * bind a callback on history state or execute if already bound
         */
        bind: function(href, callback, title)
        {
            var History = window.History,
                State = History.getState();

            if( $.trim(State.data.href) != '' && this._repository[State.data.href]  )
            {
                callback.call();
                return;
            }

            this._repository[href] = callback;

            History.pushState({href: href},
                    title ? this._titlePrefix + title : null,
                    this._base + (!config.server_tech ? '?'+href : href));
            return callback;
        },
        /*!
         * app base url:
         *  check for standard base tag in html or just get the current url
         */
        init: function(callback)
        {
            var History = window.History,
                State = History.getState(),
                self = this,
                baseTag = $('base');

            History.options.debug = true;
            this._base = baseTag.length ? baseTag.attr('href') : History.getPageUrl().split('?')[0].split('#')[0];
            this._startPathname = window.History.getPageUrl().replace(this._base, '')
                                    .replace(/^\/+|\/+$/g, '').replace(/^\?+/g, '').replace(/#/g, '');
            var triggered;
            History.Adapter.bind( window, 'statechange', function()
            {
                var State = History.getState();
                (self._repository[State.data.href])();
                triggered = true;
            });

            if( typeof callback === 'function' )
            {
                this._repository[''] = callback;
                this._base = this._base;
                History.pushState( {href: ''}, $(document).prop('title'), this._base );
                !triggered && History.Adapter.trigger( window, 'statechange' );
            }
        }
	},
	/*!
	 *
	 */
	presentation: function(script, layout, args)
	{
		var _setScript = function(value){ script = value; };
		this.setScript = function(value){ _setScript(value); return this; };
		this.getScript = function(){ return script; };

		var _setLayout = function(value){ layout = value; };
		this.setLayout = function(value){ _setLayout(value); return this; };
		this.getLayout = function(){ return layout; };

		var _setArgs = function(value){ args = value; };
		this.setArgs = function(value){ _setArgs(value); return this; };
		this.getArgs = function(){ return args; };

		var script = script,
			layout = layout || null,
			args = args || null,
			self = this;

		/*!
		 * Loads and applies script to a layout object
		 *
		 * @param string scriptPath
		 * @param object layoutObject
		 * @param object additional
		 * 	additional parameters to be passed
		 */
		this.run = function()
		{
			if(arguments[0]) _setScript(arguments[0]); // set script
			if(arguments[1]) _setLayout(arguments[1]); // set layout
			if(arguments[2]) _setArgs(arguments[2]); // set args

			var dfd = $.Deferred();
			dfd.done(function(scriptText)
			{
				// TODO additional security checking here
				(new Function('layout', 'args', scriptText)).call(self, layout, args);
			});
			if( !superdesk.cache.scripts[script] )
			{
				$.ajax(superdesk.apiUrl + '/' + script, {dataType: 'text'})
					.done(function(data)
					{
						superdesk.cache.scripts[script] = data;
						dfd.resolve(data);
					});
				return dfd;
			}
			return dfd.resolve(superdesk.cache.scripts[script]);
		};
	}
};
superdesk.presentation.prototype =
{
	view:
	{
		prefix: function(){ return superdesk.apiUrl+'/content/gui/superdesk/'; },
		load: function(template)
		{
			return superdesk.getTmpl( (typeof this.prefix == 'function' ? this.prefix() : this.prefix) + template);
		},
		render: function(selector, data)
		{
			if(typeof selector == 'string') var tmpl = $(selector, superdesk.tmplRepo);
			else var tmpl = selector;
			return $($.tmpl(tmpl, data));
		}
	},
	form:
	{
		add: function(html, nodeName)
		{
			if(!nodeName) return html;
			$(html).find('input, textarea, select').each(function()
			{
				var name = $(this).attr('name') || '';
				$(this).attr('name', name.replace(/^([^\[]+)/, nodeName+'[$1]'));
			});
			return $(html);
		}
	}
};

$.extend($, {superdesk: superdesk});
return superdesk;
});<commit_msg>stupid history...<commit_after>define(['jquery','jquery/rest','history','history/adapter'], function ($) {

var superdesk =
{
    apiUrl: typeof config !== 'undefined' ? config.api_url : '',
	/*!
	 * repository for templates
	 */
	tmplRepo: $('
'),
	/*!
	 * Loads template files via ajax and extracts the templates
	 *
	 * @param string path
	 * 	the url from which to load templates
	 * @param string selector
	 * 	optional, selector to use to match templates in loaded file
	 * @returns $.Deferred
	 */
	getTmpl: function(path)
	{
		var tplSelector = typeof arguments[1] != 'undefined' ? arguments[2] : "script[type='text/x-jQuery-tmpl']",
			dfd = new $.Deferred;
		$.ajax(path, {dataType: 'html'}).done(function(html)
		{
			var templates = [];
			$(html).each(function(i, elem){ if($(elem).is(tplSelector)) templates.push(elem); });
			superdesk.tmplRepo.append(templates);
			dfd.resolve(templates);
		});
		return dfd;
	},
	layouts: {},
	/*!
	 * load layout to superdesk object layouts
	 * @param string path
	 * 	layout path
	 * @param string name
	 * 	layout name
	 */
	loadLayout: function(path, name)
	{
		return $.ajax( superdesk.apiUrl+path, {dataType: 'html'})
			.done(function(data)
			{
				// need to wrap it in a
 tag for $ selector to work
				var layoutObject = $('
'+data+'
');
				if( typeof name == 'string')
					superdesk.layouts[name] = layoutObject;
				else
					name = layoutObject;

				return layoutObject;
			});
	},

	loaderTO: null,
	showLoader: function()
	{
	    $('#navbar-top .loader').css('display', 'block');
        this.loaderTO = setTimeout(function(){ $('#navbar-top .loader').css('display', 'none'); }, 20000);
	},
	hideLoader: function()
	{
	    $('#navbar-top .loader').css('display', 'none');
	    clearTimeout(this.loaderTO);
	},

	layoutPlaceholder: '#area-main',
	applyLayout: function(tmpl, data, callback)
	{
	    /*$(this.layoutPlaceholder).nextAll().each(function()
	    {
	        console.log(this);
	    });*/
	    return $(this.layoutPlaceholder).tmpl(tmpl, data, callback);
	},
	/*!
	 * cache repo
	 */
	cache: {actions: {}, scripts: {}, test: {}},
	ACTIONS_PATH_SEP: '.',
	/*!
	 * @param string path
	 * @returns $.Deferred()
	 */
	getActions: function(path)
	{
	    var dfd = $.Deferred(),
	    searchCache = function()
	    {
	        var results = [], searchForSubs = false, searchPath = path;
	        if( path.lastIndexOf('*') === path.length-1 )
	            searchPath = path.substr(0, path.length-1);

	        for( var i in superdesk.cache.actions )
                if( superdesk.cache.actions[i].Path.indexOf(searchPath) === 0 )
                    results.push(superdesk.cache.actions[i]);

	        return results;
	    };
	    var cachedResults = searchCache();
	    if( cachedResults.length === 0 )
		{
			new $.rest('GUI/Action?path='+path)
				.done(function(actions)
				{
				    for(var i in actions)
                        superdesk.cache.actions[actions[i].Path] = actions[i];
					dfd.resolve(searchCache());
				});
			return dfd;
		}
		return dfd.resolve(cachedResults);
	},

	getAction: function(path)
	{
	    var dfd = $.Deferred();
        if( !superdesk.cache.actions[path] )
        {
            var searchPath = path.substr(0, path.lastIndexOf(superdesk.ACTIONS_PATH_SEP));
            new $.rest('GUI/Action?path='+searchPath+'.*')
                .done(function(actions)
                {
                    for(var i in actions)
                        superdesk.cache.actions[actions[i].Path] = actions[i];
                    dfd.resolve(superdesk.cache.actions[path]);
                });
            return dfd;
        }
        return dfd.resolve(superdesk.cache.actions[path]);
	},
	/*!
	 *
	 */
	navigation:
	{
	    _repository: {},
	    _base: '',
	    _startPathname: '',
	    _titlePrefix: '',
	    getBase: function()
	    {
	        return this._base;
	    },
	    getStartPathname: function()
        {
            return this._startPathname;
        },
        /*!
         * bind a callback on history state or execute if already bound
         */
        bind: function(href, callback, title)
        {
            var History = window.History,
                State = History.getState();

            if( $.trim(State.data.href) != '' && this._repository[State.data.href]  )
                callback.call();

            this._repository[href] = callback;

            History.pushState({href: href},
                    title ? this._titlePrefix + title : null,
                    this._base + (!config.server_tech ? '?'+href : href));
            return callback;
        },
        /*!
         * app base url:
         *  check for standard base tag in html or just get the current url
         */
        init: function(callback)
        {
            var History = window.History,
                State = History.getState(),
                self = this,
                baseTag = $('base');

            History.options.debug = true;
            this._base = baseTag.length ? baseTag.attr('href') : History.getPageUrl().split('?')[0].split('#')[0];
            this._startPathname = window.History.getPageUrl().replace(this._base, '')
                                    .replace(/^\/+|\/+$/g, '').replace(/^\?+/g, '').replace(/#/g, '');
            var triggered;
            History.Adapter.bind( window, 'statechange', function()
            {
                var State = History.getState();
                (self._repository[State.data.href])();
                triggered = true;
            });

            if( typeof callback === 'function' )
            {
                this._repository[''] = callback;
                this._base = this._base;
                History.pushState( {href: ''}, $(document).prop('title'), this._base );
                !triggered && History.Adapter.trigger( window, 'statechange' );
            }
        }
	},
	/*!
	 *
	 */
	presentation: function(script, layout, args)
	{
		var _setScript = function(value){ script = value; };
		this.setScript = function(value){ _setScript(value); return this; };
		this.getScript = function(){ return script; };

		var _setLayout = function(value){ layout = value; };
		this.setLayout = function(value){ _setLayout(value); return this; };
		this.getLayout = function(){ return layout; };

		var _setArgs = function(value){ args = value; };
		this.setArgs = function(value){ _setArgs(value); return this; };
		this.getArgs = function(){ return args; };

		var script = script,
			layout = layout || null,
			args = args || null,
			self = this;

		/*!
		 * Loads and applies script to a layout object
		 *
		 * @param string scriptPath
		 * @param object layoutObject
		 * @param object additional
		 * 	additional parameters to be passed
		 */
		this.run = function()
		{
			if(arguments[0]) _setScript(arguments[0]); // set script
			if(arguments[1]) _setLayout(arguments[1]); // set layout
			if(arguments[2]) _setArgs(arguments[2]); // set args

			var dfd = $.Deferred();
			dfd.done(function(scriptText)
			{
				// TODO additional security checking here
				(new Function('layout', 'args', scriptText)).call(self, layout, args);
			});
			if( !superdesk.cache.scripts[script] )
			{
				$.ajax(superdesk.apiUrl + '/' + script, {dataType: 'text'})
					.done(function(data)
					{
						superdesk.cache.scripts[script] = data;
						dfd.resolve(data);
					});
				return dfd;
			}
			return dfd.resolve(superdesk.cache.scripts[script]);
		};
	}
};
superdesk.presentation.prototype =
{
	view:
	{
		prefix: function(){ return superdesk.apiUrl+'/content/gui/superdesk/'; },
		load: function(template)
		{
			return superdesk.getTmpl( (typeof this.prefix == 'function' ? this.prefix() : this.prefix) + template);
		},
		render: function(selector, data)
		{
			if(typeof selector == 'string') var tmpl = $(selector, superdesk.tmplRepo);
			else var tmpl = selector;
			return $($.tmpl(tmpl, data));
		}
	},
	form:
	{
		add: function(html, nodeName)
		{
			if(!nodeName) return html;
			$(html).find('input, textarea, select').each(function()
			{
				var name = $(this).attr('name') || '';
				$(this).attr('name', name.replace(/^([^\[]+)/, nodeName+'[$1]'));
			});
			return $(html);
		}
	}
};

$.extend($, {superdesk: superdesk});
return superdesk;
});<|endoftext|>


<commit_before>// for use with the PEG grammar (compiled using  http://canopy.jcoglan.com/references.html)

'use strict';

var AST = {};
module.exports = AST;

var grammar = require('./grammar');

var make_bin_op = function(name, ev) {
    AST[name] = function(left, right) {
        this.left = left; this.right = right;
    };

    AST[name].prototype.Eval = ev;
};

make_bin_op('AddOp', function(s) { return this.left.Eval() + this.right.Eval(); });
make_bin_op('SubOp', function(s) { return this.left.Eval() - this.right.Eval(); });
make_bin_op('DivideOp', function(s) { return this.left.Eval() / this.right.Eval(); });
make_bin_op('MultOp', function(s) { return this.left.Eval() * this.right.Eval(); });

AST.Literal = function(val) { this.val = val; };
AST.Literal.prototype.Eval = function(s) { return this.val; };

AST.UnaryMinus = function(val) { this.val = val; };
AST.UnaryMinus.prototype.Eval = function(s) { return -this.val; };

AST.Ref = function(name) { this.name = name; };
AST.Ref.prototype.Eval = function(scope) { return scope.get(this.name); }

AST.fromSource = function(source) {
    grammar.Parser.NumberLiteral = {
        isa: 'NumberLiteral',
        transform: function() { return new AST.Literal(Number(this.textValue));},
    };
    grammar.Parser.StringLiteral = {
        isa: 'StringLiteral',
        transform: function() { return new AST.Literal(this.textValue); },
    };
    grammar.Parser.SumNode = {
        isa: 'SumNode',
        transform: function() {
            return new AST.AddOp(this.ls.transform(), this.rs.transform());
        },
    };
    grammar.Parser.ProductNode = {
        isa: 'ProductNode',
        transform: function() {
            return new AST.MultOp(this.ls.transform(), this.rs.transform());
        },
    };
    grammar.Parser.ValueNode = {
        isa: 'ValueNode',
        transform: function() { return this.elements[0].transform(); },
    }

    return grammar.parse(source);
};
<commit_msg>Add subtraction<commit_after>// for use with the PEG grammar (compiled using  http://canopy.jcoglan.com/references.html)

'use strict';

var AST = {};
module.exports = AST;

var grammar = require('./grammar');

var make_bin_op = function(name, ev) {
    AST[name] = function(left, right) {
        this.left = left; this.right = right;
    };

    AST[name].prototype.Eval = ev;
};

make_bin_op('AddOp', function(s) { return this.left.Eval() + this.right.Eval(); });
make_bin_op('SubOp', function(s) { return this.left.Eval() - this.right.Eval(); });
make_bin_op('DivideOp', function(s) { return this.left.Eval() / this.right.Eval(); });
make_bin_op('MultOp', function(s) { return this.left.Eval() * this.right.Eval(); });

AST.Literal = function(val) { this.val = val; };
AST.Literal.prototype.Eval = function(s) { return this.val; };

AST.UnaryMinus = function(val) { this.val = val; };
AST.UnaryMinus.prototype.Eval = function(s) { return -this.val; };

AST.Ref = function(name) { this.name = name; };
AST.Ref.prototype.Eval = function(scope) { return scope.get(this.name); }

AST.fromSource = function(source) {
    grammar.Parser.NumberLiteral = {
        isa: 'NumberLiteral',
        transform: function() { return new AST.Literal(Number(this.textValue));},
    };
    grammar.Parser.StringLiteral = {
        isa: 'StringLiteral',
        transform: function() { return new AST.Literal(this.textValue); },
    };
    grammar.Parser.SumNode = {
        isa: 'SumNode',
        transform: function() {
            return new AST.AddOp(this.ls.transform(), this.rs.transform());
        },
    };
    grammar.Parser.SubNode = {
        isa: 'SumNode',
        transform: function() {
            return new AST.SubOp(this.ls.transform(), this.rs.transform());
        },
    };
    grammar.Parser.ProductNode = {
        isa: 'ProductNode',
        transform: function() {
            return new AST.MultOp(this.ls.transform(), this.rs.transform());
        },
    };
    grammar.Parser.ValueNode = {
        isa: 'ValueNode',
        transform: function() { return this.elements[0].transform(); },
    }

    return grammar.parse(source);
};
<|endoftext|>


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

var path = require('path')
var log = require('npmlog')
var fs = require('fs')
var extend = require('xtend')

var rc = require('./rc')
var download = require('./download')

var prebuildClientVersion = require('./package.json').version
if (rc.version) {
  console.log(prebuildClientVersion)
  process.exit(0)
}

if (rc.path) process.chdir(rc.path)

log.heading = 'prebuild-install'
if (rc.verbose) {
  log.level = 'verbose'
} else if (process.env.npm_config_loglevel) {
  log.level = process.env.npm_config_loglevel
}

if (!fs.existsSync('package.json')) {
  log.error('setup', 'No package.json found. Aborting...')
  process.exit(1)
}

var pkg = require(path.resolve('package.json'))

if (rc.help) {
  console.error(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf-8'))
  process.exit(0)
}

log.info('begin', 'Prebuild-install version', prebuildClientVersion)

var opts = extend(rc, {pkg: pkg, log: log})

if (opts.download) {
  if (opts.prebuild === false) {
    log.info('install', '--no-prebuild specified, not attempting download.')
    process.exit(1)
  }

  download(opts, function (err) {
    if (err) {
      log.warn('install', err.message)
      return process.exit(1)
    }
    log.info('install', 'Prebuild successfully installed!')
  })
}
<commit_msg>bail out on download for git and dev installations<commit_after>#!/usr/bin/env node

var path = require('path')
var log = require('npmlog')
var fs = require('fs')
var extend = require('xtend')

var rc = require('./rc')
var download = require('./download')

var prebuildClientVersion = require('./package.json').version
if (rc.version) {
  console.log(prebuildClientVersion)
  process.exit(0)
}

if (rc.path) process.chdir(rc.path)

log.heading = 'prebuild-install'
if (rc.verbose) {
  log.level = 'verbose'
} else if (process.env.npm_config_loglevel) {
  log.level = process.env.npm_config_loglevel
}

if (!fs.existsSync('package.json')) {
  log.error('setup', 'No package.json found. Aborting...')
  process.exit(1)
}

var pkg = require(path.resolve('package.json'))

if (rc.help) {
  console.error(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf-8'))
  process.exit(0)
}

log.info('begin', 'Prebuild-install version', prebuildClientVersion)

var opts = extend(rc, {pkg: pkg, log: log})

if (opts.download) {
  if (!(typeof pkg._from === 'string')) {
    log.info('install', 'installing inside prebuild-install directory, skipping download.')
    process.exit(1)
  } else if (pkg._from.length > 4 && pkg._from.substr(0, 4) === 'git+') {
    log.info('install', 'installing from git repository, skipping download.')
    process.exit(1)
  }

  if (opts.prebuild === false) {
    log.info('install', '--no-prebuild specified, not attempting download.')
    process.exit(1)
  }

  download(opts, function (err) {
    if (err) {
      log.warn('install', err.message)
      return process.exit(1)
    }
    log.info('install', 'Prebuild successfully installed!')
  })
}
<|endoftext|>


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

/**
 * Dependencies
 */
var lomadee = require('./')
  , nomnom = require('nomnom');

var opts = nomnom
  .script('buscape')
  .nocolors()
  .option('id', {
    abbr: 'i',
    required: true,
    help: 'Lomadee api key'
  })
  .option('price', {
    abbr: 'p',
    help: 'Price range in the form <min>..<max>'
  })
  .option('source', {
    abbr: 's',
    help: 'Set source id'
  })
  .option('country', {
    abbr: 'c',
    help: 'Country to query in'
  })
  .option('keywords', {
    abbr: 'k',
    required: true,
    help: 'Keywords to search'
  })
  .option('test', {
    abbr: 't',
    flag: true,
    help: 'Test mode'
  })
  .option('limit', {
    abbr: 'l',
    help: 'Limit number of returned products'
  })
  .option('one', {
    abbr: '1',
    help: 'Return only one product',
    flag: true,
    default: false
  })
  .parse();

lomadee({keywords: opts.keywords})
  .id(opts.id)
  .country(opts.country)
  .test(opts.test)
  .one(opts.one)
  .limit(opts.limit)
  .source(opts.source)
  .done(function (err, res) {
    console.log(JSON.stringify(res));
  });
<commit_msg>Add clientid param to bin<commit_after>#!/usr/bin/env node

/**
 * Dependencies
 */
var lomadee = require('./')
  , nomnom = require('nomnom');

var opts = nomnom
  .script('buscape')
  .nocolors()
  .option('id', {
    abbr: 'i',
    required: true,
    help: 'Lomadee api key'
  })
  .option('price', {
    abbr: 'p',
    help: 'Price range in the form <min>..<max>'
  })
  .option('source', {
    abbr: 's',
    help: 'Set source id'
  })
  .option('country', {
    abbr: 'c',
    help: 'Country to query in'
  })
  .option('keywords', {
    abbr: 'k',
    required: true,
    help: 'Keywords to search'
  })
  .option('test', {
    abbr: 't',
    flag: true,
    help: 'Test mode'
  })
  .option('limit', {
    abbr: 'l',
    help: 'Limit number of returned products'
  })
  .option('one', {
    abbr: '1',
    help: 'Return only one product',
    flag: true,
    default: false
  })
  .option('client', {
    help: 'Set client ip'
  })
  .parse();

lomadee({keywords: opts.keywords})
  .id(opts.id)
  .country(opts.country)
  .test(opts.test)
  .one(opts.one)
  .limit(opts.limit)
  .source(opts.source)
  .client(opts.client)
  .done(function (err, res) {
    console.log(JSON.stringify(res));
  });
<|endoftext|>


<commit_before>#!/usr/bin/env node
const { setup } = require('setup-eslint-config');

const packageInfo = require('./package.json');

setup({
  name: 'eslint-config-relekang',
  packageInfo,
  prompts: [
    { name: 'react', type: 'confirm', message: 'Use react?' },
    { name: 'jest', type: 'confirm', message: 'Use jest?' },
  ],
  createEslintConfig: config => {
    const eslintConfig = { extends: ['relekang'] };
    if (config.babel) {
      eslintConfig.parser = 'babel-eslint';
    }
    if (config.typescript) {
      eslintConfig.parser = 'typescript-eslint-parser';
      eslintConfig.extends.push('relekang/configs/typescript');
    }
    if (config.jest) {
      eslintConfig.extends.push('relekang/configs/jest');
    }
    if (config.flowtype) {
      eslintConfig.extends.push('relekang/configs/flowtype');
    }
    if (config.react) {
      eslintConfig.extends.push('relekang/configs/react');
    }
    return eslintConfig;
  },
  createDependencyList: config => {
    const list = [
      'eslint',
      'eslint-plugin-prettier',
      'eslint-config-prettier',
      'prettier',
    ];
    if (config.babel) {
      list.push('babel-eslint');
    }
    if (config.typescript) {
      list.push('typescript-eslint-parser');
      list.push('eslint-plugin-typescript');
    }
    if (config.react) {
      list.push('eslint-plugin-react');
    }
    return list;
  },
});
<commit_msg>fix: Add react-hooks plugins<commit_after>#!/usr/bin/env node
const { setup } = require('setup-eslint-config');

const packageInfo = require('./package.json');

setup({
  name: 'eslint-config-relekang',
  packageInfo,
  prompts: [
    { name: 'react', type: 'confirm', message: 'Use react?' },
    { name: 'jest', type: 'confirm', message: 'Use jest?' },
  ],
  createEslintConfig: config => {
    const eslintConfig = { extends: ['relekang'] };
    if (config.babel) {
      eslintConfig.parser = 'babel-eslint';
    }
    if (config.typescript) {
      eslintConfig.parser = 'typescript-eslint-parser';
      eslintConfig.extends.push('relekang/configs/typescript');
    }
    if (config.jest) {
      eslintConfig.extends.push('relekang/configs/jest');
    }
    if (config.flowtype) {
      eslintConfig.extends.push('relekang/configs/flowtype');
    }
    if (config.react) {
      eslintConfig.extends.push('relekang/configs/react');
    }
    return eslintConfig;
  },
  createDependencyList: config => {
    const list = [
      'eslint',
      'eslint-plugin-prettier',
      'eslint-config-prettier',
      'prettier',
    ];
    if (config.babel) {
      list.push('babel-eslint');
    }
    if (config.typescript) {
      list.push('typescript-eslint-parser');
      list.push('eslint-plugin-typescript');
    }
    if (config.react) {
      list.push('eslint-plugin-react');
      list.push('eslint-plugin-react-hooks');
    }
    return list;
  },
});
<|endoftext|>


<commit_before>var Discord = require('discord.js');
var fs = require('fs');
var path = require('path');
var http = require('http');
var k2 = new Discord.Client();

var token;
if (fs.existsSync('token')) {
	token = fs.readFileSync('token', 'utf8').replace(/^\s+|\s+$/g,'');
}
else {
	token = process.env.TOKEN;
	// to keep Heroku happy
	http.createServer(function(req,res) {
		res.writeHead(200, {'Content-Type': 'text/plain'});
		res.write('K-2SO is operational.\n');
	}).listen(process.env.PORT);
}
k2.login(token);

function sleep (ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
} // sleep

k2.on("ready", function (rawEvent) {
	console.log("Connected to server");
	k2.user.setPresence({ game : { name : '!k2help' }});
}); // on.ready

var responseDict = {
	"hello": "The captain says you're a friend. I will not kill you.",
	"goodbye" : "Good riddance.",
	"hug" : "I'm not giving you a hug.",
	"k2help" : "You know, I'm not that complicated. You can just figure it out.",
	"fliptable" : "(╯°□°)╯︵ ┻━┻"
}

var contestInProgress = false;
var contestEndTime;
var contestDetails;
var contestParticipants = [];
var functionDict = {
    "contest": function() {
        if (contestInProgress) {
            this.reply("There is already a contest in progress.");
            return;
        }
        var arguments = this.content.substring(1).split("!");
        arguments.shift(); // just the arguments
        if (arguments.length !== 2) {
            this.channel.sendMessage("The syntax of this command is: \n" +
				"!contest !<what you are giving away> !<how long the contest will last" +
				" [minutes]>", { code : true });
            return;
        }
        contestInProgress = true;
        contestParticipants.push("No one");
        this.channel.sendMessage("@everyone, a contest has begun! " + this.author +
            " is giving away " + arguments[0] + " in " + arguments[1] + " minute(s)! " +
            "Use !entercontest to enter the contest!");
		contestEndTime = new Date(new Date().getTime() + 60*1000*arguments[1]);
		contestDetails = [ this.author, arguments[0], contestEndTime ];
        setTimeout(function(message, prize) {
            message.channel.sendMessage("@everyone, " + message.author + "'s contest has ended! " +
				"Out of " + contestParticipants.length-1 + " entries, " +
				contestParticipants[Math.ceil(Math.random()*(contestParticipants.length-1))] +
                " has won " + prize + "!");
		contestParticipants = [];
		contestInProgress = false;
        }, 1000*60*arguments[1], this, arguments[0]);
    },
    "entercontest": function() {
        if (!contestInProgress) {
            this.reply("What contest?");
            return;
        }
        if (contestParticipants.indexOf(this.author) !== -1) {
            this.reply("Only one entry per person. That is, unless you know a guy.");
            return;
        }
        contestParticipants.push(this.author);
        this.channel.sendMessage("Your entry has been received. Good luck!");
    },
	"conteststatus": function() {
		if (!contestInProgress) {
			this.reply("What contest?");
			return;
		}
		this.channel.sendMessage("The current contest was started by " + contestDetails[0] +
			", the prize is " + contestDetails[1] + ", and the contest ends at " +
			contestDetails[2] + ".");
	},
    "endcontest": function() {
        if (!contestInProgress) {
            this.reply("What contest?");
            return;
        }
		if (this.author !== contestDetails[0]) {
			this.channel.sendMessage("This isn't your contest.");
			return;
		}
        contestInProgress = false;
        this.channel.sendMessage("@everyone, " + this.author + " has ended the contest "  +
            "prematurely, similar to how their most recent sexual encounter ended.");
    }
}

var audioTimeout = new Date();
function findInVoiceChannel(guild, userName) {
	return guild.channels.find(function(channel) {
		return (channel.type === "voice"
			&& channel.members.find(function(member) {
				return member.user.username === userName;
		})); // find member;
	});
} // findInVoiceChannel

function playAudioInChannel(tchannel, vchannel, path) {
	if (new Date().getTime() < audioTimeout) {
		tchannel.sendMessage("Have some patience.");
		return;
	}
	audioTimeout = new Date();
	audioTimeout = audioTimeout.setMinutes(audioTimeout.getMinutes() + 5);
	vchannel.join().then(connection => {
		console.log("Joined " + vchannel.name);
        setTimeout(function() {
            const dispatch = connection.playFile(path,
                { volume : 0.5 }, function(error, intent) {
                intent.on("error", function(err) {
                    console.log("playFile: " + error);
                })
            });
            dispatch.on('speaking',(val) =>  {
			if (!val) { connection.disconnect(); }
			})
			}, 750); })
        .catch(console.log);
	vchannel.leave();
	voiceReactInProgress = false;
}

k2.on("message", function (message) {
	var author = message.author;
	var channel = message.channel;
    if (message.content.substring(0, 1) == "!") {
        var arguments = message.content.substring(1).split(" ");
        var command = arguments[0];
        arguments.shift(); // just the arguments
        if (responseDict[command]) {
        	channel.sendMessage(responseDict[command]);
        } // if
        else if (functionDict[command]) {
            functionDict[command].call(message);
        }
    } // if
	// non-command responses
	else {
	 	if (message.toString().indexOf("JOHN CENA") !== -1) {
			message.react("\uD83D\uDCA5"); 	// boom
			message.react("\uD83C\uDFBA"); 	// trumpet
		} // if
		if (message.toString().toLowerCase().indexOf("who is champ?") !== -1) {
			console.log("Hint: It's John Cena");
			var vchannel = findInVoiceChannel(message.guild,
				author.username);
			if (vchannel == undefined) {
				message.reply("THAT QUESTION WILL BE ANSWERED THIS SUNDAY!");
			} // if
			else {
				voiceReactInProgress = true;
				playAudioInChannel(channel, vchannel, "audio/whoischamp.mp3");
				voiceReactInProgress = false;

			} // else
					} // if
	} // else
}); // on.message
<commit_msg>Fucking NaN...<commit_after>var Discord = require('discord.js');
var fs = require('fs');
var path = require('path');
var http = require('http');
var k2 = new Discord.Client();

var token;
if (fs.existsSync('token')) {
	token = fs.readFileSync('token', 'utf8').replace(/^\s+|\s+$/g,'');
}
else {
	token = process.env.TOKEN;
	// to keep Heroku happy
	http.createServer(function(req,res) {
		res.writeHead(200, {'Content-Type': 'text/plain'});
		res.write('K-2SO is operational.\n');
	}).listen(process.env.PORT);
}
k2.login(token);

function sleep (ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
} // sleep

k2.on("ready", function (rawEvent) {
	console.log("Connected to server");
	k2.user.setPresence({ game : { name : '!k2help' }});
}); // on.ready

var responseDict = {
	"hello": "The captain says you're a friend. I will not kill you.",
	"goodbye" : "Good riddance.",
	"hug" : "I'm not giving you a hug.",
	"k2help" : "You know, I'm not that complicated. You can just figure it out.",
	"fliptable" : "(╯°□°)╯︵ ┻━┻"
}

var contestInProgress = false;
var contestEndTime;
var contestDetails;
var contestNumParticipants;
var contestParticipants = [];
var functionDict = {
    "contest": function() {
        if (contestInProgress) {
            this.reply("There is already a contest in progress.");
            return;
        }
        var arguments = this.content.substring(1).split("!");
        arguments.shift(); // just the arguments
        if (arguments.length !== 2) {
            this.channel.sendMessage("The syntax of this command is: \n" +
				"!contest !<what you are giving away> !<how long the contest will last" +
				" [minutes]>", { code : true });
            return;
        }
        contestInProgress = true;
        contestNumParticipants = contestParticipants.push("No one");
        this.channel.sendMessage("@everyone, a contest has begun! " + this.author +
            " is giving away " + arguments[0] + " in " + arguments[1] + " minute(s)! " +
            "Use !entercontest to enter the contest!");
		contestEndTime = new Date(new Date().getTime() + 60*1000*arguments[1]);
		contestDetails = [ this.author, arguments[0], contestEndTime ];
        setTimeout(function(message, prize) {
            message.channel.sendMessage("@everyone, " + message.author + "'s contest has ended! " +
				"Out of " + (contestParticipants.length-1).toString() + " entries, " +
				contestParticipants[Math.ceil(Math.random()*(contestParticipants.length-1))] +
                " has won " + prize + "!");
		contestParticipants = [];
		contestInProgress = false;
        }, 1000*60*arguments[1], this, arguments[0]);
    },
    "entercontest": function() {
        if (!contestInProgress) {
            this.reply("What contest?");
            return;
        }
        if (contestParticipants.indexOf(this.author) !== -1) {
            this.reply("Only one entry per person. That is, unless you know a guy.");
            return;
        }
        contestNumParticipants = contestParticipants.push(this.author);
        this.channel.sendMessage("Your entry has been received. Good luck!");
    },
	"conteststatus": function() {
		if (!contestInProgress) {
			this.reply("What contest?");
			return;
		}
		this.channel.sendMessage("The current contest was started by " + contestDetails[0] +
			", the prize is " + contestDetails[1] + ", and the contest ends at " +
			contestDetails[2] + ".");
	},
    "endcontest": function() {
        if (!contestInProgress) {
            this.reply("What contest?");
            return;
        }
		if (this.author !== contestDetails[0]) {
			this.channel.sendMessage("This isn't your contest.");
			return;
		}
        contestInProgress = false;
        this.channel.sendMessage("@everyone, " + this.author + " has ended the contest "  +
            "prematurely, similar to how their most recent sexual encounter ended.");
    }
}

var audioTimeout = new Date();
function findInVoiceChannel(guild, userName) {
	return guild.channels.find(function(channel) {
		return (channel.type === "voice"
			&& channel.members.find(function(member) {
				return member.user.username === userName;
		})); // find member;
	});
} // findInVoiceChannel

function playAudioInChannel(tchannel, vchannel, path) {
	if (new Date().getTime() < audioTimeout) {
		tchannel.sendMessage("Have some patience.");
		return;
	}
	audioTimeout = new Date();
	audioTimeout = audioTimeout.setMinutes(audioTimeout.getMinutes() + 5);
	vchannel.join().then(connection => {
		console.log("Joined " + vchannel.name);
        setTimeout(function() {
            const dispatch = connection.playFile(path,
                { volume : 0.5 }, function(error, intent) {
                intent.on("error", function(err) {
                    console.log("playFile: " + error);
                })
            });
            dispatch.on('speaking',(val) =>  {
			if (!val) { connection.disconnect(); }
			})
			}, 750); })
        .catch(console.log);
	vchannel.leave();
	voiceReactInProgress = false;
}

k2.on("message", function (message) {
	var author = message.author;
	var channel = message.channel;
    if (message.content.substring(0, 1) == "!") {
        var arguments = message.content.substring(1).split(" ");
        var command = arguments[0];
        arguments.shift(); // just the arguments
        if (responseDict[command]) {
        	channel.sendMessage(responseDict[command]);
        } // if
        else if (functionDict[command]) {
            functionDict[command].call(message);
        }
    } // if
	// non-command responses
	else {
	 	if (message.toString().indexOf("JOHN CENA") !== -1) {
			message.react("\uD83D\uDCA5"); 	// boom
			message.react("\uD83C\uDFBA"); 	// trumpet
		} // if
		if (message.toString().toLowerCase().indexOf("who is champ?") !== -1) {
			console.log("Hint: It's John Cena");
			var vchannel = findInVoiceChannel(message.guild,
				author.username);
			if (vchannel == undefined) {
				message.reply("THAT QUESTION WILL BE ANSWERED THIS SUNDAY!");
			} // if
			else {
				voiceReactInProgress = true;
				playAudioInChannel(channel, vchannel, "audio/whoischamp.mp3");
				voiceReactInProgress = false;

			} // else
					} // if
	} // else
}); // on.message
<|endoftext|>


<commit_before>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
})

bot.on('message', (message) =>  {
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
})

exports.bot = bot
exports.config = config
exports.commands = {
	master: {},
	moderator: {},
	default: {},
	dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
	exports.commands[type][name] = {}
	exports.commands[type][name]['aliases'] = aliases
	exports.commands[type][name]['description'] = description
	exports.commands[type][name]['usage'] = usage
	exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
	var req = require(path)
	if (reload) {
		console.log('Reloaded script at ' + path)
	} else {
		console.log('Script loaded at ' + path)
	}
}

exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./scripts/')
commands.forEach(script => {
	if (script.substring(script.length - 3, script.length) === '.js') {
		exports.loadScript('./scripts/' + script)
	}
})

bot.login(process.env.BOT_TOKEN)<commit_msg>Fixed Bugs<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
})

bot.on('message', (message) =>  {
	if(message.content.startsWith(config.prefix))
	{
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
	}
})

exports.bot = bot
exports.config = config
exports.commands = {
	master: {},
	moderator: {},
	default: {},
	dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
	exports.commands[type][name] = {}
	exports.commands[type][name]['aliases'] = aliases
	exports.commands[type][name]['description'] = description
	exports.commands[type][name]['usage'] = usage
	exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
	var req = require(path)
	if (reload) {
		console.log('Reloaded script at ' + path)
	} else {
		console.log('Script loaded at ' + path)
	}
}

exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./scripts/')
commands.forEach(script => {
	if (script.substring(script.length - 3, script.length) === '.js') {
		exports.loadScript('./scripts/' + script)
	}
})

bot.login(process.env.BOT_TOKEN)<|endoftext|>


<commit_before>if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');
var solver = require('./solver31.js');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

controller.hears(['play'], 'direct_message,direct_mention,mention', function(bot, message) {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'lebe-lebe-matabelo',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    bot.reply(message, '.......Get ready in.......')
    setTimeout(function(){ bot.reply(message, '...............3..............'); }, 1000);
    setTimeout(function(){ bot.reply(message, '...............2..............'); }, 2000);
    setTimeout(function(){ bot.reply(message, '...............1..............'); }, 3000);
    setTimeout(function(){
        controller.storage.channels.get(message.channel, function(err, data){
            var targetNumber = 28;
            if(data && data.targetNumber) {
                console.log("CUPU")
                targetNumber = data.targetNumber + 1;
            }
            if(targetNumber > 39) {
                targetNumber = 28;
            }
            questions = generateQuestion();
            controller.storage.channels.save({id: message.channel, questions:questions, targetNumber: targetNumber}, function(err){});
            bot.reply(message, "Goal: "+ targetNumber);
            bot.reply(message, "Solve: "+ questions[0]+ " " + questions[1]+ " " + questions[2]+ " " + questions[3])
        })
   }, 4000);
});

controller.hears(['hint'], 'direct_message,direct_mention,mention', function(bot, message) {
    data = controller.storage.channels.get(message.channel, function(err, data){
        if(data && data.questions && data.targetNumber) {
            var problem_input = data.questions.join(" ")
            var solution = solver.solve(problem_input, data.targetNumber, ['+','-','*','/', '**']);

            if(solution == "NO SOLUTION!") {
                bot.reply(message, 'There are no solution. Please play again :)')
                controller.storage.channels.save({id: message.channel, questions:null}, function(err){});
            } else {
                bot.reply(message, 'There is a solution')
            }
        } else {
            bot.reply(message, 'There are no numbers to solve.')
        }
    })
})

controller.hears(['giveup'], 'direct_message,direct_mention,mention', function(bot, message) {
    data = controller.storage.channels.get(message.channel, function(err, data){
        if(data && data.questions && data.targetNumber) {
            var problem_input = data.questions.join(" ")
            var solution = solver.solve(problem_input, data.targetNumber, ['+','-','*','/', '**']);

            bot.reply(message, "Goal: "+ data.targetNumber);
            bot.reply( message, 'Will solve: [' + problem_input + ']');
            bot.reply( message, 'Solution is: ' + solution);
            controller.storage.channels.save({id: message.channel, questions:null}, function(err){});
        } else {
            bot.reply(message, "There are no numbers to solve.")
        }
    });
})

controller.hears(['solve: ([0-9\s ]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var problem_input = message.match[1].trim();
    bot.reply( message, 'Will solve: [' + problem_input + ']');
    var solution = solver.solve(problem_input, 31, ['+','-','*','/', '**']);
    bot.reply( message, 'Solution is: ' + solution);
});

controller.hears(['solve_with_target: ([0-9\s ]+), ([0-9]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var problem_input = message.match[1].trim();
    var target = parseInt(message.match[2].trim());
    bot.reply( message, 'May solve: [' + problem_input + '] with target: [' + target + ']');
    var solution = solver.solve(problem_input, target, ['+','-','*','/', '**']);
    bot.reply( message, 'Solution is: ' + solution);
});

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!');
        } else {
            bot.reply(message, 'Hello.');
        }
    });
});

controller.hears(['call me (.*)', 'my name is (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var name = message.match[1];
    controller.storage.users.get(message.user, function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user, function(err, id) {
            bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name', 'who am i'], 'direct_message,direct_mention,mention', function(bot, message) {

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Your name is ' + user.name);
        } else {
            bot.startConversation(message, function(err, convo) {
                if (!err) {
                    convo.say('I do not know your name yet!');
                    convo.ask('What should I call you?', function(response, convo) {
                        convo.ask('You want me to call you `' + response.text + '`?', [
                            {
                                pattern: 'yes',
                                callback: function(response, convo) {
                                    // since no further messages are queued after this,
                                    // the conversation will end naturally with status == 'completed'
                                    convo.next();
                                }
                            },
                            {
                                pattern: 'no',
                                callback: function(response, convo) {
                                    // stop the conversation. this will cause it to end with status == 'stopped'
                                    convo.stop();
                                }
                            },
                            {
                                default: true,
                                callback: function(response, convo) {
                                    convo.repeat();
                                    convo.next();
                                }
                            }
                        ]);

                        convo.next();

                    }, {'key': 'nickname'}); // store the results in a field called nickname

                    convo.on('end', function(convo) {
                        if (convo.status == 'completed') {
                            bot.reply(message, 'OK! I will update my dossier...');

                            controller.storage.users.get(message.user, function(err, user) {
                                if (!user) {
                                    user = {
                                        id: message.user,
                                    };
                                }
                                user.name = convo.extractResponse('nickname');
                                controller.storage.users.save(user, function(err, id) {
                                    bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
                                });
                            });

                        } else {
                            // this happens if the conversation ended prematurely for some reason
                            bot.reply(message, 'OK, nevermind!');
                        }
                    });
                }
            });
        }
    });
});

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

NUMBERS = [1,2,3,4,5,6,7,8,9,10,10]
function generateQuestion() {
    questions = [];
    for(var i=0; i<4; i++) {
        questions.push(NUMBERS[Math.floor(Math.random() * NUMBERS.length)]);
    }
    return questions
}
<commit_msg>fix dynamic<commit_after>if (!process.env.token) {
    console.log('Error: Specify token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');
var solver = require('./solver31.js');

var controller = Botkit.slackbot({
    debug: true,
});

var bot = controller.spawn({
    token: process.env.token
}).startRTM();

controller.hears(['play'], 'direct_message,direct_mention,mention', function(bot, message) {
    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'lebe-lebe-matabelo',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    bot.reply(message, '.......Get ready in.......')
    setTimeout(function(){ bot.reply(message, '...............3..............'); }, 1000);
    setTimeout(function(){ bot.reply(message, '...............2..............'); }, 2000);
    setTimeout(function(){ bot.reply(message, '...............1..............'); }, 3000);
    setTimeout(function(){
        controller.storage.channels.get(message.channel, function(err, data){
            var targetNumber = 28;
            if(data && data.targetNumber) {
                console.log("CUPU")
                targetNumber = data.targetNumber + 1;
            }
            if(targetNumber > 39) {
                targetNumber = 28;
            }
            questions = generateQuestion();
            controller.storage.channels.save({id: message.channel, questions:questions, targetNumber: targetNumber}, function(err){});
            bot.reply(message, "Goal: "+ targetNumber);
            bot.reply(message, "Solve: "+ questions[0]+ " " + questions[1]+ " " + questions[2]+ " " + questions[3])
        })
   }, 4000);
});

controller.hears(['hint'], 'direct_message,direct_mention,mention', function(bot, message) {
    data = controller.storage.channels.get(message.channel, function(err, data){
        if(data && data.questions && data.targetNumber) {
            var problem_input = data.questions.join(" ")
            var solution = solver.solve(problem_input, data.targetNumber, ['+','-','*','/', '**']);

            if(solution == "NO SOLUTION!") {
                bot.reply(message, 'There are no solution. Please play again :)')
                controller.storage.channels.save({id: message.channel, questions:null}, function(err){});
            } else {
                bot.reply(message, 'There is a solution')
            }
        } else {
            bot.reply(message, 'There are no numbers to solve.')
        }
    })
})

controller.hears(['giveup'], 'direct_message,direct_mention,mention', function(bot, message) {
    data = controller.storage.channels.get(message.channel, function(err, data){
        if(data && data.questions && data.targetNumber) {
            var problem_input = data.questions.join(" ")
            var solution = solver.solve(problem_input, data.targetNumber, ['+','-','*','/', '**']);

            bot.reply(message, "Goal: "+ data.targetNumber);
            bot.reply( message, 'Will solve: [' + problem_input + ']');
            bot.reply( message, 'Solution is: ' + solution);
            controller.storage.channels.save({id: message.channel, questions:null, targetNumber: data.targetNumber}, function(err){});
        } else {
            bot.reply(message, "There are no numbers to solve.")
        }
    });
})

controller.hears(['solve: ([0-9\s ]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var problem_input = message.match[1].trim();
    bot.reply( message, 'Will solve: [' + problem_input + ']');
    var solution = solver.solve(problem_input, 31, ['+','-','*','/', '**']);
    bot.reply( message, 'Solution is: ' + solution);
});

controller.hears(['solve_with_target: ([0-9\s ]+), ([0-9]+)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var problem_input = message.match[1].trim();
    var target = parseInt(message.match[2].trim());
    bot.reply( message, 'May solve: [' + problem_input + '] with target: [' + target + ']');
    var solution = solver.solve(problem_input, target, ['+','-','*','/', '**']);
    bot.reply( message, 'Solution is: ' + solution);
});

controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.api.reactions.add({
        timestamp: message.ts,
        channel: message.channel,
        name: 'robot_face',
    }, function(err, res) {
        if (err) {
            bot.botkit.log('Failed to add emoji reaction :(', err);
        }
    });

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Hello ' + user.name + '!!');
        } else {
            bot.reply(message, 'Hello.');
        }
    });
});

controller.hears(['call me (.*)', 'my name is (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
    var name = message.match[1];
    controller.storage.users.get(message.user, function(err, user) {
        if (!user) {
            user = {
                id: message.user,
            };
        }
        user.name = name;
        controller.storage.users.save(user, function(err, id) {
            bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
        });
    });
});

controller.hears(['what is my name', 'who am i'], 'direct_message,direct_mention,mention', function(bot, message) {

    controller.storage.users.get(message.user, function(err, user) {
        if (user && user.name) {
            bot.reply(message, 'Your name is ' + user.name);
        } else {
            bot.startConversation(message, function(err, convo) {
                if (!err) {
                    convo.say('I do not know your name yet!');
                    convo.ask('What should I call you?', function(response, convo) {
                        convo.ask('You want me to call you `' + response.text + '`?', [
                            {
                                pattern: 'yes',
                                callback: function(response, convo) {
                                    // since no further messages are queued after this,
                                    // the conversation will end naturally with status == 'completed'
                                    convo.next();
                                }
                            },
                            {
                                pattern: 'no',
                                callback: function(response, convo) {
                                    // stop the conversation. this will cause it to end with status == 'stopped'
                                    convo.stop();
                                }
                            },
                            {
                                default: true,
                                callback: function(response, convo) {
                                    convo.repeat();
                                    convo.next();
                                }
                            }
                        ]);

                        convo.next();

                    }, {'key': 'nickname'}); // store the results in a field called nickname

                    convo.on('end', function(convo) {
                        if (convo.status == 'completed') {
                            bot.reply(message, 'OK! I will update my dossier...');

                            controller.storage.users.get(message.user, function(err, user) {
                                if (!user) {
                                    user = {
                                        id: message.user,
                                    };
                                }
                                user.name = convo.extractResponse('nickname');
                                controller.storage.users.save(user, function(err, id) {
                                    bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
                                });
                            });

                        } else {
                            // this happens if the conversation ended prematurely for some reason
                            bot.reply(message, 'OK, nevermind!');
                        }
                    });
                }
            });
        }
    });
});

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

NUMBERS = [1,2,3,4,5,6,7,8,9,10,10]
function generateQuestion() {
    questions = [];
    for(var i=0; i<4; i++) {
        questions.push(NUMBERS[Math.floor(Math.random() * NUMBERS.length)]);
    }
    return questions
}
<|endoftext|>