js-beautify 1.7.0 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/CONTRIBUTING.md +3 -3
  3. package/README.md +15 -12
  4. package/js/bin/css-beautify.js +4 -0
  5. package/js/bin/html-beautify.js +4 -0
  6. package/js/bin/js-beautify.js +4 -0
  7. package/js/config/defaults.json +18 -0
  8. package/js/lib/beautify-css.js +1046 -0
  9. package/js/lib/beautify-html.js +1387 -0
  10. package/js/lib/beautify.js +2820 -0
  11. package/js/lib/cli.js +623 -0
  12. package/js/lib/unpackers/javascriptobfuscator_unpacker.js +103 -0
  13. package/js/lib/unpackers/myobfuscate_unpacker.js +90 -0
  14. package/js/lib/unpackers/p_a_c_k_e_r_unpacker.js +83 -0
  15. package/js/lib/unpackers/urlencode_unpacker.js +73 -0
  16. package/js/src/core/acorn.js +63 -0
  17. package/js/src/core/inputscanner.js +95 -0
  18. package/js/src/core/options.js +48 -0
  19. package/js/src/core/output.js +234 -0
  20. package/js/src/core/token.js +49 -0
  21. package/js/src/css/beautifier.js +477 -0
  22. package/js/src/css/index.js +36 -0
  23. package/js/src/html/beautifier.js +1035 -0
  24. package/js/src/html/index.js +36 -0
  25. package/js/src/index.js +27 -0
  26. package/js/src/javascript/beautifier.js +1449 -0
  27. package/js/src/javascript/index.js +36 -0
  28. package/js/src/javascript/tokenizer.js +620 -0
  29. package/js/test/amd-beautify-tests.js +62 -0
  30. package/js/test/generated/beautify-css-tests.js +1393 -0
  31. package/js/test/generated/beautify-html-tests.js +3212 -0
  32. package/js/test/generated/beautify-javascript-tests.js +5896 -0
  33. package/js/test/node-beautify-html-perf-tests.js +51 -0
  34. package/js/test/node-beautify-perf-tests.js +50 -0
  35. package/js/test/node-beautify-tests.js +45 -0
  36. package/js/test/requirejs-html-beautify.html +58 -0
  37. package/js/test/resources/configerror/.jsbeautifyrc +6 -0
  38. package/js/test/resources/configerror/subDir1/subDir2/empty.txt +0 -0
  39. package/js/test/resources/editorconfig/.editorconfig +6 -0
  40. package/js/test/resources/editorconfig/cr/.editorconfig +3 -0
  41. package/js/test/resources/editorconfig/crlf/.editorconfig +3 -0
  42. package/js/test/resources/editorconfig/error/.editorconfig +1 -0
  43. package/js/test/resources/editorconfig/example-base.js +3 -0
  44. package/js/test/resources/example1.js +3 -0
  45. package/js/test/resources/indent11chars/.jsbeautifyrc +6 -0
  46. package/js/test/resources/indent11chars/subDir1/subDir2/empty.txt +0 -0
  47. package/js/test/run-tests +17 -0
  48. package/js/test/sanitytest.js +144 -0
  49. package/js/test/shell-smoke-test.sh +383 -0
  50. package/package.json +1 -1
