@drupflare/spool 0.4.0 → 1.0.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 (162) hide show
  1. package/README.md +206 -1756
  2. package/dist/angular/index.d.ts +13 -0
  3. package/dist/angular/index.js +25 -0
  4. package/dist/angular/pages.d.ts +28 -0
  5. package/dist/angular/pages.js +85 -0
  6. package/dist/cdn/client.js +1 -1
  7. package/dist/cdn/location.d.ts +6 -0
  8. package/dist/cdn/location.js +8 -0
  9. package/dist/cdn/manifest.json +7 -7
  10. package/dist/cdn/spool-sw.js +1 -1
  11. package/dist/client/bootstrap.d.ts +57 -0
  12. package/dist/client/bootstrap.js +307 -0
  13. package/dist/client/contact.d.ts +24 -0
  14. package/dist/client/contact.js +66 -0
  15. package/dist/client/declared.d.ts +23 -0
  16. package/dist/client/declared.js +68 -0
  17. package/dist/client/entry.js +91 -2
  18. package/dist/client/gate.d.ts +1 -0
  19. package/dist/client/gate.js +148 -0
  20. package/dist/client/index.d.ts +25 -0
  21. package/dist/client/index.js +1 -0
  22. package/dist/client/live.d.ts +66 -0
  23. package/dist/client/live.js +225 -0
  24. package/dist/client/navigate-entry.d.ts +1 -0
  25. package/dist/client/navigate-entry.js +4 -0
  26. package/dist/client/navigate.d.ts +54 -0
  27. package/dist/client/navigate.js +272 -0
  28. package/dist/client/persist.d.ts +2 -0
  29. package/dist/client/persist.js +9 -0
  30. package/dist/client/register.d.ts +11 -1
  31. package/dist/client/register.js +19 -8
  32. package/dist/express/index.d.ts +11 -0
  33. package/dist/express/index.js +209 -0
  34. package/dist/hono/index.d.ts +19 -0
  35. package/dist/hono/index.js +49 -0
  36. package/dist/next/index.d.ts +33 -0
  37. package/dist/next/index.js +41 -0
  38. package/dist/next/pages.d.ts +22 -0
  39. package/dist/next/pages.js +39 -0
  40. package/dist/node/listener.d.ts +3 -0
  41. package/dist/node/listener.js +57 -2
  42. package/dist/nuxt/index.d.ts +22 -0
  43. package/dist/nuxt/index.js +104 -0
  44. package/dist/nuxt/pages.d.ts +26 -0
  45. package/dist/nuxt/pages.js +48 -0
  46. package/dist/nuxt/runtime/index.d.ts +24 -0
  47. package/dist/nuxt/runtime/index.js +58 -0
  48. package/dist/plugins/coverage.d.ts +14 -0
  49. package/dist/plugins/coverage.js +27 -0
  50. package/dist/plugins/mode.d.ts +19 -0
  51. package/dist/plugins/mode.js +20 -0
  52. package/dist/plugins/path.d.ts +16 -0
  53. package/dist/plugins/path.js +139 -0
  54. package/dist/plugins/report.d.ts +22 -0
  55. package/dist/plugins/report.js +18 -0
  56. package/dist/plugins/routes.d.ts +38 -0
  57. package/dist/plugins/routes.js +52 -0
  58. package/dist/plugins/static.d.ts +42 -0
  59. package/dist/plugins/static.js +97 -0
  60. package/dist/protocol/bundle.d.ts +111 -0
  61. package/dist/protocol/bundle.js +428 -0
  62. package/dist/protocol/config.d.ts +65 -1
  63. package/dist/protocol/config.js +28 -0
  64. package/dist/protocol/dataset.d.ts +6 -0
  65. package/dist/protocol/dataset.js +6 -0
  66. package/dist/protocol/envelope.d.ts +33 -1
  67. package/dist/protocol/envelope.js +15 -1
  68. package/dist/protocol/errors.d.ts +1 -1
  69. package/dist/protocol/index-rows.d.ts +22 -0
  70. package/dist/protocol/index-rows.js +53 -0
  71. package/dist/protocol/index.d.ts +2 -0
  72. package/dist/protocol/index.js +2 -0
  73. package/dist/protocol/normalise.d.ts +4 -4
  74. package/dist/protocol/normalise.js +9 -5
  75. package/dist/protocol/ring.d.ts +58 -0
  76. package/dist/protocol/ring.js +6 -0
  77. package/dist/protocol/route.d.ts +57 -11
  78. package/dist/protocol/route.js +95 -3
  79. package/dist/protocol/tag.d.ts +22 -2
  80. package/dist/protocol/tag.js +25 -4
  81. package/dist/protocol/view.d.ts +2 -0
  82. package/dist/protocol/view.js +8 -2
  83. package/dist/protocol/views.d.ts +6 -0
  84. package/dist/protocol/views.js +15 -0
  85. package/dist/protocol/write.d.ts +92 -4
  86. package/dist/protocol/write.js +251 -9
  87. package/dist/proxy/eligible.d.ts +22 -1
  88. package/dist/proxy/eligible.js +62 -15
  89. package/dist/proxy/proxy.js +28 -18
  90. package/dist/react-router/index.d.ts +20 -0
  91. package/dist/react-router/index.js +60 -0
  92. package/dist/react-router/pages.d.ts +34 -0
  93. package/dist/react-router/pages.js +83 -0
  94. package/dist/report/demand.d.ts +49 -0
  95. package/dist/report/demand.js +60 -0
  96. package/dist/report/economics.d.ts +55 -0
  97. package/dist/report/economics.js +189 -0
  98. package/dist/report/headline.d.ts +158 -0
  99. package/dist/report/headline.js +473 -0
  100. package/dist/report/index.d.ts +2 -0
  101. package/dist/report/index.js +2 -0
  102. package/dist/report/inputs.d.ts +79 -0
  103. package/dist/report/inputs.js +115 -0
  104. package/dist/report/measurement.d.ts +1 -1
  105. package/dist/report/measurement.js +5 -1
  106. package/dist/report/traffic.d.ts +8 -0
  107. package/dist/report/traffic.js +7 -0
  108. package/dist/server/bundle.d.ts +55 -0
  109. package/dist/server/bundle.js +172 -0
  110. package/dist/server/dataset.d.ts +8 -2
  111. package/dist/server/dataset.js +51 -4
  112. package/dist/server/embedded.d.ts +7 -3
  113. package/dist/server/embedded.js +7 -3
  114. package/dist/server/index.d.ts +5 -1
  115. package/dist/server/index.js +5 -1
  116. package/dist/server/live-sockets.d.ts +54 -0
  117. package/dist/server/live-sockets.js +131 -0
  118. package/dist/server/live.d.ts +146 -0
  119. package/dist/server/live.js +228 -0
  120. package/dist/server/ring.d.ts +77 -0
  121. package/dist/server/ring.js +311 -0
  122. package/dist/server/spool.d.ts +139 -4
  123. package/dist/server/spool.js +457 -28
  124. package/dist/server/static.d.ts +42 -0
  125. package/dist/server/static.js +29 -0
  126. package/dist/server/stub.d.ts +43 -5
  127. package/dist/server/stub.js +126 -8
  128. package/dist/server/write.d.ts +23 -1
  129. package/dist/server/write.js +96 -0
  130. package/dist/stores/durable-object.d.ts +46 -0
  131. package/dist/stores/durable-object.js +114 -0
  132. package/dist/sw/analytics.d.ts +1 -1
  133. package/dist/sw/analytics.js +2 -2
  134. package/dist/sw/coverage.d.ts +6 -0
  135. package/dist/sw/coverage.js +34 -0
  136. package/dist/sw/family.d.ts +15 -0
  137. package/dist/sw/family.js +48 -0
  138. package/dist/sw/idb.d.ts +2 -0
  139. package/dist/sw/idb.js +2 -2
  140. package/dist/sw/index.d.ts +2 -0
  141. package/dist/sw/index.js +1 -0
  142. package/dist/sw/pack/store.d.ts +128 -0
  143. package/dist/sw/pack/store.js +737 -0
  144. package/dist/sw/policy.d.ts +2 -0
  145. package/dist/sw/policy.js +11 -0
  146. package/dist/sw/probe.d.ts +16 -0
  147. package/dist/sw/probe.js +25 -0
  148. package/dist/sw/router.d.ts +3 -2
  149. package/dist/sw/router.js +15 -2
  150. package/dist/sw/runtime.d.ts +48 -1
  151. package/dist/sw/runtime.js +548 -68
  152. package/dist/sw/scheduler.d.ts +6 -1
  153. package/dist/sw/scheduler.js +22 -5
  154. package/dist/sw/write.d.ts +41 -1
  155. package/dist/sw/write.js +188 -5
  156. package/dist/version.d.ts +1 -1
  157. package/dist/version.js +1 -2
  158. package/dist/vite/index.d.ts +26 -0
  159. package/dist/vite/index.js +66 -0
  160. package/dist/vue/index.d.ts +36 -0
  161. package/dist/vue/index.js +53 -0
  162. package/package.json +64 -4
