Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80737 views
1
// Generated by CoffeeScript 1.9.1
2
var BANNER, CoffeeScript, EventEmitter, SWITCHES, cjsxTransform, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, findDirectoryIndex, forkNode, fs, helpers, hidden, joinTimeout, mkdirp, notSources, optionParser, optparse, opts, outputPath, parseOptions, path, printLine, printTokens, printWarn, ref, removeSource, removeSourceDir, silentUnlink, sourceCode, sources, spawn, timeLog, usage, useWinPathSep, version, wait, watch, watchDir, watchedDirs, writeJs,
3
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
4
5
fs = require('fs');
6
7
path = require('path');
8
9
helpers = require('./helpers');
10
11
optparse = require('coffee-script/lib/coffee-script/optparse');
12
13
CoffeeScript = require('./coffee-react-script');
14
15
mkdirp = require('mkdirp');
16
17
ref = require('child_process'), spawn = ref.spawn, exec = ref.exec;
18
19
EventEmitter = require('events').EventEmitter;
20
21
cjsxTransform = require('coffee-react-transform');
22
23
useWinPathSep = path.sep === '\\';
24
25
helpers.extend(CoffeeScript, new EventEmitter);
26
27
printLine = function(line) {
28
return process.stdout.write(line + '\n');
29
};
30
31
printWarn = function(line) {
32
return process.stderr.write(line + '\n');
33
};
34
35
hidden = function(file) {
36
return /^\.|~$/.test(file);
37
};
38
39
BANNER = 'Usage: cjsx [options] path/to/script.cjsx -- [args]\n\nIf called without options, `cjsx` will run your script.';
40
41
SWITCHES = [['-b', '--bare', 'compile without a top-level function wrapper'], ['-c', '--compile', 'compile to JavaScript and save as .js files'], ['-e', '--eval', 'pass a string from the command line as input'], ['-h', '--help', 'display this help message'], ['-j', '--join [FILE]', 'concatenate the source CoffeeScript before compiling'], ['-m', '--map', 'generate source map and save as .map files'], ['-n', '--nodes', 'print out the parse tree that the parser produces'], ['--nodejs [ARGS]', 'pass options directly to the "node" binary'], ['--no-header', 'suppress the "Generated by" header'], ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'], ['-p', '--print', 'print out the compiled JavaScript'], ['-s', '--stdio', 'listen for and compile scripts over stdio'], ['-l', '--literate', 'treat stdio as literate style coffee-script'], ['-t', '--tokens', 'print out the tokens that the lexer/rewriter produce'], ['-v', '--version', 'display the version number'], ['-w', '--watch', 'watch scripts for changes and rerun commands']];
42
43
opts = {};
44
45
sources = [];
46
47
sourceCode = [];
48
49
notSources = {};
50
51
watchedDirs = {};
52
53
optionParser = null;
54
55
exports.run = function() {
56
var i, len, literals, ref1, replCliOpts, results, source;
57
parseOptions();
58
replCliOpts = {
59
useGlobal: true
60
};
61
if (opts.nodejs) {
62
return forkNode();
63
}
64
if (opts.help) {
65
return usage();
66
}
67
if (opts.version) {
68
return version();
69
}
70
if (opts.stdio) {
71
return compileStdio();
72
}
73
if (opts["eval"]) {
74
return compileScript(null, opts["arguments"][0]);
75
}
76
if (!opts["arguments"].length) {
77
return usage();
78
}
79
literals = opts.run ? opts["arguments"].splice(1) : [];
80
process.argv = process.argv.slice(0, 2).concat(literals);
81
process.argv[0] = 'cjsx';
82
if (opts.output) {
83
opts.output = path.resolve(opts.output);
84
}
85
if (opts.join) {
86
opts.join = path.resolve(opts.join);
87
}
88
ref1 = opts["arguments"];
89
results = [];
90
for (i = 0, len = ref1.length; i < len; i++) {
91
source = ref1[i];
92
source = path.resolve(source);
93
results.push(compilePath(source, true, source));
94
}
95
return results;
96
};
97
98
compilePath = function(source, topLevel, base) {
99
var code, err, file, files, i, len, results, stats;
100
if (indexOf.call(sources, source) >= 0 || watchedDirs[source] || !topLevel && (notSources[source] || hidden(source))) {
101
return;
102
}
103
try {
104
stats = fs.statSync(source);
105
} catch (_error) {
106
err = _error;
107
if (err.code === 'ENOENT') {
108
console.error("File not found: " + source);
109
process.exit(1);
110
}
111
throw err;
112
}
113
if (stats.isDirectory()) {
114
if (path.basename(source) === 'node_modules') {
115
notSources[source] = true;
116
return;
117
}
118
if (opts.run) {
119
compilePath(findDirectoryIndex(source), topLevel, base);
120
return;
121
}
122
if (opts.watch) {
123
watchDir(source, base);
124
}
125
try {
126
files = fs.readdirSync(source);
127
} catch (_error) {
128
err = _error;
129
if (err.code === 'ENOENT') {
130
return;
131
} else {
132
throw err;
133
}
134
}
135
results = [];
136
for (i = 0, len = files.length; i < len; i++) {
137
file = files[i];
138
results.push(compilePath(path.join(source, file), false, base));
139
}
140
return results;
141
} else if (topLevel || helpers.isCoffee(source)) {
142
sources.push(source);
143
sourceCode.push(null);
144
delete notSources[source];
145
if (opts.watch) {
146
watch(source, base);
147
}
148
try {
149
code = fs.readFileSync(source);
150
} catch (_error) {
151
err = _error;
152
if (err.code === 'ENOENT') {
153
return;
154
} else {
155
throw err;
156
}
157
}
158
return compileScript(source, code.toString(), base);
159
} else {
160
return notSources[source] = true;
161
}
162
};
163
164
findDirectoryIndex = function(source) {
165
var err, ext, i, index, len, ref1;
166
ref1 = CoffeeScript.FILE_EXTENSIONS;
167
for (i = 0, len = ref1.length; i < len; i++) {
168
ext = ref1[i];
169
index = path.join(source, "index" + ext);
170
try {
171
if ((fs.statSync(index)).isFile()) {
172
return index;
173
}
174
} catch (_error) {
175
err = _error;
176
if (err.code !== 'ENOENT') {
177
throw err;
178
}
179
}
180
}
181
console.error("Missing index.coffee or index.litcoffee in " + source);
182
return process.exit(1);
183
};
184
185
compileScript = function(file, cjsxinput, base) {
186
var compiled, err, input, message, o, options, t, task;
187
if (base == null) {
188
base = null;
189
}
190
o = opts;
191
options = compileOptions(file, base);
192
try {
193
if (((file != null) && helpers.hasCJSXExtension(file)) || helpers.hasCJSXPragma(cjsxinput)) {
194
input = cjsxTransform(cjsxinput);
195
} else {
196
input = cjsxinput;
197
}
198
t = task = {
199
file: file,
200
input: input,
201
options: options
202
};
203
CoffeeScript.emit('compile', task);
204
if (o.tokens) {
205
return printTokens(CoffeeScript.tokens(t.input, t.options));
206
} else if (o.nodes) {
207
return printLine(CoffeeScript.nodes(t.input, t.options).toString().trim());
208
} else if (o.run) {
209
CoffeeScript.register();
210
return CoffeeScript.run(t.input, t.options);
211
} else if (o.join && t.file !== o.join) {
212
if (helpers.isLiterate(file)) {
213
t.input = helpers.invertLiterate(t.input);
214
}
215
sourceCode[sources.indexOf(t.file)] = t.input;
216
return compileJoin();
217
} else {
218
compiled = CoffeeScript.compile(t.input, t.options);
219
t.output = compiled;
220
if (o.map) {
221
t.output = compiled.js;
222
t.sourceMap = compiled.v3SourceMap;
223
}
224
CoffeeScript.emit('success', task);
225
if (o.print) {
226
return printLine(t.output.trim());
227
} else if (o.compile || o.map) {
228
return writeJs(base, t.file, t.output, options.jsPath, t.sourceMap);
229
}
230
}
231
} catch (_error) {
232
err = _error;
233
CoffeeScript.emit('failure', err, task);
234
if (CoffeeScript.listeners('failure').length) {
235
return;
236
}
237
message = err.stack || ("" + err);
238
if (o.watch) {
239
return printLine(message + '\x07');
240
} else {
241
printWarn(message);
242
return process.exit(1);
243
}
244
}
245
};
246
247
compileStdio = function() {
248
var code, stdin;
249
code = '';
250
stdin = process.openStdin();
251
stdin.on('data', function(buffer) {
252
if (buffer) {
253
return code += buffer.toString();
254
}
255
});
256
return stdin.on('end', function() {
257
return compileScript(null, code);
258
});
259
};
260
261
joinTimeout = null;
262
263
compileJoin = function() {
264
if (!opts.join) {
265
return;
266
}
267
if (!sourceCode.some(function(code) {
268
return code === null;
269
})) {
270
clearTimeout(joinTimeout);
271
return joinTimeout = wait(100, function() {
272
return compileScript(opts.join, sourceCode.join('\n'), opts.join);
273
});
274
}
275
};
276
277
watch = function(source, base) {
278
var compile, compileTimeout, err, prevStats, rewatch, startWatcher, watchErr, watcher;
279
watcher = null;
280
prevStats = null;
281
compileTimeout = null;
282
watchErr = function(err) {
283
if (err.code !== 'ENOENT') {
284
throw err;
285
}
286
if (indexOf.call(sources, source) < 0) {
287
return;
288
}
289
try {
290
rewatch();
291
return compile();
292
} catch (_error) {
293
removeSource(source, base);
294
return compileJoin();
295
}
296
};
297
compile = function() {
298
clearTimeout(compileTimeout);
299
return compileTimeout = wait(25, function() {
300
return fs.stat(source, function(err, stats) {
301
if (err) {
302
return watchErr(err);
303
}
304
if (prevStats && stats.size === prevStats.size && stats.mtime.getTime() === prevStats.mtime.getTime()) {
305
return rewatch();
306
}
307
prevStats = stats;
308
return fs.readFile(source, function(err, code) {
309
if (err) {
310
return watchErr(err);
311
}
312
compileScript(source, code.toString(), base);
313
return rewatch();
314
});
315
});
316
});
317
};
318
startWatcher = function() {
319
return watcher = fs.watch(source).on('change', compile).on('error', function(err) {
320
if (err.code !== 'EPERM') {
321
throw err;
322
}
323
return removeSource(source, base);
324
});
325
};
326
rewatch = function() {
327
if (watcher != null) {
328
watcher.close();
329
}
330
return startWatcher();
331
};
332
try {
333
return startWatcher();
334
} catch (_error) {
335
err = _error;
336
return watchErr(err);
337
}
338
};
339
340
watchDir = function(source, base) {
341
var err, readdirTimeout, startWatcher, stopWatcher, watcher;
342
watcher = null;
343
readdirTimeout = null;
344
startWatcher = function() {
345
return watcher = fs.watch(source).on('error', function(err) {
346
if (err.code !== 'EPERM') {
347
throw err;
348
}
349
return stopWatcher();
350
}).on('change', function() {
351
clearTimeout(readdirTimeout);
352
return readdirTimeout = wait(25, function() {
353
var err, file, files, i, len, results;
354
try {
355
files = fs.readdirSync(source);
356
} catch (_error) {
357
err = _error;
358
if (err.code !== 'ENOENT') {
359
throw err;
360
}
361
return stopWatcher();
362
}
363
results = [];
364
for (i = 0, len = files.length; i < len; i++) {
365
file = files[i];
366
results.push(compilePath(path.join(source, file), false, base));
367
}
368
return results;
369
});
370
});
371
};
372
stopWatcher = function() {
373
watcher.close();
374
return removeSourceDir(source, base);
375
};
376
watchedDirs[source] = true;
377
try {
378
return startWatcher();
379
} catch (_error) {
380
err = _error;
381
if (err.code !== 'ENOENT') {
382
throw err;
383
}
384
}
385
};
386
387
removeSourceDir = function(source, base) {
388
var file, i, len, sourcesChanged;
389
delete watchedDirs[source];
390
sourcesChanged = false;
391
for (i = 0, len = sources.length; i < len; i++) {
392
file = sources[i];
393
if (!(source === path.dirname(file))) {
394
continue;
395
}
396
removeSource(file, base);
397
sourcesChanged = true;
398
}
399
if (sourcesChanged) {
400
return compileJoin();
401
}
402
};
403
404
removeSource = function(source, base) {
405
var index;
406
index = sources.indexOf(source);
407
sources.splice(index, 1);
408
sourceCode.splice(index, 1);
409
if (!opts.join) {
410
silentUnlink(outputPath(source, base));
411
silentUnlink(outputPath(source, base, '.map'));
412
return timeLog("removed " + source);
413
}
414
};
415
416
silentUnlink = function(path) {
417
var err, ref1;
418
try {
419
return fs.unlinkSync(path);
420
} catch (_error) {
421
err = _error;
422
if ((ref1 = err.code) !== 'ENOENT' && ref1 !== 'EPERM') {
423
throw err;
424
}
425
}
426
};
427
428
outputPath = function(source, base, extension) {
429
var basename, dir, srcDir;
430
if (extension == null) {
431
extension = ".js";
432
}
433
basename = helpers.baseFileName(source, true, useWinPathSep);
434
srcDir = path.dirname(source);
435
if (!opts.output) {
436
dir = srcDir;
437
} else if (source === base) {
438
dir = opts.output;
439
} else {
440
dir = path.join(opts.output, path.relative(base, srcDir));
441
}
442
return path.join(dir, basename + extension);
443
};
444
445
writeJs = function(base, sourcePath, js, jsPath, generatedSourceMap) {
446
var compile, jsDir, sourceMapPath;
447
if (generatedSourceMap == null) {
448
generatedSourceMap = null;
449
}
450
sourceMapPath = outputPath(sourcePath, base, ".map");
451
jsDir = path.dirname(jsPath);
452
compile = function() {
453
if (opts.compile) {
454
if (js.length <= 0) {
455
js = ' ';
456
}
457
if (generatedSourceMap) {
458
js = js + "\n//# sourceMappingURL=" + (helpers.baseFileName(sourceMapPath, false, useWinPathSep)) + "\n";
459
}
460
fs.writeFile(jsPath, js, function(err) {
461
if (err) {
462
return printLine(err.message);
463
} else if (opts.compile && opts.watch) {
464
return timeLog("compiled " + sourcePath);
465
}
466
});
467
}
468
if (generatedSourceMap) {
469
return fs.writeFile(sourceMapPath, generatedSourceMap, function(err) {
470
if (err) {
471
return printLine("Could not write source map: " + err.message);
472
}
473
});
474
}
475
};
476
return fs.exists(jsDir, function(itExists) {
477
if (itExists) {
478
return compile();
479
} else {
480
return mkdirp(jsDir, compile);
481
}
482
});
483
};
484
485
wait = function(milliseconds, func) {
486
return setTimeout(func, milliseconds);
487
};
488
489
timeLog = function(message) {
490
return console.log(((new Date).toLocaleTimeString()) + " - " + message);
491
};
492
493
printTokens = function(tokens) {
494
var strings, tag, token, value;
495
strings = (function() {
496
var i, len, results;
497
results = [];
498
for (i = 0, len = tokens.length; i < len; i++) {
499
token = tokens[i];
500
tag = token[0];
501
value = token[1].toString().replace(/\n/, '\\n');
502
results.push("[" + tag + " " + value + "]");
503
}
504
return results;
505
})();
506
return printLine(strings.join(' '));
507
};
508
509
parseOptions = function() {
510
var o;
511
optionParser = new optparse.OptionParser(SWITCHES, BANNER);
512
o = opts = optionParser.parse(process.argv.slice(2));
513
o.compile || (o.compile = !!o.output);
514
o.run = !(o.compile || o.print || o.map);
515
return o.print = !!(o.print || (o["eval"] || o.stdio && o.compile));
516
};
517
518
compileOptions = function(filename, base) {
519
var answer, cwd, jsDir, jsPath;
520
answer = {
521
filename: filename,
522
literate: opts.literate || helpers.isLiterate(filename),
523
bare: opts.bare,
524
header: opts.compile && !opts['no-header'],
525
sourceMap: opts.map
526
};
527
if (filename) {
528
if (base) {
529
cwd = process.cwd();
530
jsPath = outputPath(filename, base);
531
jsDir = path.dirname(jsPath);
532
answer = helpers.merge(answer, {
533
jsPath: jsPath,
534
sourceRoot: path.relative(jsDir, cwd),
535
sourceFiles: [path.relative(cwd, filename)],
536
generatedFile: helpers.baseFileName(jsPath, false, useWinPathSep)
537
});
538
} else {
539
answer = helpers.merge(answer, {
540
sourceRoot: "",
541
sourceFiles: [helpers.baseFileName(filename, false, useWinPathSep)],
542
generatedFile: helpers.baseFileName(filename, true, useWinPathSep) + ".js"
543
});
544
}
545
}
546
return answer;
547
};
548
549
forkNode = function() {
550
var args, nodeArgs, p;
551
nodeArgs = opts.nodejs.split(/\s+/);
552
args = process.argv.slice(1);
553
args.splice(args.indexOf('--nodejs'), 2);
554
p = spawn(process.execPath, nodeArgs.concat(args), {
555
cwd: process.cwd(),
556
env: process.env,
557
customFds: [0, 1, 2]
558
});
559
return p.on('exit', function(code) {
560
return process.exit(code);
561
});
562
};
563
564
usage = function() {
565
return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help());
566
};
567
568
version = function() {
569
var cjsxversion;
570
version = require('../package.json').version;
571
cjsxversion = require('coffee-react-transform/package.json').version;
572
printLine("coffee-react version " + version);
573
printLine("coffee-react-transform version " + cjsxversion);
574
return printLine("coffee-script version " + CoffeeScript.VERSION);
575
};
576
577