Class: Packr::Shrinker

Inherits:
Object
  • Object
show all
Defined in:
lib/packr/shrinker.rb

Constant Summary collapse

ENCODED_DATA =
/~\^(\d+)\^~/
PREFIX =
'@'
SHRUNK =
/\@\d+\b/

Instance Method Summary collapse

Instance Method Details

#decode_data(script) ⇒ Object



8
9
10
11
# File 'lib/packr/shrinker.rb', line 8

def decode_data(script)
  # put strings and regular expressions back
  script.gsub(ENCODED_DATA) { |match| @strings[$1.to_i] }
end

#encode_data(script) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/packr/shrinker.rb', line 13

def encode_data(script)
  # encode strings and regular expressions
  @strings = [] # encoded strings and regular expressions
  DATA.exec(script, lambda { |match, *args|
    operator, regexp = args[0].to_s, args[1].to_s
    replacement = "~^#{@strings.length}^~"
    unless regexp.empty?
      replacement = operator + replacement
      match = regexp
    end
    @strings << match
    replacement
  })
end

#shrink(script, protected_names = []) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/packr/shrinker.rb', line 28

def shrink(script, protected_names = [])
  script = encode_data(script)
  protected_names ||= []
  protected_names = protected_names.map { |s| s.to_s }
  
  # identify blocks, particularly identify function blocks (which define scope)
  __block         = /((catch|do|if|while|with|function)\b[^~{};]*(\(\s*[^{};]*\s*\))\s*)?(\{[^{}]*\})/
  __brackets      = /\{[^{}]*\}|\[[^\[\]]*\]|\([^\(\)]*\)|~[^~]+~/
  __encoded_block = /~#?(\d+)~/
  __identifier    = /[a-zA-Z_$][\w\$]*/
  __scoped        = /~#(\d+)~/
  __var           = /\bvar\b/
  __vars          = /\bvar\s+[\w$]+[^;#]*|\bfunction\s+[\w$]+/
  __var_tidy      = /\b(var|function)\b|\sin\s+[^;]+/
  __var_equal     = /\s*=[^,;]*/
  
  blocks = [] # store program blocks (anything between braces {})
  total = 0
  # decoder for program blocks
  decode_blocks = lambda do |script, encoded|
    script = script.gsub(encoded) { |match| blocks[$1.to_i] } while script =~ encoded
    script
  end
  
  # encoder for program blocks
  encode_blocks = lambda do |match|
    prefix, block_type, args, block = $1 || "", $2, $3, $4
    if block_type == 'function'
      # decode the function block (THIS IS THE IMPORTANT BIT)
      # We are retrieving all sub-blocks and will re-parse them in light
      # of newly shrunk variables
      block = args + decode_blocks.call(block, __scoped)
      prefix = prefix.gsub(__brackets, "")
      
      # create the list of variable and argument names
      args = args[1...-1]
      
      if args != '_no_shrink_'
        vars = block.scan(__vars).join(";").gsub(__var, ";var")
        vars = vars.gsub(__brackets, "") while vars =~ __brackets
        vars = vars.gsub(__var_tidy, "").gsub(__var_equal, "")
      end
      block = decode_blocks.call(block, __encoded_block)
      
      # process each identifier
      if args != '_no_shrink_'
        count, short_id = 0, nil
        ids = [args, vars].join(",").scan(__identifier)
        processed = {}
        ids.each do |id|
          if !processed['#' + id] and !protected_names.include?(id)
            processed['#' + id] = true
            id = id.gsub(/([\/()\[\]{}|*+-.,^$?\\])/) { |m| "\\#{$1}" }
            # encode variable names
            count += 1 while block =~ Regexp.new("#{PREFIX}#{count}\\b")
            reg = Regexp.new("([^\\w$.])#{id}([^\\w$:])")
            block = block.gsub(reg, "\\1#{PREFIX}#{count}\\2") while block =~ reg
            reg = Regexp.new("([^{,\\w$.])#{id}:")
            block = block.gsub(reg, "\\1#{PREFIX}#{count}:")
            count += 1
          end
        end
        total = [total, count].max
      end
      replacement = "#{prefix}~#{blocks.length}~"
      blocks << block
    else
      replacement = "~##{blocks.length}~"
      blocks << (prefix + block)
    end
    replacement
  end
  
  # encode blocks, as we encode we replace variable and argument names
  script = script.gsub(__block, &encode_blocks) while script =~ __block
  
  # put the blocks back
  script = decode_blocks.call(script, __encoded_block)
  
  short_id, count = nil, 0
  shrunk = Encoder.new(SHRUNK, lambda { |object|
    # find the next free short name
    begin
      short_id = Packr.encode52(count)
      count += 1
    end while script =~ Regexp.new("[^\\w$.]#{short_id}[^\\w$:]")
    short_id
  })
  script = shrunk.encode(script)
  
  decode_data(script)
end