1 | import MagicString from 'magic-string';
|
2 | import { createFilter } from 'rollup-pluginutils';
|
3 | import { extname } from 'path';
|
4 |
|
5 | function postproc (code, opts) {
|
6 | if (!opts) opts = {}
|
7 |
|
8 | if (opts.cleanup === false) {
|
9 | return { code: code }
|
10 | }
|
11 | opts.sourceMap = opts.sourceMap !== false
|
12 |
|
13 | var magicStr = new MagicString(code)
|
14 |
|
15 | var eolTo = opts.eolType === 'win' ? '\r\n' : opts.eolType === 'mac' ? '\r' : '\n'
|
16 | var empties = opts.maxEmptyLines
|
17 |
|
18 | var maxEolChars = empties < 0 ? 0x7fffffff : empties ? empties * eolTo.length : 0
|
19 |
|
20 |
|
21 | var regex = /(\s*[\r\n])\s*\S/g
|
22 |
|
23 | var match, block, changes
|
24 |
|
25 |
|
26 | match = code.match(/^(\s*[\r\n])\s*\S/)
|
27 | if (match) {
|
28 | block = match[1]
|
29 | replaceBlock(block, 0, limitLines(block))
|
30 | regex.lastIndex = match[0].length
|
31 | }
|
32 |
|
33 |
|
34 | maxEolChars += eolTo.length
|
35 |
|
36 | if (empties) {
|
37 |
|
38 | while ((match = regex.exec(code))) {
|
39 | block = match[1]
|
40 | replaceBlock(block, match.index, limitLines(block))
|
41 | }
|
42 | } else {
|
43 |
|
44 | while ((match = regex.exec(code))) {
|
45 | replaceBlock(match[1], match.index, eolTo)
|
46 | }
|
47 | }
|
48 |
|
49 |
|
50 | match = code.match(/\s+$/)
|
51 | if (match) {
|
52 | block = match[0]
|
53 | replaceBlock(block, match.index, /[\r\n]/.test(block) ? limitLines(block) : '')
|
54 | }
|
55 |
|
56 | var result = {
|
57 | code: changes ? magicStr.toString() : code
|
58 | }
|
59 | if (changes && opts.sourceMap) {
|
60 | result.map = magicStr.generateMap({ hires: true })
|
61 | }
|
62 | return result
|
63 |
|
64 |
|
65 |
|
66 | function replaceBlock (str, start, rep) {
|
67 | if (str === rep) return
|
68 | magicStr.overwrite(start, start + str.length, rep)
|
69 | changes = true
|
70 | }
|
71 |
|
72 | function limitLines (str) {
|
73 | var ss = str.replace(/[ \t]*(?:\r\n?|\n)/g, eolTo)
|
74 | if (ss.length > maxEolChars) ss = ss.slice(0, maxEolChars)
|
75 | return ss
|
76 | }
|
77 | }
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | function _createFilter (opts) {
|
88 | if (!opts) opts = {}
|
89 |
|
90 | var flt1 = createFilter(opts.include, opts.exclude)
|
91 | var flt2 = opts.extensions &&
|
92 | opts.extensions.map(function (e) { return (e[0] !== '.' ? '.' + e : e).toLowerCase(); }) || ['.js']
|
93 |
|
94 | return function (name) {
|
95 | return flt1(name) && flt2.indexOf(extname(name).toLowerCase()) > -1
|
96 | }
|
97 | }
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 | function jspp (options) {
|
104 |
|
105 |
|
106 | var filter = _createFilter(options)
|
107 |
|
108 | return {
|
109 |
|
110 | name: 'cleanup',
|
111 |
|
112 | transform: function transform (code, id) {
|
113 | return filter(id)
|
114 | ? postproc(code, options)
|
115 | : null
|
116 | }
|
117 | }
|
118 | }
|
119 |
|
120 | export default jspp; |
\ | No newline at end of file |