package/js/lib/cli.js ADDED
@@ -0,0 +1,623 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ The MIT License (MIT)
5
+
6
+ Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors.
7
+
8
+ Permission is hereby granted, free of charge, to any person
9
+ obtaining a copy of this software and associated documentation files
10
+ (the "Software"), to deal in the Software without restriction,
11
+ including without limitation the rights to use, copy, modify, merge,
12
+ publish, distribute, sublicense, and/or sell copies of the Software,
13
+ and to permit persons to whom the Software is furnished to do so,
14
+ subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be
17
+ included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
23
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
24
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Js-Beautify Command-line for node.js
29
+ -------------------------------------
30
+
31
+ Written by Daniel Stockman (daniel.stockman@gmail.com)
32
+
33
+ */
34
+
35
+ var debug = process.env.DEBUG_JSBEAUTIFY || process.env.JSBEAUTIFY_DEBUG ? function() {
36
+ console.error.apply(console, arguments);
37
+ } : function() {};
38
+
39
+ var fs = require('fs'),
40
+ cc = require('config-chain'),
41
+ beautify = require('../index'),
42
+ mkdirp = require('mkdirp'),
43
+ nopt = require('nopt');
44
+ nopt.typeDefs.brace_style = {
45
+ type: "brace_style",
46
+ validate: function(data, key, val) {
47
+ data[key] = val;
48
+ // TODO: expand-strict is obsolete, now identical to expand. Remove in future version
49
+ // TODO: collapse-preserve-inline is obselete, now identical to collapse,preserve-inline = true. Remove in future version
50
+ var validVals = ["collapse", "collapse-preserve-inline", "expand", "end-expand", "expand-strict", "none"];
51
+ var valSplit = val.split(/[^a-zA-Z0-9_\-]+/);
52
+ for (var i = 0; i < validVals.length; i++) {
53
+ if (validVals[i] === val || validVals[i] === valSplit[0] && valSplit[1] === "preserve-inline") {
54
+ return true;
55
+ }
56
+ }
57
+ return false;
58
+ }
59
+ };
60
+ var path = require('path'),
61
+ editorconfig = require('editorconfig'),
62
+ knownOpts = {
63
+ // Beautifier
64
+ "indent_size": Number,
65
+ "indent_char": String,
66
+ "eol": String,
67
+ "indent_level": Number,
68
+ "indent_with_tabs": Boolean,
69
+ "preserve_newlines": Boolean,
70
+ "max_preserve_newlines": Number,
71
+ "space_in_paren": Boolean,
72
+ "space_in_empty_paren": Boolean,
73
+ "jslint_happy": Boolean,
74
+ "space_after_anon_function": Boolean,
75
+ "brace_style": "brace_style", //See above for validation
76
+ "unindent_chained_methods": Boolean,
77
+ "break_chained_methods": Boolean,
78
+ "keep_array_indentation": Boolean,
79
+ "unescape_strings": Boolean,
80
+ "wrap_line_length": Number,
81
+ "wrap_attributes": ["auto", "force", "force-aligned"],
82
+ "wrap_attributes_indent_size": Number,
83
+ "e4x": Boolean,
84
+ "end_with_newline": Boolean,
85
+ "comma_first": Boolean,
86
+ "operator_position": ["before-newline", "after-newline", "preserve-newline"],
87
+ // CSS-only
88
+ "selector_separator_newline": Boolean,
89
+ "newline_between_rules": Boolean,
90
+ "space_around_combinator": Boolean,
91
+ //deprecated - replaced with space_around_combinator, remove in future version
92
+ "space_around_selector_separator": Boolean,
93
+ // HTML-only
94
+ "max_char": Number, // obsolete since 1.3.5
95
+ "unformatted": [String, Array],
96
+ "content_unformatted": [String, Array],
97
+ "indent_inner_html": [Boolean],
98
+ "indent_handlebars": [Boolean],
99
+ "indent_scripts": ["keep", "separate", "normal"],
100
+ "extra_liners": [String, Array],
101
+ // CLI
102
+ "version": Boolean,
103
+ "help": Boolean,
104
+ "files": [path, Array],
105
+ "outfile": path,
106
+ "replace": Boolean,
107
+ "quiet": Boolean,
108
+ "type": ["js", "css", "html"],
109
+ "config": path,
110
+ "editorconfig": Boolean
111
+ },
112
+ // dasherizeShorthands provides { "indent-size": ["--indent_size"] }
113
+ // translation, allowing more convenient dashes in CLI arguments
114
+ shortHands = dasherizeShorthands({
115
+ // Beautifier
116
+ "s": ["--indent_size"],
117
+ "c": ["--indent_char"],
118
+ "e": ["--eol"],
119
+ "l": ["--indent_level"],
120
+ "t": ["--indent_with_tabs"],
121
+ "p": ["--preserve_newlines"],
122
+ "m": ["--max_preserve_newlines"],
123
+ "P": ["--space_in_paren"],
124
+ "Q": ["--space_in_empty_paren"],
125
+ "j": ["--jslint_happy"],
126
+ "a": ["--space_after_anon_function"],
127
+ "b": ["--brace_style"],
128
+ "u": ["--unindent_chained_methods"],
129
+ "B": ["--break_chained_methods"],
130
+ "k": ["--keep_array_indentation"],
131
+ "x": ["--unescape_strings"],
132
+ "w": ["--wrap_line_length"],
133
+ "X": ["--e4x"],
134
+ "n": ["--end_with_newline"],
135
+ "C": ["--comma_first"],
136
+ "O": ["--operator_position"],
137
+ // CSS-only
138
+ "L": ["--selector_separator_newline"],
139
+ "N": ["--newline_between_rules"],
140
+ // HTML-only
141
+ "A": ["--wrap_attributes"],
142
+ "i": ["--wrap_attributes_indent_size"],
143
+ "W": ["--max_char"], // obsolete since 1.3.5
144
+ "U": ["--unformatted"],
145
+ "T": ["--content_unformatted"],
146
+ "I": ["--indent_inner_html"],
147
+ "H": ["--indent_handlebars"],
148
+ "S": ["--indent_scripts"],
149
+ "E": ["--extra_liners"],
150
+ // non-dasherized hybrid shortcuts
151
+ "good-stuff": [
152
+ "--keep_array_indentation",
153
+ "--keep_function_indentation",
154
+ "--jslint_happy"
155
+ ],
156
+ "js": ["--type", "js"],
157
+ "css": ["--type", "css"],
158
+ "html": ["--type", "html"],
159
+ // CLI
160
+ "v": ["--version"],
161
+ "h": ["--help"],
162
+ "f": ["--files"],
163
+ "o": ["--outfile"],
164
+ "r": ["--replace"],
165
+ "q": ["--quiet"]
166
+ // no shorthand for "config"
167
+ // no shorthand for "editorconfig"
168
+ });
169
+
170
+ function verifyExists(fullPath) {
171
+ return fs.existsSync(fullPath) ? fullPath : null;
172
+ }
173
+
174
+ function findRecursive(dir, fileName) {
175
+ var fullPath = path.join(dir, fileName);
176
+ var nextDir = path.dirname(dir);
177
+ var result = verifyExists(fullPath);
178
+
179
+ if (!result && (nextDir !== dir)) {
180
+ result = findRecursive(nextDir, fileName);
181
+ }
182
+
183
+ return result;
184
+ }
185
+
186
+ function getUserHome() {
187
+ var user_home = '';
188
+ try {
189
+ user_home = process.env.USERPROFILE || process.env.HOME || '';
190
+ } catch (ex) {}
191
+ return user_home;
192
+ }
193
+
194
+ function set_file_editorconfig_opts(file, config) {
195
+ try {
196
+ var eConfigs = editorconfig.parseSync(file);
197
+
198
+ if (eConfigs.indent_style === "tab") {
199
+ config.indent_with_tabs = true;
200
+ } else if (eConfigs.indent_style === "space") {
201
+ config.indent_with_tabs = false;
202
+ }
203
+
204
+ if (eConfigs.indent_size) {
205
+ config.indent_size = eConfigs.indent_size;
206
+ }
207
+
208
+ if (eConfigs.max_line_length) {
209
+ if (eConfigs.max_line_length === "off") {
210
+ config.wrap_line_length = 0;
211
+ } else {
212
+ config.wrap_line_length = parseInt(eConfigs.max_line_length);
213
+ }
214
+ }
215
+
216
+ if (eConfigs.insert_final_newline === true) {
217
+ config.end_with_newline = true;
218
+ } else if (eConfigs.insert_final_newline === false) {
219
+ config.end_with_newline = false;
220
+ }
221
+
222
+ if (eConfigs.end_of_line) {
223
+ if (eConfigs.end_of_line === 'cr') {
224
+ config.eol = '\r';
225
+ } else if (eConfigs.end_of_line === 'lf') {
226
+ config.eol = '\n';
227
+ } else if (eConfigs.end_of_line === 'crlf') {
228
+ config.eol = '\r\n';
229
+ }
230
+ }
231
+ } catch (e) {
232
+ debug(e);
233
+ }
234
+ }
235
+
236
+ // var cli = require('js-beautify/cli'); cli.interpret();
237
+ var interpret = exports.interpret = function(argv, slice) {
238
+ var parsed = nopt(knownOpts, shortHands, argv, slice);
239
+
240
+ if (parsed.version) {
241
+ console.log(require('../../package.json').version);
242
+ process.exit(0);
243
+ } else if (parsed.help) {
244
+ usage();
245
+ process.exit(0);
246
+ }
247
+
248
+ var cfg;
249
+ var configRecursive = findRecursive(process.cwd(), '.jsbeautifyrc');
250
+ var configHome = verifyExists(path.join(getUserHome() || "", ".jsbeautifyrc"));
251
+ var configDefault = __dirname + '/../config/defaults.json';
252
+
253
+ try {
254
+ cfg = cc(
255
+ parsed,
256
+ cleanOptions(cc.env('jsbeautify_'), knownOpts),
257
+ parsed.config,
258
+ configRecursive,
259
+ configHome,
260
+ configDefault
261
+ ).snapshot;
262
+ } catch (ex) {
263
+ debug(cfg);
264
+ // usage(ex);
265
+ console.error(ex);
266
+ console.error('Error while loading beautifier configuration.');
267
+ console.error('Configuration file chain included:');
268
+ if (parsed.config) {
269
+ console.error(parsed.config);
270
+ }
271
+ if (configRecursive) {
272
+ console.error(configRecursive);
273
+ }
274
+ if (configHome) {
275
+ console.error(configHome);
276
+ }
277
+ console.error(configDefault);
278
+ console.error('Run `' + getScriptName() + ' -h` for help.');
279
+ process.exit(1);
280
+ }
281
+
282
+ try {
283
+ // Verify arguments
284
+ checkType(cfg);
285
+ checkFiles(cfg);
286
+ debug(cfg);
287
+
288
+ // Process files synchronously to avoid EMFILE error
289
+ cfg.files.forEach(processInputSync, {
290
+ cfg: cfg
291
+ });
292
+ } catch (ex) {
293
+ debug(cfg);
294
+ // usage(ex);
295
+ console.error(ex);
296
+ console.error('Run `' + getScriptName() + ' -h` for help.');
297
+ process.exit(1);
298
+ }
299
+ };
300
+
301
+ // interpret args immediately when called as executable
302
+ if (require.main === module) {
303
+ interpret();
304
+ }
305
+
306
+ function usage(err) {
307
+ var scriptName = getScriptName();
308
+ var msg = [
309
+ scriptName + '@' + require('../../package.json').version,
310
+ '',
311
+ 'CLI Options:',
312
+ ' -f, --file Input file(s) (Pass \'-\' for stdin)',
313
+ ' -r, --replace Write output in-place, replacing input',
314
+ ' -o, --outfile Write output to file (default stdout)',
315
+ ' --config Path to config file',
316
+ ' --type [js|css|html] ["js"]',
317
+ ' -q, --quiet Suppress logging to stdout',
318
+ ' -h, --help Show this help',
319
+ ' -v, --version Show the version',
320
+ '',
321
+ 'Beautifier Options:',
322
+ ' -s, --indent-size Indentation size [4]',
323
+ ' -c, --indent-char Indentation character [" "]',
324
+ ' -t, --indent-with-tabs Indent with tabs, overrides -s and -c',
325
+ ' -e, --eol Character(s) to use as line terminators.',
326
+ ' [first newline in file, otherwise "\\n]',
327
+ ' -n, --end-with-newline End output with newline',
328
+ ' --editorconfig Use EditorConfig to set up the options'
329
+ ];
330
+
331
+ switch (scriptName.split('-').shift()) {
332
+ case "js":
333
+ msg.push(' -l, --indent-level Initial indentation level [0]');
334
+ msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)');
335
+ msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]');
336
+ msg.push(' -P, --space-in-paren Add padding spaces within paren, ie. f( a, b )');
337
+ msg.push(' -E, --space-in-empty-paren Add a single space inside empty paren, ie. f( )');
338
+ msg.push(' -j, --jslint-happy Enable jslint-stricter mode');
339
+ msg.push(' -a, --space-after-anon-function Add a space before an anonymous function\'s parens, ie. function ()');
340
+ msg.push(' -b, --brace-style [collapse|expand|end-expand|none][,preserve-inline] [collapse,preserve-inline]');
341
+ msg.push(' -u, --unindent-chained-methods Don\'t indent chained method calls');
342
+ msg.push(' -B, --break-chained-methods Break chained method calls across subsequent lines');
343
+ msg.push(' -k, --keep-array-indentation Preserve array indentation');
344
+ msg.push(' -x, --unescape-strings Decode printable characters encoded in xNN notation');
345
+ msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]');
346
+ msg.push(' -X, --e4x Pass E4X xml literals through untouched');
347
+ msg.push(' --good-stuff Warm the cockles of Crockford\'s heart');
348
+ msg.push(' -C, --comma-first Put commas at the beginning of new line instead of end');
349
+ msg.push(' -O, --operator-position Set operator position (before-newline|after-newline|preserve-newline) [before-newline]');
350
+ break;
351
+ case "html":
352
+ msg.push(' -b, --brace-style [collapse|expand|end-expand] ["collapse"]');
353
+ msg.push(' -I, --indent-inner-html Indent body and head sections. Default is false.');
354
+ msg.push(' -H, --indent-handlebars Indent handlebars. Default is false.');
355
+ msg.push(' -S, --indent-scripts [keep|separate|normal] ["normal"]');
356
+ msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]');
357
+ msg.push(' -A, --wrap-attributes Wrap html tag attributes to new lines [auto|force] ["auto"]');
358
+ msg.push(' -i, --wrap-attributes-indent-size Indent wrapped tags to after N characters [indent-level]');
359
+ msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)');
360
+ msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]');
361
+ msg.push(' -U, --unformatted List of tags (defaults to inline) that should not be reformatted');
362
+ msg.push(' -T, --content_unformatted List of tags (defaults to pre) whose content should not be reformatted');
363
+ msg.push(' -E, --extra_liners List of tags (defaults to [head,body,/html] that should have an extra newline');
364
+ break;
365
+ case "css":
366
+ msg.push(' -L, --selector-separator-newline Add a newline between multiple selectors.');
367
+ msg.push(' -N, --newline-between-rules Add a newline between CSS rules.');
368
+ }
369
+
370
+ if (err) {
371
+ msg.push(err);
372
+ msg.push('');
373
+ console.error(msg.join('\n'));
374
+ } else {
375
+ console.log(msg.join('\n'));
376
+ }
377
+ }
378
+
379
+ // main iterator, {cfg} passed as thisArg of forEach call
380
+
381
+ function processInputSync(filepath) {
382
+ var data = '',
383
+ config = this.cfg,
384
+ outfile = config.outfile,
385
+ input;
386
+
387
+ // -o passed with no value overwrites
388
+ if (outfile === true || config.replace) {
389
+ outfile = filepath;
390
+ }
391
+
392
+ var fileType = getOutputType(outfile, filepath, config.type);
393
+
394
+ if (config.editorconfig) {
395
+ var editorconfig_filepath = filepath;
396
+
397
+ if (editorconfig_filepath === '-') {
398
+ if (outfile) {
399
+ editorconfig_filepath = outfile;
400
+ } else {
401
+ editorconfig_filepath = 'stdin.' + fileType;
402
+ }
403
+ }
404
+
405
+ debug("EditorConfig is enabled for ", editorconfig_filepath);
406
+ config = cc(config).snapshot;
407
+ set_file_editorconfig_opts(editorconfig_filepath, config);
408
+ debug(config);
409
+ }
410
+
411
+ if (filepath === '-') {
412
+ input = process.stdin;
413
+ input.resume();
414
+
415
+ input.setEncoding('utf8');
416
+
417
+ input.on('data', function(chunk) {
418
+ data += chunk;
419
+ });
420
+
421
+ input.on('end', function() {
422
+ makePretty(fileType, data, config, outfile, writePretty); // Where things get beautified
423
+ });
424
+ } else {
425
+ data = fs.readFileSync(filepath, 'utf8');
426
+ makePretty(fileType, data, config, outfile, writePretty);
427
+ }
428
+ }
429
+
430
+ function makePretty(fileType, code, config, outfile, callback) {
431
+ try {
432
+ var pretty = beautify[fileType](code, config);
433
+
434
+ callback(null, pretty, outfile, config);
435
+ } catch (ex) {
436
+ callback(ex);
437
+ }
438
+ }
439
+
440
+ function writePretty(err, pretty, outfile, config) {
441
+ debug('writing ' + outfile);
442
+ if (err) {
443
+ console.error(err);
444
+ process.exit(1);
445
+ }
446
+
447
+ if (outfile) {
448
+ mkdirp.sync(path.dirname(outfile));
449
+
450
+ if (isFileDifferent(outfile, pretty)) {
451
+ try {
452
+ fs.writeFileSync(outfile, pretty, 'utf8');
453
+ logToStdout('beautified ' + path.relative(process.cwd(), outfile), config);
454
+ } catch (ex) {
455
+ onOutputError(ex);
456
+ }
457
+ } else {
458
+ logToStdout('beautified ' + path.relative(process.cwd(), outfile) + ' - unchanged', config);
459
+ }
460
+ } else {
461
+ process.stdout.write(pretty);
462
+ }
463
+ }
464
+
465
+ function isFileDifferent(filePath, expected) {
466
+ try {
467
+ return fs.readFileSync(filePath, 'utf8') !== expected;
468
+ } catch (ex) {
469
+ // failing to read is the same as different
470
+ return true;
471
+ }
472
+ }
473
+
474
+ // workaround the fact that nopt.clean doesn't return the object passed in :P
475
+
476
+ function cleanOptions(data, types) {
477
+ nopt.clean(data, types);
478
+ return data;
479
+ }
480
+
481
+ // error handler for output stream that swallows errors silently,
482
+ // allowing the loop to continue over unwritable files.
483
+
484
+ function onOutputError(err) {
485
+ if (err.code === 'EACCES') {
486
+ console.error(err.path + " is not writable. Skipping!");
487
+ } else {
488
+ console.error(err);
489
+ process.exit(0);
490
+ }
491
+ }
492
+
493
+ // turn "--foo_bar" into "foo-bar"
494
+
495
+ function dasherizeFlag(str) {
496
+ return str.replace(/^\-+/, '').replace(/_/g, '-');
497
+ }
498
+
499
+ // translate weird python underscored keys into dashed argv,
500
+ // avoiding single character aliases.
501
+
502
+ function dasherizeShorthands(hash) {
503
+ // operate in-place
504
+ Object.keys(hash).forEach(function(key) {
505
+ // each key value is an array
506
+ var val = hash[key][0];
507
+ // only dasherize one-character shorthands
508
+ if (key.length === 1 && val.indexOf('_') > -1) {
509
+ hash[dasherizeFlag(val)] = val;
510
+ }
511
+ });
512
+
513
+ return hash;
514
+ }
515
+
516
+ function getOutputType(outfile, filepath, configType) {
517
+ if (outfile && /\.(js|css|html)$/.test(outfile)) {
518
+ return outfile.split('.').pop();
519
+ } else if (filepath !== '-' && /\.(js|css|html)$/.test(filepath)) {
520
+ return filepath.split('.').pop();
521
+ } else if (configType) {
522
+ return configType;
523
+ } else {
524
+ throw 'Could not determine appropriate beautifier from file paths: ' + filepath;
525
+ }
526
+ }
527
+
528
+ function getScriptName() {
529
+ return path.basename(process.argv[1]);
530
+ }
531
+
532
+ function checkType(parsed) {
533
+ var scriptType = getScriptName().split('-').shift();
534
+ if (!/^(js|css|html)$/.test(scriptType)) {
535
+ scriptType = null;
536
+ }
537
+
538
+ debug("executable type:", scriptType);
539
+
540
+ var parsedType = parsed.type;
541
+ debug("parsed type:", parsedType);
542
+
543
+ if (!parsedType) {
544
+ debug("type defaulted:", scriptType);
545
+ parsed.type = scriptType;
546
+ }
547
+ }
548
+
549
+ function checkFiles(parsed) {
550
+ var argv = parsed.argv;
551
+ var isTTY = true;
552
+
553
+ try {
554
+ isTTY = process.stdin.isTTY;
555
+ } catch (ex) {
556
+ debug("error querying for isTTY:", ex);
557
+ }
558
+
559
+ debug('isTTY: ' + isTTY);
560
+
561
+ if (!parsed.files) {
562
+ parsed.files = [];
563
+ } else {
564
+ if (argv.cooked.indexOf('-') > -1) {
565
+ // strip stdin path eagerly added by nopt in '-f -' case
566
+ parsed.files.some(removeDashedPath);
567
+ }
568
+ }
569
+
570
+ if (argv.remain.length) {
571
+ // assume any remaining args are files
572
+ argv.remain.forEach(function(f) {
573
+ if (f !== '-') {
574
+ parsed.files.push(path.resolve(f));
575
+ }
576
+ });
577
+ }
578
+
579
+ if ('string' === typeof parsed.outfile && isTTY && !parsed.files.length) {
580
+ // use outfile as input when no other files passed in args
581
+ parsed.files.push(parsed.outfile);
582
+ // operation is now an implicit overwrite
583
+ parsed.replace = true;
584
+ }
585
+
586
+ if (!parsed.files.length) {
587
+ // read stdin by default
588
+ parsed.files.push('-');
589
+ }
590
+ debug('files.length ' + parsed.files.length);
591
+
592
+ if (parsed.files.indexOf('-') > -1 && isTTY) {
593
+ throw 'Must pipe input or define at least one file.';
594
+ }
595
+
596
+ parsed.files.forEach(testFilePath);
597
+
598
+ return parsed;
599
+ }
600
+
601
+ function removeDashedPath(filepath, i, arr) {
602
+ var found = filepath.lastIndexOf('-') === (filepath.length - 1);
603
+ if (found) {
604
+ arr.splice(i, 1);
605
+ }
606
+ return found;
607
+ }
608
+
609
+ function testFilePath(filepath) {
610
+ try {
611
+ if (filepath !== "-") {
612
+ fs.statSync(filepath);
613
+ }
614
+ } catch (err) {
615
+ throw 'Unable to open path "' + filepath + '"';
616
+ }
617
+ }
618
+
619
+ function logToStdout(str, config) {
620
+ if (typeof config.quiet === "undefined" || !config.quiet) {
621
+ console.log(str);
622
+ }
623
+ }