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

/* eslint no-process-exit:0 */

"use strict";

const path = require("path");
const fs = require("fs");
const mkdirp = require("mkdirp");
const untildify = require("untildify");
const touch = require("touch");
const del = require("del");
const argv = require("minimist")(process.argv.slice(2));
const service = require("../service");
const assert = require("hoek").assert;
const arrivals = require("../lib/arrivals");
const config = require("ez-config");

let svc;

const ACTION = argv._[0] || "run";
const RUN_AS_ROOT = argv["run-as-root"] || false;
const CWD = argv.cwd || process.cwd();
const HOME_DIR = untildify("~/");
const BASE_DIR = config.get("baseDir");

if (ACTION === "uninstall" || ACTION === "restart" || ACTION === "stop") {
  svc = service.create({ runAsUserAgent: !RUN_AS_ROOT });
  svc[ACTION]();
  process.exit();
}

const prepareDirs = function (reset) {
  if (reset) {
    del.sync([
      process.env.TMP_PATH,
      process.env.DB_PATH,
      process.env.LOG_FILE
    ], {
      force: true
    });
  }

  mkdirp.sync(process.env.TMP_PATH);
  mkdirp.sync(process.env.DB_PATH);
  touch.sync(process.env.LOG_FILE);
};

const setEnvPath = function (key, val, defaultVal) {
  if (val) {
    if (path.isAbsolute(val)) {
      process.env[key] = val;
    } else {
      process.env[key] = path.resolve(CWD, val);
    }
  } else if (defaultVal) {
    process.env[key] = path.join(HOME_DIR, BASE_DIR, defaultVal);
  }
};

setEnvPath("TMP_PATH", argv.tmp, config.get("tmpDir"));
setEnvPath("DB_PATH", argv.db, config.get("dbDir"));
setEnvPath("LOG_FILE", argv.log, config.get("logFile"));

if (ACTION === "reset") {
  prepareDirs(true);
  process.exit();
} else {
  prepareDirs();
}

if (argv.watch) {
  argv.watch.split(",").forEach((p) => {
    const watchPath = path.resolve(CWD, p);
    let watchPathStat;
    try {
      watchPathStat = fs.statSync(watchPath);
    } catch (err) {
      watchPathStat = null;
    }
    assert(watchPathStat && watchPathStat.isDirectory(),
        "Watch path must exist and be a directory");
  });
}

assert(argv.destination || argv["video-destination"] && argv["audio-destination"],
    "Destination is required");

setEnvPath("VIDEO_DESTINATION", argv["video-destination"] || argv.destination);
setEnvPath("AUDIO_DESTINATION", argv["audio-destination"] || argv.destination);

if (argv["log-type"]) {
  process.env.LOG_TYPE = argv["log-type"];
} else {
  process.env.LOG_TYPE = ACTION === "run" ? "file" : "console";
}

process.env.CWD = CWD;
process.env.WATCH_PATH = argv.watch;
process.env.LOG_LEVEL = argv["log-level"] || "info";

process.env.FFMPEG_PATH = argv.ffmpeg || "/usr/local/bin/ffmpeg";
process.env.MKVTOMP4_PATH = argv.mkvtomp4 || "/usr/local/bin/mkvtomp4";
process.env.MP4BOX_PATH = argv.mp4box || "/usr/local/bin/mp4box";
process.env.MKVINFO_PATH = argv.mkvinfo || "/usr/local/bin/mkvinfo";
process.env.MKVEXTRACT_PATH = argv.mkvextract || "/usr/local/bin/mkvextract";

if (ACTION === "run") {
  arrivals();
} else if (ACTION === "install") {
  svc = service.create({
    runAsUserAgent: !RUN_AS_ROOT
  });
  svc.install();
}
<commit_msg>fixing scoping for ez-config in bin<commit_after>#!/usr/bin/env node

/* eslint no-process-exit:0 */

"use strict";

const path = require("path");
process.env.NODE_CONFIG_DIR = path.resolve(__dirname, "../config");

const fs = require("fs");
const mkdirp = require("mkdirp");
const untildify = require("untildify");
const touch = require("touch");
const del = require("del");
const argv = require("minimist")(process.argv.slice(2));
const service = require("../service");
const assert = require("hoek").assert;
const arrivals = require("../lib/arrivals");
const config = require("ez-config");

let svc;

const ACTION = argv._[0] || "run";
const RUN_AS_ROOT = argv["run-as-root"] || false;
const CWD = argv.cwd || process.cwd();
const HOME_DIR = untildify("~/");
const BASE_DIR = config.get("baseDir");

if (ACTION === "uninstall" || ACTION === "restart" || ACTION === "stop") {
  svc = service.create({ runAsUserAgent: !RUN_AS_ROOT });
  svc[ACTION]();
  process.exit();
}

const prepareDirs = function (reset) {
  if (reset) {
    del.sync([
      process.env.TMP_PATH,
      process.env.DB_PATH,
      process.env.LOG_FILE
    ], {
      force: true
    });
  }

  mkdirp.sync(process.env.TMP_PATH);
  mkdirp.sync(process.env.DB_PATH);
  touch.sync(process.env.LOG_FILE);
};

const setEnvPath = function (key, val, defaultVal) {
  if (val) {
    if (path.isAbsolute(val)) {
      process.env[key] = val;
    } else {
      process.env[key] = path.resolve(CWD, val);
    }
  } else if (defaultVal) {
    process.env[key] = path.join(HOME_DIR, BASE_DIR, defaultVal);
  }
};

setEnvPath("TMP_PATH", argv.tmp, config.get("tmpDir"));
setEnvPath("DB_PATH", argv.db, config.get("dbDir"));
setEnvPath("LOG_FILE", argv.log, config.get("logFile"));

if (ACTION === "reset") {
  prepareDirs(true);
  process.exit();
} else {
  prepareDirs();
}

if (argv.watch) {
  argv.watch.split(",").forEach((p) => {
    const watchPath = path.resolve(CWD, p);
    let watchPathStat;
    try {
      watchPathStat = fs.statSync(watchPath);
    } catch (err) {
      watchPathStat = null;
    }
    assert(watchPathStat && watchPathStat.isDirectory(),
        "Watch path must exist and be a directory");
  });
}

assert(argv.destination || argv["video-destination"] && argv["audio-destination"],
    "Destination is required");

setEnvPath("VIDEO_DESTINATION", argv["video-destination"] || argv.destination);
setEnvPath("AUDIO_DESTINATION", argv["audio-destination"] || argv.destination);

if (argv["log-type"]) {
  process.env.LOG_TYPE = argv["log-type"];
} else {
  process.env.LOG_TYPE = ACTION === "run" ? "file" : "console";
}

process.env.CWD = CWD;
process.env.WATCH_PATH = argv.watch;
process.env.LOG_LEVEL = argv["log-level"] || "info";

process.env.FFMPEG_PATH = argv.ffmpeg || "/usr/local/bin/ffmpeg";
process.env.MKVTOMP4_PATH = argv.mkvtomp4 || "/usr/local/bin/mkvtomp4";
process.env.MP4BOX_PATH = argv.mp4box || "/usr/local/bin/mp4box";
process.env.MKVINFO_PATH = argv.mkvinfo || "/usr/local/bin/mkvinfo";
process.env.MKVEXTRACT_PATH = argv.mkvextract || "/usr/local/bin/mkvextract";

if (ACTION === "run") {
  arrivals();
} else if (ACTION === "install") {
  svc = service.create({
    runAsUserAgent: !RUN_AS_ROOT
  });
  svc.install();
}
<|endoftext|>


<commit_before>const rewrite     = require('connect-modrewrite');
const serveIndex  = require('serve-index');
const serveStatic = require('serve-static');
const languages   = require('../scripts/common').languages;

