compile a ejs file into javascript
507366
def js_source(source_path, namespace = nil, output_as_array = false)
      template_name = File.basename(source_path, ".ejs")
      template_name = "#{namespace}.#{template_name}" if namespace
      
      js_source_from_string(template_name, File.read(source_path), output_as_array)
    end
564757
function compileHtml(target) {
	return gulp.src(config.src.html)
		.pipe(gulp.dest(`${config.output.dist}/${target}`))
}
928097
function processJs(jsFiles) {
      var mergedJs = mergeFiles(jsFiles).join(' ');
      var script = replaceDemoModuleWithCodepenModule(mergedJs);
      return script;
    }
55357
function Compiler (handleImportCall) {
  var self = this
  this.event = new EventManager()

  var compileJSON

  var worker = null

  var currentVersion

  var optimize = false

  this.setOptimize = function (_optimize) {
    optimize = _optimize
  }

  var compilationStartTime = null
  this.event.register('compilationFinished', (success, data, source) => {
    if (success && compilationStartTime) {
      this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
    }
    compilationStartTime = null
  })

  this.event.register('compilationStarted', () => {
    compilationStartTime = new Date().getTime()
  })

  var internalCompile = function (files, target, missingInputs) {
    gatherImports(files, target, missingInputs, function (error, input) {
      if (error) {
        self.lastCompilationResult = null
        self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
      } else {
        compileJSON(input, optimize ? 1 : 0)
      }
    })
  }

  var compile = function (files, target) {
    self.event.trigger('compilationStarted', [])
    internalCompile(files, target)
  }
  this.compile = compile

  function setCompileJSON (_compileJSON) {
    compileJSON = _compileJSON
  }
  this.setCompileJSON = setCompileJSON // this is exposed for testing

  function onCompilerLoaded (version) {
    currentVersion = version
    self.event.trigger('compilerLoaded', [version])
  }

  function onInternalCompilerLoaded () {
    if (worker === null) {
      var compiler
      var userAgent = (typeof (navigator) !== 'undefined') && navigator.userAgent ? navigator.userAgent.toLowerCase() : '-'
      if (typeof (window) === 'undefined' || userAgent.indexOf(' electron/') > -1) {
        compiler = require('@dexon-foundation/dsolc')
      } else {
        compiler = solc(window.Module)
      }

      compileJSON = function (source, optimize, cb) {
        var missingInputs = []
        var missingInputsCallback = function (path) {
          missingInputs.push(path)
          return { error: 'Deferred import' }
        }

        var result
        try {
          var input = compilerInput(source.sources, {optimize: optimize, target: source.target})
          result = compiler.compile(input, missingInputsCallback)
          result = JSON.parse(result)
        } catch (exception) {
          result = { error: { formattedMessage: 'Uncaught JavaScript exception:\n' + exception, severity: 'error', mode: 'panic' } }
        }

        compilationFinished(result, missingInputs, source)
      }
      onCompilerLoaded(compiler.version())
    }
  }
  // exposed for use in node
  this.onInternalCompilerLoaded = onInternalCompilerLoaded

  this.lastCompilationResult = {
    data: null,
    source: null
  }

  /**
    * return the contract obj of the given @arg name. Uses last compilation result.
    * return null if not found
    * @param {String} name    - contract name
    * @returns contract obj and associated file: { contract, file } or null
    */
  this.getContract = (name) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.getContract(name, this.lastCompilationResult.data.contracts)
    }
    return null
  }

  /**
    * call the given @arg cb (function) for all the contracts. Uses last compilation result
    * @param {Function} cb    - callback
    */
  this.visitContracts = (cb) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return txHelper.visitContracts(this.lastCompilationResult.data.contracts, cb)
    }
    return null
  }

  /**
    * return the compiled contracts from the last compilation result
    * @return {Object}     - contracts
    */
  this.getContracts = () => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.contracts) {
      return this.lastCompilationResult.data.contracts
    }
    return null
  }

   /**
    * return the sources from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSources = () => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources
    }
    return null
  }

  /**
    * return the sources @arg fileName from the last compilation result
    * @param {Object} cb    - map of sources
    */
  this.getSource = (fileName) => {
    if (this.lastCompilationResult.source) {
      return this.lastCompilationResult.source.sources[fileName]
    }
    return null
  }

  /**
    * return the source from the last compilation result that has the given index. null if source not found
    * @param {Int} index    - index of the source
    */
  this.getSourceName = (index) => {
    if (this.lastCompilationResult.data && this.lastCompilationResult.data.sources) {
      return Object.keys(this.lastCompilationResult.data.sources)[index]
    }
    return null
  }

  function compilationFinished (data, missingInputs, source) {
    var noFatalErrors = true // ie warnings are ok

    function isValidError (error) {
      // The deferred import is not a real error
      // FIXME: maybe have a better check?
      if (/Deferred import/.exec(error.message)) {
        return false
      }

      return error.severity !== 'warning'
    }

    if (data['error'] !== undefined) {
      // Ignore warnings (and the 'Deferred import' error as those are generated by us as a workaround
      if (isValidError(data['error'])) {
        noFatalErrors = false
      }
    }
    if (data['errors'] !== undefined) {
      data['errors'].forEach(function (err) {
        // Ignore warnings and the 'Deferred import' error as those are generated by us as a workaround
        if (isValidError(err)) {
          noFatalErrors = false
        }
      })
    }

    if (!noFatalErrors) {
      // There are fatal errors - abort here
      self.lastCompilationResult = null
      self.event.trigger('compilationFinished', [false, data, source])
    } else if (missingInputs !== undefined && missingInputs.length > 0) {
      // try compiling again with the new set of inputs

      internalCompile(source.sources, source.target, missingInputs)
    } else {
      data = updateInterface(data)

      self.lastCompilationResult = {
        data: data,
        source: source
      }
      self.event.trigger('compilationFinished', [true, data, source])
    }
  }

  // TODO: needs to be changed to be more node friendly
  this.loadVersion = function (usingWorker, url) {
    console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
    self.event.trigger('loadingCompiler', [url, usingWorker])

    if (usingWorker) {
      loadWorker(url)
    } else {
      loadInternal(url)
    }
  }

  function loadInternal (url) {
    delete window.Module
    // NOTE: workaround some browsers?
    window.Module = undefined

    // Set a safe fallback until the new one is loaded
    setCompileJSON(function (source, optimize) {
      compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
    })

    var newScript = document.createElement('script')
    newScript.type = 'text/javascript'
    newScript.src = url
    document.getElementsByTagName('head')[0].appendChild(newScript)
    var check = window.setInterval(function () {
      if (!window.Module) {
        return
      }
      window.clearInterval(check)
      onInternalCompilerLoaded()
    }, 200)
  }

  function loadWorker (url) {
    if (worker !== null) {
      worker.terminate()
    }
    worker = webworkify(require('./compiler-worker.js'))
    var jobs = []
    worker.addEventListener('message', function (msg) {
      var data = msg.data
      switch (data.cmd) {
        case 'versionLoaded':
          onCompilerLoaded(data.data)
          break
        case 'compiled':
          var result
          try {
            result = JSON.parse(data.data)
          } catch (exception) {
            result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
          }
          var sources = {}
          if (data.job in jobs !== undefined) {
            sources = jobs[data.job].sources
            delete jobs[data.job]
          }
          compilationFinished(result, data.missingInputs, sources)
          break
      }
    })
    worker.onerror = function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    }
    worker.addEventListener('error', function (msg) {
      compilationFinished({ error: 'Worker error: ' + msg.data })
    })
    compileJSON = function (source, optimize) {
      jobs.push({sources: source})
      worker.postMessage({cmd: 'compile', job: jobs.length - 1, input: compilerInput(source.sources, {optimize: optimize, target: source.target})})
    }
    worker.postMessage({cmd: 'loadVersion', data: url})
  }

  function gatherImports (files, target, importHints, cb) {
    importHints = importHints || []

    // FIXME: This will only match imports if the file begins with one.
    //        It should tokenize by lines and check each.
    // eslint-disable-next-line no-useless-escape
    var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g

    for (var fileName in files) {
      var match
      while ((match = importRegex.exec(files[fileName].content))) {
        var importFilePath = match[1]
        if (importFilePath.startsWith('./')) {
          var path = /(.*\/).*/.exec(fileName)
          if (path !== null) {
            importFilePath = importFilePath.replace('./', path[1])
          } else {
            importFilePath = importFilePath.slice(2)
          }
        }

        // FIXME: should be using includes or sets, but there's also browser compatibility..
        if (importHints.indexOf(importFilePath) === -1) {
          importHints.push(importFilePath)
        }
      }
    }

    while (importHints.length > 0) {
      var m = importHints.pop()
      if (m in files) {
        continue
      }

      if (handleImportCall) {
        handleImportCall(m, function (err, content) {
          if (err) {
            cb(err)
          } else {
            files[m] = { content }
            gatherImports(files, target, importHints, cb)
          }
        })
      }

      return
    }

    cb(null, { 'sources': files, 'target': target })
  }

  function truncateVersion (version) {
    var tmp = /^(\d+.\d+.\d+)/.exec(version)
    if (tmp) {
      return tmp[1]
    }
    return version
  }

  function updateInterface (data) {
    txHelper.visitContracts(data.contracts, (contract) => {
      data.contracts[contract.file][contract.name].abi = solcABI.update(truncateVersion(currentVersion), contract.object.abi)
    })
    return data
  }
}
1235955
function compileJS(js, opts, type, extra) {
    if (typeof opts === 'string') {
      extra = type
      type = opts
      opts = {}
    }
    if (typeof type === 'object') {
      extra = type
      type = ''
    }
    else if (!extra) extra = {}

    return _compileJS(js, opts, type, extra.parserOptions, extra.url)
  }
