Best JavaScript code snippet using playwright-internal
spa-xhr.js
Source:spa-xhr.js  
...350          }351        }352        if (thisPromise.isResolved) {353          // This will run when the promise is resolved354          _runFn(_thenFns, 'then');355        } else {356          // This will run when the promise is rejected357          _runFn(_failFns, 'fail');358        }359        // This will run finally (resolved or rejected)360        _runFn(_doneFns, 'done');361      } else {362        console.warn('Already this promise has been ' + (thisPromise.isResolved ? 'Resolved.' : 'Rejected.'));363      }364      _clearTimer([timer0, timer1, timer2]);365    }366    function resolve () {367      complete.call(thisPromise, true, Array.prototype.slice.call(arguments));368    }369    function reject () {370      complete.call(thisPromise, false, Array.prototype.slice.call(arguments));371    }372    var fnContext = {373      resolve  : resolve,374      reject   : reject375    };376    timer0 = setTimeout(function () {377      if (_isFn(fn)) {378        var fnRes = fn.call(fnContext, resolve, reject);379        if (promiseTimeout) {380          timer1 = setTimeout(function () {381            if (thisPromise.isPending) {382              complete.call(thisPromise, !!fnRes, [fnRes]);383            }384          }, (_isUndef(fnRes) ? promiseTimeout : (deferTime || _defaultDeferTime)));385        }386      } else {387        timer2 = setTimeout(function () {388          if (thisPromise.isPending) {389            complete.call(thisPromise, !!fn, [fn]);390          }391        }, (deferTime || _defaultDeferTime));392      }393    }, _defaultDeferTime);394  }395  /* Attaching .then .fail .catch .done .always .finally to SimplePromise Class */396  _attachPrototypes(SimplePromise, {397    then   : _onPromiseSuccess,398    else   : _onPromiseError,399    fail   : _onPromiseError,400    catch  : _onPromiseError,401    done   : _onPromiseAlways,402    always : _onPromiseAlways,403    finally: _onPromiseAlways404  });405  function _registerPromiseFn (xPromise, fnType, fn) {406    var thisPromise = xPromise;407    if (typeof fn === 'function') {408      var isPromiseComplete = (!thisPromise.isPending);409      if (fnType === 'then') {410        isPromiseComplete = (isPromiseComplete && thisPromise.isResolved);411      } else if (fnType === 'fail') {412        isPromiseComplete = (isPromiseComplete && thisPromise.isRejected);413      }414      if (isPromiseComplete) {415        var prevFnRes = fn.apply(thisPromise, thisPromise.prevFnRes);416        if (_isDeferred(prevFnRes)) {417          thisPromise = prevFnRes;418        } else {419          thisPromise.prevFnRes = [prevFnRes];420        }421      } else {422        thisPromise.fnQ[fnType].push(fn);423      }424    }425    return thisPromise;426  }427  function _onPromiseSuccess (fn) {428    return _registerPromiseFn(this, 'then', fn);429  }430  function _onPromiseError (fn) {431    return _registerPromiseFn(this, 'fail', fn);432  }433  function _onPromiseAlways (fn) {434    return _registerPromiseFn(this, 'done', fn);435  }436  // export wrapper437  function _defer (input, deferTime, timeout) {438    if (arguments.length) {439      return new SimplePromise(input, deferTime, timeout);440    } else {441      return new SimplePromise(1, _defaultDeferTime);442    }443  }444  // ---------------------------------------------------------445  // XHRQ446  function XHRQ (que) {447    Object.defineProperty(this, 'fnQ', { value: { then:[], fail:[], done:[] } });448    this.requests  = que;449    this.responses = [];450    this.length    = que.length;451    this.isPending = que.length;452    this.isFailed  = false;453    this.failed    = [];454    this.prevFnRes;455    var thisPromise = this;456    var timerX;457    function _runFn (fnType) {458      var fnList = thisPromise.fnQ[fnType], nxtFnArg0;459      while (fnList.length > 0) {460        try {461          nxtFnArg0 = (typeof thisPromise.prevFnRes === 'undefined')? [] : [thisPromise.prevFnRes];462          thisPromise.prevFnRes = (fnList.shift()).apply(thisPromise, nxtFnArg0.concat(thisPromise.responses));463          _shiftFnsToNxtPromise(thisPromise, thisPromise.prevFnRes, fnType);464        } catch (e) {465          console.error('Function Execution Error.', e);466        }467      }468    }469    function updateQ () {470      thisPromise.isPending--;471      try {472        if (!thisPromise.isPending) {473          if (thisPromise.isFailed) {474            // This will run when any one request is failed475            _runFn('fail');476          } else {477            // This will run when all requests are successful478            _runFn('then');479          }480          // This will run when always481          _runFn('done');482          _clearTimer(timerX);483        }484      } catch (e) {485        console.error('Function Execution Error.', e);486        _clearTimer(timerX);487      }488    }489    timerX = setTimeout(function () {490      que.forEach(function (qItem, qIdx) {491        if ( (_isDeferred(qItem)) || (_isObjLike(qItem) && (_isFn(qItem['then']) || _isFn(qItem['fail']) || _isFn(qItem['catch']))) ) {492          if (typeof (qItem['then']) === 'function') {493            qItem.then(function () {494              thisPromise.responses[qIdx] = _argsToArr(arguments);495              updateQ();496            });497          }498          var failFnName = (typeof (qItem['fail']) === 'function') ? 'fail' : ((typeof (qItem['catch']) === 'function') ? 'catch' : '');499          if (failFnName) {500            qItem[failFnName](function () {501              thisPromise.responses[qIdx] = _argsToArr(arguments);502              thisPromise.isFailed  = true;503              thisPromise.failed.push(qIdx);504              updateQ();505            });506          }507        } else if (typeof qItem === 'function') {508          var qFnRes = qItem.call(thisPromise, thisPromise.requests, thisPromise.responses, qIdx);509          var isFnFailed = ((typeof (qFnRes) !== 'undefined') && !qFnRes);510          thisPromise.responses[qIdx] = qFnRes;511          thisPromise.isFailed  = thisPromise.isFailed || isFnFailed;512          if (isFnFailed) {513            thisPromise.failed.push(qIdx);514          }515          updateQ();516        } else {517          thisPromise.responses[qIdx] = qItem;518          thisPromise.isFailed = thisPromise.isFailed || !qItem;519          if (thisPromise.isFailed) {520            thisPromise.failed.push(qIdx);521          }522          updateQ();523        }524      });525    }, _defaultDeferTime);526  }527  Object.defineProperties(XHRQ.prototype, {528    then   : { value: _onXHRQSuccess  },529    fail   : { value: _onXHRQError    },530    catch  : { value: _onXHRQError    },531    done   : { value: _onXHRQAlways   },532    always : { value: _onXHRQAlways   },533    finally: { value: _onXHRQAlways   }534  });535  function _registerXHRQChainFn (xXHR, fnType, fn) {536    var thisXHRQ = xXHR, nxtFnArg0;537    if (typeof fn === 'function') {538      var isXHRQComplete = (!thisXHRQ.isPending);539      if (fnType === 'then') {540        isXHRQComplete = (isXHRQComplete && !thisXHRQ.isFailed);541      } else if (fnType === 'fail') {542        isXHRQComplete = (isXHRQComplete && thisXHRQ.isFailed);543      }544      if (isXHRQComplete) {545        nxtFnArg0 = (typeof thisXHRQ.prevFnRes === 'undefined')? [] : [thisXHRQ.prevFnRes];546        thisXHRQ.prevFnRes = fn.apply(thisXHRQ, nxtFnArg0.concat(thisXHRQ.responses));547        if (_isDeferred(thisXHRQ.prevFnRes)) {548          thisXHRQ = thisXHRQ.prevFnRes;549        }550      } else {551        thisXHRQ.fnQ[fnType].push(fn);552      }553    }554    return thisXHRQ;555  }556  function _onXHRQSuccess (fn) {557    return _registerXHRQChainFn(this, 'then', fn);558  }559  function _onXHRQError (fn) {560    return _registerXHRQChainFn(this, 'fail', fn);561  }562  function _onXHRQAlways (fn) {563    return _registerXHRQChainFn(this, 'done', fn);564  }565  function _xhrQ () {566    var que = [];567    var commonOptions = {};568    var method;569    var url;570    if (arguments.length) {571      for (var i = 0; i < arguments.length; i++) {572        if (Array.isArray(arguments[i])) {573          que = que.concat(arguments[i]);574        } else {575          que.push(arguments[i]);576        }577      }578    }579    que.forEach(function (qItem, qIdx) {580      if (typeof (qItem) === 'string') {581        if ((/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)(:+)/i).test(qItem)) {582          method = qItem.split(':')[0];583          url = qItem.replace(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)(:+)/i, '');584          if (url) {585            qItem = {586              url: url,587              method: method588            };589          } else {590            commonOptions['method'] = method;591          }592        } else {593          qItem = { url:qItem };594        }595        que[qIdx] = qItem;596      }597      if ((typeof (qItem) === 'object') && (!qItem['url'])) {598        commonOptions = _extend(commonOptions, qItem);599      }600    });601    var apiQue = [];602    que.forEach(function (qItem) {603      if ((_isObj(qItem) && qItem['url']) && (!_isDeferred(qItem))) {604        apiQue.push(_xhr(_extend({}, commonOptions, qItem)));605      } else if (_isDeferred(qItem)) {606        apiQue.push(qItem);607      } else {608        apiQue.push(_defer( qItem ));609      }610    });611    return new XHRQ(apiQue);612  }613  // ---------------------------------------------------------614  // ---------------------------------------------------------615  /* The Core XHR Base Class */616  function XHR (options) {617    Object.defineProperty(this, 'fnQ', { value:{ then:[], fail:[], done:[] } });618    this.xhr        = new XMLHttpRequest();619    this.reqOptions = options;620    this.isPending  = true;621    this.isSuccess  = false;622    this.isFailed   = false;623    this.response   = '';624    this.prevFnRes;625  }626  /* Attaching chain functions to XHR Class */627  Object.defineProperties(XHR.prototype, {628    then   : { value: _onXhrSuccess },629    fail   : { value: _onXhrError   },630    catch  : { value: _onXhrError   },631    done   : { value: _onXhrAlways  },632    always : { value: _onXhrAlways  },633    finally: { value: _onXhrAlways  }634  });635  function _registerXHRChainFn (xXHR, fnType, fn) {636    var thisXHR = xXHR, nxtFnArg0;637    if (typeof fn === 'function') {638      var isXHRComplete = (!thisXHR.isPending);639      if (fnType === 'then') {640        isXHRComplete = (isXHRComplete && thisXHR.isSuccess);641      } else if (fnType === 'fail') {642        isXHRComplete = (isXHRComplete && thisXHR.isFailed);643      }644      if (isXHRComplete) {645        if (thisXHR.isFailed) {646          nxtFnArg0 = (typeof thisXHR.prevFnRes === 'undefined')? thisXHR : thisXHR.prevFnRes;647          thisXHR.prevFnRes = fn.call(thisXHR.reqOptions, nxtFnArg0, thisXHR.statusText, thisXHR.statusMessage, thisXHR.response);648        } else {649          nxtFnArg0 = (typeof thisXHR.prevFnRes === 'undefined')? thisXHR.response : thisXHR.prevFnRes;650          thisXHR.prevFnRes = fn.call(thisXHR.reqOptions, nxtFnArg0, thisXHR.statusText, thisXHR, thisXHR.response);651        }652        if (_isDeferred(thisXHR.prevFnRes)) {653          thisXHR = thisXHR.prevFnRes;654        }655      } else {656        thisXHR.fnQ[fnType].push(fn);657      }658    }659    return thisXHR;660  }661  /* Internal function to handle .then( function ) */662  function _onXhrSuccess (fn) {663    return _registerXHRChainFn(this, 'then', fn);664  }665  /* Internal function to handle .fail( function ) | .catch( function ) */666  function _onXhrError (fn) {667    return _registerXHRChainFn(this, 'fail', fn);668  }669  /* Internal function to handle .done( function ) | .always( function ) | .finally( function ) */670  function _onXhrAlways (fn) {671    return _registerXHRChainFn(this, 'done', fn);672  }673  // ---------------------------------------------------------674  var _xhrProps = {675    defaults : {676      dataType     : 'text', // text, html, css, csv, xml, json, pdf, script, zip // responseType677      async        : true,   // true | false678      cache        : false,  // true | false679      method       : 'GET',  // GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS680      headers      : {},     // {key: 'value'} or function which returns {key: 'value'}681      auth         : null,   // { user: '', pwd: ''},682      timeout      : 0,      // 0=No Timeout; in milliseconds683      success      : null,   // function(response, statusCode, XHR) {}684      error        : null,   // function(response, statusCode, XHR) {}685      finally      : null    // function(response, statusCode, XHR) {}686      // ,preFilter   : false   // function(finalReqOptions, originalReqOptions, XHR){}687      // ,dataFilter  : false   // function(responseText, dataType){}688      // ,beforeSend  : function(rawXHR, finalReqOptions){} // to be used to set headers or cancel the request689      // ,urlParams     : {}690      // ,data          : {}  // payload691      // ,defaultPayload: {}  // {key: 'value'} or function which returns {key: 'value'}692      // ,defaultHeaders: {}  // {key: 'value'} or function which returns {key: 'value'}693      // ,onAbort           : function(event, XHR) {}694      // ,onError           : function(event, XHR) {}695      // ,onLoad            : function(event, XHR) {}696      // ,onLoadEnd         : function(event, XHR) {}697      // ,onLoadStart       : function(event, XHR) {}698      // ,onProgress        : function(event, XHR) {}699      // ,onReadyStateChange: function(event, XHR) {}700      // ,onTimeout         : function(event, XHR) {}701    },702    dataParsers : {703      css: _cssParser,704      json: _jsonParser,705      script: _scriptParser,706      javascript: _scriptParser707    },708    urls   : {},709    url    : _xhrUrl,710    setup  : _setupGlobalXHRDefaults,711    preFilter: _setupPreFilter,712    get   : function () {713      _arrProto.unshift.call(arguments, 'get');714      return _xhr.apply(undefined, arguments);715    },716    post  : function () {717      _arrProto.unshift.call(arguments, 'post');718      return _xhr.apply(undefined, arguments);719    },720    put   : function () {721      _arrProto.unshift.call(arguments, 'put');722      return _xhr.apply(undefined, arguments);723    },724    del   : function () {725      _arrProto.unshift.call(arguments, 'delete');726      return _xhr.apply(undefined, arguments);727    },728    patch : function () {729      _arrProto.unshift.call(arguments, 'patch');730      return _xhr.apply(undefined, arguments);731    },732    head : function () {733      _arrProto.unshift.call(arguments, 'head');734      return _xhr.apply(undefined, arguments);735    },736    options : function () {737      _arrProto.unshift.call(arguments, 'options');738      return _xhr.apply(undefined, arguments);739    }740  };741  var roKeys = 'url,setup,converters,preFilter,get,post,put,del,patch,head,options'.split(',');742  function _setupGlobalXHRDefaults ( newDefaults ) {743    if (_isObj(newDefaults)) {744      Object.keys(newDefaults).forEach(function(key){745        if (roKeys.indexOf(key)<0) {746          switch(key) {747            case 'dataParsers':748            case 'urls':749              if (_isObj(newDefaults[key])) {750                Object.keys(newDefaults[key]).forEach(function(parserKey){751                  _xhrProps[key][parserKey] = newDefaults[key][parserKey];752                });753              }754              break;755            default:756              _xhrProps.defaults[key] = newDefaults[key];757            break;758          }759        }760      });761    }762  }763  function _setupPreFilter( preFilterFn ) {764    if (_isFn(preFilterFn)) {765      _xhrProps.defaults['preFilter'] = preFilterFn;766    }767  }768  function _getOptionalVal(options, key){769    var optValue;770    if (_hasOwnProp(options, key)) {771      optValue = options[key];772    } else {773      optValue = _xhrProps.defaults[key];774    }775    return optValue;776  }777  function _cssParser ( srcCss ) {778    var styleText = document.createTextNode( srcCss );779    var styleNode = document.createElement( 'style' );780    styleNode.setAttribute( 'id', 'css-'+((new Date()).getTime()));781    styleNode.setAttribute( 'type', 'text/css');782    styleNode.appendChild(styleText);783    document.head.appendChild( styleNode );784    return srcCss;785  }786  function _jsonParser ( srcStr ) {787    var retObj = srcStr;788    try {789      retObj = JSON.parse(srcStr);790    } catch(e) {}791    return retObj;792  }793  function _scriptParser ( srcScript ) {794    if (srcScript.trim()) {795      var xScript = document.createElement( "script" );796      xScript.setAttribute( 'id', 'js-'+((new Date()).getTime()));797      xScript.text = srcScript;798      document.head.appendChild( xScript ).parentNode.removeChild( xScript );799    }800    return srcScript;801  }802  var httpStatus = {803    '200' : 'OK',804    '301' : 'Moved Permanently',805    '400' : 'Bad Request',806    '403' : 'Forbidden',807    '404' : 'Not Found',808    '405' : 'Method Not Allowed',809    '406' : 'Not Acceptable',810    '407' : 'Proxy Authentication Required',811    '408' : 'Request Timeout',812    '413' : 'Payload Too Large',813    '414' : 'URI Too Long',814    '415' : 'Unsupported Media Type',815    '429' : 'Too Many Requests',816    '431' : 'Request Header Fields Too Large',817    '500' : 'Internal Server Error',818    '502' : 'Bad Gateway',819    '503' : 'Service Unavailable',820    '504' : 'Gateway Timeout',821    '505' : 'HTTP Version Not Supported',822    '511' : 'Network Authentication Required'823  };824  var contentTypes = { text:'text/plain', html:'text/html', css:'text/css'825    , style:'text/css', csv:'text/csv', xml:'text/xml'826    , json:'application/json', pdf:'application/pdf', script:'application/javascript'827    , spacomponent:'application/javascript', zip:'application/zip' };828  /* URL Processing for any parameter replacement with object */829  /**830   * @param {string} url831   *832   * @example833   * xhr.url( '//127.0.0.1:1001/service-api/auth' )834   *         ==> '//127.0.0.1:1001/service-api/auth'835   *836   * xhr.url( '//127.0.0.1:1001/service-api/auth/{sesID}' )837   *         ==> '//127.0.0.1:1001/service-api/auth/{sesID}'838   *839   * xhr.url( '//127.0.0.1:1001/service-api/auth/{sesID}', {sesID: '12345-abcd-0000-xyz'} )840   *         ==> '//127.0.0.1:1001/auth/12345-abcd-0000-xyz'841   *842   * xhr.url( '//127.0.0.1:1001/service-api/auth/{ sesID }', {sesID: '12345-abcd-0000-xyz'} )843   *         ==> '//127.0.0.1:1001/auth/12345-abcd-0000-xyz'844   *845   * xhr.url( '//127.0.0.1:1001/service-api/auth/{ userInfo.sesID }', {userInfo: {sesID: '12345-abcd-0000-xyz'}} )846   *         ==> '//127.0.0.1:1001/auth/12345-abcd-0000-xyz'847   *848   * xhr.url( '//127.0.0.1:1001/service-api/auth/{ *sesID }', {userInfo: {sesID: '12345-abcd-0000-xyz'}} )849   *         ==> '//127.0.0.1:1001/auth/12345-abcd-0000-xyz'850   *851   */852  function _xhrUrl (url) {853    var lookUpUrl = (String(url || '')[0] === '@');854    url = String(url || '').replace(/^[@\s]+/, ''); //trimLeft @\s855    var finalUrl = lookUpUrl ? (_xhrProps.urls[url] || _findInX(_xhrProps.urls, url, url)) : url;856    var urlParamsDataCollection = _argsToArr(arguments, 1).map(function (obj) { return _is(obj, 'object|array') ? obj : {}; });857    var urlParams;858    var pKey;859    var pValue;860    urlParamsDataCollection = _mergeDeep.apply(null, urlParamsDataCollection);861    if (Object.keys(urlParamsDataCollection).length && (finalUrl.indexOf('{') > -1)) {862      urlParams = _strExtract(finalUrl, '{', '}', true);863      urlParams.forEach(function (param) {864        pKey     = param.replace(/[{}<>]/g, '');865        pValue   = _findInX(urlParamsDataCollection, pKey, urlParamsDataCollection['_undefined']);866        finalUrl = finalUrl.replace(new RegExp(param.replace(/([^a-zA-Z0-9])/g, '\\$1'), 'g'), pValue);867      });868    }869    return finalUrl;870  }871  function _xhr () {872    if (!arguments.length) {873      return _xhrQ.apply(null, []);874    } else if ((arguments.length === 2) && _isStr(arguments[0]) && (!(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)$/i).test(arguments[0])) && _isObj(arguments[1]) && !_hasOwnProp(arguments[1], 'url')) {875      // for jQ.ajax(url, {})876      var nOptions    = arguments[1];877      nOptions['url'] = arguments[0];878      return _xhr( nOptions );879    } else if (arguments.length > 1 || Array.isArray(arguments[0])) {880      return _xhrQ.apply(null, arguments);881    } else if (_isDeferred(arguments[0])) {882      return arguments[0];883    }884    // updating axOptions885    var iOptions = (_isObj(arguments[0])) ? arguments[0] : ((_isStr(arguments[0])) ? { url:arguments[0] } : {});886    var axDefaultsBase  = {};887    var skipDefaultsKeys = [];888    /** skipDefaults: true ==> ['payload','headers']889     *  skipDefaults: 'payload,headers' or ['payload', 'headers']890     *  skipDefaults: 'payload' or ['payload']891     *  skipDefaults: 'headers' or ['headers']892     */893    if (iOptions['skipDefaults']) {894      skipDefaultsKeys = iOptions['skipDefaults'];895      if (typeof (skipDefaultsKeys) === 'string') {896        skipDefaultsKeys = skipDefaultsKeys.split(',');897      } else if (typeof (skipDefaultsKeys) === 'boolean') {898        skipDefaultsKeys = ['payload','headers'];899      }900      if (Array.isArray(skipDefaultsKeys) && skipDefaultsKeys.length) {901        skipDefaultsKeys = skipDefaultsKeys.map(function (sKey) {902          sKey = sKey.replace(/default/gi, '').trim();903          return sKey? ('default'+ (sKey[0].toUpperCase()) + (sKey.slice(1))) : '';904        });905        Object.keys(_xhrProps.defaults).forEach(function (key) {906          if (skipDefaultsKeys.indexOf(key) < 0) {907            axDefaultsBase[key] = _xhrProps.defaults[key];908          }909        });910      } else {911        skipDefaultsKeys = [];912        axDefaultsBase = _extend({}, _xhrProps.defaults);913      }914    } else {915      axDefaultsBase = _extend({}, _xhrProps.defaults);916    }917    axDefaultsBase['method'] =  iOptions['method'] || iOptions['type'] || _xhrProps.defaults['method'];918    var axOptions = _extend({}, axDefaultsBase, iOptions);919    if (!axOptions.url) {920      console.error('XHR without URL.', arguments, axOptions);921      return;922    }923    axOptions.type = axOptions.method = axOptions.method.toUpperCase();924    var axResType     = axOptions.dataType.toLowerCase();925    var axContentType = contentTypes[ axResType ] || ( (axResType && (axResType.indexOf('/')<-1))? ('text/'+axOptions.dataType) : axOptions.dataType );926    var axHeaders     = {};927    // Headers928    var axDefaultHeaders = axOptions['defaultHeaders'];929    if (_isFn(axDefaultHeaders)) {930      axDefaultHeaders = axDefaultHeaders.call(axOptions, axOptions);931    }932    if (_isFn(axOptions.headers)) {933      axOptions.headers = axOptions.headers.call(undefined, axOptions);934    }935    if (_isObj(axOptions.headers)) {936      Object.keys(axOptions.headers).forEach(function (oKey) {937        axHeaders[oKey] = axOptions.headers[oKey];938      });939    }940    if (_isObj(axDefaultHeaders)) {941      if (_isUndef(axHeaders)) {942        axHeaders = axDefaultHeaders;943      } else if (_isObj(axHeaders)) {944        axHeaders = _extend(axDefaultHeaders, axHeaders);945      }946    }947    if (!axHeaders.hasOwnProperty('Content-Type') && axContentType) {948      axHeaders['Content-Type'] = axContentType;949    }950    axHeaders['X-Requested-With'] = 'XMLHttpRequest';951    axHeaders['Cache-Control'] = axOptions.cache ? 'max-age=86400000' : 'no-cache, no-store, must-revalidate, max-age=0';952    axHeaders['Expires']       = axOptions.cache ? ((new Date( (new Date()).setDate( (new Date()).getDate() + 1 ) )).toUTCString()) : '0';953    if (!axOptions.cache) {954      axHeaders['Pragma'] = 'no-cache';955    }956    axOptions['headers'] = axHeaders;957    // ----------------------------------------------------------------------958    // Create new HTTP Request Object959    var axReq       = new XHR(axOptions);960    var xhr         = axReq.xhr;961    var _reqOptions = axReq.reqOptions;962    var _fnQ        = axReq.fnQ;963    var timeoutTimer;964    var isTimeout;965    var isAborted;966    var isCanceled;967    var tX;968    if (_isFn(_reqOptions.success)) {969      _fnQ.then.push(_reqOptions.success);970    }971    if (_isFn(_reqOptions.error)) {972      _fnQ.fail.push(_reqOptions.error);973    }974    if (_isFn(_reqOptions.finally)) {975      _fnQ.done.push(_reqOptions.finally);976    }977    var onReadyStateChange;978    // Attach events979    Object.keys(_reqOptions).forEach(function (oKey) {980      var eName = oKey.toLowerCase();981      if ((eName === 'onreadystatechange') && (_isFn(_reqOptions[oKey]))) {982        onReadyStateChange = _reqOptions[oKey];983      } else if ((eName.indexOf('on') === 0) && (_isFn(_reqOptions[oKey]))) {984        xhr[eName] = function (e) {985          _reqOptions[oKey].call(xhr, e, axReq);986        };987      }988    });989    // Setup listener to process request state changes990    function _xhrReadyStateChange (e) {991      var thisXhrRaw = this;992      var xhrStatus  = thisXhrRaw.status;993      if (onReadyStateChange) {994        onReadyStateChange.call(_reqOptions, thisXhrRaw, e);995      }996      // Only run if the request is complete else return997      if (!isAborted && !isCanceled && thisXhrRaw.readyState !== 4) return;998      axReq.isPending    = false;999      axReq.readyState   = thisXhrRaw.readyState;1000      axReq.status       = thisXhrRaw.status;1001      axReq.responseText = thisXhrRaw.responseText;1002      axReq.response     = thisXhrRaw.responseText;1003      var xhrResponse   = thisXhrRaw.responseText;1004      function _runFn (fnType) {1005        var fnList = _fnQ[fnType], nxtFnArg0;1006        while (fnList.length > 0) {1007          try {1008            if (axReq.isFailed) {1009              nxtFnArg0 = (typeof axReq.prevFnRes === 'undefined')? axReq : axReq.prevFnRes;1010              axReq.prevFnRes = (fnList.shift()).call(_reqOptions, nxtFnArg0, axReq.statusText, axReq.statusMessage, axReq.response);1011            } else {1012              nxtFnArg0 = (typeof axReq.prevFnRes === 'undefined')? axReq.response : axReq.prevFnRes;1013              axReq.prevFnRes = (fnList.shift()).call(_reqOptions, nxtFnArg0, axReq.statusText, axReq, axReq.response);1014            }1015            _shiftFnsToNxtPromise(axReq, axReq.prevFnRes, fnType);1016          } catch (e) {1017            console.error('Function Execution Error.', e);1018          }1019        }1020      }1021      // Process response data1022      if ((xhrStatus >= 200 && xhrStatus < 300) || (xhrStatus === 304)) {1023        axReq.isSuccess  = true;1024        axReq.statusText = 'success';1025        axReq.statusMessage = 'OK';1026        var dataParser, parsedResponse;1027        if (_hasOwnProp(_reqOptions, 'dataParser')) {1028          dataParser = _reqOptions.dataParser;1029        } else {1030          dataParser = _xhrProps.dataParsers[ axResType ];1031        }1032        if (dataParser && _isFn(dataParser)) {1033          try {1034            parsedResponse = dataParser(xhrResponse, axResType);1035          } catch (e) {1036            console.warn('dataParsing failed.', xhrResponse, axReq, e);1037          }1038        }1039        if (!_isUndef(parsedResponse)) {1040          xhrResponse = parsedResponse;1041        }1042        var dataFilter = _getOptionalVal(_reqOptions, 'dataFilter'), dataFilterResponse;1043        if (dataFilter && _isFn(dataFilter)) {1044          try {1045            dataFilterResponse = dataFilter.call(axReq['reqOptions'], xhrResponse, axResType);1046          } catch (e) {1047            console.warn('dataFilter failed.', xhrResponse, axReq, e);1048          }1049        }1050        if (!_isUndef(dataFilterResponse)) {1051          xhrResponse = dataFilterResponse;1052        }1053        var _sanitizeApiXss = _reqOptions['sanitizeApiXss']; //ajaxOptions.sanitizeApiXss1054        if (_sanitizeApiXss) {1055          xhrResponse = _isFn(_sanitizeApiXss)? (_sanitizeApiXss.call(xhrResponse, xhrResponse) || xhrResponse) : _sanitizeXSS(xhrResponse);1056        }1057        if (axResType === 'json') {1058          axReq.responseJSON = xhrResponse;1059        }1060      } else {1061        xhrResponse         = thisXhrRaw.responseText;1062        axReq.isFailed      = true;1063        if (timeoutTimer && isTimeout) {1064          axReq.statusText    = 'timeout';1065          axReq.statusMessage = 'timeout';1066        } else if (isAborted) {1067          axReq.statusText    = 'abort';1068          axReq.statusMessage = 'abort';1069        } else if (isCanceled) {1070          axReq.statusText    = 'canceled';1071          axReq.statusMessage = 'canceled';1072        } else {1073          axReq.statusText    = 'error';1074          axReq.statusMessage = httpStatus[xhrStatus] || 'Unknown Error';1075        }1076      }1077      axReq.response  = xhrResponse;1078      if (axReq.isSuccess) {1079        // This will run when the request is successful1080        _runFn('then');1081      } else if (axReq.isFailed) {1082        // This will run when the request is failed1083        _runFn('fail');1084      }1085      // This will run always1086      _runFn('done');1087      _clearTimer([timeoutTimer, tX]);1088    }1089    xhr.onreadystatechange = _xhrReadyStateChange;1090    // request payload1091    var axDefaultPayload = _reqOptions['defaultPayload'];1092    if (_isFn(axDefaultPayload)) {1093      axDefaultPayload = axDefaultPayload.call(_reqOptions, _reqOptions);1094    }1095    var axPayload = _reqOptions['data'];1096    if (_isObj(axDefaultPayload)) {1097      if (_isUndef(axPayload)) {1098        axPayload = axDefaultPayload;1099      } else if (_isObj(axPayload)) {1100        axPayload = _mergeDeep(axDefaultPayload, axPayload);...breathe.js
Source:breathe.js  
...38        return;39      }40      that.state = promiseStates.resolved;41      that._value = value;42      that._runFn(function () {43        that._clearResolvedQueue();44      });45    };46    this.reject = function (reason) {47      if (that.state !== promiseStates.pending) {48        return;49      }50      that.state = promiseStates.rejected;51      that._reason = reason;52      if (!that._pendingCatch.length && ImmediatePromise.loggingErrors) {53        that._loggingErrorTimeout = setTimeout(function () {54          console.warn(that._reason);55        }, ImmediatePromise.loggingErrorTimeout);56      }57      that._runFn(function () {58        that._clearRejectedQueue();59      });60    };61    fn.call(this, this.resolve, this.reject);62  };63  var _resolveValueOrPromise = function (that, d, resolve, reject) {64    var then;65    var thenableCalled = false;66    try {67      if (d === that) {68        reject(new TypeError("Recursive Promise Detected"));69        return;70      }71      then = d && d.then;72      if ((isObject(d) || isFunction(d)) && isFunction(then)) {73        then.call(d, function (val) {74          if (thenableCalled) {75            return;76          }77          if (d === val) {78            reject(new TypeError("Recursive Promise Detected"));79            return;80          }81          thenableCalled = true;82          _resolveValueOrPromise(that, val, resolve, reject);83        }, function (reason) {84          if (thenableCalled) {85            return;86          }87          thenableCalled = true;88          reject(reason);89        });90      } else {91        resolve(d);92      }93    } catch (e) {94      if (!thenableCalled) {95        reject(e);96      }97    }98  };99  ImmediatePromise.prototype = {100    _clearResolvedQueue: function () {101      while (this._pendingThen.length) {102        this._pendingThen.shift()(this._value);103      }104    },105    _clearRejectedQueue: function () {106      while (this._pendingCatch.length) {107        this._pendingCatch.shift()(this._reason);108      }109    },110    _runFn: function (fn) {111      if (this.immediate) {112        fn();113      } else {114        setTimeout(fn, 0);115      }116    },117    then: function (onResolved, onRejected) {118      var that = this;119      var p = {};120      p = new ImmediatePromise(function (resolve, reject) {121        var resolveValue = (that.state === promiseStates.rejected) ? null : function (value) {122          if (isFunction(onResolved)) {123            try {124              _resolveValueOrPromise(p, onResolved(value), resolve, reject);125            } catch (e) {126              reject(e);127            }128          } else {129            resolve(value);130          }131        };132        var catchReason = (that.state === promiseStates.resolved) ? null : function (reason) {133          if (isFunction(onRejected)) {134            try {135              _resolveValueOrPromise(p, onRejected(reason), resolve, reject);136            } catch (e) {137              reject(e);138            }139          } else {140            reject(reason);141          }142        };143        that._pendingThen.push(resolveValue);144        that._pendingCatch.push(catchReason);145        clearTimeout(that._loggingErrorTimeout);146        if (that.state === promiseStates.resolved) {147          that._runFn(function () {148            that._clearResolvedQueue();149          });150        } else if (that.state === promiseStates.rejected) {151          that._runFn(function () {152            that._clearRejectedQueue();153          });154        }155      });156      return p;157    },158    'catch': function (onRejected) {159      this.then(null, onRejected);160    }161  };162  ImmediatePromise.resolve = function (d) {163    var p = new ImmediatePromise(function (resolve, reject) {164      _resolveValueOrPromise({}, d, resolve, reject);165    });...flow-stage.js
Source:flow-stage.js  
...192    // ## 2. Run this stage193    const input = this._getInput();194    let output;195    try {196      output = await this._runFn(input);197    } catch (error) {198      this._state = {199        status: 'run-error',200        error,201      };202      throw error;203    }204    // ## 3. Save result205    this._state = {206      status: 'response-received',207      output,208    };209  }, { cachePromiseRejection: true });210  beforeSetup() {...datalazyload.js
Source:datalazyload.js  
1/**2 * @todo : Êý¾ÝÀÁ¼ÓÔØ3 * @author : yu.yuy4 * @createTime : 2011-04-255 * @version : 1.26 * @update : yu.yuy 2011-11-02 Ìí¼Óbind·½·¨£¬»ùÓÚbind·½·¨ÓÅ»¯Á˱éÀú×ÊÔ´³ØµÄÐÔÄÜ7 * @update : yu.yuy 2011-11-10 (1)Ôö¼ÓÊÓ´°µ×²¿¸ÕºÃµÈÓÚÈÝÆ÷λÖõÄÅжÏÂß¼£»(2)·Ï³ýÒì²½º¯ÊýµÄhash±í£¬¸ÄÓÃÔÚ×ÊÔ´³ØÖÐÓë¼ÄÖ÷DOMÔªËØÒ»ÆðÀ¦°ó³ÉÒ»¸öÊý×飻(3)ʹÓÃattr´úÌædataÀ´È¡×Ô¶¨ÒåÊôÐÔµÄÖµ¡£8 * @update : yu.yuy 2011-12-19 ÓÉÓÚIEÏÂͬһͼƬµÄonloadʼþÖ»´¥·¢Ò»´Î£¬Õâµ¼ÖÂÔÚÒ³ÃæÖжദÒýÓÃͬһͼƬµÄʱºò³öÏֶദͼƬÎÞ·¨ÔØÈëµÄÇé¿ö£¬ËùÒÔ±¾´ÎÐÞ¸ÄÏÈÈ¥³ýͼƬ¼ÓÔØÊ±µÄ½¥ÏÔ¶¯»¡£9 */10('datalazyload' in FE.util) || 11    (function($, Util){12    var WIN = window,13    DOC = document,14    IMGSRCNAME = 'data-lazyload-src',15    FNCLASSNAME = 'lazyload-fn',16    FNATTRIBUTE = 'data-lazyload-fn-body',17    TEXTAREACLASSNAME = 'lazyload-textarea',18    datalazyload = function(){19        var _defaultThreshold = 200,20        _threshold = 0,21        options = {},22        _isRunning = false,23        _viewportHeight = 0,24        _scollBody = $(WIN),25        //×ÊÔ´³Ø26        resourcePool = {27            img : [],28            fn : [],29            textarea : []30        },31        /*32         * ºÏ²¢Êý×飬ȥ³ýÖØ¸´Ïî¡£33         */34        _uniqueMerge = function(des,a){35            for(var i=0;i<a.length;i++){36                for(var j=0,len=des.length;j<len;j++){37                    if(a[i] === des[j]){38                        a.splice(i,1);39                        break;40                    }41                }42            }43            $.merge(des,a);44        },45        /*46         * ±éÀú×ÊÔ´Êý×飬ÌÞ³ýÂú×ãÒªÇóµÄÏî47         */48        _filter = function(array, method, context){49            var item;50            for(var i=0;i<array.length;) {51                item = array[i];52                if(_checkPosition(item)){53                    array.splice(i, 1);54                    method.call(context,item);55                }56                else{57                    i++;58                }59            }60        },61        /*62         * º¯Êý½ÚÁ÷63         */64        _throttle = function(method, context){65            clearTimeout(method.tId);66            method.tId = setTimeout(function(){67                method.call(context);68            },100);69        },70        /*71         * »ñÈ¡µ±Ç°ÊÓ´°¸ß¶È72         */73        _getViewportHeight = function(){74            return _scollBody.height();75        },76        /*77         * °ó¶¨¹ö¶¯¡¢´°¿ÚËõ·Åʼþ78         */79        _bindEvent = function(){80            if(_isRunning){81                return;82            }83            _scollBody.bind('scroll.datalazyload', function(e){84                _throttle(_loadResources);85            }); 86            _scollBody.bind('resize.datalazyload', function(e){87                _viewportHeight = _getViewportHeight();88                _throttle(_loadResources);89            });90            _isRunning = true;91        },92        /*93         * ÒÆ³ý¹ö¶¯¡¢´°¿ÚËõ·Åʼþ94         */95        _removeEvent = function(){96            if(!_isRunning){97                return;98            }99            _scollBody.unbind('scroll.datalazyload');100            _scollBody.unbind('resize.datalazyload');101            _isRunning = false;102        },103        /*104         * ÊÕ¼¯ËùÓÐÐèÒªÀÁ¼ÓÔØµÄ×ÊÔ´105         */106        _collect = function(container){107            var imgs = $('img['+IMGSRCNAME+']',container).toArray(),108            fns = $('.'+FNCLASSNAME,container).toArray(),109            textareas = $('.'+TEXTAREACLASSNAME,container).toArray();110            _uniqueMerge(resourcePool['img'],imgs);111            _uniqueMerge(resourcePool['fn'],fns);112            _uniqueMerge(resourcePool['textarea'],textareas);113        },114        /*115         * ¼ÓÔØ¸÷×ÊÔ´116         */117        _loadResources = function(){118            _filter(resourcePool['img'], _loadImg);119            _filter(resourcePool['fn'], _runFn);120            _filter(resourcePool['textarea'], _loadTextarea);121                122            //Èç¹ûÒÑÎÞ×ÊÔ´¿ÉÒÔ¼ÓÔØ£¬ÔòÇå³ýËùÓÐÀÁ¼ÓÔØÊ¼þ123            if(resourcePool['img'].length===0 && resourcePool['fn'].length===0 && resourcePool['textarea'].length===0){124                _removeEvent();125                //that._trigger('complete');126            }127        },128        /*129         * ¼ÓÔØÍ¼Æ¬130         */131        _loadImg = function(el){132            var src;133            el = $(el);134            src = el.attr(IMGSRCNAME);135            if(src){136                //el.css('display', 'none');137                el.attr('src',src);138                el.removeAttr(IMGSRCNAME);139                //el.load(function(){140                //    $(this).fadeIn('show');141                //});142            }143        },144        /*145         * Ö´ÐÐÒì²½º¯Êý146         */147        _runFn = function(a){148            var el,149            fn,150            fnStr;151            if($.isArray(a)){152                el = a[0];153                fn = a[1];154            }155            else{156                el = a;157            }158            if(fn){159                fn(el);160            }161            el = $(el);162            fnStr = el.attr(FNATTRIBUTE);163            if(fnStr){164                fn = _parseFunction(fnStr);165                fn(el);166                el.removeAttr(FNATTRIBUTE);167            }168        },169        /*170         * ´ÓÖ¸¶¨µÄtextareaÔªËØÖÐÌáÈ¡ÄÚÈÝ£¬²¢½«ËüäÖȾµ½Ò³ÃæÉÏ171         */172        _loadTextarea = function(el){173            el = $(el);174            el.html($('textarea', el).val());175        },176        /*177         * ½«×Ö·û´®×ª»¯Îª¿ÉÒÔÖ´Ðеĺ¯Êý178         */179        _parseFunction = function(s){180            var a = s.split('.'),181            l=a.length,182            o = WIN;183            for(var i=($.isWindow(a[0])?1:0);i<l;i++){184                if($.isFunction(o[a[i]]) || $.isPlainObject(o[a[i]])){185                    o = o[a[i]];186                }187                else{188                    return null;189                }190            }191            if($.isFunction(o)){192                return o;193            }194            return null;195        },196        /*197         * ÅжÏÔªËØÊÇ·ñÒѾµ½ÁË¿ÉÒÔ¼ÓÔØµÄµØ·½198         */199        _checkPosition = function(el){200            var ret = false,201            currentScrollTop = $(DOC).scrollTop(),202            benchmark = currentScrollTop + _viewportHeight + _threshold,203            currentOffsetTop = $(el).offset().top;204            if(currentOffsetTop <= benchmark){205                ret = true;206            }207            return ret;208        },209        _toFnArray = function(els,fn){210            var ret = [],211            l;212            if(!els){213                return ret;214            }215            l = els.length;216            if(!l){217                ret.push([els,fn]);218            }219            else if(l > 0){220                for(var i=0;i<l;i++){221                    ret.push([els[i],fn])222                }223            }224            return ret;225        };226        return {227                228            /**229                         * ³õʼ»¯230                         */231            init : function(){232                if(!_isRunning){233                    _viewportHeight = _getViewportHeight();234                    _bindEvent();235                }236                _loadResources();237            },238            /*239                         * ×¢²á240                         */241            register : function(options){242                var containers = options.containers;243                _threshold = options.threshold || _defaultThreshold;244                for(var i=0,l=containers.length;i<l;i++){245                    this.bind(containers[i],$.proxy(this.add, this));246                }247                this.init();248            },249            /*250                         * Ìí¼ÓÐèÒªÀÁ¼ÓÔØµÄ×ÊÔ´251                         */252            add : function(container){253                _collect(container);254                this.init();255            },256            /*257                         * ½«Òì²½´¥·¢º¯Êý°ó¶¨ÔÚ¸¡±êÔªËØÉÏ£¬¼´×ø±êÔªËØÒ»ÆØ¹â¾Í´¥·¢¸Ãº¯Êý¡£258                         */259            bind : function(el,fn){260                var els = _toFnArray(el,fn);261                if(els.length === 0){262                    return;263                }264                _uniqueMerge(resourcePool['fn'],els);265            }266        }267    };268    Util.datalazyload = datalazyload();
...PromiseQueue.js
Source:PromiseQueue.js  
...55    return promise;56  }57  async _next(): Promise<void> {58    let fn = this._queue.shift();59    await this._runFn(fn);60    if (this._queue.length) {61      this._next();62    } else if (this._numRunning === 0) {63      this._done();64    }65  }66  async _runFn(fn: () => mixed): Promise<void> {67    this._numRunning++;68    try {69      await fn();70    } catch (e) {71      // Only store the first error that occurs.72      // We don't reject immediately so that any other concurrent73      // requests have time to complete.74      if (this._error == null) {75        this._error = e;76      }77    } finally {78      this._numRunning--;79    }80  }...Plugin.js
Source:Plugin.js  
...21        }22    };23    t.load = function (...layouts) {24        t.add(isArray(layouts[0]) ? layouts[0] : layouts);25        _runFn();26    };27    t.reload = function () {28        t.load(_lastLayouts)29    }30    t.getType = function() {31        return type;32    };33    // private functions34    const _readyFn = function () {35        _isReady = true;36        _isPending = false;37    };38    const _pendingFn = function () {39        _isPending = true;...Timer.js
Source:Timer.js  
...47            let elapsedTime = this._interval + elapsedTime_Total - Math.floor(48                    elapsedTime_Total / this._interval) * this._interval;49            this._interval_Elapsed = null;50            this._lastTick = (new Date()).getTime();51            this._runFn(elapsedTime, elapsedTime_Total);52            setTimeout(() => {53                tick();54            }, this._interval + elapsedTime_Diff);55        };56        this._lastTick = (new Date()).getTime();57        let firstInterval = this._interval_Elapsed === null ? 58                this._interval : (this._interval - this._interval_Elapsed);59        60        this._running = true;61        setTimeout(() => {62            tick();63        }, firstInterval);64    }65    stop()...Op.js
Source:Op.js  
...22        if (button.confirm) {23            // å¼¹åºçªå£ä¸ç¨24            Modal.confirm({25                content: button.confirm,26                onOk: () => _runFn(reference, item)27            })28        } else {29            // ç´æ¥æ§è¡30            _runFn(reference, item);31        }32    }33}34const rxClick = (reference, item) => (event) => {35    Ux.prevent(event);36    _runExecute(reference, item);37};38const rxMenu = (reference) => (menuitem) => {39    const {data = {}} = menuitem.item.props;40    _runExecute(reference, data);41}42export default {43    rxClick,44    rxMenu...Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  await page._runFn(async (page) => {7    await page.evaluate(() => {8      document.querySelector('text=Get started').scrollIntoViewIfNeeded();9    });10  });11  await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15  const browser = await chromium.launch();16  const context = await browser.newContext();17  const page = await context.newPage();18  await page._runFn(async (page) => {19    await page.evaluate(() => {20      document.querySelector('text=Get started').scrollIntoViewIfNeeded();21    });22  });23  await browser.close();24})();Using AI Code Generation
1const { _runFn } = require('playwright');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  const title = await _runFn(page, (page) => page.title());7  console.log(title);8  await browser.close();9})();10const { _runFn } = require('playwright');11const { chromium } = require('playwright');12(async () => {13  const browser = await chromium.launch();14  const page = await browser.newPage();15  const title = await _runFn(page, (page) => page.title());16  console.log(title);17  await browser.close();18})();19const { _runFn } = require('playwright');20const { chromium } = require('playwright');21(async () => {22  const browser = await chromium.launch();23  const page = await browser.newPage();24  const title = await _runFn(page, (page) => page.title());25  console.log(title);26  await browser.close();27})();28const { _runFn } = require('playwright');29const { chromium } = require('playwright');30(async () => {31  const browser = await chromium.launch();32  const page = await browser.newPage();33  const title = await _runFn(page, (page) => page.title());34  console.log(title);35  await browser.close();36})();37const { _runFn } = require('playwright');38const { chromium } = require('playwright');39(async () => {40  const browser = await chromium.launch();41  const page = await browser.newPage();42  const title = await _runFn(page, (page) => page.title());43  console.log(title);44  await browser.close();45})();Using AI Code Generation
1const { chromium } = require('playwright');2const { _runFn } = require('playwright/lib/server/frames');3(async () => {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  const userAgent = await _runFn(page, frame => frame._userAgent);7  console.log(userAgent);8  await browser.close();9})();Using AI Code Generation
1const { _runFn } = require('playwright');2const { chromium } = require('playwright');3async function main() {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  await _runFn(page, async (page) => {7    await page.click('text=About');8  });9  await browser.close();10}11main();Using AI Code Generation
1const {chromium} = require('playwright');2const {Internal} = require('playwright/lib/server/server');3const {BrowserServer} = require('playwright/lib/server/browserServer');4const {BrowserContext} = require('playwright/lib/server/browserContext');5const {Page} = require('playwright/lib/server/page');6const {ElementHandle} = require('playwright/lib/server/dom');7const {JSHandle} = require('playwright/lib/server/injected/injectedScript');8const internal = new Internal();9const browserContext = new BrowserContext(internal, browserServer, {viewport: {width: 800, height: 600}});10const page = new Page(internal, browserContext, 'page1');11const elementHandle = new ElementHandle(internal, page, 'element1', 'element1', 'element1', [], [], []);12const jsHandle = new JSHandle(internal, page, 'jsHandle1', 'jsHandle1', 'jsHandle1', [], [], []);13let fn = function () {14    console.log('Hello World');15    return 'Hello World';16};17let fnWithArgs = function (a, b) {18    console.log(a, b);19    return a + b;20};21internal._runFn(fn, 'test.js', []);22internal._runFn(fnWithArgs, 'test.js', [1, 2]);23internal._runFn(fn, 'test.js', [], elementHandle);24internal._runFn(fn, 'test.js', [], jsHandle);25internal._runFn(fn, 'test.js', [], elementHandle, jsHandle);26const {chromium} = require('playwright');27const {Internal} = require('playwright/lib/server/server');28const {BrowserServer} = require('playwright/lib/server/browserUsing AI Code Generation
1const { Internal } = require('playwright');2const internal = new Internal();3const runFn = internal._runFn;4const browser = await runFn('launch');5const context = await runFn('newContext', browser);6const page = await runFn('newPage', context);7const title = await runFn('title', page);8console.log(title);9await runFn('close', browser);Using AI Code Generation
1const { _runFn } = require('@playwright/test/lib/test');2const { runFn } = require('@playwright/test/lib/test');3const runFn = () => {4    console.log('runFn method of Playwright Internal class');5};6await _runFn(runFn);7await runFn();8const { _runFn } = require('@playwright/test/lib/test');9const { runFn } = require('@playwright/test/lib/test');10const runFn = () => {11    console.log('runFn method of Playwright Internal class');12};13await _runFn(runFn);14await runFn();15const { _runFn } = require('@playwright/test/lib/test');16const { runFn } = require('@playwright/test/lib/test');17const runFn = () => {18    console.log('runFn method of Playwright Internal class');19};20await _runFn(runFn);21await runFn();22const { _runFn } = require('@playwright/test/lib/test');23const { runFn } = require('@playwright/test/lib/test');24const runFn = () => {25    console.log('runFn method of Playwright Internal class');26};27await _runFn(runFn);28await runFn();Using AI Code Generation
1const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');2const api = new InternalAPI();3api._runFn(async () => {4});5const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');6const api = new InternalAPI();7api._runFn(async () => {8});9const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');10const api = new InternalAPI();11api._runFn(async () => {12});13const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');14const api = new InternalAPI();15api._runFn(async () => {16});17const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');18const api = new InternalAPI();19api._runFn(async () => {20});21const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');22const api = new InternalAPI();23api._runFn(async () => {24});25const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');26const api = new InternalAPI();27api._runFn(async () => {28});29const { InternalAPI } = require('playwright/lib/server/inspector/inspector.js');30const api = new InternalAPI();31api._runFn(async () => {32});LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