module.exports = function (grunt) {
    lang_regex = languages.join('|').toLowerCase();

    return {
        livereload: {
            options: {
                hostname  : '0.0.0.0',
                port      : 4433,
                protocol  : 'http',
                base      : 'dist',
                open      : {
                    appName: {
                        app: 'Google\ Chrome'
                    },
                    target : 'https://localhost',
                },
                middleware: (connect, options) => {
                    const middlewares = [
                        require('connect-livereload')(),
                    ];

                    const rules = [
                        '^/binary-static/(.*)$ /$1',
                        `^/app/(${lang_regex})/index(\\.html)?/(.*)$ /app/$1/$2 [L]`,
                        `^/app/(${lang_regex})/service-worker\\.js$ - [L]`,
                        `^/app/(${lang_regex})/manifest\\.json$ - [L]`,
                        `^/app/(${lang_regex})/.*$ /app/$1/ [L]`,
                    ];
                    middlewares.push(rewrite(rules));

                    if (!Array.isArray(options.base)) {
                        options.base = [options.base];
                    }

                    options.base.forEach((base) => {
                        middlewares.push(serveStatic(base));
                    });

                    const directory = options.directory || options.base[options.base.length - 1];
                    middlewares.push(serveIndex(directory));

                    middlewares.push((req, res) => {
                        const path_404 = `${options.base[0]}/404.html`;
                        if (grunt.file.exists(path_404)) {
                            require('fs').createReadStream(path_404).pipe(res);
                            return;
                        }
                        res.statusCode(404); // 404.html not found
                        res.end();
                    });

                    return middlewares;
                }
            }
        },
    };
};
<commit_msg>Revert connect.js local changes (#6548)<commit_after>const rewrite     = require('connect-modrewrite');
const serveIndex  = require('serve-index');
const serveStatic = require('serve-static');
const languages   = require('../scripts/common').languages;

module.exports = function (grunt) {
    lang_regex = languages.join('|').toLowerCase();

    return {
        livereload: {
            options: {
                hostname  : '0.0.0.0',
                port      : 443,
                protocol  : 'https',
                base      : 'dist',
                open      : {
                    appName: {
                        app: 'Google\ Chrome'
                    },
                    target : 'https://localhost',
                },
                middleware: (connect, options) => {
                    const middlewares = [
                        require('connect-livereload')(),
                    ];

                    const rules = [
                        '^/binary-static/(.*)$ /$1',
                        `^/app/(${lang_regex})/index(\\.html)?/(.*)$ /app/$1/$2 [L]`,
                        `^/app/(${lang_regex})/service-worker\\.js$ - [L]`,
                        `^/app/(${lang_regex})/manifest\\.json$ - [L]`,
                        `^/app/(${lang_regex})/.*$ /app/$1/ [L]`,
                    ];
                    middlewares.push(rewrite(rules));

                    if (!Array.isArray(options.base)) {
                        options.base = [options.base];
                    }

                    options.base.forEach((base) => {
                        middlewares.push(serveStatic(base));
                    });

                    const directory = options.directory || options.base[options.base.length - 1];
                    middlewares.push(serveIndex(directory));

                    middlewares.push((req, res) => {
                        const path_404 = `${options.base[0]}/404.html`;
                        if (grunt.file.exists(path_404)) {
                            require('fs').createReadStream(path_404).pipe(res);
                            return;
                        }
                        res.statusCode(404); // 404.html not found
                        res.end();
                    });

                    return middlewares;
                }
            }
        },
    };
};
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview using private properties isn't a Closure violation in tests.
 * @suppress {accessControls}
 */

/**
 * @param jsCoveragePerBlock - Collect per Block coverage if `true`, per function coverage otherwise.
 * @return {!Promise}
 */
CoverageTestRunner.startCoverage = async function(jsCoveragePerBlock) {
  UI.viewManager.showView('coverage');
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._startRecording({reload: false, jsCoveragePerBlock});
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.stopCoverage = function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  return coverageView.stopRecording();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.suspendCoverageModel = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._model.preSuspendModel();
  await coverageView._model.suspendModel();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.resumeCoverageModel = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._model.resumeModel();
  await coverageView._model.postResumeModel();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.pollCoverage = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  // Make sure not to have two instances of _pollAndCallback running at the same time.
  await coverageView._model._currentPollPromise;
  return coverageView._model._pollAndCallback();
};

/**
 * @return {!Promise<string>}
 */
CoverageTestRunner.exportReport = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  let data;
  await coverageView._model.exportReport({write: d => data = d, close: _ => 0});
  return data;
};

/**
 * @return {!Promise<!SourceFrame.SourceFrame>}
 */
CoverageTestRunner.sourceDecorated = async function(source) {
  await UI.inspectorView.showPanel('sources');
  const decoratePromise = TestRunner.addSnifferPromise(Coverage.CoverageView.LineDecorator.prototype, '_innerDecorate');
  const sourceFrame = await SourcesTestRunner.showScriptSourcePromise(source);
  await decoratePromise;
  return sourceFrame;
};

CoverageTestRunner.dumpDecorations = async function(source) {
  const sourceFrame = await CoverageTestRunner.sourceDecorated(source);
  CoverageTestRunner.dumpDecorationsInSourceFrame(sourceFrame);
};

/**
 * @return {?DataGrid.DataGridNode}
 */
CoverageTestRunner.findCoverageNodeForURL = function(url) {
  const coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
  const rootNode = coverageListView._dataGrid.rootNode();

  for (const child of rootNode.children) {
    if (child._coverageInfo.url().endsWith(url)) {
      return child;
    }
  }

  return null;
};

CoverageTestRunner.dumpDecorationsInSourceFrame = function(sourceFrame) {
  const markerMap = new Map([['used', '+'], ['unused', '-']]);
  const codeMirror = sourceFrame.textEditor.codeMirror();

  for (let line = 0; line < codeMirror.lineCount(); ++line) {
    const text = codeMirror.getLine(line);
    let markerType = ' ';
    const lineInfo = codeMirror.lineInfo(line);

    if (!lineInfo) {
      continue;
    }

    const gutterElement = lineInfo.gutterMarkers && lineInfo.gutterMarkers['CodeMirror-gutter-coverage'];

    if (gutterElement) {
      const markerClass = /^text-editor-coverage-(\w*)-marker$/.exec(gutterElement.classList)[1];
      markerType = markerMap.get(markerClass) || gutterElement.classList;
    }

    TestRunner.addResult(`${line}: ${markerType} ${text}`);
  }
};

CoverageTestRunner.dumpCoverageListView = function() {
  const coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
  const dataGrid = coverageListView._dataGrid;
  dataGrid.updateInstantly();

  for (const child of dataGrid.rootNode().children) {
    const data = child._coverageInfo;
    const url = TestRunner.formatters.formatAsURL(data.url());

    if (url.startsWith('test://')) {
      continue;
    }

    const type = Coverage.CoverageListView._typeToString(data.type());
    TestRunner.addResult(`${url} ${type} used: ${data.usedSize()} unused: ${data.unusedSize()} total: ${data.size()}`);
  }
};
<commit_msg>Add helper function to CoverageTestRunner<commit_after>// Copyright 2017 The Chromium Authors. All
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview using private properties isn't a Closure violation in tests.
 * @suppress {accessControls}
 */

/**
 * @param jsCoveragePerBlock - Collect per Block coverage if `true`, per function coverage otherwise.
 * @return {!Promise}
 */
CoverageTestRunner.startCoverage = async function(jsCoveragePerBlock) {
  UI.viewManager.showView('coverage');
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._startRecording({reload: false, jsCoveragePerBlock});
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.stopCoverage = function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  return coverageView.stopRecording();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.suspendCoverageModel = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._model.preSuspendModel();
  await coverageView._model.suspendModel();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.resumeCoverageModel = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  await coverageView._model.resumeModel();
  await coverageView._model.postResumeModel();
};

/**
 * @return {!Promise}
 */
CoverageTestRunner.pollCoverage = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  // Make sure not to have two instances of _pollAndCallback running at the same time.
  await coverageView._model._currentPollPromise;
  return coverageView._model._pollAndCallback();
};

/**
 * @return {!Promise<Coverage.CoverageModel>}
 */
CoverageTestRunner.getCoverageModel = function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  return coverageView._model;
};

/**
 * @return {!Promise<string>}
 */
CoverageTestRunner.exportReport = async function() {
  const coverageView = self.runtime.sharedInstance(Coverage.CoverageView);
  let data;
  await coverageView._model.exportReport({write: d => data = d, close: _ => 0});
  return data;
};

/**
 * @return {!Promise<!SourceFrame.SourceFrame>}
 */
CoverageTestRunner.sourceDecorated = async function(source) {
  await UI.inspectorView.showPanel('sources');
  const decoratePromise = TestRunner.addSnifferPromise(Coverage.CoverageView.LineDecorator.prototype, '_innerDecorate');
  const sourceFrame = await SourcesTestRunner.showScriptSourcePromise(source);
  await decoratePromise;
  return sourceFrame;
};

CoverageTestRunner.dumpDecorations = async function(source) {
  const sourceFrame = await CoverageTestRunner.sourceDecorated(source);
  CoverageTestRunner.dumpDecorationsInSourceFrame(sourceFrame);
};

/**
 * @return {?DataGrid.DataGridNode}
 */
CoverageTestRunner.findCoverageNodeForURL = function(url) {
  const coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
  const rootNode = coverageListView._dataGrid.rootNode();

  for (const child of rootNode.children) {
    if (child._coverageInfo.url().endsWith(url)) {
      return child;
    }
  }

  return null;
};

CoverageTestRunner.dumpDecorationsInSourceFrame = function(sourceFrame) {
  const markerMap = new Map([['used', '+'], ['unused', '-']]);
  const codeMirror = sourceFrame.textEditor.codeMirror();

  for (let line = 0; line < codeMirror.lineCount(); ++line) {
    const text = codeMirror.getLine(line);
    let markerType = ' ';
    const lineInfo = codeMirror.lineInfo(line);

    if (!lineInfo) {
      continue;
    }

    const gutterElement = lineInfo.gutterMarkers && lineInfo.gutterMarkers['CodeMirror-gutter-coverage'];

    if (gutterElement) {
      const markerClass = /^text-editor-coverage-(\w*)-marker$/.exec(gutterElement.classList)[1];
      markerType = markerMap.get(markerClass) || gutterElement.classList;
    }

    TestRunner.addResult(`${line}: ${markerType} ${text}`);
  }
};

CoverageTestRunner.dumpCoverageListView = function() {
  const coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView;
  const dataGrid = coverageListView._dataGrid;
  dataGrid.updateInstantly();

  for (const child of dataGrid.rootNode().children) {
    const data = child._coverageInfo;
    const url = TestRunner.formatters.formatAsURL(data.url());

    if (url.startsWith('test://')) {
      continue;
    }

    const type = Coverage.CoverageListView._typeToString(data.type());
    TestRunner.addResult(`${url} ${type} used: ${data.usedSize()} unused: ${data.unusedSize()} total: ${data.size()}`);
  }
};
<|endoftext|>


<commit_before>module.exports = {
  "audio-mp3.js":  require('./audio-mp3.js'),
  "channel.js":  require('./channel.js'),
  "emoji.js":  require('./emoji.js'),
  "suggest-emoji.js":  require('./suggest-emoji.js'),
  "dns.js":  require('./dns.js'),
  "git.js":  require('./git.js'),
  "git-ssb.js":  require('./git-ssb.js'),
  "key.js":  require('./key.js'),
  "notifications.js":  require('./notifications.js'),
  "meta-image.js":  require('./meta-image.js'),
  "music-release-cc.js":  require('./music-release-cc.js'),
  "music-release.js":  require('./music-release.js'),
  "network.js":  require('./network.js'),
  "query.js":  require('./query.js'),
  "raw.js": require('./raw.js'),
  "search.js": require('./search'),
  "split.js":  require('./split.js'),
  "versions.js":  require('./versions.js')
}

<commit_msg>disable audio-mp3 module (unment blob_urls need)<commit_after>module.exports = {
  // "audio-mp3.js":  require('./audio-mp3.js'),
  "channel.js":  require('./channel.js'),
  "emoji.js":  require('./emoji.js'),
  "suggest-emoji.js":  require('./suggest-emoji.js'),
  "dns.js":  require('./dns.js'),
  "git.js":  require('./git.js'),
  "git-ssb.js":  require('./git-ssb.js'),
  "key.js":  require('./key.js'),
  "notifications.js":  require('./notifications.js'),
  "meta-image.js":  require('./meta-image.js'),
  "music-release-cc.js":  require('./music-release-cc.js'),
  "music-release.js":  require('./music-release.js'),
  "network.js":  require('./network.js'),
  "query.js":  require('./query.js'),
  "raw.js": require('./raw.js'),
  "search.js": require('./search'),
  "split.js":  require('./split.js'),
  "versions.js":  require('./versions.js')
}

<|endoftext|>


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

(function() {
    'use strict';

    var Info        = require('../package'),
        DIR         = __dirname + '/../',
        DIR_LIB     = DIR + 'lib/',
        DIR_SERVER  = DIR_LIB + 'server/',

    exit        = require(DIR_SERVER + 'exit'),
    config      = require(DIR_SERVER + 'config'),
    createPass  = require(DIR_SERVER + 'password'),

    options,
    argv        = process.argv,

    args        = require('minimist')(argv.slice(2), {
        string: [
            'port',
            'password',
            'username',
            'config',
            'editor',
            'root',
            'prefix'
        ],
        boolean: [
            'auth',
            'repl',
            'save',
            'server',
            'online',
            'minify',
            'progress',
            'progress-of-copying',
            'html-dialogs'
        ],
        default: {
            server      : true,
            auth        : config('auth'),
            port        : config('port'),
            minify      : config('minify'),
            online      : config('online'),
            editor      : config('editor') || 'edward',
            username    : config('username'),
            root        : config('root') || '/',
            prefix      : config('prefix') || '',
            progress    : config('progress') || config('progressOfCopying'),

            'html-dialogs' : config('htmlDialogs')
        },
        alias: {
            v: 'version',
            h: 'help',
            p: 'password',
            o: 'online',
            u: 'username',
            s: 'save',
            a: 'auth',
            c: 'config'
        },
        unknown: function(cmd) {
            exit('\'%s\' is not a cloudcmd option. See \'cloudcmd --help\'.', cmd);
        }
    });

if (args.version) {
    version();
} else if (args.help) {
    help();
} else {
    if (args.repl)
        repl();

    checkUpdate();

    port(args.port);

    config('auth', args.auth);
    config('online', args.online);
    config('minify', args.minify);
    config('username', args.username);
    config('progress', args.progress);
    config('prefix', args.prefix);
    config('root', args.root);
    config('htmlDialogs', args['html-dialogs']);

    deprecate('progress-of-copying', 'progress');

    readConfig(args.config);

    options = {
        root: args.root,
        editor: args.editor,
        prefix: args.prefix
    };

    if (args.password)
        config('password', getPassword(args.password));

    if (!args.save)
        start(options);
    else
        config.save(function() {
            start(options);
        });
}

function getPassword(password) {
    return createPass(config('algo'), password);
}

function deprecate(was, became) {
    var value = args[was];

    if (value) {
        console.log('cloudcmd --' + was + ': deprecated, use --' + became);
        config(became, value);
    }
}

function version() {
    console.log('v' + Info.version);
}

function start(config) {
    var SERVER = '../lib/server';

    if (args.server)
        require(SERVER)(config);
}

function port(arg) {
    var number = parseInt(arg, 10);

    if (!isNaN(number))
        config('port', number);
    else
        exit('cloudcmd --port: should be a number');
}

function readConfig(name) {
    var fs, data, error, tryCatch;

    if (name) {
        fs          = require('fs');
        tryCatch    = require('try-catch');
        error       = tryCatch(function() {
            var json    = fs.readFileSync(name);
            data        = JSON.parse(json);
        });

        if (error)
            exit(error.message);
        else
            Object.keys(data).forEach(function(item) {
                config(item, data[item]);
            });
    }
}

function help() {
    var bin         = require('../json/bin'),
        usage       = 'Usage: cloudcmd [options]',
        url         = Info.homepage;

    console.log(usage);
    console.log('Options:');

    Object.keys(bin).forEach(function(name) {
        console.log('  %s %s', name, bin[name]);
    });

    console.log('\nGeneral help using Cloud Commander: <%s>', url);
}

function repl() {
    console.log('REPL mode enabled (telnet localhost 1337)');
    require(DIR_LIB + '/server/repl');
}

function checkUpdate() {
    var load    = require('package-json'),
        chalk   = require('chalk'),
        rendy   = require('rendy');

    load(Info.name, 'latest').then(function(data) {
        var latest,
            current,
            version = data.version;

            if (version !== Info.version) {
                latest  = rendy('update available: {{ latest }}', {
                    latest: chalk.green.bold('v' + version),
                });

                current = chalk.dim(rendy('(current: v{{ current }})', {
                    current: Info.version
                }));

                console.log('%s %s', latest, current);
            }
        });
    }

})();
<commit_msg>chore(cloudcmd) add " "<commit_after>#!/usr/bin/env node

