Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

sw.ts

123 lines · 6.2 KB · TypeScript
/**
 * Service worker source, served at <appBase>/sw.js with scope <appBase>/.
 *
 * - Offline shell: event pages and pie list APIs are network-first. A
 *   genuine network failure (fetch TypeError) is retried once, then the last
 *   copy of that page or /offline is used. Non-OK and redirect responses are
 *   passed through. There is no short timeout: a slow but live app must not
 *   look offline.
 * - Updates (lesson from @kody/kody-factory's Refresh bug): a new worker waits.
 *   The page shows "Refresh" only while registration.waiting is a real worker
 *   behind the current controller; Refresh asks the registration for the
 *   worker waiting *now*, posts SKIP_WAITING (string and object form), and
 *   reloads on controllerchange with a timeout fallback.
 * - Push: shows the notification with the color icon and the white
 *   status-bar badge; a tap focuses or opens the event page.
 */
export function serviceWorkerJs(input: { appBase: string; assetBase: string; version: string }) {
	const cfg = JSON.stringify({ base: input.appBase, assets: input.assetBase, version: input.version })
	return `'use strict';
var CFG = ${cfg};
var BASE = CFG.base, ASSETS = CFG.assets;
var CACHE = 'pie-night-' + CFG.version;
var SHELL = [BASE + '/offline', ASSETS + '/styles.css?v=' + CFG.version, ASSETS + '/app.js?v=' + CFG.version, ASSETS + '/home.js?v=' + CFG.version, ASSETS + '/pwa.js?v=' + CFG.version, ASSETS + '/icon-192.png', ASSETS + '/badge-96.png', BASE + '/favicon.svg'];
self.addEventListener('install', function (event) {
  event.waitUntil(caches.open(CACHE).then(function (c) {
    return Promise.all(SHELL.map(function (u) { return fetch(u, { cache: 'no-cache' }).then(function (r) { if (r.ok) return c.put(u, r); }).catch(function () {}); }));
  }));
});
self.addEventListener('message', function (event) {
  var d = event.data;
  if (d === 'SKIP_WAITING' || (d && d.type === 'SKIP_WAITING')) self.skipWaiting();
});
self.addEventListener('activate', function (event) {
  event.waitUntil(caches.keys().then(function (keys) {
    return Promise.all(keys.filter(function (k) { return k.indexOf('pie-night-') === 0 && k !== CACHE; }).map(function (k) { return caches.delete(k); }));
  }).then(function () { return self.clients.claim(); }));
});
function rel(url) { return url.pathname.slice(BASE.length) || '/'; }
function okHtml(res) { return res && res.ok && res.type === 'basic' && (res.headers.get('content-type') || '').indexOf('text/html') === 0; }
function okJson(res) { return res && res.ok && (res.headers.get('content-type') || '').indexOf('application/json') === 0; }
function okAsset(req, res) {
  if (!res || !res.ok) return false;
  var type = res.headers.get('content-type') || '';
  // Never cache an HTML error or sign-in page under an image or script URL.
  if (/\\.(png|svg)(\\?|$)/.test(req.url)) return type.indexOf('image/') === 0;
  if (/\\.js(\\?|$)/.test(req.url)) return type.indexOf('javascript') >= 0;
  if (/\\.css(\\?|$)/.test(req.url)) return type.indexOf('text/css') === 0;
  return false;
}
function isNetworkFailure(err) {
  return !!err && err.name === 'TypeError';
}
function networkFirst(request, key, check, fallbackKey) {
  function fromCache() {
    return caches.match(key).then(function (hit) { return hit || (fallbackKey ? caches.match(fallbackKey) : null); }).then(function (hit) {
      return hit || Response.error();
    });
  }
  function attempt() {
    return fetch(request).then(function (res) {
      if (check(res)) { var copy = res.clone(); caches.open(CACHE).then(function (c) { c.put(key, copy); }); }
      return res;
    });
  }
  return attempt().catch(function (err) {
    if (!isNetworkFailure(err)) return Promise.reject(err);
    return attempt().catch(function () { return fromCache(); });
  });
}
self.addEventListener('fetch', function (event) {
  var req = event.request;
  if (req.method !== 'GET') return;
  var url = new URL(req.url);
  if (url.origin !== self.location.origin) return;
  var r = rel(url);
  if (r.indexOf('/admin') >= 0 || r.indexOf('/-/') === 0) return;
  if (req.mode === 'navigate') {
    if (/^\\/e\\/[a-z0-9-]+$/.test(r) || r === '/' || r === '/new') {
      event.respondWith(networkFirst(req, BASE + r, okHtml, BASE + '/offline'));
    }
    return;
  }
  if (/^\\/api\\/e\\/[a-z0-9-]+(\\/pies)?$/.test(r)) { event.respondWith(networkFirst(req, BASE + r, okJson)); return; }
  if (url.pathname.indexOf(ASSETS + '/') === 0 || r === '/favicon.svg') {
    event.respondWith(caches.match(req).then(function (hit) {
      return hit || fetch(req).then(function (res) {
        if (okAsset(req, res)) { var copy = res.clone(); caches.open(CACHE).then(function (c) { c.put(req, copy); }); }
        return res;
      });
    }));
  }
});
self.addEventListener('push', function (event) {
  var d = {};
  try { d = event.data ? event.data.json() : {}; } catch (e) { d = { title: 'Pie Night', body: event.data ? event.data.text() : '' }; }
  var path = typeof d.path === 'string' && d.path.charAt(0) === '/' && d.path.charAt(1) !== '/' ? d.path : BASE + '/';
  event.waitUntil(self.registration.showNotification(String(d.title || 'Pie Night').slice(0, 120), {
    body: String(d.body || '').slice(0, 300),
    tag: typeof d.tag === 'string' ? d.tag : undefined,
    renotify: !!d.tag,
    icon: ASSETS + '/icon-192.png',
    badge: ASSETS + '/badge-96.png',
    data: { url: path }
  }));
});
self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  var target = event.notification.data && typeof event.notification.data.url === 'string' ? event.notification.data.url : BASE + '/';
  var abs = new URL(target, self.location.origin);
  if (abs.origin !== self.location.origin || (BASE && abs.pathname !== BASE && abs.pathname.indexOf(BASE + '/') !== 0)) abs = new URL(BASE + '/', self.location.origin);
  event.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
    for (var i = 0; i < list.length; i++) {
      var c = list[i];
      if (new URL(c.url).pathname === abs.pathname && 'focus' in c) return c.focus();
    }
    for (var j = 0; j < list.length; j++) {
      if ('navigate' in list[j] && 'focus' in list[j]) return list[j].navigate(abs.href).then(function (c) { return c && c.focus(); });
    }
    return self.clients.openWindow(abs.href);
  }));
});
`
}