@rsc-kit/core 0.25.0 → 0.27.0

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 (47) hide show
  1. package/dist/changed.d.ts +260 -0
  2. package/dist/changed.js +605 -0
  3. package/dist/changed.js.map +1 -0
  4. package/dist/conformance.d.ts +2 -0
  5. package/dist/conformance.js +28 -0
  6. package/dist/conformance.js.map +1 -1
  7. package/dist/headers.d.ts +8 -0
  8. package/dist/headers.js +8 -0
  9. package/dist/headers.js.map +1 -1
  10. package/dist/host.d.ts +3 -1
  11. package/dist/host.js +21 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/js/Changes.d.ts +11 -0
  14. package/dist/js/Changes.js +19 -0
  15. package/dist/js/Changes.js.map +1 -0
  16. package/dist/js/changesStore.d.ts +9 -0
  17. package/dist/js/changesStore.js +178 -0
  18. package/dist/js/changesStore.js.map +1 -0
  19. package/dist/js/navigate.d.ts +1 -1
  20. package/dist/js/navigate.js +4 -1
  21. package/dist/js/navigate.js.map +1 -1
  22. package/dist/js/refreshOn.d.ts +21 -0
  23. package/dist/js/refreshOn.js +58 -0
  24. package/dist/js/refreshOn.js.map +1 -0
  25. package/dist/js/router.d.ts +2 -0
  26. package/dist/js/router.js +7 -0
  27. package/dist/js/router.js.map +1 -1
  28. package/dist/js/section.d.ts +21 -1
  29. package/dist/js/section.js +31 -6
  30. package/dist/js/section.js.map +1 -1
  31. package/dist/manifest.d.ts +6 -0
  32. package/dist/manifest.js.map +1 -1
  33. package/dist/request.d.ts +11 -0
  34. package/dist/request.js +17 -0
  35. package/dist/request.js.map +1 -1
  36. package/dist/sharedRenders.d.ts +9 -0
  37. package/dist/sharedRenders.js +41 -0
  38. package/dist/sharedRenders.js.map +1 -0
  39. package/dist/testHost.d.ts +22 -0
  40. package/dist/testHost.js +23 -0
  41. package/dist/testHost.js.map +1 -1
  42. package/dist/testing.d.ts +1 -1
  43. package/dist/testing.js +7 -1
  44. package/dist/testing.js.map +1 -1
  45. package/dist/vite.js +79 -11
  46. package/dist/vite.js.map +1 -1
  47. package/package.json +5 -1
@@ -0,0 +1,605 @@
1
+ /**
2
+ * Names: a name for data a page depends on, so whatever changes it can say so
3
+ * from anywhere - a webhook, a job, another visitor's action - and every open
4
+ * tab showing it refreshes.
5
+ *
6
+ * // a section says what it depends on
7
+ * export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })
8
+ *
9
+ * // and whatever changes it says so
10
+ * changed(`team:${team}:repos`) // here, from a route.ts or an action
11
+ * rsckit.Changed(ctx, "team:1:repos") // or the backend, from its webhook
12
+ * Rsc::changed("team:$team:repos"); // Laravel
13
+ *
14
+ * A name has a version: a number that moves whenever something says the name
15
+ * changed. Nothing else - not what changed, not the data. A page learns the
16
+ * versions at render; one stream per open tab watches them; when one moves,
17
+ * the sections carrying that name ask for themselves again, the way refresh()
18
+ * does. Data is never pushed, which is what keeps this working on a host that
19
+ * cannot hold state: a version is a read.
20
+ *
21
+ * Where versions live is the source's business. Without a backend they are in
22
+ * this process, which is one instance. With one, the backend keeps them - in
23
+ * its cache or a table, shared by every instance it runs - and answers
24
+ * `__rsc.changed`: given the versions a watcher holds, the ones that differ now.
25
+ * A backend that can wait holds the call until one does; one that cannot
26
+ * answers at once, and the watcher asks again on its interval. The protocol
27
+ * is the same either way, and so is the page.
28
+ */
29
+ import { KEEPALIVE_MS, frame } from "./events.js";
30
+ import { HEADER } from "./headers.js";
31
+ /** The reserved name a backend answers name versions on. */
32
+ export const CHANGED_FUNCTION = "__rsc.changed";
33
+ /** Versions kept in this process: the source without a backend, and the one tests use. */
34
+ export function memoryVersions() {
35
+ const versions = new Map();
36
+ const waiters = new Set();
37
+ const differing = (since) => {
38
+ const out = {};
39
+ for (const [name, held] of Object.entries(since)) {
40
+ const current = versions.get(name) ?? 0;
41
+ if (current !== held)
42
+ out[name] = current;
43
+ }
44
+ return out;
45
+ };
46
+ return {
47
+ async changed(since, wait) {
48
+ const now = differing(since);
49
+ if (Object.keys(now).length > 0 || wait <= 0)
50
+ return now;
51
+ await new Promise((resolve) => {
52
+ const done = () => {
53
+ clearTimeout(timer);
54
+ waiters.delete(done);
55
+ resolve();
56
+ };
57
+ const timer = setTimeout(done, wait);
58
+ // A test or a build must not be held open by a watcher's wait.
59
+ timer.unref?.();
60
+ waiters.add(done);
61
+ });
62
+ return differing(since);
63
+ },
64
+ bump(names) {
65
+ for (const name of names)
66
+ versions.set(name, (versions.get(name) ?? 0) + 1);
67
+ for (const wake of [...waiters])
68
+ wake();
69
+ },
70
+ };
71
+ }
72
+ /**
73
+ * Versions kept by the backend, read through `__rsc.changed`.
74
+ *
75
+ * A backend that has not got the function - an adapter from before names, or
76
+ * a host of plain rpc functions - is answered from this process instead,
77
+ * found out on the first ask and remembered, so a page with names still works
78
+ * on it: one instance, versions bumped by `changed()` here.
79
+ */
80
+ export function backendVersions(call) {
81
+ let local = null;
82
+ // A backend's "no such function", or the test host's "no handler for".
83
+ const unknown = (error) => /no host function named|has no handler for/i.test(error instanceof Error ? error.message : String(error));
84
+ return {
85
+ async changed(since, wait) {
86
+ if (local)
87
+ return local.changed(since, wait);
88
+ try {
89
+ const answer = (await call(CHANGED_FUNCTION, {
90
+ since,
91
+ wait,
92
+ }));
93
+ return answer?.versions ?? {};
94
+ }
95
+ catch (error) {
96
+ if (!unknown(error))
97
+ throw error;
98
+ local = memoryVersions();
99
+ return local.changed(since, wait);
100
+ }
101
+ },
102
+ bump(names) {
103
+ if (local)
104
+ return local.bump(names);
105
+ throw new Error("changed() bumps versions this process keeps, and a backend keeps these: say the name changed there - " +
106
+ "rsckit.Changed(ctx, ...) in Go, Rsc::changed(...) in Laravel.");
107
+ },
108
+ };
109
+ }
110
+ /**
111
+ * Versions in a table every instance shares: the web servers, and the worker
112
+ * that finishes a job and says so. The same table and columns Go's
113
+ * `SQLVersions` uses, so a Go service and a JavaScript worker can share one.
114
+ *
115
+ * installVersionSource(sqlVersions({
116
+ * query: (text, params) => sql.unsafe(text, params),
117
+ * placeholder: (n) => '$' + n,
118
+ * listen: (wake) => sql.listen('rsc_versions', wake),
119
+ * notify: () => sql.notify('rsc_versions', ''),
120
+ * }))
121
+ *
122
+ * Written with an UPDATE and, the first time, an INSERT - two statements any
123
+ * SQL dialect has - rather than an upsert each spells differently. Takes the
124
+ * app's own driver, so the engine has no database dependency of its own.
125
+ */
126
+ export function sqlVersions(options) {
127
+ const { query } = options;
128
+ const table = options.table ?? "rsc_versions";
129
+ const mark = options.placeholder ?? (() => "?");
130
+ return createVersions({
131
+ async read(names) {
132
+ const rows = await query(`SELECT name, version FROM ${table} WHERE name IN (${names.map((_, i) => mark(i + 1)).join(", ")})`, names);
133
+ // A BIGINT comes back as a string from most drivers.
134
+ return Object.fromEntries(rows.map((row) => [String(row.name), Number(row.version)]));
135
+ },
136
+ async bump(names) {
137
+ const update = `UPDATE ${table} SET version = version + 1 WHERE name = ${mark(1)}`;
138
+ const insert = `INSERT INTO ${table} (name, version) VALUES (${mark(1)}, 1)`;
139
+ for (const name of names) {
140
+ // The row count is not something every driver reports the same way,
141
+ // so ask: a name with no row yet gets one.
142
+ const [exists] = await query(`SELECT 1 AS found FROM ${table} WHERE name = ${mark(1)}`, [name]);
143
+ if (exists) {
144
+ await query(update, [name]);
145
+ continue;
146
+ }
147
+ try {
148
+ await query(insert, [name]);
149
+ }
150
+ catch {
151
+ // Another instance inserted it first: bump that one.
152
+ await query(update, [name]);
153
+ }
154
+ }
155
+ },
156
+ listen: options.listen,
157
+ notify: options.notify,
158
+ }, { poll: options.poll });
159
+ }
160
+ /**
161
+ * A version source over any store: SQL through any driver or ORM - Drizzle,
162
+ * Prisma, Kysely, Knex - or Redis, or anything with a read and an increment.
163
+ *
164
+ * installVersionSource(createVersions({ read, bump, listen, notify }))
165
+ *
166
+ * rsc-kit owns the rest: an ask waits up to the time it was given for a
167
+ * version to differ, reading every `poll` ms (1000 by default) or the moment
168
+ * `listen` wakes it, and a bump in this process wakes this process's asks at
169
+ * once whatever the store.
170
+ */
171
+ export function createVersions(store, options = {}) {
172
+ const poll = options.poll ?? 1_000;
173
+ const waiters = new Set();
174
+ const wakeAll = () => {
175
+ for (const wake of [...waiters])
176
+ wake();
177
+ };
178
+ if (store.listen)
179
+ void Promise.resolve(store.listen(wakeAll)).catch(() => { });
180
+ const read = async (names) => {
181
+ if (names.length === 0)
182
+ return {};
183
+ const found = await store.read(names);
184
+ return Object.fromEntries(names.map((name) => [name, Number(found[name] ?? 0)]));
185
+ };
186
+ return {
187
+ async changed(since, wait) {
188
+ const names = Object.keys(since);
189
+ const deadline = Date.now() + Math.max(0, wait);
190
+ for (;;) {
191
+ const versions = await read(names);
192
+ const differ = {};
193
+ for (const name of names)
194
+ if (versions[name] !== since[name])
195
+ differ[name] = versions[name] ?? 0;
196
+ const remaining = deadline - Date.now();
197
+ if (Object.keys(differ).length > 0 || remaining <= 0)
198
+ return differ;
199
+ await new Promise((resolve) => {
200
+ const done = () => {
201
+ clearTimeout(timer);
202
+ waiters.delete(done);
203
+ resolve();
204
+ };
205
+ const timer = setTimeout(done, Math.min(poll, remaining));
206
+ timer.unref?.();
207
+ waiters.add(done);
208
+ });
209
+ }
210
+ },
211
+ async bump(names) {
212
+ const unique = [...new Set(names)];
213
+ if (unique.length === 0)
214
+ return;
215
+ await store.bump(unique);
216
+ wakeAll();
217
+ if (store.notify)
218
+ await store.notify();
219
+ },
220
+ };
221
+ }
222
+ /**
223
+ * Versions in Postgres, from the client the app already has:
224
+ *
225
+ * installVersionSource(postgresVersions(sql))
226
+ *
227
+ * `sqlVersions` with Postgres's placeholders, and - when the client can
228
+ * LISTEN, as postgres.js can - a change on one instance wakes the waiting asks
229
+ * on every other at once, rather than on their next read of the table.
230
+ * Without it (`Bun.sql`), the table is read once a second while an ask waits.
231
+ *
232
+ * CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)
233
+ */
234
+ export function postgresVersions(sql, options = {}) {
235
+ const channel = options.channel ?? "rsc_versions";
236
+ const listen = sql.listen?.bind(sql);
237
+ const notify = sql.notify?.bind(sql);
238
+ return sqlVersions({
239
+ query: async (text, params) => await sql.unsafe(text, params),
240
+ placeholder: (n) => "$" + n,
241
+ table: options.table,
242
+ poll: options.poll,
243
+ listen: listen ? (wake) => listen(channel, wake) : undefined,
244
+ notify: listen && notify ? () => notify(channel, "") : undefined,
245
+ });
246
+ }
247
+ const SOURCE = Symbol.for("rsc-kit.version-source");
248
+ const BACKEND_SOURCE = Symbol.for("rsc-kit.backend-version-source");
249
+ const LOCAL_SOURCE = Symbol.for("rsc-kit.local-version-source");
250
+ const globals = globalThis;
251
+ /**
252
+ * Install where versions are read from - a table, Redis, any store - for this
253
+ * process; `null` takes it out again.
254
+ *
255
+ * The app's choice wins over the backend's: with a Go or Laravel backend that
256
+ * writes its versions to a store this process can read too, reading it here
257
+ * means watching costs the backend nothing.
258
+ */
259
+ export function installVersionSource(source) {
260
+ globals[SOURCE] = source;
261
+ }
262
+ /** The engine's, when a backend is installed: its versions, read through it. Not for apps. */
263
+ export function installBackendVersionSource(source) {
264
+ globals[BACKEND_SOURCE] = source;
265
+ }
266
+ /** The source in use: the app's, else the backend's, else this process's own. */
267
+ export function versionSource() {
268
+ return (globals[SOURCE] ??
269
+ globals[BACKEND_SOURCE] ??
270
+ (globals[LOCAL_SOURCE] ??= memoryVersions()));
271
+ }
272
+ /**
273
+ * Say these names changed, so every open tab showing them refreshes.
274
+ *
275
+ * export async function POST(request: Request) { // a webhook, in a route.ts
276
+ * const { team } = await request.json()
277
+ * changed(`team:${team}:repos`)
278
+ * return new Response(null, { status: 204 })
279
+ * }
280
+ *
281
+ * For an app that keeps its versions here. With a backend the versions are
282
+ * its, and so is the call: `rsckit.Changed`, `Rsc::changed`.
283
+ */
284
+ export async function changed(...names) {
285
+ await versionSource().bump(names);
286
+ }
287
+ // ── Tokens ───────────────────────────────────────────────────────────────────
288
+ //
289
+ // A tab may watch exactly the names its page was rendered with. Rather than
290
+ // remembering what each tab was given - state, which a Worker cannot keep
291
+ // between requests - every name goes to the client signed, and comes back
292
+ // with its signature. Verified, not looked up, so a watch request is
293
+ // stateless, and a browser cannot make up a name to watch.
294
+ /** Thrown when a production server has no key to sign names with. */
295
+ export class MissingSigningSecret extends Error {
296
+ constructor() {
297
+ super("refreshOn needs a signing secret in production, the same on every instance: set RSC_SIGNING_SECRET " +
298
+ "to a long random string. Without one, each instance would sign with its own random key, and a tab " +
299
+ "served by one would be refused by the next.");
300
+ this.name = "MissingSigningSecret";
301
+ }
302
+ }
303
+ // On the global rather than in this module: an app imports this file through
304
+ // its own copy of the package, and a key configured there must be the key the
305
+ // engine's copy signs and verifies with.
306
+ const KEY = Symbol.for("rsc-kit.signing-key");
307
+ function keying() {
308
+ return (globals[KEY] ??= {
309
+ secret: null,
310
+ keyed: null,
311
+ signatures: new Map(),
312
+ });
313
+ }
314
+ const env = (name) => globalThis
315
+ .process?.env?.[name] || undefined;
316
+ const production = () => env("NODE_ENV") === "production";
317
+ /**
318
+ * The secret names are signed with, when it does not come from the
319
+ * environment. Normally it does: `RSC_SIGNING_SECRET`, the same on every
320
+ * instance, or a tab served by one is refused by another.
321
+ *
322
+ * Its own secret, not the backend's host-call secret: that one authorises
323
+ * calls between the renderer and a backend, and an app with no backend has
324
+ * no reason to have it. Two jobs, two keys - one leaking does not hand out
325
+ * the other.
326
+ */
327
+ export function configureChanged(options) {
328
+ const state = keying();
329
+ state.secret = options.secret ?? null;
330
+ state.keyed = null;
331
+ state.signatures.clear();
332
+ }
333
+ /** The secret in use: configured, or from the environment; null when there is none. */
334
+ function secretInUse() {
335
+ const state = keying();
336
+ return state.secret ?? env("RSC_SIGNING_SECRET") ?? null;
337
+ }
338
+ /**
339
+ * Refuse, in production, to sign with a key nobody else has.
340
+ *
341
+ * A random key is right for one process - a dev server - and silently wrong
342
+ * for two: every tab served by one instance is refused by the next, and never
343
+ * refreshes. The server calls this on its first request when the app uses
344
+ * refreshOn, so the misconfiguration is an error at once rather than a page
345
+ * that quietly stops updating.
346
+ */
347
+ export function assertSigningSecret() {
348
+ if (!secretInUse() && production())
349
+ throw new MissingSigningSecret();
350
+ }
351
+ let warnedRandom = false;
352
+ async function key() {
353
+ const state = keying();
354
+ return (state.keyed ??= (async () => {
355
+ const secret = secretInUse();
356
+ let raw;
357
+ if (secret)
358
+ raw = new TextEncoder().encode(secret);
359
+ else if (production())
360
+ throw new MissingSigningSecret();
361
+ else {
362
+ if (!warnedRandom) {
363
+ warnedRandom = true;
364
+ console.warn("[rsc-kit] refreshOn is signing with a random key, which is fine for one dev server. " +
365
+ "Set RSC_SIGNING_SECRET before running more than one instance.");
366
+ }
367
+ raw = crypto.getRandomValues(new Uint8Array(32));
368
+ }
369
+ return await crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
370
+ })());
371
+ }
372
+ /** A name's signature: the first 16 bytes of an HMAC, base64url, which is what rides in a url. */
373
+ export function sign(name) {
374
+ const { signatures } = keying();
375
+ let pending = signatures.get(name);
376
+ if (!pending) {
377
+ pending = (async () => {
378
+ const mac = await crypto.subtle.sign("HMAC", await key(), new TextEncoder().encode(name));
379
+ return base64url(new Uint8Array(mac).slice(0, 16));
380
+ })();
381
+ // Bounded: a name with a visitor's id in it is a new entry per visitor.
382
+ if (signatures.size > 10_000)
383
+ signatures.clear();
384
+ signatures.set(name, pending);
385
+ }
386
+ return pending;
387
+ }
388
+ async function verify(name, signature) {
389
+ const expected = await sign(name);
390
+ if (expected.length !== signature.length)
391
+ return false;
392
+ let differ = 0;
393
+ for (let i = 0; i < expected.length; i++)
394
+ differ |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
395
+ return differ === 0;
396
+ }
397
+ function base64url(bytes) {
398
+ let text = "";
399
+ for (const byte of bytes)
400
+ text += String.fromCharCode(byte);
401
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
402
+ }
403
+ // ── Watching ─────────────────────────────────────────────────────────────────
404
+ //
405
+ // One stream per open tab, and one ask of the source per process: every
406
+ // stream's names are asked about together, on an interval, and a version that
407
+ // moved is written to every stream holding its name. A thousand tabs on a
408
+ // long-lived server cost the backend one call per interval, not a thousand.
409
+ // On a host that answers each request in its own isolate the sharing is
410
+ // whatever the isolate serves at once, and a lone stream asks for itself -
411
+ // the same code, degrading to one small call per tab per interval.
412
+ /** How often the source is asked, when it answered at once. */
413
+ export const CHANGES_INTERVAL_MS = 2_000;
414
+ /** How long the source may hold one ask. Bounds how long a new tab waits to join the shared ask. */
415
+ export const CHANGES_WAIT_MS = 5_000;
416
+ const streams = new Set();
417
+ /** The latest version seen for each name any stream holds. */
418
+ const known = new Map();
419
+ let running = false;
420
+ let wake = null;
421
+ let warned = false;
422
+ function observe(name, version) {
423
+ if (known.get(name) === version)
424
+ return;
425
+ known.set(name, version);
426
+ for (const stream of streams)
427
+ if (stream.names.has(name))
428
+ stream.send(name, version);
429
+ }
430
+ /** Mapped to this process's set of streams: what to ask about, relative to what is known. */
431
+ function sinceAll() {
432
+ const since = {};
433
+ for (const stream of streams)
434
+ for (const name of stream.names)
435
+ since[name] = known.get(name) ?? 0;
436
+ return since;
437
+ }
438
+ async function loop() {
439
+ running = true;
440
+ try {
441
+ while (streams.size > 0) {
442
+ const started = Date.now();
443
+ try {
444
+ const moved = await versionSource().changed(sinceAll(), CHANGES_WAIT_MS);
445
+ for (const [name, version] of Object.entries(moved))
446
+ observe(name, version);
447
+ }
448
+ catch (error) {
449
+ // A backend blip is not the end of watching. Said once, not per interval.
450
+ if (!warned) {
451
+ warned = true;
452
+ console.warn("[rsc-kit] asking the backend for name versions failed: " +
453
+ (error instanceof Error ? error.message : String(error)));
454
+ }
455
+ }
456
+ // A source that waited used the interval; one that answered at once is
457
+ // asked again after it. A stream opening meanwhile wakes this early.
458
+ const remaining = CHANGES_INTERVAL_MS - (Date.now() - started);
459
+ if (remaining > 0 && streams.size > 0) {
460
+ await new Promise((resolve) => {
461
+ const timer = setTimeout(resolve, remaining);
462
+ timer.unref?.();
463
+ wake = () => {
464
+ clearTimeout(timer);
465
+ resolve();
466
+ };
467
+ });
468
+ wake = null;
469
+ }
470
+ }
471
+ }
472
+ finally {
473
+ running = false;
474
+ // A stream that opened as the loop was ending starts it again.
475
+ if (streams.size > 0)
476
+ void loop();
477
+ }
478
+ }
479
+ function parseWatch(url) {
480
+ const raw = url.searchParams.get("w");
481
+ if (!raw)
482
+ return null;
483
+ let entries;
484
+ try {
485
+ entries = JSON.parse(raw);
486
+ }
487
+ catch {
488
+ return null;
489
+ }
490
+ if (!Array.isArray(entries) || entries.length === 0 || entries.length > 200)
491
+ return null;
492
+ const parsed = [];
493
+ for (const entry of entries) {
494
+ if (!Array.isArray(entry) || entry.length !== 3)
495
+ return null;
496
+ const [name, version, signature] = entry;
497
+ if (typeof name !== "string" ||
498
+ typeof version !== "number" ||
499
+ typeof signature !== "string")
500
+ return null;
501
+ parsed.push({ name, version, signature });
502
+ }
503
+ return parsed;
504
+ }
505
+ /**
506
+ * The stream a tab watches its names on: `GET /_rsc/changes?w=[[name, version, signature], …]`.
507
+ *
508
+ * One `data:` line per version that moved, `{ name, version }`, from the moment
509
+ * the stream opens - a name that moved between the render and now is reported
510
+ * at once, so nothing that happened in the gap is missed. Keepalives as an
511
+ * events() route sends them; ends when the browser goes away.
512
+ */
513
+ export async function changes(request) {
514
+ const entries = parseWatch(new URL(request.url));
515
+ if (!entries)
516
+ return new Response("Bad watch request.", { status: 400 });
517
+ for (const { name, signature } of entries) {
518
+ if (!(await verify(name, signature))) {
519
+ return new Response("Not a name this page was rendered with.", {
520
+ status: 403,
521
+ });
522
+ }
523
+ }
524
+ const since = {};
525
+ for (const { name, version } of entries)
526
+ since[name] = version;
527
+ const encoder = new TextEncoder();
528
+ let stream = null;
529
+ const body = new ReadableStream({
530
+ start(sink) {
531
+ const write = (text) => {
532
+ try {
533
+ sink.enqueue(encoder.encode(text));
534
+ }
535
+ catch {
536
+ // Closed under us; the cancel below ends the rest.
537
+ }
538
+ };
539
+ write("retry: 2000\n\n");
540
+ const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
541
+ keepalive.unref?.();
542
+ const me = {
543
+ names: new Set(Object.keys(since)),
544
+ send: (name, version) => write(frame({ name, version })),
545
+ };
546
+ stream = me;
547
+ streams.add(me);
548
+ const end = () => {
549
+ clearInterval(keepalive);
550
+ streams.delete(me);
551
+ try {
552
+ sink.close();
553
+ }
554
+ catch {
555
+ // Already closed.
556
+ }
557
+ };
558
+ request.signal.addEventListener("abort", end, { once: true });
559
+ // What is known already answers at once; what is not is seeded with
560
+ // what this tab holds, so the shared ask compares against it.
561
+ for (const [name, version] of Object.entries(since)) {
562
+ const seen = known.get(name);
563
+ if (seen === undefined)
564
+ known.set(name, version);
565
+ else if (seen !== version)
566
+ me.send(name, seen);
567
+ }
568
+ // This tab's own first ask, holding as long as the source will: the
569
+ // shared ask may be mid-wait on an older set of names, and a name moving
570
+ // in the seconds before this one joins it must not go unnoticed.
571
+ void versionSource()
572
+ .changed(since, CHANGES_WAIT_MS)
573
+ .then((moved) => {
574
+ for (const [name, version] of Object.entries(moved))
575
+ observe(name, version);
576
+ })
577
+ .catch(() => { });
578
+ if (!running)
579
+ void loop();
580
+ else
581
+ wake?.();
582
+ },
583
+ cancel() {
584
+ if (stream)
585
+ streams.delete(stream);
586
+ },
587
+ });
588
+ return new Response(body, {
589
+ headers: {
590
+ "Content-Type": "text/event-stream; charset=utf-8",
591
+ "Cache-Control": "no-store",
592
+ "X-Accel-Buffering": "no",
593
+ },
594
+ });
595
+ }
596
+ /** For tests: forget every stream and version this process has seen. */
597
+ export function resetChanges() {
598
+ streams.clear();
599
+ known.clear();
600
+ warned = false;
601
+ delete globals[LOCAL_SOURCE];
602
+ }
603
+ /** The url a tab opens to watch, for the client. */
604
+ export const CHANGES_PATH = HEADER.changesPath;
605
+ //# sourceMappingURL=changed.js.map