(function() {
    'use strict';

    var Info        = require('../package'),
        DIR         = __dirname + '/../',
        DIR_LIB     = DIR + 'lib/',
        DIR_SERVER  = DIR_LIB + 'server/',

    exit        = require(DIR_SERVER + 'exit'),
    config      = require(DIR_SERVER + 'config'),
    createPass  = require(DIR_SERVER + 'password'),

    options,
    argv        = process.argv,

    args        = require('minimist')(argv.slice(2), {
        string: [
            'port',
            'password',
            'username',
            'config',
            'editor',
            'root',
            'prefix'
        ],
        boolean: [
            'auth',
            'repl',
            'save',
            'server',
            'online',
            'minify',
            'progress',
            'progress-of-copying',
            'html-dialogs'
        ],
        default: {
            server      : true,
            auth        : config('auth'),
            port        : config('port'),
            minify      : config('minify'),
            online      : config('online'),
            editor      : config('editor') || 'edward',
            username    : config('username'),
            root        : config('root') || '/',
            prefix      : config('prefix') || '',
            progress    : config('progress') || config('progressOfCopying'),

            'html-dialogs' : config('htmlDialogs')
        },
        alias: {
            v: 'version',
            h: 'help',
            p: 'password',
            o: 'online',
            u: 'username',
            s: 'save',
            a: 'auth',
            c: 'config'
        },
        unknown: function(cmd) {
            exit('\'%s\' is not a cloudcmd option. See \'cloudcmd --help\'.', cmd);
        }
    });

    if (args.version) {
        version();
    } else if (args.help) {
        help();
    } else {
        if (args.repl)
            repl();

        checkUpdate();

        port(args.port);

        config('auth', args.auth);
        config('online', args.online);
        config('minify', args.minify);
        config('username', args.username);
        config('progress', args.progress);
        config('prefix', args.prefix);
        config('root', args.root);
        config('htmlDialogs', args['html-dialogs']);

        deprecate('progress-of-copying', 'progress');

        readConfig(args.config);

        options = {
            root: args.root,
            editor: args.editor,
            prefix: args.prefix
        };

        if (args.password)
            config('password', getPassword(args.password));

        if (!args.save)
            start(options);
        else
            config.save(function() {
                start(options);
            });
    }

    function getPassword(password) {
        return createPass(config('algo'), password);
    }

    function deprecate(was, became) {
        var value = args[was];

        if (value) {
            console.log('cloudcmd --' + was + ': deprecated, use --' + became);
            config(became, value);
        }
    }

    function version() {
        console.log('v' + Info.version);
    }

    function start(config) {
        var SERVER = '../lib/server';

        if (args.server)
            require(SERVER)(config);
    }

    function port(arg) {
        var number = parseInt(arg, 10);

        if (!isNaN(number))
            config('port', number);
        else
            exit('cloudcmd --port: should be a number');
    }

    function readConfig(name) {
        var fs, data, error, tryCatch;

        if (name) {
            fs          = require('fs');
            tryCatch    = require('try-catch');
            error       = tryCatch(function() {
                var json    = fs.readFileSync(name);
                data        = JSON.parse(json);
            });

            if (error)
                exit(error.message);
            else
                Object.keys(data).forEach(function(item) {
                    config(item, data[item]);
                });
        }
    }

    function help() {
        var bin         = require('../json/bin'),
            usage       = 'Usage: cloudcmd [options]',
            url         = Info.homepage;

        console.log(usage);
        console.log('Options:');

        Object.keys(bin).forEach(function(name) {
            console.log('  %s %s', name, bin[name]);
        });

        console.log('\nGeneral help using Cloud Commander: <%s>', url);
    }

    function repl() {
        console.log('REPL mode enabled (telnet localhost 1337)');
        require(DIR_LIB + '/server/repl');
    }

    function checkUpdate() {
        var load    = require('package-json'),
            chalk   = require('chalk'),
            rendy   = require('rendy');

        load(Info.name, 'latest').then(function(data) {
            var latest,
                current,
                version = data.version;

            if (version !== Info.version) {
                latest  = rendy('update available: {{ latest }}', {
                    latest: chalk.green.bold('v' + version),
                });

                current = chalk.dim(rendy('(current: v{{ current }})', {
                    current: Info.version
                }));

                console.log('%s %s', latest, current);
            }
        });
    }

})();
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = function (env) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },
    module: {
      rules: [
        {
          test: /\.scss$/,
          // loaders: ["style-loader", "css-loader", "sass-loader"],
          loaders: ExtractTextPlugin.extract('css-loader?sourceMap!sass-loader')
        }
      ]
    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new ExtractTextPlugin('[name].[contenthash].css'),

      /**
       * Plugin: WebpackMd5Hash
       * Description: Plugin to replace a standard webpack chunkhash with md5.
       *
       * See: https://www.npmjs.com/package/webpack-md5-hash
       */
      new WebpackMd5Hash(),

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        output: {
          comments: false
        },
        mangle: {
          screw_ie8: true
        }, //prod
        compress: {
          screw_ie8: true,
          warnings: false,
          conditionals: true,
          unused: true,
          comparisons: true,
          sequences: true,
          dead_code: true,
          evaluate: true,
          if_return: true,
          join_vars: true,
          negate_iife: false // we need this for lazy v8
        }
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/modules/angular2-hmr-prod.js')
      ),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      // new LoaderOptionsPlugin({
      //   debug: false,
      //   options: {

      //     /**
      //      * Static analysis linter for TypeScript advanced options configuration
      //      * Description: An extensible linter for the TypeScript language.
      //      *
      //      * See: https://github.com/wbuchwalter/tslint-loader
      //      */
      //     tslint: {
      //       emitErrors: true,
      //       failOnHint: true,
      //       resourcePath: 'src'
      //     },

      //     /**
      //      * Html loader advanced options
      //      *
      //      * See: https://github.com/webpack/html-loader#advanced-options
      //      */
      //     // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
      //     htmlLoader: {
      //       minimize: true,
      //       removeAttributeQuotes: false,
      //       caseSensitive: true,
      //       customAttrSurround: [
      //         [/#/, /(?:)/],
      //         [/\*/, /(?:)/],
      //         [/\[?\(?/, /(?:)/]
      //       ],
      //       customAttrAssign: [/\)?\]?=/]
      //     },

      //   }
      // }),
      new CopyWebpackPlugin([{
          from: 'config/heroku',
          to: './'
        }
      ])
    ],
    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<commit_msg>updated: added cname to dist task<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false
});

module.exports = function (env) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },
    module: {
      rules: [
        {
          test: /\.scss$/,
          // loaders: ["style-loader", "css-loader", "sass-loader"],
          loaders: ExtractTextPlugin.extract('css-loader?sourceMap!sass-loader')
        }
      ]
    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new ExtractTextPlugin('[name].[contenthash].css'),

      /**
       * Plugin: WebpackMd5Hash
       * Description: Plugin to replace a standard webpack chunkhash with md5.
       *
       * See: https://www.npmjs.com/package/webpack-md5-hash
       */
      new WebpackMd5Hash(),

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        output: {
          comments: false
        },
        mangle: {
          screw_ie8: true
        }, //prod
        compress: {
          screw_ie8: true,
          warnings: false,
          conditionals: true,
          unused: true,
          comparisons: true,
          sequences: true,
          dead_code: true,
          evaluate: true,
          if_return: true,
          join_vars: true,
          negate_iife: false // we need this for lazy v8
        }
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/modules/angular2-hmr-prod.js')
      ),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      // new LoaderOptionsPlugin({
      //   debug: false,
      //   options: {

      //     /**
      //      * Static analysis linter for TypeScript advanced options configuration
      //      * Description: An extensible linter for the TypeScript language.
      //      *
      //      * See: https://github.com/wbuchwalter/tslint-loader
      //      */
      //     tslint: {
      //       emitErrors: true,
      //       failOnHint: true,
      //       resourcePath: 'src'
      //     },

      //     /**
      //      * Html loader advanced options
      //      *
      //      * See: https://github.com/webpack/html-loader#advanced-options
      //      */
      //     // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
      //     htmlLoader: {
      //       minimize: true,
      //       removeAttributeQuotes: false,
      //       caseSensitive: true,
      //       customAttrSurround: [
      //         [/#/, /(?:)/],
      //         [/\*/, /(?:)/],
      //         [/\[?\(?/, /(?:)/]
      //       ],
      //       customAttrAssign: [/\)?\]?=/]
      //     },

      //   }
      // }),
      new CopyWebpackPlugin([{
          from: 'config/heroku',
          to: './'
        },
        {
          from: 'CNAME',
          to: './'
        }
      ])
    ],
    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<|endoftext|>


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

