Best JavaScript code snippet using stryker-parent
optimize.js
Source:optimize.js
1/*jslint plusplus: true, nomen: true, regexp: true */2/*global define: false */3define([ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',4 'pragma', 'uglifyjs',5 'source-map'],6function (lang, logger, envOptimize, file, parse,7 pragma, uglify,8 sourceMap) {9 'use strict';10 var optimize,11 cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,12 cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,13 cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,14 protocolRegExp = /^\w+:/,15 SourceMapGenerator = sourceMap.SourceMapGenerator,16 SourceMapConsumer =sourceMap.SourceMapConsumer;17 /**18 * If an URL from a CSS url value contains start/end quotes, remove them.19 * This is not done in the regexp, since my regexp fu is not that strong,20 * and the CSS spec allows for ' and " in the URL if they are backslash escaped.21 * @param {String} url22 */23 function cleanCssUrlQuotes(url) {24 //Make sure we are not ending in whitespace.25 //Not very confident of the css regexps above that there will not be ending26 //whitespace.27 url = url.replace(/\s+$/, "");28 if (url.charAt(0) === "'" || url.charAt(0) === "\"") {29 url = url.substring(1, url.length - 1);30 }31 return url;32 }33 function fixCssUrlPaths(fileName, path, contents, cssPrefix) {34 return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {35 var firstChar, hasProtocol, parts, i,36 fixedUrlMatch = cleanCssUrlQuotes(urlMatch);37 fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");38 //Only do the work for relative URLs. Skip things that start with / or #, or have39 //a protocol.40 firstChar = fixedUrlMatch.charAt(0);41 hasProtocol = protocolRegExp.test(fixedUrlMatch);42 if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {43 //It is a relative URL, tack on the cssPrefix and path prefix44 urlMatch = cssPrefix + path + fixedUrlMatch;45 } else if (!hasProtocol) {46 logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);47 }48 //Collapse .. and .49 parts = urlMatch.split("/");50 for (i = parts.length - 1; i > 0; i--) {51 if (parts[i] === ".") {52 parts.splice(i, 1);53 } else if (parts[i] === "..") {54 if (i !== 0 && parts[i - 1] !== "..") {55 parts.splice(i - 1, 2);56 i -= 1;57 }58 }59 }60 return "url(" + parts.join("/") + ")";61 });62 }63 /**64 * Inlines nested stylesheets that have @import calls in them.65 * @param {String} fileName the file name66 * @param {String} fileContents the file contents67 * @param {String} cssImportIgnore comma delimited string of files to ignore68 * @param {String} cssPrefix string to be prefixed before relative URLs69 * @param {Object} included an object used to track the files already imported70 */71 function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {72 //Find the last slash in the name.73 fileName = fileName.replace(lang.backSlashRegExp, "/");74 var endIndex = fileName.lastIndexOf("/"),75 //Make a file path based on the last slash.76 //If no slash, so must be just a file name. Use empty string then.77 filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",78 //store a list of merged files79 importList = [],80 skippedList = [];81 //First make a pass by removing any commented out @import calls.82 fileContents = fileContents.replace(cssCommentImportRegExp, '');83 //Make sure we have a delimited ignore list to make matching faster84 if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {85 cssImportIgnore += ",";86 }87 fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {88 //Only process media type "all" or empty media type rules.89 if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {90 skippedList.push(fileName);91 return fullMatch;92 }93 importFileName = cleanCssUrlQuotes(importFileName);94 //Ignore the file import if it is part of an ignore list.95 if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {96 return fullMatch;97 }98 //Make sure we have a unix path for the rest of the operation.99 importFileName = importFileName.replace(lang.backSlashRegExp, "/");100 try {101 //if a relative path, then tack on the filePath.102 //If it is not a relative path, then the readFile below will fail,103 //and we will just skip that import.104 var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,105 importContents = file.readFile(fullImportFileName),106 importEndIndex, importPath, flat;107 //Skip the file if it has already been included.108 if (included[fullImportFileName]) {109 return '';110 }111 included[fullImportFileName] = true;112 //Make sure to flatten any nested imports.113 flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);114 importContents = flat.fileContents;115 if (flat.importList.length) {116 importList.push.apply(importList, flat.importList);117 }118 if (flat.skippedList.length) {119 skippedList.push.apply(skippedList, flat.skippedList);120 }121 //Make the full import path122 importEndIndex = importFileName.lastIndexOf("/");123 //Make a file path based on the last slash.124 //If no slash, so must be just a file name. Use empty string then.125 importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";126 //fix url() on relative import (#5)127 importPath = importPath.replace(/^\.\//, '');128 //Modify URL paths to match the path represented by this file.129 importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);130 importList.push(fullImportFileName);131 return importContents;132 } catch (e) {133 logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);134 return fullMatch;135 }136 });137 if (cssPrefix && topLevel) {138 //Modify URL paths to match the path represented by this file.139 fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);140 }141 return {142 importList : importList,143 skippedList: skippedList,144 fileContents : fileContents145 };146 }147 optimize = {148 /**149 * Optimizes a file that contains JavaScript content. Optionally collects150 * plugin resources mentioned in a file, and then passes the content151 * through an minifier if one is specified via config.optimize.152 *153 * @param {String} fileName the name of the file to optimize154 * @param {String} fileContents the contents to optimize. If this is155 * a null value, then fileName will be used to read the fileContents.156 * @param {String} outFileName the name of the file to use for the157 * saved optimized content.158 * @param {Object} config the build config object.159 * @param {Array} [pluginCollector] storage for any plugin resources160 * found.161 */162 jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {163 if (!fileContents) {164 fileContents = file.readFile(fileName);165 }166 fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);167 file.saveUtf8File(outFileName, fileContents);168 },169 /**170 * Optimizes a file that contains JavaScript content. Optionally collects171 * plugin resources mentioned in a file, and then passes the content172 * through an minifier if one is specified via config.optimize.173 *174 * @param {String} fileName the name of the file that matches the175 * fileContents.176 * @param {String} fileContents the string of JS to optimize.177 * @param {Object} [config] the build config object.178 * @param {Array} [pluginCollector] storage for any plugin resources179 * found.180 */181 js: function (fileName, fileContents, outFileName, config, pluginCollector) {182 var optFunc, optConfig,183 parts = (String(config.optimize)).split('.'),184 optimizerName = parts[0],185 keepLines = parts[1] === 'keepLines',186 licenseContents = '';187 config = config || {};188 //Apply pragmas/namespace renaming189 fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);190 //Optimize the JS files if asked.191 if (optimizerName && optimizerName !== 'none') {192 optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];193 if (!optFunc) {194 throw new Error('optimizer with name of "' +195 optimizerName +196 '" not found for this environment');197 }198 optConfig = config[optimizerName] || {};199 if (config.generateSourceMaps) {200 optConfig.generateSourceMaps = !!config.generateSourceMaps;201 optConfig._buildSourceMap = config._buildSourceMap;202 }203 try {204 if (config.preserveLicenseComments) {205 //Pull out any license comments for prepending after optimization.206 try {207 licenseContents = parse.getLicenseComments(fileName, fileContents);208 } catch (e) {209 throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());210 }211 }212 fileContents = licenseContents + optFunc(fileName,213 fileContents,214 outFileName,215 keepLines,216 optConfig);217 if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {218 config._buildSourceMap = optConfig._buildSourceMap;219 }220 } catch (e) {221 if (config.throwWhen && config.throwWhen.optimize) {222 throw e;223 } else {224 logger.error(e);225 }226 }227 } else {228 if (config._buildSourceMap) {229 config._buildSourceMap = null;230 }231 }232 return fileContents;233 },234 /**235 * Optimizes one CSS file, inlining @import calls, stripping comments, and236 * optionally removes line returns.237 * @param {String} fileName the path to the CSS file to optimize238 * @param {String} outFileName the path to save the optimized file.239 * @param {Object} config the config object with the optimizeCss and240 * cssImportIgnore options.241 */242 cssFile: function (fileName, outFileName, config) {243 //Read in the file. Make sure we have a JS string.244 var originalFileContents = file.readFile(fileName),245 flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),246 //Do not use the flattened CSS if there was one that was skipped.247 fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,248 startIndex, endIndex, buildText, comment;249 if (flat.skippedList.length) {250 logger.warn('Cannot inline @imports for ' + fileName +251 ',\nthe following files had media queries in them:\n' +252 flat.skippedList.join('\n'));253 }254 //Do comment removal.255 try {256 if (config.optimizeCss.indexOf(".keepComments") === -1) {257 startIndex = 0;258 //Get rid of comments.259 while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {260 endIndex = fileContents.indexOf("*/", startIndex + 2);261 if (endIndex === -1) {262 throw "Improper comment in CSS file: " + fileName;263 }264 comment = fileContents.substring(startIndex, endIndex);265 if (config.preserveLicenseComments &&266 (comment.indexOf('license') !== -1 ||267 comment.indexOf('opyright') !== -1 ||268 comment.indexOf('(c)') !== -1)) {269 //Keep the comment, just increment the startIndex270 startIndex = endIndex;271 } else {272 fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);273 startIndex = 0;274 }275 }276 }277 //Get rid of newlines.278 if (config.optimizeCss.indexOf(".keepLines") === -1) {279 fileContents = fileContents.replace(/[\r\n]/g, " ");280 fileContents = fileContents.replace(/\s+/g, " ");281 fileContents = fileContents.replace(/\{\s/g, "{");282 fileContents = fileContents.replace(/\s\}/g, "}");283 } else {284 //Remove multiple empty lines.285 fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");286 fileContents = fileContents.replace(/(\n)+/g, "\n");287 }288 //Remove unnecessary whitespace289 if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {290 //Remove leading and trailing whitespace from lines291 fileContents = fileContents.replace(/^[ \t]+/gm, "");292 fileContents = fileContents.replace(/[ \t]+$/gm, "");293 //Remove whitespace after semicolon, colon, curly brackets and commas294 fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");295 //Remove whitespace before opening curly brackets296 fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");297 //Truncate double whitespace298 fileContents = fileContents.replace(/([ \t])+/g, "$1");299 //Remove empty lines300 fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');301 }302 } catch (e) {303 fileContents = originalFileContents;304 logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);305 }306 file.saveUtf8File(outFileName, fileContents);307 //text output to stdout and/or written to build.txt file308 buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";309 flat.importList.push(fileName);310 buildText += flat.importList.map(function(path){311 return path.replace(config.dir, "");312 }).join("\n");313 return {314 importList: flat.importList,315 buildText: buildText +"\n"316 };317 },318 /**319 * Optimizes CSS files, inlining @import calls, stripping comments, and320 * optionally removes line returns.321 * @param {String} startDir the path to the top level directory322 * @param {Object} config the config object with the optimizeCss and323 * cssImportIgnore options.324 */325 css: function (startDir, config) {326 var buildText = "",327 importList = [],328 shouldRemove = config.dir && config.removeCombined,329 i, fileName, result, fileList;330 if (config.optimizeCss.indexOf("standard") !== -1) {331 fileList = file.getFilteredFileList(startDir, /\.css$/, true);332 if (fileList) {333 for (i = 0; i < fileList.length; i++) {334 fileName = fileList[i];335 logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);336 result = optimize.cssFile(fileName, fileName, config);337 buildText += result.buildText;338 if (shouldRemove) {339 result.importList.pop();340 importList = importList.concat(result.importList);341 }342 }343 }344 if (shouldRemove) {345 importList.forEach(function (path) {346 if (file.exists(path)) {347 file.deleteFile(path);348 }349 });350 }351 }352 return buildText;353 },354 optimizers: {355 uglify: function (fileName, fileContents, outFileName, keepLines, config) {356 var result, existingMap, resultMap, finalMap, sourceIndex,357 uconfig = {},358 existingMapPath = outFileName + '.map',359 baseName = fileName && fileName.split('/').pop();360 config = config || {};361 lang.mixin(uconfig, config, true);362 uconfig.fromString = true;363 if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {364 uconfig.outSourceMap = baseName + '.map';365 if (config._buildSourceMap) {366 existingMap = JSON.parse(config._buildSourceMap);367 uconfig.inSourceMap = existingMap;368 } else if (file.exists(existingMapPath)) {369 uconfig.inSourceMap = existingMapPath;370 existingMap = JSON.parse(file.readFile(existingMapPath));371 }372 }373 logger.trace("Uglify file: " + fileName);374 try {375 //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');376 result = uglify.minify(fileContents, uconfig, baseName + '.src.js');377 if (uconfig.outSourceMap && result.map) {378 resultMap = result.map;379 if (!existingMap && !config._buildSourceMap) {380 file.saveFile(outFileName + '.src.js', fileContents);381 }382 fileContents = result.code;383 if (config._buildSourceMap) {384 config._buildSourceMap = resultMap;385 } else {386 file.saveFile(outFileName + '.map', resultMap);387 }388 } else {389 fileContents = result.code;390 }391 } catch (e) {392 throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());393 }394 return fileContents;395 }396 }397 };398 return optimize;...
pragma.js
Source:pragma.js
1/*jslint regexp: true, plusplus: true */2/*global define: false */3define(['parse', 'logger'], function (parse, logger) {4 'use strict';5 function Temp() {}6 function create(obj, mixin) {7 Temp.prototype = obj;8 var temp = new Temp(), prop;9 //Avoid any extra memory hanging around10 Temp.prototype = null;11 if (mixin) {12 for (prop in mixin) {13 if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {14 temp[prop] = mixin[prop];15 }16 }17 }18 return temp; // Object19 }20 var pragma = {21 conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,22 useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g,23 hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,24 configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,25 nsWrapRegExp: /\/\*requirejs namespace: true \*\//,26 apiDefRegExp: /var requirejs,\s*require,\s*define;/,27 defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,28 defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,29 defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,30 defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,31 defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,32 defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,33 defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/,34 defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/,35 amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,36 removeStrict: function (contents, config) {37 return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1');38 },39 namespace: function (fileContents, ns, onLifecycleName) {40 if (ns) {41 //Namespace require/define calls42 fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');43 fileContents = parse.renameNamespace(fileContents, ns);44 //Namespace define ternary use:45 fileContents = fileContents.replace(pragma.defineTernaryRegExp,46 "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");47 //Namespace define jquery use:48 fileContents = fileContents.replace(pragma.defineJQueryRegExp,49 "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");50 //Namespace has.js define use:51 fileContents = fileContents.replace(pragma.defineHasRegExp,52 "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");53 //Namespace async.js define use:54 fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp,55 "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd");56 //Namespace define checks.57 //Do these ones last, since they are a subset of the more specific58 //checks above.59 fileContents = fileContents.replace(pragma.defineCheckRegExp,60 "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");61 fileContents = fileContents.replace(pragma.defineStringCheckRegExp,62 "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");63 fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,64 "'function' === typeof " + ns + ".define && " + ns + ".define.amd");65 fileContents = fileContents.replace(pragma.defineExistsRegExp,66 "typeof " + ns + ".define !== 'undefined'");67 //Check for require.js with the require/define definitions68 if (pragma.apiDefRegExp.test(fileContents) &&69 fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {70 //Wrap the file contents in a typeof check, and a function71 //to contain the API globals.72 fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +73 "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +74 fileContents +75 "\n" +76 ns + ".requirejs = requirejs;" +77 ns + ".require = require;" +78 ns + ".define = define;\n" +79 "}\n}());";80 }81 //Finally, if the file wants a special wrapper because it ties82 //in to the requirejs internals in a way that would not fit83 //the above matches, do that. Look for /*requirejs namespace: true*/84 if (pragma.nsWrapRegExp.test(fileContents)) {85 //Remove the pragma.86 fileContents = fileContents.replace(pragma.nsWrapRegExp, '');87 //Alter the contents.88 fileContents = '(function () {\n' +89 'var require = ' + ns + '.require,' +90 'requirejs = ' + ns + '.requirejs,' +91 'define = ' + ns + '.define;\n' +92 fileContents +93 '\n}());';94 }95 }96 return fileContents;97 },98 /**99 * processes the fileContents for some //>> conditional statements100 */101 process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {102 /*jslint evil: true */103 var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,104 matches, type, marker, condition, isTrue, endRegExp, endMatches,105 endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,106 i, dep, moduleName, collectorMod,107 lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,108 //Legacy arg defined to help in dojo conversion script. Remove later109 //when dojo no longer needs conversion:110 kwArgs = pragmas;111 //Mix in a specific lifecycle scoped object, to allow targeting112 //some pragmas/has tests to only when files are saved, or at different113 //lifecycle events. Do not bother with kwArgs in this section, since114 //the old dojo kwArgs were for all points in the build lifecycle.115 if (onLifecycleName) {116 lifecyclePragmas = config['pragmas' + onLifecycleName];117 lifecycleHas = config['has' + onLifecycleName];118 if (lifecyclePragmas) {119 pragmas = create(pragmas || {}, lifecyclePragmas);120 }121 if (lifecycleHas) {122 hasConfig = create(hasConfig || {}, lifecycleHas);123 }124 }125 //Replace has references if desired126 if (hasConfig) {127 fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {128 if (hasConfig.hasOwnProperty(test)) {129 return !!hasConfig[test];130 }131 return match;132 });133 }134 if (!config.skipPragmas) {135 while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {136 //Found a conditional. Get the conditional line.137 lineEndIndex = fileContents.indexOf("\n", foundIndex);138 if (lineEndIndex === -1) {139 lineEndIndex = fileContents.length - 1;140 }141 //Increment startIndex past the line so the next conditional search can be done.142 startIndex = lineEndIndex + 1;143 //Break apart the conditional.144 conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);145 matches = conditionLine.match(pragma.conditionalRegExp);146 if (matches) {147 type = matches[1];148 marker = matches[2];149 condition = matches[3];150 isTrue = false;151 //See if the condition is true.152 try {153 isTrue = !!eval("(" + condition + ")");154 } catch (e) {155 throw "Error in file: " +156 fileName +157 ". Conditional comment: " +158 conditionLine +159 " failed with this error: " + e;160 }161 //Find the endpoint marker.162 endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");163 endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));164 if (endMatches) {165 endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;166 //Find the next line return based on the match position.167 lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);168 if (lineEndIndex === -1) {169 lineEndIndex = fileContents.length - 1;170 }171 //Should we include the segment?172 shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));173 //Remove the conditional comments, and optionally remove the content inside174 //the conditional comments.175 startLength = startIndex - foundIndex;176 fileContents = fileContents.substring(0, foundIndex) +177 (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +178 fileContents.substring(lineEndIndex + 1, fileContents.length);179 //Move startIndex to foundIndex, since that is the new position in the file180 //where we need to look for more conditionals in the next while loop pass.181 startIndex = foundIndex;182 } else {183 throw "Error in file: " +184 fileName +185 ". Cannot find end marker for conditional comment: " +186 conditionLine;187 }188 }189 }190 }191 //If need to find all plugin resources to optimize, do that now,192 //before namespacing, since the namespacing will change the API193 //names.194 //If there is a plugin collector, scan the file for plugin resources.195 if (config.optimizeAllPluginResources && pluginCollector) {196 try {197 deps = parse.findDependencies(fileName, fileContents);198 if (deps.length) {199 for (i = 0; i < deps.length; i++) {200 dep = deps[i];201 if (dep.indexOf('!') !== -1) {202 moduleName = dep.split('!')[0];203 collectorMod = pluginCollector[moduleName];204 if (!collectorMod) {205 collectorMod = pluginCollector[moduleName] = [];206 }207 collectorMod.push(dep);208 }209 }210 }211 } catch (eDep) {212 logger.error('Parse error looking for plugin resources in ' +213 fileName + ', skipping.');214 }215 }216 //Strip amdefine use for node-shared modules.217 if (!config.keepAmdefine) {218 fileContents = fileContents.replace(pragma.amdefineRegExp, '');219 }220 //Do namespacing221 if (onLifecycleName === 'OnSave' && config.namespace) {222 fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);223 }224 return pragma.removeStrict(fileContents, config);225 }226 };227 return pragma;...
index.js
Source:index.js
1const { exec } = require('child_process');2'use strict';3/* Blackbox test for the gitDescribe and gitDescribeSync functions4 * using operations on a real git repository.5 * Requires a git binary available in the executable path.6 * The test-repo directory must be writable.7 */8const path = require('path');9const fs = require('fs');10const os = require('os');11const expect = require('chai').expect;12const TestRepo = require('./lib/test-repo');13const repoDir = path.join(os.tmpdir(), 'test-repo');14const repo = new TestRepo(repoDir);15before(function() {16 repo.clean();17});18describe('appversion', function() {19 it('should skip when no package.json is found.', function(done) {20 exec('node dist/index.js --root=' + repoDir + ' --file=version-test.ts', (err, stdout, stderr) => {21 if (err) {22 done('Test failed: Could not execute command.');23 return;24 }25 if (stderr) {26 done(stderr);27 return;28 }29 expect(stdout).to.contains('Cannot find package.json in root path. Skipping...');30 done();31 });32 });33 it('should succeed with default settings and without a Git repository', function(done) {34 fs.mkdirSync(path.join(repoDir, 'src'), {recursive: true});35 fs.writeFileSync(path.join(repoDir, 'package.json'), '{"version": "1.0.0", "name": "test", "description": "test description"}');36 exec('node dist/index.js --root=' + repoDir, (err, stdout, stderr) => {37 if (err) {38 done('Test failed: Could not execute command.');39 return;40 }41 if (stderr) {42 done(stderr);43 return;44 }45 expect(stdout).to.match(/Writing version module to/);46 const outputFile = path.join(repoDir, 'src', '_versions.ts');47 if (!fs.existsSync(outputFile)) {48 done('File ' + outputFile + ' not found.');49 return;50 }51 const fileContents = fs.readFileSync(outputFile, 'utf8');52 // interface well format test53 expect(fileContents).to.contains('export interface TsAppVersion {'); // interface start54 expect(fileContents).to.contains('version: string;');55 expect(fileContents).to.contains('name: string;');56 expect(fileContents).to.contains('description?: string;');57 expect(fileContents).to.contains('versionLong?: string;');58 expect(fileContents).to.contains('versionDate: string;');59 expect(fileContents).to.contains('gitCommitHash?: string;');60 expect(fileContents).to.contains('gitCommitDate?: string;');61 expect(fileContents).to.contains('gitTag?: string;');62 expect(fileContents).to.contains('};\nexport const versions: TsAppVersion = {'); // interface end + obj start63 // data test64 expect(fileContents).to.contains('version: \'1.0.0\',');65 expect(fileContents).to.contains('name: \'test\',');66 expect(fileContents).to.contains('description: \'test description\',');67 expect(fileContents).to.contains('};\nexport default versions;\n'); // export default obj + file close68 expect(fileContents).not.to.contains('versionLong = \'1.0.0-');69 done();70 });71 });72 it('should succeed with default settings', function(done) {73 repo.init();74 fs.mkdirSync(path.join(repoDir, 'src'));75 fs.writeFileSync(path.join(repoDir, 'package.json'), '{"version": "1.0.0", "name": "test", "description": "test description"}');76 exec('node dist/index.js --root=' + repoDir, (err, stdout, stderr) => {77 if (err) {78 done('Test failed: Could not execute command.');79 return;80 }81 if (stderr) {82 done(stderr);83 return;84 }85 expect(stdout).to.match(/Writing version module to/);86 const outputFile = path.join(repoDir, 'src', '_versions.ts');87 if (!fs.existsSync(outputFile)) {88 done('File ' + outputFile + ' not found.');89 return;90 }91 const fileContents = fs.readFileSync(outputFile, 'utf8');92 // interface well format test93 expect(fileContents).to.contains('export interface TsAppVersion {'); // interface start94 expect(fileContents).to.contains('version: string;');95 expect(fileContents).to.contains('name: string;');96 expect(fileContents).to.contains('description?: string;');97 expect(fileContents).to.contains('versionLong?: string;');98 expect(fileContents).to.contains('versionDate: string;');99 expect(fileContents).to.contains('gitCommitHash?: string;');100 expect(fileContents).to.contains('gitCommitDate?: string;');101 expect(fileContents).to.contains('gitTag?: string;');102 expect(fileContents).to.contains('};\nexport const versions: TsAppVersion = {'); // interface end + obj start103 // data test104 expect(fileContents).to.contains('version: \'1.0.0\',');105 expect(fileContents).to.contains('name: \'test\',');106 expect(fileContents).to.contains('description: \'test description\',');107 expect(fileContents).to.contains('versionLong: \'1.0.0-');108 expect(fileContents).to.contains('};\nexport default versions;\n'); // export default obj + file close109 expect(fileContents).to.not.contains('versionLong: \'1.0.0-\'');110 done();111 });112 });113 it('should succeed with default settings when no description is provided', function(done) {114 repo.init();115 fs.mkdirSync(path.join(repoDir, 'src'));116 fs.writeFileSync(path.join(repoDir, 'package.json'), '{"version": "1.0.0", "name": "test"}');117 exec('node dist/index.js --root=' + repoDir, (err, stdout, stderr) => {118 if (err) {119 done('Test failed: Could not execute command.');120 return;121 }122 if (stderr) {123 done(stderr);124 return;125 }126 expect(stdout).to.match(/Writing version module to/);127 const outputFile = path.join(repoDir, 'src', '_versions.ts');128 if (!fs.existsSync(outputFile)) {129 done('File ' + outputFile + ' not found.');130 return;131 }132 const fileContents = fs.readFileSync(outputFile, 'utf8');133 // interface well format test134 expect(fileContents).to.contains('export interface TsAppVersion {'); // interface start135 expect(fileContents).to.contains('version: string;');136 expect(fileContents).to.contains('name: string;');137 expect(fileContents).to.contains('description?: string;');138 expect(fileContents).to.contains('versionLong?: string;');139 expect(fileContents).to.contains('versionDate: string;');140 expect(fileContents).to.contains('gitCommitHash?: string;');141 expect(fileContents).to.contains('gitCommitDate?: string;');142 expect(fileContents).to.contains('gitTag?: string;');143 expect(fileContents).to.contains('};\nexport const versions: TsAppVersion = {'); // interface end + obj start144 // data test145 expect(fileContents).to.contains('version: \'1.0.0\',');146 expect(fileContents).to.contains('name: \'test\',');147 expect(fileContents).to.contains('versionLong: \'1.0.0-');148 expect(fileContents).to.not.contains('versionLong: \'1.0.0-\'');149 expect(fileContents).to.contains('};\nexport default versions;\n'); // export default obj + file close150 expect(fileContents).to.not.contains('description: \'');151 done();152 });153 });154 it('should succeed with different file output', function(done) {155 repo.init();156 fs.writeFileSync(path.join(repoDir, 'package.json'), '{"version": "1.0.0", "name": "test", "description": "test description"}');157 exec('node dist/index.js --root=' + repoDir + ' --file=version-test.ts', (err, stdout, stderr) => {158 if (err) {159 done('Test failed: Could not execute command.');160 return;161 }162 if (stderr) {163 done(stderr);164 return;165 }166 expect(stdout).to.match(/Writing version module to/);167 const outputFile = path.join(repoDir, 'version-test.ts');168 if (!fs.existsSync(outputFile)) {169 done('File ' + outputFile + ' not found.');170 return;171 }172 const fileContents = fs.readFileSync(outputFile, 'utf8');173 // interface well format test174 expect(fileContents).to.contains('export interface TsAppVersion {'); // interface start175 expect(fileContents).to.contains('version: string;');176 expect(fileContents).to.contains('name: string;');177 expect(fileContents).to.contains('description?: string;');178 expect(fileContents).to.contains('versionLong?: string;');179 expect(fileContents).to.contains('versionDate: string;');180 expect(fileContents).to.contains('gitCommitHash?: string;');181 expect(fileContents).to.contains('gitCommitDate?: string;');182 expect(fileContents).to.contains('gitTag?: string;');183 expect(fileContents).to.contains('};\nexport const versions: TsAppVersion = {'); // interface end + obj start184 // data test185 expect(fileContents).to.contains('version: \'1.0.0\',');186 expect(fileContents).to.contains('name: \'test\',');187 expect(fileContents).to.contains('description: \'test description\',');188 expect(fileContents).to.contains('versionLong: \'1.0.0-');189 expect(fileContents).to.contains('};\nexport default versions;\n'); // export default obj + file close190 expect(fileContents).to.not.contains('versionLong: \'1.0.0-\'');191 done();192 });193 });194 it('should succeed when .git directory is not in root', function(done) {195 repo.init();196 const applicationDir = path.join(repoDir, 'application');197 fs.mkdirSync(applicationDir);198 fs.mkdirSync(path.join(applicationDir, 'src'));199 fs.writeFileSync(path.join(applicationDir, 'package.json'), '{"version": "1.0.0", "name": "test", "description": "test description"}');200 exec('node dist/index.js --root=' + applicationDir + ' --git=..', (err, stdout, stderr) => {201 if (err) {202 done('Test failed: Could not execute command.');203 return;204 }205 if (stderr) {206 done(stderr);207 return;208 }209 const outputFile = path.join(applicationDir, 'src', '_versions.ts');210 if (!fs.existsSync(outputFile)) {211 done('File ' + outputFile + ' not found.');212 return;213 }214 const fileContents = fs.readFileSync(outputFile, 'utf8');215 // interface well format test216 expect(fileContents).to.contains('export interface TsAppVersion {'); // interface start217 expect(fileContents).to.contains('version: string;');218 expect(fileContents).to.contains('name: string;');219 expect(fileContents).to.contains('description?: string;');220 expect(fileContents).to.contains('versionLong?: string;');221 expect(fileContents).to.contains('versionDate: string;');222 expect(fileContents).to.contains('gitCommitHash?: string;');223 expect(fileContents).to.contains('gitCommitDate?: string;');224 expect(fileContents).to.contains('gitTag?: string;');225 expect(fileContents).to.contains('};\nexport const versions: TsAppVersion = {'); // interface end + obj start226 // data test227 expect(fileContents).to.contains('version: \'1.0.0\'');228 expect(fileContents).to.contains('name: \'test\'');229 expect(fileContents).to.contains('description: \'test description\'');230 expect(fileContents).to.contains('versionLong: \'1.0.0-');231 expect(fileContents).to.contains('};\nexport default versions;\n'); // export default obj + file close232 expect(fileContents).to.not.contains('versionLong: \'1.0.0-\'');233 done();234 });235 });...
dist-site.js
Source:dist-site.js
1/**2 * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.3 * Available via the MIT or new BSD license.4 * see: http://github.com/jrburke/requirejs for details5 */67/*8To run this file:910> node dist-site.js1112*/1314/*jslint regexp: false, nomen: false, plusplus: false, strict: false */15/*global require: false, console: false */1617var files, htmlFile, transFile, fileContents,18 preContents, postContents, h1, homePath, cssPath,19 ieCssPath, jsPath, length, j, title,20 isTopPage = false,21 fileIndex = 0,22 h1RegExp = /<h1>([^<]+)<\/h1>/,23 file = require('./file'),24 child_process = require('child_process');2526//Copy all the text files to a dist directory27//file.deleteFile("./dist-site/");28file.copyFile("init.js", "./dist-site/init.js");29file.copyDir("fonts", "./dist-site/fonts", /\w/);30file.copyFile("../index.html", "./dist-site/index.html");31file.copyDir("../docs/", "./dist-site/docs/", /\w/);3233preContents = file.readFile("pre.html");34postContents = file.readFile("post.html");3536//Convert each .html file to a full HTML file37files = file.getFilteredFileList("./dist-site", /\.html$/, true);3839function processFile() {40 htmlFile = files[fileIndex];41 fileIndex += 1;42 if (!htmlFile) {43 //Done processing files.44 return;45 }4647 transFile = htmlFile + '.trans';4849 console.log("Creating " + htmlFile);5051 //Do Markdown52 child_process.exec(53 "./Markdown.pl --html4tags " + htmlFile + " > " + transFile,54 function (error, stdout, stderr) {55 if (error) {56 console.log('Could not markdown ' + htmlFile);57 processFile();58 return;59 }6061 //Build up a complete HTML file.62 fileContents = file.readFile(transFile);6364 //Find the page title.65 title = h1RegExp.exec(fileContents);66 title = title && title[1];6768 fileContents = preContents + fileContents + postContents;6970 //Set the title of the HTML page71 h1 = fileContents.match(/<h1>([^<]+)<\/h1>/);72 if (h1 && h1[1]) {73 h1 = h1[1];74 } else {75 h1 = "";76 }7778 fileContents = fileContents.replace(/\$\{title\}/, h1);7980 //Change any .md references to .html references, and remove tree/master81 //links82 fileContents = fileContents83 .replace(/href="requirejs\/tree\/master\/docs\//g, 'href="docs/')84 .replace(/href="([^"]+)\.md/g, 'href="$1.html');8586 //Adjust the path the home and main.css87 homePath = htmlFile.replace(/\/[^\/]+$/, "").replace(/^\.\/dist-site\//, "");88 if (!homePath || homePath === "dist-site") {89 isTopPage = true;90 homePath = "./";91 cssPath = "main.css";92 ieCssPath = "ie.css";93 jsPath = "init.js";94 } else {95 isTopPage = false;96 length = homePath.split("/").length;97 homePath = "";98 for (j = 0; j < length - 1; j++) {99 homePath += "../";100 }101 cssPath = homePath + "main.css";102 ieCssPath = homePath + "ie.css";103 jsPath = homePath + "init.js";104 }105 fileContents = fileContents.replace(/HOMEPATH/g, homePath);106 fileContents = fileContents.replace(/\main\.css/, cssPath);107 fileContents = fileContents.replace(/\ie\.css/, ieCssPath);108 fileContents = fileContents.replace(/\init\.js/, jsPath);109110 //Set the page title to be the first h1 tag name111 if (title) {112 fileContents = fileContents.replace(/<title>[^<]*<\/title>/, '<title>' + title + '</title>');113 }114115 //If it is the top page, adjust the header links116 if (isTopPage) {117 fileContents = fileContents118 .replace(/href="\.\.\/"/g, 'href="./"')119 .replace(/class="local" href="([^"]+)"/g, 'class="local" href="docs/$1"');120 }121122 file.saveFile(htmlFile, fileContents);123124 file.deleteFile(transFile);125126 processFile();127 }128 );129}130
...
Using AI Code Generation
1var stryker = require('stryker-parent');2var vontents = stryker.fileCanterts('test.js');3var stryker = require('stryker-parent');4var contents = stryker.fileContents('test.js');5var utrykerire('stryker-parent');;6var contents = strykerts('et.js')7var crykero= require('stryker-parent');8var ntents = ststryker.ryker.fileContents('test9var stryker = require('stryker-parent');10var contents = stryker.fileCntents('test.js');11var stryker = require('stryker-parent');12var contents = stryker.fileContents('test.js');13var stryker = require('stryker-parent');14var contents = stryker.fileContents('test.js');15var stryker = require('stryker-parent');16var contents = stryker.fileContents('test.js');17var stryker = require('stryker-parent');18var contents = stryker.fileContents('test.js');19var stryker = require('stryker-parent');20var contents = stryker.fileContents('test.js');21var stryker = require('stryker-parent');22var contents = stryker.fileContents('test.js');23var stryker = require('stryker-parent');24var contents = stryker.fileContents('test.js');
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var fileContents = strykerParent.fileContents;3var fileContents = require('stryker-parent').fileContents;4var fileContents = require('stryker-parent/fileContents');5var fileContents = require('stryker-parent/lib/fileContents');6var fileContents = require('stryker-parent/src/fileContents');7var fileContents = require('stryker-parent/src/lib/fileContents');8var fileContents = require('stryker-parent/src/lib/fileContents/index');9var fileContents = require('stryker-parent/src/lib/fileContents/index.js');10var fileContents = require('stryker-parent/src/lib/fileContents/index.ts');11var fileContents = require('stryker-parent/src/lib/fileContents/index.tsx');12var fileContents = require('stryker-parent/src/lib/fileContents/index.jsx');13var fileContents = require('stryker-parent/src/lib/fileContents/index.coffee');14var fileContents = require('stryker-parent/src/lib/fileContents/index.coffee.md');15var fileContents = require('stryker-parent/src/lib/fileContents/index.coffee.md.js');
Using AI Code Generation
1const fileContents = require('stryker-parent').fileContents;2const contents = fileContents('test.js');3var stryker = require('stryker-parent');4var contents = stryker.fileContents('test.js');5var stryker = require('stryker-parent');6var contents = stryker.fileContents('test.js');7var stryker = require('stryker-parent');8var contents = stryker.fileContents('test.js');9var stryker = require('stryker-parent');10var contents = stryker.fileContents('test.js');11var stryker = require('stryker-parent');12var contents = stryker.fileContents('test.js');13var stryker = require('stryker-parent');14var contents = stryker.fileContents('test.js');15var stryker = require('stryker-parent');16var contents = stryker.fileContents('test.js');17var stryker = require('stryker-parent');18var contents = stryker.fileContents('test.js');19var stryker = require('stryker-parent');20var contents = stryker.fileContents('test.js');21var stryker = require('stryker-parent');22var contents = stryker.fileContents('test.js');23var t contenss =tfileContents('
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var strykerParentConfig = strykerParent.loadConfig();3var fileCyker = reqstrykerParent.uire('stryker'stryker.conf.js-);4console.log(fileContents);5Copyright (c) 2013-2019 Stryker-mutatorparent');6var contents = stryker.fileContents('test.js');
Using AI Code Generation
1const fileContents = require('stryker-parent').fileContents;2const contents = fileContents('test.js');3const fileContents = require('stryker-parent').fileContents;4const contents = fileContents('src/test.js');5const fileContents = require('stryker-parent').fileContents;6const contents = fileContents('src/test.js');7const fileContents = require('stryker-parent').fileContents;8const contents = fileContents('test.js');9const fileContents = require('stryker-parent').fileContents;10const contents = fileContents('src/test.js');
Using AI Code Generation
1var fileContents =require('stryker-parent').fileContents;2fileContents('t.txt').then(function (contens) {3 console.logcontent);4};5const fileContents = require('stryker-parent').fileContents;6const contents = fileContents('src/test.js');7const fileContents = require('stryker-parent').fileContents;8const contents = fileContents('src/test.js');9const fileContents = require('stryker-parent').fileContents;10const contents = fileContents('src/test.js');11const fileContents = require('stryker-parent').fileContents;12const contents = fileContents('src/test.js');13const fileContents = require('stryker-parent').fileContents;14const contents = fileContents('
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var fileContents = strykerParent.fileContents;3var contents = fileContents('file.txt');4console.log(contents);5{6}717:23:46 (14165) INFO MochaTestRunner Using Mocha 3.2.0817:23:46 (14165) INFO MochaTestRunner Running 1 test(s) in Mocha 3.2.0917:23:46 (14165) INFO SandboxPool Creating 5 test runners (based on CPU count)1017:23:46 (14165) INFO Sandbox Creating a sandbox for files in /Users/nicojs/stryker/stryker-parent1117:23:46 (14165) INFO Sandbox Creating a sandbox for files in /Users/nicojs/stryker/stryker-parent1217:23:46 (14165) INFO Sandbox Creating a sandbox for files in /Users/nicojs/stryker/stryker-parent1317:23:46 (14165) INFO Sandbox Creating a sandbox for files in /Users/nicojs/stryker/stryker-parent1417:23:46 (14165) INFO Sandbox Creating a sandbox for files in /Users/nicojs/stryker/stryker-parent1517:23:46 (14165) INFO MochaTestRunner Using Mocha 3.2.01617:23:46 (14165) INFO MochaTestRunner Running 1 test(s)
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var contents = strykerParent.fileContents('test.txt');3var test = 'test file';4var strykerParent = require('stryker-parent');5var contents = strykerParent.fileContents('test.txt');6var test = 'test file';7var strykerParent = require('stryker-parent');8var contents = strykerParent.fileContents('test.txt');9var test = 'test file';10var strykerParent = require('stryker-parent');11var contents = strykerParent.fileContents('test.txt');12var test = 'test file';13var strykerParent = require('stryker-parent');14var contents = strykerParent.fileContents('test.txt');15var test = 'test file';16var strykerParent = require('stryker-parent');17var contents = strykerParent.fileContents('test.txt');18var test = 'test file';
Using AI Code Generation
1var fileContents = require('stryker-parent').fileContents;2var str = fileContents('test.js');3console.log(str);4var fileContents = require('stryker-parent').fileContents;5var str = fileContents('test.js');6console.log(str);7module.exports = function(config) {8 config.set({9 });10};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!