2023-05-23 18:53:53 +00:00
|
|
|
import Dexie from "https://esm.sh/v120/dexie@3.2.2/dist/dexie.js";
|
|
|
|
|
|
|
|
import type { FileContent } from "../common/spaces/indexeddb_space_primitives.ts";
|
|
|
|
import { simpleHash } from "../common/crypto.ts";
|
2023-07-02 14:30:37 +00:00
|
|
|
import type { FileMeta } from "../common/types.ts";
|
2023-05-23 18:53:53 +00:00
|
|
|
|
|
|
|
const CACHE_NAME = "{{CACHE_NAME}}";
|
|
|
|
|
|
|
|
const precacheFiles = Object.fromEntries([
|
|
|
|
"/",
|
2023-06-13 18:47:05 +00:00
|
|
|
"/.client/logout.html",
|
2023-05-23 18:53:53 +00:00
|
|
|
"/.client/client.js",
|
|
|
|
"/.client/favicon.png",
|
|
|
|
"/.client/iAWriterMonoS-Bold.woff2",
|
|
|
|
"/.client/iAWriterMonoS-BoldItalic.woff2",
|
|
|
|
"/.client/iAWriterMonoS-Italic.woff2",
|
|
|
|
"/.client/iAWriterMonoS-Regular.woff2",
|
|
|
|
"/.client/logo.png",
|
|
|
|
"/.client/logo-dock.png",
|
|
|
|
"/.client/main.css",
|
|
|
|
"/.client/manifest.json",
|
|
|
|
].map((path) => [path, path + "?v=" + CACHE_NAME, path])); // Cache busting
|
|
|
|
|
|
|
|
self.addEventListener("install", (event: any) => {
|
|
|
|
console.log("[Service worker]", "Installing service worker...");
|
|
|
|
event.waitUntil(
|
2023-07-06 14:47:50 +00:00
|
|
|
(async () => {
|
|
|
|
const cache = await caches.open(CACHE_NAME);
|
|
|
|
console.log(
|
|
|
|
"[Service worker]",
|
|
|
|
"Now pre-caching client files",
|
|
|
|
);
|
|
|
|
await cache.addAll(Object.values(precacheFiles));
|
|
|
|
console.log(
|
|
|
|
"[Service worker]",
|
|
|
|
Object.keys(precacheFiles).length,
|
|
|
|
"client files cached",
|
|
|
|
);
|
|
|
|
// @ts-ignore: No need to wait
|
|
|
|
self.skipWaiting();
|
|
|
|
})(),
|
2023-05-23 18:53:53 +00:00
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener("activate", (event: any) => {
|
2023-07-27 15:02:53 +00:00
|
|
|
console.log("[Service worker]", "Activating new service worker!");
|
2023-05-23 18:53:53 +00:00
|
|
|
event.waitUntil(
|
2023-07-06 14:47:50 +00:00
|
|
|
(async () => {
|
|
|
|
const cacheNames = await caches.keys();
|
|
|
|
await Promise.all(
|
2023-05-23 18:53:53 +00:00
|
|
|
cacheNames.map((cacheName) => {
|
|
|
|
if (cacheName !== CACHE_NAME) {
|
|
|
|
console.log("[Service worker]", "Removing old cache", cacheName);
|
|
|
|
return caches.delete(cacheName);
|
|
|
|
}
|
|
|
|
}),
|
2023-07-06 14:47:50 +00:00
|
|
|
);
|
|
|
|
// @ts-ignore: No need to wait
|
|
|
|
return clients.claim();
|
|
|
|
})(),
|
2023-05-23 18:53:53 +00:00
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
let db: Dexie | undefined;
|
|
|
|
let fileContentTable: Dexie.Table<FileContent, string> | undefined;
|
2023-07-02 14:30:37 +00:00
|
|
|
let fileMetatable: Dexie.Table<FileMeta, string> | undefined;
|
2023-05-23 18:53:53 +00:00
|
|
|
|
|
|
|
self.addEventListener("fetch", (event: any) => {
|
|
|
|
const url = new URL(event.request.url);
|
|
|
|
|
|
|
|
// Use the custom cache key if available, otherwise use the request URL
|
|
|
|
const cacheKey = precacheFiles[url.pathname] || event.request.url;
|
|
|
|
|
|
|
|
event.respondWith(
|
2023-07-04 14:54:57 +00:00
|
|
|
(async () => {
|
2023-07-06 14:47:50 +00:00
|
|
|
const request = event.request;
|
|
|
|
|
|
|
|
// console.log("Getting request", request, [...request.headers.entries()]);
|
|
|
|
|
|
|
|
// Any request with the X-Sync-Mode header originates from the sync engine: pass it on to the server
|
|
|
|
if (request.headers.has("x-sync-mode")) {
|
|
|
|
return fetch(request);
|
|
|
|
}
|
|
|
|
|
2023-07-04 14:54:57 +00:00
|
|
|
// Try the static (client) file cache first
|
|
|
|
const cachedResponse = await caches.match(cacheKey);
|
|
|
|
// Return the cached response if found
|
|
|
|
if (cachedResponse) {
|
|
|
|
return cachedResponse;
|
|
|
|
}
|
2023-05-23 18:53:53 +00:00
|
|
|
|
2023-07-06 14:47:50 +00:00
|
|
|
const requestUrl = new URL(request.url);
|
2023-07-04 14:54:57 +00:00
|
|
|
const pathname = requestUrl.pathname;
|
|
|
|
|
2023-07-06 14:47:50 +00:00
|
|
|
// Are we fetching a URL from the same origin as the app? If not, we don't handle it and pass it on
|
|
|
|
if (location.host !== requestUrl.host) {
|
|
|
|
return fetch(request);
|
2023-07-04 14:54:57 +00:00
|
|
|
}
|
|
|
|
|
2023-07-07 07:28:20 +00:00
|
|
|
if (pathname === "/.auth" || pathname === "/index.json") {
|
2023-07-06 14:47:50 +00:00
|
|
|
return fetch(request);
|
2023-07-07 07:28:20 +00:00
|
|
|
} else if (/\/.+\.[a-zA-Z]+$/.test(pathname)) {
|
|
|
|
// If this is a /*.* request, this can either be a plug worker load or an attachment load
|
|
|
|
return handleLocalFileRequest(request, pathname);
|
2023-07-04 14:54:57 +00:00
|
|
|
} else {
|
|
|
|
// Must be a page URL, let's serve index.html which will handle it
|
2023-07-06 14:47:50 +00:00
|
|
|
return (await caches.match(precacheFiles["/"])) || fetch(request);
|
2023-07-04 14:54:57 +00:00
|
|
|
}
|
2023-07-27 09:41:44 +00:00
|
|
|
})().catch((e) => {
|
|
|
|
console.warn("[Service worker]", "Fetch failed:", e);
|
|
|
|
return new Response("Offline", {
|
|
|
|
status: 503, // Service Unavailable
|
|
|
|
});
|
|
|
|
}),
|
2023-05-23 18:53:53 +00:00
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2023-07-06 14:47:50 +00:00
|
|
|
async function handleLocalFileRequest(
|
|
|
|
request: Request,
|
|
|
|
pathname: string,
|
|
|
|
): Promise<Response> {
|
|
|
|
if (!fileContentTable) {
|
|
|
|
// Not initialzed yet, or explicitly in sync mode (so direct server communication requested)
|
|
|
|
return fetch(request);
|
|
|
|
}
|
2023-07-07 13:45:52 +00:00
|
|
|
|
|
|
|
if (!db?.isOpen()) {
|
|
|
|
console.log("Detected that the DB was closed, reopening");
|
|
|
|
await db!.open();
|
|
|
|
}
|
2023-07-06 14:47:50 +00:00
|
|
|
const path = decodeURIComponent(pathname.slice(1));
|
|
|
|
const data = await fileContentTable.get(path);
|
|
|
|
if (data) {
|
|
|
|
// console.log("Serving from space", path);
|
|
|
|
if (!data.meta) {
|
|
|
|
// Legacy database not fully synced yet
|
|
|
|
data.meta = (await fileMetatable!.get(path))!;
|
|
|
|
}
|
|
|
|
return new Response(
|
|
|
|
data.data,
|
|
|
|
{
|
|
|
|
headers: {
|
|
|
|
"Content-type": data.meta.contentType,
|
|
|
|
"Content-Length": "" + data.meta.size,
|
|
|
|
"X-Permission": data.meta.perm,
|
|
|
|
"X-Last-Modified": "" + data.meta.lastModified,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
console.error(
|
|
|
|
"Did not find file in locally synced space",
|
|
|
|
path,
|
|
|
|
);
|
|
|
|
return new Response("Not found", {
|
|
|
|
status: 404,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-23 18:53:53 +00:00
|
|
|
self.addEventListener("message", (event: any) => {
|
|
|
|
if (event.data.type === "flushCache") {
|
|
|
|
caches.delete(CACHE_NAME)
|
|
|
|
.then(() => {
|
|
|
|
console.log("[Service worker]", "Cache deleted");
|
|
|
|
db?.close();
|
|
|
|
event.source.postMessage({ type: "cacheFlushed" });
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (event.data.type === "config") {
|
|
|
|
const spaceFolderPath = event.data.config.spaceFolderPath;
|
|
|
|
const dbPrefix = "" + simpleHash(spaceFolderPath);
|
|
|
|
|
|
|
|
// Setup space
|
|
|
|
db = new Dexie(`${dbPrefix}_space`, {
|
|
|
|
indexedDB: globalThis.indexedDB,
|
|
|
|
});
|
|
|
|
db.version(1).stores({
|
|
|
|
fileMeta: "name",
|
|
|
|
fileContent: "name",
|
|
|
|
});
|
|
|
|
|
|
|
|
fileContentTable = db.table<FileContent, string>("fileContent");
|
2023-07-02 14:30:37 +00:00
|
|
|
fileMetatable = db.table<FileMeta, string>("fileMeta");
|
2023-05-23 18:53:53 +00:00
|
|
|
}
|
2022-10-10 12:50:21 +00:00
|
|
|
});
|