CLASS({
  name: 'EMailGSnippet',
  package: 'foam.navigator.views',
  extendsModel: 'foam.navigator.views.GSnippet',

  properties: [
    {
      name: 'title',
      lazyFactory: function() {
        return this.data && this.data.subject;
      }
    },
    {
      name: 'snippet',
      lazyFactory: function() {
        return this.data.snippet;
      }
    },
    {
      name: 'url',
      lazyFactory: function() {
        return 'https://mail.google.com/mail/u/0#inbox/' + this.data.id.split(':')[1]
      }
    },
    {
      name: 'metadata',
      lazyFactory: function() {
        return [
          this.GSnippetMetadatum.create({ text: this.data.labels.join(',') })
        ];
      }
    }
  ]
});
<commit_msg>SLICE demo: Nicer email metadata<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'EMailGSnippet',
  package: 'foam.navigator.views',
  extendsModel: 'foam.navigator.views.GSnippet',

  properties: [
    {
      name: 'title',
      lazyFactory: function() {
        return this.data && this.data.subject;
      }
    },
    {
      name: 'snippet',
      lazyFactory: function() {
        return this.data.snippet;
      }
    },
    {
      name: 'url',
      lazyFactory: function() {
        return 'https://mail.google.com/mail/u/0#inbox/' + this.data.id.split(':')[1]
      }
    },
    {
      name: 'metadata',
      lazyFactory: function() {
        return [
          this.GSnippetMetadatum.create({ label: 'From', text: this.data.from }),
          this.GSnippetMetadatum.create({ label: 'Date', text: this.data.timestamp.toString() })
        ];
      }
    }
  ]
});
<|endoftext|>


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

 function toasterDirective($rootScope, $interval, UISessionService) {
  var notificationVisibleInMilliseconds = 30000;

  return {
    restrict: 'A',
    templateUrl: $rootScope.urlBase + 'app/base/toaster.html',
    scope: true,
    link: function(scope, element, attrs) {

      // TODO: pause toaster
      // https://github.com/extendedmind/extendedmind/blob/719b7fba55cdab65989df50fcff448f48ea9e805/frontend/core/src/main/webapp/static/app/main/footer.html#L3
      // https://github.com/extendedmind/extendedmind/blob/719b7fba55cdab65989df50fcff448f48ea9e805/frontend/core/src/main/webapp/static/app/main/FooterController.js#L88

      scope.toasterNotifications = false;

      UISessionService.registerNotificationsActiveCallback(attrs.toaster, notificationsActive);

      function notificationsActive(notifications) {
        scope.toasterNotifications = true;
        showNotifications(notifications);

        // Digest may not be running when callback is executed. E.g. from $animate promise.
        if (!scope.$phase && !$rootScope.$$phase) scope.$digest();
      }

      /*
      * Show notifications serialized.
      */
      function showNotifications(notifications) {
        if (notifications && notifications.length > 0) {
          var notification = notifications.shift();
          scope.notification = notification;

          // Proceed to next notification when timeout is reached or promise is cancelled.
          var notificationTimer = $interval(function() {
            scope.notification = undefined; // clear notification just in case
            showNotifications(notifications);
          }, notificationVisibleInMilliseconds, 1);

          // Timeout promise cancelled.
          notificationTimer.then(null, function() {
            scope.notification = undefined; // clear notification just in case
            showNotifications(notifications);
          });
          scope.notification.timer = notificationTimer; // attach timeout promise to notification
        } else
        // No more notifications. End.
        scope.toasterNotifications = false;
      }

      /*
      * Cancel notification's timeout promise and fire callback.
      */
      scope.closeNotificationAndCall = function(notification, item, callback) {
        if (notification.timer) $interval.cancel(notification.timer);
        if (callback) callback(item);
      };

      scope.$on('$destroy', function() {
        // Unregister notifications callback for toaster type in UISessionService
        UISessionService.unregisterNotificationsActiveCallback(attrs.toaster);
      });
    }
  };
}
toasterDirective['$inject'] = ['$rootScope', '$interval', 'UISessionService'];
angular.module('em.base').directive('toaster', toasterDirective);
<commit_msg>Fixed mistakenly committed toaster 30s animation.<commit_after>/* Copyright 2013-2016 Extended Mind Technologies Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 'use strict';

 function toasterDirective($rootScope, $interval, UISessionService) {
  var notificationVisibleInMilliseconds = 3000;

  return {
    restrict: 'A',
    templateUrl: $rootScope.urlBase + 'app/base/toaster.html',
    scope: true,
    link: function(scope, element, attrs) {

      // TODO: pause toaster
      // https://github.com/extendedmind/extendedmind/blob/719b7fba55cdab65989df50fcff448f48ea9e805/frontend/core/src/main/webapp/static/app/main/footer.html#L3
      // https://github.com/extendedmind/extendedmind/blob/719b7fba55cdab65989df50fcff448f48ea9e805/frontend/core/src/main/webapp/static/app/main/FooterController.js#L88

      scope.toasterNotifications = false;

      UISessionService.registerNotificationsActiveCallback(attrs.toaster, notificationsActive);

      function notificationsActive(notifications) {
        scope.toasterNotifications = true;
        showNotifications(notifications);

        // Digest may not be running when callback is executed. E.g. from $animate promise.
        if (!scope.$phase && !$rootScope.$$phase) scope.$digest();
      }

      /*
      * Show notifications serialized.
      */
      function showNotifications(notifications) {
        if (notifications && notifications.length > 0) {
          var notification = notifications.shift();
          scope.notification = notification;

          // Proceed to next notification when timeout is reached or promise is cancelled.
          var notificationTimer = $interval(function() {
            scope.notification = undefined; // clear notification just in case
            showNotifications(notifications);
          }, notificationVisibleInMilliseconds, 1);

          // Timeout promise cancelled.
          notificationTimer.then(null, function() {
            scope.notification = undefined; // clear notification just in case
            showNotifications(notifications);
          });
          scope.notification.timer = notificationTimer; // attach timeout promise to notification
        } else
        // No more notifications. End.
        scope.toasterNotifications = false;
      }

      /*
      * Cancel notification's timeout promise and fire callback.
      */
      scope.closeNotificationAndCall = function(notification, item, callback) {
        if (notification.timer) $interval.cancel(notification.timer);
        if (callback) callback(item);
      };

      scope.$on('$destroy', function() {
        // Unregister notifications callback for toaster type in UISessionService
        UISessionService.unregisterNotificationsActiveCallback(attrs.toaster);
      });
    }
  };
}
toasterDirective['$inject'] = ['$rootScope', '$interval', 'UISessionService'];
angular.module('em.base').directive('toaster', toasterDirective);
<|endoftext|>


<commit_before>export { Base, Root };

import { IssuedObjects } from "./Pool_IssuedObjects.js"

/**
 * A pool for recycling (re-using) objects. It collects all recycled (i.e. could be re-issued) objects of Pool.Base.
 * This could improve performance by reducing memory re-allocation.
 *
 *
 * @member {string} poolName
 *   The string name of this pool.
 *
 * @member {Class} objectClass
 *   The class for all newly created objects. If the instance of this objectClass has a method .disposeResources(), it will be called
 * when .sessionCall()'s ending (i.e. in .session_pop()) to release more resources.
 *
 * @member {function} pfn_SetAsConstructor_ReturnObject
 *   A function set contents like its constructor and return an object. Before .get_or_create_by() returns a recycled object,
 * its .pfnSetAsConstructor() method will be called to re-initilaize it. Its return value will be the final returned object.
 *
 * @member {Object} recycledObjectArray
 *   For fetching object efficiently (without creating iterator).
 *
 * @member {Set} recycledObjectSet
 *   The same content as .recycledObjectArray for checking object whether is recycled multiple times.
 *
 * @member {number} recycled_count
 *   The quantity of recycled objects.
 *
 */
let Base = ( ParentClass = Object ) => class Base extends ParentClass {

  /**
   * This constructor will register this object to Pool.All.registeredPoolArray list. And it will never be removed from the list.
   *
   */
  constructor( poolName, objectClass, pfn_SetAsConstructor_ReturnObject, ...restArgs ) {
    super( ...restArgs );

    this.poolName = poolName;
    this.objectClass = objectClass;
    this.pfn_SetAsConstructor_ReturnObject = pfn_SetAsConstructor_ReturnObject;

    this.recycledObjectArray = new Array();
    this.recycledObjectSet = new Set();

    IssuedObjects.Singleton.registeredPoolArray.push( this ); // Register to the only one global All pool list.
  }

  /**
   *
   * @return {object}
   *   An obeject which is an instance of this.ObjectClass. If it is newly created, all RestArgs will be passed into its constructor.
   * If it is re-used (i.e. from recycled) object, all RestArgs will be passed into its .pfnSetAsConstructor() method.
   */
  get_or_create_by( ...restArgs ) {
    let returnedObject;

    // 1.

    // 1.1 Get recycled object.
    //
    // Note: candicatedObject and returnedObject may not be the same one object. It is possible the pfn_SetAsConstructor_ReturnObject()
    //       returns a different object.
    //
    let candicatedObject = this.recycledObjects.pop();
    if ( candicatedObject != null ) {
      returnedObject = this.pfn_SetAsConstructor_ReturnObject.apply( candicatedObject, restArgs );

    // 1.2 Create new object.
    } else {
      returnedObject = new ( this.objectClass )( ...restArgs );
    }

    // 2. Tracking the issued object for recycling automatically by session_pop().
    IssuedObjects.issuedObject_add.call( IssuedObjects.Singleton, returnedObject, this );

    return returnedObject;
  }

  /**
   * @param {Object} objectToBeRecycled
   *   The object (which should be an instance of this.ObjectClass) to be recycled.
   *
   * @return {boolean}
   *   Return true, if the object is recycled. Return false, if the object has already been recycled.
   */
  recycle( objectToBeRecycled ) {

    if ( objectToBeRecycled == null )
      return false; // 1. Can not recycle a null object.

    if ( !( objectToBeRecycled instanceof this.objectClass ) )
      throw Error( `Pool.Base.recycle(): `
        + `The object to be recycled ( ${objectToBeRecycled} ) `
        + `should be an instance of class ( ${this.objectClass} ).`
      );

    // 2. Removed it from issued object list. Otheriwse, the list will become larger and larger.
    IssuedObjects.issuedObject_remove.call( IssuedObjects.Singleton, objectToBeRecycled );

    // 3. Recycle it.
    let bRecycleOk = Base.recycled_add( this, objectToBeRecycled );
    return bRecycleOk;
  }

//!!!
  /**
   * @param {Object} objectToBeRecycled
   *   The object (which should be an instance of this.ObjectClass) to be recycled.
   *
   * @return {boolean}
   *   Return true, if the object is recycled. Return false, if the object has already been recycled.
   */
  static recycle_without_removeFrom_IssuedObjects( objectToBeRecycled ) {

    if ( objectToBeRecycled == null )
      return false; // 1. Can not recycle a null object.

    if ( !( objectToBeRecycled instanceof this.objectClass ) )
      throw Error( `Pool.Base.recycle(): `
        + `The object to be recycled ( ${objectToBeRecycled} ) `
        + `should be an instance of class ( ${this.objectClass} ).`
      );

//!!!
//     // 2. Removed it from issued object list. Otheriwse, the list will become larger and larger.
//     IssuedObjects.issuedObject_remove.call( IssuedObjects.Singleton, objectToBeRecycled );

    // 3. Recycle it.
    let bRecycleOk = Base.recycled_add( this, objectToBeRecycled );
    return bRecycleOk;
  }

  get recycled_count() {
    return this.recycledObjectArray.length;
  }

  /**
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @return {boolean} Return true, if the object is recorded in this recycle bin.
   */
  recycled_has( object ) {
    return this.recycledObjectSet.has( object );
  }

  /**
   * Discard all recycled objects (in this Pool.Base). (Note: The issued objects list are not influenced.)
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   */
  recycled_removeAll() {
    this.recycledObjectArray.length = 0;
    this.recycledObjectSet.clear();
  }

//!!! (2022/06/23 Remarked) seems not used.
//   /**
//    * @return {iterator)
//    *   Return an iterator object that contains all recycled objects.
//    */
//   * recycledValues() {
//     yield* this.recycledObjects.array.values();
//   }

  /**
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @param {Object} objectToBeRecycled
   *   The object to be recorded as recycled.
   *
   * @return {boolean}
   *   - Return true, if the object is recycled.
   *   - Return false, if the object has already been a recycled object.
   */
  static recycled_add( objectToBeRecycled ) {
    if ( this.recycledObjectSet.has( objectToBeRecycled ) ) { // Avoid recycling one object multiple times (i.e. duplicately).

      throw Error(
        `Pool.Base.recycled_add(): `
          + `An object ( ${objectToBeRecycled} ) is recycled multiple times. `
          + `This may imply some problem (e.g. resource not transferred properly).`
        );

      return false;

    } else { // Record it as recycled.
      this.recycledObjectSet.add( objectToBeRecycled );
      this.recycledObjectArray.push( objectToBeRecycled );
      return true;
    }
  }

  /**
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @return {Object}
   *   Pop the last object and return it. It may be null, if there is no object in this recycle bin.
   */
  static recycled_pop() {
    let object = this.recycledObjectArray.pop();
    if ( object == undefined )
      return null;
    this.recycledObjectSet.delete( object ); // Removed from set.
    return object;
  }

}

