Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

4.6 KB
Raw Blame
/// <reference lib="webworker" />
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute, NavigationRoute } from 'workbox-routing';
import { NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { clientsClaim } from 'workbox-core';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { ExpirationPlugin } from 'workbox-expiration';

declare let self: ServiceWorkerGlobalScope;

// Auto-update: take control immediately
self.skipWaiting();
clientsClaim();

// Precache all assets generated by the build
cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST); // This will be replaced by the build process with the list of assets to precache

// ─── Navigation (HTML pages) ─────────────────────────────────────────────────
registerRoute(
  new NavigationRoute(
    new NetworkFirst({
      cacheName: 'pages-cache',
      networkTimeoutSeconds: 3,
      plugins: [
        new CacheableResponsePlugin({
          statuses: [0, 200],
        }),
        new ExpirationPlugin({
          maxEntries: 1000,
        }),
      ],
    }),
    { denylist: [/^\/api\//] },
  ),
);

// ─── i18n Translations cache ─────────────────────────────────────────────────
registerRoute(
  ({ url }) => url.pathname.includes('/_i18n/'),
  new StaleWhileRevalidate({
    cacheName: 'i18n-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 10 * 24 * 60 * 60,
      }),
    ],
  }),
);

// ─── API cache ───────────────────────────────────────────────────────────────
registerRoute(
  ({ url }) => url.origin === __BASE_API__ && !url.pathname.startsWith('/api/backup/'),
  new NetworkFirst({
    cacheName: 'api-cache',
    networkTimeoutSeconds: 3,
    plugins: [
      new ExpirationPlugin({
        maxEntries: 1000,
      }),
    ],
  }),
);

// ─── CDN cache ────────────────────────────────────────────────────────────────
registerRoute(
  ({ url }) => url.origin === __BASE_CDN__,
  new NetworkFirst({
    cacheName: 'cdn-cache',
    networkTimeoutSeconds: 3,
    plugins: [
      new ExpirationPlugin({
        purgeOnQuotaError: true,
      }),
    ],
  }),
);

// ─── Share Target API handler ────────────────────────────────────────────────
// When the PWA receives a share via the Share Target API (POST with form data),
// the service worker intercepts it, caches the form data, and redirects
// to the share-target page which reads from the cache.

self.addEventListener('fetch', (event: FetchEvent) => {
  const url = new URL(event.request.url);

  if (url.pathname === '/dashboard/share-target' && event.request.method === 'POST') {
    event.respondWith(handleShareTarget(event.request));
  }
});

async function handleShareTarget(request: Request): Promise<Response> {
  try {
    // Clone formData from the incoming POST request
    const formData = await request.formData();

    // Store the shared data in the Cache API so the page can read it
    const cache = await caches.open('share-target-cache');

    // Create a synthetic response from the form data to store in cache
    // We need to reconstruct a new FormData-based response
    const newFormData = new FormData();

    const title = formData.get('title');
    const text = formData.get('text');
    const url = formData.get('url');

    if (title) newFormData.append('title', title);
    if (text) newFormData.append('text', text);
    if (url) newFormData.append('url', url);

    // Handle shared files
    const files = formData.getAll('files');
    for (const file of files) {
      if (file instanceof File && file.size > 0) {
        newFormData.append('files', file, file.name);
      }
    }

    // Store as a Response with the form data
    const response = new Response(newFormData);
    await cache.put('/share-target-data', response);
  } catch (error) {
    console.error('[SW] Error handling share target:', error);
  }

  // Redirect to the share target page (GET)
  return Response.redirect('/dashboard/share-target', 303);
}