compile: function(path, options, cb) { var input = fs.readFileSync(path, 'utf8'); try { cb( coffee.compile(input, {bare: true}) ); } catch (e) { var message = "! Error compiling " + path + " into CoffeeScript"; console.log(String.prototype.hasOwnProperty('red') && message.red || message); cb("Error compiling to CoffeeScript: " + e.stack); throw new Error(e); } }
function compile (data) { try { // Try to compile the coffee file data = coffee.compile(data.toString('utf-8')); return [200, data]; } catch (compileError) { // Bad coffeescript, send a 500 return [500, compileError]; } }
exports.compile = function(file, data, cb) { var coffescript = require('coffee-script'); var options = utile.mixin({}, compileOpts, {filename: file}); try { cb(null, coffescript.compile(data, options)); } catch(err) { cb(new Error("Error compiling coffeescript: " + data + ", " + err)); } };
it('should concat two files', function(done) { var filepath = "/home/contra/test/file.coffee"; var contents = new Buffer("a = 2"); var opts = {bare: true}; var expected = coffeescript.compile(String(contents), opts); coffee(opts) .on('error', done) .on('data', this.testData(expected, "/home/contra/test/file.js", done)) .write(createFile(filepath, contents)); });
it('should compile a literate file (with bare)', function(done) { var filepath = 'test/fixtures/journo.litcoffee'; var contents = new Buffer(fs.readFileSync(filepath)); var opts = {literate: true, bare: true}; var expected = coffeescript.compile(String(contents), opts); coffee(opts) .on('error', done) .on('data', this.testData(expected, 'test/fixtures/journo.js', done)) .write(createFile(filepath, contents)); });
it('should compile a file (with bare)', function(done) { var filepath = "test/fixtures/grammar.coffee"; var contents = new Buffer(fs.readFileSync(filepath)); var opts = {bare: true}; var expected = coffeescript.compile(String(contents), opts); coffee(opts) .on('error', done) .on('data', this.testData(expected, "test/fixtures/grammar.js", done)) .write(createFile(filepath, contents)); });
compile: function(input, filename, callback){ var self = this; var output, err; try { output = coffee_script.compile(input, self.compiler_options); } catch(error) { err = error; } return callback(err, output); }
Base.prototype.getFileSource = function (filename) { var src = fs.readFileSync(filename, 'utf8'); if (filename.match(this.coffeeExtRegEx)) { src = coffee.compile(src, { header: false, bare: true }); } return src; };
compiler.compile = function (filepath, data) { if (path.extname(filepath) === '.coffee') { data = coffee.compile(data); } if (path.extname(filepath) === '.iced') { data = iced.compile(data); } return data; };
return function(uncompiled) { var comp = require('coffee-script'); var compiled = comp.compile('0 || (' + uncompiled + ')'); // Strip out coffeescript scoping wrapper to get translated condition var re = /\(function\(\) {\s*0 \|\| \((.*)\);\n\n\}\)\.call\(this\);/; var match = re.exec(compiled); if (match && match.length > 1) { return match[1].trim(); } else { throw new Error('Compilation Error for: ' + uncompiled); } };
compileJs = function *(obj) { if (obj.ext !== "coffee") return; // The user can override this using the eventData config variable var data = { bare: true }; if (obj.thoughtpad.config && obj.thoughtpad.config.eventData && obj.thoughtpad.config.eventData['javascript-compile']) { data = obj.thoughtpad.config.eventData['javascript-compile']; } yield obj.thoughtpad.notify("javascript-compile-complete", { contents: coffee.compile(obj.contents, data), name: obj.name }); };
var compileCoffee = function(srcFile, options) { options = grunt.util._.extend({filename: srcFile}, options); var srcCode = grunt.file.read(srcFile); try { return coffeeScript.compile(srcCode, options); } catch (e) { grunt.log.error(e); grunt.fail.warn('CoffeeScript failed to compile.'); } };
var testSuite = function(code1, code2) { if (Array.isArray(code1)) { code1 = code1.join("\n"); } if (Array.isArray(code2)) { code2 = code2.join("\n"); } code1 = cc.createCompiler().compile(code1).trim(); code2 = coffee.compile(code2, {bare:true}).trim(); assert.equal(code1, code2); };
/** * Resolves specified module and overrides dependencies with specified stubs. * @name resolve * @function * @param {string} mdl Path to the module to be resolved. * @param {string} test__dirname __dirname of the test file calling this method. * @param {object} stubs Key/value pairs of modules to be stubbed out. * Keys are paths to modules relative to the tested file NOT the test file, e.g., exactly * as it is required in the tested file. * Values themselves are key/value pairs of functions/properties and the appropriate override. */ function resolve (mdl, test__dirname, stubs) { validateArguments(mdl, test__dirname, stubs); var mdlPath = isRelativePath(mdl) ? path.join(test__dirname, mdl) : mdl , resolvedMdl = require.resolve(mdlPath) , resolvedFile = findFile(resolvedMdl) , originalCode = fs.readFileSync(resolvedFile) , compiledCode = coffee.compile(originalCode.toString()) , mdlProxyFile = path.basename(resolvedFile) + '@' + (stubkey++).toString() , resolvedProxy = path.join(tmpDir, normalizeExtension(mdlProxyFile)) // all code will be written on one line, prepended to whatever was on first line to maintain linenos , mdlProxyCode = [ 'var __dirname = "' + escapeBackslashes(path.dirname(resolvedFile)) + '"; ' , 'var __filename = "' + escapeBackslashes(resolvedFile) + '"; ' , 'function require(mdl) { ' , 'return module' , '.require("' , escapeBackslashes(__filename), '")' , '._require(mdl, "' + escapeBackslashes(resolvedProxy) + '", __dirname); ' , '} ' , compiledCode ].join('') , dependency ; if (stubs) { // Adjust no call thru settings for each stubbed module if it was overridden globally if (!callThru) { Object.keys(stubs).forEach(function (key) { // allow turning call thru back on per module by setting it to false if (stubs[key]['@noCallThru'] !== false) stubs[key]['@noCallThru'] = true; }); } registeredStubs[resolvedProxy] = stubs; } fs.writeFileSync(resolvedProxy, mdlProxyCode); try { dependency = require(resolvedProxy); } catch (err) { console.trace(); console.error(err); throw (err); } finally { // Make sure we remove the generated file even if require fails fs.unlinkSync(resolvedProxy); } return dependency; }
function compileCoffeeScript(filePath, coffeeScript) { try{ var script = cs.compile(coffeeScript, { bare: true }); return script; }catch(e){ e.source = "SmangPack"; e.dest = "JavaScript"; e.filename = filePath; e.stack += "\n" + coffeeScript; e.lineno = parseInt(e.location.first_line ? e.location.first_line + 1 : -1); throw new TerraformError(e); } }
exports["Test compiled against source"] = function(test){ test.expect(1); // Get the JS commited in the project var commited = grunt.file.read('dist/YouTubePlayer.js'); var src = grunt.file.read('src/YouTubePlayer.coffee'); var compiled = coffee.compile(src); test.equal(commited, compiled, "Compiled Javascipt up to date with CoffeeScript source"); test.done(); };
grunt.registerHelper('coffee', function(src) { var coffee = require('coffee-script'), path = require('path'), js = '', dest = path.join(path.dirname(src), path.basename(src, '.coffee') + '.js'); try { js = coffee.compile(grunt.file.read(src), { bare: true }); grunt.file.write(dest, js); } catch (e) { grunt.log.error("Unable to compile your coffee", e); } });
// The acutal compilation of CoffeeScript. function compileCoffeeScript (code) { // Compile options var options = { bare: true } try { return CoffeeScript.compile(code, options) } catch (error) { var message = 'In: \n' + code + '\n was the following error:' + error.message throw new SyntaxError(message, error.fileName, error.lineNumber) } }
fs.watch(file, function() { if (doRequire) { delete Module._cache[file]; contents[name] = requireFile(file, doRequire); } else { contents[name] = fs.readFileSync(file).toString(); if (ext === 'coffee') { contents[name] = cs.compile(contents[name]); } } });
app.post('/coffeescript/', function(req, res) { var resp = { }; try { var coffee = require("coffee-script"); resp['js'] = coffee.compile(req.body.js, { }); } catch(e) { resp['error'] = e.message; } res.send(JSON.stringify(resp)); });
files.forEach(function(file) { if (options.exclude && options.exclude.test(file)) return; var isCoffee = file.match(/\.coffee$/); if (options.recurse && fs.statSync(file).isDirectory()) { files = fs.readdirSync(file).map(function(innerFile){ return path.join(file,innerFile); }); runReports(files); } else if (file.match(/\.js$/) || isCoffee) { log.info('Reading "%s"', file); var fileShort = file.replace(commonBasePath, ''); var fileSafe = fileShort.replace(/[^a-zA-Z0-9]/g,'_'); var source = fs.readFileSync(file).toString().trim(); if (isCoffee) source = coffee.compile(source); if (!source) { log.info('Not parsing empty file "%s"', file); return; } var report = { info : { file : file, fileShort : fileShort, fileSafe : fileSafe, link : fileDir + '/' + fileSafe + '/index.html' } }; var error = false; _.each(reporters,function(reporter, name){ try { report[name] = reporter.process(source, flags[name], report.info); } catch(e) { error = true; log.error('Error reading file : ', e.toString()); log.error(e.stack); return; } }); if (error) return; reports.push(report); if (outputDir) { var outdir = path.join(fileOutputDir, report.info.fileSafe); if (!fs.existsSync(outdir)) fs.mkdirSync(outdir); writeFileReport(outdir, report, source); } } });
tryFiles(name) { if (!name) { throw new Error('Name arg must be set!'); } let confFile = this.getFirstExisting(name); if (!confFile) { return null; } let ext = path.extname(confFile); let json; try { if (ext === '.json') { json = require(confFile); if (path.basename(confFile) === 'package.json') { json = json[name]; } } else { let source = fs.readFileSync(confFile, { encoding: 'utf8' }); if (ext === '.cson') { let js = CoffeeScript('module.exports =\n' + source); let sandbox = { module: {} }; let module = {}; eval(js); json = module.exports; } else if (ext === '.yaml' || ext === '.yml') { json = yaml.safeLoad(source); } else { let source = fs.readFileSync(confFile, { encoding: 'utf8' }); eval('json = ' + source); } } } catch (err) { throw new SyntaxError('Could not parse config file: ' + confFile + '\n\n' + err); } if (json) { return json; } }
fs.readFile(root + req.url, 'utf8', function(err, content) { if (err) { next(); } else { try { var code = coffee.compile(content); } catch (e) { fail(req, e); next(); return; } send(res, 'text/javascript', code); } });
ArangoApp.prototype.loadAppScript = function (filename, options) { options = options || {}; var appContext = _.extend({}, options.appContext, this._context); var full = fs.join(this._root, this._path, filename); if (!fs.exists(full)) { throwFileNotFound(full); } var fileContent = fs.read(full); if (options.transform) { fileContent = options.transform(fileContent); } else if (/\.coffee$/.test(filename)) { var cs = require("coffee-script"); fileContent = cs.compile(fileContent, {bare: true}); } var context = {}; if (options.context) { Object.keys(options.context).forEach(function (key) { context[key] = options.context[key]; }); } var localModule = appContext.appPackage.createAppModule(this, filename); context.__filename = full; context.__dirname = module.normalizeModuleName(full + "/.."); context.console = require("org/arangodb/foxx/console")(this._mount); context.applicationContext = appContext; try { return localModule.run(fileContent, context); } catch(e) { if (e instanceof ArangoError) { throw e; } var err = new ArangoError({ errorNum: errors.ERROR_FAILED_TO_EXECUTE_SCRIPT.code, errorMessage: errors.ERROR_FAILED_TO_EXECUTE_SCRIPT.message + "\nFile: " + filename }); err.stack = e.stack; err.cause = e; throw err; } };
it('should compile a file with source map', function(done) { var filepath = "test/fixtures/grammar.coffee"; var contents = new Buffer(fs.readFileSync(filepath)); var expected = coffeescript.compile(String(contents), { sourceMap: true, sourceFiles: ['grammar.coffee'], generatedFile: 'grammar.js' }); coffee({sourceMap: true}) .on('error', done) .on('data', this.testData(expected, "test/fixtures/grammar.js", done)) .write(createFile(filepath, contents)); });
var readConfigFile = function(filepath) { var ADAPTER_DIR = __dirname + '/../adapter'; var configEnv = { // constants LOG_DISABLE: constant.LOG_DISABLE, LOG_ERROR: constant.LOG_ERROR, LOG_WARN: constant.LOG_WARN, LOG_INFO: constant.LOG_INFO, LOG_DEBUG: constant.LOG_DEBUG, JASMINE: ADAPTER_DIR + '/lib/jasmine.js', JASMINE_ADAPTER: ADAPTER_DIR + '/jasmine.js', MOCHA: ADAPTER_DIR + '/lib/mocha.js', MOCHA_ADAPTER: ADAPTER_DIR + '/mocha.js', ANGULAR_SCENARIO: ADAPTER_DIR + '/lib/angular-scenario.js', ANGULAR_SCENARIO_ADAPTER: ADAPTER_DIR + '/angular-scenario.js', REQUIRE: ADAPTER_DIR + '/lib/require.js', REQUIRE_ADAPTER: ADAPTER_DIR + '/require.js', QUNIT: ADAPTER_DIR + '/lib/qunit.js', QUNIT_ADAPTER: ADAPTER_DIR + '/qunit.js', // access to globals console: console, require: require, process: process, __filename: filepath, __dirname: path.dirname(filepath) }; try { var configSrc = fs.readFileSync(filepath); // if the configuration file is coffeescript compile it if (path.extname(filepath) === '.coffee') { configSrc = coffee.compile(configSrc.toString(), {bare: true}); } vm.runInNewContext(configSrc, configEnv); } catch(e) { if (e.name === 'SyntaxError') { log.error('Syntax error in config file!\n' + e.message); } else if (e.code === 'ENOENT' || e.code === 'EISDIR') { log.error('Config file does not exist!'); } else { log.error('Invalid config file!\n', e); } process.exit(1); } return configEnv; };
names.forEach(function (name) { if (!fs.existsSync(name)) return; var code = fs.readFileSync(name).toString(); if (name.match(/\.ya?ml$/)) { code = JSON.stringify(JSON.stringify(yaml.load(code))); name = name.replace(/ya?ml$/, 'json'); } else if (name.match(/\.coffee$/)) { code = JSON.stringify(coffee.compile(code)); name = name.replace(/coffee$/, 'js'); } else { code = JSON.stringify(code); } buf.push('\'' + name + '\': ' + code + ''); });
"coffee", function (bundle, source_path, serve_path, where) { serve_path = serve_path + '.js'; var contents = fs.readFileSync(source_path); contents = new Buffer(coffee.compile(contents.toString('utf8'))); // XXX report coffee compile failures better? bundle.add_resource({ type: "js", path: serve_path, data: contents, where: where }); }
return function(content, file, done) { var processed = null; log.debug('Processing "%s".', file.originalPath); file.path = file.originalPath.replace(/\.coffee$/, '.js'); try { processed = coffee.compile(content, {bare: true}); } catch (e) { log.error('%s\n at %s', e.message, file.originalPath); } done(processed); };
let compileCoffee = function (filedata, callback) { let err = null; try { filedata = coffee.compile(filedata, { bare: true }); } catch (e) { err = new Error(e.toString().replace('[stdin]', '[coffee]')); } finally { callback(err, filedata); } };