/**
 * Almost the same as Pool.Base class except its parent class is fixed to Object. In other words, caller can not
 * specify the parent class of Pool.Root (so it is named "Root" which can not have parent class).
 */
class Root extends Base() {
}

<commit_msg>Update Pool_Base.js<commit_after>export { Base, Root };

import { IssuedObjects } from "./Pool_IssuedObjects.js"

/**
 * A pool for recycling (re-using) objects. It collects all recycled (i.e. could be re-issued) objects of Pool.Base.
 * This could improve performance by reducing memory re-allocation.
 *
 *
 * @member {string} poolName
 *   The string name of this pool.
 *
 * @member {Class} objectClass
 *   The class for all newly created objects. If the instance of this objectClass has a method .disposeResources(), it will be called
 * when .sessionCall()'s ending (i.e. in .session_pop()) to release more resources.
 *
 * @member {function} pfn_SetAsConstructor_ReturnObject
 *   A function set contents like its constructor and return an object. Before .get_or_create_by() returns a recycled object,
 * its .pfnSetAsConstructor() method will be called to re-initilaize it. Its return value will be the final returned object.
 *
 * @member {Object} recycledObjectArray
 *   For fetching object efficiently (without creating iterator).
 *
 * @member {Set} recycledObjectSet
 *   The same content as .recycledObjectArray for checking object whether is recycled multiple times.
 *
 * @member {number} recycled_count
 *   The quantity of recycled objects.
 *
 */
let Base = ( ParentClass = Object ) => class Base extends ParentClass {

  /**
   * This constructor will register this object to Pool.All.registeredPoolArray list. And it will never be removed from the list.
   *
   */
  constructor( poolName, objectClass, pfn_SetAsConstructor_ReturnObject, ...restArgs ) {
    super( ...restArgs );

    this.poolName = poolName;
    this.objectClass = objectClass;
    this.pfn_SetAsConstructor_ReturnObject = pfn_SetAsConstructor_ReturnObject;

    this.recycledObjectArray = new Array();
    this.recycledObjectSet = new Set();

    IssuedObjects.Singleton.registeredPoolArray.push( this ); // Register to the only one global All pool list.
  }

  /**
   *
   * @return {object}
   *   An obeject which is an instance of this.ObjectClass. If it is newly created, all RestArgs will be passed into its constructor.
   * If it is re-used (i.e. from recycled) object, all RestArgs will be passed into its .pfnSetAsConstructor() method.
   */
  get_or_create_by( ...restArgs ) {
    let returnedObject;

    // 1.

    // 1.1 Get recycled object.
    //
    // Note: candicatedObject and returnedObject may not be the same one object. It is possible the pfn_SetAsConstructor_ReturnObject()
    //       returns a different object.
    //
    let candicatedObject = this.recycledObjects.pop();
    if ( candicatedObject != null ) {
      returnedObject = this.pfn_SetAsConstructor_ReturnObject.apply( candicatedObject, restArgs );

    // 1.2 Create new object.
    } else {
      returnedObject = new ( this.objectClass )( ...restArgs );
    }

    // 2. Tracking the issued object for recycling automatically by session_pop().
    IssuedObjects.issued_add.call( IssuedObjects.Singleton, returnedObject, this );

    return returnedObject;
  }

  /**
   * @param {Object} objectToBeRecycled
   *   The object (which should be an instance of this.ObjectClass) to be recycled.
   *
   * @return {boolean}
   *   Return true, if the object is recycled. Return false, if the object has already been recycled.
   */
  recycle( objectToBeRecycled ) {

    if ( objectToBeRecycled == null )
      return false; // 1. Can not recycle a null object.

    if ( !( objectToBeRecycled instanceof this.objectClass ) )
      throw Error( `Pool.Base.recycle(): `
        + `The object to be recycled ( ${objectToBeRecycled} ) `
        + `should be an instance of class ( ${this.objectClass} ).`
      );

    // 2. Removed it from issued object list. Otheriwse, the list will become larger and larger.
    IssuedObjects.issued_remove.call( IssuedObjects.Singleton, objectToBeRecycled );

    // 3. Recycle it.
    let bRecycleOk = Base.recycled_add( this, objectToBeRecycled );
    return bRecycleOk;
  }

//!!!
  /**
   * @param {Object} objectToBeRecycled
   *   The object (which should be an instance of this.ObjectClass) to be recycled.
   *
   * @return {boolean}
   *   Return true, if the object is recycled. Return false, if the object has already been recycled.
   */
  static recycle_without_removeFrom_IssuedObjects( objectToBeRecycled ) {

    if ( objectToBeRecycled == null )
      return false; // 1. Can not recycle a null object.

    if ( !( objectToBeRecycled instanceof this.objectClass ) )
      throw Error( `Pool.Base.recycle(): `
        + `The object to be recycled ( ${objectToBeRecycled} ) `
        + `should be an instance of class ( ${this.objectClass} ).`
      );

//!!!
//     // 2. Removed it from issued object list. Otheriwse, the list will become larger and larger.
//     IssuedObjects.issued_remove.call( IssuedObjects.Singleton, objectToBeRecycled );

    // 3. Recycle it.
    let bRecycleOk = Base.recycled_add( this, objectToBeRecycled );
    return bRecycleOk;
  }

  get recycled_count() {
    return this.recycledObjectArray.length;
  }

  /**
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @return {boolean} Return true, if the object is recorded in this recycle bin.
   */
  recycled_has( object ) {
    return this.recycledObjectSet.has( object );
  }

  /**
   * Discard all recycled objects (in this Pool.Base). (Note: The issued objects list are not influenced.)
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   */
  recycled_removeAll() {
    this.recycledObjectArray.length = 0;
    this.recycledObjectSet.clear();
  }

//!!! (2022/06/23 Remarked) seems not used.
//   /**
//    * @return {iterator)
//    *   Return an iterator object that contains all recycled objects.
//    */
//   * recycledValues() {
//     yield* this.recycledObjects.array.values();
//   }

  /**
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @param {Object} objectToBeRecycled
   *   The object to be recorded as recycled.
   *
   * @return {boolean}
   *   - Return true, if the object is recycled.
   *   - Return false, if the object has already been a recycled object.
   */
  static recycled_add( objectToBeRecycled ) {
    if ( this.recycledObjectSet.has( objectToBeRecycled ) ) { // Avoid recycling one object multiple times (i.e. duplicately).

      throw Error(
        `Pool.Base.recycled_add(): `
          + `An object ( ${objectToBeRecycled} ) is recycled multiple times. `
          + `This may imply some problem (e.g. resource not transferred properly).`
        );

      return false;

    } else { // Record it as recycled.
      this.recycledObjectSet.add( objectToBeRecycled );
      this.recycledObjectArray.push( objectToBeRecycled );
      return true;
    }
  }

  /**
   *
   * @param {Base}
   *   The Pool.Base object for handling the recycled bojects.
   *
   * @return {Object}
   *   Pop the last object and return it. It may be null, if there is no object in this recycle bin.
   */
  static recycled_pop() {
    let object = this.recycledObjectArray.pop();
    if ( object == undefined )
      return null;
    this.recycledObjectSet.delete( object ); // Removed from set.
    return object;
  }

}

