Best JavaScript code snippet using wpt
index.js
Source:index.js
1'use strict';2const co = require('co');3const util = require('util');4const is = require('is-type-of');5const assert = require('assert');6const awaitEvent = require('await-event');7const awaitFirst = require('await-first');8const EventEmitter = require('events').EventEmitter;9const CLOSE_PROMISE = Symbol('base#closePromise');10class Base extends EventEmitter {11 constructor(options) {12 super();13 if (options && options.initMethod) {14 assert(is.function(this[options.initMethod]),15 `[sdk-base] this.${options.initMethod} should be a function.`);16 process.nextTick(() => {17 if (is.generatorFunction(this[options.initMethod])) {18 this[options.initMethod] = co.wrap(this[options.initMethod]);19 }20 const ret = this[options.initMethod]();21 assert(is.promise(ret), `[sdk-base] this.${options.initMethod} should return either a promise or a generator`);22 ret.then(() => this.ready(true))23 .catch(err => this.ready(err));24 });25 }26 this.options = options || {};27 this._ready = false;28 this._readyError = null;29 this._readyCallbacks = [];30 this._closed = false;31 // support `yield this.await('event')`32 this.await = awaitEvent;33 this.awaitFirst = awaitFirst;34 this.on('error', err => { this._defaultErrorHandler(err); });35 }36 _wrapListener(eventName, listener) {37 if (is.generatorFunction(listener)) {38 assert(eventName !== 'error', '[sdk-base] `error` event should not have a generator listener.');39 const newListener = (...args) => {40 co(function* () {41 yield listener(...args);42 }).catch(err => {43 err.name = 'EventListenerProcessError';44 this.emit('error', err);45 });46 };47 newListener.original = listener;48 return newListener;49 }50 return listener;51 }52 addListener(eventName, listener) {53 return super.addListener(eventName, this._wrapListener(eventName, listener));54 }55 on(eventName, listener) {56 return super.on(eventName, this._wrapListener(eventName, listener));57 }58 once(eventName, listener) {59 return super.once(eventName, this._wrapListener(eventName, listener));60 }61 prependListener(eventName, listener) {62 return super.prependListener(eventName, this._wrapListener(eventName, listener));63 }64 prependOnceListener(eventName, listener) {65 return super.prependOnceListener(eventName, this._wrapListener(eventName, listener));66 }67 removeListener(eventName, listener) {68 let target = listener;69 if (is.generatorFunction(listener)) {70 const listeners = this.listeners(eventName);71 for (const fn of listeners) {72 if (fn.original === listener) {73 target = fn;74 break;75 }76 }77 }78 return super.removeListener(eventName, target);79 }80 /**81 * detect sdk start ready or not82 * @return {Boolean} ready status83 */84 get isReady() {85 return this._ready;86 }87 /**88 * set ready state or onready callback89 *90 * @param {Boolean|Error|Function} flagOrFunction - ready state or callback function91 * @return {void|Promise} ready promise92 */93 ready(flagOrFunction) {94 if (arguments.length === 0) {95 // return a promise96 // support `this.ready().then(onready);` and `yield this.ready()`;97 return new Promise((resolve, reject) => {98 if (this._ready) {99 return resolve();100 } else if (this._readyError) {101 return reject(this._readyError);102 }103 this._readyCallbacks.push(err => {104 if (err) {105 reject(err);106 } else {107 resolve();108 }109 });110 });111 } else if (is.function(flagOrFunction)) {112 this._readyCallbacks.push(flagOrFunction);113 } else if (flagOrFunction instanceof Error) {114 this._ready = false;115 this._readyError = flagOrFunction;116 if (!this._readyCallbacks.length) {117 this.emit('error', flagOrFunction);118 }119 } else {120 this._ready = flagOrFunction;121 }122 if (this._ready || this._readyError) {123 this._readyCallbacks.splice(0, Infinity).forEach(callback => {124 process.nextTick(() => {125 callback(this._readyError);126 });127 });128 }129 }130 _defaultErrorHandler(err) {131 if (this.listeners('error').length > 1) {132 // ignore defaultErrorHandler133 return;134 }135 console.error('\n[%s][pid: %s][%s] %s: %s \nError Stack:\n %s',136 Date(), process.pid, this.constructor.name, err.name,137 err.message, err.stack);138 // try to show addition property on the error object139 // e.g.: `err.data = {url: '/foo'};`140 const additions = [];141 for (const key in err) {142 if (key === 'name' || key === 'message') {143 continue;144 }145 additions.push(util.format(' %s: %j', key, err[key]));146 }147 if (additions.length) {148 console.error('Error Additions:\n%s', additions.join('\n'));149 }150 console.error();151 }152 close() {153 if (this._closed) {154 return Promise.resolve();155 }156 if (this[CLOSE_PROMISE]) {157 return this[CLOSE_PROMISE];158 }159 if (!this._close) {160 this._closed = true;161 return Promise.resolve();162 }163 let closeFunc = this._close;164 if (is.generatorFunction(closeFunc)) {165 closeFunc = co.wrap(closeFunc);166 }167 this[CLOSE_PROMISE] = closeFunc.apply(this);168 assert(is.promise(this[CLOSE_PROMISE]), '[sdk-base] this._close should return either a promise or a generator');169 return this[CLOSE_PROMISE]170 .then(() => {171 this._closed = true;172 })173 .catch(err => {174 this._closed = true;175 this.emit('error', err);176 });177 }178}179module.exports = Base;180// support es module...
egg.ts
Source:egg.ts
1import KoaApplication from 'koa'2const assert = require('assert')3const fs = require('fs')4const is = require('is-type-of')5const co = require('co')6const BaseContextClass = require('./utils/base_context_class')7const utils = require('./utils')8const Router = require('@eggjs/router').EggRouter9const Timing = require('./utils/timing')10const Lifecycle = require('./lifecycle')11const DEPRECATE = Symbol('EggCore#deprecate')12const ROUTER = Symbol('EggCore#router')13const EGG_LOADER = Symbol.for('egg#loader')14const CLOSE_PROMISE = Symbol('EggCore#closePromise')15export default class Core extends KoaApplication {16 timing: any17 _options: any18 options: any19 BaseContextClass: any20 Controller: any21 Service: any22 lifecycle: any23 loader: any24 console: any25 constructor (options: any = {}) {26 options.baseDir = options.baseDir || process.cwd()27 options.type = options.type || 'application'28 assert(typeof options.baseDir === 'string', 'options.baseDir required, and must be a string')29 assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`)30 assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`)31 assert(options.type === 'application' || options.type === 'agent', 'options.type should be application or agent')32 super()33 this.timing = new Timing()34 // cache deprecate object by file35 this[DEPRECATE] = new Map()36 this._options = this.options = options37 this.deprecate.property(this, '_options', 'app._options is deprecated, use app.options instead')38 this.BaseContextClass = BaseContextClass39 const Controller = this.BaseContextClass40 this.Controller = Controller41 const Service = this.BaseContextClass42 this.Service = Service43 this.lifecycle = new Lifecycle({44 baseDir: options.baseDir,45 app: this46 })47 this.lifecycle.on('error', err => this.emit('error', err))48 this.lifecycle.on('ready_timeout', id => this.emit('ready_timeout', id))49 this.lifecycle.on('ready_stat', data => this.emit('ready_stat', data))50 const Loader = this[EGG_LOADER]51 assert(Loader, 'Symbol.for(\'egg#loader\') is required')52 this.loader = new Loader({53 baseDir: options.baseDir,54 app: this,55 plugins: options.plugins,56 logger: this.console,57 serverScope: options.serverScope,58 env: options.env59 })60 }61 use (fn: any): any {62 assert(is.function(fn), 'app.use() requires a function')63 this.middleware.push(utils.middleware(fn))64 return this65 }66 get type () {67 return this.options.type68 }69 get baseDir () {70 return this.options.baseDir71 }72 get deprecate () {73 const caller = utils.getCalleeFromStack()74 if (!this[DEPRECATE].has(caller)) {75 const deprecate = require('depd')('egg')76 deprecate._file = caller77 this[DEPRECATE].set(caller, deprecate)78 }79 return this[DEPRECATE].get(caller)80 }81 get name () {82 return this.loader ? this.loader.pkg.name : ''83 }84 get plugins () {85 return this.loader ? this.loader.plugins : {}86 }87 get config () {88 return this.loader ? this.loader.config : {}89 }90 beforeStart (scope) {91 this.lifecycle.registerBeforeStart(scope)92 }93 ready (flagOrFunction) {94 return this.lifecycle.ready(flagOrFunction)95 }96 readyCallback (name, opts) {97 return this.lifecycle.legacyReadyCallback(name, opts)98 }99 beforeClose (fn) {100 this.lifecycle.registerBeforeClose(fn)101 }102 async close () {103 if (this[CLOSE_PROMISE]) return this[CLOSE_PROMISE]104 this[CLOSE_PROMISE] = this.lifecycle.close()105 return this[CLOSE_PROMISE]106 }107 get router () {108 if (this[ROUTER]) {109 return this[ROUTER]110 }111 const router = this[ROUTER] = new Router({ sensitive: true }, this)112 // register router middleware113 this.beforeStart(() => {114 this.use(router.middleware())115 })116 return router117 }118 url (name, params) {119 return this.router.url(name, params)120 }121 del (...args) {122 this.router.delete(...args)123 return this124 }125 get [EGG_LOADER] () {126 return require('./loader/egg_loader')127 }128 // toAsyncFunction (fn) {129 // if (!is.generatorFunction(fn)) return fn130 // fn = co.wrap(fn)131 // return async function (...args) {132 // return fn.apply(this, args)133 // }134 // }135 toPromise (obj) {136 return co(function * () {137 return yield obj138 })139 }140}141// delegate all router method to application142utils.methods.concat(['all', 'resources', 'register', 'redirect']).forEach(method => {143 Core.prototype[method] = function (...args) {144 this.router[method](...args)145 return this146 }...
authenticator-db.js
Source:authenticator-db.js
1function AuthenticatorDB() {2 var delete_promise = db_delete("crypto");3 var create_promise = db_create("Authenticator", db => db.createObjectStore("Client", { keyPath: "id" }))4 .then(db => db_close(db));5 this.ready = Promise.all([delete_promise, create_promise])6 .then(() => Promise.resolve())7 .catch(e => console.error("AuthenticatorDB " + e) || Promise.reject());8}9AuthenticatorDB.prototype.openDb = function() {10 return this.ready11 .then(() => db_open("Authenticator"));12}13AuthenticatorDB.prototype.deleteDb = function() {14 return db_delete("Authenticator");15}16AuthenticatorDB.prototype.getClientId = function() {17 var db_promise = this.openDb();18 var get_promise = db_promise19 .then(db => db_get(db, "Client", 0));20 var clientId_promise = get_promise.then(item => item.clientId);21 var close_promise = clientId_promise22 .finally(() => db_promise.then(db => db_close(db)));23 return Promise.all([clientId_promise,close_promise])24 .then(all => all[0])25 .catch(e => console.error("AuthenticatorDB.getClientId " + e) || Promise.reject());26}27AuthenticatorDB.prototype.setClientId = function(clientId) {28 var db_promise = this.openDb();29 var update_promise = db_promise30 .then(db => db_update(db, "Client", 0, item => item.clientId = clientId));31 var close_promise = update_promise32 .finally(() => db_promise.then(db => db_close(db)));33 return Promise.all([update_promise,close_promise])34 .then(() => Promise.resolve())35 .catch(e => console.error("AuthenticatorDB.setClientId " + e) || Promise.reject());36}37AuthenticatorDB.prototype.getKeyPair = function() {38 var db_promise = this.openDb();39 var get_promise = db_promise40 .then(db => db_get(db, "Client", 0));41 var keyPair_promise = get_promise.then(item => ({ publicKey: item.publicKey, privateKey: item.privateKey }));42 var close_promise = keyPair_promise43 .finally(() => db_promise.then(db => db_close(db)));44 return Promise.all([keyPair_promise,close_promise])45 .then(all => all[0])46 .catch(e => console.error("AuthenticatorDB.getKeyPair " + e) || Promise.reject());47}48AuthenticatorDB.S256 = { name: "SHA-256" };49AuthenticatorDB.RS256 = {50 name: "RSASSA-PKCS1-v1_5",51 modulusLength: 2048,52 publicExponent: new Uint8Array([1, 0, 1]),53 hash: AuthenticatorDB.S25654};55AuthenticatorDB.prototype.generateKeyPair = function() {56 var db_promise = this.openDb();57 var key_promise = crypto.subtle.generateKey(AuthenticatorDB.RS256, false, ["sign", "verify"]);58 var put_promise = Promise.all([db_promise, key_promise])59 .then(all => db_put(all[0], "Client", { id: 0, publicKey: all[1].publicKey, privateKey: all[1].privateKey, clientId: null }));60 var close_promise = put_promise61 .finally(() => db_promise.then(db => db_close(db)));62 return Promise.all([put_promise,key_promise,close_promise])63 .then(all => all[1])64 .catch(e => console.error("AuthenticatorDB.generateKey " + e) || Promise.reject());65}66AuthenticatorDB.prototype.getOrGenerateKeyPair = function() {67 return this.getKeyPair()68 .catch(() => this.generateKeyPair());...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test status: ' + data.statusText);5 wpt.close_promise();6});7var wpt = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org');9 if (err) return console.error(err);10 console.log('Test status: ' + data.statusText);11 wpt.close_promise();12});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 wpt.close_promise().then(function(
Using AI Code Generation
1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'your_api_key');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) return console.error(err);7 console.log('Test started: ' + data.data.testId);8 wpt.close_promise(data.data.testId)9 .then(function(data) {10 console.log('Test completed: ' + data.data.testId);11 console.log('Test results: ' + data.data.summary);12 })13 .catch(function(err) {14 console.log('Error: ' + err);15 });16});17var WebPageTest = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org', 'your_api_key');19var options = {20};21wpt.runTest(url, options, function(err, data) {22 if (err) return console.error(err);23 console.log('Test started: ' + data.data.testId);24 wpt.close_promise(data.data.testId)25 .then(function(data) {26 console.log('Test completed: ' + data.data.testId);27 console.log('Test results: ' + data.data.summary);28 })29 .catch(function(err) {30 console.log('Error: ' + err);31 });32});33var WebPageTest = require('webpagetest');34var wpt = new WebPageTest('www.webpagetest.org', 'your_api_key');35var options = {36};37wpt.runTest(url, options, function(err, data) {38 if (err) return console.error(err);
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.close_promise().then(function(){4 console.log("Wpt instance closed");5}).catch(function(err){6 console.log("Error in closing wpt instance");7 console.log(err);8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11wpt.close_promise().then(function(){12 console.log("Wpt instance closed");13}).catch(function(err){14 console.log("Error in closing wpt instance");15 console.log(err);16});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!