@alexsun-top/opencode-chat-room 0.8.1 → 0.8.3

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.
Files changed (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
package/server/sw.js CHANGED
@@ -1,39 +1,40 @@
1
+ "use strict";
1
2
  // The server fills in {{version}} so a release installs a worker that replaces the old cache.
2
3
  const VERSION = "{{version}}";
3
4
  const CACHE = `oc-chat-${VERSION}`;
4
5
  const SHELL = "/chat";
5
6
  const STATIC = [
6
- "/assets/base.css",
7
- "/assets/icons.css",
8
- "/assets/fluent-icons.svg",
9
- "/assets/settings.css",
10
- "/assets/conversation.css",
11
- "/assets/recall.css",
12
- "/assets/attachments.css",
13
- "/assets/responsive.css",
14
- "/assets/code-highlight.css",
15
- "/assets/room-create.css",
16
- "/assets/edit-room.css",
17
- "/assets/palette.css",
18
- "/assets/files.css",
19
- "/assets/tasks.css",
20
- "/assets/doc-preview.css",
21
- "/assets/diagram-viewer.css",
22
- "/assets/chat/office-preview.js",
23
- "/assets/office/docx.bundle.js",
24
- "/assets/office/xlsx.bundle.js",
25
- "/assets/office/pptx.bundle.js",
26
- "/assets/marked-18.0.4.js",
27
- "/assets/dompurify-3.4.7.js",
28
- "/assets/mermaid-11.12.2.min.js",
29
- "/assets/icons/icon-192.png",
30
- "/assets/icons/icon-512.png",
31
- "/assets/icons/apple-touch-icon.png",
32
- "/manifest.webmanifest",
7
+ "/assets/base.css",
8
+ "/assets/icons.css",
9
+ "/assets/fluent-icons.svg",
10
+ "/assets/settings.css",
11
+ "/assets/conversation.css",
12
+ "/assets/recall.css",
13
+ "/assets/attachments.css",
14
+ "/assets/responsive.css",
15
+ "/assets/window-controls.css",
16
+ "/assets/code-highlight.css",
17
+ "/assets/room-create.css",
18
+ "/assets/edit-room.css",
19
+ "/assets/palette.css",
20
+ "/assets/files.css",
21
+ "/assets/tasks.css",
22
+ "/assets/doc-preview.css",
23
+ "/assets/diagram-viewer.css",
24
+ "/assets/chat/office-preview.js",
25
+ "/assets/office/docx.bundle.js",
26
+ "/assets/office/xlsx.bundle.js",
27
+ "/assets/office/pptx.bundle.js",
28
+ "/assets/marked-18.0.4.js",
29
+ "/assets/dompurify-3.4.7.js",
30
+ "/assets/mermaid-11.12.2.min.js",
31
+ "/assets/icons/icon-192.png",
32
+ "/assets/icons/icon-512.png",
33
+ "/assets/icons/apple-touch-icon.png",
34
+ "/manifest.webmanifest",
33
35
  ];
34
36
  const VERSIONED = new Set(STATIC.filter((path) => path.endsWith(".css") || /^\/assets\/(?:marked|dompurify|mermaid)-/.test(path)));
35
37
  const versioned = (path) => `${path}?v=${VERSION}`;
36
-
37
38
  // Recently viewed images live in their own cache: a release upgrades CACHE, but a photo
38
39
  // should survive until the person changes identity, it ages out, or the caps evict it.
39
40
  const MEDIA_CACHE = "oc-chat-media";
@@ -45,292 +46,370 @@ const REVALIDATE_MS = 10 * 60 * 1000;
45
46
  const MEDIA_LIMITS = { entries: 80, bytes: 64 * 1024 * 1024, age: 30 * 24 * 60 * 60 * 1000 };
46
47
  // Tests lower these numbers before seeding entries; production keeps the values above.
47
48
  self.__MEDIA_LIMITS__ = MEDIA_LIMITS;
48
-
49
49
  // The page owns the identity (a hash of its token and session ID); this worker only
50
50
  // partitions the cache by it. Unknown identity means network-only.
51
51
  let mediaIdentity;
52
52
  let mediaQueue = Promise.resolve();
53
53
  const queueMedia = (task) => {
54
- const run = mediaQueue.then(task, task);
55
- mediaQueue = run.catch(() => {});
56
- return run;
54
+ const run = mediaQueue.then(task, task);
55
+ mediaQueue = run.catch(() => { });
56
+ return run;
57
57
  };
58
-
59
58
  self.addEventListener("install", (event) => {
60
- event.waitUntil((async () => {
61
- const cache = await caches.open(CACHE);
62
- // Stylesheets and classic scripts carry the release version. A client still
63
- // running an older worker therefore misses its old cache after a deploy instead
64
- // of mixing new HTML with stale styles.
65
- await cache.addAll([SHELL, ...STATIC.map((path) => VERSIONED.has(path) ? versioned(path) : path)]);
66
- // The shell is a module graph, so an offline start needs the imports too. Walk them
67
- // from the entry point instead of keeping a list that drifts with every new module.
68
- const pending = ["/assets/chat/index.js"], seen = new Set();
69
- while (pending.length) {
70
- const url = pending.pop();
71
- if (seen.has(url)) continue;
72
- seen.add(url);
73
- const response = await fetch(url).catch(() => null);
74
- if (!response?.ok) continue;
75
- const source = await response.clone().text();
76
- await cache.put(url, response);
77
- for (const match of source.matchAll(/(?:from\s+"|import\(\s*")(\.\.?\/[^"]+\.js)"/g)) {
78
- pending.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
79
- }
80
- }
81
- // A first install should control immediately. A replacement waits until the page
82
- // asks for it, so an open conversation is never reloaded without consent.
83
- if (!self.registration.active) await self.skipWaiting();
84
- })());
59
+ event.waitUntil((async () => {
60
+ const cache = await caches.open(CACHE);
61
+ const report = async (phase, detail = {}) => {
62
+ const clients = await self.clients.matchAll({ includeUncontrolled: true });
63
+ for (const client of clients)
64
+ client.postMessage({ type: "OC_PRECACHE", phase, ...detail });
65
+ };
66
+ // One bad optional asset must not fail the whole release: try each twice, report
67
+ // it as pending, then let a runtime miss fetch it. The shell and the chat module
68
+ // graph are critical: offline start breaks without them, so they fail the install.
69
+ const grab = async (url) => {
70
+ for (let attempt = 0; attempt < 2; attempt++) {
71
+ try {
72
+ const response = await fetch(url, { cache: "no-store" });
73
+ if (response.ok)
74
+ return response;
75
+ }
76
+ catch { /* Retry once, then leave it to the runtime cache miss. */ }
77
+ }
78
+ return null;
79
+ };
80
+ // Stylesheets and classic scripts carry the release version. A client still
81
+ // running an older worker therefore misses its old cache after a deploy instead
82
+ // of mixing new HTML with stale styles.
83
+ const targets = STATIC.map((path) => VERSIONED.has(path) ? versioned(path) : path);
84
+ await report("downloading", { total: targets.length + 1 });
85
+ try {
86
+ const shell = await grab(SHELL);
87
+ if (!shell)
88
+ throw new Error("precache: shell unavailable");
89
+ await cache.put(SHELL, shell).catch(() => { });
90
+ let pending = 0;
91
+ const pendingPaths = [];
92
+ await Promise.all(targets.map(async (url) => {
93
+ const response = await grab(url);
94
+ if (!response) {
95
+ pending += 1;
96
+ pendingPaths.push(url);
97
+ return;
98
+ }
99
+ await cache.put(url, response).catch(() => { });
100
+ }));
101
+ // The shell is a module graph, so an offline start needs the imports too. Walk them
102
+ // from the entry point instead of keeping a list that drifts with every new module.
103
+ const queue = ["/assets/chat/index.js"], seen = new Set();
104
+ while (queue.length) {
105
+ const url = queue.pop();
106
+ if (seen.has(url))
107
+ continue;
108
+ seen.add(url);
109
+ const response = await grab(url);
110
+ if (!response)
111
+ throw new Error(`precache: module unavailable: ${url}`);
112
+ const source = await response.clone().text();
113
+ await cache.put(url, response).catch(() => { });
114
+ for (const match of source.matchAll(/(?:from\s+"|import\(\s*")(\.\.?\/[^"]+\.js)"/g)) {
115
+ queue.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
116
+ }
117
+ }
118
+ await report("ready", { pending, pendingPaths });
119
+ }
120
+ catch (error) {
121
+ await report("failed");
122
+ throw error;
123
+ }
124
+ // A first install should control immediately. A replacement waits until the page
125
+ // asks for it, so an open conversation is never reloaded without consent.
126
+ if (!self.registration.active)
127
+ await self.skipWaiting();
128
+ })());
85
129
  });
86
-
87
130
  self.addEventListener("message", (event) => {
88
- if (event.data?.type === "SKIP_WAITING") {
89
- event.waitUntil(self.skipWaiting());
90
- return;
91
- }
92
- // The first message is a cheap moment to enforce the age policy even if the worker
93
- // was already active when this release first loaded.
94
- if (!self.__mediaPruned) {
95
- self.__mediaPruned = true;
96
- event.waitUntil(pruneMedia().catch(() => {}));
97
- }
98
- if (event.data?.type === "SET_MEDIA_IDENTITY") event.waitUntil(setMediaIdentity(event.data.identity).catch(() => {}));
99
- else if (event.data?.type === "CLEAR_MEDIA_CACHE") event.waitUntil(clearMedia().catch(() => {}));
131
+ if (event.data?.type === "SKIP_WAITING") {
132
+ event.waitUntil(self.skipWaiting());
133
+ return;
134
+ }
135
+ // The first message is a cheap moment to enforce the age policy even if the worker
136
+ // was already active when this release first loaded.
137
+ if (!self.__mediaPruned) {
138
+ self.__mediaPruned = true;
139
+ event.waitUntil(pruneMedia().catch(() => { }));
140
+ }
141
+ if (event.data?.type === "SET_MEDIA_IDENTITY")
142
+ event.waitUntil(setMediaIdentity(event.data.identity).catch(() => { }));
143
+ else if (event.data?.type === "CLEAR_MEDIA_CACHE")
144
+ event.waitUntil(clearMedia().catch(() => { }));
100
145
  });
101
-
102
146
  self.addEventListener("activate", (event) => {
103
- event.waitUntil((async () => {
104
- for (const key of await caches.keys()) {
105
- if (key !== CACHE && key !== MEDIA_CACHE && key.startsWith("oc-chat-")) await caches.delete(key);
106
- }
107
- await self.clients.claim();
108
- })());
109
- // Housekeeping must never delay or fail activation.
110
- event.waitUntil(pruneMedia().catch(() => {}));
147
+ event.waitUntil((async () => {
148
+ for (const key of await caches.keys()) {
149
+ if (key !== CACHE && key !== MEDIA_CACHE && key.startsWith("oc-chat-"))
150
+ await caches.delete(key);
151
+ }
152
+ await self.clients.claim();
153
+ })());
154
+ // Housekeeping must never delay or fail activation.
155
+ event.waitUntil(pruneMedia().catch(() => { }));
111
156
  });
112
-
113
157
  self.addEventListener("fetch", (event) => {
114
- const request = event.request;
115
- if (request.method !== "GET") return;
116
- const url = new URL(request.url);
117
- if (url.origin !== self.location.origin) return;
118
- if (MEDIA_PATH.test(url.pathname)) {
119
- // Partial responses do not belong in a whole-body cache; leave ranges to the browser.
120
- if (request.headers.has("range")) return;
121
- event.respondWith(mediaResponse(event));
122
- return;
123
- }
124
- // Chat data never comes from a cache: a stale answer would show a room that was deleted
125
- // and messages that were already read.
126
- if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/")) return;
127
- if (url.pathname === SHELL) {
158
+ const request = event.request;
159
+ if (request.method !== "GET")
160
+ return;
161
+ const url = new URL(request.url);
162
+ if (url.origin !== self.location.origin)
163
+ return;
164
+ if (MEDIA_PATH.test(url.pathname)) {
165
+ // Partial responses do not belong in a whole-body cache; leave ranges to the browser.
166
+ if (request.headers.has("range"))
167
+ return;
168
+ event.respondWith(mediaResponse(event));
169
+ return;
170
+ }
171
+ // Chat data never comes from a cache: a stale answer would show a room that was deleted
172
+ // and messages that were already read.
173
+ if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/"))
174
+ return;
175
+ if (url.pathname === SHELL) {
176
+ // A page open must not wait for the server or for a release. This worker's cache
177
+ // holds the HTML of its own version; the next worker precaches the next HTML and
178
+ // only shows an update prompt once that install finished.
179
+ event.respondWith((async () => {
180
+ const cached = await caches.match(SHELL);
181
+ if (cached)
182
+ return cached;
183
+ try {
184
+ const response = await fetch(request);
185
+ if (response.ok)
186
+ await (await caches.open(CACHE)).put(SHELL, response.clone());
187
+ return response;
188
+ }
189
+ catch {
190
+ return Response.error();
191
+ }
192
+ })());
193
+ return;
194
+ }
195
+ // Cache hits are not revalidated in the background: install already stored this
196
+ // version's bytes, and rewriting them while an older page runs would mix releases.
128
197
  event.respondWith((async () => {
129
- try {
130
- const response = await fetch(request);
131
- if (response.ok) await (await caches.open(CACHE)).put(SHELL, response.clone());
132
- return response;
133
- } catch {
134
- return (await caches.match(SHELL)) || Response.error();
135
- }
198
+ const cached = await caches.match(request);
199
+ if (cached)
200
+ return cached;
201
+ try {
202
+ const response = await fetch(request);
203
+ if (response.ok)
204
+ await (await caches.open(CACHE)).put(request, response.clone());
205
+ return response;
206
+ }
207
+ catch {
208
+ return Response.error();
209
+ }
136
210
  })());
137
- return;
138
- }
139
- event.respondWith((async () => {
140
- const cached = await caches.match(request);
141
- const network = fetch(request).then(async (response) => {
142
- if (response.ok) await (await caches.open(CACHE)).put(request, response.clone());
143
- return response;
144
- }).catch(() => cached || Response.error());
145
- return cached || network;
146
- })());
147
211
  });
148
-
149
212
  // Cache Storage drops URL fragments, so the partition rides a reserved query parameter.
150
213
  // The index keeps the readable `${url}#${identity}` form.
151
214
  const mediaBodyKey = (url, identity) => `${url}${url.includes("?") ? "&" : "?"}__media_identity__=${identity}`;
152
215
  const mediaIndexKey = (url, identity) => `${url}#${identity}`;
153
-
154
216
  const isMediaEntry = (item) => Boolean(item)
155
- && typeof item.url === "string" && typeof item.key === "string" && typeof item.identity === "string"
156
- && Number.isFinite(item.size) && item.size >= 0
157
- && Number.isFinite(item.usedAt) && Number.isFinite(item.revalidatedAt);
158
-
217
+ && typeof item.url === "string" && typeof item.key === "string" && typeof item.identity === "string"
218
+ && Number.isFinite(item.size) && item.size >= 0
219
+ && Number.isFinite(item.usedAt) && Number.isFinite(item.revalidatedAt);
159
220
  const isCacheable = (response) => response.status !== 206
160
- && response.ok && response.type === "basic"
161
- && (response.headers.get("content-type") || "").startsWith("image/");
162
-
221
+ && response.ok && response.type === "basic"
222
+ && (response.headers.get("content-type") || "").startsWith("image/");
163
223
  const tagged = (response, state) => {
164
- const headers = new Headers(response.headers);
165
- headers.set("X-Media-Cache", state);
166
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
224
+ const headers = new Headers(response.headers);
225
+ headers.set("X-Media-Cache", state);
226
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
167
227
  };
168
-
169
228
  async function loadMediaIdentity() {
170
- if (mediaIdentity !== undefined) return mediaIdentity;
171
- mediaIdentity = null;
172
- try {
173
- const cache = await caches.open(MEDIA_CACHE);
174
- const response = await cache.match(MEDIA_IDENTITY);
175
- const value = response ? await response.json() : null;
176
- if (typeof value?.identity === "string" && IDENTITY_PATTERN.test(value.identity)) mediaIdentity = value.identity;
177
- } catch { /* No stored identity means network-only media. */ }
178
- return mediaIdentity;
229
+ if (mediaIdentity !== undefined)
230
+ return mediaIdentity;
231
+ mediaIdentity = null;
232
+ try {
233
+ const cache = await caches.open(MEDIA_CACHE);
234
+ const response = await cache.match(MEDIA_IDENTITY);
235
+ const value = response ? await response.json() : null;
236
+ if (typeof value?.identity === "string" && IDENTITY_PATTERN.test(value.identity))
237
+ mediaIdentity = value.identity;
238
+ }
239
+ catch { /* No stored identity means network-only media. */ }
240
+ return mediaIdentity;
179
241
  }
180
-
181
242
  async function saveMediaIdentity(identity) {
182
- const cache = await caches.open(MEDIA_CACHE);
183
- await cache.put(MEDIA_IDENTITY, new Response(JSON.stringify({ identity }), { headers: { "Content-Type": "application/json" } }));
243
+ const cache = await caches.open(MEDIA_CACHE);
244
+ await cache.put(MEDIA_IDENTITY, new Response(JSON.stringify({ identity }), { headers: { "Content-Type": "application/json" } }));
184
245
  }
185
-
186
246
  async function setMediaIdentity(identity) {
187
- if (typeof identity !== "string" || !IDENTITY_PATTERN.test(identity)) return;
188
- await queueMedia(async () => {
189
- const previous = await loadMediaIdentity();
190
- mediaIdentity = identity;
191
- if (previous === identity) {
192
- await saveMediaIdentity(identity);
193
- return;
194
- }
195
- // A different browser identity must never read the previous one's cached images.
196
- await caches.delete(MEDIA_CACHE);
197
- await saveMediaIdentity(identity);
198
- });
247
+ if (typeof identity !== "string" || !IDENTITY_PATTERN.test(identity))
248
+ return;
249
+ await queueMedia(async () => {
250
+ const previous = await loadMediaIdentity();
251
+ mediaIdentity = identity;
252
+ if (previous === identity) {
253
+ await saveMediaIdentity(identity);
254
+ return;
255
+ }
256
+ // A different browser identity must never read the previous one's cached images.
257
+ await caches.delete(MEDIA_CACHE);
258
+ await saveMediaIdentity(identity);
259
+ });
199
260
  }
200
-
201
261
  async function clearMedia() {
202
- await queueMedia(async () => {
203
- const identity = await loadMediaIdentity();
204
- await caches.delete(MEDIA_CACHE);
205
- if (identity) await saveMediaIdentity(identity);
206
- });
262
+ await queueMedia(async () => {
263
+ const identity = await loadMediaIdentity();
264
+ await caches.delete(MEDIA_CACHE);
265
+ if (identity)
266
+ await saveMediaIdentity(identity);
267
+ });
207
268
  }
208
-
209
269
  async function readIndex(cache) {
210
- const response = await cache.match(MEDIA_INDEX);
211
- if (!response) return [];
212
- try {
213
- const value = await response.json();
214
- if (!Array.isArray(value)) throw new Error("invalid index");
215
- return value.filter(isMediaEntry);
216
- } catch {
217
- // A damaged index cannot account for bodies; drop them so the caps stay meaningful.
218
- for (const request of await cache.keys()) {
219
- const path = new URL(request.url).pathname;
220
- if (path !== MEDIA_INDEX && path !== MEDIA_IDENTITY) await cache.delete(request);
270
+ const response = await cache.match(MEDIA_INDEX);
271
+ if (!response)
272
+ return [];
273
+ try {
274
+ const value = await response.json();
275
+ if (!Array.isArray(value))
276
+ throw new Error("invalid index");
277
+ return value.filter(isMediaEntry);
278
+ }
279
+ catch {
280
+ // A damaged index cannot account for bodies; drop them so the caps stay meaningful.
281
+ for (const request of await cache.keys()) {
282
+ const path = new URL(request.url).pathname;
283
+ if (path !== MEDIA_INDEX && path !== MEDIA_IDENTITY)
284
+ await cache.delete(request);
285
+ }
286
+ await cache.delete(MEDIA_INDEX);
287
+ return [];
221
288
  }
222
- await cache.delete(MEDIA_INDEX);
223
- return [];
224
- }
225
289
  }
226
-
227
290
  const writeIndex = (cache, items) => cache.put(MEDIA_INDEX, new Response(JSON.stringify(items), { headers: { "Content-Type": "application/json" } }));
228
-
229
291
  async function applyLimits(cache, items) {
230
- const kept = [...items].sort((a, b) => a.usedAt - b.usedAt);
231
- let bytes = kept.reduce((sum, item) => sum + item.size, 0);
232
- const evicted = [];
233
- while (kept.length > MEDIA_LIMITS.entries || (bytes > MEDIA_LIMITS.bytes && kept.length)) {
234
- const item = kept.shift();
235
- bytes -= item.size;
236
- evicted.push(item);
237
- }
238
- for (const item of evicted) await cache.delete(mediaBodyKey(item.url, item.identity));
239
- await writeIndex(cache, kept);
292
+ const kept = [...items].sort((a, b) => a.usedAt - b.usedAt);
293
+ let bytes = kept.reduce((sum, item) => sum + item.size, 0);
294
+ const evicted = [];
295
+ while (kept.length > MEDIA_LIMITS.entries || (bytes > MEDIA_LIMITS.bytes && kept.length)) {
296
+ const item = kept.shift();
297
+ bytes -= item.size;
298
+ evicted.push(item);
299
+ }
300
+ for (const item of evicted)
301
+ await cache.delete(mediaBodyKey(item.url, item.identity));
302
+ await writeIndex(cache, kept);
240
303
  }
241
-
242
304
  async function storeMedia(url, identity, response) {
243
- const blob = await response.blob();
244
- await queueMedia(async () => {
245
- // An identity switch queued between fetch and put must not resurrect old bytes.
246
- if (mediaIdentity !== identity) return;
247
- const cache = await caches.open(MEDIA_CACHE);
248
- await cache.put(mediaBodyKey(url, identity), new Response(blob, {
249
- status: response.status, statusText: response.statusText, headers: response.headers,
250
- }));
251
- const key = mediaIndexKey(url, identity), now = Date.now();
252
- const items = (await readIndex(cache)).filter((item) => item.key !== key);
253
- items.push({ key, url, identity, size: blob.size, usedAt: now, revalidatedAt: now });
254
- await applyLimits(cache, items);
255
- });
305
+ const blob = await response.blob();
306
+ await queueMedia(async () => {
307
+ // An identity switch queued between fetch and put must not resurrect old bytes.
308
+ if (mediaIdentity !== identity)
309
+ return;
310
+ const cache = await caches.open(MEDIA_CACHE);
311
+ await cache.put(mediaBodyKey(url, identity), new Response(blob, {
312
+ status: response.status, statusText: response.statusText, headers: response.headers,
313
+ }));
314
+ const key = mediaIndexKey(url, identity), now = Date.now();
315
+ const items = (await readIndex(cache)).filter((item) => item.key !== key);
316
+ items.push({ key, url, identity, size: blob.size, usedAt: now, revalidatedAt: now });
317
+ await applyLimits(cache, items);
318
+ });
256
319
  }
257
-
258
320
  const touchMedia = (url, identity) => queueMedia(async () => {
259
- const cache = await caches.open(MEDIA_CACHE);
260
- const items = await readIndex(cache);
261
- const item = items.find((entry) => entry.url === url && entry.identity === identity);
262
- if (!item) return;
263
- item.usedAt = Date.now();
264
- await writeIndex(cache, items);
321
+ const cache = await caches.open(MEDIA_CACHE);
322
+ const items = await readIndex(cache);
323
+ const item = items.find((entry) => entry.url === url && entry.identity === identity);
324
+ if (!item)
325
+ return;
326
+ item.usedAt = Date.now();
327
+ await writeIndex(cache, items);
265
328
  });
266
-
267
329
  const revalidating = new Set();
268
330
  function revalidateMedia(request, url, identity) {
269
- const key = mediaIndexKey(url, identity);
270
- if (revalidating.has(key)) return Promise.resolve();
271
- revalidating.add(key);
272
- return (async () => {
273
- try {
274
- const response = await fetch(request);
275
- if (response.status === 401 || response.status === 403 || response.status === 404) {
276
- await queueMedia(async () => {
277
- const cache = await caches.open(MEDIA_CACHE);
278
- const items = await readIndex(cache);
279
- const kept = items.filter((item) => item.key !== key);
280
- await cache.delete(mediaBodyKey(url, identity));
281
- if (kept.length !== items.length) await writeIndex(cache, kept);
282
- });
283
- } else if (response.status === 200 && isCacheable(response)) {
284
- await storeMedia(url, identity, response);
285
- }
286
- } catch { /* A failed revalidation must not remove a working entry. */ }
287
- finally { revalidating.delete(key); }
288
- })();
331
+ const key = mediaIndexKey(url, identity);
332
+ if (revalidating.has(key))
333
+ return Promise.resolve();
334
+ revalidating.add(key);
335
+ return (async () => {
336
+ try {
337
+ const response = await fetch(request);
338
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
339
+ await queueMedia(async () => {
340
+ const cache = await caches.open(MEDIA_CACHE);
341
+ const items = await readIndex(cache);
342
+ const kept = items.filter((item) => item.key !== key);
343
+ await cache.delete(mediaBodyKey(url, identity));
344
+ if (kept.length !== items.length)
345
+ await writeIndex(cache, kept);
346
+ });
347
+ }
348
+ else if (response.status === 200 && isCacheable(response)) {
349
+ await storeMedia(url, identity, response);
350
+ }
351
+ }
352
+ catch { /* A failed revalidation must not remove a working entry. */ }
353
+ finally {
354
+ revalidating.delete(key);
355
+ }
356
+ })();
289
357
  }
290
-
291
358
  async function pruneMedia() {
292
- await queueMedia(async () => {
293
- const cache = await caches.open(MEDIA_CACHE);
294
- const items = await readIndex(cache);
295
- const cutoff = Date.now() - MEDIA_LIMITS.age;
296
- const fresh = items.filter((item) => item.usedAt >= cutoff);
297
- for (const item of items) if (item.usedAt < cutoff) await cache.delete(mediaBodyKey(item.url, item.identity));
298
- await applyLimits(cache, fresh);
299
- });
359
+ await queueMedia(async () => {
360
+ const cache = await caches.open(MEDIA_CACHE);
361
+ const items = await readIndex(cache);
362
+ const cutoff = Date.now() - MEDIA_LIMITS.age;
363
+ const fresh = items.filter((item) => item.usedAt >= cutoff);
364
+ for (const item of items)
365
+ if (item.usedAt < cutoff)
366
+ await cache.delete(mediaBodyKey(item.url, item.identity));
367
+ await applyLimits(cache, fresh);
368
+ });
300
369
  }
301
-
302
370
  async function mediaResponse(event) {
303
- try {
304
- return await serveMedia(event);
305
- } catch {
306
- // Cache Storage can be unavailable (private modes, quota). Media then stays network-only.
307
- try { return tagged(await fetch(event.request), "bypass"); }
308
- catch { return Response.error(); }
309
- }
371
+ try {
372
+ return await serveMedia(event);
373
+ }
374
+ catch {
375
+ // Cache Storage can be unavailable (private modes, quota). Media then stays network-only.
376
+ try {
377
+ return tagged(await fetch(event.request), "bypass");
378
+ }
379
+ catch {
380
+ return Response.error();
381
+ }
382
+ }
310
383
  }
311
-
312
384
  async function serveMedia(event) {
313
- const request = event.request;
314
- const identity = await loadMediaIdentity();
315
- if (!identity) {
316
- try { return tagged(await fetch(request), "bypass"); }
317
- catch { return Response.error(); }
318
- }
319
- const url = request.url;
320
- const cache = await caches.open(MEDIA_CACHE);
321
- const cached = await cache.match(mediaBodyKey(url, identity));
322
- if (cached) {
323
- event.waitUntil(touchMedia(url, identity).catch(() => {}));
324
- const entry = (await readIndex(cache)).find((item) => item.key === mediaIndexKey(url, identity));
325
- // Serving stale is fine; revalidation is background hygiene for revocation/deletion.
326
- if (!entry || Date.now() - entry.revalidatedAt > REVALIDATE_MS) event.waitUntil(revalidateMedia(request, url, identity).catch(() => {}));
327
- return tagged(cached, "hit");
328
- }
329
- try {
330
- const response = await fetch(request);
331
- if (isCacheable(response)) await storeMedia(url, identity, response.clone()).catch(() => {});
332
- return tagged(response, "miss");
333
- } catch {
334
- return Response.error();
335
- }
336
- }
385
+ const request = event.request;
386
+ const identity = await loadMediaIdentity();
387
+ if (!identity) {
388
+ try {
389
+ return tagged(await fetch(request), "bypass");
390
+ }
391
+ catch {
392
+ return Response.error();
393
+ }
394
+ }
395
+ const url = request.url;
396
+ const cache = await caches.open(MEDIA_CACHE);
397
+ const cached = await cache.match(mediaBodyKey(url, identity));
398
+ if (cached) {
399
+ event.waitUntil(touchMedia(url, identity).catch(() => { }));
400
+ const entry = (await readIndex(cache)).find((item) => item.key === mediaIndexKey(url, identity));
401
+ // Serving stale is fine; revalidation is background hygiene for revocation/deletion.
402
+ if (!entry || Date.now() - entry.revalidatedAt > REVALIDATE_MS)
403
+ event.waitUntil(revalidateMedia(request, url, identity).catch(() => { }));
404
+ return tagged(cached, "hit");
405
+ }
406
+ try {
407
+ const response = await fetch(request);
408
+ if (isCacheable(response))
409
+ await storeMedia(url, identity, response.clone()).catch(() => { });
410
+ return tagged(response, "miss");
411
+ }
412
+ catch {
413
+ return Response.error();
414
+ }
415
+ }