Skip to content

Commit a496fa9

Browse files
committed
Add service worker middleware and better logging
1 parent ed0321b commit a496fa9

File tree

11 files changed

+269
-4
lines changed

11 files changed

+269
-4
lines changed

README.md

+15
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,15 @@ level or any specific nested package level.
110110
recursively search for inconsistencies, displays warnings unless debugging is
111111
enabled, then it throws errors instead.
112112

113+
* [diffhtml-middleware-service-worker](/packages/diffhtml-middleware-service-worker)
114+
115+
``` sh
116+
npm install diffhtml-middleware-service-worker
117+
```
118+
119+
Helps with the creation of a service worker for PWAs, available as a
120+
convenience to make development more friendlier.
121+
113122
* [diffhtml-react-compat](/packages/diffhtml-react-compat)
114123

115124
```
@@ -130,6 +139,12 @@ level or any specific nested package level.
130139
A work-in-progress static HTML server that automatically reloads your markup
131140
as you save using Web Sockets.
132141

142+
* [diffhtml-devtools](/packages/diffhtml-devtools)
143+
144+
A work-in-progress set of developer tools that logs out transactions.
145+
Eventually will allow for subscription/unsubscription of middleware, charting
146+
for the overall application health, and more.
147+
133148
* [diffhtml-website](/packages/diffhtml-website)
134149

135150
The source for the [www.diffhtml.org](https://www.diffhtml.org) website,
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
console.warn('Unable to load prop-types with real ESM');
1+
console.warn('diffHTML Components: Unable to load prop-types with real ESM');
22

33
export default {};

packages/diffhtml-middleware-logger/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ npm install diffhtml-middleware-logger
2020
import { use } from 'diffhtml';
2121
import logger from 'diffhtml-middleware-logger';
2222

23-
diff.use(logger());
23+
use(logger());
2424
```
2525

2626
This is not a very performant middleware, so please do not use this in
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"presets": ["diffhtml-imports"]
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# <±/> diffHTML ServiceWorker Middleware
2+
3+
Stable Version: 1.0.0-beta.9
4+
5+
While this does not really benefit from being a middleware, I made it as such
6+
since it looks nice in the `use` and can be disabled if the middleware is
7+
unsubscribed. I've added some developer niceties, like auto clearing the caches
8+
for development. It's also possible to disable the worker completely if you
9+
get annoyed with some behavior.
10+
11+
## Installation
12+
13+
``` sh
14+
npm install diffhtml-middleware-service-worker
15+
```
16+
17+
## Example
18+
19+
``` javascript
20+
import { use } from 'diffhtml';
21+
import serviceWorker from 'diffhtml-middleware-service-worker';
22+
```
23+
24+
``` javascript
25+
// Defaults shown, these are all optional values.
26+
use(serviceWorker({
27+
url: '/service-worker.js',
28+
scope: '/',
29+
autoClearCaches: location.search.includes('diff_autoclear'),
30+
disable: location.search.includes('diff_disable'),
31+
quiet: location.search.includes('diff_quiet'),
32+
options: {},
33+
}));
34+
```
35+
36+
## Options
37+
38+
These options are available to change depending on the use case. It is
39+
entirely possible to get away with simply:
40+
41+
``` javascript
42+
use(serviceWorker());
43+
```
44+
45+
If you meet the the default use case.
46+
47+
### `url`
48+
49+
Specifies which Service Worker URL to load.
50+
51+
### `scope`
52+
53+
Specifices the path to use, called scope since it restricts what content is
54+
visible.
55+
56+
### `autoClearCaches`
57+
58+
Allow the middleware to automatically clear all caches. By default this is
59+
disabled as it defeats the point of a service worker and may muck with other
60+
apps running on localhost. Can be toggled via the query param
61+
`?diff_autoclear`.
62+
63+
### `disable`
64+
65+
Unregisters all Service Workers and does not try to register a new one. This
66+
can be toggled via the query param: `?diff_disable`.
67+
68+
### `quiet`
69+
70+
Do not log anything to the console. Can be toggled via the query param
71+
`?diffhtml_quiet`.
72+
73+
### `options`
74+
75+
Defaults to an empty object, gets spread into the Service Worker registration
76+
call.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
const { assign } = Object;
2+
3+
// Wipe all caches for this domain.
4+
const clear = ({ quiet }) => caches.keys().then(cachesNames => {
5+
return Promise.all(cachesNames.map(cacheName => {
6+
return caches.delete(cacheName).then(function () {
7+
if (!quiet) {
8+
console.warn(`diffHTML ServiceWorker: Deleted cache ${cacheName}`);
9+
}
10+
});
11+
}))
12+
});
13+
14+
// Wipe out all the service workers for this domain.
15+
const unregister = ({ quiet }) => navigator.serviceWorker.getRegistrations().then(regs => {
16+
for (let reg of regs) {
17+
reg.unregister();
18+
19+
if (!quiet) {
20+
console.warn('diffHTML ServiceWorker: Unregistering worker', reg);
21+
}
22+
}
23+
});
24+
25+
// Simplify's creating a service worker with diffHTML.
26+
const wrapper = ({
27+
// Default to the root /service-worker.js.
28+
url = '/service-worker.js',
29+
30+
// Allow the middleware to automatically clear all caches. By default this is
31+
// disabled as it defeats the point of a service worker and may muck with
32+
// other apps running on localhost.
33+
autoClearCaches = location.search.includes('diff_autoclear'),
34+
35+
// Useful for debugging, wipes and doesn't set. Default to the query param
36+
// for disable.
37+
disable = location.search.includes('diff_disable'),
38+
39+
// Useful for debugging, logs out service worker events. Default to the query
40+
// param to enable.
41+
quiet = location.search.includes('diff_quiet'),
42+
43+
// Defaults to the page root, gets set into the service worker options.
44+
scope = '/',
45+
46+
// The remaining options to be spread into the serviceWorker configuration.
47+
options = {},
48+
}) => assign(function serviceWorkerMiddleware() {}, {
49+
subscribe() {
50+
const { serviceWorker } = navigator;
51+
52+
let chain = Promise.resolve();
53+
54+
// If the user wants to work on the service worker, we need to clear the
55+
// old ones out first.
56+
if (autoClearCaches) {
57+
chain = chain.then(() => clear({ quiet }));
58+
}
59+
60+
// If we're disabling, then clear the c
61+
if (disable) {
62+
// Iterate through all service workers and remove the old ones.
63+
chain = chain.then(() => unregister({ quiet }));
64+
}
65+
66+
// If the user disables the service worker, do not attempt to re-register
67+
// it.
68+
chain = chain.then(() => {
69+
if (!disable) {
70+
return serviceWorker.register(url, { scope, ...options })
71+
}
72+
});
73+
74+
// If not in quiet mode, echo out some standard messaging and give access
75+
// to the objects.
76+
if (!quiet) {
77+
chain
78+
.then(reg => reg && console.warn(
79+
'diffHTML ServiceWorker: Registration succeeded', reg
80+
))
81+
.catch(err => err && console.warn(
82+
'diffHTML ServiceWorker: Registration failed', err
83+
));
84+
}
85+
},
86+
87+
unsubscribe() {
88+
unregister({ quiet });
89+
},
90+
});
91+
92+
export default opts => wrapper(opts || {});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
{
2+
"name": "diffhtml-middleware-service-worker",
3+
"version": "1.0.0-beta.9",
4+
"description": "Helps with service workers",
5+
"main": "dist/cjs/index",
6+
"module": "dist/es/index",
7+
"jsnext:main": "dist/es/index",
8+
"esnext:main": "dist/es/index",
9+
"scripts": {
10+
"prepublish": "npm run min",
11+
"clean": "rm -rf dist/* && mkdir -p dist",
12+
"min": "npm run build && npm run build-min",
13+
"build": "npm run clean && npm run build-umd && npm run build-cjs && npm run build-esm",
14+
"build-cjs": "NODE_ENV=cjs babel index.js -d dist/cjs",
15+
"build-esm": "NODE_ENV=esm babel index.js -d dist/es",
16+
"build-umd": "NODE_ENV=umd rollup -c rollup.config.js",
17+
"build-min": "NODE_ENV=min rollup -c rollup.config.js && uglifyjs dist/logger.min.js -o dist/logger.min.js -m -c",
18+
"watch": "NODE_ENV=umd rollup -c rollup.config.js -w"
19+
},
20+
"keywords": [
21+
"diffhtml",
22+
"service workers",
23+
"middleware"
24+
],
25+
"author": "Tim Branyen (@tbranyen)",
26+
"license": "MIT",
27+
"devDependencies": {
28+
"babel-cli": "^6.24.1",
29+
"babel-preset-diffhtml-imports": "^1.0.0-beta.9",
30+
"diffhtml": "^1.0.0-beta.9",
31+
"rollup": "^0.41.4",
32+
"rollup-plugin-babel": "^2.7.1",
33+
"rollup-plugin-node-resolve": "^2.0.0",
34+
"rollup-plugin-replace": "^1.1.1",
35+
"rollup-plugin-visualizer": "^0.2.0",
36+
"rollup-watch": "^3.2.2",
37+
"uglify-js": "^3.0.15"
38+
},
39+
"peerDependencies": {
40+
"diffhtml": "^1.0.0-beta.9"
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import babel from 'rollup-plugin-babel';
2+
import nodeResolve from 'rollup-plugin-node-resolve';
3+
import replace from 'rollup-plugin-replace';
4+
import Visualizer from 'rollup-plugin-visualizer';
5+
6+
const entries = {
7+
min: 'index.js',
8+
umd: 'index.js',
9+
};
10+
11+
const dests = {
12+
min: 'dist/logger.min.js',
13+
umd: 'dist/logger.js',
14+
}
15+
16+
const { NODE_ENV = 'umd' } = process.env;
17+
18+
export const exports = 'default';
19+
export const context = 'this';
20+
export const entry = entries[NODE_ENV];
21+
export const sourceMap = false;
22+
export const moduleName = 'logger';
23+
export const globals = { diffhtml: 'diff' };
24+
export const external = ['diffhtml'];
25+
26+
export const targets = [{
27+
dest: dests[NODE_ENV],
28+
format: 'umd',
29+
}];
30+
31+
export const plugins = [
32+
NODE_ENV === 'min' && replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
33+
babel(),
34+
nodeResolve({ jsnext: true }),
35+
NODE_ENV === 'umd' && Visualizer({ filename: './dist/build-size.html' }),
36+
];

packages/diffhtml/lib/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ api.Internals = Internals;
4949
// Automatically hook up to DevTools if they are present.
5050
if (typeof devTools !== 'undefined') {
5151
use(devTools(Internals));
52-
console.info('diffHTML DevTools Found and Activated...');
52+
console.warn('diffHTML: DevTools Found and Activated...');
5353
}
5454

5555
export {

packages/diffhtml/lib/runtime.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ api.Internals = Internals;
4242
// Automatically hook up to DevTools if they are present.
4343
if (typeof devTools === 'function') {
4444
use(devTools(Internals));
45-
console.info('diffHTML DevTools Found and Activated...');
45+
console.warn('diffHTML: DevTools Found and Activated...');
4646
}
4747

4848
export {

0 commit comments

Comments
 (0)