How to use buildSpecs method in Cypress

Best JavaScript code snippet using cypress

BuildProject.js

Source:BuildProject.js Github

copy

Full Screen

1var util = require('util');2var fs = require('fs');3var scriptDir = __dirname;4var curDir = process.cwd();5var projectName = require('path').basename(curDir);6var exec = require('child_process').exec;7// Forward declarations - we'll unpack dependencies then require them.8var jsParser;9var uglify;10var modulr;11var findIt;12/**13 * We first build the monolithicBuild.js without closure. Then we potentially14 * perform advanced minification using closure. If so, that in itself is a two15 * step process:16 * monolithicBuild.js =>17 *    monolithicBuildNotCssAppropriate.js(first pass output)18 *    monolithicBuildCssAppropriate.js(second pass output)19 */20var BASE_CLOSURE_COMMAND = 'java -jar ' + curDir + '/build/buildRequirements/closure_compiler/compiler.jar ';21var INITIAL_CLOSURE_COMMAND = BASE_CLOSURE_COMMAND +22 '--js ' + curDir + '/build/client/monolithicBuild.js ' +23 '--property_map_output_file ' + curDir + '/build/artifacts/keyRenameMapNotCssAppropriate.txt ' +24 '--compilation_level ADVANCED_OPTIMIZATIONS ' +25 // Temporary intermediate file - not yet appropriate for use with minified css.26 // Only used to generate potential key renaming map for correction.27 '--js_output_file ' + curDir + '/build/artifacts/monolithicBuildNotCssAppropriate.js ';28/**29 * Recompile a second time, after we use the output of the first to detect when30 * keys would collide if used in css minification. We resolve those collissions31 * here and recompile a second time with those resolutions enhancing the32 * process.33 */34var CLOSURE_COMMAND_CSS_APPROPRIATE = BASE_CLOSURE_COMMAND +35 '--js ' + curDir + '/build/client/monolithicBuild.js ' +36 '--property_map_input_file ' + curDir + '/build/artifacts/keyRenameMapCssAppropriate.txt ' +37 '--compilation_level ADVANCED_OPTIMIZATIONS ' +38 '--js_output_file ' + curDir + '/build/artifacts/monolithicBuildPostCorrectedClosure.js; ' +39 'mv ' + curDir + '/build/artifacts/monolithicBuildPostCorrectedClosure.js ' + curDir +40        '/build/client/monolithicBuild.js';41var FaxTailConstructionOptimizer = require('./FaxTailConstructionOptimizer');42var FaxStyleGenerator = require('./FaxStyleGenerator');43var FaxStyleExportsRemover = require('./FaxStyleExportsRemover');44function replaceAll(text, search, replace) {45  if (search === replace) {46    return text;47  }48  while(text.indexOf(search) !== -1) {49    text = text.replace(search, replace);50  }51  return text;52}53function execAndStream(commandStr, callback) {54  util.debug('Executing:' + commandStr);55  exec(commandStr, function (error, stdout, stderr) {56      util.debug(stdout);57      util.debug(stderr);58      callback(error);59  });60}61var DEDUPE_KEYS = [62];63var CONSUMED_DEDUPE_KEYS = 0;64var CHARS = "abcdefghijklmnopqrstuvwxyz";65var CHARS_NUMS = '0123456789abcdefghijklmnopqrstuvwxyz';66var TOTAL_DEDUPE_COMBS = CHARS.length*CHARS_NUMS.length;67for (var i = 0; i < CHARS.length; i++) {68  DEDUPE_KEYS.push(CHARS[i]);69  for (var j = 0; j < CHARS_NUMS.length; j++) {70    DEDUPE_KEYS.push(CHARS[i]+CHARS_NUMS[j]);71  }72}73function nextDedupedKeyNotIn(map) {74  do {75    CONSUMED_DEDUPE_KEYS++;76  } while(CONSUMED_DEDUPE_KEYS < TOTAL_DEDUPE_COMBS && map[DEDUPE_KEYS[CONSUMED_DEDUPE_KEYS]]);77  return DEDUPE_KEYS[CONSUMED_DEDUPE_KEYS];78}79/** Red is 31, off is 0, green is 32 **/80function redStr(str) {81  return "\033[31m" + str + "\033[0m";82}83function greenStr(str) {84  return "\033[32m" + str + "\033[0m";85}86function objMapToArray(obj, mapper) {87  var ret = [], aKey;88  for (aKey in obj) {89    if (obj.hasOwnProperty(aKey)) {90      ret.push(mapper(obj[aKey], aKey));91    }92  }93  return ret;94}95function getProjectConfigByPath(filePath) {96	var projectConfig = require(filePath).projectConfig || require(filePath);97  if (!projectConfig) {98    console.error("[ERROR]: Can't find project config");99    throw "See error message";100  } else {101    return projectConfig;102  }103}104function logAndThrow(str, e) {105  console.error(redStr('[ERROR]:' + str));106  throw e || str;107}108function logAndThrowIf(b, str, e) {109  if (b) {110    console.error(redStr('[ERROR]:' + str));111    throw e || str;112  }113}114console.log("\n------ Build Results ------");115function modulrize(buildSpecs, callback) {116  console.log('-> Building using modulr');117  var paths = objMapToArray(118      buildSpecs.projectConfig.projectModules,119      function(moduleDesc, projectModuleName) {120        return buildSpecs.buildClientBuildLibDir + projectModuleName;121      }122    );123  modulr.build(buildSpecs.projectMainModule, {124    paths:paths ,125    root: '/'126  },127  function(one, two) {128    logAndThrowIf(one, one);129    fs.writeFileSync(curDir + '/build/client/monolithicBuild.js',130        fixModuleOutputForAdvancedCompilation(two.output), 'utf8');131    callback();132    console.log(greenStr("Successfully built and packaged non-closure-optimized js"));133  });134}135function fixModuleOutputForAdvancedCompilation(output) {136  return output.replace("exports.define", "exports['define']").137         replace("exports.require", "exports['require']");138}139function cssNameForJsFileNamePath (fileNamePath) {140  return fileNamePath.substr(0, fileNamePath.length - 3) + '.css';141}142function isJsFileNamePath (fileNamePath) {143  return fileNamePath.indexOf('.js') === fileNamePath.length-3;144}145function outputCss(styleSheetsByPath, transformer) {146  var monolithicStyle = '';147  util.debug(greenStr('Outputting generated css'));148  for (var filePath in styleSheetsByPath) {149    if(styleSheetsByPath.hasOwnProperty(filePath)) {150      var lastStepProcessedStyleSheet = transformer(styleSheetsByPath[filePath]);151      monolithicStyle += lastStepProcessedStyleSheet;152      fs.writeFileSync(filePath, lastStepProcessedStyleSheet, 'utf8');153    }154  }155  fs.writeFileSync(curDir + '/build/client/monolithicStyle.css', monolithicStyle, 'utf8');156  util.debug(greenStr('Done outputing css and monolithic css'));157}158function compile(buildSpecs) {159  var i, origFileText, origFileAst, optimizedAst, generatedStyleString,160      buildLibFiles = findIt.sync(curDir + '/build/client/buildLib/'),161      /* We have to save the style sheets for later, because we don't yet know if we're going162       * to advanced minify - if so we need to hold off on the writing out of files. */163      styleSheetsForLaterByPath = {},164      files = [];165  /**166   * The ProjectConfig is the way that ordering of styles is defined for now. It167   * should probably be in dependency order - but this works okay for now.168   * So we build up the files array based on the module order. Repeat: files has169   * files from buildLib in order of modules listed in ProjectConfig.js170   * Once modular allows hooks for build processing, it will be in dependency171   * order.172   */173  for (var moduleName in buildSpecs.projectConfig.projectModules) {174    util.debug(moduleName);175    for (i=0; i < buildLibFiles.length; i=i+1) {176      if(buildLibFiles[i].indexOf(curDir + '/build/client/buildLib//' + moduleName+'/') === 0) {177        files.push(buildLibFiles[i]);178      }179    }180  }181  function doComile() {182    for (i=0; i < files.length; i=i+1) {183      if (!isJsFileNamePath(files[i])) {184        continue;185      }186      try {187        origFileText = fs.readFileSync(files[i], 'utf8');188        origFileAst = jsParser.parse(origFileText);189        optimizedAst = FaxTailConstructionOptimizer.optimizeTailConstructions(origFileAst);190        try {191          fs.writeFileSync(files[i], uglify.gen_code(optimizedAst), 'utf8');192          generatedStyleString = FaxStyleGenerator.generateCss(files[i]);193          if (generatedStyleString) {194            styleSheetsForLaterByPath[cssNameForJsFileNamePath(files[i])] = generatedStyleString;195          }196        } catch (e2) {197          console.error(redStr('[ERROR]: Could not optimize style module:' + files[i] + '/.css'));198          throw e2;199        }200        optimizedAstWithStyleExportsRemoved = FaxStyleExportsRemover.removeStyleExports(optimizedAst);201        fs.writeFileSync(files[i], uglify.gen_code(optimizedAstWithStyleExportsRemoved), 'utf8');202      } catch (e) {203        console.error(redStr('[ERROR]: Could not optimize module:' + files[i]));204        throw e;205      }206    }207    modulrize(buildSpecs, potentiallyMinifyAndGenerateStyleSheets);208  }209  doComile(buildSpecs);210  function potentiallyMinifyAndGenerateStyleSheets() {211    if (!buildSpecs.minifyClosureAdvanced) {212      outputCss(styleSheetsForLaterByPath, function(s) {return s;});213    } else {214      // As a last step, we process the stylesheets, minifying them. We could have just minified215      // everything, then called styleExports, but this way allows us to rip style exports out of216      // the minification process which could polute closure's choice of tiny keys (1char).217      // This way, we first run closure, get the remap file, then use that to shorten up the css.218      // Although, we could do it in a more elegant way here - by rerunning closure on each js219      // file, then yanking out the styleExports - but that would be very very slow. This is just220      // string replacement. Store the rename maps by length so that we can easily replace them221      // in css without having problems where class names are prefixes of other class names -222      // we start at the shortest class names and work our way to the longer223      // ones so that we don't "reclobber" something that was just renamed.224      buildAdvancedRenameKeysForAppropriateCssUsage(buildSpecs, function(cssAppropriateKeyRenameMap) {225        var subsetByOriginalSymbLength = orderKeyRenameMapByOriginalSymbolLength(cssAppropriateKeyRenameMap);226        var styleSheetTransformer = function(styleSheet) {227          for (var keyLen = 0; keyLen < subsetByOriginalSymbLength.length; keyLen++) {228            var renameMap = subsetByOriginalSymbLength[keyLen];229            for (var symbol in renameMap) {230              styleSheet = replaceAll(styleSheet, '.'+symbol + ' ', '.'+renameMap[symbol] + ' ');231              styleSheet = replaceAll(styleSheet, '.'+symbol + ':', '.'+renameMap[symbol] + ':');232            }233          }234          return styleSheet;235        };236        outputCss(styleSheetsForLaterByPath, styleSheetTransformer);237      });238    }239  }240}241/**242 * Builds with closure, dedupes keys to tolerate css symbol case insensitivity, returns243 * the new key rename map that will not have any two symbols renamed to identical symbols244 * congruent modulo lowerCase.245 * Before: {dog: 'aa', cat: 'aA'} After: {dog: 'aa', cat: 'D1'}246 * Todo: rename any symbols that got leading dollar signs.247 * Todo: first search css output for any occurance before applying any of these rules.248 */249function buildAdvancedRenameKeysForAppropriateCssUsage(buildSpecs, callback) {250  util.debug(greenStr('Building advanced Closure Compilation - going to make css conform to key remapping'));251  buildWithAdvancedClosure(false, function () {252    var keyRenameMap = getMostRecentKeyRenameMapFromFile();253    var cssAppropriateKeyRenameMap = dedupeCssAppropriate(keyRenameMap);254    writeOutKeyRenameMapForNextClosureCompile(buildSpecs, cssAppropriateKeyRenameMap);255    /* Have to build a second time, this time clobering that rename file. */256    buildWithAdvancedClosure(true, function() {257      callback(cssAppropriateKeyRenameMap);258    });259  });260}261function writeOutKeyRenameMapForNextClosureCompile(buildSpecs, keyRenameMap) {262  var fileStr = '';263  var minifyClosureAdvancedPreserveKeys = buildSpecs.minifyClosureAdvancedPreserveKeys;264  for (var origSymbol in keyRenameMap) {265    if(!keyRenameMap.hasOwnProperty(origSymbol)) {266      continue;267    }268    if (!minifyClosureAdvancedPreserveKeys[origSymbol]) {269      fileStr+=(origSymbol + ':' + keyRenameMap[origSymbol] + '\n');270    } else {271      fileStr+=(origSymbol + ':' + origSymbol + '\n');272    }273  }274  fs.writeFileSync(275    curDir +  '/build/artifacts/keyRenameMapCssAppropriate.txt',276    fileStr,277    'utf8');278}279/* Builds advanced, dedupes keys (in case INsensitive manner), passes deduped280 * rename map and same map ordered by original key length. */281function buildWithAdvancedClosure(cssAppropriate, callback) {282  util.debug(greenStr('Attempting Google Closure Advanced Minification'));283  execAndStream(cssAppropriate ? CLOSURE_COMMAND_CSS_APPROPRIATE : INITIAL_CLOSURE_COMMAND, function (error) {284    logAndThrowIf(error, 'Error performing Closure Advanced Minification');285    callback();286  });287}288function orderKeyRenameMapByOriginalSymbolLength(keyRenameMap) {289  var subsetByOriginalSymbLength = [];290  for (var originalSymbol in keyRenameMap) {291    if(keyRenameMap.hasOwnProperty(originalSymbol)) {292      if (!subsetByOriginalSymbLength[originalSymbol.length]) {293        subsetByOriginalSymbLength[originalSymbol.length] = {};294      }295      subsetByOriginalSymbLength[originalSymbol.length][originalSymbol] =296          keyRenameMap[originalSymbol];297    }298  }299  return subsetByOriginalSymbLength;300}301/**302 * Gets rid of duplicates with respect to case insensitivity, and keys that are303 * not valid symbols across javascript and css files.304 * { aa => {dog:aa, cat:aA}}305 */306function dedupeCssAppropriate(keyRenameMap) {307  var lowerCaseKeyToEntries = {};308  var newRenameMap = {};309  for (var symbol in keyRenameMap) {310    if(keyRenameMap.hasOwnProperty(symbol)) {311      var renamedTo = keyRenameMap[symbol];312      var lowerCaseRenamedTo = renamedTo.toLowerCase();313      if (!lowerCaseKeyToEntries[lowerCaseRenamedTo]) {314        lowerCaseKeyToEntries[lowerCaseRenamedTo] = {};315      }316      lowerCaseKeyToEntries[lowerCaseRenamedTo][symbol] = renamedTo;317    }318  }319  for (var lowerCaseKey in lowerCaseKeyToEntries) {320    if(lowerCaseKeyToEntries.hasOwnProperty(lowerCaseKey)) {321      var entries = lowerCaseKeyToEntries[lowerCaseKey];322      /* If there's dups w.r.t. lowerCase, or a dollar sign.  Todo, let the323       * first occurance keep the mixed case, non-dollar sign */324      if (Object.keys(entries).length > 1 || lowerCaseKey.indexOf('$') !== -1) {325        var first = true;326        for(var originalSymbol in entries) {327          if(!entries.hasOwnProperty(originalSymbol)) {328            continue;329          }330          if (!first || lowerCaseKey.indexOf('$') !== -1) {331            newRenameMap[originalSymbol] = nextDedupedKeyNotIn(lowerCaseKeyToEntries);332          } else {333            newRenameMap[originalSymbol] = lowerCaseKey;334          }335          first = false;336        }337      } else {338        for(var originalSymbol in entries) {339          if(entries.hasOwnProperty(originalSymbol)) {340            newRenameMap[originalSymbol] = entries[originalSymbol];341          }342        }343      }344    }345  }346  return newRenameMap;347}348function getMostRecentKeyRenameMapFromFile() {349  var keyRenameMapFileText = fs.readFileSync(350      curDir + '/build/artifacts/keyRenameMapNotCssAppropriate.txt', 'utf8');351  var keyRenameLines = keyRenameMapFileText.split('\n');352  var keyRenameMap = {};353  for (var i = keyRenameLines.length - 1; i >= 0; i--) {354    var split = keyRenameLines[i].split(':');355    if (split[0] && split[1]) {356      keyRenameMap[split[0]] = split[1];357    }358  }359  return keyRenameMap;360}361function build(buildSpecs) {362  var i, moduleName, moduleDesc, moduleMain, moduleMainPath;363  console.log("-> Creating New Build Directories");364  fs.mkdirSync(curDir + '/build/client', '0777');365  fs.mkdirSync(curDir + '/build/client/staticResources', '0777');366  fs.mkdirSync(curDir + '/build/client/buildLib', '0777');367  console.log('-> Copying project modules to build directory');368  for (moduleName in buildSpecs.projectConfig.projectModules) {369    if (buildSpecs.projectConfig.projectModules.hasOwnProperty(moduleName)) {370      moduleDesc = buildSpecs.projectConfig.projectModules[moduleName];371      moduleMain = moduleDesc.main;372      logAndThrowIf(moduleMain && (373          moduleMain.length < 6 || moduleMain.substr(0,2) !== './' ||374          moduleMain.substr(moduleMain.length-3) !== '.js'),375          'If a main module is specified (' + moduleMain + ') then it must begin with' +376          '"./" and end with ".js" indicating the file inside of lib/ModuleName');377      logAndThrowIf(buildSpecs.libDirContentsArr.indexOf(moduleName) === -1,378          'Cannot find a directory with module name ' + moduleName + ' in lib -' +379          'Why is it specified as a project module in ProjectConfig.js?');380      moduleMainPath = buildSpecs.buildClientBuildLibDir + moduleName + '/' +(381           moduleMain ? moduleMain.substr(2) : (moduleName + '.js'));382      console.log('   -> Using single module main file in build:' + moduleMainPath);383    }384  }385  /* Todo: build skeletons for missing modules. */386  /* Here, we sym link node_modules to the buildLib because things we require387   * (that have style modules that we want to turn into css) have dependencies388   * on the other project modules. We need to make sure that their dependencies389   * are met. */390  execAndStream("cp -r " + curDir + "/lib/* " + curDir + "/build/client/buildLib/; " +391       "ln -s " + curDir + "/build/client/buildLib " + curDir + "/build/client/node_modules; " +392       "cp " + curDir + "/index.html " + curDir + "/build/client/ ;" +393       "cp -r " + curDir + "/staticResources/* " + curDir + "/build/client/staticResources/ ;",394    function (error) {395      logAndThrowIf(error, 'Error moving lib to buildLib');396      compile(buildSpecs);397    });398}399function setup() {400  var i, req, projectConfigText;401  try {402    projectConfigText = fs.readFileSync(curDir + '/ProjectConfig.js', 'utf8');403  } catch (e) {404    logAndThrow("[ERROR]: No Project Config Found!", e);405  }406  var curDirContents = fs.readdirSync(curDir);407  var curBuildDirContents = fs.readdirSync(curDir + '/build');408  var CHECK_PREBUILD = {409    'build': false,410    'lib': false,411    'index.html': false,412    'server.js': true,413    'staticResources': false,414    'ProjectConfig.js': false,415    'build/buildRequirements': false,416    'build/buildRequirements/buildPrereqsAndNodeModules.zip': false417  };418  var CHECK_PREBUILD_IN_BUILD = {419    'client': false,420    'artifacts': false,421  };422  var BUILD_REQUIREMENTS = {423    'lib': true,424    'index.html': true,425    'server.js': true,426    'missingRequirements': true,427    'ProjectConfig.js': true428  };429  var buildReqs = {};430  var missingRequirements = [];431  util.debug(JSON.stringify(curDirContents));432  for (req in CHECK_PREBUILD) {433    if (CHECK_PREBUILD.hasOwnProperty(req)) {434      CHECK_PREBUILD[req] = curDirContents.indexOf(req) !== -1;435      if (BUILD_REQUIREMENTS[req] && !CHECK_PREBUILD[req]) {436        missingRequirements.push(req);437      }438    }439  }440  for (req in CHECK_PREBUILD_IN_BUILD) {441    if (CHECK_PREBUILD_IN_BUILD.hasOwnProperty(req)) {442      CHECK_PREBUILD_IN_BUILD[req] = curBuildDirContents.indexOf(req) !== -1;443    }444  }445  logAndThrowIf(missingRequirements.length,446        "Missing Build Requirements:" +447        JSON.stringify(missingRequirements) + "\n" +448        "Observe project root to have: " +449        JSON.stringify(curDirContents));450  var projectConfig = getProjectConfigByPath(curDir + '/ProjectConfig.js');451  var projectMainModule = projectConfig.projectMainModule;452  var libDirContentsArr = fs.readdirSync(curDir + '/lib');453  var buildClientBuildLibDir = curDir + '/build/client/buildLib/'; 454  var curTime = (new Date()).getTime();455  logAndThrowIf(!projectMainModule, 'NO Main Module Name!');456  var buildSpecs = {457    libDirContentsArr: libDirContentsArr,458    projectConfig: projectConfig,459    curDir: curDir,460    projectMainModule: projectMainModule,461    buildClientBuildLibDir: buildClientBuildLibDir,462    minifyClosureAdvanced: projectConfig.minifyClosureAdvanced,463    minifyClosureAdvancedPreserveKeys: projectConfig.minifyClosureAdvancedPreserveKeys464  };465  /* Lazily create the artifacts directory. */466  if (!CHECK_PREBUILD_IN_BUILD['artifacts']) {467    fs.mkdirSync(curDir + '/build/artifacts', '0777');468  }469  /* Remove build client directory. */470  console.log('-> Removing Old Build client Directory (Backing up)');471  if (CHECK_PREBUILD_IN_BUILD['client']) {472    try {473      exec(474        'mv ' + curDir + '/build/client ' + curDir + '/build/buildBackups/b' + curTime + ' ;',475        function (error, stdout, stderr) {476          util.debug(stdout);477          util.debug(stderr);478          logAndThrowIf(error, 'Error moving Build directory', error);479          build(buildSpecs);480        }481      );482    } catch (e1) {483      logAndThrow('Could Not Issue Exec For Clean Build Directory!', e1);484    }485  } else {486    build(buildSpecs);487  }488}489exec(490  'rm -r ' + curDir + '/build/buildRequirements/node_modules/; rm -r ' + curDir + '/build/buildRequirements/closure_compiler/; ' +491   ' cd ' + curDir + '/build/buildRequirements; unzip buildPrereqsAndNodeModules.zip; cd ' + curDir + ';',492  function (error, stdout, stderr) {493    util.debug(stdout);494    util.debug(stderr);495    logAndThrowIf(error, 'Error Unpacking build prereqs', error);496    util.debug('Unpacked resources');497    jsParser = require('uglify-js').parser;498    uglify = require('uglify-js').uglify;499    modulr = require('modulr');500    findIt = require('findit');501    setup();502  }503);504/*projectRoot505|506+- staticResources (optional)507|508+- runBuild.sh509|510+- server.js511|512+- simpleClientFileServer.sh 513|514+- ProjectConfig.js515|516+- index.html (optional - will be used if present)517|518+- lib519|  |520|  +- YourModule521|  |522|  +- YourOtherModule523|524+- build   (All of the above is packaged into the build directory, which is a self-contained, portable directory.)525           (You would likely take the result and integrate it into your system, but a simple client file server526            is given just to test serving from a web server. You can also usually just open index.html in any browser without527            running any server.)528  +- server529  |  |530  |  +- simpleClientFileServer.js531  |532  +- client533  |  |534  |  +- index.html535  |  |536  |  +- staticResources537  |  |538  |  +- monolithicBuild.js (process all files -> browserify.js -> closure = monolithicBuild.js)539  |  |540  |  +- monolithicStyle.css (simple concatenation of all optimized css files - optional to use)541  |  |542  |  +- lib543  |     |544  |     +- YourModule545  |     |  |546  |     |  +- YourModule.js (even if we use monolithic)547  |     |  |548  |     |  +- YourModule.css (if applicable)549  |     |  |550  |     |  +- otherContentsInOriginalModuleDir (such as images etc.)551  |     |552  |     +- YourOtherModule...