1145346
function webpackGetCodeOnDone (compiler, done) {
	if (!(compiler instanceof Compiler)) {
		throw new Error(`Expected compiler to be an instance of 'Compiler'`)
	}

	const outputFs = compiler.outputFileSystem
	const outputPath = compiler.outputPath

	installSourceMapSupport(outputFs)

	let compiledCode
	let error = false

	compiler.plugin('done', stats => {
		error = false
		// Server compilation errors need to be propagated to the client.
		if (stats.compilation.errors.length) {
			error = stats.compilation.errors[0]
			return
		}
		const filename = getFilename(stats, outputPath, 'main')
		const buffer = outputFs.readFileSync(filename)

		try {
			compiledCode = getCompiled(filename, buffer)
		} catch (ex) {
			error = ex
		}

		if (compiledCode) {
			done(compiledCode)
		} else {
			throw new Error(
				`webpack-get-code-on-done: Compiled code is 'undefined'. Please check latest changes that may produced this error. ${error}`
			)
		}
	})
}
1225310
async function build() {
  console.time('Packager');

  let requires = [];
  let esmExportString = '';
  let cjsExportString = '';

  try {
    if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
    fs.writeFileSync(ROLLUP_INPUT_FILE, '');
    fs.writeFileSync(TEST_MODULE_FILE, '');

    // All the snippets that are Node.js-based and will break in a browser
    // environment
    const nodeSnippets = fs
      .readFileSync('tag_database', 'utf8')
      .split('\n')
      .filter(v => v.search(/:.*node/g) !== -1)
      .map(v => v.slice(0, v.indexOf(':')));

    const snippets = fs.readdirSync(SNIPPETS_PATH);
    const archivedSnippets = fs
      .readdirSync(SNIPPETS_ARCHIVE_PATH)
      .filter(v => v !== 'README.md');

    snippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
      const snippetName = snippet.replace('.md', '');
      let code = getCode(rawSnippetString);
      if (nodeSnippets.includes(snippetName)) {
        requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
        code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
      }
      esmExportString += `export ${code}`;
      cjsExportString += code;
    });
    archivedSnippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(
        SNIPPETS_ARCHIVE_PATH,
        snippet
      );
      cjsExportString += getCode(rawSnippetString);
    });

    requires = [
      ...new Set(
        requires
          .filter(Boolean)
          .map(v =>
            v[0].replace(
              'require(',
              'typeof require !== "undefined" && require('
            )
          )
      )
    ].join('\n');

    fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);

    const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
      .map(v => v.replace('.md', ''))
      .join(',')}}`;

    fs.writeFileSync(
      TEST_MODULE_FILE,
      `${requires}\n\n${cjsExportString}\n\n${testExports}`
    );

    // Check Travis builds - Will skip builds on Travis if not CRON/API
    if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
      fs.unlink(ROLLUP_INPUT_FILE);
      console.log(
        `${chalk.green(
          'NOBUILD'
        )} Module build terminated, not a cron job or a custom build!`
      );
      console.timeEnd('Packager');
      process.exit(0);
    }

    await doRollup();

    // Clean up the temporary input file Rollup used for building the module
    fs.unlink(ROLLUP_INPUT_FILE);

    console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
    console.timeEnd('Packager');
  } catch (err) {
    console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
    process.exit(1);
  }
}
1112882
def compile_compiler_source(source)
      ExecJS.compile(source).tap do |compiler|
        raise engine::CompilerError, "Failed to compile #{ engine.name } compiler" unless compiler
      end
    end
529193
function manualCompile(templateCompilerPath, template, grunt){
  'use strict';

  var fs = require('fs'),
      vm = require('vm'),
      templateCompilerJs;

  try {
    templateCompilerJs = fs.readFileSync(templateCompilerPath, 'utf8');
  } catch (e) {
    if (e.code !== 'ENOENT') {
      throw e;
    }
    grunt.fail.warn('ember-template-compiler.js is not found. You can install with `bower install ember --save`. If you would like to use a custom location you can setup `templateCompilerPath` option in Gruntfile.js. It has to point to ember-template-compiler.js which bundled with Ember.js. The default path: bower_components/ember/ember-template-compiler.js');
  }

  // Create a context into which we will load both the ember template compiler
  // as well as the template to be compiled. The ember template compiler expects
  // `exports` to be defined, and uses it to export `precompile()`. It also
  // expects `global` to be defined and to be an object.
  var context = vm.createContext({
    module: {},
    exports: {},
    global: {},
    template: template,
    mainContext: undefined,
    setTimeout: setTimeout
  });

  // Load the ember template compiler
  vm.runInContext(templateCompilerJs, context, 'ember-template-compiler.js');

  // Compile the template
  vm.runInContext('compiledJS = ((typeof Ember !== "undefined" && Ember.HTMLBars) || module.exports || exports).precompile(template);', context);

  return context.compiledJS;
}
1238502
function extract() {
    var scripts = document.getElementsByTagName('script'),
        script;
    for (var i = 0, l = scripts.length; i < l; i++) {
        script = scripts[i];
        if (!script.getAttribute('compiled') && script.id && script.innerHTML && script.type === 'text/x-eoraptor') {
            compile(script.id, trim(script.innerHTML));
            script.setAttribute('compiled','1');
        }
    }
}
136937
function compileHtml(src, dest) {
  return gulp.src([src])
    .pipe(plumber(config.plumberOptions))
    .pipe(pug(pugOptions))
    .pipe(prettify())
    .pipe(gulp.dest(dest));
}
1033337
function compileScript(source, code, base) {
  var o = options
  try {
    var js = new Kaffeine().compile(code)
    if(o.print)         print(js)
    else if(o.compile)  writeJs(source, js, base)
  }
  catch(err) {
    if(!o.watch) {
      console.log(err.stack)
      process.exit(1)
    }
    console.log(err.message)
  }
}
1133653
protected function compileJs()
    {
        $base = $this->path . "js" . DIRECTORY_SEPARATOR;
        if ($this->debug || !file_exists($base . $this->hash . ".js")) {
            $data = '';
            if (0 < count($this->files)) {
                $minifier = new JS();
                foreach ($this->files as $file) {
                    $pathParts = explode("/", $file);
                    if (file_exists($file)) {
                        if ($this->debug) {
                            $data = $this->putDebugJs($pathParts, $base, $file);
                        } elseif (!file_exists($base . $this->hash . ".js")) {
                            $minifier->add($file);
                            //$data = $this->putProductionJs($base, $file, $data);
                        }
                    }
                }
                if($this->debug) {
                    $this->storeContents($base . $this->hash . ".js", $data);
                } else {
                    ini_set('max_execution_time', -1);
                    ini_set('memory_limit', -1);
                    GeneratorHelper::createDir($base);
                    $minifier->minify($base . $this->hash . ".js");
                    ini_restore('memory_limit');
                    ini_restore('max_execution_time');
                }
                unset($minifier);
            }
        }
        return $this;
    }
315008
function createJsModule(source) {
    var compilerOptions = {
        compilerOptions: {
            target: ts.ScriptTarget.ES5,
            module: ts.ModuleKind.CommonJS,
            alwaysStrict: false
        }
    };
    var transpiled = ts.transpileModule(source, compilerOptions);
    return transpiled.outputText;
}
676419
def build_js(ctx, force=False):
    
    for fname in JSX_FILENAMES:
        jstools.babel(
            ctx,
            '{pkg.source_js}/' + fname,
            '{pkg.django_static}/{pkg.name}/js/' + fname + '.js',
            force=force
        )
705160
function buildJs() {
  const jsFiles = config.jsCoreFiles;
  config.componentPaths.forEach(component => {
    jsFiles.push(path.join(component, '*.js'));
    jsFiles.push(path.join(component, '**/*.js'));
  });

  gutil.log("building js files...");

  const jsBuildStream = gulp.src(jsFiles)
  .pipe(filterNonCodeFiles())
  .pipe(utils.buildNgMaterialDefinition())
  .pipe(plumber())
  .pipe(ngAnnotate())
  .pipe(utils.addJsWrapper(true));

  const jsProcess = series(jsBuildStream, themeBuildStream())
  .pipe(concat('angular-material.js'))
  .pipe(BUILD_MODE.transform())
  .pipe(insert.prepend(config.banner))
  .pipe(insert.append(';window.ngMaterial={version:{full: "' + VERSION + '"}};'))
  .pipe(gulp.dest(config.outputDir))
  .pipe(gulpif(!IS_DEV, uglify({output: {comments: 'some'}})))
  .pipe(rename({extname: '.min.js'}))
  .pipe(gulp.dest(config.outputDir));

  return series(jsProcess, deployMaterialMocks());

  // Deploy the `angular-material-mocks.js` file to the `dist` directory
  function deployMaterialMocks() {
    return gulp.src(config.mockFiles)
    .pipe(gulp.dest(config.outputDir));
  }
}
1258574
private function js() {
		foreach ($this->localStatic[ __FUNCTION__ ] as $jswip) {
			
			// r.js optimization
			if($this->compress) {
				$rjsBuild = $jswip .DIRECTORY_SEPARATOR. self::RJS_BUILD;
				if(is_file($rjsBuild)) {
					$this	->start('Optimizing '. self::RJS_BUILD .' with r.js')
							->runLocal(['r.js.cmd',
								'-o', $rjsBuild,
							])->finish();

					// temp destination directory
					$jswip .= DIRECTORY_SEPARATOR . 'dist';
					$this->wipe[] = $jswip;
				}
			}
			
			// make file for each sub folder
			foreach (glob($jswip . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR) as $v) {
				if ($this->compress) {
					$output = $this->tmp[ __FUNCTION__ ] . basename($v) . '.js';
					self::readyDir($output);

					$this->start('Minifing ' . basename($v) . ' with closure');

					$this->runLocal([self::BIN . 'closure.bat',
						'--language_in', 'ECMASCRIPT5',
						'--js_output_file', $output,
						$v . DIRECTORY_SEPARATOR . '**',
					]);

					$this->finish();
				} else {
					$this->start('Merging ' . basename($v) . '\'s JS files');

					$full = $this->tmp[ __FUNCTION__ ] . basename($v) . '.js';

					//remove compiled file
					if (is_file($full))
						unlink($full);

					// append to new js file
					self::readyDir($full);
					$f = fopen($full, 'a'); //match with $g!
										// get js files
					$g = self::rglob($v . DIRECTORY_SEPARATOR . '*.js');

					// add js files
					foreach ($g as $vv) {
						//$this->start('Adding in '. basename($vv) .' to '. basename($v));
												// start buffer
						ob_start();

						// nice title
						echo "\n\n\n/*** ", basename($vv), " ***/\n\n";

						// output file
						require $vv;

						// save the executed css file
						$file = ob_get_clean();

						// add to file
						fwrite($f, $file);

						//$this->finish();
					}

					fclose($f);
					$this->finish();
				}
			}
		}
		
		return $this;
	}