Best JavaScript code snippet using cypress
server.js
Source:server.js
1/*-------------------------------------------------------------------------------------------------------------------*\2| Copyright (C) 2017 PayPal |3| |4| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance |5| with the License. |6| |7| You may obtain a copy of the License at |8| |9| http://www.apache.org/licenses/LICENSE-2.0 |10| |11| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed |12| on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for |13| the specific language governing permissions and limitations under the License. |14\*-------------------------------------------------------------------------------------------------------------------*/15'use strict';16var isString = require('lodash/isString');17var assign = require('lodash/assign');18var unset = require('lodash/unset');19var path = require('path');20var util = require('./util');21var assert = require('assert');22var Config = require('./config.json');23var jsesc = require('jsesc');24var ReactDOMServer = require('react-dom/server');25var debug = require('debug')(require('../package').name);26var ReactRouterServerErrors = require('./reactRouterServerErrors');27var format = require('util').format;28var Performance = require('./performance');29// safely require the peer-dependencies30var React = util.safeRequire('react');31function generateReactRouterServerError(type, existingErrorObj, additionalProperties) {32 var err = existingErrorObj || new Error('react router match fn error');33 err._type = type;34 if (additionalProperties) {35 assign(err, additionalProperties);36 }37 return err;38}39exports.create = function create(createOptions) {40 createOptions = createOptions || {};41 // safely require the peer-dependencies42 var React = util.safeRequire('react');43 var Router;44 var match;45 var RouterContext;46 try {47 Router = require('react-router');48 match = Router.match;49 // compatibility for both `react-router` v2 and v150 RouterContext = Router.RouterContext || Router.RoutingContext;51 } catch (err) {52 if (!Router && createOptions.routes) {53 throw err;54 }55 }56 createOptions.scriptType = isString(createOptions.scriptType) ? createOptions.scriptType : Config.scriptType;57 createOptions.docType = isString(createOptions.docType) ? createOptions.docType : Config.docType;58 createOptions.renderOptionsKeysToFilter = createOptions.renderOptionsKeysToFilter || [];59 createOptions.staticMarkup = createOptions.staticMarkup !== undefined ? createOptions.staticMarkup : Config.staticMarkup;60 assert(Array.isArray(createOptions.renderOptionsKeysToFilter),61 '`renderOptionsKeysToFilter` - should be an array');62 createOptions.renderOptionsKeysToFilter =63 createOptions.renderOptionsKeysToFilter.concat(Config.defaultKeysToFilter);64 if (createOptions.performanceCollector) {65 assert.equal(typeof createOptions.performanceCollector,66 'function',67 '`performanceCollector` - should be a function');68 }69 // the render implementation70 return function render(thing, options, callback) {71 var perfInstance;72 if (createOptions.performanceCollector) {73 perfInstance = Performance(thing);74 }75 function done(err, html) {76 if (!options.settings['view cache']) {77 // remove all the files under the express's view folder from require cache.78 // Helps in making changes to react views without restarting the server.79 util.clearRequireCache(createOptions.routesFilePath);80 util.clearRequireCacheInDir(options.settings.views, options.settings['view engine']);81 }82 if (createOptions.performanceCollector) {83 createOptions.performanceCollector(perfInstance());84 }85 callback(err, html);86 }87 function renderAndDecorate(component, data, html) {88 if (createOptions.staticMarkup) {89 // render the component to static markup90 html += ReactDOMServer.renderToStaticMarkup(component);91 } else {92 // render the redux wrapped component93 if (createOptions.reduxStoreInitiator) {94 // add redux provider95 var Provider = require('react-redux').Provider;96 var initStore;97 try {98 initStore = require(createOptions.reduxStoreInitiator);99 if (initStore.default) {100 initStore = initStore.default;101 }102 var store = initStore(data);103 var wrappedComponent = React.createElement(Provider, { store: store }, component);104 // render the component105 html += ReactDOMServer.renderToString(wrappedComponent);106 } catch (err) {107 return done(err);108 }109 } else {110 // render the component111 html += ReactDOMServer.renderToString(component);112 }113 // the `script` tag that gets injected into the server rendered pages.114 // https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_JavaScript_Data_Values115 var openScriptTag = `<script id="${Config.client.markupId}" type="${createOptions.scriptType}" ${options.nonce ? `nonce="${options.nonce}"` : ''}>`;116 // Escape data for injecting into <script> tag117 // https://mathiasbynens.be/notes/etago118 var script = openScriptTag + jsesc(data, {119 'escapeEtago': true, // old option for escaping in <script> or <style> context120 'isScriptContext': true, // soon to be new option121 'compact': true, // minifies122 'json': true // ensures JSON compatibility123 })124 + '</script>';125 if (createOptions.docType === '') {126 // if the `docType` is empty, the user did not want to add a docType to the rendered component,127 // which means they might not be rendering a full page with `html` and `body` tags128 // so attach the script tag to just the end of the generated html string129 html += script;130 }131 else {132 var htmlTag = createOptions.scriptLocation === 'head' ? '</head>' : '</body>';133 html = html.replace(htmlTag, script + htmlTag);134 }135 }136 return html;137 }138 if (createOptions.routes && createOptions.routesFilePath) {139 // if `routesFilePath` property is provided, then in140 // cases where 'view cache' is false, the routes are reloaded for every render.141 createOptions.routes = require(createOptions.routesFilePath);142 if (createOptions.routes.default) {143 createOptions.routes = createOptions.routes.default;144 }145 }146 // initialize the markup string147 var html = createOptions.docType;148 // create the data object that will be fed into the React render method.149 // Data is a mash of the express' `render options` and `res.locals`150 // and meta info about `react-engine`151 var data = assign({152 __meta: {153 // get just the relative path for view file name154 view: null,155 markupId: Config.client.markupId156 }157 }, options);158 if (this.useRouter && !createOptions.routes) {159 return done(new Error('asking to use react router for rendering, but no routes are provided'));160 }161 // since `unset` mutates the obj, lets clone a copy162 // Also, we are using JSON.parse(JSON.stringify(data)) to clone the object super fast.163 // a valid assumption in using this method of cloning at this point: we have only variables164 // and not any functions in data object - so need for lodash cloneDeep165 try {166 data = JSON.parse(JSON.stringify(data));167 createOptions.renderOptionsKeysToFilter.forEach(function(key) {168 unset(data, key);169 });170 } catch (parseErr) {171 return done(parseErr);172 }173 try {174 if (this.useRouter) {175 return match({ routes:createOptions.routes, location:thing}, function reactRouterMatchHandler(error, redirectLocation, renderProps) {176 if (error) {177 debug('server.js match 500 %s', error.message);178 var err = generateReactRouterServerError(ReactRouterServerErrors.MATCH_INTERNAL_ERROR, error);179 return done(err);180 } else if (redirectLocation) {181 debug('server.js match 302 %s', redirectLocation.pathname + redirectLocation.search);182 var err = generateReactRouterServerError(ReactRouterServerErrors.MATCH_REDIRECT, null, {183 redirectLocation: redirectLocation.pathname + redirectLocation.search184 });185 return done(err);186 } else if (renderProps) {187 renderProps.createElement = function(Component, routerProps) {188 // Other than fusing the data object with the routerProps, there is no way189 // to pass data into the routing context of react-router during a server render.190 // since we are going to use `assign` to fuse the routerProps and the actual191 // data object, we need to make sure that there are no properties between the two object192 // with the same name at the root level. (Having two properties with the same name breaks assign.)193 // Info on why we need to fuse the two objects?194 // --------------------------------------------195 // * https://github.com/ngduc/react-setup/issues/10196 // * https://github.com/reactjs/react-router/issues/1969197 // * http://stackoverflow.com/questions/36137901/react-route-and-server-side-rendering-how-to-render-components-with-data198 if (options.settings.env !== 'production') {199 var intersection = Object.keys(routerProps).filter(function(elem) {200 return Object.keys(data).indexOf(elem) !== -1;201 });202 if (intersection.length) {203 var errMsg = 'Your data object cannot have property(ies) named: "' +204 intersection +205 '"\n Blacklisted property names that cannot be used: "' +206 Object.keys(routerProps) +207 '"\n'208 throw new Error(errMsg);209 }210 }211 // define a createElement strategy for react-router that transfers data props to all route "components"212 // for any component created by react-router, fuse data object with the routerProps213 // NOTE: This may be imposing too large of an opinion?214 return React.createElement(Component, assign({}, data, routerProps));215 };216 return done(null, renderAndDecorate(React.createElement(RouterContext, renderProps), data, html));217 } else {218 debug('server.js match 404');219 var err = generateReactRouterServerError(ReactRouterServerErrors.MATCH_NOT_FOUND);220 return done(err);221 }222 });223 }224 else {225 // path utility to make path string compatible in different OS226 // ------------------------------------------------------------227 // use `path.normalize()` to normalzie absolute view file path and absolute base directory path228 // to prevent path strings like `/folder1/folder2/../../folder3/exampleFile`229 // then, derive relative view file path230 // and replace backslash with slash to be compatible on Windows231 data.__meta.view = path.normalize(thing)232 .replace(path.normalize(options.settings.views), '').substring(1)233 .replace('\\', '/');234 var view = require(thing);235 // Check for an ES6 `default` property on the module export236 // ------------------------------------------------------------237 // TypeScript and Babel users that leverage ES6 module depend on this238 // e.g. `export default function MyView() {};`239 if (view.default) {240 view = view.default;241 }242 // create the Component using react's createFactory243 var component = React.createFactory(view);244 return done(null, renderAndDecorate(component(data), data, html));245 }246 }247 catch (err) {248 // on error, pass to the next249 // middleware in the chain!250 return done(err);251 }252 };...
miscs.js
Source:miscs.js
1var utils = require('../lib/utils');2var extend = utils.extend;3var Misc = function(config) {4 this.config = config;5};6/**7 * Get Activity Log - http://docs.whmcs.com/API:Get_Activity_Log8 * @param [opts] Object9 * @param [opts.limitstart] - Which User ID to start at (defaults to 0)10 * @param [opts.limitnum] - Limit by number (defaults to 25)11 * @param callback12 */13Misc.prototype.getActivityLog = function ( opts, callback) {14 var options = {15 action: 'getactivitylog'16 };17 if(typeof opts === 'function'){18 callback = opts;19 } else {20 options = extend(options,opts);21 }22 var createOptions = {23 client: this,24 body: options25 };26 utils.modem(createOptions, callback);27};28/**29 * Get Admin Details - http://docs.whmcs.com/API:Get_Admin_Details30 * @param callback31 */32Misc.prototype.getAdminDetails = function ( opts, callback) {33 var options = {34 action: 'getadmindetails'35 };36 if(typeof opts === 'function'){37 callback = opts;38 } else {39 options = extend(options,opts);40 }41 var createOptions = {42 client: this,43 body: options44 };45 utils.modem(createOptions, callback);46};47/**48 * Update Admin Notes - http://docs.whmcs.com/API:Update_Admin_Notes49 * @param callback50 */51Misc.prototype.updateAdminNotes = function ( notes, callback) {52 var options = {53 action: 'updateadminnotes',54 notes: notes55 };56 var createOptions = {57 client: this,58 body: options59 };60 utils.modem(createOptions, callback);61};62/**63 * Get Currencies - http://docs.whmcs.com/API:Get_Currencies64 * @param callback65 */66Misc.prototype.getCurrencies = function (callback) {67 var options = {68 action: 'getcurrencies'69 };70 var createOptions = {71 client: this,72 body: options73 };74 utils.modem(createOptions, callback);75};76/**77 * Get Promotions - http://docs.whmcs.com/API:Get_Promotions78 * @param [opts] Object79 * @param [opts.code] - the specific promotion code to return information for80 * @param callback81 */82Misc.prototype.getPromotions = function (callback) {83 var options = {84 action: 'getpromotions'85 };86 var createOptions = {87 client: this,88 body: options89 };90 utils.modem(createOptions, callback);91};92/**93 * Get Client Groups - http://docs.whmcs.com/API:Get_Client_Groups94 * @param callback95 */96Misc.prototype.getClientGroups = function (callback) {97 var options = {98 action: 'getclientgroups'99 };100 var createOptions = {101 client: this,102 body: options103 };104 utils.modem(createOptions, callback);105};106/**107 * Get Email Templates - http://docs.whmcs.com/API:Get_Email_Templates108 * @param [opts] Objects109 * @param [opts.type] - from product,domain,support,general,invoice,affiliate,admin110 * @param [opts.language] - only required for additional languages111 * @param callback112 */113Misc.prototype.getEmailTemplates = function (callback) {114 var options = {115 action: 'getemailtemplates'116 };117 var createOptions = {118 client: this,119 body: options120 };121 utils.modem(createOptions, callback);122};123/**124 * Get Todo Items - http://docs.whmcs.com/API:Get_To-Do_Items125 * @param [opts] Object126 * @param [opts.status] - from New,Pending,In Progress,Completed,Postponed127 * @param [opts.limitstart] - where to start the output. Used for pagination. (default = 0)128 * @param [opts.limitnum] - limit the number of records returned (default = 25)]129 * @param callback130 */131Misc.prototype.getTodoItems = function (callback) {132 var options = {133 action: 'gettodoitems'134 };135 var createOptions = {136 client: this,137 body: options138 };139 utils.modem(createOptions, callback);140};141/**142 * Get Todo Items Statuses - http://docs.whmcs.com/API:Get_To-Do_Items_Statuses143 * @param callback144 */145Misc.prototype.getTodoItemsStatuses = function (callback) {146 var options = {147 action: 'gettodoitemstatuses'148 };149 var createOptions = {150 client: this,151 body: options152 };153 utils.modem(createOptions, callback);154};155/**156 * Update Todo Item - http://docs.whmcs.com/API:Update_To-Do_Item157 * @param itemid - ID of the ToDo in WHMCS to update158 * @param adminid - Admin ID to update the To Do item to159 * @param [opts] Object160 * @param [opts.date] - open date of the To Do YYYYMMDD161 * @param [opts.title] - Title of the to do162 * @param [opts.description] - Text of the To Do163 * @param [opts.status] - Status - New, Pending, In Progress, Completed, Postponed164 * @param [opts.duedate] - due date of the To Do YYYYMMDD165 * @param callback166 */167Misc.prototype.updateTodoItem = function (itemid, adminid, opts, callback) {168 var options = {169 action: 'updatetodoitem',170 itemid: itemid,171 adminid: adminid172 };173 if(typeof opts === 'function'){174 callback = opts;175 } else {176 options = extend(options,opts);177 }178 var createOptions = {179 client: this,180 body: options181 };182 utils.modem(createOptions, callback);183};184/**185 * Get Staff Online - http://docs.whmcs.com/API:Get_Staff_Online186 * @param callback187 */188Misc.prototype.getStaffOnline = function (callback) {189 var options = {190 action: 'getstaffonline'191 };192 var createOptions = {193 client: this,194 body: options195 };196 utils.modem(createOptions, callback);197};198/**199 * Get Stats - http://docs.whmcs.com/API:Get_Stats200 * @param callback201 */202Misc.prototype.getStats = function (callback) {203 var options = {204 action: 'getstats'205 };206 var createOptions = {207 client: this,208 body: options209 };210 utils.modem(createOptions, callback);211};212/**213 * Encrypt Password - http://docs.whmcs.com/API:Encrypt_Password214 * @param password2 - should contain the string you want encrypting215 * @param callback216 */217Misc.prototype.encryptPassword = function (password2, callback) {218 var options = {219 action: 'encryptpassword',220 password2: password2221 };222 var createOptions = {223 client: this,224 body: options225 };226 utils.modem(createOptions, callback);227};228/**229 * Decrypt Password - http://docs.whmcs.com/API:Decrypt_Password230 * @param password2 - should contain the string you want encrypting231 * @param callback232 */233Misc.prototype.decryptPassword = function (password2, callback) {234 var options = {235 action: 'decryptpassword',236 password2: password2237 };238 var createOptions = {239 client: this,240 body: options241 };242 utils.modem(createOptions, callback);243};244/**245 * Add Banned IP - http://docs.whmcs.com/API:Add_Banned_IP246 * @param ip - IP address to ban247 * @param [opts] Object248 * @param [opts.reason] - reason for ban249 * @param [opts.days] - number of days to ban for. If not submitted defaults to 7 (not required)250 * @param [opts.expires] - in YYYY-MM-DD HH:II:SS format eg: 2011-06-06 01:12:34 (optional in place of "days")251 * @param callback252 */253Misc.prototype.addBannedIP = function (ip, opts, callback) {254 var options = {255 action: 'addbannedip',256 ip: ip257 };258 if(typeof opts === 'function'){259 callback = opts;260 } else {261 options = extend(options,opts);262 }263 var createOptions = {264 client: this,265 body: options266 };267 utils.modem(createOptions, callback);268};269/**270 * Add Banned IP - http://docs.whmcs.com/API:Add_Banned_IP271 * @param type - one of hostingaccount, reselleraccount, server or other272 * @param gid - the product group ID to add it to273 * @param name - the product name274 * @param paytype - free, onetime or recurring275 * @param [opts] Object276 * @param [opts.description] - the product description277 * @param [opts.hidden] - set true to hide278 * @param [opts.showdomainoptions] - set true to show279 * @param [opts.welcomeemail] - the email template ID for a welcome email280 * @param [opts.qty] - set quantity to enable stock control281 * @param [opts.proratadate]282 * @param [opts.proratachargenextmonth]283 * @param [opts.autosetup] - on, payment, order or blank for none284 * @param [opts.module] - module name285 * @param [opts.servergroupid] - server group ID286 * @param [opts.subdomain] - subdomain to offer with product287 * @param [opts.tax] - set true to apply tax288 * @param [opts.order] - display sort order to override default289 * @param [opts.configoption1]290 * @param [opts.configoption2]291 * @param [opts.etc...]292 * @param [opts.pricing] - an array of pricing in the format pricing[currencyid][cycle] (example below)293 * @param callback294 */295Misc.prototype.addProduct = function (opts, callback) {296 var options = {297 action: 'addproduct'298 };299 if(typeof opts === 'function'){300 callback = opts;301 } else {302 options = extend(options,opts);303 }304 var createOptions = {305 client: this,306 body: options307 };308 utils.modem(createOptions, callback);309};310/**311 * Log Activity - http://docs.whmcs.com/API:Log_Activity312 * @param description - Text to add to the log313 * @param [opts] Object314 * @param [opts.userid] - UserID to assign the log to in order to appear in Client Log315 * @param callback316 */317Misc.prototype.logActivity = function (description, opts, callback) {318 var options = {319 action: 'logactivity',320 description: description321 };322 if(typeof opts === 'function'){323 callback = opts;324 } else {325 options = extend(options,opts);326 }327 var createOptions = {328 client: this,329 body: options330 };331 utils.modem(createOptions, callback);332};333/**334 * Send Admin Email - http://docs.whmcs.com/API:Send_Admin_Email335 * @param messagename - Name of the Admin email template to send336 * @param mergefields - array of merge fields to populate the template being sent337 * @param type - Who to send the email to. One of system, account or support. Default: system338 * @param [opts] Object339 * @param [opts.customsubject] - Subject for a custommessage being sent340 * @param [opts.custommessage] - Send a custom email to admin users, this will override 'messagename'341 * @param [opts.deptid - If type] = support, the users of a department to send email to342 * @param callback343 */344Misc.prototype.sendAdminEmail = function (messagename, mergefields, type, opts, callback) {345 var options = {346 action: 'sendadminemail',347 messagename: messagename,348 mergefields: mergefields,349 type: type350 };351 if(typeof opts === 'function'){352 callback = opts;353 } else {354 options = extend(options,opts);355 }356 var createOptions = {357 client: this,358 body: options359 };360 utils.modem(createOptions, callback);361};...
domains.js
Source:domains.js
1var utils = require('../lib/utils');2var extend = utils.extend;3var Domains = function(config) {4 this.config = config;5};6/**7 * Register domain - http://docs.whmcs.com/API:Register_Domain8 * @param domainid - Domain ID from WHMCS9 * @param domain - The domain name(send domain id * or * domain)10 * @param callback11 */12Domains.prototype.registerDomain = function(domainid, callback)13{14 var options = {15 action: 'domainregister'16 };17 if(typeof domainid === 'number' || domainid.indexOf('@') === -1)18 options.domainid = domainid;19 else20 options.domain = domainid;21 var createOptions = {22 client : this,23 body : options24 };25 utils.modem(createOptions, callback);26}27/**28 * Renew domain - http://docs.whmcs.com/API:Renew_Domain29 * @param domainid - Domain ID from WHMCS30 * @param domain - The domain name(send domain id * or * domain)31 * @param callback32 */33Domains.prototype.renewDomain = function(domainid, callback)34{35 var options = {36 action: 'domainrenew'37 };38 if(typeof domainid === 'number' || domainid.indexOf('@') === -1)39 options.domainid = domainid;40 else41 options.domain = domainid;42 var createOptions = {43 client : this,44 body : options45 };46 utils.modem(createOptions, callback);47}48/**49 * Transfer domain - http://docs.whmcs.com/API:Transfer_Domain50 * @param domainid - Domain ID from WHMCS51 * @param domain - The domain name(send domain id * or * domain)52 * @param [options] Object53 * @param [options.eppcode] String - The EPP code for the transfer54 * @param callback55 */56Domains.prototype.transferDomain = function(domainid, opts, callback)57{58 var options = {59 action: 'domaintransfer'60 };61 if(typeof domainid === 'number' || domainid.indexOf('@') === -1)62 options.domainid = domainid;63 else64 options.domain = domainid;65 if ( typeof opts === 'function') {66 callback = opts;67 } else {68 options = extend(options, opts);69 }70 var createOptions = {71 client : this,72 body : options73 };74 utils.modem(createOptions, callback);75}76/**77 * Release domain - http://docs.whmcs.com/API:Release_Domain78 * @param domainid - Domain ID from WHMCS79 * @param domain - The domain name(send domain id * or * domain)80 * @param newtag - The new tag for the domain81 * @param callback82 */83Domains.prototype.releaseDomain = function(domainid, newtag, callback)84{85 var options = {86 action: 'domainrelease',87 newtag: newtag88 };89 if(typeof domainid === 'number' || domainid.indexOf('@') === -1)90 options.domainid = domainid;91 else92 options.domain = domainid;93 var createOptions = {94 client : this,95 body : options96 };97 utils.modem(createOptions, callback);98}99/**100 * Get domain lock status - http://docs.whmcs.com/API:Domain_Locking_Status101 * @param domainid String|Number102 * @param callback103 */104Domains.prototype.domainGetLockingStatus = function (domainid, callback) {105 var options = {106 action: 'domaingetlockingstatus',107 domainid: domainid108 };109 var createOptions = {110 client: this,111 body: options112 };113 utils.modem(createOptions, callback);114};115/**116 * Get domain nameservers - http://docs.whmcs.com/API:Domain_Nameservers117 * @param domainid String|Number118 * @param callback119 */120Domains.prototype.domainGetNameservers = function (domainid, callback) {121 var options = {122 action: 'domaingetnameservers',123 domainid: domainid124 };125 var createOptions = {126 client: this,127 body: options128 };129 utils.modem(createOptions, callback);130};131/**132 * Get domain WHOIS Info - http://docs.whmcs.com/API:Get_Domain_WHOIS133 * @param domainid String|Number134 * @param callback135 */136Domains.prototype.domainGetWHOISInfo = function (domainid, callback) {137 var options = {138 action: 'domaingetwhoisinfo',139 domainid: domainid140 };141 var createOptions = {142 client: this,143 body: options144 };145 utils.modem(createOptions, callback);146};147/**148 * Get domain request EPP - http://docs.whmcs.com/API:Domain_EPP149 * @param domainid String|Number150 * @param callback151 */152Domains.prototype.domainRequestEPP = function (domainid, callback) {153 var options = {154 action: 'domainrequestepp',155 domainid: domainid156 };157 var createOptions = {158 client: this,159 body: options160 };161 utils.modem(createOptions, callback);162};163/**164 * Get domain toggle ID Protect - http://docs.whmcs.com/API:Toggle_ID_Protect165 * @param domainid String|Number166 * @param callback167 */168Domains.prototype.domainToggleIDProtect = function (domainid, idprotect, callback) {169 var options = {170 action: 'domaintoggleidprotect',171 domainid: domainid,172 idprotect: idprotect173 };174 var createOptions = {175 client: this,176 body: options177 };178 utils.modem(createOptions, callback);179};180/**181 * Domain Update Lock - http://docs.whmcs.com/API:Domain_Update_Lock182 * @param domainid String|Number183 * @param [options] Object184 * @param [options.lockstatus] - set 1 to lock the domain185 * @param callback186 */187Domains.prototype.domainUpdateLockingStatus = function (domainid, status, callback) {188 189 if(typeof status === 'function'){190 callback = status;191 status = 0;192 }193 var options = {194 action: 'domainupdatelockingstatus',195 domainid: domainid,196 lockstatus: status197 };198 var createOptions = {199 client: this,200 body: options201 };202 utils.modem(createOptions, callback);203};204/**205 * Update Domain Nameservers - http://docs.whmcs.com/API:Domain_Update_Nameservers206 * @param domainid String|Number207 * @param nameservers Object|Array Pass in an object with ns* properties, or an array of nameservers208 * @param nameservers.ns1 String209 * @param nameservers.ns2 String210 * @param [nameservers.ns3] String211 * @param [nameservers.ns4] String212 * @param [nameservers.ns5] String213 * @param callback214 */215Domains.prototype.domainUpdateNameservers = function (domainid, nameservers, callback) {216 217 var options = {218 action: 'domainupdatenameservers'219 };220 if(typeof domainid === 'number' || domainid.indexOf('@') === -1)221 options.domainid = domainid;222 else223 options.domain = domainid;224 if(Array.isArray(nameservers)){225 var len = nameservers.length;226 for(var i = 0; i < len; i++){227 options['ns' + (i + 1)] = nameservers[i];228 }229 } else if(typeof nameservers === 'object') {230 options = extend(options,nameservers);231 }232 var createOptions = {233 client: this,234 body: options235 };236 utils.modem(createOptions, callback);237};238/**239 * Domain Update WHOIS - http://docs.whmcs.com/API:Domain_Update_WHOIS240 * @param domainid String|Number241 * @param xml - xml of the details to update Get WHOIS242 * @param callback243 */244Domains.prototype.domainUpdateWHOISInfo = function (domainid, xml, callback) {245 246 var options = {247 action: 'domainupdatewhoisinfo',248 domainid: domainid,249 xml: xml250 };251 var createOptions = {252 client: this,253 body: options254 };255 utils.modem(createOptions, callback);256};257/**258 * Domain WHOIS - http://docs.whmcs.com/API:Domain_WHOIS259 * @param domain String260 * @param callback261 */262Domains.prototype.domainWHOIS = function (domain, callback) {263 264 var options = {265 action: 'domainwhois',266 domain: domain267 };268 var createOptions = {269 client: this,270 body: options271 };272 utils.modem(createOptions, callback);273};...
index.js
Source:index.js
1#!/usr/bin/env node2const chalk = require("chalk");3const readline = require("readline");4const os = require("os");5const path = require("path");6const fs = require("fs-extra");7const packageDependencies = require("../template/package/dependence.json");8const packageJson = require("../template/package/package.json");9const { exec } = require("child_process");10const webpackTemplate = require("../template/webpack/webpack.config");11const rl = readline.createInterface({12 input: process.stdin,13 output: process.stdout14});15/**16 * å®è£
é
ç½®17 */18const createOptions = {19 rootDir: '', // ç¨åºç®å½20 workDir: '', // å·¥ä½ç®å½21 name: '',22 cssLoader: "sass",23 packageFile: {},24 typescript: false,25};26const greeting = chalk.white.bold("Welcome to apusic app create application!");27const info = chalk.greenBright.bold(`Working dir is ${process.cwd()}`);28console.log(greeting);29console.log(info);30start();31async function start() {32 initEnvironment();33 await setCss();34 setDependencies();35 createWebpackConfig();36 copyFiles();37 exec(`cd ${createOptions.workDir} && git init`, (err, stdout, stderr) => {38 if (err) {39 console.log(chalk.red("git init failed"));40 return;41 }42 console.log(chalk.greenBright.bold("Success, please run npm or yarn install in your project."));43 });44}45function initEnvironment() {46 if (process.argv.length < 3 || !process.argv[2]) {47 console.log(chalk.red("please input project name"));48 process.exit(-1);49 }50 packageJson.name = createOptions.name = process.argv[2];51 createOptions.rootDir = path.resolve(__dirname, '../');52 createOptions.workDir = path.resolve(process.cwd(), createOptions.name);53 //check typescript54 if(process.argv.includes("--typescript")){55 createOptions.typescript = true;56 }57 if (fs.existsSync(createOptions.workDir)) {58 console.log(chalk.red("project directory is already exist!"));59 process.exit(-1);60 }61}62/**63 * cssç¼è¯å¨éæ©64 */65async function setCss() {66 // check css loaders67 const cssLoaders = ["less", "sass"];68 const cssText = cssLoaders.join(",");69 const inputCssCompileText = chalk.white.bold(`please input css loader(default sass): (${cssText}) ${os.EOL}`);70 return await new Promise(resolve => {71 rl.question(inputCssCompileText, answer => {72 if(answer === '') {73 createOptions.cssLoader = 'sass';74 }else if (cssLoaders.includes(answer)) {75 createOptions.cssLoader = answer;76 } else {77 const invalid = chalk.red("invalid css compile!");78 console.error(invalid);79 rl.close();80 process.exit(-1);81 }82 rl.close();83 resolve(answer);84 })85 });86}87/**88 * 设置ä¾èµ89 */90function setDependencies() {91 let merge = {92 dependencies: packageDependencies.dependencies,93 devDependencies: {}94 };95 if (createOptions.cssLoader === 'sass') {96 merge.devDependencies = Object.assign({}, packageDependencies.devDependencies, packageDependencies.sass);97 }98 if (createOptions.cssLoader === 'less') {99 merge.devDependencies = Object.assign({}, packageDependencies.devDependencies, packageDependencies.less);100 }101 if (createOptions.typescript) {102 merge.devDependencies = Object.assign({}, packageDependencies.devDependencies, packageDependencies.ts);103 }104 createOptions.packageFile = Object.assign(packageJson, merge);105 // after check css then we create dir106 fs.mkdirSync(createOptions.workDir, {recursive: true});107 const packageFile = path.resolve(createOptions.workDir, 'package.json');108 let writer = fs.createWriteStream(packageFile);109 writer.write(JSON.stringify(createOptions.packageFile, null, 2));110 writer.close();111}112function createWebpackConfig(){113 let template = webpackTemplate.template;114 const outputFile = path.resolve(createOptions.workDir, 'webpack.config.js');115 if(createOptions.cssLoader === 'less'){116 template = template.replace(/sass-loader/g, "less-loader");117 template = template.replace(/scss/g, "less");118 }119 if(createOptions.typescript){120 template = template.replace(/index.jsx/g, "index.tsx");121 }122 // copy sass webpack.config.js123 let writer = fs.createWriteStream(outputFile);124 writer.write(template);125 writer.close();126}127/**128 * æ·è´å
³é®æ¨¡æ¿129 */130function copyFiles(){131 const src = {132 tsConfig: path.resolve(createOptions.rootDir, 'template/tsconfig.json'),133 babelConfig: path.resolve(createOptions.rootDir, 'template/.babelrc'),134 typeConfig: path.resolve(createOptions.rootDir, 'template/declaration.d.ts'),135 publicDir: path.resolve(createOptions.rootDir, 'template/public'),136 eslintConfig: path.resolve(createOptions.rootDir, 'template/.eslintrc'),137 gitIgnoreConfig: path.resolve(createOptions.rootDir, 'template/gitignore.tpl'),138 };139 if(createOptions.typescript){140 src.sourceDir = path.resolve(createOptions.rootDir, 'template/ts')141 } else {142 src.sourceDir = path.resolve(createOptions.rootDir, 'template/js')143 }144 const des = {145 tsConfig: path.resolve(createOptions.workDir, 'tsconfig.json'),146 babelConfig: path.resolve(createOptions.workDir, '.babelrc'),147 typeConfig: path.resolve(createOptions.workDir, 'declaration.d.ts'),148 sourceDir: path.resolve(createOptions.workDir, 'src'),149 publicDir: path.resolve(createOptions.workDir, 'public'),150 eslintConfig: path.resolve(createOptions.workDir, '.eslintrc'),151 gitIgnoreConfig: path.resolve(createOptions.workDir, '.gitignore'),152 };153 if(createOptions.typescript){154 // copy tsconfig.json155 fs.copySync(src.tsConfig, des.tsConfig);156 //copy types file157 fs.copySync(src.typeConfig, des.typeConfig);158 }159 // copy git ignore160 fs.copySync(src.gitIgnoreConfig, des.gitIgnoreConfig);161 // copy babelrc162 fs.copySync(src.babelConfig, des.babelConfig);163 //copy eslint file164 fs.copySync(src.eslintConfig, des.eslintConfig);165 // copy source files166 if (!fs.existsSync(des.sourceDir)){167 fs.mkdirSync(des.sourceDir, {recursive: true});168 fs.copySync(src.sourceDir, des.sourceDir);169 }170 // copy public dir171 if (!fs.existsSync(des.publicDir)){172 fs.mkdirSync(des.publicDir, {recursive: true});173 fs.copySync(src.publicDir, des.publicDir);174 }...
Filter.js
Source:Filter.js
...86 <ul className="filter__body-row">87 <li className="filter__body-item">88 <label className="filter__label">ÐаÑегоÑиÑ</label>89 <ReactSelect90 defaultValue={createOptions(props.weightCat)[0]}91 styles={customStyles}92 options={createOptions(props.weightCat)}93 onChange={(event) => { console.log(event.value) }}94 />95 </li>96 <li className="filter__body-item">97 <label className="filter__label">СÑÑана</label>98 <ReactSelect99 defaultValue={createOptions(props.country)[0]}100 styles={customStyles}101 options={createOptions(props.country)}102 onChange={(event) => { console.log(event.value) }}103 />104 </li>105 <li className="filter__body-item">106 <label className="filter__label">ÐаÑка</label>107 <ReactSelect108 defaultValue={createOptions(props.brandCat)[0]}109 styles={customStyles}110 options={createOptions(props.brandCat)}111 onChange={(event) => { console.log(event.value) }}112 />113 </li>114 <li className="filter__body-item">115 <label className="filter__label">ÐоделÑ</label>116 <ReactSelect117 defaultValue={createOptions(props.model)[0]}118 styles={customStyles}119 options={createOptions(props.model)}120 onChange={(event) => { console.log(event.value) }}121 />122 </li>123 <li className="filter__body-item">124 <label className="filter__label">Ðод (наÑÐ¸Ð½Ð°Ñ Ñ)</label>125 <ReactSelect126 defaultValue={createOptions(props.year)[0]}127 styles={customStyles}128 options={createOptions(props.year)}129 onChange={(event) => { console.log(event.value) }}130 />131 </li>132 <li className="filter__body-item">133 <label className="filter__label">Ñена</label>134 <ReactSelect135 defaultValue={createOptions(props.price)[0]}136 styles={customStyles}137 options={createOptions(props.price)}138 onChange={(event) => { console.log(event.value) }}139 />140 </li>141 <li className="filter__body-item">142 <label className="filter__label">ÐÑобег</label>143 <ReactSelect144 defaultValue={createOptions(props.mileage)[0]}145 styles={customStyles}146 options={createOptions(props.mileage)}147 onChange={(event) => { console.log(event.value) }}148 />149 </li>150 <li className="filter__body-item">151 <label className="filter__label">ÐеÑ</label>152 <ReactSelect153 defaultValue={createOptions(props.weight)[0]}154 styles={customStyles}155 options={createOptions(props.weight)}156 onChange={(event) => { console.log(event.value) }}157 />158 </li>159 </ul>160 </div>161 <footer className="filter__footer footer-filter">162 <NavLink to="/search-result" className="link footer-filter__link">{`поиÑк ${props.cars.length - 1}(ÑезÑлÑÑаÑов)`}</NavLink>163 </footer>164 </article>165 <aside className="filter-day-offer filter-offer">166 <FilterCard card_description={true} />167 </aside>168 </div>169 </div>...
system.js
Source:system.js
...28 }29 });30 const request = (name, ...args) => adapter[name](vfs, vfs)(...args);31 test('#touch', () => {32 return expect(request('touch', 'home:/test', createOptions()))33 .resolves34 .toBe(true);35 });36 test('#stat', () => {37 const realPath = path.join(core.configuration.tempPath, 'jest/test');38 return expect(request('stat', 'home:/test', createOptions()))39 .resolves40 .toMatchObject({41 filename: 'test',42 path: realPath,43 size: 0,44 isFile: true,45 isDirectory: false,46 mime: 'application/octet-stream'47 });48 });49 test('#copy', () => {50 return expect(request('copy', 'home:/test', 'home:/test-copy', createOptions()))51 .resolves52 .toBe(true);53 });54 test('#rename', () => {55 return expect(request('rename', 'home:/test-copy', 'home:/test-rename', createOptions()))56 .resolves57 .toBe(true);58 });59 test('#mkdir', () => {60 return expect(request('mkdir', 'home:/test-directory', createOptions()))61 .resolves62 .toBe(true);63 });64 test('#mkdir - existing directory', () => {65 return expect(request('mkdir', 'home:/test-directory', createOptions()))66 .rejects67 .toThrowError();68 });69 test('#mkdir - ensure', () => {70 return expect(request('mkdir', 'home:/test-directory', createOptions({ensure: true})))71 .resolves72 .toBe(true);73 });74 test('#readfile', () => {75 return expect(request('readfile', 'home:/test', createOptions()))76 .resolves77 .toBeInstanceOf(stream.Readable);78 });79 test('#writefile', () => {80 const s = new stream.Readable();81 s._read = () => {};82 s.push('jest');83 s.push(null);84 return expect(request('writefile', 'home:/test', s, createOptions()))85 .resolves86 .toBe(true);87 });88 test('#exists - existing file', () => {89 return expect(request('exists', 'home:/test-rename', createOptions()))90 .resolves91 .toBe(true);92 });93 test('#exists - existing directory', () => {94 return expect(request('exists', 'home:/test-directory', createOptions()))95 .resolves96 .toBe(true);97 });98 test('#exists - non existing file', () => {99 return expect(request('exists', 'home:/test-copy', createOptions()))100 .resolves101 .toBe(false);102 });103 test('#search', () => {104 return expect(request('search', 'home:/', '*', createOptions()))105 .resolves106 .toEqual(107 expect.arrayContaining([108 expect.objectContaining({109 filename: 'test',110 isFile: true111 }),112 expect.objectContaining({113 filename: 'test-rename',114 isFile: true115 })116 ])117 );118 });119 test('#readdir', () => {120 return expect(request('readdir', 'home:/', createOptions()))121 .resolves122 .toEqual(123 expect.arrayContaining([124 expect.objectContaining({125 filename: 'test-directory',126 isDirectory: true127 }),128 expect.objectContaining({129 filename: 'test',130 isFile: true131 }),132 expect.objectContaining({133 filename: 'test-rename',134 isFile: true135 })136 ])137 );138 });139 test('#unlink', () => {140 const files = ['home:/test', 'home:/test-directory', 'home:/test-rename'];141 return Promise.all(files.map(f => {142 return expect(request('unlink', f, createOptions()))143 .resolves144 .toBe(true);145 }));146 });147 test('#unlink', () => {148 return expect(request('unlink', 'home:/test-directory', createOptions()))149 .resolves150 .toBe(true);151 });152 test('#realpath', () => {153 const realPath = path.join(core.configuration.tempPath, 'jest/test');154 return expect(request('realpath', 'home:/test', createOptions()))155 .resolves156 .toBe(realPath);157 });...
45544.user.js
Source:45544.user.js
...11var index=0;12131415function createOptions(obj,color,forecolor)16{ 17 18 var opt = document.createElement("OPTION");19 opt.value = color;20 opt.text = color;21 opt.style.color = forecolor;22 opt.style.backgroundColor = color;23 obj.options.add(opt,index); 24 index++;2526}2728var color1=document.createElement("select");29color1.setAttribute("type","SELECT");30color1.setAttribute("name","color1");3132createOptions(color1,"","");33createOptions(color1,"white","black");34createOptions(color1,"red","white");35createOptions(color1,"blue","white");36createOptions(color1,"green","white");37createOptions(color1,"gray","white");38createOptions(color1,"pink","black");39createOptions(color1,"yellow","black");40createOptions(color1,"orange","white");41createOptions(color1,"teal","white");42createOptions(color1,"brown","white");43createOptions(color1,"purple","white");44createOptions(color1,"black","white");454647484950var color2=document.createElement("select");51color2.setAttribute("type","SELECT");52color2.setAttribute("name","color2");53index=0;5455createOptions(color2,"","");56createOptions(color2,"white","black");57createOptions(color2,"red","white");58createOptions(color2,"blue","white");59createOptions(color2,"green","white");60createOptions(color2,"gray","white");61createOptions(color2,"pink","black");62createOptions(color2,"yellow","black");63createOptions(color2,"orange","white");64createOptions(color2,"teal","white");65createOptions(color2,"brown","white");66createOptions(color2,"purple","white");67createOptions(color2,"black","white");6869707172optbar.appendChild(document.createTextNode(" Color 1: "));73optbar.appendChild(color1);7475optbar.appendChild(document.createTextNode(" Color 2: "));76optbar.appendChild(color2);7778var forms=document.getElementsByName("gs");79 gform=forms[0];80 gform.addEventListener("submit",function(e){81 e.preventDefault();
...
options.js
Source:options.js
1 2import { createOptions } from "../../../createOptions";3 4const options = (things) => ({5 meistrija: createOptions(6 things.meistrija.sort((m1, m2) => m1.ind - m2.ind),7 "-- nenurodyta --",8 x => x.abbr + ", " + x.name9 ),10 kkateg: createOptions(11 things.kkateg,12 "-- nenurodyta --",13 x => x.id14 ),15 btipas: createOptions(16 things.btipas,17 "-- nenurodyta --",18 x => x.id19 ),20 bgamykl: createOptions(21 things.bgamykl,22 "-- nenurodyta --",23 x => x.id24 ),25 siule: createOptions(26 things.siule,27 "-- --",28 x => x.id29 ),30 pavoj: createOptions(31 things.pavoj.sort((p1, p2) => p1.ind - p2.ind),32 "-- nenurodyta --",33 x => x.id34 ),35 apar: createOptions(36 things.defskop.sort((d1, d2) => d1.id - d2.id),37 "-- nenurodyta --",38 x => x.id + ", " + x.model39 ),40 oper: createOptions(41 things.operat.sort((o1, o2) => o1.name - o2.name),42 "-- nenurodyta --",43 x => x.id + ", " + x.name44 )45});...
Using AI Code Generation
1describe('Create Options', function () {2 it('Create Options', function () {3 cy.get('.action-select').select('apples')4 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])5 })6})7describe('Create Options', function () {8 it('Create Options', function () {9 cy.get('.action-select').select('apples')10 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])11 })12})13describe('Create Options', function () {14 it('Create Options', function () {15 cy.get('.action-select').select('apples')16 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])17 })18})19describe('Create Options', function () {20 it('Create Options', function () {21 cy.get('.action-select').select('apples')22 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])23 })24})25describe('Create Options', function () {26 it('Create Options', function () {27 cy.get('.action-select').select('apples')28 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])29 })30})31describe('Create Options', function () {32 it('Create Options', function () {33 cy.get('.action-select').select('apples')34 cy.get('.action-select-multiple').select(['apples', 'oranges', 'bananas'])35 })36})
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('input').type('test')4 cy.get('button').click()5 cy.get('li').should('have.length', 1)6 cy.get('li').contains('test')7 cy.get('input').type('test2')8 cy.get('button').click()9 cy.get('li').should('have.length', 2)10 cy.get('li').contains('test2')11 cy.get('input').type('test3')12 cy.get('button').click()13 cy.get('li').should('have.length', 3)14 cy.get('li').contains('test3')15 })16})17describe('My First Test', function() {18 it('Does not do much!', function() {19 cy.get('input').type('test')20 cy.get('button').click()21 cy.get('li').should('have.length', 1)22 cy.get('li').contains('test')23 cy.get('input').type('test2')24 cy.get('button').click()25 cy.get('li').should('have.length', 2)26 cy.get('li').contains('test2')27 cy.get('input').type('test3')28 cy.get('button').click()29 cy.get('li').should('have.length', 3)30 cy.get('li').contains('test3')31 })32})
Using AI Code Generation
1Cypress.Commands.add('createOptions', (method, url, body) => {2 return {3 }4 })5 describe('API test', () => {6 it('Verify API response', () => {7 })8 cy.request(options).then((response) => {9 expect(response.status).to.eq(201)10 expect(response.body).to.have.property('name', 'morpheus')11 expect(response.body).to.have.property('job', 'leader')12 expect(response.body).to.have.property('id')13 expect(response.body).to.have.property('createdAt')14 })15 })16 })
Using AI Code Generation
1describe('My First Test', () => {2 it('Visits the Kitchen Sink', () => {3 cy.viewport(320, 568)4 cy.get('.home-list > :nth-child(1) > a').click()5 })6})7{8}9Cypress.Commands.add('viewport', (width, height) => {10 if (Cypress._.isNumber(width) && Cypress._.isNumber(height)) {11 cy.log(`Setting viewport to ${width}x${height}`)12 cy.viewport(width, height)13 } else {14 cy.log(`Getting viewport dimensions`)15 return cy.viewport()16 }17})18describe('viewport command', () => {19 it('gets viewport dimensions', () => {20 cy.viewport().should('deep.equal', {21 })22 })23 it('sets viewport dimensions', () => {24 cy.viewport(320, 568)25 cy.viewport().should('deep.equal', {26 })27 })28 it('sets viewport dimensions with preset', () => {29 cy.viewport('macbook-13')30 cy.viewport().should('deep.equal', {31 })32 })33 it('sets viewport dimensions with preset and orientation', () => {34 cy.viewport('macbook-13', 'portrait')35 cy.viewport().should('deep.equal', {36 })37 })38})39describe('viewport command', () => {40 sizes.forEach((size) => {41 it(`sets viewport to ${size[0]}x${size[1]}`, () => {42 cy.viewport(size[0], size[1])43 cy.get('.home-list >
Using AI Code Generation
1describe("My First Test", () => {2 it("Does not do much!", () => {3 expect(true).to.equal(true);4 });5});6describe("My First Test", () => {7 it("Does not do much!", () => {8 expect(true).to.equal(true);9 });10});11describe("My First Test", () => {12 it("Does not do much!", () => {13 expect(true).to.equal(true);14 });15});
Using AI Code Generation
1import '@cypress/code-coverage/support'2Cypress.Commands.add('createOptions', (fixtureName, method, url, body) => {3 cy.fixture(fixtureName).then((fixture) => {4 cy.route({5 })6 })7})8describe('Test', () => {9 it('test', () => {10 })11})12{13}
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!