Example #1
0
keywords["object"] = function(arr) {
    var ret = new SourceNode()

    if (arr.length == 1) {
        ret.add("{}")
        return ret
    }

    indent += indentSize
    handleSubExpressions(arr)

    ret.add("{\n" + " ".repeat(indent))

    for (var i = 1; i < arr.length; i = i + 2) {
        if (i > 1) {
            ret.add(",\n" + " ".repeat(indent))
        }

        ret.add([arr[i], ': ', arr[i + 1]])
    }

    indent -= indentSize
    ret.add("\n" + " ".repeat(indent) + "}")

    return ret
}
  opts.templates.forEach(function (template) {
    var options = {
      knownHelpers: known,
      knownHelpersOnly: opts.o
    };

    if (opts.map) {
      options.srcName = template.path;
    }
    if (opts.data) {
      options.data = true;
    }

    var precompiled = Handlebars.precompile(template.source, options);

    // If we are generating a source map, we have to reconstruct the SourceNode object
    if (opts.map) {
      var consumer = new _sourceMap.SourceMapConsumer(precompiled.map);
      precompiled = _sourceMap.SourceNode.fromStringWithSourceMap(precompiled.code, consumer);
    }

    if (opts.simple) {
      output.add([precompiled, '\n']);
    } else {
      if (!template.name) {
        throw new Handlebars.Exception('Name missing for template');
      }

      if (opts.amd && !multiple) {
        output.add('return ');
      }
      output.add([objectName, '[\'', template.name, '\'] = template(', precompiled, ');\n']);
    }
  });
Example #3
0
 output.forEach(function(asset) {
   if(asset.sourceMap && asset.sourceMap.mappings !== '') {
     sourceNode.add(SourceNode.fromStringWithSourceMap(asset.toString(), new SourceMapConsumer(asset.sourceMap)));
   } else {
     asset.toString().split('\n').forEach(function(line, j){
       sourceNode.add(new SourceNode(j + 1, 0, asset.relativePath, line + '\n'));
     });
     sourceNode.add('\n');
   }
 });
Example #4
0
keywords["throw"] = function(arr) {
    if (arr.length != 2)  handleError(0, arr._line, arr._filename)

    var ret = new SourceNode()

    ret.add(Array.isArray(arr[1]) ? handleExpression(arr[1]) : arr[1])
    ret.prepend("(function(){throw ")
    ret.add(";})()")

    return ret
}
Example #5
0
keywords["str"] = function(arr) {
    if (arr.length < 2) handleError(0, arr._line, arr._filename)
    handleSubExpressions(arr)
    var ret = new SourceNode()
    ret.add(arr.slice(1))
    ret.join (",")
    ret.prepend("[")
    ret.add("].join('')")

    return ret
}
  _createBundleMap(reactCode, reactMap, appCode, appMap) {
    const node = new SourceNode();

    node.add(SourceNode.fromStringWithSourceMap(
      reactCode,
      new SourceMapConsumer(reactMap)
    ));
    node.add(SourceNode.fromStringWithSourceMap(
      appCode,
      new SourceMapConsumer(appMap)
    ));

    return node.join('').toStringWithSourceMap().map.toString();
  }
Example #7
0
    function bufferContents(file) {
        if (file.isNull()) return; // ignore
        if (file.isStream()) return this.emit('error', new PluginError('gulp-concat-sourcemap', 'Streaming not supported'));

        if (!firstFile) firstFile = file;

        var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/');

        if(opts.prefix) {
            var p = opts.prefix;
            while(p-- > 0) {
                rel = rel.substring(rel.indexOf('/') + 1);
            }
        }

        if (file.contents[0] === 0xEF && file.contents[1] === 0xBB && file.contents[2] === 0xBF) {
            file.contents = file.contents.slice(3);
        }
        file.contents.toString('utf8').split('\n').forEach(function(line, j){
            sourceNode.add(new SourceNode(j + 1, 0, rel, line + '\n'));
        });
        sourceNode.add('\n');

        if (opts.sourcesContent) {
            sourceNode.setSourceContent(file.relative, file.contents.toString('utf8'));
        }
    }
Example #8
0
keywords["function"] = function(arr) {

    var ret
    var fName, fArgs, fBody

    if (arr.length < 2) handleError(0, arr._line, arr._filename)

    if(Array.isArray(arr[1])) {
        // an anonymous function
        fArgs = arr[1]
        fBody = arr.slice(2)
    }
    else if(!Array.isArray(arr[1]) && Array.isArray(arr[2])) {
        // a named function
        fName = arr[1]
        fArgs = arr[2]
        fBody = arr.slice(3)
    }
    else
        handleError(0, arr._line)

    ret = new SourceNode(null, null, null, fArgs)
    ret.join(",")
    ret.prepend("function" + (fName ? " " + fName.name : "") + "(")
    ret.add([") {\n",handleExpressions(fBody),
               " ".repeat(indent), "}"])

    if(fName) 
        noSemiColon = true

    return ret
}
Example #9
0
var handleArithOperator = function(arr) {
    if (arr.length < 3)  handleError(0, arr._line)
    handleSubExpressions(arr)

    var op = new SourceNode()
    op.add([" ", arr.shift(), " "])

    var ret = new SourceNode()
    ret.add(arr)

    ret.join (op)

    ret.prepend("(")
    ret.add(")")

    return ret
}
Example #10
0
    function endStream(){
        if (!firstFile) return this.emit('end');

        var contentPath = path.join(firstFile.base, fileName),
            mapPath = contentPath + '.map';

        if(!firstFile.sourceMap) {
            if (/\.css$/.test(fileName)) {
                sourceNode.add('/*# sourceMappingURL=' + (opts.sourceMappingBaseURL || '') + fileName + '.map' + ' */');
            } else {
                sourceNode.add('//# sourceMappingURL=' + (opts.sourceMappingBaseURL || '') + fileName + '.map');
            }
        }

        var codeMap = sourceNode.toStringWithSourceMap({
            file: fileName,
            sourceRoot: opts.sourceRoot || ''
        });

        var sourceMap = codeMap.map.toJSON();

        sourceMap.file = path.basename(sourceMap.file);

        var contentFile = new File({
            cwd: firstFile.cwd,
            base: firstFile.base,
            path: contentPath,
            contents: new Buffer(codeMap.code)
        });

        if(firstFile.sourceMap){
            contentFile.sourceMap = sourceMap;
        } else {
            var mapFile = new File({
                cwd: firstFile.cwd,
                base: firstFile.base,
                path: mapPath,
                contents: new Buffer(JSON.stringify(sourceMap, null, '  '))
            });
        }

        this.emit('data', contentFile);
        if(!firstFile.sourceMap) this.emit('data', mapFile);
        this.emit('end');
    }
  _createBundleMap: function(reactCode, reactMap, appCode, appMap) {
    var node = new SourceNode();
    var map;

    node.add(SourceNode.fromStringWithSourceMap(
      reactCode,
      new SourceMapConsumer(reactMap)
    ));
    node.add(SourceNode.fromStringWithSourceMap(
      appCode,
      new SourceMapConsumer(appMap)
    ));

    node = node.join('');
    map = node.toStringWithSourceMap().map;

    return JSON.stringify(map);
  },
Example #12
0
 tokens.forEach(function(token) {
   node.add(new SourceNode(lineIndex, charIndex, name, token));
   if (token === '\n') {
     lineIndex++;
     charIndex = 0;
   } else {
     charIndex += token.length;
   }
 });
Example #13
0
keywords["new"] = function(arr) {
    if (arr.length < 2) handleError(0, arr._line, arr._filename)

    var ret = new SourceNode()

    ret.add(handleExpression(arr.slice(1)))
    ret.prepend ("new ")

    return ret
}
Example #14
0
var handleExpression = function(expr) {
    if (!expr || !expr[0]) {
        return null
    }

    var command = expr[0].name


    if (macros[command]) {
        expr = macroExpand(expr)
        if (Array.isArray(expr)) {
            return handleExpression(expr)
        } else {
            return expr
        }
    }

    if (typeof command === "string") {
        if (keywords[command]) {
            return keywords[command](expr)
        }
        if (command.charAt(0) === ".") {
            var ret = new SourceNode()
            ret.add(Array.isArray(expr[1]) ? handleExpression(expr[1]) : expr[1])
            ret.prepend("(")
            ret.add([")", expr[0]])

            return ret
        }
    }
    handleSubExpressions(expr)
    var fName = expr[0]
    if (!fName) {
        handleError(1, expr._line)
    }
    if (isFunction.test(fName))
        fName = new SourceNode(null, null, null, ['(', fName, ')'])

    exprNode = new SourceNode (null, null, null, expr.slice(1)).join(",")

    return new SourceNode (null, null, null, [fName, "(", exprNode, ")"])
}
Example #15
0
var handleCompOperator = function(arr) {
    if (arr.length < 3)  handleError(0, arr._line)
    handleSubExpressions(arr)
    if (arr[0] == "=") arr[0] = "==="
    if (arr[0] == "!=") arr[0] = "!=="

    var op = arr.shift()
    var ret = new SourceNode()

    for (i = 0; i < arr.length - 1; i++)
        ret.add (new SourceNode (null, null, null, [arr[i], " ", op, " ", arr[i + 1]]))

    ret.join (' && ')

    ret.prepend('(')
    ret.add(')')

    return ret

}
Example #16
0
module.exports = function ngInject(src, origSourceMap) {
    this.cacheable();

    var sourceFn = this.resourcePath;

    var node = new SourceNode();
    node.add('module.exports = require(' + utils.stringifyRequest(this, wrapperPath) + ')(');
    node.add('function (module, exports, ngRequire) {\n');
    if (origSourceMap) {
        node.add(SourceNode.fromStringWithSourceMap(src, origSourceMap));
    }
    else {
        node.add(new SourceNode(1, 1, sourceFn, src));
    }
    node.add('\n});\n');

    var result = node.toStringWithSourceMap();

    this.callback(null, result.code, result.map.toJSON());
};
Example #17
0
keywords["var"] = function(arr) {
    if (arr.length < 3) handleError(0, arr._line, arr._filename)
    if (arr.length > 3) {
        indent += indentSize
    }
    handleSubExpressions(arr)
    var ret = new SourceNode ()
    ret.add("var ")

    for (var i = 1; i < arr.length; i = i + 2) {
        if (i > 1) {
            ret.add(",\n" + " ".repeat(indent))
        }
        if (!validName.test(arr[i])) handleError(9, arr._line, arr._filename)
        ret.add([arr[i], ' = ', arr[i + 1]])
    }
    if (arr.length > 3) {
        indent -= indentSize
    }
    return ret
}
Example #18
0
 tokens.forEach(function(token, i) {
   node.add(new SourceNode(lineIndex, charIndex, name, token));
   // Count lines and chars.
   token.split('\n').forEach(function(subtoken, j, subtokens) {
     if (j < subtokens.length - 1) {
       lineIndex++;
       charIndex = 0;
     } else {
       charIndex += subtoken.length;
     }
   });
 });
Example #19
0
keywords["if"] = function(arr) {
    if (arr.length < 3 || arr.length > 4)  handleError(0, arr._line, arr._filename)
    indent += indentSize
    handleSubExpressions(arr)

    var ret = new SourceNode()
    ret.add(["(", arr[1], " ?\n" +
        " ".repeat(indent), arr[2], " :\n" +
        " ".repeat(indent), (arr[3] || "undefined"), ")"])
    indent -= indentSize
    return ret
}
Example #20
0
    function bufferContents(file) {
        if (file.isNull()) return; // ignore
        if (file.isStream()) return this.emit('error', new PluginError('gulp-concat-sourcemap', 'Streaming not supported'));

        if (!firstFile) firstFile = file;

        var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/');

        if(opts.prefix) {
            var p = opts.prefix;
            while(p-- > 0) {
                rel = rel.substring(rel.indexOf('/') + 1);
            }
        }

        // remove utf-8 byte order mark
        if (file.contents[0] === 0xEF && file.contents[1] === 0xBB && file.contents[2] === 0xBF) {
            file.contents = file.contents.slice(3);
        }

        if(file.sourceMap && file.sourceMap.mappings != '') {
          sourceNode.add(SourceNode.fromStringWithSourceMap(file.contents.toString('utf8') + '\n\n', new SourceMapConsumer(file.sourceMap)));
        } else {
            file.contents.toString('utf8').split('\n').forEach(function(line, j){
                sourceNode.add(new SourceNode(j + 1, 0, rel, line));
            });
            if(opts.newLine !== undefined) {
                sourceNode.add(opts.newLine);
            }else{
                sourceNode.add('\n');
            }
        }


        if (opts.sourcesContent) {
            sourceNode.setSourceContent(rel, file.contents.toString('utf8'));
        }
    }