Full Screen

Full Screen

NewBuild.js

Source:NewBuild.js Github

copy

Full Screen

1'use strict'2import React, {Component} from 'react'3import {4	Image,5	ScrollView,6	TextInput,7	TouchableWithoutFeedback,8	View9} from 'react-native'10import {connect} from 'react-redux'11import {Actions} from 'react-native-router-flux'12import {Bar} from 'react-native-progress'13import ImagePicker from 'react-native-image-crop-picker'14import Video from 'react-native-video'15import ParallaxScrollView from 'react-native-parallax-scroll-view';16import {keys, isEqual} from 'lodash'17import F8Header from '../common/F8Header'18import F8Button from '../common/F8Button'19import Part from '../part/Part'20import {Heading3, Paragraph} from '../common/F8Text'21import {Requests} from '../utils'22import {Titles, General, PartStyles, DetailStyles, NewPostStyles, Styles, PostStyles, Specs, WIDTH} from '../styles'23import {LinkContent, LoadingView, ErrorView, MetricsGraph, BackSquare} from '../components'24import {unlinkBuild, removeBuild, uploadToS3} from '../reducers/newpost/newpostActions'25import {26	newBuildSelector,27	profileSelector,28	linkedBuilds, 29	linkedParts, 30	userIdSelector,31	buildSpecs32} from '../selectors'33import {34	addBuildMedia, 35	removeBuildMedia, 36	setBuildImage,37	setBuildName,38	addBuildSpecEntry,39	editBuildSpecEntry,40	removeBuildSpecEntry,41	removePart,42	createBuild, 43	setBuildSpecs,44} from '../reducers/build/buildActions'45const mapStateToProps = (state) => {46	return {47		// build: newBuildSelector (state),48		userId: userIdSelector (state),49		linkedBuilds: linkedBuilds (state),50		linkedParts: linkedParts (state),51	    profileData: profileSelector (state),52	    buildSpecs: buildSpecs (state),53	}54}55const mapDispatchToProps = (dispatch) => {56	return {57		addBuildMedia: (mediaList) => dispatch (addBuildMedia (mediaList)),58		removeBuildMedia: (path) => dispatch (removeBuildMedia (path)),59	60		setBuildImage: (path) => dispatch (setBuildImage (path)),61		setBuildName: (name) => dispatch (setBuildName(name)),62	63		addBuildSpecEntry: (name, value) => dispatch (addBuildSpecEntry (name, value)),64		editBuildSpecEntry: (name, value) => dispatch (editBuildSpecEntry (name, value)),65		removeBuildSpecEntry: (name) => dispatch (removeBuildSpecEntry (name)),66		setBuildSpecs: (specs) => dispatch (setBuildSpecs (specs)),67		createBuild: () => dispatch (createBuild()),68		unlinkBuild: (buildId) => dispatch (removeBuild (buildId)),69		unlinkPart: (partId) => dispatch (removePart (partId)),70		uploadToS3: (file, postData) => dispatch (uploadToS3 (file, postData))71	}72}73class NewBuild extends Component {74	constructor (props) {75		super (props)76		console.log (props)77		this.state = {78			buildId: '', 79			// build: props.build, 80			buildSpecs: props.buildSpecs, 81			linkedParts: props.linkedParts, 82			linkedBuilds: props.linkedBuilds, 83			newBuild: {84				media: {85					source: props.source, 86					type: props.fileType87				},88				name: '',89			},90			filePath: props.source,91			fileType: props.fileType,92			fileName: props.fileName,93			text: props.text,94			isUploading: false,95			progress: 0,96		}97		this.renderSpecs = this.renderSpecs.bind (this)98		this.renderLinkedBuilds = this.renderLinkedBuilds.bind (this)99		this.renderLinkedParts = this.renderLinkedParts.bind (this)100		this.renderNewBuild = this.renderNewBuild.bind (this)101	    this.fetchBuildDetails = this.fetchBuildDetails.bind (this)102	    this.renderPostContent = this.renderPostContent.bind (this)103	    this.uploadPost = this.uploadPost.bind (this)104	}105	renderPostContent () {106		let {filePath, fileType, text} = this.state107		  , content108		if (filePath && filePath.length) {109		  if (fileType === 'photo') {110		    content = (111		      <Image source={{uri: filePath}} style={PostStyles.primaryImage}/>112		    )113		  }114		  else if (fileType === 'video') {115		    content = (116		      <Video117		        repeat118		        resizeMode='cover'119		        source={{uri: filePath}}120		        style={PostStyles.primaryImage}121		      />122		    )123		  }124		}125		return (126	          <View style={{flexDirection: 'column', flex: -1}}>127				<Image source={{uri: this.props.profileData.picture}} style={{height: 56, width: 56, margin: 8}}/>128	          	{content}129				<Paragraph style={[Titles.filterSectionTitle, {marginVertical: 8}]}>{"TEXT"}</Paragraph>          130				<TextInput131					multiline={true}132					onChangeText={(text) => {133						this.setState({text});134					}}135					placeholder="OMG IT'S FAST"136					style={[NewPostStyles.largeBlockInput, {marginHorizontal: 16}]}/>137			</View>138		)139	}140	renderNewBuild () {141		let {userId} = this.props142		return (143            <View style={{flex: -1,  marginLeft: 20, marginBottom: 20, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start'}}>144				<Image style={{width: 100, height: 100}} source={{uri: this.state.newBuild.media.source}}/>145				<View style={{flexDirection: 'column', flex: 1, marginHorizontal: 8}}>146				<TextInput147	                onChangeText={(text) => {148	                	let newBuild = Object.assign (this.state.newBuild, {name: text})149						this.setState({newBuild})150	                }}151					placeholder="Give your ride a name"152					multiline={false}153					style={{flex: 1}}/>154				<View style={{flexDirection: 'row', flex: 1, alignSelf: 'flex-start' ,justifyContent: 'space-around'}}>	155			    <F8Button 156			    	icon={require ('../common/img/tuning.png')} 157			    	onPress={()=>Actions.Makes({build: true})}158	    			type="carTag" 159	    			style={{flex: -1}} 160	    			caption="Create New Build"/>161			    <F8Button 162			    	icon={require ('../common/img/car.png')} 163			    	onPress={()=>Actions.BuildsByUserId({userId, selector: true})}164	    			type="carTag" 165	    			style={{flex: -1}} 166	    			caption="Choose From My Builds"/>167	    		</View>168				</View>169            </View>170		)171	}172	componentWillReceiveProps(nextProps) {173		console.log ({nextProps, props: this.props})174		let {linkedBuilds, buildSpecs, linkedParts} = nextProps175			, buildId = ''176		if (linkedBuilds.length && linkedBuilds[0] && linkedBuilds[0].buildId !== this.state.buildId) {177			this.fetchBuildDetails (linkedBuilds[0].buildId)178			buildId = linkedBuilds[0].buildId179			this.setState ({buildId, build: nextProps.build, linkedParts, linkedBuilds: nextProps.linkedBuilds, buildSpecs: buildSpecs || {}})180		} else {181			this.setState ({buildId: '', build: nextProps.build, linkedParts, linkedBuilds: nextProps.linkedBuilds, buildSpecs: buildSpecs || {}})182		}183	}184	async fetchBuildDetails (buildId) {185		try {186		    let data = await Requests.fetchBuildDetails (buildId)187			this.setState ({188				hasError: false,189				isLoading: false,190			})191			data && data.specs && this.props.setBuildSpecs (data.specs) && data.specs.specId && this.setState ({specId: data.specs.specId})192	    } catch (err) {193	      this.setState ({hasError: true, isLoading: false})194	    }195	}196	renderSpecs () {197		let {buildSpecs} = this.state198		if (keys(buildSpecs).length) {199	        let {200	            cylinders, compressor, configuration,201	            transmissionSpeed, transmission, drivenWheels, size,202	          } = buildSpecs203			, dataArray = keys (buildSpecs).filter((key)=>Number.isInteger (buildSpecs[key]))204											.map ((key)=>{return {name: key, value: buildSpecs[key]}})205	        return (206	        	<View style={{alignItems: 'center', justifyContent: 'center'}}>207					<Paragraph style={Titles.filterSectionTitle}>{"SPECS"}</Paragraph>          208					<View style={{marginHorizontal: 16}}>209						{size && cylinders && compressor?(<Heading3 style={Specs.subtitle}>{size.toFixed(1) + ` L ${configuration}-${cylinders} ${compressor}`.toUpperCase()}</Heading3>):(<View/>)}210						{drivenWheels?(<Heading3 style={Specs.subtitle}>{`${drivenWheels}`.toUpperCase()}</Heading3>):(<View/>)}211						<MetricsGraph onDoneEdit={this.props.editBuildSpecEntry} editable={true} data={[{entries:dataArray}]}/>212					</View>213				</View>214	          )215		}216		else return (<View/>)217	}218	219	renderLinkedBuilds () {220		let {linkedBuilds} = this.state221		console.log (linkedBuilds)222		return (223			<View>224			{linkedBuilds.map ((build, idx)=>(<LinkContent removeAction={()=>this.props.unlinkBuild (build.buildId)} key={idx} name={build.name} image={build.image} />))}225			</View>226		)227	}228	renderLinkedParts () {229		let {linkedParts} = this.state230		console.log (linkedParts)231		return (linkedParts && linkedParts.length > 0)?(232			<View>233			<Paragraph style={Titles.filterSectionTitle}>{"PART"}</Paragraph>          234			{linkedParts.map ((part, idx)=>(<LinkContent removeAction={()=>this.props.unlinkPart (part.partId)} key={idx} name={part.name} image={part.media} />))}235			</View>236		):(<View/>)237	}238	render() {239		console.log (this.state)240		let {241			addBuildMedia,242			removeBuildMedia,243			setBuildImage,244			setBuildName,245			addBuildSpecEntry,246			editBuildSpecEntry,247			removeBuildSpecEntry,248			removePart,249			createBuild,250			userId,251		} = this.props252		, {253			buildSpecs,254		} = this.state255		, { specId } = this.state256		, leftItem = {257			title: 'Back',258			onPress: ()=>Actions.pop()259		}			260		, rightItem = (buildSpecs.specId)?{title: 'Tag Part',onPress: ()=>{Actions.Manufacturers ({specId: buildSpecs.specId})}}:{}261		, specsContent = this.renderSpecs()262		, partLink = this.renderLinkedParts()263		, buildLink = this.state.linkedBuilds.length ? (this.renderLinkedBuilds()) : (this.renderNewBuild())264		console.log (this.state)265		return (266	        <View style={{flex: 1}}>267			<F8Header style={General.Header} foreground="dark" leftItem={leftItem} title="Build Info" rightItem={rightItem}/>268			<ScrollView style={{marginBottom: 50}}>269		        {this.renderPostContent()}270				<Paragraph style={Titles.filterSectionTitle}>{"CAR"}</Paragraph>          271				{buildLink}272			    <View style={{alignItems: 'flex-start', flex: 1, flexDirection: 'column', marginVertical: 16}}>273				{specsContent}274	    		{partLink}275	    		</View>276			</ScrollView>277	        <F8Button278	          style={[General.bottomButtonStyle, {position: 'absolute', bottom: 0}]}279	          type="saved" caption="POST!"280	          onPress={()=>{281	          	this.uploadPost ()282	          	Actions.popTo("main")283	          }}284	        />285		</View>286		)287	}288	uploadPost () {289		let {linkedBuilds, linkedParts, newBuild, text, fileName, filePath, fileType, buildSpecs} = this.state290			, partIds = linkedParts.map ((part)=>part.partId)291			, buildId = linkedBuilds[0] && linkedBuilds[0].buildId || ''292			, {userId} = this.props293		try {294			let data = {295				buildSpecs,296				buildId,297				partIds,298				text,299				userId,300				mediaType: fileType301			}, file = {302				uri: filePath,303				name: fileName,304				type: fileType,305			}306			data = (buildId === '') ? Object.assign (data, {newBuild}) : data307			this.props.uploadToS3 (file, data)308		} catch (err) {309		}310	}311}...

Full Screen

Full Screen

abdo.js

Source:abdo.js Github

copy

Full Screen

1import chalk from 'chalk';2import chokidar from 'chokidar';3import minimist from 'minimist';4import path from 'path';5import { createFilter } from '@rollup/pluginutils';6import { readdirSync, lstatSync, readFileSync } from 'fs';7import buildspec from '../lib/buildspec';8import { bundler, openPage } from '../lib/bundler';9import { getBrowser } from '../lib/puppeteer';10const { cyan, yellow, green, red } = chalk;11const cmd = process.argv[2];12const cmds = ['watch', 'build', 'preview', 'build-all', 'screenshot'];13if (!cmds.includes(cmd)) {14	console.log('Unsupported command: ' + cmd);15	console.log('Supported commands are: ' + cmds.join(', '));16	process.exit();17}18const watch = cmd === 'watch';19let rollupWatcher = null;20const targetPath = process.argv[3] || '.';21const cmdArgs = minimist(process.argv.slice(3), {22	boolean: ['build'],23	alias: {24		b: 'build',25		u: 'url',26		n: 'name',27	},28});29// More graceful exit30process.on('SIGINT', () => {31	console.log('');32	process.exit();33});34switch (cmd) {35	case 'watch':36	case 'build':37		buildSingleEntry(targetPath);38		break;39	case 'preview':40	case 'build-all':41		buildMultiEntry(targetPath);42		break;43	case 'screenshot':44		createScreenshots(targetPath);45		break;46	default:47		process.exit();48}49/**50 * Builds a bundle for commands that have single matching entry.51 * @param {string} targetPath52 */53async function buildSingleEntry(targetPath) {54	const [config] = await getMatchingBuildspec(targetPath);55	if (!config) {56		console.log(red("Couldn't find buildspec.json for the variant", targetPath));57		process.exit();58	}59	switch (cmd) {60		case 'watch':61			if (rollupWatcher) {62				rollupWatcher.close();63			} else {64				console.log(cyan('Starting bundler with a file watcher...'));65			}66			const watcher = chokidar.watch(config._specFiles, {67				awaitWriteFinish: true,68			});69			watcher.on('change', (filepath) => {70				console.log('');71				console.log('Buildspec changed', yellow(filepath));72				console.log(green('Restarting bundler...'));73				console.log('');74				buildSingleEntry(targetPath);75				watcher.close();76			});77			break;78		case 'build':79			console.log(cyan('Building variant bundle...'));80			break;81		default:82			break;83	}84	console.log('Entry:', yellow(config.entryFile));85	console.log('');86	try {87		const output = await bundler({ ...config, watch });88		rollupWatcher = output.watcher;89		if (!watch) {90			console.log(green('Bundle built.'));91		}92		console.log('');93	} catch (error) {94		console.log(error);95	}96}97/**98 * Builds a bundle for commands that may have multiple matching entries.99 * @param {string} targetPath100 */101async function buildMultiEntry(targetPath) {102	const buildOnly = cmd === 'build-all';103	const buildspecs = await getMatchingBuildspec(targetPath);104	const [testConfig] = buildspecs;105	if (!testConfig) {106		console.log("Couldn't find any variant files");107		process.exit();108	}109	switch (cmd) {110		case 'preview':111			console.log(cyan('Starting bundlers for preview...'));112			break;113		case 'build-all':114			console.log(cyan('Building all variant bundles...'));115			break;116		default:117			break;118	}119	console.log();120	try {121		if (!buildOnly) {122			await getBrowser(testConfig);123		}124		for (const buildspec of buildspecs) {125			const { entryFile } = buildspec;126			const output = await bundler(buildspec);127			if (!buildOnly) {128				await openPage(output);129			} else {130				console.log(entryFile.replace(process.env.INIT_CWD, ''), green('Done.'));131			}132		}133		if (buildOnly) {134			console.log();135			console.log(green('Variant bundles built.'));136			console.log();137			process.exit(0);138		}139	} catch (e) {140		console.log(e);141		// Do nothing142	}143}144/**145 * Creates screenshots from variants that matches the given path.146 * @param {string} targetPath147 */148async function createScreenshots(targetPath) {149	const buildspecs = await getMatchingBuildspec(targetPath);150	const { url: cmdArgUrl, name, ...screenshotArgs } = cmdArgs;151	let cmdArgBuild = false;152	if ('build' in screenshotArgs) {153		cmdArgBuild = true;154		delete screenshotArgs.build;155	}156	if (!buildspecs.length) {157		console.log(red('0 test variants found with path:'));158		console.log(targetPath);159		process.exit();160	}161	let origPage;162	console.log(cyan(`Taking screenshots`));163	console.log();164	for (const config of buildspecs) {165		const nth = buildspecs.indexOf(config) + 1;166		if (cmdArgUrl) {167			if (isNaN(cmdArgUrl)) {168				config.url = [cmdArgUrl];169			} else {170				if (Array.isArray(config.url)) {171					const urlIndex = +cmdArgUrl;172					if (urlIndex < config.url.length) {173						config.url = [config.url[urlIndex]];174					} else {175						console.log(yellow(`Undefined index for test config url. Argument was`), '--url=' + cmdArgUrl);176						console.log(yellow(`Current config`), config.url);177					}178				} else {179					console.log(180						yellow(`Test config url wasn't an array, can't use indexed url argument. Argument was`),181						'--url=' + cmdArgUrl182					);183				}184			}185		}186		const { testPath, buildDir, entryFile, entryFileExt, screenshot = {}, onLoad, onBefore } = config;187		Object.assign(screenshot, screenshotArgs);188		let {189			waitFor,190			waitForOptions = {},191			onLoad: screenshotOnLoad,192			onBefore: screenshotOnBefore,193			...pptrScreenshotOptions194		} = screenshot;195		const entryName = path.basename(entryFile, '.' + entryFileExt);196		// Bundle main events and screenshot events197		const singleOnLoad = async (page) => {198			if (onLoad) await onLoad(page);199			if (screenshotOnLoad) await screenshotOnLoad(page);200		};201		const singleOBefore = async (page) => {202			if (onBefore) await onBefore(page);203			if (screenshotOnBefore) await screenshotOnBefore(page);204		};205		const bundleConfig = { ...config, onLoad: singleOnLoad, onBefore: singleOBefore, preview: true };206		if (!cmdArgBuild) {207			const bundlePath = path.join(testPath, buildDir, `${entryName}.bundle.js`);208			if (lstatSync(bundlePath).isFile()) {209				bundleConfig.assetBundle = {210					bundle: readFileSync(bundlePath).toString(),211				};212			}213		}214		const output = bundleConfig.assetBundle ? bundleConfig : await bundler(bundleConfig);215		console.log(cyan(`Creating a bundle for screenshot`), entryFile);216		console.log();217		const page = await openPage({ ...output, headless: true, devtools: false });218		const url = Array.isArray(config.url) ? config.url[0] : config.url;219		const waitForAll = async (page) => {220			if (typeof waitFor === 'string') {221				console.log(cyan(`Waiting for selector ${waitFor}...`));222				await page.waitForSelector(waitFor, waitForOptions);223			}224			if (typeof waitFor === 'number') {225				console.log(cyan(`Waiting for timeout ${waitFor} ms...`));226				await page.waitForTimeout(waitFor, waitForOptions);227			}228			if (typeof waitFor === 'function') {229				console.log(cyan(`Waiting for function...`));230				await page.waitForFunction(waitFor, waitForOptions);231			}232		};233		if (pptrScreenshotOptions.fullPage === undefined) {234			pptrScreenshotOptions.fullPage = true;235		}236		if (pptrScreenshotOptions.clip) {237			pptrScreenshotOptions.fullPage = false;238		}239		await waitForAll(page);240		// Take screenshot from variant241		await page.screenshot({242			...pptrScreenshotOptions,243			path: path.join(config.testPath, config.buildDir, `screenshot-${path.basename(name || entryName)}-v${nth}.png`),244		});245		console.log(cyan(`Screenshot ready`), `${entryFile}, variant ${nth}`);246		// Get new page for the original (without listeners etc)247		origPage = await page.browser().newPage();248		await singleOBefore(origPage);249		// Go to the same url and take the screenshot from the original as well.250		await origPage.goto(url, { waitUntil: 'networkidle0' });251		await singleOnLoad(origPage);252		await waitForAll(origPage);253		await origPage.screenshot({254			...pptrScreenshotOptions,255			path: path.join(config.testPath, config.buildDir, `screenshot-${path.basename(name || entryName)}-orig.png`),256		});257		console.log(cyan(`Screenshot ready`), `${entryFile}, original`);258		console.log();259		console.log(green('Took screenshots for'), entryFile.replace(process.env.INIT_CWD, ''));260		console.log();261	}262	console.log(green('Done.'));263	if (origPage) {264		await origPage.browser().close();265	}266}267/**268 * Returns all entry buildspecs that matches the given path.269 * @param {string} targetPath270 * @return {Object[]}271 */272async function getMatchingBuildspec(targetPath) {273	let indexFiles = [];274	targetPath = path.resolve(process.env.INIT_CWD, targetPath);275	if (lstatSync(targetPath).isFile()) {276		indexFiles = indexFiles.concat(targetPath);277	}278	if (!indexFiles.length) {279		const files = readdirSync(targetPath, { encoding: 'utf8' });280		indexFiles = indexFiles.concat(281			targetPath,282			files.map((file) => path.join(targetPath, file)).filter((path) => lstatSync(path).isDirectory())283		);284	}285	const entries = await Promise.all(286		indexFiles.map(async (entryFile) => {287			const filter = createFilter([/\.(jsx?|tsx?|(le|sa|sc|c)ss)$/]);288			if (entryFile.includes('.build')) {289				return null;290			}291			if (!filter(entryFile) && !lstatSync(entryFile).isDirectory()) {292				return null;293			}294			const spec = await buildspec(entryFile);295			if (spec && new RegExp(`${spec.buildDir}(/|$)`).test(entryFile)) {296				return null;297			}298			return spec;299		})300	);301	return entries.filter(Boolean);...

Full Screen

Full Screen

build_all.js

Source:build_all.js Github

copy

Full Screen

1/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,2regexp:true, undef:true, strict:true, trailing:true, white:true */3/*global X:true, Backbone:true, _:true, XM:true, XT:true*/4var _              = require('underscore'),5    async          = require('async'),6    build_database = require("./build_database"),7    buildDatabase  = build_database.buildDatabase,8    buildClient    = require("./build_client").buildClient,9    dataSource     = require('../../node-datasource/lib/ext/datasource').dataSource,10    exec           = require('child_process').exec,11    fs             = require('fs'),12    path           = require('path'),13    unregister     = build_database.unregister,14    winston        = require('winston');15/**16 * This is the point of entry for both the lightweight CLI entry-point and17 * programmatic calls to build, such as from mocha. Most of the work in this18 * file is in determining what the defaults mean. For example, if the19 * user does not specify an extension, we install the core and all registered20 * extensions, which requires a call to xt.ext.21 *22 * We delegate the work of actually building the database and building the23 * client to build_database.js and build_client.js.24 */25(function () {26  "use strict";27  var creds;28  exports.build = function build(options, callback) {29    var buildSpecs = {},30        databases = [],31        extension,32        config,33      // Resolve the correct path for file. "/direct/path/" vs "../../relative"34        resolvePath = function (f) {35          var resolvedPath;36          if (f && f.substring(0, 1) === '/') {37            resolvedPath = f;38          } else if (f) {39            resolvedPath = path.join(process.cwd(), f);40          }41          return resolvedPath;42        },43        // List registered extensions in database & append core dirs to list44        getRegisteredExtensions = function (database, callback) {45          var result,46              credsClone = JSON.parse(JSON.stringify(creds)),47              existsSql = "select relname from pg_class where relname = 'ext'",48              extSql = "SELECT * FROM xt.ext ORDER BY ext_load_order",49              adaptExtensions = function (err, res) {50                if (err) {51                  callback(err);52                  return;53                }54                var paths = _.map(res.rows, function (row) {55                  var location = row.ext_location,56                      name = row.ext_name,57                      extPath;58                  if (location === '/extensions') {59                    extPath = path.join(__dirname, "../../lib/extensions", name);60                  }61                  return extPath;62                });63                // Add orm to extensions paths.64                paths.unshift(path.join(__dirname, "../../lib/orm")); // lib path65                callback(null, {66                  extensions: paths,67                  database: database,68                  keepSql: options.keepSql,69                  wipeViews: options.wipeViews,70                  clientOnly: options.clientOnly,71                  databaseOnly: options.databaseOnly,72                  queryDirect: options.queryDirect73                });74              };75          credsClone.database = database;76          dataSource.query(existsSql, credsClone, function (err, res) {77            if (err) {78              callback(err);79              return;80            }81            if (res.rowCount === 0) {82              // xt.ext doesn't exist, because this is probably a brand-new DB.83              // No problem! Give them empty set.84              adaptExtensions(null, { rows: [] });85            } else {86              dataSource.query(extSql, credsClone, adaptExtensions);87            }88          });89        },90        // Build the application according to the buildSpecs91        buildToSpec = function (specs, creds, buildCallback) {92          buildClient(specs, function (err, res) {93            if (err) {94              buildCallback(err);95              return;96            }97            buildDatabase(specs, creds, function (databaseErr, databaseRes) {98              var returnMessage;99              if (databaseErr && specs[0].wipeViews) {100                buildCallback(databaseErr);101                return;102              } else if (databaseErr) {103                buildCallback("Build failed. Try wiping the views next time by running me with the -w flag.");104                return;105              }106              returnMessage = "\n";107              _.each(specs, function (spec) {108                returnMessage += "Database: " + spec.database + '\nDirectories:\n';109                _.each(spec.extensions, function (ext) {110                  returnMessage += '  ' + ext + '\n';111                });112              });113              buildCallback(null, "Build succeeded." + returnMessage);114            });115          });116        };117    /**118     * Go through the commander options and build the app accordingly.119     *120     *   -b, --backup [/path/to/the.backup], Location of database backup file. Must be used with the -i flag.121     *   -c, --config [/path/to/alternate_config.js], Location of datasource config file. [config.js]122     *   -d, --database [database name], Use specific database. [All databases in config file.]123     *   -e, --extension [/path/to/extension], Extension to build. [Core plus all extensions registered for the database.]124     *   -i, --initialize, Initialize database. Must be used with the -b flag.125     *   -k, --keepsql, Do not delete the temporary sql files that represent the payload of the build.126     *   -q, --querydirect, Query the database directly, without delegating to psql.127     *   -u, --unregister, Unregister an extension.128     *   -w, --wipeviews, Drop the views and the orm registrations pre-emptively.129     *   -y, --clientonly, Only rebuild the client.130     *   -z, --databaseonly', Only rebuild the database.131     */132    // Load the application configuration config.js.133    var resolvedPath = resolvePath(options.config);134    if (resolvedPath) {135      config = require(resolvedPath);136    } else {137      config = require(path.join(__dirname, "../../node-datasource/config.js"));138    }139    // Set Database Credentials140    creds = config.databaseServer;141    creds.host = creds.hostname; // adapt our lingo to node-postgres lingo142    creds.username = creds.user; // adapt our lingo to orm installer lingo143    // Build all databases in node-datasource/config.js unless the user set.144    if (options.database) {145      databases.push(options.database);146    } else {147      databases = config.datasource.databases;148    }149    // The user should set both clientOnly & databaseOnly flags. Warn them!150    if (options.clientOnly && options.databaseOnly) {151      callback("You set both clientOnly & databaseOnly flags. Use only one.");152    }153    // Initialize the database. This is serious business, and we only do it if154    // the user does all the arguments correctly. Must be on one database only,155    // with no extensions, with the initialize flag, and with a backup file.156    if (157        options.initialize &&158        options.backup &&159        options.database &&160        !options.extension161    ) {162      buildSpecs.database = options.database;163      buildSpecs.backup = resolvePath(options.backup);164      buildSpecs.initialize = true;165      buildSpecs.keepSql = options.keepSql;166      buildSpecs.wipeViews = options.wipeViews;167      buildSpecs.clientOnly = options.clientOnly;168      buildSpecs.databaseOnly = options.databaseOnly;169      buildSpecs.queryDirect = options.queryDirect;170      buildSpecs.extensions = [171        path.join(__dirname, '../../lib/orm')172      ];173      buildToSpec([buildSpecs], creds, callback);174    }175    // Alert the user they must also specify a database.176    else if (options.initialize || options.backup) {177      callback(178        "You want to initialize the database with a backup but you didn't " +179        "tell us which database to use. Specifiy the database with the -d flag."180      );181    }182    // The user has specified an extension to build or unregister.183    else if (options.extension) {184      buildSpecs = _.map(databases, function (database) {185        var extension = resolvePath(options.extension);186        return {187          database: database,188          keepSql: options.keepSql,189          wipeViews: options.wipeViews,190          clientOnly: options.clientOnly,191          databaseOnly: options.databaseOnly,192          queryDirect: options.queryDirect,193          extensions: [extension]194        };195      });196      if (options.unregister) {197        unregister(buildSpecs, creds, callback);198      } else {199        // synchronous build200        buildToSpec(buildSpecs, creds, callback);201      }202    }203    // Build all registered extensions for the database204    else {205      async.map(databases, getRegisteredExtensions, function (err, results) {206        // asynchronous...207        buildToSpec(results, creds, callback);208      });209    }210  };...

Full Screen

Full Screen

gulp.config.js

Source:gulp.config.js Github

copy

Full Screen

1module.exports = function() {2  var ts = '**/*.ts';3  var js = '**/*.js';4  var specs = '**/*.specs.ts';5  var htmls = '**/*.html';6  var root = './';7  var src = root + 'src/';8  var srcWithOutRoot = 'src/'9  var build = root + 'build/';10  var temp = root + '.tmp/';11  var index = src + 'index.html';12  var wiredep = require('wiredep');13  var report = './report/';14  var bowerFiles = wiredep({15    devDependencies: true16  })['js'];17  var buildSpecs = src + 'specs/';18  var buildJs = build + js;19  var specRunnerFile = '/specs/specs.html';20  var specRunner = src + specRunnerFile;21  var config = {22    /**23     * Files paths24     */25    sourceTs: [26      srcWithOutRoot + ts,27      '!' + srcWithOutRoot + specs28    ],29    sourceHtmls: [30      src + htmls,31      '!' + index,32      '!' + specRunner33    ],34    sourceSpecs: [35      srcWithOutRoot + 'specs/' + specs36    ],37    build: './build/',38    buildTs: build + ts,39    buildJs: buildJs,40    buildHtmls: build + htmls,41    buildSpecs: buildSpecs,42    src: src,43    root: root,44    fonts: './bower_components/font-awesome/fonts/**/*.*',45    images: src + 'images/**/*.*',46    compiledJs: [47      build + '**/*.module.js',48      build + js49    ],50    css: temp + 'styles.css',51    buildMaps: build + js + '.map',52    configTs: [53      './*.ts'54    ],55    temp: temp,56    less: src + 'styles/styles.less',57    index: index,58    buildIndex: build + 'index.html',59    /**60    Caches61    */62    cache: {63      tsLinted: 'tsLinted',64      tsCompiled: 'tsCompiled',65      tsSpecCompiled: 'tsSpecCompiled',66      tsCopy: 'tsCopy',67      htmlLinted: 'htmlLinted',68      htmlCopy: 'htmlCopy'69    },70    /**71    + TSC options72    */73    tsc: {74      module: 'commonjs',75      declarationFiles: true,76      emitError: false77    },78    /**79     * SourceMaps Options80     **/81    sourceMaps: {82      pathToWrite: '../build',83      configMaps: {84        includeContent: false,85        sourceRoot: '/build/app'86      }87    },88    sourceMapsForSpecs: {89      pathToWrite: '/',90      configMaps: {91        includeContent: false,92        sourceRoot: '/src/'93      }94    },95/**96     * HTML Hint Options97     * /98     */99    htmlHintOptions: {100        'attr-lowercase': false,101        'tagname-lowercase': true,102        'attr-value-double-quotes': true,103        'doctype-first': true,104        'tag-pair': true,105        'spec-char-escape': true,106        'id-unique': true,107        'src-not-empty': true,108        'attr-no-duplication': true,109        'title-require': false110    },111    /**112     * Bower and NPM locations113     */114    bower: {115      json: require('./bower.json'),116      directory: './bower_components/',117      ignorePath: '../..'118    },119    packages: [120      './package.json',121      './bower.json'122    ],123    /**124     * optimized files125     */126    optimized: {127      app: 'app.js',128      lib: 'lib.js'129    },130    /**131     * template cache132     */133    templateCache: {134      file: 'templates.js',135      options: {136        module: 'app.core',137        standAlone: false138      }139    },140    /**141     * Karma and testing settings142     */143    specHelpers: [src + 'test-helpers/*.*'],144    serverIntegrationSpecs: [src + 'specsIntegration/**/*.spec.*'],145    compiledSpecs: buildSpecs + '**/*.js',146    /**147     * specs.html, our HTML spec runner148     */149    specRunner: specRunner,150    specRunnerFile: specRunnerFile,151    /*152     * bootlint settings153     */154    bootlint: {155      disableRules: ['W001', 'W005']156    },157    testlibraries: [158      'node_modules/mocha/mocha.js',159      'node_modules/chai/chai.js',160      'node_modules/mocha-clean/index.js',161      'node_modules/sinon-chai/lib/sinon-chai.js'162    ],163    /**164     * Nancy Settings165     */166    defaultPort: 3000,167    subdomain: 'unicron'168  };169  config.getWiredepDefaultOptions = function() {170    var options = {171      bowerJson: config.bower.json,172      directory: config.bower.directory,173      ignorePath: config.bower.ignorePath174    };175    return options;176  };177  config.karma = getKarmaOptions();178  return config;179  function getKarmaOptions() {180    var options = {181      files: [].concat(182        bowerFiles,183        config.specHelpers,184        build + '**/*.module.js',185        build + '**/*.js',186        buildSpecs + '**/*.js',187        buildSpecs + '**/**/*.js',188        temp + config.templateCache.file,189        config.serverIntegrationSpecs190      ),191      exclude: [],192      coverage: {193        dir: report + 'coverage',194        reporters: [{195          type: 'html',196          subdir: 'report-html'197        }, {198          type: 'lcov',199          subdir: 'report-lcov'200        }, {201          type: 'text-summary'202        }]203      },204      preprocessors: {}205    };206    options.preprocessors[buildSpecs + '**/!(*.spec)+(.js)'] = ['coverage'];207    options.preprocessors[buildSpecs + '**/**/!(*.spec)+(.js)'] = ['coverage'];208    options.preprocessors[buildJs] = ['coverage'];209    return options;210  }...

Full Screen

Full Screen

navigationUI.js

Source:navigationUI.js Github

copy

Full Screen

1function NavigationUI(buildSpecs, container) {2    const _NavigationUI = this;34    /* buildSpecs: 5     *  display:[composite, single]6     *  bookLength:number7     */8    this.specs = {9        //  -- in init, to throw errors and stuff10        // display: buildSpecs.display,11        // length: bookLength,12        // initShown: true/false13        display: "",14        bookLength: 0,15        initShown: true,16        initEnabled: true,17        startPage: 0,18        lastPageSpread: true19    }2021    this.elems = {22        cont: false,23        next: false,24        prev: false,25        goto: false,26        gotoSelect: false,27        gotoCover: false,28    }2930    this.getCurPageString = function (updatePage) {31        if (updatePage == 0) {32            return "COVER";33        } else {34            if (this.specs.display !== "composite") {35                return updatePage;36            } else {37                if (updatePage == this.specs.bookLength - 138                        && !this.specs.lastPageSpread) {39                    return (this.specs.bookLength - 1) * 2;40                } else {41                    let firstNum = updatePage * 2;42                    return firstNum + "-" + (1 + firstNum);43                }44            }45        }46    }4748    this.enable = function () {49        $(".navigationUI .next").removeClass("disabled");50        $(".navigationUI .goto").removeClass("disabled");51        $(".navigationUI .previous").removeClass("disabled");52    }53    this.disable = function () {54        $(".navigationUI .next").addClass("disabled");55        $(".navigationUI .goto").addClass("disabled");56        $(".navigationUI .previous").addClass("disabled");57    }58    this.hide = function () {59        $(".navigationUI").css("display", "none");60    }61    this.show = function () {62        $(".navigationUI").css("display", "inline-block");63    }6465    this.update = function (newPage) {66        // Update goto index6768        // TODO: Use this.elems not $ shit69        // Update goto cover70        $(".goto p.cover").html(this.getCurPageString(newPage));7172        // In case page changed through sequencing73        if ($(".goto select option:selected")[0])74            $(".goto select option:selected")[0].removeAttribute("selected");75        if ($(".goto select option.page_" + newPage)[0])76            $(".goto select option.page_" + newPage)[0].setAttribute("selected", "");7778        // Disable next if no next79        if (newPage + 1 == this.specs.bookLength) {80            $(".navigationUI .next").addClass("noTurn");81        } else {82            $(".navigationUI .next").removeClass("noTurn");83        }84        // Disable prev if no prev85        if (newPage == 0) {86            $(".navigationUI .previous").addClass("noTurn");87        } else {88            $(".navigationUI .previous").removeClass("noTurn");89        }90    }9192    this.init = function () {93        let errMessage = "";94        for (let prop in this.specs) {95            if (typeof buildSpecs[prop] == "undefined") {96                errMessage += "Missing buildSpecs property '" + prop + "'\r\n";97            } else {98                this.specs[prop] = buildSpecs[prop];99            }100        }101        if (errMessage !== "") {102            error("fatal", "navigationUI", errMessage + "\r\n" + "Check top of constructor for how to init");103        } else {104            this.specs.display = buildSpecs.display;105            this.specs.length = buildSpecs.bookLength;106107            let options = "<option class='page_0'>COVER</option>";108            for (let p = 1; p < this.specs.bookLength; p++) {109                options += "\r\n<option class='page_" + p + "'>" + this.getCurPageString(p) + "</option>";110            }111            container.append(`112<div class='navigationUI'>113    <div class='previous'>114        <img />115    </div>116    <div class='goto'>117        <p class='cover'>COVER</p>118        <select class='dropdown'>119            ${options}120        </select>121    </div>122    <div class='next'>123        <img />124    </div>125</div>`);126            this.elems.cont = container.find(".navigationUI");127            // TODO: Put elems here128129            // throw away props, only used here, no need to transfer over to this.specs130            if (!buildSpecs.initShown) {131                this.hide();132            }133134            this.update(this.specs.startPage);135            this.disable();136137        }138    };139140    this.init();
...

Full Screen

Full Screen

hex.js

Source:hex.js Github

copy

Full Screen

...11    case "build-editor":12        buildEditor();13        break;14    case "build-spec":15        buildSpecs();16        break;17    case "watch-editor":18        watchEditor();19        break;20    case "watch-spec":21        watchSpec();22        break;23}24function watchEditor() {25    const watcher = chokidar.watch(path.resolve("./src"), {26        persistent: true27    });28    //todo stupid mode! make this cached per file29    watcher.on('ready', function () {30        buildEditor();31        watcher32            .on('add', function (filePath) {33                buildEditor();34            })35            .on('change', function (filePath) {36                buildEditor();37            })38            .on('unlink', function (filePath) {39                buildEditor();40            });41    });42}43function watchSpec() {44    const watcher = chokidar.watch([path.resolve("./src"), path.resolve("./spec")], {45        ignored: /node_modules\/*/,46        persistent: true47    });48    /**/49    //todo stupid mode! make this cached per file50    watcher.on('ready', function () {51        buildSpecs();52        watcher53            .on('add', function (filePath) {54                buildSpecs();55            })56            .on('change', function (filePath) {57                if(filePath.indexOf("spec_bundle") !== -1) {58                    return;59                }60                buildSpecs();61            })62            .on('unlink', function (filePath) {63                buildSpecs();64            });65    });66}67function buildEditor() {68    var start = Date.now();69    const dtsFiles = getAllFileNames([70        "./src",71        "./node_modules/@types"72    ],dtsRegex);73    const files = [74        path.resolve("./src/editor/main.tsx"),75    ].concat(dtsFiles);76    compiler = new Compiler(files);77    compiler.addDecoratorMutator(require("../mutators/input_event_mutator"));78    compiler.addDecoratorMutator(require("../mutators/tag_type_mutator"));79    compiler.addDecoratorMutator(require("../mutators/unique_component_mutator"));80    compiler.addDecoratorMutator(require("../mutators/require_component_mutator"));81    compiler.addDecoratorMutator(require("../mutators/app_event_mutator"));82    compiler.addVisitor(require("../mutators/inline_visitor"));83    var StructVisitor = require("hex-compiler/src/struct_visitor.js").StructVisitor;84    compiler.addVisitor(new StructVisitor());85    const compileResult = compiler.compile();86    if (compileResult) {87        fs.writeFileSync(path.resolve("./build/editor.js"), compileResult);88    }89    console.log("compiled in", (Date.now() - start), "ms");90}91function buildSpecs() {92    var start = Date.now();93    const specRegex = /_spec.ts$/;94    const dtsFiles = getAllFileNames([95        "./src",96        "./spec",97        "./node_modules/@types",98    ], dtsRegex);99    const files = getAllFileNames("./spec", specRegex).concat(dtsFiles);100    compiler = new Compiler(files);101    compiler.addDecoratorMutator(require("../mutators/input_event_mutator"));102    compiler.addDecoratorMutator(require("../mutators/tag_type_mutator"));103    compiler.addDecoratorMutator(require("../mutators/unique_component_mutator"));104    compiler.addDecoratorMutator(require("../mutators/require_component_mutator"));105    compiler.addDecoratorMutator(require("../mutators/app_event_mutator"));...

Full Screen

Full Screen

sns.js

Source:sns.js Github

copy

Full Screen

1/**2 * @module sns3 * @overview implements functionality related to parsing github events from sns4 */5import Ajv from 'ajv';6import attempt from 'lodash.attempt';7import get from 'lodash.get';8export const inject = {9  name: 'sns',10  require: ['config'],11};12export default function (config) {13  const ajv = new Ajv({14    useDefaults: true,15    coerceTypes: true,16  });17  const eventSourceARN = config.get('sns.topic_arn');18  // compile buildspec validation functions19  let buildspecs = config.get('github.buildspecs', {});20  buildspecs = Object.keys(buildspecs).reduce((acc, spec) => {21    acc[spec] = ajv.compile(buildspecs[spec]);22    return acc;23  }, {});24  /**25   * Extract github events from lambda event26   * @param  {Object}   e           - lambda event27   * @param  {Object}   options     - options28   * @param  {Object}   options.log - logger29   * @return {Object}30   */31  function extractPayloads(e, { log }) {32    return get(e, 'Records', [])33      .reduce((acc, record) => {34        // filter out records that did not originate from the our target input stream35        if (record.EventSource !== 'aws:sns' || record.Sns.TopicArn !== eventSourceARN) {36          log.warn({ record: JSON.stringify(record) }, 'invalid event source');37          return acc;38        }39        // filter out records that can not be parsed40        const parsed = attempt(() => JSON.parse(record.Sns.Message));41        if (parsed instanceof Error) {42          log.warn({ record: JSON.stringify(record) }, 'parse error');43          return acc;44        }45        parsed.eventName = record.Sns.Subject;46        // ensure buildspec match47        const buildspecOverride = matchBuildspec(parsed);48        if (!buildspecOverride) {49          log.warn({ record: JSON.stringify(record) }, 'no buildspec match');50          return acc;51        }52        parsed.buildspecOverride = buildspecOverride;53        acc.push(parsed);54        return acc;55      }, []);56  }57  /**58   * Find the appropriate buildspec based on event schemas59   * @param  {Object} payload - parsed github event payload60   * @return {String}61   */62  function matchBuildspec(payload) {63    return Object.keys(buildspecs).find(spec => buildspecs[spec](payload));64  }65  return {66    extractPayloads,67    matchBuildspec,68  };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { CypressBuilder } = require('@nrwl/cypress');2const builder = new CypressBuilder();3builder.buildSpecs({4  options: {5  },6});7MIT © [nrwl](

Full Screen

Using AI Code Generation

copy

Full Screen

1const {CypressBuilder} = require('@cypress/browser-tools');2const cypressBuilder = new CypressBuilder();3cypressBuilder.buildSpecs('cypress/integration/spec1.js', 'cypress/integration/spec2.js').then((specs) => {4  console.log(specs);5});6### `buildSpecs(specs)`7### `buildProject(projectRoot)`8### `getVersion()`9### `getInstallDir()`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { CypressBuilder } = require("@badeball/cypress-browserify-webpack-preprocessor");2const builder = new CypressBuilder();3builder.buildSpecs("cypress/integration", "cypress/integration", "cypress/support", "cypress/support");4const { CypressBuilder } = require("@badeball/cypress-browserify-webpack-preprocessor");5const builder = new CypressBuilder();6builder.buildWebpackConfig("cypress/integration", "cypress/integration", "cypress/support", "cypress/support");7const browserify = require("@cypress/browserify-preprocessor");8module.exports = (on, config) => {9  const options = browserify.defaultOptions;10  options.browserifyOptions.plugin.unshift(["tsify"]);11  on("file:preprocessor", browserify(options));12};13{14}15{16  "compilerOptions": {17  }18}19import "./commands";20describe("My First Test", () => {21  it("Visits the Kitchen Sink", () => {22    cy.contains("type").click();23    cy.url().should("include", "/commands/actions");24    cy.get(".action-email").type("

Full Screen

Using AI Code Generation

copy

Full Screen

1let reporter = require('cypress-testrail-reporter');2let specFiles = Cypress.specs;3let specFilesArray = [];4specFiles.forEach(function (item) {5    specFilesArray.push(item.name);6});7reporter.createRun('My Project', specFilesArray, 'My Run');8let reporter = require('cypress-testrail-reporter');9reporter.publishResults('My Project', 'My Run');10let reporter = require('cypress-testrail-reporter');11reporter.publishResults('My Project', 'My Run', {12});

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const path = require('path');3const specs = fs.readdirSync('./cypress/integration').filter((file) => {4  return file.match(/\.spec\.js$/);5});6const buildSpecs = (specs) => {7  let specsString = '';8  specs.forEach((spec) => {9    specsString += `import './${spec}';\n`;10  });11  return specsString;12};13fs.writeFileSync(14  path.join(__dirname, 'cypress', 'integration', 'index.js'),15  buildSpecs(specs)16);

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful