@mblaney/holster-browser 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ const isLocalhost = Boolean(
2
+ window.location.hostname === "localhost" ||
3
+ window.location.hostname === "[::1]" ||
4
+ window.location.hostname.match(
5
+ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
6
+ ),
7
+ )
8
+
9
+ export function register(config) {
10
+ if (import.meta.env.PROD && "serviceWorker" in navigator) {
11
+ window.addEventListener("load", () => {
12
+ const swUrl = `${import.meta.env.BASE_URL}service-worker.js`
13
+
14
+ if (isLocalhost) {
15
+ checkValidServiceWorker(swUrl, config)
16
+ } else {
17
+ registerValidSW(swUrl, config)
18
+ }
19
+ })
20
+ }
21
+ }
22
+
23
+ function registerValidSW(swUrl, config) {
24
+ navigator.serviceWorker
25
+ .register(swUrl)
26
+ .then(registration => {
27
+ registration.onupdatefound = () => {
28
+ const installingWorker = registration.installing
29
+ if (installingWorker == null) {
30
+ return
31
+ }
32
+ installingWorker.onstatechange = () => {
33
+ if (installingWorker.state === "installed") {
34
+ if (navigator.serviceWorker.controller) {
35
+ if (config && config.onUpdate) {
36
+ config.onUpdate(registration)
37
+ }
38
+ } else {
39
+ if (config && config.onSuccess) {
40
+ config.onSuccess(registration)
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
46
+ })
47
+ .catch(error => {
48
+ console.error("Error during service worker registration:", error)
49
+ })
50
+ }
51
+
52
+ function checkValidServiceWorker(swUrl, config) {
53
+ fetch(swUrl, {
54
+ headers: {"Service-Worker": "script"},
55
+ })
56
+ .then(response => {
57
+ const contentType = response.headers.get("content-type")
58
+ if (
59
+ response.status === 404 ||
60
+ (contentType != null && contentType.indexOf("javascript") === -1)
61
+ ) {
62
+ navigator.serviceWorker.ready.then(registration => {
63
+ registration.unregister().then(() => {
64
+ window.location.reload()
65
+ })
66
+ })
67
+ } else {
68
+ registerValidSW(swUrl, config)
69
+ }
70
+ })
71
+ .catch(() => {
72
+ console.log(
73
+ "No internet connection found. App is running in offline mode.",
74
+ )
75
+ })
76
+ }
77
+
78
+ export function unregister() {
79
+ if ("serviceWorker" in navigator) {
80
+ navigator.serviceWorker.ready
81
+ .then(registration => {
82
+ registration.unregister()
83
+ })
84
+ .catch(error => {
85
+ console.error(error.message)
86
+ })
87
+ }
88
+ }