Example #21
0
keywords["try"] = function(arr) {
    if (arr.length < 3) handleError(0, arr._line, arr._filename)
    var c = arr.pop(),
        ind = " ".repeat(indent),
        ret = new SourceNode()

    ret.add(["(function() {\n" + ind + 
           "try {\n", handleExpressions(arr.slice(1)), "\n" +
           ind + "} catch (e) {\n" +
           ind + "return (", (Array.isArray(c) ? handleExpression(c) : c), ")(e);\n" +
           ind + "}\n" + ind + "})()"])

    return ret
}
/**
 * @name LoaderContext
 * @property {function} callback
 */

/**
 * @this LoaderContext
 * @param {string} content
 * @returns {string}
 */
function prependLoader(content) {
    var currentRequest = loaderUtils.getCurrentRequest(this);
    var node;
    var result;

    node = new SourceNode(1, 1, currentRequest);
    node.setSourceContent(currentRequest, content);
    node.prepend("'something to prepend';");
    node.add("'something to append';");
    result = node.toStringWithSourceMap({
        file: currentRequest
    });
    return this.callback(null, result.code, result.map.toJSON());
}
Example #23
0
// Concatenate the files while building up a sourcemap for the concatenation,
// and replace the line defining L.version with the string prepared in the jakefile
function bundleFiles(files, copy, version) {
	var node = new SourceNode(null, null, null, '');

	node.add(new SourceNode(null, null, null, copy + '(function (window, document, undefined) {'));

	for (var i = 0, len = files.length; i < len; i++) {
		var contents = fs.readFileSync(files[i], 'utf8');

		if (files[i] === 'src/Leaflet.js') {
			contents = contents.replace(
				new RegExp('version: \'.*\''),
				'version: ' + JSON.stringify(version)
			);
		}

		var lines = contents.split('\n');
		var lineCount = lines.length;
		var fileNode = new SourceNode(null, null, null, '');

		fileNode.setSourceContent(files[i], contents);

		for (var j=0; j<lineCount; j++) {
			fileNode.add(new SourceNode(j+1, 0, files[i], lines[j] + '\n'));
		}
		node.add(fileNode);

		node.add(new SourceNode(null, null, null, '\n\n'));
	}

	node.add(new SourceNode(null, null, null, '}(window, document));'));

	var bundle = node.toStringWithSourceMap();
	return {
		src: bundle.code,
		srcmap: bundle.map.toString()
	};
}
Example #24
0
keywords["array"] = function(arr) {
    var ret = new SourceNode()

    if (arr.length == 1) {
        ret.add("[]")
        return ret
    }

    indent += indentSize
    handleSubExpressions(arr)

    ret.add("[\n" + " ".repeat(indent))
    for (var i = 1; i < arr.length; ++i) {
        if (i > 1) {
            ret.add(",\n" + " ".repeat(indent))
        }
        ret.add(arr[i])
    }
    indent -= indentSize

    ret.add("\n" + " ".repeat(indent) + "]")

    return ret
}
Example #25
0
    exprs.forEach(function(expr, i, exprs) {
        var exprName,
            tmp = null,
            r = ""

        if (Array.isArray(expr)) {
            exprName = expr[0].name
            if (exprName === "include")
                ret.add(handleExpression(expr))
            else
                tmp = handleExpression(expr)
        } else {
            tmp = expr
        }

        if (i === l - 1 && indent) {
            if (!noReturn.test(exprName)) r = "return "
        }
        if (tmp) {
            var endline = noSemiColon ? "\n" : ";\n"
            noSemiColon = false
            ret.add([indentstr + r, tmp, endline])
        }
    })
Example #26
0
/**
 * Createa a selfie map.
 * @param file {Object}
 * @return {Object}
 */
function selfie(file) {
	var sourceNode = new SourceNode(), codeMap,
		lines = file.data.split(DELIMITER),
		len = lines.length,
		i = 0,
		source = file.path.substring(1),
		delimiter;
		
	for (; i < len; ++i) {
		// Last line DO NOT need to append delimiter.
		delimiter = (i + 1 === len) ?
			'' : DELIMITER;
		sourceNode.add(new SourceNode(i + 1, 0,
			source, lines[i] + delimiter));
	}
	
	codeMap = sourceNode.toStringWithSourceMap();
	file.data = codeMap.code;

	return codeMap.map.toJSON();
}
Example #27
0
module.exports = function(content, map) {
  this.cacheable();

  if (!content.match(amdRequireRE)) {
    return this.callback(null, content, map);
  }

  var sourceNode;

  if (map) {
    sourceNode = SourceNode.fromStringWithSourceMap(content, new SourceMapConsumer(map));
  } else {
    var fileName = loaderUtils.getRemainingRequest(this);
    sourceNode = new SourceNode(null, null, null);
    content.split('\n').forEach(function(line, idx) {
      sourceNode.add(new SourceNode(idx + 1, 0, fileName, line + '\n'));
    });
    sourceNode.setSourceContent(fileName, content);
  }

  var concatSrc = new SourceNode();

  var deps = [];
  content
  .replace(commentRE, '')
  .replace(requireRE, function (match, dep) {
    deps.push('require(\'' + dep + '\');');
  });

  concatSrc.add([
    deps.length ? HEADER + uniq(deps).join('\n') + '\n\n' : '',
    sourceNode,
  ]);

  var result = concatSrc.toStringWithSourceMap();
  this.callback(undefined, result.code, result.map.toString());
};
Example #28
0
module.exports = function(file, opts) {
  // 不是 js 文件不处理。
  if (!file.isJsLike || file.isPartial) {
    return;
  }

  var content = file.getContent();
  var forceNoWrap = file.wrap === false;
  
  if (!forceNoWrap && file.isMod) {
    
    var deps = '';
    if (opts.forwardDeclaration) {
      var reqs = opts.skipBuiltinModules ? [] : ['\'require\'', '\'exports\'', '\'module\''];

      file.requires.forEach(function(id) {
        var dep = fis.uri(id, file.dirname);
        if (dep.file) {
          if (dep.file.isJsLike) {
            reqs.push('\'' + (dep.file.moduleId || dep.file.id) + '\'');
          }
        } else {
          /(\.\w+)$/.test(id) ? (~opts.extList.indexOf(RegExp.$1) ? reqs.push('\'' + id.replace(/\.js$/i, '') + '\'') : '') : reqs.push('\'' + id + '\'');
        }
      });

      deps = ' [' + reqs.join(', ') + '],';
    }

    var originContent = content;

    if (opts.tab) {
      content = fis.util.pad(' ', opts.tab) + content.split(/\n|\r\n|\r/g).join('\n' + fis.util.pad(' ', opts.tab));
    }

    var prefix = 'define(\'' + (file.moduleId || file.id) + '\',' + deps + ' function(require, exports, module) {\n\n';
    var affix = '\n\n});\n';

    content = prefix + content + affix;

    if (file.moduleId !== file.id) {
      file.extras.moduleId = file.moduleId;
    }

    // 同时修改 sourcemap 文件内容。
    var derived = file.derived;
    if (!derived || !derived.length) {
      derived = file.extras && file.extras.derived;
    }

    if (derived && derived[0] && derived[0].rExt === '.map') {
      var SourceMap = require('source-map');
      

      var sourcemap = derived[0];
      var json = JSON.parse(sourcemap.getContent());
      var smc = new SourceMap.SourceMapConsumer(json);

      var sourceNode = new SourceMap.SourceNode();

      sourceNode.add(prefix);
      sourceNode.add(SourceMap.SourceNode.fromStringWithSourceMap(originContent, smc));
      sourceNode.add(affix);

      var code_map = sourceNode.toStringWithSourceMap({
        file: smc.file
      });

      var generater = SourceMap.SourceMapGenerator.fromSourceMap(new SourceMap.SourceMapConsumer(code_map.map.toJSON()));
      sourcemap.setContent(generater.toString());
    }

    file.setContent(content);
  }
}
Example #29
0
 node.append = function () {
     var prevNode = new SourceNode(null, null, null, node.sourceNodes());
     prevNode.add(new SourceNode(null, null, null, Array.prototype.slice.apply(arguments)));
     node.replace(prevNode);
 };
 }).forEach(function(line, j){
   sourceNode.add(new SourceNode(j + 1, 0, filename, line));
 });