Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

synchronously copy polyfill file. Fixes #3 #4

Merged
merged 1 commit into from
Sep 30, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 31 additions & 31 deletions lib/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ var BroccoliServiceWorker = function BroccoliServiceWorker(inTree, options) {
if (!(this instanceof BroccoliServiceWorker)) {
return new BroccoliServiceWorker(inTree, options);
}
this.inTree = inTree;
this.inTree = inTree;
options = options || {};
this.addPolyfill = options.addPolyfill || true;
this.addPolyfill = options.addPolyfill || true;
this.debug = options.debug || true;
this.dynamicCache = options.dynamicCache || [];
this.excludePaths = options.excludePaths || ['tests/*'];
this.fallback = options.fallback || [];
this.fallback = options.fallback || [];
this.includePaths = options.includePaths || [];
this.polyFillLocation = options.polyFillLocation || 'serviceworker-cache-polyfill.js';
this.serviceWorkerFile = options.serviceWorkerFile || "service-worker.js";
Expand All @@ -35,8 +35,8 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
var serviceWorkerTree = funnel(this.inTree, {
exclude: this.excludePaths
});
return readTree(serviceWorkerTree).then(function (srcDir) {

return readTree(serviceWorkerTree).then(function (srcDir) {
var cacheVersion = (new Date()).getTime();
var lines = [];
if (addPolyfill) {
Expand All @@ -48,7 +48,7 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
lines.push("};");
if (dynamicCache.length) {
lines.push("CURRENT_CACHES['dynamic'] = 'dynamic-cache-v' + CACHE_VERSION;");
}
}
if (dynamicCache.length) {
lines.push("var DYNAMIC_URLS = [");
dynamicCache.forEach(function(cacheURL, idx, array) {
Expand All @@ -61,13 +61,13 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
fallback.forEach(function(fallback, idx, array) {
var fallbackParts = fallback.split(' ');
if (fallbackParts.length > 1) {
var matchLine = "{match: new RegExp('"+escapeRegExp(fallbackParts[0])+"'), fallback:'"+fallbackParts[1]+"'}";
var matchLine = "{match: new RegExp('"+escapeRegExp(fallbackParts[0])+"'), fallback:'"+fallbackParts[1]+"'}";
lines.push(createArrayLine(matchLine, idx, array.length));
}
});
lines.push("];");
}


lines.push("self.addEventListener('install', function(event) {");
lines.push(" var urlsToPrefetch = [");
Expand All @@ -80,11 +80,11 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
lines.push(createArrayLine("'"+file+"'", idx, array.length));
});
lines.push("];");

includePaths.forEach(function (file, idx, array) {
lines.push("urlsToPrefetch.push('"+file+"');");
});

//ServiceWorker code derived from examples at https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker
addDebugLine("'Handling install event. Resources to pre-fetch:', urlsToPrefetch", debug, lines);
lines.push(" event.waitUntil(");
Expand Down Expand Up @@ -127,20 +127,20 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
if (dynamicCache.length) {
lines.push(" if(dynamicCacheResponse(event)) {");
addDebugLine("'Found dynamic cache response:', event.request.url", debug, lines);
lines.push(" return;");
lines.push(" return;");
lines.push(" }");
}
addDebugLine("'Looking in caches for:', event.request.url", debug, lines);
lines.push(" event.respondWith(");

lines.push(" // caches.match() will look for a cache entry in all of the caches available to the service worker.");
lines.push(" // It's an alternative to first opening a specific named cache and then matching on that.");
lines.push(" caches.match(event.request).then(function(response) {");
lines.push(" if (response) {");
addDebugLine("'Found response in cache:', response", debug, lines);
if (fallback.length) {
lines.push(" if (response.status >= 400) {");
addDebugLine("'Got error status, checking for fallback. Response status was:', response.status", debug, lines);
addDebugLine("'Got error status, checking for fallback. Response status was:', response.status", debug, lines);
lines.push(" return fallbackResponse(event.request, response);");
lines.push(" }");
}
Expand All @@ -159,66 +159,66 @@ BroccoliServiceWorker.prototype.write = function(readTree, destDir) {
if (fallback.length) {
addDebugLine("'Got error, checking for fallback. Error was:', error", debug, lines);
lines.push(" return fallbackResponse(event.request, response);");
} else {
} else {
lines.push(" console.error('Fetching failed:', error);");
lines.push(" throw error;");
}
lines.push(" });");
lines.push(" })");
lines.push(" );");
lines.push("});");
lines.push("});");
if (dynamicCache.length) {
lines.push("function dynamicCacheResponse(event) {");
lines.push(" var matchingUrls = DYNAMIC_URLS.filter(function(dynamicURL) {");
lines.push(" return (event.request.url.match(dynamicURL) !== null);");
lines.push(" });");
lines.push(" if (matchingUrls.length) {");
addDebugLine("'Pulling dynamic url: '+event.request.url+' from network and adding to cache.'", debug, lines);
lines.push(" if (matchingUrls.length) {");
addDebugLine("'Pulling dynamic url: '+event.request.url+' from network and adding to cache.'", debug, lines);
lines.push(" event.respondWith(");
lines.push(" caches.open('dynamic-cache-v"+cacheVersion+"').then(function(cache) {");
lines.push(" caches.open('dynamic-cache-v"+cacheVersion+"').then(function(cache) {");
lines.push(" return fetch(event.request).then(function(response) {");
addDebugLine("'Got response for dynamic url: '+event.request.url+' now adding to cache.', response", debug, lines);
lines.push(" if (response.status >= 400) {");
addDebugLine("'Got response error for dynamic url, try to pull from cache: ',response.status", debug, lines);
addDebugLine("'Got response error for dynamic url, try to pull from cache: ',response.status", debug, lines);
lines.push(" caches.match(event.request).then(function(response) {");
lines.push(" return response;");
lines.push(" });");
lines.push(" } else {");
lines.push(" cache.put(event.request, response.clone());");
lines.push(" cache.put(event.request, response.clone());");
lines.push(" return response;");
lines.push(" }");
lines.push(" }");
lines.push(" }).catch(function(error) {");
addDebugLine("'Got error for dynamic url, try to pull from cache: ',error", debug, lines);
addDebugLine("'Got error for dynamic url, try to pull from cache: ',error", debug, lines);
lines.push(" caches.match(event.request).then(function(response) {");
lines.push(" return response;");
lines.push(" });");
lines.push(" });");
lines.push(" });");
lines.push(" });");
lines.push(" })");
lines.push(" );");
lines.push(" return true;");
lines.push(" } else {");
lines.push(" return false;");
lines.push(" }");
lines.push(" }");
lines.push("}");
}
}
if (fallback.length) {
lines.push("function fallbackResponse(request, response) {");
addDebugLine("'Looking for fallback for:', request.url", debug, lines);
lines.push(" var matchingUrls =FALLBACK_URLS.filter(function(fallbackURL) {");
addDebugLine("'Checking for fallback match with:', fallbackURL", debug, lines);
lines.push(" return (request.url.match(fallbackURL.match) !== null);");
addDebugLine("'Checking for fallback match with:', fallbackURL", debug, lines);
lines.push(" return (request.url.match(fallbackURL.match) !== null);");
lines.push(" });");
lines.push(" if (matchingUrls.length) {");
lines.push(" if (matchingUrls.length) {");
addDebugLine("'Fetching from fallback url: '+ matchingUrls[0].fallback +'for url: '+event.request.url", debug, lines);
lines.push(" return caches.match(matchingUrls[0].fallback);");
lines.push(" } else {");
lines.push(" return response; ");
lines.push(" } ");
lines.push(" } ");
lines.push("}");
}
fs.writeFileSync(path.join(destDir, serviceWorkerFile), lines.join("\n"));
if (addPolyfill) {
fs.createReadStream(swCachePolyFillFile).pipe(fs.createWriteStream(path.join(destDir, polyFillLocation)));
fs.writeFileSync(path.join(destDir, polyFillLocation), fs.readFileSync(swCachePolyFillFile));
}
});
};
Expand Down