1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
import { Hono } from "hono";
import type { AuthEnv } from "../middleware/auth";
import { requireAuth } from "../middleware/auth";
import {
getVapidPublicKey,
sendPushToUser,
subscribeUser,
unsubscribeUser,
} from "../lib/push";
const pwa = new Hono<AuthEnv>();
export const MANIFEST = {
name: "Gluecron",
short_name: "Gluecron",
description: "AI-native code intelligence + git hosting",
start_url: "/",
scope: "/",
display: "standalone",
background_color: "#0d1117",
theme_color: "#0d1117",
icons: [
{
src: "/icon.svg",
sizes: "any",
type: "image/svg+xml",
purpose: "any maskable",
},
],
categories: ["developer", "productivity"],
} as const;
pwa.get("/manifest.webmanifest", (c) => {
c.header("content-type", "application/manifest+json");
c.header("cache-control", "public, max-age=3600");
return c.body(JSON.stringify(MANIFEST));
});
const ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<rect width="128" height="128" rx="24" fill="#0d1117"/>
<g fill="#58a6ff" font-family="monospace" font-size="58" font-weight="700" text-anchor="middle">
<text x="64" y="82">gc</text>
</g>
<circle cx="28" cy="28" r="5" fill="#3fb950"/>
</svg>`;
pwa.get("/icon.svg", (c) => {
c.header("content-type", "image/svg+xml");
c.header("cache-control", "public, max-age=86400, immutable");
return c.body(ICON_SVG);
});
export const SERVICE_WORKER_SRC = `// gluecron service worker — v4 (self-nuke)
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => {
e.waitUntil((async () => {
// Purge every cache from any prior SW version
const keys = await caches.keys();
await Promise.all(keys.map((k) => caches.delete(k)));
// Tell every client we're done so they reload onto clean network state
const clients = await self.clients.matchAll({ type: 'window' });
for (const c of clients) c.navigate(c.url).catch(() => {});
// Then unregister this SW so future loads skip the SW layer entirely
await self.registration.unregister();
})());
});
// No fetch handler — every request goes straight to the network.
`;
let _missingShaWarned = false;
export function _resetSwShaWarningForTests(): void {
_missingShaWarned = false;
}
export function buildSwVersion(): string {
const sha = process.env.BUILD_SHA?.trim();
if (sha) return sha;
if (!_missingShaWarned) {
_missingShaWarned = true;
console.warn(
"[pwa] BUILD_SHA env not set — service worker will fall back to a dev-mode version string. Set BUILD_SHA in the deploy environment so cache-busting pins to the deploy SHA."
);
}
return `dev-${process.pid}`;
}
export function buildVersionedServiceWorker(version: string): string {
const safe = version.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `// gluecron service worker — Block S2 (deploy-SHA-pinned cache bust)
const SW_VERSION = "${safe}";
const CACHE_PREFIX = "gluecron-";
const CURRENT_CACHE = CACHE_PREFIX + SW_VERSION;
self.addEventListener("install", (e) => {
// Activate immediately — don't wait for every tab to close. Pairs with
// the layout's updatefound→reload hook so the user sees the new HTML
// on the very next page load instead of "forever until DevTools".
self.skipWaiting();
});
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((names) =>
Promise.all(
names
.filter((n) => n.startsWith(CACHE_PREFIX) && n !== CURRENT_CACHE)
.map((n) => caches.delete(n))
)
).then(() => self.clients.claim())
);
});
// No fetch handler — every request goes straight to the network. The
// version-pinned cache machinery is in place for future opt-in caching
// without re-introducing the stale-HTML bug.
`;
}
pwa.get("/sw.js", (c) => {
c.header("content-type", "application/javascript");
c.header("cache-control", "no-store");
c.header("pragma", "no-cache");
c.header("service-worker-allowed", "/");
const version = buildSwVersion();
return c.body(buildVersionedServiceWorker(version));
});
export const PWA_REGISTER_SNIPPET = `
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').catch(function() {});
});
}
`.trim();
export const PUSH_SERVICE_WORKER_SRC = `// gluecron push + offline service worker (Block M2)
const CACHE = 'gluecron-offline-v1';
const OFFLINE_URL = '/offline.html';
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE);
try { await cache.add(new Request(OFFLINE_URL, { cache: 'reload' })); } catch (_) {}
self.skipWaiting();
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
// Drop any cache that isn't our current one.
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)));
await self.clients.claim();
})());
});
self.addEventListener('push', (event) => {
let data = { title: 'Gluecron', body: '', url: '/', tag: 'gluecron', icon: '/icon.svg' };
if (event.data) {
try { data = Object.assign(data, event.data.json()); }
catch (_) { try { data.body = event.data.text(); } catch (_) {} }
}
event.waitUntil(self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
tag: data.tag,
data: { url: data.url },
}));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const target = (event.notification.data && event.notification.data.url) || '/';
event.waitUntil((async () => {
const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const c of all) {
try {
const u = new URL(c.url);
if (u.pathname === target || c.url === target) {
await c.focus();
return;
}
} catch (_) {}
}
await self.clients.openWindow(target);
})());
});
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const accept = req.headers.get('accept') || '';
// Only intervene on top-level HTML navigations. Everything else (CSS,
// images, API, /api/*, /.git/*, login/logout) passes straight through.
if (req.mode !== 'navigate' && !accept.includes('text/html')) return;
event.respondWith((async () => {
try {
return await fetch(req);
} catch (_) {
const cache = await caches.open(CACHE);
const cached = await cache.match(OFFLINE_URL);
if (cached) return cached;
return new Response('Offline', { status: 503, headers: { 'content-type': 'text/plain' } });
}
})());
});
`;
pwa.get("/sw-push.js", (c) => {
c.header("content-type", "application/javascript");
c.header("cache-control", "no-cache, no-store, must-revalidate");
c.header("pragma", "no-cache");
c.header("service-worker-allowed", "/");
return c.body(PUSH_SERVICE_WORKER_SRC);
});
export const OFFLINE_HTML = `<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Offline — gluecron</title>
<style>
:root { --bg:#0d1117; --fg:#c9d1d9; --muted:#8b949e; --accent:#58a6ff; --border:#30363d; }
html, body { margin:0; padding:0; background:var(--bg); color:var(--fg);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
main { max-width: 480px; margin: 12vh auto 0; padding: 24px; text-align:center; }
h1 { font-size: 22px; margin: 0 0 12px; }
p { color: var(--muted); line-height: 1.5; }
a.btn {
display:inline-block; margin-top:18px; padding:10px 18px;
background:transparent; border:1px solid var(--border); border-radius:6px;
color:var(--accent); text-decoration:none;
}
.pulse {
width:10px; height:10px; border-radius:50%;
background:#f85149; display:inline-block; margin-right:8px;
box-shadow:0 0 12px rgba(248,81,73,0.6);
}
</style>
</head>
<body>
<main>
<h1><span class="pulse"></span>You're offline</h1>
<p>We couldn't reach gluecron. Your last-known dashboard is still in cache — reconnect to refresh it.</p>
<a class="btn" href="/dashboard">Retry</a>
</main>
</body>
</html>
`;
pwa.get("/offline.html", (c) => {
c.header("content-type", "text/html; charset=utf-8");
c.header("cache-control", "public, max-age=300");
return c.body(OFFLINE_HTML);
});
pwa.get("/pwa/vapid-public-key", async (c) => {
try {
const key = await getVapidPublicKey();
return c.json({ key });
} catch (err) {
console.error("[pwa] vapid public key failed:", err);
return c.json({ error: "vapid_unavailable" }, 500);
}
});
pwa.post("/pwa/subscribe", requireAuth, async (c) => {
const user = c.get("user")!;
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "invalid_json" }, 400);
}
const endpoint = typeof body?.endpoint === "string" ? body.endpoint : "";
const p256dh =
typeof body?.keys?.p256dh === "string" ? body.keys.p256dh : "";
const auth = typeof body?.keys?.auth === "string" ? body.keys.auth : "";
if (!endpoint || !p256dh || !auth) {
return c.json({ error: "invalid_subscription" }, 400);
}
const ua = c.req.header("user-agent") ?? null;
try {
await subscribeUser(
user.id,
{ endpoint, keys: { p256dh, auth } },
ua ?? undefined
);
} catch (_) {
return c.json({ error: "subscribe_failed" }, 500);
}
return c.json({ ok: true }, 201);
});
pwa.post("/pwa/unsubscribe", requireAuth, async (c) => {
const user = c.get("user")!;
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "invalid_json" }, 400);
}
const endpoint = typeof body?.endpoint === "string" ? body.endpoint : "";
if (!endpoint) return c.json({ error: "missing_endpoint" }, 400);
await unsubscribeUser(user.id, endpoint);
return c.body(null, 204);
});
pwa.post("/pwa/test", requireAuth, async (c) => {
const user = c.get("user")!;
const result = await sendPushToUser(user.id, {
title: "Gluecron test notification",
body: "If you can read this, push delivery is working on this device.",
url: "/notifications",
tag: "gluecron-test",
});
return c.json(result);
});
export default pwa;
|