示例#1
0
文件: init.js 项目: guyzmuch/jpm
 .then(function () {
   return fs.exists(testPath)
 })
示例#2
0
 .map(function(p) { return fs.exists(p); }))
示例#3
0
 .then(path => {
   tmpPath = path;
   return fsp.exists(tmpPath);
 })
示例#4
0
文件: init.js 项目: guyzmuch/jpm
 .then(function() {
   return fs.exists(readmePath);
 })
 beforeEach(() => fsp.exists('test/tmp/.git/hooks/commit-msg')
   .then(exists => {
     if(exists) {
       return fsp.unlink('test/tmp/.git/hooks/commit-msg');
     }
 }));
 return retry(function () {
   return fs.exists(packageDir).then(function (nodeModulesExists) {
     expect(nodeModulesExists).to.be.false;
   });
 });
(() => __awaiter(this, void 0, void 0, function* () {
    const electronPrebuiltPath = argv.e ? path.resolve(process.cwd(), argv.e) : electron_locater_1.locateElectronPrebuilt();
    let electronPrebuiltVersion = argv.v;
    if (!electronPrebuiltVersion) {
        try {
            if (!electronPrebuiltPath)
                throw new Error("electron-prebuilt not found");
            const pkgJson = require(path.join(electronPrebuiltPath, 'package.json'));
            electronPrebuiltVersion = pkgJson.version;
        }
        catch (e) {
            throw new Error('Unable to find electron-prebuilt\'s version number, either install it or specify an explicit version');
        }
    }
    let rootDirectory = argv.m;
    if (!rootDirectory) {
        // NB: We assume here that we're going to rebuild the immediate parent's
        // node modules, which might not always be the case but it's at least a
        // good guess
        rootDirectory = path.resolve(__dirname, '../../..');
        if (!(yield fs.exists(rootDirectory)) || !(yield fs.exists(path.resolve(rootDirectory, 'package.json')))) {
            // Then we try the CWD
            rootDirectory = process.cwd();
            if (!(yield fs.exists(rootDirectory)) || !(yield fs.exists(path.resolve(rootDirectory, 'package.json')))) {
                throw new Error('Unable to find parent node_modules directory, specify it via --module-dir, E.g. "--module-dir ." for the current directory');
            }
        }
    }
    else {
        rootDirectory = path.resolve(process.cwd(), rootDirectory);
    }
    let modulesDone = 0;
    let moduleTotal = 0;
    const rebuildSpinner = ora('Searching dependency tree').start();
    let lastModuleName;
    const redraw = (moduleName) => {
        if (moduleName)
            lastModuleName = moduleName;
        if (argv.p) {
            rebuildSpinner.text = `Building modules: ${modulesDone}/${moduleTotal}`;
        }
        else {
            rebuildSpinner.text = `Building module: ${lastModuleName}, Completed: ${modulesDone}`;
        }
    };
    const rebuilder = rebuild_1.rebuild(rootDirectory, electronPrebuiltVersion, argv.a || process.arch, argv.w ? argv.w.split(',') : [], argv.f, argv.d, argv.t ? argv.t.split(',') : ['prod', 'dev'], argv.p ? 'parallel' : (argv.s ? 'sequential' : undefined));
    const lifecycle = rebuilder.lifecycle;
    lifecycle.on('module-found', (moduleName) => {
        moduleTotal += 1;
        redraw(moduleName);
    });
    lifecycle.on('module-done', () => {
        modulesDone += 1;
        redraw();
    });
    try {
        yield rebuilder;
    }
    catch (err) {
        rebuildSpinner.text = 'Rebuild Failed';
        rebuildSpinner.fail();
        throw err;
    }
    rebuildSpinner.text = 'Rebuild Complete';
    rebuildSpinner.succeed();
}))();
示例#8
0
co(function * () {
    /*  command-line option parsing  */
    let argv = yargs
        .usage("Usage: $0 [-v] [-w] [--ui=<dir>] [--db=<file>]")
        .count("v").alias("v", "verbose")
            .describe("v", "verbose output (repeatable)")
        .string("U").nargs("U", 1).alias("U", "ui").default("U", path.join(__dirname, "ui"))
            .describe("U", "user interface directory")
        .string("D").nargs("D", 1).alias("D", "db").default("D", path.join(__dirname, "app-db.json"))
            .describe("D", "database file")
        .string("H").alias("H", "host").nargs("H", 1).default("H", "127.0.0.1")
            .describe("H", "host name to listen on")
        .string("P").alias("P", "port").nargs("P", 1).default("P", "8888")
            .describe("P", "TCP port to listen on")
        .boolean("s").alias("s", "ssl").default("s", false)
            .describe("s", "speak SSL/TLS on host/port")
        .string("k").alias("k", "key").default("k", path.join(__dirname, "./app-tls-key.pem"))
            .describe("k", "use private key for SSL/TLS")
        .string("c").alias("c", "cert").default("c", path.join(__dirname, "./app-tls-crt.pem"))
            .describe("c", "use X.509 certificate for SSL/TLS")
        .boolean("t").alias("t", "traffic").default("t", false)
            .describe("t", "perform traffic accounting")
        .string("p").alias("p", "password").default("p", "admin")
            .describe("p", "password of superuser")
        .help("h").alias("h", "help").default("h", false)
            .describe("h", "show usage help")
        .boolean("V").alias("V", "version").default("V", false)
            .describe("V", "show program version")
        .strict()
        .showHelpOnFail(true)
        .demand(0)
        .parse(process.argv.slice(2))

    /*  short-circuit some options  */
    if (argv.version) {
        process.stderr.write(`${Package.name} ${Package.version} <${Package.homepage}>\n`)
        process.stderr.write(`${Package.description}\n`)
        process.stderr.write(`Copyright (c) ${Package.author.name} <${Package.author.url}>\n`)
        process.stderr.write(`Licensed under ${Package.license} <http://spdx.org/licenses/${Package.license}.html>\n`)
        process.exit(0)
    }

    /*  force color output  */
    chalk.enabled = true

    /*  utility function for verbose output  */
    const verbose = (level, msg) => {
        if (level <= argv.verbose)
            process.stderr.write(`${msg}\n`)
    }

    /*  drop a command-line headline  */
    verbose(1, "++ starting " + chalk.bold(Package.description))

    /*  establish connection to database  */
    const db = {
        query (...args) {
            return AlaSQL.promise(...args)
        },
        queryOne (...args) {
            return this.query(...args).then((result) => {
                if (result.length > 1)
                    throw new Error("more than one result found")
                return (result.length === 1 ? result[0] : null)
            })
        }
    }
    let exists = yield fs.exists(argv.D)
    if (!exists) {
        /*  on-the-fly provide database  */
        let password = yield pbkdf2.hash(argv.p, 10, "sha256")
        password = password.toString("hex")
        yield db.query(`
            CREATE FILESTORAGE DATABASE db("${argv.D}");
            ATTACH FILESTORAGE DATABASE db("${argv.D}");
            USE DATABASE db;
            CREATE TABLE users (username TEXT PRIMARY KEY, password TEXT);
            CREATE TABLE items (name TEXT PRIMARY KEY, val TEXT);
            INSERT INTO users VALUES ("admin", ?);`, [ password ])
    }
    else
        yield db.query(`
            ATTACH FILESTORAGE DATABASE db("${argv.D}");
            USE DATABASE db;`)

    /*  establish a new server context  */
    var server = new HAPI.Server()

    /*  create underlying HTTP/HTTPS listener  */
    let listener
    if (argv.ssl) {
        let key = yield fs.readFile(argv.key,  "utf8")
        let crt = yield fs.readFile(argv.cert, "utf8")
        listener = Http2.createServer({ key: key, cert: crt })
    }
    else
        listener = http.createServer()
    if (!listener.address)
        listener.address = function () { return this._server.address() }

    /*  configure the listening socket  */
    let hapiOpts = {
        listener: listener,
        address:  argv.host,
        port:     argv.port
    }
    if (argv.ssl)
        hapiOpts.tls = true
    server.connection(hapiOpts)

    /*  register HAPI plugins  */
    let register = Bluebird.promisify(server.register, { context: server })
    yield register({ register: Inert })
    yield register({ register: Auth })
    yield register({ register: HAPIBoom })
    yield register({ register: HAPIDucky })
    yield register({ register: HAPIHeader, options: { Server: `${Package.name}/${Package.version}` }})
    yield register({ register: HAPIWebSocket })
    yield register({ register: HAPICo })
    if (argv.t)
        yield register({ register: HAPITraffic })

    /*  log all requests  */
    server.on("tail", (request) => {
        let traffic = argv.t ? request.traffic() : null
        let ws = request.websocket()
        let protocol =
            (ws ? `WebSocket/${ws.ws.protocolVersion}+` : "") +
            `HTTP/${request.raw.req.httpVersion}`
        verbose(2, "-- request: " +
            "remote="   + chalk.blue(`${request.info.remoteAddress}:${request.info.remotePort}`) + ", " +
            "method="   + chalk.blue(request.method.toUpperCase()) + ", " +
            "url="      + chalk.blue(request.url.path) + ", " +
            "protocol=" + chalk.blue(protocol) + ", " +
            "response=" + chalk.blue(request.response.statusCode) +
            (argv.t ?  ", " +
                "recv="     + chalk.blue(traffic.recvPayload) + "/" + chalk.blue(traffic.recvRaw) + ", " +
                "sent="     + chalk.blue(traffic.sentPayload) + "/" + chalk.blue(traffic.sentRaw) + ", " +
                "duration=" + chalk.blue(traffic.timeDuration) : "")
        )
    })

    /*  prepare for JSONWebToken (JWT) authentication  */
    let result = yield db.queryOne(`SELECT password FROM users WHERE username = "admin"`)
    if (result === null)
        throw new Error("admin user not found")
    let jwtKey = result.password
    server.register(require("hapi-auth-jwt2"), (err) => {
        if (err)
            throw new Error(err)
        server.auth.strategy("jwt", "jwt", {
            key:           jwtKey,
            verifyOptions: { algorithms: [ "HS256" ] },
            urlKey:        "token",
            cookieKey:     "token",
            tokenType:     "JWT",
            validateFunc: (decoded, request, callback) => {
                db.queryOne("SELECT 1 FROM users WHERE username = ?", [ decoded.id ]).then((result) => {
                    return callback(null, result !== null, decoded)
                })
            }
        })
    })

    /*  display network interaction information  */
    const displayListenHint = ([ scheme, proto ]) => {
        let url = `${scheme}://${argv.host}:${argv.port}`
        verbose(1, `-- listen on ${chalk.blue(url)} (${proto})`)
    }
    displayListenHint(argv.ssl ?
        [ "https", "HTTP/{1.0,1.1,2.0} + SSL/TLS" ] :
        [ "http",  "HTTP/{1.0,1.1}" ])
    displayListenHint(argv.ssl ?
        [ "wss", "WebSockets + SSL/TLS" ] :
        [ "ws", "WebSockets" ])

    /*  load all modules  */
    let ctx = { argv, db, server, verbose, jwtKey }
    let mods = yield glob("./app-mod-*.js")
    mods.forEach((mod) => {
        require(mod)(ctx)
    })

    /*  fire up server  */
    yield Bluebird.promisify(server.start, { context: server })()

    /*  gracefully handle server shutdown  */
    const hookInto = (signal) => {
        process.on(signal, () => {
            verbose(2, `-- received ${signal} signal`)
            verbose(2, "-- shutting down service")
            server.root.stop({ timeout: 1 * 2000 }, () => {
                verbose(1, "++ shutting down " + chalk.bold(Package.description))
                process.exit(0)
            })
        })
    }
    let signals = [ "SIGINT", "SIGTERM" ]
    signals.forEach((signal) => hookInto(signal))

}).catch((err) => {
示例#9
0
文件: render.js 项目: jsonmaur/cdnex
/**
 * render cdnex
 * @return {Promise/object} It depends... should decouple this.
 */
export default async function render (options = {}) {
  try {
    if (!options.args) {
      options.args = []
    }

    if (!options.validate && options.validate !== false) {
      options.validate = true
    }

    if (options.validate && !validator.isURL(options.url)) {
      throw new Error(`${options.url} is not a valid domain name.`)
    }

    let input
    let isDir
    if (options.src) { /* input data was passed through as string */
      if (options.input) {
        throw new Error('dont specify both input and src. only choose one!')
      }

      input = options.src
    } else { /* input is a file/dirname, read from disk */
      input = options.input || options.args[0]
      if (!input) throw new Error('no input file or directory was specified.')

      const exists = await fs.exists(input)
      if (!exists) throw new Error(`"${input}" does not exist!`)

      const stats = await fs.lstat(input)
      isDir = stats.isDirectory()
    }

    let cdnexed
    if (isDir) {
      options.pattern = options.pattern || '/**/*.{html,css}'
      if (options.pattern.charAt(0) !== '/') {
        options.pattern = '/' + options.pattern
      }

      const files = await dn(glob)(path.resolve(input) + options.pattern)

      cdnexed = await Promise.all(
        files.map(async (file) => {
          try {
            cdnexed = await prepend(file, options)
            return { file, cdnexed }
          } catch (err) {
            return Promise.reject(err)
          }
        })
      )
    } else {
      cdnexed = await prepend(input, options)
    }

    if (options.output) {
      /* warn if overwriting */
      let outputExists = await fs.exists(options.output)
      if (outputExists) {
        /* doesnt really exist if its just an empty directory */
        outputExists = (await dn(glob)(`${options.output}/**/*`, {
          nodir: true
        })).length > 0
      }

      if (outputExists && !options.force && options.args.length > 0) {
        /* ask if they want to overwrite */
        const { overwrite } = await dn(inquirer.prompt, (a) => [null, a])([{
          type: 'confirm',
          name: 'overwrite',
          message: chalk.yellow(`${options.output} already exists. overwrite?`)
        }])

        /* abort if they dont */
        if (!overwrite) {
          throw new Error(chalk.red('change your output and try again.'))
        }
      } else if (outputExists && options.args.length === 0 && !options.force) {
        throw new Error('output already exists')
      }

      /* output to file(s) */
      if (typeof cdnexed === 'object') {
        await fs.ensureDir(options.output)

        await Promise.all(cdnexed.map((obj) => {
          /* generate output filename */
          obj.output = obj.file.replace(input, options.output)

          /* log paths without the cwd */
          if (!options.quiet) {
            console.log('rendering',
              obj.file.replace(process.cwd() + '/', ''), 'to',
              obj.output.replace(process.cwd() + '/', '')
            )
          }

          return fs.writeFile(obj.output, obj.cdnexed)
        }))
      } else {
        /* output to a single file */
        if (!options.quiet) {
          console.log(`rendering ${input} to ${options.output}`)
        }

        await fs.writeFile(options.output, cdnexed)
      }
    } else {
      /* no output, just return it */
      return cdnexed
    }
  } catch (err) {
    return Promise.reject(err)
  }
}