1 | _moment = require 'moment'
|
2 | _ = require 'lodash'
|
3 |
|
4 | _utils = require './utils'
|
5 | CONSTKEY = null
|
6 |
|
7 | exports.getRawUniqueKey = (constant)->
|
8 |
|
9 | return CONSTKEY if constant and CONSTKEY
|
10 |
|
11 | uniqueKey = _utils.config.uniqueKey
|
12 | return "" if not uniqueKey
|
13 | uniqueKey = '{md5}' if uniqueKey is true
|
14 | uniqueKey = uniqueKey.replace /\{(.+)\}/g, (segment, value)->
|
15 | switch value
|
16 | when 'md5' then _utils.md5(new Date().toString()).substr(0, 10)
|
17 | when 'date' then _moment().format('YYYYMMDD')
|
18 | when 'datetime' then _moment().format('YYYYMMDDHHmmss')
|
19 | else ''
|
20 |
|
21 | CONSTKEY = uniqueKey if not CONSTKEY
|
22 | uniqueKey
|
23 |
|
24 |
|
25 | exports.getUniqueKey = (constant)->
|
26 | uniqueKey = exports.getRawUniqueKey constant
|
27 | uniqueKey = "?#{uniqueKey}" if uniqueKey.substr(0, 1) isnt '?'
|
28 | uniqueKey
|
29 |
|
30 |
|
31 | replaceUniqueKey = (content, rule, uniqueKey)->
|
32 | content = content.replace(rule.firstExpr, (line, match)->
|
33 | match += uniqueKey
|
34 | line = line.replace rule.secondExpr, ->
|
35 | rule.replaceTo.replace '{0}', match
|
36 | line
|
37 | )
|
38 | content
|
39 |
|
40 |
|
41 | cssUniqueKey = (content, uniqueKey)->
|
42 | uniqueKey = uniqueKey || exports.getUniqueKey(true)
|
43 | content.replace(/url\(['"]?(.+?)['"]?\)/g, (all, match)->
|
44 | match += uniqueKey
|
45 | return "url('#{match}')"
|
46 | )
|
47 |
|
48 |
|
49 |
|
50 | htmlUniqueKey = (content, uniqueKey)->
|
51 | uniqueKey = uniqueKey || exports.getUniqueKey(true)
|
52 |
|
53 | rules = [
|
54 | {
|
55 | firstExpr: /<link.+href=['"](.+?)['"].*>/g,
|
56 | secondExpr: /href=['"](.+?)['"]/i,
|
57 | replaceTo: "href='{0}'"
|
58 | },{
|
59 | firstExpr: /<script.+src=['"](.+?)['"].*>/g,
|
60 | secondExpr: /src=['"](.+?)['"]/i,
|
61 | replaceTo: "src='{0}'"
|
62 | },{
|
63 | firstExpr: /<img.+src=['"](.+?)['"].*>/g,
|
64 | secondExpr: /src=['"](.+?)['"]/i,
|
65 | replaceTo: "src='{0}'"
|
66 | }
|
67 | ]
|
68 |
|
69 | _.map rules, (rule)-> content = replaceUniqueKey content, rule, uniqueKey
|
70 | content
|
71 |
|
72 |
|
73 | exports.execute = (content, type, uniqueKey)->
|
74 | switch type
|
75 | when 'css' then cssUniqueKey(content, uniqueKey)
|
76 | when 'html' then htmlUniqueKey(content, uniqueKey)
|
77 | else content |
\ | No newline at end of file |