@@ -0,0 +1,148 @@
1
+ // the inline gate; it stands in for the client's script tag until a click needs the runtime
2
+ import { engineOf } from '../protocol/view.js';
3
+ import { viewStamps } from '../protocol/views.js';
4
+ const { dataset } = document.currentScript;
5
+ const VIEWS = 'spool:views';
6
+ const STAMPS = 'spool:stamps';
7
+ const BOOT = 'spool:boot';
8
+ const paths = (dataset['held'] ?? '').split(' ').filter(Boolean);
9
+ const leaseMs = Number(dataset['lease']) * 1000;
10
+ let life = 1;
11
+ let view = 1;
12
+ let prev = '';
13
+ let loaded = false;
14
+ let src = dataset['src'] ?? '';
15
+ try {
16
+ const seen = Number(localStorage.getItem(VIEWS));
17
+ life = (seen >= 0 && seen < 1e9 ? seen : 0) + 1;
18
+ localStorage.setItem(VIEWS, String(life));
19
+ view = life;
20
+ if (leaseMs > 0) {
21
+ prev = localStorage.getItem(STAMPS) ?? '';
22
+ const stamps = viewStamps(prev, Date.now(), leaseMs);
23
+ localStorage.setItem(STAMPS, stamps.join());
24
+ view = stamps.length;
25
+ }
26
+ // a boot script used before is in the browser cache; one from another runtime version is not used
27
+ const stored = localStorage.getItem(BOOT);
28
+ if (stored?.startsWith(src.slice(0, src.lastIndexOf('/') + 1))) {
29
+ src = stored;
30
+ loaded = true;
31
+ }
32
+ }
33
+ catch {
34
+ // a failing storage leaves the gate to the click
35
+ }
36
+ // the client counts its own view, so the gate gives back the one it wrote
37
+ function load(url, to) {
38
+ const script = document.createElement('script');
39
+ script.src = url;
40
+ if (dataset['integrity']) {
41
+ script.integrity = dataset['integrity'];
42
+ script.crossOrigin = 'anonymous';
43
+ }
44
+ script.dataset['spoolClient'] = '';
45
+ if (dataset['spoolWorker'])
46
+ script.dataset['spoolWorker'] = dataset['spoolWorker'];
47
+ if (to)
48
+ script.onerror = () => location.assign(to);
49
+ try {
50
+ localStorage.setItem(VIEWS, String(life - 1));
51
+ localStorage.setItem(STAMPS, prev);
52
+ }
53
+ catch {
54
+ // the client counts from what the storage holds
55
+ }
56
+ document.head.append(script);
57
+ }
58
+ // the boot script the page's ring names; a page with no ring, or a ring that names none, has no pack to carry
59
+ function bootOf() {
60
+ try {
61
+ return JSON.parse(document.getElementById('spool-ring')?.textContent ?? '').boot;
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ // the boot script is going to load, so no click or later view loads it again
68
+ function claim(boot) {
69
+ loaded = true;
70
+ document.removeEventListener('click', onClick);
71
+ document.removeEventListener('submit', onSubmit);
72
+ try {
73
+ localStorage.setItem(BOOT, boot);
74
+ }
75
+ catch {
76
+ // the boot script is fetched again on a later document
77
+ }
78
+ }
79
+ function take(event, url) {
80
+ const { pathname, search } = url;
81
+ if (url.origin !== location.origin)
82
+ return;
83
+ if (url.hash && pathname === location.pathname && search === location.search)
84
+ return;
85
+ const answered = (path) => path[0] === '?'
86
+ ? search && pathname === path.slice(1)
87
+ : !search && pathname.startsWith(path);
88
+ const boot = paths.some(answered) ? bootOf() : undefined;
89
+ if (!boot)
90
+ return;
91
+ claim(boot);
92
+ // a client router cancels the event on the anchor, before this listener; it keeps the navigation
93
+ // and never makes the document views that register a worker, so the runtime registers it now
94
+ if (event.defaultPrevented) {
95
+ globalThis.__SPOOL_BOOT__ = { router: true };
96
+ return load(boot);
97
+ }
98
+ event.preventDefault();
99
+ globalThis.__SPOOL_BOOT__ = { to: url.href };
100
+ load(boot, url.href);
101
+ }
102
+ function onClick(event) {
103
+ const link = event.target?.closest?.('a[href]');
104
+ if (!link || event.button || link.target)
105
+ return;
106
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
107
+ return;
108
+ if (link.hasAttribute('download'))
109
+ return;
110
+ take(event, new URL(link.href));
111
+ }
112
+ function onSubmit(event) {
113
+ const form = event.target;
114
+ if (form.target)
115
+ return;
116
+ if ((form.getAttribute('method') ?? 'get').toLowerCase() !== 'get')
117
+ return;
118
+ const url = new URL(form.getAttribute('action') ?? '', location.href);
119
+ url.search = new URLSearchParams(new FormData(form)).toString();
120
+ take(event, url);
121
+ }
122
+ if (loaded) {
123
+ load(src);
124
+ }
125
+ else {
126
+ document.addEventListener('click', onClick);
127
+ document.addEventListener('submit', onSubmit);
128
+ // a ring with no boot script has no pack to wait for, so its runtime loads from the second view;
129
+ // one that names a boot script waits for a click, or for the third view, which registers the worker
130
+ // unless the page has none to register or one already controls it
131
+ if (view > 1) {
132
+ addEventListener('DOMContentLoaded', () => {
133
+ if (loaded)
134
+ return;
135
+ const boot = bootOf();
136
+ if (!boot)
137
+ return load(dataset['src'] ?? '');
138
+ if (view < 3 || dataset['spoolWorker'] === 'never')
139
+ return;
140
+ if (dataset['spoolWorker'] !== 'always' && engineOf(navigator.userAgent) === 'webkit')
141
+ return;
142
+ if (navigator.serviceWorker?.controller)
143
+ return;
144
+ claim(boot);
145
+ load(boot);
146
+ });
147
+ }
148
+ }
@@ -1,4 +1,29 @@
1
+ import type { createActivity } from './activity.js';
2
+ import type { SpoolFetch } from './declared.js';
3
+ import type { SpoolClient } from './register.js';
1
4
  export type { Hello, Status } from '../sw/runtime.js';
2
5
  export * from './activity.js';
3
6
  export * from './lifecycle.js';
7
+ export { enableNavigation, type NavigateOptions } from './navigate.js';
4
8
  export * from './register.js';
9
+ declare global {
10
+ interface Window {
11
+ /** the page runtime, set once it loads; absent on a page without spool */
12
+ spool?: {
13
+ /** resolves to the client handle, or to null where service workers do not exist */
14
+ ready: Promise<SpoolClient | null>;
15
+ /** lets the page hand spool a pause and a resume for one of its loops */
16
+ activity: ReturnType<typeof createActivity>;
17
+ /** a fetch for a page without a worker; settles declared writes and passes other requests on */
18
+ fetch: SpoolFetch;
19
+ /** queues a value as the newest for a declared write class and key */
20
+ write: SpoolClient['write'];
21
+ /** sends every queued value now; call it before a logout navigation */
22
+ flush: SpoolClient['flush'];
23
+ /** the state of each queued value of the signed-in partition, without the values */
24
+ writes: SpoolClient['writes'];
25
+ /** settles a conflicted key with the local value or the server's */
26
+ resolve: SpoolClient['resolve'];
27
+ };
28
+ }
29
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './activity.js';
2
2
  export * from './lifecycle.js';
3
+ export { enableNavigation } from './navigate.js';
3
4
  export * from './register.js';
@@ -0,0 +1,66 @@
1
+ import type { LiveAck, LiveMessage, LiveState } from '../sw/runtime.js';
2
+ /** the part of `EventSource` the stream uses */
3
+ export type StreamSource = {
4
+ readonly readyState: number;
5
+ addEventListener(name: string, listener: (event: MessageEvent<string>) => void): void;
6
+ close(): void;
7
+ };
8
+ /** what {@link startLive} needs from the page and the worker */
9
+ export type LiveDeps = {
10
+ /** asks the worker for the partition held, the cursor to start from and whether the site has a stream */
11
+ state(): Promise<LiveState>;
12
+ /** tells the worker what the stream delivered; undefined when the worker did not answer */
13
+ send(message: LiveMessage): Promise<LiveAck | undefined>;
14
+ visible(): boolean;
15
+ /** calls `fn` when the page becomes visible or hidden, or is shown again from the back/forward cache */
16
+ onVisibility(fn: () => void): void;
17
+ /** calls `fn` when the document is going away */
18
+ onPageHide(fn: () => void): void;
19
+ /** `navigator.locks`; without it no stream opens, since two tabs would each hold one */
20
+ locks: Pick<LockManager, 'request'> | undefined;
21
+ /** `socket` is true when the site's hub accepts a WebSocket upgrade at the same URL */
22
+ open(url: string, socket?: boolean): StreamSource;
23
+ };
24
+ /** the lock the tab holding the stream owns; every tab of the origin asks for the same name */
25
+ export declare const LIVE_LOCK = "spool-live";
26
+ /**
27
+ * Holds one stream per origin while a tab is visible. Tabs queue on a Web Lock and only the holder
28
+ * connects; a tab that is hidden or leaves gives the lock up and the next visible tab takes it, so
29
+ * the stream closes when no tab is visible. The worker is shared by every tab, so the holder alone
30
+ * tells it what the stream read and no tab-to-tab channel is needed. A browser without Web Locks or
31
+ * `EventSource`, a stream that fails, or a site with no stream leaves the page on the renewals it
32
+ * always made. `reconcile` reopens the stream for the partition the worker holds now. Where the site
33
+ * sets `mode: 'adaptive'` (the default) nothing opens until `arm`, which the worker calls for at the
34
+ * second lease renewal of a visible session; hiding the tab disarms it.
35
+ */
36
+ export declare function startLive(deps: LiveDeps): {
37
+ reconcile(): void;
38
+ arm(): void;
39
+ };
40
+ /** the part of `WebSocket` {@link socketSource} uses */
41
+ export type SocketWire = {
42
+ readonly readyState: number;
43
+ addEventListener(name: string, listener: (event: {
44
+ data: unknown;
45
+ }) => void): void;
46
+ send(text: string): void;
47
+ close(): void;
48
+ };
49
+ /** how {@link socketSource} makes its transports; `events` is the SSE fallback */
50
+ export type SocketMakers = {
51
+ socket(url: string): SocketWire;
52
+ events(url: string): StreamSource;
53
+ };
54
+ /**
55
+ * A {@link StreamSource} over a WebSocket. Each message is one SSE frame in text form, so the
56
+ * listeners see what an `EventSource` would give them. The page sends `ping` every 25 seconds and
57
+ * the server answers with a `lease` frame. A socket the server closes after it opened is opened
58
+ * again after three seconds. If the upgrade fails before the socket opens, the same URL opens as
59
+ * SSE and stays SSE, which keeps a site served by a hub without sockets working.
60
+ */
61
+ export declare function socketSource(url: string, make: SocketMakers): StreamSource;
62
+ /** the live deps for a page with a worker; `client` is what `register()` returned */
63
+ export declare function browserLiveDeps(client: {
64
+ liveState(): Promise<LiveState>;
65
+ liveEvent(message: LiveMessage): Promise<LiveAck | undefined>;
66
+ }): LiveDeps | null;
@@ -0,0 +1,225 @@
1
+ import { LIVE_PATH, LIVE_PING } from '../protocol/config.js';
2
+ import { parseLiveDelta } from '../protocol/envelope.js';
3
+ /** the lock the tab holding the stream owns; every tab of the origin asks for the same name */
4
+ export const LIVE_LOCK = 'spool-live';
5
+ const CLOSED = 2;
6
+ function read(text, parse) {
7
+ try {
8
+ return parse(JSON.parse(text));
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
14
+ /**
15
+ * Holds one stream per origin while a tab is visible. Tabs queue on a Web Lock and only the holder
16
+ * connects; a tab that is hidden or leaves gives the lock up and the next visible tab takes it, so
17
+ * the stream closes when no tab is visible. The worker is shared by every tab, so the holder alone
18
+ * tells it what the stream read and no tab-to-tab channel is needed. A browser without Web Locks or
19
+ * `EventSource`, a stream that fails, or a site with no stream leaves the page on the renewals it
20
+ * always made. `reconcile` reopens the stream for the partition the worker holds now. Where the site
21
+ * sets `mode: 'adaptive'` (the default) nothing opens until `arm`, which the worker calls for at the
22
+ * second lease renewal of a visible session; hiding the tab disarms it.
23
+ */
24
+ export function startLive(deps) {
25
+ let held;
26
+ let armed = false;
27
+ let waiting;
28
+ let revoked = null;
29
+ function drop() {
30
+ waiting?.abort();
31
+ waiting = undefined;
32
+ held?.release();
33
+ }
34
+ function want() {
35
+ if (held || waiting || !deps.visible() || !deps.locks)
36
+ return;
37
+ const queue = new AbortController();
38
+ waiting = queue;
39
+ deps.locks
40
+ .request(LIVE_LOCK, { signal: queue.signal }, () => hold(queue))
41
+ .catch(() => undefined)
42
+ .finally(() => {
43
+ if (waiting === queue)
44
+ waiting = undefined;
45
+ });
46
+ }
47
+ async function hold(queue) {
48
+ if (waiting === queue)
49
+ waiting = undefined;
50
+ if (queue.signal.aborted)
51
+ return;
52
+ const state = await deps.state().catch(() => undefined);
53
+ if (!state?.live || !deps.visible())
54
+ return;
55
+ // adaptive: wait for the worker to ask; a visible session starts its renewal count at zero
56
+ if (state.live.mode === 'adaptive' && !armed) {
57
+ void deps.send({ partition: null, event: 'session' });
58
+ return;
59
+ }
60
+ const { partition, have } = state;
61
+ // a worker that kept a partition the server called revoked would loop here
62
+ if (partition !== revoked)
63
+ revoked = null;
64
+ if (partition === null ? !state.live.public : partition === revoked)
65
+ return;
66
+ await new Promise((done) => {
67
+ const query = [
68
+ ...(partition === null ? [] : [`partition=${encodeURIComponent(partition)}`]),
69
+ ...(have === null ? [] : [`have=${have}`])
70
+ ].join('&');
71
+ const source = deps.open(`${LIVE_PATH}${query ? `?${query}` : ''}`, state.live?.socket === true);
72
+ let again = false;
73
+ const release = () => {
74
+ source.close();
75
+ held = undefined;
76
+ done();
77
+ if (again)
78
+ want();
79
+ };
80
+ const reopen = () => {
81
+ again = true;
82
+ release();
83
+ };
84
+ held = { release, reopen };
85
+ source.addEventListener('delta', (event) => {
86
+ const delta = read(event.data, parseLiveDelta);
87
+ if (!delta)
88
+ return;
89
+ // a gap means a change went by unseen: connect again and catch up
90
+ void deps.send({ partition, event: 'delta', delta }).then((ack) => {
91
+ if (ack && !ack.ok)
92
+ reopen();
93
+ });
94
+ });
95
+ source.addEventListener('lease', (event) => {
96
+ const leaseMs = read(event.data, (v) => v.leaseMs);
97
+ if (typeof leaseMs === 'number')
98
+ void deps.send({ partition, event: 'lease', leaseMs });
99
+ });
100
+ source.addEventListener('revoked', () => {
101
+ revoked = partition;
102
+ void deps.send({ partition, event: 'revoked' }).finally(reopen);
103
+ });
104
+ // the browser reconnects on its own until it gives up; once it has, the renewals take over
105
+ source.addEventListener('error', () => {
106
+ if (source.readyState === CLOSED)
107
+ release();
108
+ });
109
+ });
110
+ }
111
+ function leave() {
112
+ armed = false;
113
+ drop();
114
+ }
115
+ deps.onVisibility(() => (deps.visible() ? want() : leave()));
116
+ deps.onPageHide(leave);
117
+ want();
118
+ return {
119
+ reconcile: () => (held ? held.reopen() : want()),
120
+ arm() {
121
+ armed = true;
122
+ want();
123
+ }
124
+ };
125
+ }
126
+ /** milliseconds between pings; each is answered with a `lease` frame and doubles as the keepalive */
127
+ const PING_MS = 25_000;
128
+ /** how long after the server closes an open socket the page connects again, as `EventSource` does */
129
+ const RETRY_MS = 3000;
130
+ /**
131
+ * A {@link StreamSource} over a WebSocket. Each message is one SSE frame in text form, so the
132
+ * listeners see what an `EventSource` would give them. The page sends `ping` every 25 seconds and
133
+ * the server answers with a `lease` frame. A socket the server closes after it opened is opened
134
+ * again after three seconds. If the upgrade fails before the socket opens, the same URL opens as
135
+ * SSE and stays SSE, which keeps a site served by a hub without sockets working.
136
+ */
137
+ export function socketSource(url, make) {
138
+ const listeners = new Map();
139
+ let wire;
140
+ let fallback;
141
+ let retry;
142
+ let ping;
143
+ let closed = false;
144
+ function connect() {
145
+ const own = make.socket(url);
146
+ wire = own;
147
+ let opened = false;
148
+ own.addEventListener('open', () => {
149
+ opened = true;
150
+ ping = setInterval(() => own.send(LIVE_PING), PING_MS);
151
+ });
152
+ own.addEventListener('message', (event) => {
153
+ if (typeof event.data !== 'string')
154
+ return;
155
+ const name = /^event: (.*)$/m.exec(event.data)?.[1];
156
+ const data = /^data: (.*)$/m.exec(event.data)?.[1];
157
+ if (name === undefined || data === undefined)
158
+ return;
159
+ for (const fn of listeners.get(name) ?? [])
160
+ fn({ data });
161
+ });
162
+ own.addEventListener('close', () => {
163
+ clearInterval(ping);
164
+ if (closed || wire !== own)
165
+ return;
166
+ if (!opened)
167
+ return fall();
168
+ retry = setTimeout(connect, RETRY_MS);
169
+ });
170
+ }
171
+ function fall() {
172
+ wire = undefined;
173
+ fallback = make.events(url);
174
+ for (const [name, fns] of listeners)
175
+ for (const fn of fns)
176
+ fallback.addEventListener(name, fn);
177
+ }
178
+ connect();
179
+ return {
180
+ get readyState() {
181
+ if (fallback)
182
+ return fallback.readyState;
183
+ if (closed)
184
+ return CLOSED;
185
+ return wire?.readyState === 1 ? 1 : 0;
186
+ },
187
+ addEventListener(name, listener) {
188
+ listeners.set(name, [...(listeners.get(name) ?? []), listener]);
189
+ fallback?.addEventListener(name, listener);
190
+ },
191
+ close() {
192
+ closed = true;
193
+ clearTimeout(retry);
194
+ clearInterval(ping);
195
+ wire?.close();
196
+ fallback?.close();
197
+ }
198
+ };
199
+ }
200
+ /** the live deps for a page with a worker; `client` is what `register()` returned */
201
+ export function browserLiveDeps(client) {
202
+ if (typeof EventSource === 'undefined')
203
+ return null;
204
+ return {
205
+ state: () => client.liveState(),
206
+ send: (message) => client.liveEvent(message),
207
+ visible: () => document.visibilityState === 'visible',
208
+ onVisibility: (fn) => {
209
+ document.addEventListener('visibilitychange', fn);
210
+ addEventListener('pageshow', fn);
211
+ },
212
+ onPageHide: (fn) => addEventListener('pagehide', fn),
213
+ locks: navigator.locks,
214
+ open: (url, socket) => socket && typeof WebSocket !== 'undefined'
215
+ ? socketSource(url, {
216
+ socket: (path) => {
217
+ const target = new URL(path, location.href);
218
+ target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
219
+ return new WebSocket(target);
220
+ },
221
+ events: (path) => new EventSource(path)
222
+ })
223
+ : new EventSource(url)
224
+ };
225
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { enableNavigation } from './navigate.js';
2
+ globalThis.spoolNavigate = {
3
+ enableNavigation
4
+ };
@@ -0,0 +1,54 @@
1
+ import type { CompiledTemplate } from '../protocol/template/compile.js';
2
+ import type { PackStore } from '../sw/pack/store.js';
3
+ import { type Renderers } from '../sw/render.js';
4
+ /** what a page renders its held routes with */
5
+ export type NavigateOptions = {
6
+ /** the compiled templates the page renders with, keyed by route pattern */
7
+ templates?: Record<string, CompiledTemplate>;
8
+ /** the page runtime's script tag, so a local page carries the tag the server injects */
9
+ clientTag?: string;
10
+ /** custom renderers keyed by route pattern, as the worker's `serve` takes them */
11
+ renderers?: Renderers;
12
+ /** the pack store the page reads, the `spool-bundle` database the entry opens */
13
+ store: PackStore;
14
+ };
15
+ /**
16
+ * The page's view of its held routes. `offers` answers at once from the routes it loaded; `render`
17
+ * reads the row or rows and returns the HTML, or null when the network must answer.
18
+ *
19
+ * @internal
20
+ */
21
+ export declare function createNavigator(options: NavigateOptions): {
22
+ ready: Promise<void | undefined>;
23
+ offers(url: URL): boolean;
24
+ render(url: URL): Promise<string | null>;
25
+ };
26
+ /**
27
+ * Budgets the history entries of in-page moves. `take` reserves one entry before the page renders,
28
+ * so a click past {@link HISTORY_BUDGET} in a 10 second window is left to the browser as a document
29
+ * navigation. `push` writes the entry once the new content is in place.
30
+ *
31
+ * @internal
32
+ */
33
+ export declare function createHistoryWriter(history: Pick<History, 'pushState'>, now?: () => number): {
34
+ take(): boolean;
35
+ push(url: string): void;
36
+ };
37
+ /**
38
+ * Answers same-origin link clicks, GET form submits and history moves to held routes from the
39
+ * page, with no request. Anything the held rows cannot answer goes to the browser as it would
40
+ * have. Dispatches `spool:navigated` on `window` after each local swap. Resolves `ready` once the
41
+ * routes are loaded; until then nothing is intercepted. `go` moves to `url` as a click would, and
42
+ * loads it as a document when the held rows cannot answer.
43
+ */
44
+ export declare function enableNavigation(options: NavigateOptions): {
45
+ ready: Promise<void>;
46
+ go(url: URL): void;
47
+ stop(): void;
48
+ };
49
+ /**
50
+ * The first difference between the page this device renders for `href` and the network's
51
+ * document for it, or null when they match after normalisation. A URL the device cannot answer
52
+ * is a difference too.
53
+ */
54
+ export declare function compareToDocument(href: string, options: NavigateOptions): Promise<string | null>;