/**
 * Almost the same as Pool.Base class except its parent class is fixed to Object. In other words, caller can not
 * specify the parent class of Pool.Root (so it is named "Root" which can not have parent class).
 */
class Root extends Base() {
}

<|endoftext|>


<commit_before>// kludge until this is normal.
if (!process.EventEmitter.prototype.on) {
  process.EventEmitter.prototype.on = process.EventEmitter.prototype.addListener
}
var path = require("path")
if (!process.execPath) {
  process.execPath = path.join(process.installPrefix, "bin", "node")
}

var npm = exports
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("fs")

npm.commands = {}
npm.SHOULD_EXIT = true

try {
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
} catch (ex) {
  log(ex, "error reading version")
  npm.version = ex
}

var commandCache = {}
; [ "install"
  , "activate"
  , "deactivate"
  , "uninstall"
  , "build"
  , "link"
  , "publish"
  , "tag"
  , "adduser"
  , "config"
  , "help"
  , "cache"
  , "test"
  , "stop"
  , "start"
  , "restart"
  , "unpublish"
  , "list"
  , "ls"
  , "rm"
  , "owner"
  , "update"
  , "update-dependents"
  ].forEach(function (c) {
    Object.defineProperty(npm.commands, c, { get : function () {
      c = c === "list" ? "ls"
        : c === "rm" ? "uninstall"
        : c
      if (c in commandCache) return commandCache[c]
      return commandCache[c] = require(__dirname+"/lib/"+c)
    }})
  })

// Local store for package data, so it won't have to be fetched/read more than
// once in a single pass.  TODO: cache this to disk somewhere when we're using
// the registry, to cut down on HTTP calls.
var registry = {}
npm.set = function (key, val) {
  if (typeof key === "object" && !val && key._id) {
    val = key
    key = key._id
  }
  return set(registry, key, val)
}
npm.get = function (key) { return get(registry, key) }

var path = require("path")
npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "root",
  { get : function () { return npm.config.get("root") }
  , set : function (r) {
      r = r.charAt(0) === "/" ? r
        : path.join(process.execPath, "..", "..", r)
      return npm.config.set("root", r)
    }
  , enumerable : true
  })
Object.defineProperty(npm, "dir",
  { get : function () { return path.join(npm.root, ".npm") }
  , enumerable : true
  })
Object.defineProperty(npm, "cache",
  { get : function () { return path.join(npm.root, ".npm", ".cache") }
  , enumerable : true
  })
Object.defineProperty(npm, "tmp",
  { get : function () { return path.join(npm.root, ".npm", ".tmp") }
  , enumerable : true
  })

process.on("exit", function () {
  var tmp = npm.tmp
  try {
    var files = fs.readdirSync(tmp)
  } catch (er) {
    if (er.message.indexOf("ENOENT") === 0) return
    return log(er, "Couldn't clean up tmp folder")
  }
  files.forEach(function (f) {
    try { fs.unlinkSync(tmp + "/" +f) }
    catch (er) { log(er, "Couldn't remove "+tmp+"/"+f) }
  })
})
<commit_msg>Print a kinder gentler error message when the tmp folder can't be cleaned up.<commit_after>// kludge until this is normal.
if (!process.EventEmitter.prototype.on) {
  process.EventEmitter.prototype.on = process.EventEmitter.prototype.addListener
}
var path = require("path")
if (!process.execPath) {
  process.execPath = path.join(process.installPrefix, "bin", "node")
}

var npm = exports
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("fs")

npm.commands = {}
npm.SHOULD_EXIT = true

try {
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
} catch (ex) {
  log(ex, "error reading version")
  npm.version = ex
}

var commandCache = {}
; [ "install"
  , "activate"
  , "deactivate"
  , "uninstall"
  , "build"
  , "link"
  , "publish"
  , "tag"
  , "adduser"
  , "config"
  , "help"
  , "cache"
  , "test"
  , "stop"
  , "start"
  , "restart"
  , "unpublish"
  , "list"
  , "ls"
  , "rm"
  , "owner"
  , "update"
  , "update-dependents"
  ].forEach(function (c) {
    Object.defineProperty(npm.commands, c, { get : function () {
      c = c === "list" ? "ls"
        : c === "rm" ? "uninstall"
        : c
      if (c in commandCache) return commandCache[c]
      return commandCache[c] = require(__dirname+"/lib/"+c)
    }})
  })

// Local store for package data, so it won't have to be fetched/read more than
// once in a single pass.  TODO: cache this to disk somewhere when we're using
// the registry, to cut down on HTTP calls.
var registry = {}
npm.set = function (key, val) {
  if (typeof key === "object" && !val && key._id) {
    val = key
    key = key._id
  }
  return set(registry, key, val)
}
npm.get = function (key) { return get(registry, key) }

var path = require("path")
npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "root",
  { get : function () { return npm.config.get("root") }
  , set : function (r) {
      r = r.charAt(0) === "/" ? r
        : path.join(process.execPath, "..", "..", r)
      return npm.config.set("root", r)
    }
  , enumerable : true
  })
Object.defineProperty(npm, "dir",
  { get : function () { return path.join(npm.root, ".npm") }
  , enumerable : true
  })
Object.defineProperty(npm, "cache",
  { get : function () { return path.join(npm.root, ".npm", ".cache") }
  , enumerable : true
  })
Object.defineProperty(npm, "tmp",
  { get : function () { return path.join(npm.root, ".npm", ".tmp") }
  , enumerable : true
  })

process.on("exit", function () {
  var tmp = npm.tmp
  try {
    var files = fs.readdirSync(tmp)
  } catch (er) {
    if (er.message.indexOf("ENOENT") === 0) return
    return log(er, "Couldn't clean up tmp folder")
  }
  files.forEach(function (f) {
    try { fs.unlinkSync(tmp + "/" +f) }
    catch (er) {
      log("Couldn't remove "+tmp+"/"+f, "tmp cleanup error")
      log(er, "tmp cleanup error")
      log("No big deal, just remove it manually.", "tmp cleanup error")
      log("    rm "+tmp+"/"+f, "tmp cleanup error")
    }
  })
})
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var path = require('path');
var chalk = require('chalk');
var ncp = Promise.promisify(require('ncp').ncp);
var rename = Promise.promisify(require('fs').rename);
var fs = Promise.promisifyAll(require('fs'));
var finder = require('fs-finder');
var exec = require('child_process').exec;

ncp.limit = 16;

var newProjectDir = process.cwd();
var generatorFilesPath = path.join(__dirname, '../generated');

// rename files
// make a promise
var noDb = process.argv[2] === "nodb";

var renameNoDbFiles = function renameNoDbFiles() {
  var paths = finder.from(newProjectDir).findFiles('*.nodb*');
  var newPaths = [];

  for (var i = 0; i < paths.length; i++) {
      var oldPath = paths[i];
      var targetString = '.nodb';
      var startPos = oldPath.indexOf(targetString);
      var newPath = oldPath.slice(0, startPos) + oldPath.slice(startPos + targetString.length);
      newPaths.push(rename(oldPath, newPath));
  }

  return Promise.all(newPaths);
};

var removeDbFiles = function removeDbFiles() {
  return new Promise(function(resolve, reject) {
    exec('rm -r ./client/pre-build/modules/ ./seed.js ./server/api/ ./server/db.js', function(error, stdout, stderr) {
      if(error) return reject(stderr);
      else return resolve(stdout);
    });
  });
};

var removeNoDbFiles = function removeNoDbFiles() {
  return new Promise(function(resolve, reject) {
    exec('find . -type f -name "*.nodb*" -delete', function(error, stdout, stderr) {
      if(error) return reject(stderr);
      else return resolve(stdout);
    });
  });

};

var copyFiles = function () {
    return ncp(generatorFilesPath, newProjectDir);
};

