Browse Source

combine all service-worker scripts into a single file to try and ensure included scripts aren't lost

starred-projects
Trent Larson 9 months ago
parent
commit
f517b09ed7
  1. 2
      .gitignore
  2. 6
      README.md
  3. 8
      project.task.yaml
  4. 2
      src/registerServiceWorker.ts
  5. 29
      sw_combine.js
  6. 29
      sw_scripts/additional-scripts.js
  7. 4
      sw_scripts/safari-notifications.js
  8. 21
      vue.config.js

2
.gitignore

@ -2,6 +2,8 @@
node_modules node_modules
/dist /dist
signature.bin signature.bin
# generated during `npm run build`
sw_scripts-combined.js
*.pem *.pem
verified.txt verified.txt
myenv myenv

6
README.md

@ -42,12 +42,6 @@ npm run lint
* `npm run build` * `npm run build`
...to make sure the service worker scripts are in proper form. (It's only important if you changed something in that directory.)
* `cp sw_scripts/[ns]* dist/`
... to copy the contents of the `sw_scripts` folder to the `dist` folder - except additional_scripts.js.
* Get on the server and back up the time-safari folder. * Get on the server and back up the time-safari folder.
* `rsync -azvu -e "ssh -i ~/.ssh/..." dist ubuntutest@test.timesafari.app:time-safari` * `rsync -azvu -e "ssh -i ~/.ssh/..." dist ubuntutest@test.timesafari.app:time-safari`

8
project.task.yaml

@ -1,17 +1,16 @@
tasks : tasks :
- 02 error passing control of a project to another user - 01 release server & client for fix to project-editing
- 08 notifications for feed - make them reliable :
- leverage different messaging platform?
- .5 fix timeSafari.org cert renewals - .5 fix timeSafari.org cert renewals
- .2 anchor hash into BTC - .2 anchor hash into BTC
- .1 add step 1 to onboarding hints to "install"
- 01 bookmarks for BVC - 01 bookmarks for BVC
- 24 compelling UI for credential presentations - 24 compelling UI for credential presentations
- discover who in my network has activity on a project
- 24 compelling UI for statistics (eg. World?) - 24 compelling UI for statistics (eg. World?)
- .5 stop from seeing an error on the first page when browser doesn't support service workers (which I've seen on iPhone; visible in Firefox private window) - .5 stop from seeing an error on the first page when browser doesn't support service workers (which I've seen on iPhone; visible in Firefox private window)
@ -28,6 +27,7 @@ tasks :
- 24 make the contact browsing on the front page something that invites more action - 24 make the contact browsing on the front page something that invites more action
- .2 list the "show more" contacts alphabetically
- .5 change server plan & project endpoints to use jwtId as identifier rather than rowid - .5 change server plan & project endpoints to use jwtId as identifier rather than rowid
- 16 edit offers & gives, or revoke allowing re-creation - 16 edit offers & gives, or revoke allowing re-creation
- .1 When available in the server, give message for 'nonAmountGiven' on offers on ProjectsView page. - .1 When available in the server, give message for 'nonAmountGiven' on offers on ProjectsView page.

2
src/registerServiceWorker.ts

