1 | var path = require('path'),
|
2 | _ = require('lodash'),
|
3 | util = require('./lib/util'),
|
4 | parseOptions = require('./lib/parseOptions'),
|
5 |
|
6 |
|
7 | lodashTemplateSettings = {
|
8 | evaluate: _.templateSettings.evaluate,
|
9 | interpolate: _.templateSettings.interpolate,
|
10 | escape: _.templateSettings.escape
|
11 | };
|
12 |
|
13 | function makeCdnizer(opts) {
|
14 | "use strict";
|
15 |
|
16 | opts = parseOptions(opts);
|
17 |
|
18 | function cdnizer(contents) {
|
19 |
|
20 | var canAddFallback = opts.shouldAddFallback && contents.indexOf('<head') !== -1,
|
21 | didAddFallback = false;
|
22 |
|
23 | _.union(opts.matchers, util.matchers).forEach(function(m) {
|
24 | contents = contents.replace(m.pattern, function(match, pre, url, post) {
|
25 | var fileInfo = util.findFileInfo(url, opts), result, params;
|
26 | if(fileInfo) {
|
27 | result = pre;
|
28 | params = _.merge(util.getVersionInfo(fileInfo, opts), {
|
29 | defaultCDNBase: opts.defaultCDNBase,
|
30 | filepath: url,
|
31 |
|
32 | filepathRel: path.join(opts.relativeRoot, url).split(path.sep).join('/').replace(/^\//, ''),
|
33 | filename: path.basename(url),
|
34 | filenameMin: util.getFilenameMin(url, opts),
|
35 | package: fileInfo.package,
|
36 | test: fileInfo.test
|
37 | });
|
38 | result += _.template(fileInfo.cdn || opts.defaultCDN, params, lodashTemplateSettings);
|
39 | result += post;
|
40 | if(canAddFallback && m.fallback && fileInfo.test) {
|
41 | result += _.template(opts.fallbackTest, params, lodashTemplateSettings);
|
42 | didAddFallback = true;
|
43 | }
|
44 | return result;
|
45 | } else {
|
46 |
|
47 | return match;
|
48 | }
|
49 | });
|
50 | });
|
51 |
|
52 | if(didAddFallback) {
|
53 | contents = contents.replace(/<link|<script|<\/head/i, function(m) {
|
54 | return opts.fallbackScript + m;
|
55 | });
|
56 | }
|
57 |
|
58 | return contents;
|
59 | }
|
60 |
|
61 | return cdnizer;
|
62 | }
|
63 |
|
64 | module.exports = makeCdnizer;
|