var renameGitignore = function () {
    var oldPath = path.join(newProjectDir, 'gitignore.txt');
    var newPath = path.join(newProjectDir, '.gitignore');
    return rename(oldPath, newPath);
};

console.log(chalk.green('Meaniscule is generating your new miniscule MEAN stack app.'));
console.log(chalk.green('You\'ll be up and running in no time!'));

(new Promise(function(resolve, reject) {
  if(noDb) {
    return copyFiles()
    .then(renameNoDbFiles)
    .then(removeDbFiles)
    .then(renameGitignore)
    .then(resolve);
  }
  else {
    return copyFiles()
    .then(removeNoDbFiles)
    .then(renameGitignore)
    .then(resolve);
  }
}))
.then(function () {
    console.log(chalk.green('Your app is ready!'));
    console.log(chalk.yellow('Run the following commands to get set up:'));
    console.log(chalk.white.bgBlack('- [Terminal 1] npm install '));
    console.log(chalk.white.bgBlack('- [Terminal 1] npm start   '));
    if(!noDb) console.log(chalk.white.bgBlack('- [Terminal 2] gulp seedDB '));
    console.log(chalk.white.bgBlack('- [Terminal 2] gulp        '));
})
.catch(function(err) {
    console.log(err);
});
<commit_msg>refactored promises to start from copyFiles function, then checking if nodb flag present<commit_after>var Promise = require('bluebird');
var path = require('path');
var chalk = require('chalk');
var ncp = Promise.promisify(require('ncp').ncp);
var rename = Promise.promisify(require('fs').rename);
var fs = Promise.promisifyAll(require('fs'));
var finder = require('fs-finder');
var exec = require('child_process').exec;

ncp.limit = 16;

var newProjectDir = process.cwd();
var generatorFilesPath = path.join(__dirname, '../generated');

// rename files
// make a promise
var noDb = process.argv[2] === "nodb";

var renameNoDbFiles = function renameNoDbFiles() {
  var paths = finder.from(newProjectDir).findFiles('*.nodb*');
  var newPaths = [];

  for (var i = 0; i < paths.length; i++) {
      var oldPath = paths[i];
      var targetString = '.nodb';
      var startPos = oldPath.indexOf(targetString);
      var newPath = oldPath.slice(0, startPos) + oldPath.slice(startPos + targetString.length);
      newPaths.push(rename(oldPath, newPath));
  }

  return Promise.all(newPaths);
};

var removeDbFiles = function removeDbFiles() {
  return new Promise(function(resolve, reject) {
    exec('rm -r ./client/pre-build/modules/ ./seed.js ./server/api/ ./server/db.js', function(error, stdout, stderr) {
      if(error) return reject(stderr);
      else return resolve(stdout);
    });
  });
};

var removeNoDbFiles = function removeNoDbFiles() {
  return new Promise(function(resolve, reject) {
    exec('find . -type f -name "*.nodb*" -delete', function(error, stdout, stderr) {
      if(error) return reject(stderr);
      else return resolve(stdout);
    });
  });

};

var copyFiles = function () {
    return ncp(generatorFilesPath, newProjectDir);
};

var renameGitignore = function () {
    var oldPath = path.join(newProjectDir, 'gitignore.txt');
    var newPath = path.join(newProjectDir, '.gitignore');
    return rename(oldPath, newPath);
};

console.log(chalk.green('Meaniscule is generating your new miniscule MEAN stack app.'));
console.log(chalk.green('You\'ll be up and running in no time!'));

copyFiles()
.then(function() {
  if(noDb) {
    return renameNoDbFiles()
    .then(removeDbFiles);
  }
  else {
    return removeNoDbFiles();
  }
})
.then(renameGitignore)
.then(function () {
    console.log(chalk.green('Your app is ready!'));
    console.log(chalk.yellow('Run the following commands to get set up:'));
    console.log(chalk.white.bgBlack('- [Terminal 1] npm install '));
    console.log(chalk.white.bgBlack('- [Terminal 1] npm start   '));
    if(!noDb) console.log(chalk.white.bgBlack('- [Terminal 2] gulp seedDB '));
    console.log(chalk.white.bgBlack('- [Terminal 2] gulp        '));
})
.catch(function(err) {
    console.log(err);
});

<|endoftext|>


<commit_before>// nodejs support
var exports = {};
var process = {};

// Ammo physics library
var Ammo = {};

// CRN, DDS support?
var Module = {};

<commit_msg>Temporary externs fix (#1755)<commit_after>// nodejs support
var exports = {};
var process = {};

// Ammo physics library
var Ammo = {};

// CRN, DDS support?
var Module = {};

// temp
var performance = {};
var WebAssembly = {};
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');

/**
 * Webpack Plugins
 */
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'test';

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /**
   * Source map for Karma from the help of karma-sourcemap-loader &  karma-webpack
   *
   * Do not change, leave as is or it wont work.
   * See: https://github.com/webpack/karma-webpack#source-maps
   */
  devtool: 'inline-source-map',

  /**
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /**
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js'],

    /**
     * Make sure root is src
     */
    root: helpers.root('src'),

  },

  /**
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /**
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /**
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [helpers.root('node_modules')]
      },

      /**
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
        // these packages have problems with their sourcemaps
        helpers.root('node_modules/rxjs'),
        helpers.root('node_modules/@angular')
      ]}

    ],

    /**
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /**
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
          compilerOptions: {

            // Remove TypeScript helpers to be injected
            // below by DefinePlugin
            removeComments: true

          }
        },
        exclude: [/\.e2e\.ts$/]
      },

      /**
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      { test: /\.json$/, loader: 'json-loader', exclude: [helpers.root('src/index.html')] },

      /**
       * Raw loader support for *.css files
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      { test: /\.css$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] },

      /**
       * Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] }

    ],

    /**
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    postLoaders: [

      /**
       * Instruments JS files with Istanbul for subsequent code coverage reporting.
       * Instrument only testing sources.
       *
       * See: https://github.com/deepsweet/istanbul-instrumenter-loader
       */
      {
        test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader',
        include: helpers.root('src'),
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }

    ]
  },

  /**
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Plugin: DefinePlugin
     * Description: Define free variables.
     * Useful for having development builds with debug logging or adding global constants.
     *
     * Environment helpers
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     */
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new DefinePlugin({
      'ENV': JSON.stringify(ENV),
      'HMR': false,
      'process.env': {
        'ENV': JSON.stringify(ENV),
        'NODE_ENV': JSON.stringify(ENV),
        'HMR': false,
      }
    }),

  ],

  /**
   * Static analysis linter for TypeScript advanced options configuration
   * Description: An extensible linter for the TypeScript language.
   *
   * See: https://github.com/wbuchwalter/tslint-loader
   */
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },

  /**
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    process: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<commit_msg>chore(webpack.test): correct css loaders<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');

/**
 * Webpack Plugins
 */
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'test';

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /**
   * Source map for Karma from the help of karma-sourcemap-loader &  karma-webpack
   *
   * Do not change, leave as is or it wont work.
   * See: https://github.com/webpack/karma-webpack#source-maps
   */
  devtool: 'inline-source-map',

  /**
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /**
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js'],

    /**
     * Make sure root is src
     */
    root: helpers.root('src'),

  },

  /**
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /**
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /**
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [helpers.root('node_modules')]
      },

      /**
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
        // these packages have problems with their sourcemaps
        helpers.root('node_modules/rxjs'),
        helpers.root('node_modules/@angular')
      ]}

    ],

    /**
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /**
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
          compilerOptions: {

            // Remove TypeScript helpers to be injected
            // below by DefinePlugin
            removeComments: true

          }
        },
        exclude: [/\.e2e\.ts$/]
      },

      /**
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      { test: /\.json$/, loader: 'json-loader', exclude: [helpers.root('src/index.html')] },

      /**
       * Raw loader support for *.css files
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [helpers.root('src/index.html')] },

      /**
       * Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] }

    ],

    /**
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    postLoaders: [

      /**
       * Instruments JS files with Istanbul for subsequent code coverage reporting.
       * Instrument only testing sources.
       *
       * See: https://github.com/deepsweet/istanbul-instrumenter-loader
       */
      {
        test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader',
        include: helpers.root('src'),
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }

    ]
  },

  /**
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /**
     * Plugin: DefinePlugin
     * Description: Define free variables.
     * Useful for having development builds with debug logging or adding global constants.
     *
     * Environment helpers
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
     */
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new DefinePlugin({
      'ENV': JSON.stringify(ENV),
      'HMR': false,
      'process.env': {
        'ENV': JSON.stringify(ENV),
        'NODE_ENV': JSON.stringify(ENV),
        'HMR': false,
      }
    }),

  ],

  /**
   * Static analysis linter for TypeScript advanced options configuration
   * Description: An extensible linter for the TypeScript language.
   *
   * See: https://github.com/wbuchwalter/tslint-loader
   */
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },

  /**
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    process: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<|endoftext|>