@ -3,7 +3,7 @@
import { register } from "register-service-worker"; import { register } from "register-service-worker";
if (process.env.NODE_ENV === "production") { if (process.env.NODE_ENV === "production") {
register("/additional-scripts.js", { register("/sw_scripts-combined.js", {
ready() { ready() {
console.log( console.log(
"App is being served from cache by a service worker.\n" + "App is being served from cache by a service worker.\n" +

29
sw_combine.js

@ -0,0 +1,29 @@
/**
* We've seen cases where the functions inside safari-notifications.js are not found.
* This is our attempt to ensure that all the functions are available.
*/
const fs = require("fs");
const path = require("path");
const swScriptsDir = path.resolve(__dirname, "sw_scripts");
const outputFile = path.resolve(__dirname, "sw_scripts-combined.js");
// Read all files in the sw_scripts directory
fs.readdir(swScriptsDir, (err, files) => {
if (err) {
console.error("Error reading directory:", err);
return;
}
// Combine files content into one script
const combinedContent = files
.filter((file) => path.extname(file) === ".js")
.map((file) => fs.readFileSync(path.join(swScriptsDir, file), "utf8"))
.join("\n");
// Write the combined content to the output file
fs.writeFileSync(outputFile, combinedContent, "utf8");
console.log("Service worker files combined.");
});

29
sw_scripts/additional-scripts.js

@ -1,5 +1,6 @@
/* eslint-env serviceworker */ /* eslint-env serviceworker */
/* global workbox */ /* global workbox */
/* eslint-disable *//* ... because old-browser-compatible files in this directory are combined into a single script during `npm run build` */
importScripts( importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js", "https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js",
); );
@ -7,7 +8,9 @@ importScripts(
function logConsoleAndDb(message, arg1, arg2) { function logConsoleAndDb(message, arg1, arg2) {
// in chrome://serviceworker-internals note that the arg1 and arg2 here will show as "[object Object]" in that page but will show as expandable objects in the console // in chrome://serviceworker-internals note that the arg1 and arg2 here will show as "[object Object]" in that page but will show as expandable objects in the console
console.log(`${new Date().toISOString()} ${message}`, arg1, arg2); console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
if (self.appendDailyLog) { // appendDailyLog is injected at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
if (appendDailyLog) {
let fullMessage = `${new Date().toISOString()} ${message}`; let fullMessage = `${new Date().toISOString()} ${message}`;
if (arg1) { if (arg1) {
fullMessage += `\n${JSON.stringify(arg1)}`; fullMessage += `\n${JSON.stringify(arg1)}`;
@ -15,25 +18,19 @@ function logConsoleAndDb(message, arg1, arg2) {
if (arg2) { if (arg2) {
fullMessage += `\n${JSON.stringify(arg2)}`; fullMessage += `\n${JSON.stringify(arg2)}`;
} }
self.appendDailyLog(fullMessage); // appendDailyLog is injected from safari-notifications.js at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
appendDailyLog(fullMessage);
} else { } else {
// sometimes we get the error: "Uncaught TypeError: self.appendDailyLog is not a function" // sometimes we get the error: "Uncaught TypeError: appendDailyLog is not a function"
console.log( console.log(
"Not logging to DB (often because self.appendDailyLog doesn't exist).", "Not logging to DB (often because appendDailyLog doesn't exist).",
); );
} }
} }
self.addEventListener("install", async (event) => { self.addEventListener("install", async (/* event */) => {
console.log("Service worker got install event. Importing scripts...", event); logConsoleAndDb("Service worker finished installation.");
await importScripts(
"safari-notifications.js",
"nacl.js",
"noble-curves.js",
"noble-hashes.js",
);
// this should now be available
logConsoleAndDb("Service worker imported all scripts.");
}); });
self.addEventListener("activate", (event) => { self.addEventListener("activate", (event) => {
@ -84,7 +81,9 @@ self.addEventListener("push", function (event) {
} else { } else {
title = payload.title || "Update"; title = payload.title || "Update";
} }
message = await self.getNotificationCount(); // getNotificationCount is injected from safari-notifications.js at build time by the vue.config.js configureWebpack apply plugin
// eslint-disable-next-line no-undef
message = await getNotificationCount();
} }
if (message) { if (message) {
const options = { const options = {

4
sw_scripts/safari-notifications.js

@ -547,8 +547,12 @@ async function getNotificationCount() {
newClaims++; newClaims++;
} }
if (newClaims > 0) { if (newClaims > 0) {
if (newClaims === 1) {
result = "There is 1 new activity on Time Safari";
} else {
result = `There are ${newClaims} new activities on Time Safari`; result = `There are ${newClaims} new activities on Time Safari`;
} }
}
const most_recent_notified = claims[0]["id"]; const most_recent_notified = claims[0]["id"];
await setMostRecentNotified(most_recent_notified); await setMostRecentNotified(most_recent_notified);
} else { } else {

21
vue.config.js

@ -1,5 +1,6 @@
const { defineConfig } = require("@vue/cli-service"); const { defineConfig } = require("@vue/cli-service");
const { gitDescribeSync } = require("git-describe"); const { gitDescribeSync } = require("git-describe");
const { exec } = require("child_process");
process.env.VUE_APP_GIT_HASH = gitDescribeSync().hash; process.env.VUE_APP_GIT_HASH = gitDescribeSync().hash;
@ -10,6 +11,23 @@ module.exports = defineConfig({
experiments: { experiments: {
topLevelAwait: true, topLevelAwait: true,
}, },
plugins: [
{
// Still don't know why this runs three times.
apply: (compiler) => {
compiler.hooks.beforeCompile.tap("BeforeCompile", () => {
// Execute combine-sw.js script
exec("node sw_combine.js", (error, stdout, stderr) => {
if (error || stderr) {
console.error("Service worker files error:", error || stderr);
} else {
console.log("Finished combining service worker files.", stdout);
}
});
});
},
},
],
}, },
pwa: { pwa: {
iconPaths: { iconPaths: {
@ -17,7 +35,8 @@ module.exports = defineConfig({
}, },
workboxPluginMode: "InjectManifest", workboxPluginMode: "InjectManifest",
workboxOptions: { workboxOptions: {
swSrc: "./sw_scripts/additional-scripts.js", // this script will be checked for linting (sw_scripts/* files generate about 1000 linting errors)
swSrc: "./sw_scripts-combined.js",
}, },
}, },
}); });

Loading…
Cancel
Save