@drupflare/spool 0.0.0-stage โ†’ 0.2.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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1749 -2
  3. package/dist/cdn/client.js +1 -0
  4. package/dist/cdn/location.d.ts +11 -0
  5. package/dist/cdn/location.js +15 -0
  6. package/dist/cdn/manifest.json +16 -0
  7. package/dist/cdn/spool-sw.js +1 -0
  8. package/dist/client/entry.d.ts +1 -0
  9. package/dist/client/entry.js +25 -0
  10. package/dist/client/index.d.ts +3 -0
  11. package/dist/client/index.js +2 -0
  12. package/dist/client/lifecycle.d.ts +10 -0
  13. package/dist/client/lifecycle.js +10 -0
  14. package/dist/client/loads.d.ts +16 -0
  15. package/dist/client/loads.js +41 -0
  16. package/dist/client/register.d.ts +34 -0
  17. package/dist/client/register.js +58 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +2 -0
  20. package/dist/media/embeds.d.ts +59 -0
  21. package/dist/media/embeds.js +120 -0
  22. package/dist/media/headers.d.ts +13 -0
  23. package/dist/media/headers.js +44 -0
  24. package/dist/media/html.d.ts +27 -0
  25. package/dist/media/html.js +93 -0
  26. package/dist/media/image.d.ts +222 -0
  27. package/dist/media/image.js +413 -0
  28. package/dist/media/index.d.ts +6 -0
  29. package/dist/media/index.js +6 -0
  30. package/dist/media/lazy.d.ts +26 -0
  31. package/dist/media/lazy.js +74 -0
  32. package/dist/media/responsive.d.ts +45 -0
  33. package/dist/media/responsive.js +98 -0
  34. package/dist/media/video.d.ts +30 -0
  35. package/dist/media/video.js +75 -0
  36. package/dist/node/listener.d.ts +19 -0
  37. package/dist/node/listener.js +76 -0
  38. package/dist/protocol/artifact.d.ts +54 -0
  39. package/dist/protocol/artifact.js +79 -0
  40. package/dist/protocol/assembly.d.ts +34 -0
  41. package/dist/protocol/assembly.js +72 -0
  42. package/dist/protocol/beacon.d.ts +59 -0
  43. package/dist/protocol/beacon.js +86 -0
  44. package/dist/protocol/collector.d.ts +41 -0
  45. package/dist/protocol/collector.js +84 -0
  46. package/dist/protocol/config.d.ts +89 -0
  47. package/dist/protocol/config.js +13 -0
  48. package/dist/protocol/envelope.d.ts +47 -0
  49. package/dist/protocol/envelope.js +162 -0
  50. package/dist/protocol/errors.d.ts +7 -0
  51. package/dist/protocol/errors.js +9 -0
  52. package/dist/protocol/graph.d.ts +81 -0
  53. package/dist/protocol/graph.js +201 -0
  54. package/dist/protocol/index.d.ts +19 -0
  55. package/dist/protocol/index.js +19 -0
  56. package/dist/protocol/manifest.d.ts +29 -0
  57. package/dist/protocol/manifest.js +94 -0
  58. package/dist/protocol/normalise.d.ts +20 -0
  59. package/dist/protocol/normalise.js +29 -0
  60. package/dist/protocol/pattern.d.ts +12 -0
  61. package/dist/protocol/pattern.js +82 -0
  62. package/dist/protocol/provision.d.ts +100 -0
  63. package/dist/protocol/provision.js +105 -0
  64. package/dist/protocol/route.d.ts +179 -0
  65. package/dist/protocol/route.js +135 -0
  66. package/dist/protocol/sync.d.ts +31 -0
  67. package/dist/protocol/sync.js +87 -0
  68. package/dist/protocol/tag.d.ts +12 -0
  69. package/dist/protocol/tag.js +26 -0
  70. package/dist/protocol/template/compile.d.ts +35 -0
  71. package/dist/protocol/template/compile.js +82 -0
  72. package/dist/protocol/template/interpret.d.ts +9 -0
  73. package/dist/protocol/template/interpret.js +82 -0
  74. package/dist/protocol/vector.d.ts +32 -0
  75. package/dist/protocol/vector.js +56 -0
  76. package/dist/protocol/view.d.ts +110 -0
  77. package/dist/protocol/view.js +201 -0
  78. package/dist/proxy/dictionary.d.ts +58 -0
  79. package/dist/proxy/dictionary.js +197 -0
  80. package/dist/proxy/eligible.d.ts +45 -0
  81. package/dist/proxy/eligible.js +96 -0
  82. package/dist/proxy/index.d.ts +5 -0
  83. package/dist/proxy/index.js +5 -0
  84. package/dist/proxy/proxy.d.ts +133 -0
  85. package/dist/proxy/proxy.js +507 -0
  86. package/dist/proxy/purge.d.ts +10 -0
  87. package/dist/proxy/purge.js +66 -0
  88. package/dist/proxy/tags.d.ts +8 -0
  89. package/dist/proxy/tags.js +36 -0
  90. package/dist/report/derive.d.ts +223 -0
  91. package/dist/report/derive.js +494 -0
  92. package/dist/report/economics.d.ts +14 -0
  93. package/dist/report/economics.js +24 -0
  94. package/dist/report/index.d.ts +9 -0
  95. package/dist/report/index.js +9 -0
  96. package/dist/report/inputs.d.ts +141 -0
  97. package/dist/report/inputs.js +216 -0
  98. package/dist/report/ledger.d.ts +169 -0
  99. package/dist/report/ledger.js +278 -0
  100. package/dist/report/measurement.d.ts +48 -0
  101. package/dist/report/measurement.js +117 -0
  102. package/dist/report/model.d.ts +42 -0
  103. package/dist/report/model.js +74 -0
  104. package/dist/report/thirdparty.d.ts +62 -0
  105. package/dist/report/thirdparty.js +107 -0
  106. package/dist/report/traffic.d.ts +140 -0
  107. package/dist/report/traffic.js +228 -0
  108. package/dist/report/trim.d.ts +81 -0
  109. package/dist/report/trim.js +105 -0
  110. package/dist/server/beacon.d.ts +20 -0
  111. package/dist/server/beacon.js +47 -0
  112. package/dist/server/embedded.d.ts +6 -0
  113. package/dist/server/embedded.js +6 -0
  114. package/dist/server/ga4.d.ts +70 -0
  115. package/dist/server/ga4.js +165 -0
  116. package/dist/server/identity.d.ts +12 -0
  117. package/dist/server/identity.js +17 -0
  118. package/dist/server/index.d.ts +7 -0
  119. package/dist/server/index.js +7 -0
  120. package/dist/server/sink.d.ts +56 -0
  121. package/dist/server/sink.js +133 -0
  122. package/dist/server/size.d.ts +7 -0
  123. package/dist/server/size.js +18 -0
  124. package/dist/server/spool.d.ts +97 -0
  125. package/dist/server/spool.js +463 -0
  126. package/dist/server/stub.d.ts +9 -0
  127. package/dist/server/stub.js +19 -0
  128. package/dist/server/sync.d.ts +12 -0
  129. package/dist/server/sync.js +48 -0
  130. package/dist/server/work.d.ts +22 -0
  131. package/dist/server/work.js +30 -0
  132. package/dist/stores/durable-object.d.ts +19 -0
  133. package/dist/stores/durable-object.js +53 -0
  134. package/dist/stores/index.d.ts +2 -0
  135. package/dist/stores/index.js +2 -0
  136. package/dist/stores/memory.d.ts +4 -0
  137. package/dist/stores/memory.js +10 -0
  138. package/dist/stores/version-store.d.ts +11 -0
  139. package/dist/stores/version-store.js +1 -0
  140. package/dist/sw/analytics.d.ts +81 -0
  141. package/dist/sw/analytics.js +275 -0
  142. package/dist/sw/collect.d.ts +8 -0
  143. package/dist/sw/collect.js +33 -0
  144. package/dist/sw/core.d.ts +1 -0
  145. package/dist/sw/core.js +3 -0
  146. package/dist/sw/freshness.d.ts +15 -0
  147. package/dist/sw/freshness.js +20 -0
  148. package/dist/sw/graph/index.d.ts +67 -0
  149. package/dist/sw/graph/index.js +170 -0
  150. package/dist/sw/graph/invalidate.d.ts +23 -0
  151. package/dist/sw/graph/invalidate.js +109 -0
  152. package/dist/sw/graph/projections.d.ts +7 -0
  153. package/dist/sw/graph/projections.js +9 -0
  154. package/dist/sw/graph/records.d.ts +7 -0
  155. package/dist/sw/graph/records.js +9 -0
  156. package/dist/sw/graph/store.d.ts +32 -0
  157. package/dist/sw/graph/store.js +52 -0
  158. package/dist/sw/idb.d.ts +8 -0
  159. package/dist/sw/idb.js +117 -0
  160. package/dist/sw/index.d.ts +2 -0
  161. package/dist/sw/index.js +1 -0
  162. package/dist/sw/partition.d.ts +21 -0
  163. package/dist/sw/partition.js +137 -0
  164. package/dist/sw/policy.d.ts +8 -0
  165. package/dist/sw/policy.js +24 -0
  166. package/dist/sw/provision.d.ts +39 -0
  167. package/dist/sw/provision.js +61 -0
  168. package/dist/sw/render.d.ts +21 -0
  169. package/dist/sw/render.js +53 -0
  170. package/dist/sw/replica.d.ts +77 -0
  171. package/dist/sw/replica.js +299 -0
  172. package/dist/sw/router.d.ts +42 -0
  173. package/dist/sw/router.js +48 -0
  174. package/dist/sw/routing.d.ts +23 -0
  175. package/dist/sw/routing.js +48 -0
  176. package/dist/sw/runtime.d.ts +112 -0
  177. package/dist/sw/runtime.js +1070 -0
  178. package/dist/sw/scheduler.d.ts +83 -0
  179. package/dist/sw/scheduler.js +149 -0
  180. package/dist/sw/seal.d.ts +37 -0
  181. package/dist/sw/seal.js +183 -0
  182. package/dist/sw/serve.d.ts +15 -0
  183. package/dist/sw/serve.js +63 -0
  184. package/dist/sw/shadow.d.ts +16 -0
  185. package/dist/sw/shadow.js +27 -0
  186. package/dist/sw/static.d.ts +17 -0
  187. package/dist/sw/static.js +81 -0
  188. package/dist/sw/storage.d.ts +64 -0
  189. package/dist/sw/storage.js +34 -0
  190. package/dist/sw/thirdparty.d.ts +17 -0
  191. package/dist/sw/thirdparty.js +36 -0
  192. package/dist/trim/css.d.ts +38 -0
  193. package/dist/trim/css.js +328 -0
  194. package/dist/trim/index.d.ts +3 -0
  195. package/dist/trim/index.js +3 -0
  196. package/dist/trim/manifest.d.ts +67 -0
  197. package/dist/trim/manifest.js +134 -0
  198. package/dist/trim/tokens.d.ts +47 -0
  199. package/dist/trim/tokens.js +142 -0
  200. package/dist/version.d.ts +2 -0
  201. package/dist/version.js +3 -0
  202. package/package.json +150 -5
package/README.md CHANGED
@@ -1,3 +1,1750 @@
1
- # Temporary Holding Version
1
+ # ๐Ÿงต spool
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > An incremental application replica for the browser
4
+
5
+ [![Build](https://github.com/drupflare/spool/actions/workflows/build.yml/badge.svg)](https://github.com/drupflare/spool/actions/workflows/build.yml)
6
+ [![Browser](https://github.com/drupflare/spool/actions/workflows/browser.yml/badge.svg)](https://github.com/drupflare/spool/actions/workflows/browser.yml)
7
+ [![Prettier](https://github.com/drupflare/spool/actions/workflows/prettier.yml/badge.svg)](https://github.com/drupflare/spool/actions/workflows/prettier.yml)
8
+ [![codecov](https://codecov.io/gh/drupflare/spool/branch/master/graph/badge.svg)](https://codecov.io/gh/drupflare/spool)
9
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10
+
11
+ spool keeps a replica of what a page needs on the visitor's device. The server sends templates
12
+ and authorised, versioned data. A service worker stores them and computes eligible pages on the
13
+ device, so a repeat view makes no request and costs the server no work.
14
+
15
+ It runs on any runtime that speaks `Request` and `Response`, bridges `node:http` for the rest, and
16
+ has no runtime dependencies. A site with no server code can load it from two files and a manifest.
17
+
18
+ ---
19
+
20
+ ## ๐Ÿ“‹ Table of Contents
21
+
22
+ - [Why Spool](#-why-spool)
23
+ - [Install](#-install)
24
+ - [Quick Start](#-quick-start)
25
+ - [Page Runtime](#-page-runtime)
26
+ - [Runtimes](#-runtimes)
27
+ - [Compatibility](#-compatibility)
28
+ - [Static Sites](#-static-sites)
29
+ - [Strategies](#-strategies)
30
+ - [Freshness Contracts](#-freshness-contracts)
31
+ - [Authenticated Data](#-authenticated-data)
32
+ - [Catalogue](#-catalogue)
33
+ - [Analytics Batching](#-analytics-batching)
34
+ - [Third-Party Files](#-third-party-files)
35
+ - [Subresource Handling](#-subresource-handling)
36
+ - [Shadow Mode](#-shadow-mode)
37
+ - [Proxy Mode](#-proxy-mode)
38
+ - [Trimmed Stylesheets](#-trimmed-stylesheets)
39
+ - [Images and Video](#-images-and-video)
40
+ - [Out of Scope](#-out-of-scope)
41
+ - [Browser Support](#-browser-support)
42
+ - [Subpath Exports](#-subpath-exports)
43
+ - [Testing](#-testing)
44
+ - [Related Repositories](#-related-repositories)
45
+ - [License](#-license)
46
+
47
+ ---
48
+
49
+ ## ๐ŸŽฏ Why Spool
50
+
51
+ A response is a deterministic transformation of a set of authorised, versioned dependencies. The
52
+ server half names those dependencies and sends the snapshot the visitor may hold. The worker keeps
53
+ a graph of records, projections and responses, with their versions, and syncs only what the next
54
+ page needs.
55
+
56
+ Your application keeps every write, every access decision and every page it cannot reproduce
57
+ safely on the device. A route the worker cannot answer goes to the network, so adopting spool
58
+ changes no page that was not declared.
59
+
60
+ [docs/impact.md](docs/impact.md) holds the energy model and the measurements behind it.
61
+
62
+ ---
63
+
64
+ ## ๐Ÿ“ฅ Install
65
+
66
+ ### Package
67
+
68
+ ```sh
69
+ bun add @drupflare/spool
70
+ ```
71
+
72
+ The package ships ES modules and type declarations. Node, Deno, Bun, Workers and bundlers import
73
+ it directly.
74
+
75
+ ### CDN Script
76
+
77
+ A page can load the runtime from `cdn.drupflare.com` with a Subresource Integrity hash. The release
78
+ notes list the hash for each version.
79
+
80
+ ```html
81
+ <script
82
+ src="https://cdn.drupflare.com/spool/<version>/client.js"
83
+ integrity="sha384-<hash from the release notes>"
84
+ crossorigin="anonymous"
85
+ defer
86
+ data-spool-client
87
+ ></script>
88
+ ```
89
+
90
+ [Page Runtime](#-page-runtime) shows how `createSpool` injects the same tag.
91
+
92
+ ### Direct Files
93
+
94
+ `spool-sw.js`, `client.js` and `manifest.json` are attached to every GitHub release and published
95
+ under `https://cdn.drupflare.com/spool/<version>/`. A site that serves them as plain files needs no
96
+ server library. See [Static Sites](#-static-sites).
97
+
98
+ ---
99
+
100
+ ## ๐Ÿš€ Quick Start
101
+
102
+ Every runtime below makes the same three moves:
103
+
104
+ 1. Declare the routes the device may answer, and the version store that tracks changes.
105
+ 2. Wrap the application's handler with `spool.handle`. It answers `/.spool/*` and `/spool-sw.js`.
106
+ 3. Send the client tag, which is the script tag for the page runtime. `handle` injects it into
107
+ every HTML page the application returns, and `spool.decorate` does the same where there is no
108
+ Fetch response to wrap.
109
+
110
+ ### Declare Routes
111
+
112
+ A route has a path pattern, a strategy, the tags it depends on and a `load` function that returns
113
+ the data for one page. `load` runs on the server and may check the visitor's identity. Only its
114
+ result reaches the device.
115
+
116
+ ```ts
117
+ import { defineRoute } from '@drupflare/spool/server';
118
+
119
+ export const routes = [
120
+ defineRoute('/node/:id', {
121
+ strategy: 'template',
122
+ template: {
123
+ source:
124
+ '<!doctype html><html><head><title>Node {{id}}</title></head><body><h1>Node {{id}}</h1></body></html>'
125
+ },
126
+ depends: (ctx) => [`node:${ctx.params['id']}`],
127
+ load: (ctx) => ({ id: ctx.params['id'] })
128
+ })
129
+ ];
130
+
131
+ const escape = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
132
+
133
+ export const page = (request: Request) => {
134
+ const id = escape(new URL(request.url).pathname.split('/')[2] ?? '');
135
+ return new Response(
136
+ `<!doctype html><html><head><title>Node ${id}</title></head><body><h1>Node ${id}</h1></body></html>`,
137
+ { headers: { 'content-type': 'text/html; charset=utf-8' } }
138
+ );
139
+ };
140
+ ```
141
+
142
+ `page` stands in for your application. The page it returns has to match what the template
143
+ renders from the route's data, because the device renders the same route without asking you.
144
+
145
+ The version store records which tags changed. `memoryStore` serves a single process. Every other
146
+ deployment needs a store that all instances share, which is any object with three methods:
147
+ `bump(tags)`, `cursor()` and `diff(from)`. On Cloudflare, `durableObjectStore` keeps the vector in
148
+ a Durable Object.
149
+
150
+ ```ts
151
+ import { memoryStore } from '@drupflare/spool/stores';
152
+
153
+ export const store = memoryStore();
154
+ ```
155
+
156
+ `createSpool` joins the two:
157
+
158
+ ```ts
159
+ import { createSpool } from '@drupflare/spool/server';
160
+ import { routes } from './routes';
161
+ import { store } from './store';
162
+
163
+ export const spool = createSpool({ routes, store });
164
+ ```
165
+
166
+ After a write, call `await spool.invalidate(['node:1'])` with the tags it touched. Devices
167
+ holding a page that depends on them fetch a fresh copy before they show it again.
168
+
169
+ ---
170
+
171
+ ## ๐Ÿ“ฆ Page Runtime
172
+
173
+ `handle` and `decorate` inject one script tag into each HTML page. By default the script is
174
+ served from the same origin at `/.spool/<version>/client.js`, which suits a strict
175
+ `script-src 'self'` policy. To serve it from `cdn.drupflare.com` instead, pass the integrity hash
176
+ that the release notes list for your version. The URL defaults to that version's file.
177
+
178
+ ```ts
179
+ import { createSpool } from '@drupflare/spool/server';
180
+ import { memoryStore } from '@drupflare/spool/stores';
181
+ import { routes } from './routes';
182
+
183
+ export const spool = createSpool({
184
+ routes,
185
+ store: memoryStore(),
186
+ cdn: { integrity: 'sha384-<hash from the release notes>' }
187
+ });
188
+ ```
189
+
190
+ The CDN copy carries `Cache-Control: public, max-age=31536000, immutable` and the browser checks
191
+ it against the hash, so a changed file never runs. Release files are never overwritten. If the
192
+ script fails to load, the page works as it did before.
193
+
194
+ The script registers `/spool-sw.js` and exposes `window.spool.ready`, which resolves to the client
195
+ handle or to `null` where service workers do not exist. To bundle the runtime yourself, import
196
+ `register` from `@drupflare/spool/client`.
197
+
198
+ ---
199
+
200
+ ## ๐Ÿงฉ Runtimes
201
+
202
+ Each example uses the `routes`, `page` and `spool` from [Quick Start](#-quick-start). The
203
+ [compatibility table](#-compatibility) lists what each framework hands a handler.
204
+
205
+ ### Cloudflare Workers
206
+
207
+ Bind the Durable Object that holds the version vector, then pass its namespace to
208
+ `durableObjectStore`.
209
+
210
+ ```jsonc
211
+ {
212
+ "durable_objects": { "bindings": [{ "name": "SPOOL_VERSIONS", "class_name": "SpoolVersions" }] },
213
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["SpoolVersions"] }]
214
+ }
215
+ ```
216
+
217
+ ```ts
218
+ import { createSpool } from '@drupflare/spool/server';
219
+ import { durableObjectStore } from '@drupflare/spool/stores/durable-object';
220
+ import { page, routes } from './routes';
221
+
222
+ export { SpoolVersions } from '@drupflare/spool/stores/durable-object';
223
+
224
+ export default {
225
+ fetch(request: Request, env: Cloudflare.Env) {
226
+ const spool = createSpool({ routes, store: durableObjectStore(env.SPOOL_VERSIONS) });
227
+ return spool.handle(request, page);
228
+ }
229
+ };
230
+ ```
231
+
232
+ ### Cloudflare Pages Functions
233
+
234
+ A function takes a context with the request and a `next` that runs the next function or the
235
+ static asset server.
236
+
237
+ ```ts
238
+ import { spool } from './spool';
239
+
240
+ export const onRequest = (context: { request: Request; next(): Promise<Response> }) =>
241
+ spool.handle(context.request, () => context.next());
242
+ ```
243
+
244
+ ### Hono
245
+
246
+ Hono ignores the response a middleware returns once a route has answered, so assign it to
247
+ `c.res`.
248
+
249
+ ```ts
250
+ import { Hono } from 'hono';
251
+ import { page } from './routes';
252
+ import { spool } from './spool';
253
+
254
+ const app = new Hono();
255
+
256
+ app.use('*', async (c, next) => {
257
+ c.res = await spool.handle(c.req.raw, async () => {
258
+ await next();
259
+ return c.res;
260
+ });
261
+ });
262
+ app.get('/node/:id', (c) => page(c.req.raw));
263
+
264
+ export default app;
265
+ ```
266
+
267
+ ### Elysia
268
+
269
+ `onRequest` answers the spool paths and returns nothing for the rest. The hook has to be an
270
+ `async` function, because Elysia does not await a promise that a plain function returns.
271
+
272
+ ```ts
273
+ import { Elysia } from 'elysia';
274
+ import { page } from './routes';
275
+ import { spool } from './spool';
276
+
277
+ export const app = new Elysia()
278
+ .onRequest(async ({ request }) => {
279
+ const { pathname } = new URL(request.url);
280
+ return pathname === '/spool-sw.js' ? spool.stub() : await spool.respond(request);
281
+ })
282
+ .get('/node/:id', ({ request }) => spool.decorate(request, page(request)));
283
+ ```
284
+
285
+ ### itty-router
286
+
287
+ A handler that returns `undefined` passes the request to the next one, which is what
288
+ `spool.respond` returns for a path that is not spool's.
289
+
290
+ ```ts
291
+ import { IttyRouter } from 'itty-router';
292
+ import { page } from './routes';
293
+ import { spool } from './spool';
294
+
295
+ const router = IttyRouter();
296
+
297
+ router
298
+ .all('*', (request) => spool.respond(request))
299
+ .get('/spool-sw.js', () => spool.stub())
300
+ .get('/node/:id', (request) => spool.decorate(request, page(request)));
301
+
302
+ export default { fetch: router.fetch };
303
+ ```
304
+
305
+ ### Bun
306
+
307
+ Bun serves a default export that has a `fetch` function.
308
+
309
+ ```ts
310
+ import { page } from './routes';
311
+ import { spool } from './spool';
312
+
313
+ export default {
314
+ port: 3000,
315
+ fetch: (request: Request) => spool.handle(request, page)
316
+ };
317
+ ```
318
+
319
+ ### Deno
320
+
321
+ Run it with `deno serve`.
322
+
323
+ ```ts
324
+ import { page } from './routes';
325
+ import { spool } from './spool';
326
+
327
+ export default {
328
+ fetch: (request: Request) => spool.handle(request, page)
329
+ };
330
+ ```
331
+
332
+ ### Netlify Functions
333
+
334
+ A function takes a `Request` and returns a `Response`. `config.path` sends the spool paths and the
335
+ pages to it.
336
+
337
+ ```ts
338
+ import type { Config, Context } from '@netlify/functions';
339
+ import { page } from './routes';
340
+ import { spool } from './spool';
341
+
342
+ export default (request: Request, context: Context) => spool.handle(request, page);
343
+
344
+ export const config: Config = { path: ['/node/*', '/spool-sw.js', '/.spool/*'] };
345
+ ```
346
+
347
+ ### Netlify Edge Functions
348
+
349
+ An edge function runs in front of the site. `context.next()` returns the response the site would
350
+ have sent, which `handle` decorates.
351
+
352
+ ```ts
353
+ import type { Config, Context } from '@netlify/edge-functions';
354
+ import { spool } from './spool';
355
+
356
+ export default (request: Request, context: Context) => spool.handle(request, () => context.next());
357
+
358
+ export const config: Config = { path: '/*' };
359
+ ```
360
+
361
+ ### Vercel Functions
362
+
363
+ A function under `api/` takes a default export with `fetch`. Send every path to it from
364
+ `vercel.json`, so the function sees `/.spool/*` and `/spool-sw.js` as well as the pages. Function
365
+ instances do not share memory, so `store` has to be a shared `VersionStore`.
366
+
367
+ ```json
368
+ { "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }
369
+ ```
370
+
371
+ ```ts
372
+ import { page } from './routes';
373
+ import { spool } from './spool';
374
+
375
+ export default {
376
+ fetch: (request: Request) => spool.handle(request, page)
377
+ };
378
+ ```
379
+
380
+ ### Next.js
381
+
382
+ Next.js route handlers return `Response` objects, so `handle` wraps one directly. The spool
383
+ endpoints and the worker script go through the proxy, which returns `undefined` for every other
384
+ request. Next.js 16 calls the file `proxy.ts` and the export `proxy`. Earlier versions call them
385
+ `middleware.ts` and `middleware`. The proxy and the route handlers need the same shared store.
386
+
387
+ ```ts
388
+ import { spool } from './spool';
389
+
390
+ export function proxy(request: Request) {
391
+ const { pathname } = new URL(request.url);
392
+ return pathname === '/spool-sw.js' ? spool.stub() : spool.respond(request);
393
+ }
394
+ ```
395
+
396
+ ```ts
397
+ import { page } from './routes';
398
+ import { spool } from './spool';
399
+
400
+ export const GET = (request: Request) => spool.handle(request, page);
401
+ ```
402
+
403
+ ### Nuxt and Nitro
404
+
405
+ h3 turns an event into a standard request with `toWebRequest`, and it sends a `Response` that a
406
+ handler returns. A server middleware that returns nothing passes the request on. Put the first
407
+ file in `server/middleware/` and the second in `server/routes/node/[id].ts`. Both share one store
408
+ from `./store`.
409
+
410
+ ```ts
411
+ import { defineEventHandler, toWebRequest } from 'h3';
412
+ import { spool } from './spool';
413
+
414
+ export default defineEventHandler((event) => {
415
+ const request = toWebRequest(event);
416
+ return new URL(request.url).pathname === '/spool-sw.js' ? spool.stub() : spool.respond(request);
417
+ });
418
+ ```
419
+
420
+ ```ts
421
+ import { defineEventHandler, toWebRequest } from 'h3';
422
+ import { page } from './routes';
423
+ import { spool } from './spool';
424
+
425
+ export default defineEventHandler((event) => spool.handle(toWebRequest(event), page));
426
+ ```
427
+
428
+ ### AWS Lambda
429
+
430
+ Lambda gives a function a JSON event and expects a JSON result, so spool needs an adapter. Hono's
431
+ `hono/aws-lambda` converts Function URL, API Gateway HTTP API and ALB events. Save the Hono app
432
+ above as `hono.ts` and wrap it.
433
+
434
+ ```ts
435
+ import { handle } from 'hono/aws-lambda';
436
+ import app from './hono';
437
+
438
+ export const handler = handle(app);
439
+ ```
440
+
441
+ ### Azure Functions
442
+
443
+ An Azure v4 HTTP function takes an `HttpRequest`, which follows the Fetch standard, and returns an
444
+ `HttpResponseInit`. Route every path to it with `{*path}`.
445
+
446
+ ```ts
447
+ import { app, type HttpRequest, type HttpResponseInit } from '@azure/functions';
448
+ import { page } from './routes';
449
+ import { spool } from './spool';
450
+
451
+ export async function handler(request: HttpRequest): Promise<HttpResponseInit> {
452
+ const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
453
+ const response = await spool.handle(
454
+ new Request(request.url, {
455
+ method: request.method,
456
+ headers: [...request.headers],
457
+ body: hasBody ? await request.arrayBuffer() : undefined
458
+ }),
459
+ page
460
+ );
461
+ return {
462
+ status: response.status,
463
+ headers: [...response.headers],
464
+ body: await response.arrayBuffer()
465
+ };
466
+ }
467
+
468
+ app.http('spool', {
469
+ route: '{*path}',
470
+ methods: ['GET', 'POST'],
471
+ authLevel: 'anonymous',
472
+ handler
473
+ });
474
+ ```
475
+
476
+ ### Node
477
+
478
+ `toNodeListener` turns a Fetch-style handler into a `node:http` listener. Its `toRequest` and
479
+ `writeResponse` parts are what the frameworks below use to cross between Node and Fetch.
480
+
481
+ ```ts
482
+ import { createServer } from 'node:http';
483
+ import { toNodeListener } from '@drupflare/spool/node';
484
+ import { page } from './routes';
485
+ import { spool } from './spool';
486
+
487
+ export const server = createServer(toNodeListener((request) => spool.handle(request, page)));
488
+ ```
489
+
490
+ ### Express
491
+
492
+ Express responds through its own `res`, so it has no Fetch response to wrap. `spool.respond`
493
+ answers `/.spool/*` and returns `undefined` for everything else, which sends the request on to the
494
+ next Express handler. A route passes its page through `spool.decorate` to get the envelope and the
495
+ script tag.
496
+
497
+ ```ts
498
+ import express from 'express';
499
+ import { toNodeListener, toRequest, writeResponse } from '@drupflare/spool/node';
500
+ import { page } from './routes';
501
+ import { spool } from './spool';
502
+
503
+ export const app = express();
504
+
505
+ app.use(toNodeListener((request) => spool.respond(request)));
506
+ app.get('/spool-sw.js', (req, res) => writeResponse(res, spool.stub()));
507
+ app.get('/node/:id', async (req, res) => {
508
+ const request = toRequest(req, res);
509
+ await writeResponse(res, await spool.decorate(request, page(request)));
510
+ });
511
+ ```
512
+
513
+ ### Fastify
514
+
515
+ Fastify's `reply.send` takes a Fetch `Response`. An `onRequest` hook answers the spool paths from
516
+ the raw request before Fastify reads the body.
517
+
518
+ ```ts
519
+ import Fastify from 'fastify';
520
+ import { toRequest } from '@drupflare/spool/node';
521
+ import { page } from './routes';
522
+ import { spool } from './spool';
523
+
524
+ export const app = Fastify();
525
+
526
+ app.addHook('onRequest', async (req, reply) => {
527
+ const response = await spool.respond(toRequest(req.raw, reply.raw));
528
+ if (response) return reply.send(response);
529
+ });
530
+ app.get('/spool-sw.js', (req, reply) => reply.send(spool.stub()));
531
+ app.get('/node/:id', async (req, reply) => {
532
+ const request = toRequest(req.raw, reply.raw);
533
+ return reply.send(await spool.decorate(request, page(request)));
534
+ });
535
+ ```
536
+
537
+ ### Koa
538
+
539
+ Koa exposes the Node objects as `ctx.req` and `ctx.res`. Setting `ctx.respond` to `false` stops
540
+ Koa from writing a second response.
541
+
542
+ ```ts
543
+ import Koa from 'koa';
544
+ import { toRequest, writeResponse } from '@drupflare/spool/node';
545
+ import { page } from './routes';
546
+ import { spool } from './spool';
547
+
548
+ export const app = new Koa();
549
+
550
+ app.use(async (ctx, next) => {
551
+ const request = toRequest(ctx.req, ctx.res);
552
+ const response = ctx.path === '/spool-sw.js' ? spool.stub() : await spool.respond(request);
553
+ if (!response) return next();
554
+ ctx.respond = false;
555
+ await writeResponse(ctx.res, response);
556
+ });
557
+ app.use(async (ctx) => {
558
+ if (!ctx.path.startsWith('/node/')) return;
559
+ const request = toRequest(ctx.req, ctx.res);
560
+ ctx.respond = false;
561
+ await writeResponse(ctx.res, await spool.decorate(request, page(request)));
562
+ });
563
+ ```
564
+
565
+ ### hapi
566
+
567
+ hapi keeps the Node objects at `request.raw`. Returning `h.abandon` tells it the response is
568
+ already written.
569
+
570
+ ```ts
571
+ import Hapi from '@hapi/hapi';
572
+ import { toRequest, writeResponse } from '@drupflare/spool/node';
573
+ import { page } from './routes';
574
+ import { spool } from './spool';
575
+
576
+ export const server = Hapi.server();
577
+
578
+ server.ext('onRequest', async (request, h) => {
579
+ const { req, res } = request.raw;
580
+ const spoolRequest = toRequest(req, res);
581
+ const response =
582
+ request.path === '/spool-sw.js' ? spool.stub() : await spool.respond(spoolRequest);
583
+ if (!response) return h.continue;
584
+ await writeResponse(res, response);
585
+ return h.abandon;
586
+ });
587
+ server.route({
588
+ method: 'GET',
589
+ path: '/node/{id}',
590
+ handler: async (request, h) => {
591
+ const { req, res } = request.raw;
592
+ const spoolRequest = toRequest(req, res);
593
+ await writeResponse(res, await spool.decorate(spoolRequest, page(spoolRequest)));
594
+ return h.abandon;
595
+ }
596
+ });
597
+ ```
598
+
599
+ ### NestJS
600
+
601
+ On the Express adapter, `app.use` takes spool's listener and a controller method that injects
602
+ `@Req()` and `@Res()` writes the page. The example needs `experimentalDecorators` in
603
+ `tsconfig.json`.
604
+
605
+ ```ts
606
+ import { Controller, Get, Module, Req, Res } from '@nestjs/common';
607
+ import { NestFactory } from '@nestjs/core';
608
+ import type { Request, Response } from 'express';
609
+ import 'reflect-metadata';
610
+ import { toNodeListener, toRequest, writeResponse } from '@drupflare/spool/node';
611
+ import { page } from './routes';
612
+ import { spool } from './spool';
613
+
614
+ @Controller()
615
+ class NodeController {
616
+ @Get('node/:id')
617
+ async show(@Req() req: Request, @Res() res: Response) {
618
+ const request = toRequest(req, res);
619
+ await writeResponse(res, await spool.decorate(request, page(request)));
620
+ }
621
+ }
622
+
623
+ @Module({ controllers: [NodeController] })
624
+ class AppModule {}
625
+
626
+ export async function bootstrap() {
627
+ const app = await NestFactory.create(AppModule, { logger: false });
628
+ app.use(toNodeListener((request) => spool.respond(request)));
629
+ app.use('/spool-sw.js', (req: Request, res: Response) => writeResponse(res, spool.stub()));
630
+ return app;
631
+ }
632
+ ```
633
+
634
+ ### Google Cloud Functions
635
+
636
+ The Functions Framework gives an HTTP function Express-style `req` and `res`, so the Node listener
637
+ fits as it is.
638
+
639
+ ```ts
640
+ import { http } from '@google-cloud/functions-framework';
641
+ import { toNodeListener } from '@drupflare/spool/node';
642
+ import { page } from './routes';
643
+ import { spool } from './spool';
644
+
645
+ http(
646
+ 'spool',
647
+ toNodeListener((request) => spool.handle(request, page))
648
+ );
649
+ ```
650
+
651
+ ---
652
+
653
+ ## ๐Ÿ“Š Compatibility
654
+
655
+ The gate column says how far each row is checked. **runs** means the fixture above drives the
656
+ framework's own package. **stand-in** means a fixture calls the platform's handler with a plain
657
+ object where the platform would pass its context. **not tested** means the adapter column comes
658
+ from the framework's documentation and nothing here has run it.
659
+
660
+ | Framework or host | What a handler receives | Spool entry | Gate |
661
+ | ------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------- |
662
+ | Express | Node `req`, `res` | `toNodeListener`, `respond`, `decorate` | runs |
663
+ | Fastify | Node `req.raw`, `reply.raw`; `reply.send` takes a `Response` | `toRequest`, `respond`, `decorate` | runs |
664
+ | Koa | Node `ctx.req`, `ctx.res` | `toRequest`, `writeResponse` | runs |
665
+ | hapi | Node `request.raw.req`, `request.raw.res` | `toRequest`, `writeResponse` | runs |
666
+ | NestJS, Express adapter | Node, through Express | `app.use` with `toNodeListener`; `toRequest` in a controller | runs |
667
+ | NestJS, Fastify adapter | Node, through Fastify | the Fastify entry | not tested |
668
+ | AdonisJS | Node at `ctx.request.request` and `ctx.response.response` | `toRequest`, `writeResponse` in a middleware | not tested |
669
+ | Hono | Fetch | `handle` | runs |
670
+ | Elysia | Fetch | `respond`, `decorate` | runs |
671
+ | itty-router | Fetch | `respond`, `decorate` | runs |
672
+ | Oak | Fetch, through `app.handle`; published on JSR only | `handle` | not tested |
673
+ | h3, Nitro, Nuxt | Fetch, through `toWebRequest` | `respond`, `handle` | runs |
674
+ | Analog | Nitro and h3 routes | as Nuxt | not tested |
675
+ | Next.js | Fetch | `respond` in the proxy, `handle` in the route | runs |
676
+ | SvelteKit | Fetch `event.request` in the `handle` hook | `handle(event.request, () => resolve(event))` | not tested |
677
+ | Astro | `context.request` in `onRequest(context, next)` | `handle(context.request, () => next())` | not tested |
678
+ | React Router v7, Remix | Fetch `request` in `handleRequest` and the server build | `handle` around the request handler | not tested |
679
+ | TanStack Start | Fetch, in the server entry's `fetch(request)` | `handle(request, () => handler.fetch(request))` | not tested |
680
+ | SolidStart | an event in `onRequest` that may return a `Response` | `respond` in the middleware | not tested |
681
+ | Qwik City | `requestEv` in `onRequest`; `send(Response)` | `respond` in the middleware | not tested |
682
+ | Cloudflare Workers | Fetch | `handle` | runs, in workerd |
683
+ | Cloudflare Pages Functions | Fetch, in `onRequest(context)` | `handle(request, () => context.next())` | stand-in |
684
+ | Netlify Functions | Fetch | `handle` | stand-in |
685
+ | Netlify Edge Functions | Fetch; returning `undefined` passes on | `handle(request, () => context.next())` | stand-in |
686
+ | Deno, Deno Deploy | Fetch, through `Deno.serve` or `deno serve` | `handle` | stand-in |
687
+ | Bun | Fetch | `handle` | runs, under `Bun.serve` |
688
+ | Vercel Functions | Fetch | `handle` | stand-in |
689
+ | AWS Lambda, Function URL or HTTP API | JSON event version 2.0 | `hono/aws-lambda` around a Hono app | stand-in event |
690
+ | AWS Lambda, API Gateway REST API | JSON event version 1.0 | `hono/aws-lambda` around a Hono app | not tested |
691
+ | Lambda@Edge | CloudFront event with header arrays | none; a converter to `Request` is needed | not tested |
692
+ | Fastly Compute | Fetch, through `event.request` in a `fetch` listener | `event.respondWith(spool.handle(event.request, next))` | not tested |
693
+ | Azure Functions v4 | `HttpRequest`, which follows Fetch; returns `HttpResponseInit` | convert, then `handle` | runs, with a real `HttpRequest` |
694
+ | Google Cloud Functions | Node `req`, `res` from the Functions Framework | `toNodeListener` | runs, on the Functions Framework test server |
695
+ | Google Cloud Run | any HTTP server on `PORT` | the Node example | not tested |
696
+
697
+ A host that serves static files and runs no code, such as an object store or a plain web server, uses
698
+ [Static Sites](#-static-sites).
699
+
700
+ ---
701
+
702
+ ## ๐Ÿงฑ Static Sites
703
+
704
+ A site with no spool server can still answer repeat views from the device. It serves three files
705
+ from one directory:
706
+
707
+ - `spool-sw.js`, the worker, from a release or `https://cdn.drupflare.com/spool/<version>/`.
708
+ - `client.js`, the page script, from the same place.
709
+ - `spool.json`, the list of files the worker may keep.
710
+
711
+ Each page loads the script with the tag from [CDN Script](#-install), or from the site's own copy.
712
+ The worker has no server to talk to, so it reads `spool.json` from the directory its own script
713
+ sits in.
714
+
715
+ ```json
716
+ {
717
+ "schema": 1,
718
+ "routes": [
719
+ {
720
+ "pattern": "/",
721
+ "strategy": "static",
722
+ "version": "sha256-<base64 digest of the page>",
723
+ "freshness": { "maxStale": 3600, "mode": "soft" }
724
+ },
725
+ { "pattern": "/about", "strategy": "static", "version": "sha256-<base64 digest of the page>" },
726
+ { "pattern": "/css/site.css", "strategy": "static", "version": "build-42" },
727
+ {
728
+ "pattern": "/client.js",
729
+ "strategy": "static",
730
+ "version": "sha384-<base64 digest of the file>"
731
+ }
732
+ ]
733
+ }
734
+ ```
735
+
736
+ A route names one path, or a `:name` pattern whose paths share one version. `version` says what
737
+ the file is now:
738
+
739
+ - A `sha256-`, `sha384-` or `sha512-` value is checked against the bytes the worker fetched. A
740
+ mismatch keeps nothing.
741
+ - An entity tag such as `"abc"` is checked against the response's `ETag`.
742
+ - Any other string is a label you change when the file changes.
743
+
744
+ The first view of a path goes to the network, and the worker keeps a copy of the response as it
745
+ arrives: the bytes and the headers, including any `Content-Security-Policy`. Later views of that
746
+ path make no request until the route's `maxStale` passes, which defaults to 15 minutes. After that
747
+ a `soft` route shows the copy and fetches `spool.json` once, and a `hard` route fetches it first.
748
+ A file whose version changed, or whose route left the manifest, is dropped and the next view
749
+ fetches it again. Set `sync` to `deferred` to wait for a request the page makes anyway, and
750
+ `offline` to `refuse` to keep a hard route from showing a copy it cannot check.
751
+
752
+ The worker keeps files up to 4 MiB and never a redirect or an error. It sends no analytics batches
753
+ and makes no request to `/.spool/*`. Serve `spool-sw.js` with `Cache-Control: max-age=86400`; that
754
+ header is what lets Chromium and Firefox skip the update check. To pin the script to the CDN, make
755
+ `/spool-sw.js` a one-line file:
756
+
757
+ ```js
758
+ importScripts('https://cdn.drupflare.com/spool/<version>/spool-sw.js');
759
+ ```
760
+
761
+ `importScripts` has no integrity check, so this form trusts the CDN host with the worker.
762
+
763
+ ---
764
+
765
+ ## ๐Ÿ”€ Strategies
766
+
767
+ A route is answered locally in one of five ways. A `template` route stores JSON and renders it
768
+ through a compiled template. An `assembly` route stores a shell with named holes, fragment markup
769
+ for the holes and values for named slots. A `static` route stores a file as the server sent it. A
770
+ `data` route stores JSON and answers a GET for it. A `projection` route stores JSON and renders a
771
+ page from it with a function your site bundles into its own worker.
772
+
773
+ ```ts
774
+ import { placeholder, slot } from '@drupflare/spool/protocol';
775
+ import { defineRoute } from '@drupflare/spool/server';
776
+
777
+ export const about = defineRoute('/about', {
778
+ strategy: 'assembly',
779
+ depends: () => ['menu'],
780
+ load: () => ({
781
+ shell: `<!doctype html><html><head><title>About</title></head><body>${placeholder('menu')}<main>Updated ${slot('updated')}</main></body></html>`,
782
+ fragments: { menu: '<nav><a href="/">Home</a></nav>' },
783
+ slots: { updated: '2026-10-19' }
784
+ })
785
+ });
786
+ ```
787
+
788
+ The worker leaves a hole it cannot fill in place and refuses to render a page with a gap, so the
789
+ request goes to the network instead.
790
+
791
+ A page the worker renders keeps the site's security headers. The worker remembers
792
+ `Content-Security-Policy` (and its report-only form), `X-Frame-Options`, `X-Content-Type-Options`,
793
+ `Referrer-Policy`, `Permissions-Policy` and the three `Cross-Origin-*` policies from the network
794
+ answer to each path, and sends them with every local render of it. A path with no answer of its own
795
+ uses the latest set from any navigation. A page with neither goes to the network until the worker
796
+ has seen one, so a local view never goes out without the site's policy.
797
+
798
+ ### Records and Projections
799
+
800
+ Pages that read the same data share one stored copy. `ctx.record(id, data)` stores an
801
+ authoritative value once under its id, and `ctx.projection(id, data)` stores a value derived from
802
+ records. Both return a reference to put in the page's data. A record's id is its invalidation tag.
803
+ Invalidating `course:101` refreshes the records and projections that read it, and no others.
804
+
805
+ ```ts
806
+ import { defineRoute } from '@drupflare/spool/server';
807
+
808
+ const courses: Record<string, string> = { '101': 'Intro', '102': 'Advanced' };
809
+
810
+ export const course = defineRoute('/courses/:id', {
811
+ strategy: 'template',
812
+ template: {
813
+ source: '<h1>{{title}}</h1><nav>{{#each menu}}<a>{{this}}</a>{{/each}}</nav>'
814
+ },
815
+ load: (ctx) => {
816
+ const id = ctx.params['id'] ?? '';
817
+ return {
818
+ title: ctx.record(`course:${id}`, courses[id]),
819
+ menu: ctx.projection(
820
+ 'menu',
821
+ Object.keys(courses).map((key) => ctx.record(`course:${key}`, courses[key]))
822
+ )
823
+ };
824
+ }
825
+ });
826
+ ```
827
+
828
+ The server sends only the records and projections the device does not already hold at a current
829
+ version. A sync for the next page transfers the entries that page reads and that changed.
830
+
831
+ ### Templates
832
+
833
+ Templates use Mustache-shaped syntax with no expressions, so the worker needs no `eval`.
834
+
835
+ | Syntax | Meaning |
836
+ | ------------------------------------ | -------------------------------------------------------- |
837
+ | `{{field}}` | the field, HTML-escaped; `a.b` reaches into objects |
838
+ | `{{{field}}}` | the field as markup; allowed only for names in `trusted` |
839
+ | `{{#each list}}...{{/each}}` | repeats for each item; `{{this}}` and `{{@index}}` work |
840
+ | `{{#if field}}...{{else}}...{{/if}}` | renders a branch on whether the field is truthy |
841
+ | `{{! note }}` | a comment that renders nothing |
842
+
843
+ ```ts
844
+ import { defineRoute } from '@drupflare/spool/server';
845
+
846
+ export const news = defineRoute('/news/:slug', {
847
+ strategy: 'template',
848
+ template: {
849
+ source:
850
+ '<article><h1>{{title}}</h1>{{#if byline}}<p>{{byline}}</p>{{else}}<p>Staff</p>{{/if}}<div>{{{body}}}</div><ul>{{#each tags}}<li>{{@index}} {{this}}</li>{{/each}}</ul></article>',
851
+ trusted: ['body']
852
+ },
853
+ depends: (ctx) => [`news:${ctx.params['slug']}`],
854
+ load: () => ({
855
+ title: 'Hello',
856
+ byline: null,
857
+ body: '<p>Trusted markup</p>',
858
+ tags: ['a', 'b']
859
+ })
860
+ });
861
+ ```
862
+
863
+ A template that names a field it does not trust for markup fails when the route is declared.
864
+
865
+ ### Static Files
866
+
867
+ A `static` route has no `load` and no template. The application serves the file as it always did,
868
+ and `handle` or `decorate` marks the response for the worker, which keeps the bytes. A tag in
869
+ `depends` ties the file to a deploy, and `spool.invalidate` after one makes devices fetch the
870
+ file again. A static route is always public and is always answered from the device, so it takes no
871
+ `scope`, `persist` or `mode`. A query string makes a different file: `/app.js?v=2` is not
872
+ answered with the copy of `/app.js`, and a query the worker has not stored goes to the network.
873
+
874
+ ```ts
875
+ import { defineRoute } from '@drupflare/spool/server';
876
+
877
+ export const about = defineRoute('/about', {
878
+ strategy: 'static',
879
+ depends: () => ['site'],
880
+ freshness: { maxStale: 3600, mode: 'soft' }
881
+ });
882
+ ```
883
+
884
+ ### Projection and Data Routes
885
+
886
+ A `data` route answers a GET for JSON, such as an API read, from the stored value, so the page's
887
+ `fetch` makes no request. The worker answers with `JSON.stringify` of what `load` returned, which
888
+ means the application's own handler has to return the same JSON. A navigation to the URL still goes
889
+ to the network.
890
+
891
+ A `projection` route needs a renderer. Spool ships no bundler: write a worker with `serve` from
892
+ `@drupflare/spool/sw`, bundle it with your own toolchain, and pass the bundle to `createSpool` as
893
+ `worker`. The server puts the config in front of your bundle as `self.__SPOOL_CONFIG__`, and
894
+ `spool.config` is the same object as JSON if you would rather inline it at build time. A route with
895
+ no renderer is refused by the worker and the network answers.
896
+
897
+ ```ts
898
+ import { defineRoute } from '@drupflare/spool/server';
899
+
900
+ export const course = defineRoute('/api/courses/:id', {
901
+ strategy: 'data',
902
+ depends: (ctx) => [`course:${ctx.params['id']}`],
903
+ load: (ctx) => ({ id: ctx.params['id'], title: 'Intro' }),
904
+ provision: { reuse: 0.8, futureViews: 6 }
905
+ });
906
+
907
+ export const roster = defineRoute('/rosters/:id', {
908
+ strategy: 'projection',
909
+ depends: (ctx) => [`roster:${ctx.params['id']}`],
910
+ load: (ctx) => ({ id: ctx.params['id'], names: ['Ada', 'Bo'] })
911
+ });
912
+ ```
913
+
914
+ ```ts
915
+ import { escapeHtml } from '@drupflare/spool/protocol';
916
+ import { serve } from '@drupflare/spool/sw';
917
+
918
+ declare const CONFIG: string;
919
+
920
+ serve(JSON.parse(CONFIG), {
921
+ '/rosters/:id': (artifact) => {
922
+ const { names } = (artifact.body as { data: { names: string[] } }).data;
923
+ return `<!doctype html><html><head><title>Roster</title></head><body><ul>${names.map((name) => `<li>${escapeHtml(name)}</li>`).join('')}</ul></body></html>`;
924
+ }
925
+ });
926
+ ```
927
+
928
+ The server also decides whether to send an artifact at all. It weighs the bytes it would send,
929
+ records included, against what a local view saves: reuse times future views times the bytes a view
930
+ avoids, less the cost of the request. When that is not positive it answers `204` with
931
+ `Spool-Provision: declined`, and the worker leaves that path to the network until it restarts.
932
+ The priors are scenario assumptions: set them from your own telemetry in `provision`, or per route
933
+ as above. A `data` route weighs against its own size, so it needs reuse times future views above
934
+
935
+ 1. With the defaults of 0.5 and 2 it breaks even and is left out.
936
+
937
+ ---
938
+
939
+ ## โณ Freshness Contracts
940
+
941
+ Each route declares how long a stored page may go without validation. `maxStale` is in seconds.
942
+
943
+ - **hard:** once `maxStale` passes, the worker validates the page with the server before it
944
+ shows it. Offline, the route's `offline` rule decides.
945
+ - **soft:** the worker shows the stored page at once and syncs afterward. A soft bound is a
946
+ stale-while-revalidate window and promises nothing about how fresh the shown page is.
947
+
948
+ Public routes default to 15 minutes soft, and routes with `scope: 'principal'` to five minutes
949
+ hard; [Authenticated Data](#-authenticated-data) covers how their pages are stored. `offline`
950
+ defaults to `serve` for public routes and `refuse` for principal routes. A soft route may set `sync: 'deferred'` to queue its refresh
951
+ for the next network request that happens anyway.
952
+
953
+ ```ts
954
+ import { defineRoute } from '@drupflare/spool/server';
955
+
956
+ export const stock = defineRoute('/stock/:sku', {
957
+ strategy: 'template',
958
+ template: { source: '<p>{{sku}}: {{count}}</p>' },
959
+ depends: (ctx) => [`stock:${ctx.params['sku']}`],
960
+ load: (ctx) => ({ sku: ctx.params['sku'], count: 3 }),
961
+ freshness: { maxStale: 60, mode: 'hard' },
962
+ offline: 'refuse'
963
+ });
964
+
965
+ export const notice = defineRoute('/notices/:id', {
966
+ strategy: 'template',
967
+ template: { source: '<p>{{text}}</p>' },
968
+ depends: (ctx) => [`notice:${ctx.params['id']}`],
969
+ load: () => ({ text: 'Closed on Friday' }),
970
+ freshness: { maxStale: 3600, mode: 'soft' },
971
+ sync: 'deferred'
972
+ });
973
+ ```
974
+
975
+ The worker syncs the smallest set of changed dependencies the next page needs. One worker
976
+ leads the sync for every tab of an origin. A response to a request that happens anyway can carry
977
+ invalidations, so a sync does not always need a request of its own.
978
+
979
+ ---
980
+
981
+ ## ๐Ÿ” Authenticated Data
982
+
983
+ Set `scope: 'principal'` on a route that depends on who is signed in, and give `createSpool` an
984
+ `identity` option. The server sends `Spool-Partition`, an HMAC of the principal under your secret,
985
+ so the browser can tell users apart without learning who they are. The worker keeps each partition
986
+ in its own IndexedDB database with the artifacts, records, projections and sync state sealed with
987
+ AES-GCM. Each value is bound to its partition, kind and id, so a row copied into another slot does
988
+ not decrypt.
989
+
990
+ `retention` picks the key. `persistent` is a non-extractable key in IndexedDB that survives a
991
+ restart and is deleted on logout or a change of partition. `session`, the default, is a key held in
992
+ the worker's memory, which the browser discards when it stops the worker. Deleting a key makes what
993
+ it sealed unreadable, which is crypto-shredding of data at rest. It does not protect against script
994
+ running on your origin, which can ask the worker for whatever the page can. The ids and versions
995
+ that serve as storage keys stay readable, so use opaque ids for anything sensitive.
996
+
997
+ A principal route defaults to a five-minute hard bound and `offline: 'refuse'`. Revocation rides
998
+ the same bound: tag a page with the permission it needs, call `spool.invalidate` when the
999
+ permission goes, and the first required sync past the bound finds the page invalid.
1000
+
1001
+ A different `Spool-Partition` wipes the partition before it. A login or account-switch handler has
1002
+ to send the new value itself with `spool.partition(principal)`, because the request it answers
1003
+ still carries the old identity. A sync answer carries `Spool-Partition` for the request's identity
1004
+ too, so a sign-in the worker never saw ends at the first required sync, no later than the route's
1005
+ `maxStale` plus the next view. Paths in `logout` are wiped when the request reaches the worker,
1006
+ before it is sent, so logout empties every tab even with the network down. The worker first sends
1007
+ the same-origin posts it holds in `beacons`, while they still carry the session that is ending,
1008
+ and drops any that do not get through. The page runtime
1009
+ dispatches a `spool:cleared` event on `window` in every tab when that happens, so a page can blank
1010
+ what it shows. A response can also send
1011
+ `Spool-Clear`: `*` wipes everything, a partition id wipes one. `decorate(request, response, { clear:
1012
+ ['*'], hardReset: true })` adds `Clear-Site-Data: "storage"` as well, the browser's own reset
1013
+ of everything the origin holds, service worker included. Its Safari support is unverified, so rely
1014
+ on the worker's wipe.
1015
+
1016
+ ```ts
1017
+ import { createSpool, defineRoute } from '@drupflare/spool/server';
1018
+ import { memoryStore } from '@drupflare/spool/stores';
1019
+
1020
+ export const grades = defineRoute('/grades', {
1021
+ strategy: 'template',
1022
+ scope: 'principal',
1023
+ retention: 'persistent',
1024
+ template: { source: '<h1>Grades for {{owner}}</h1>' },
1025
+ depends: (ctx) => [`perm:${ctx.identity?.principal}`, `grades:${ctx.identity?.principal}`],
1026
+ load: (ctx) => ({ owner: ctx.identity?.principal })
1027
+ });
1028
+
1029
+ export const spool = createSpool({
1030
+ routes: [grades],
1031
+ store: memoryStore(),
1032
+ identity: {
1033
+ secret: 'a long random value kept on the server',
1034
+ resolve: (request) => {
1035
+ const user = /user=(\w+)/.exec(request.headers.get('cookie') ?? '')?.[1];
1036
+ return user ? { principal: user } : null;
1037
+ }
1038
+ },
1039
+ logout: ['/logout']
1040
+ });
1041
+
1042
+ export async function login(user: string): Promise<Response> {
1043
+ return new Response('Signed in', {
1044
+ headers: {
1045
+ 'set-cookie': `user=${user}; Path=/`,
1046
+ 'spool-partition': await spool.partition(user)
1047
+ }
1048
+ });
1049
+ }
1050
+ ```
1051
+
1052
+ A sync that asks for everything changed lists the tags of every change, so tags for principal data
1053
+ should be opaque too. The worker syncs a principal page with `need`, which names only the tags
1054
+ that page reads.
1055
+
1056
+ ---
1057
+
1058
+ ## ๐Ÿ“š Catalogue
1059
+
1060
+ A catalogue sends the data of pages a visitor may open next, so that opening one makes no
1061
+ request. An entry costs its bytes whether or not the page is opened, and an opened one saves a
1062
+ document request, so an entry pays only when enough visitors open it. The break-even share is
1063
+ `k * E / (k * D + o)`, where `E` is the entry's compressed bytes, `D` the bytes of the document
1064
+ it replaces, `k` the joules to move a byte and `o` the origin request a view avoids. An entry the
1065
+ size of the document needs 96% of visitors to open it, which no page gets. An entry that is only
1066
+ the data for a template the device already holds is a few hundred bytes to a few kilobytes and
1067
+ pays at a few percent. On the `payload` reading, the rendered fields of a node were a median 473
1068
+ bytes compressed on 19 pages from two sites (L1, `measurements/payload`), against a document of
1069
+ about 17,000 bytes. References such as media and terms are left out of that figure, so a real entry
1070
+ is larger. An entry is data for a `template`, `projection` or `data` route and never HTML.
1071
+
1072
+ The site supplies the candidates. A route's `catalogue` returns the pages a visitor on it may open
1073
+ next, each with the share expected to. Take the share from your own `nextShare` over the sink
1074
+ (each `spool.view` names the route the visitor came from), from link position, or from a fixed
1075
+ prior. `documentBytes` on the entry's route says what a hit saves, and the provisioning prior is
1076
+ used when it is absent.
1077
+
1078
+ ```ts
1079
+ import { createSpool, defineRoute } from '@drupflare/spool/server';
1080
+ import { memoryStore } from '@drupflare/spool/stores';
1081
+
1082
+ export const home = defineRoute('/', {
1083
+ strategy: 'template',
1084
+ template: { source: '<h1>Courses</h1>' },
1085
+ load: () => ({}),
1086
+ catalogue: () => [
1087
+ { path: '/courses/101', p: 0.3 },
1088
+ { path: '/courses/102', p: 0.1 }
1089
+ ]
1090
+ });
1091
+
1092
+ export const course = defineRoute('/courses/:id', {
1093
+ strategy: 'template',
1094
+ template: { source: '<h1>{{title}}</h1>' },
1095
+ depends: (ctx) => [`course:${ctx.params['id']}`],
1096
+ load: (ctx) => ({ title: `Course ${ctx.params['id']}` }),
1097
+ documentBytes: 17_000
1098
+ });
1099
+
1100
+ export const spool = createSpool({
1101
+ routes: [home, course],
1102
+ store: memoryStore(),
1103
+ catalogueBytes: 16_384
1104
+ });
1105
+ ```
1106
+
1107
+ The server sends an entry only when its share reaches its own break-even, best expected net first,
1108
+ until `catalogueBytes` is spent. The cap counts compressed bytes and defaults to 32 KiB. It builds
1109
+ at most 32 pages for one request, measures each entry with Brotli where the runtime has it and
1110
+ gzip where it does not, and skips a `static` or `assembly` route. A request with `Save-Data: on`
1111
+ gets no entries.
1112
+
1113
+ The ask rides the beacon batch the worker already sends. A due ask also makes the next network
1114
+ moment send that batch, when a view is held to carry it, so a visit of two or three pages gets its
1115
+ entries without waiting for 20 views or an hour. That costs one `POST /.spool/beacon` for each
1116
+ catalogue page, device and day, sent at a request that happens anyway. A local view never sends
1117
+ it, and a moment with nothing held sends nothing. The worker stores the entries like provisioned
1118
+ pages, and the first view of an unopened one is reported with the reason `catalogue`. `catalogueFigures` reads the views and the worker's ledger for the entries sent
1119
+ and used, the hit share, and the bytes sent against the bytes saved. Until shadow views measure
1120
+ the shares, the saving is a scenario.
1121
+
1122
+ A hit saves the document request and nothing else. On the Drupal pages measured (75 first views of
1123
+ internal pages on 10 sites, L1, `measurements/trim`), a view of a page still fetched that page's
1124
+ new images and stylesheet and script aggregates: only 3% of those first views moved nothing but
1125
+ the document. A catalogue view takes the document off the wire, and the rest of the page is
1126
+ the site's own HTTP cache and [asset trimming](#-trimmed-stylesheets).
1127
+
1128
+ A `principal` route can be an entry. The worker then names every catalogue entry no page has
1129
+ opened at each sync of a principal page, so a revoked one is dropped at the first required sync.
1130
+ The request that asks for a catalogue names the path of the page the visitor is on, including one
1131
+ the worker showed locally, so a route that should not tell the server leaves `catalogue` off.
1132
+ [docs/security.md](docs/security.md#catalogue-entries) covers both.
1133
+
1134
+ ---
1135
+
1136
+ ## ๐Ÿ“ก Analytics Batching
1137
+
1138
+ A page that keeps analytics scripts posting to an endpoint makes a request on every view, which
1139
+ defeats a local view. List the same-origin POST paths in `beacons`. The worker answers each post
1140
+ with a `204` and queues it in IndexedDB. At the next network request that happens anyway it sends
1141
+ the post to the URL the page meant, with its method, content type, query and body, so the vendor
1142
+ receives what the page sent. Spool's own events go to `/.spool/beacon` in one batch, where a
1143
+ `sink` receives them. A held post goes out on its own at most once every 24 hours, when the oldest
1144
+ is a day old. A body over 64 KiB, counted in bytes, or a binary body goes to the network at once.
1145
+ Firefox does not route `fetch` calls made with `keepalive: true` through the worker, so a script
1146
+ that posts that way is not queued there.
1147
+
1148
+ ```ts
1149
+ import { createSpool, jsonLinesSink } from '@drupflare/spool/server';
1150
+ import { memoryStore } from '@drupflare/spool/stores';
1151
+ import { routes } from './routes';
1152
+
1153
+ export const spool = createSpool({
1154
+ routes,
1155
+ store: memoryStore(),
1156
+ beacons: ['/cdn-cgi/rum'],
1157
+ sink: jsonLinesSink((line) => console.log(line))
1158
+ });
1159
+ ```
1160
+
1161
+ `jsonLinesSink` writes one JSON line per event. `analyticsEngineSink` writes to a Workers
1162
+ Analytics Engine dataset, splitting a long body across data points so nothing is cut off, and
1163
+ `memorySink` keeps events for tests. The worker also queues one
1164
+ `spool.view` event per page view with the tier, the reason, the staleness and the route the
1165
+ visitor came from (a pattern or `external`, never a URL). `viewsOf` reads
1166
+ those events back. Set `views: false` to turn that off. `workSeries` records how long each route's
1167
+ handler took, for peak-work reports.
1168
+
1169
+ ### Collectors
1170
+
1171
+ A `collectors` entry holds requests to another origin, such as an analytics host. The page gets an
1172
+ empty answer at once and the request leaves at a network moment, inside `maxAgeMs`. An event past
1173
+ the cap is dropped, never sent late, and each drop is counted and written to the sink as
1174
+ `/.spool/dropped`. With `delivery: 'replay'` the worker sends the held request to the vendor with no
1175
+ cookies, so identity has to be in the payload, and `stamp` writes the event's time into a query
1176
+ parameter for a vendor that takes one. With `delivery: 'sink'` the server half forwards it.
1177
+
1178
+ GA4's browser collector takes no backdating. The Measurement Protocol accepts events with their
1179
+ own timestamps up to 72 hours old and wants them within 48 hours to attribute them, and it needs an
1180
+ API secret the page must not hold. `GA4_COLLECTOR` holds the `g/collect` hit for 48 hours and
1181
+ `ga4Sink` sends it as a Measurement Protocol request carrying the original `timestamp_micros`.
1182
+ `ga4Sink` checks its requests against the rules spool knows (`mpViolations`); set `debug: true` to
1183
+ send them to `/debug/mp/collect` with your own measurement id and secret. Spool holds events
1184
+ whether or not the visitor consented, so gate the analytics tag itself, and ask your counsel
1185
+ whether holding an event in IndexedDB needs consent where you operate. Programmatic ads are never
1186
+ held, replayed or answered locally.
1187
+
1188
+ ```ts
1189
+ import { GA4_COLLECTOR } from '@drupflare/spool/protocol';
1190
+ import { combineSinks, createSpool, ga4Sink, jsonLinesSink } from '@drupflare/spool/server';
1191
+ import { memoryStore } from '@drupflare/spool/stores';
1192
+ import { routes } from './routes';
1193
+
1194
+ export const spool = createSpool({
1195
+ routes,
1196
+ store: memoryStore(),
1197
+ collectors: [
1198
+ GA4_COLLECTOR,
1199
+ {
1200
+ vendor: 'matomo',
1201
+ match: 'https://stats.example.edu/matomo.php',
1202
+ maxAgeMs: 23 * 3_600_000,
1203
+ delivery: 'replay',
1204
+ stamp: { param: 'cdt', kind: 'datetime-utc' }
1205
+ }
1206
+ ],
1207
+ sink: combineSinks(
1208
+ jsonLinesSink((line) => console.log(line)),
1209
+ ga4Sink({ measurementId: 'G-XXXXXXXXXX', apiSecret: 'kept on the server' })
1210
+ )
1211
+ });
1212
+ ```
1213
+
1214
+ ---
1215
+
1216
+ ## ๐Ÿงท Third-Party Files
1217
+
1218
+ A view that loads a file from another origin is not zero-network. The page reports, when it is
1219
+ hidden, how many cross-origin resources it loaded and from which origins (origins only, never
1220
+ paths). `thirdPartyReport` reads those reports from `viewsOf` and ranks the origins by the views
1221
+ each one alone blocks, with a class and a remedy from a short table you can replace. The counts
1222
+ are an upper bound on network requests, since a cross-origin timing entry says nothing about cache
1223
+ hits without `Timing-Allow-Origin`.
1224
+
1225
+ The opt-in `thirdParty` cache removes the request for files that name their own bytes. List the
1226
+ origins in `allow`. The worker learns a file from the first view and keeps it only when the URL
1227
+ carries a hash, a version or a `/v12/` segment, or the origin marks it immutable. A file versioned
1228
+ only by a query parameter is checked again at a network moment once it is a day old. It keeps
1229
+ nothing else, and nothing it cannot read: an opaque response counts about 7 MB against quota in
1230
+ Chromium, so `allowOpaque` is off by default. WebKit does not send font requests from a stylesheet
1231
+ through the worker, so fonts stay on the network there.
1232
+
1233
+ ```ts
1234
+ import { thirdPartyReport } from '@drupflare/spool/report';
1235
+ import { createSpool, memorySink, viewsOf } from '@drupflare/spool/server';
1236
+ import { memoryStore } from '@drupflare/spool/stores';
1237
+ import { routes } from './routes';
1238
+
1239
+ const sink = memorySink();
1240
+
1241
+ export const spool = createSpool({
1242
+ routes,
1243
+ store: memoryStore(),
1244
+ sink,
1245
+ thirdParty: {
1246
+ allow: ['https://fonts.gstatic.com', 'https://cdn.example.edu'],
1247
+ maxEntries: 32
1248
+ }
1249
+ });
1250
+
1251
+ export const report = () => thirdPartyReport(viewsOf(sink.events));
1252
+ ```
1253
+
1254
+ ---
1255
+
1256
+ ## โšก Subresource Handling
1257
+
1258
+ By default the worker answers an immutable same-origin asset from CacheStorage. `assets` changes
1259
+ that. `passthrough` leaves assets to the browser's cache and never touches them. `static-routing`
1260
+ asks the browser through `InstallEvent.addRoutes` to send only navigations, beacons and routed
1261
+ paths to the worker and the rest of the origin to the network, and acts as `passthrough` where the
1262
+ API does not exist: Chromium has it, Playwright's WebKit has it on macOS and not on Linux, and
1263
+ Firefox does not. Both options cut the service worker's fetch events (Static Routing took them from
1264
+ 32 to 3 per view on a desktop Chromium rig); neither changes server-side Worker invocations.
1265
+ Neither is measured to save energy. In the same run, new-tab views drew 2.78 J,
1266
+ 2.83 J and 2.84 J of RAPL package energy above idle with CacheStorage, navigation-only handling
1267
+ and Static Routing (8 rounds each), and the ranges overlap. Under Static Routing a same-origin write no
1268
+ longer reaches the worker, so it is not a network moment and its response cannot carry
1269
+ invalidations; navigations still are.
1270
+
1271
+ ```ts
1272
+ import { createSpool } from '@drupflare/spool/server';
1273
+ import { memoryStore } from '@drupflare/spool/stores';
1274
+ import { routes } from './routes';
1275
+
1276
+ export const spool = createSpool({
1277
+ routes,
1278
+ store: memoryStore(),
1279
+ assets: 'static-routing'
1280
+ });
1281
+ ```
1282
+
1283
+ ---
1284
+
1285
+ ## ๐Ÿ” Shadow Mode
1286
+
1287
+ In shadow mode the worker decides whether it could serve a page locally, renders it, still fetches
1288
+ the page from the server, compares the two with `normalise` and reports the result. It never
1289
+ serves the local page. Use it to measure eligibility and mismatches on real traffic before turning
1290
+ serving on. A `static` route has no shadow comparison.
1291
+
1292
+ ```ts
1293
+ import { createSpool } from '@drupflare/spool/server';
1294
+ import { memoryStore } from '@drupflare/spool/stores';
1295
+ import { routes } from './routes';
1296
+
1297
+ export const shadowed = createSpool({ routes, store: memoryStore(), mode: 'shadow' });
1298
+ export const canary = createSpool({ routes, store: memoryStore(), shadowSample: 0.05 });
1299
+ ```
1300
+
1301
+ `mode: 'shadow'` applies to every route that does not name its own `mode`. `shadowSample` keeps a
1302
+ share of views in shadow while the rest are served, which gives a standing canary. A mismatch
1303
+ names its route, so a route whose template and application disagree shows up before a visitor
1304
+ sees it. The worker records the shadow comparison for navigations only. Subresources and other
1305
+ requests keep the browser's own path.
1306
+
1307
+ ---
1308
+
1309
+ ## ๐Ÿ”Œ Proxy Mode
1310
+
1311
+ `spoolProxy` fronts an origin that cannot load the library, such as PHP, Drupal with no module,
1312
+ or anything else that speaks HTTP. It returns a Fetch handler. The proxy answers `/.spool/*` and
1313
+ `/spool-sw.js`. Every other request goes to the origin with its method, headers and body, and a
1314
+ redirect is passed on, not followed. A page the proxy may keep is decorated like a `createSpool`
1315
+ response, so the worker stores it and answers later views with no request.
1316
+
1317
+ `spool` takes the options `createSpool` takes, minus `routes`. The proxy adds one public
1318
+ `assembly` route that matches every path (`/**`) and uses the origin's finished HTML as the
1319
+ artifact. `routes` lists overrides, such as a shorter freshness bound for one pattern. They
1320
+ match first and take the same fields as `defineRoute`, without `load`.
1321
+
1322
+ On Node the handler goes through `toNodeListener`. `origin` is the address of the real server
1323
+ and has no path.
1324
+
1325
+ ```ts
1326
+ import { createServer } from 'node:http';
1327
+ import { toNodeListener } from '@drupflare/spool/node';
1328
+ import { spoolProxy } from '@drupflare/spool/proxy';
1329
+ import { memoryStore } from '@drupflare/spool/stores';
1330
+
1331
+ const proxy = spoolProxy({
1332
+ origin: process.env['ORIGIN'] as string,
1333
+ spool: { store: memoryStore() },
1334
+ purgeSecret: process.env['PURGE_SECRET']
1335
+ });
1336
+
1337
+ export const server = createServer(toNodeListener(proxy));
1338
+ ```
1339
+
1340
+ On Workers the proxy is built once per isolate and keeps the version vector in a Durable Object,
1341
+ bound as in [Cloudflare Workers](#cloudflare-workers). Set the purge secret with
1342
+ `wrangler secret put PURGE_SECRET`.
1343
+
1344
+ ```ts
1345
+ import { spoolProxy, type SpoolProxy } from '@drupflare/spool/proxy';
1346
+ import { durableObjectStore } from '@drupflare/spool/stores/durable-object';
1347
+
1348
+ export { SpoolVersions } from '@drupflare/spool/stores/durable-object';
1349
+
1350
+ let proxy: SpoolProxy | undefined;
1351
+
1352
+ export default {
1353
+ fetch(request: Request, env: Cloudflare.Env) {
1354
+ proxy ??= spoolProxy({
1355
+ origin: 'https://origin.example.edu',
1356
+ spool: { store: durableObjectStore(env.SPOOL_VERSIONS) },
1357
+ purgeSecret: env.PURGE_SECRET
1358
+ });
1359
+ return proxy(request);
1360
+ }
1361
+ };
1362
+ ```
1363
+
1364
+ ### Tags
1365
+
1366
+ The tags the origin sends become the page's dependencies. The proxy reads `Cache-Tag` (comma
1367
+ separated), `Surrogate-Key` and `X-Drupal-Cache-Tags` (space separated) and `xkey` (spaces or
1368
+ commas), then removes them from the response unless `exposeTags` is true. A page with no tags
1369
+ depends on one tag derived from its path.
1370
+
1371
+ ### Eligibility
1372
+
1373
+ The proxy keeps a response only when all of these hold:
1374
+
1375
+ - the request is a GET or HEAD, has no query string and no `Authorization` header, and carries
1376
+ no cookie outside `publicCookies`, which is empty by default
1377
+ - the response is a 200 `text/html`, or the answer of a `data` route
1378
+ - the page is UTF-8, or declares no charset in its `Content-Type` or in a `<meta>` within its
1379
+ first 1024 bytes
1380
+ - the response sets no cookie outside `publicCookies`, has no `private` or `no-store` in
1381
+ `Cache-Control`, a `Vary` that names only `Accept-Encoding` and `Cookie`, no more than
1382
+ `maxTags` tags and no more than `maxBytes` bytes
1383
+
1384
+ Everything else is forwarded untouched. A page the proxy declines tells the worker to drop its
1385
+ copy of that path, and a response that sets a cookie outside `publicCookies` tells the worker to
1386
+ clear everything it holds, so a login leaves no anonymous copy to show. Put cookies that carry no
1387
+ identity on the list, such as a bot-check or load-balancer cookie set on every response; otherwise
1388
+ proxy mode never keeps a page on that site. Writes always go to the origin and are never
1389
+ answered locally.
1390
+
1391
+ Principal routes are off unless `spool.identity` is set. With it, a route declared
1392
+ `scope: 'principal'` follows the partitions in [Authenticated Data](#-authenticated-data). The
1393
+ cookie, `Authorization` and `private` rules do not apply to it. `Set-Cookie` and `no-store`
1394
+ still do.
1395
+
1396
+ ### Invalidation
1397
+
1398
+ Two signals reach the proxy. When a page it forwards differs from the last body it saw, it bumps
1399
+ that page's tags. The proxy hashes the body after `normalise`, and `ignore` takes patterns to
1400
+ blank, such as a per-render form token. `POST /.spool/purge` bumps the tags it is given, so a CMS
1401
+ hook or Drupal's purge module can call it. It needs `Authorization: Bearer <purgeSecret>` and a
1402
+ JSON body, and it refuses every call when no secret is set.
1403
+
1404
+ ```sh
1405
+ curl -X POST https://example.edu/.spool/purge \
1406
+ -H "Authorization: Bearer $PURGE_SECRET" \
1407
+ -H "Content-Type: application/json" \
1408
+ -d '{"tags": ["node:1", "config:system.menu.main"]}'
1409
+ ```
1410
+
1411
+ ### Limits
1412
+
1413
+ The proxy sees finished HTML, not the database behind it. An artifact is a whole page, the
1414
+ replica holds no records, and two pages never share a fragment. A page stays on a device until its
1415
+ route's `maxStale` passes and the next sync reports a change, so freshness is bounded by
1416
+ `maxStale` plus the time a purge takes to arrive.
1417
+
1418
+ A tag shared by many pages invalidates all of them when one changes. The remembered bodies live
1419
+ in the instance: a restart forgets them, and each instance of a scaled-out proxy keeps its own.
1420
+ A whole page is a large artifact, and the provisioning rule declines one that costs more than the
1421
+ priors say it saves, so set `provision` on the spool for large pages. A `Content-Security-Policy`
1422
+ that allows only nonce or hash scripts blocks the injected client tag. A URL with a query string
1423
+ always goes to the origin. [Trimmed Stylesheets](#-trimmed-stylesheets) covers the `trim` option
1424
+ and [Images and Video](#-images-and-video) the `images` and `video` options.
1425
+
1426
+ ---
1427
+
1428
+ ## ๐Ÿงน Trimmed Stylesheets
1429
+
1430
+ A new page of a Drupal site usually loads a stylesheet aggregate the visitor has not seen, and
1431
+ most of its rules match nothing on the page. `@drupflare/spool/trim` builds a manifest that removes
1432
+ the rules no page of the site can match, and `spoolProxy` serves the trimmed text in place of the
1433
+ origin's file. Each file is trimmed against every page and script of the site, never against one
1434
+ page, so it keeps its URL and its one cached copy. Rules are only removed, so the cascade of what
1435
+ stays is unchanged.
1436
+
1437
+ ```ts
1438
+ import { spoolProxy } from '@drupflare/spool/proxy';
1439
+ import { memoryStore } from '@drupflare/spool/stores';
1440
+ import { buildTrimManifest } from '@drupflare/spool/trim';
1441
+
1442
+ export const manifest = await buildTrimManifest({
1443
+ pages: ['<body class="hero"><a class="button">Apply</a></body>'],
1444
+ scripts: [{ url: '/js/site.js', text: 'menu.classList.add("open")' }],
1445
+ styles: [{ url: '/css/site.css', text: '.hero{a:b}.button{c:d}.open{e:f}.print-only{g:h}' }]
1446
+ });
1447
+
1448
+ export const proxy = spoolProxy({
1449
+ origin: 'https://origin.example.edu',
1450
+ spool: { store: memoryStore() },
1451
+ trim: manifest
1452
+ });
1453
+ ```
1454
+
1455
+ `pages` is HTML, `scripts` and `styles` are the same-origin files the pages load, and `url` is the
1456
+ address the page links. Crawl with a browser and pass the page's DOM after load and after a
1457
+ scroll as well as the origin's HTML: a class that a script builds from parts, such as
1458
+ `'fs-carousel' + '-enabled'`, is only in the rendered page. Pass the scripts of other origins that
1459
+ the pages load as `foreignScripts`, since a widget that builds markup adds classes too.
1460
+
1461
+ Two checks protect a visitor. The proxy serves a trimmed file only when the origin's bytes still
1462
+ hash to the manifest's `source`, and otherwise sends the origin's file and counts a mismatch. It
1463
+ also reads every HTML page before it leaves: a page with a token the trim removed a rule for, or a
1464
+ same-origin script the manifest was not built with, links the full file through `spool-trim=0`.
1465
+ `proxy.trim` counts the files served, the mismatches and the guard firings, and the sink gets
1466
+ each mismatch and firing as an event. [docs/security.md](docs/security.md#trimmed-stylesheets) names
1467
+ what the guard cannot see: a class a vendor script adds after the crawl, markup injected after load
1468
+ from a page the crawl never requested, and a class name built at runtime that no crawl rendered.
1469
+
1470
+ The proxy trims CSS and leaves JavaScript alone. Coverage at load cannot see what a click or a
1471
+ scroll will need: the used share of same-origin JavaScript rose from 36% at load to 40% after one
1472
+ scroll on the pages measured (L1), so no load-time figure says which of the rest is dead. The same
1473
+ saving from a build step that runs PurgeCSS with a safelist needs no proxy. The proxy gets it
1474
+ without a change to the origin. The saving applies to a network view of a page the visitor has not
1475
+ seen, never to a repeat or local view, and it is not part of the per-view headline;
1476
+ [docs/impact.md](docs/impact.md#asset-trimming) has the bytes, joules and prices.
1477
+
1478
+ ---
1479
+
1480
+ ## ๐ŸŽฌ Images and Video
1481
+
1482
+ A browser that has fetched an image cannot make it smaller, so conversion happens where the file is
1483
+ served. `@drupflare/spool/media` gives `spoolProxy` three options, each off until set. `images`
1484
+ converts a JPEG or PNG response to WebP for a browser whose `Accept` lists it. `video` rewrites
1485
+ the `<video>` tags of an HTML response, such as adding `preload="none"`. `embeds` swaps a YouTube
1486
+ or Vimeo iframe for a link that loads the player on click.
1487
+
1488
+ ```ts
1489
+ import { type ImageEncoder } from '@drupflare/spool/media';
1490
+ import { spoolProxy } from '@drupflare/spool/proxy';
1491
+ import { memoryStore } from '@drupflare/spool/stores';
1492
+
1493
+ export function mediaProxy(encoder: ImageEncoder) {
1494
+ return spoolProxy({
1495
+ origin: 'https://origin.example.edu',
1496
+ spool: { store: memoryStore() },
1497
+ images: { encoder, width: { fallback: 1600 } },
1498
+ video: { preload: 'none', autoplay: 'defer', when: 'slow' }
1499
+ });
1500
+ }
1501
+ ```
1502
+
1503
+ An `ImageEncoder` takes the origin's bytes and `{ format: 'webp', quality, width }` and returns
1504
+ `{ bytes }`. It never upscales, so `width` is a ceiling, and it throws on input it cannot decode.
1505
+ spool has no runtime dependencies and ships an adapter for [tinyimg](https://tinyimg.gmitch215.dev),
1506
+ which decodes and encodes inside WebAssembly:
1507
+
1508
+ ```js
1509
+ import { readFile } from 'node:fs/promises';
1510
+ import { TinyImgModule, transform } from '@gmitch215/tinyimg';
1511
+ import { tinyimgEncoder } from '@drupflare/spool/media';
1512
+
1513
+ const wasm = new URL(import.meta.resolve('@gmitch215/tinyimg/tinyimg.wasm'));
1514
+ const module = await TinyImgModule.loadBytes(await readFile(wasm));
1515
+
1516
+ export const encoder = tinyimgEncoder({ module, transform });
1517
+ ```
1518
+
1519
+ Use tinyimg 1.1.1 or later. Version 1.1.0 and earlier drop the EXIF orientation tag without
1520
+ rotating the pixels, so a phone photo comes out sideways. `tinyimgEncoder` throws when the module
1521
+ reports an older version.
1522
+
1523
+ Quality is 80, 65 for `Save-Data: on` and 70 for an `ECT` of `slow-2g`, `2g` or `3g`. The width
1524
+ comes from `Sec-CH-Width`, then `Sec-CH-Viewport-Width` times `Sec-CH-DPR`, then
1525
+ `width.fallback`. The proxy converts a `GET` that matches `paths` (JPEG and PNG names by default),
1526
+ has no `Range` or `Authorization`, and gets a `200` JPEG or PNG without a cookie between
1527
+ `minBytes` (4096) and `maxBytes` (15,000,000). Anything else, and any file the encoder cannot
1528
+ shrink, goes out as the origin sent it. The proxy fetches the origin for every request, so a
1529
+ visitor only gets bytes the origin sent that visitor.
1530
+
1531
+ A converted response carries `Vary` for `Accept`, `Save-Data`, `Sec-CH-Width`, `Sec-CH-DPR`,
1532
+ `Sec-CH-Viewport-Width` and `ECT`, a weak `ETag` and `X-Spool-Image`. HTML responses gain
1533
+ `Accept-CH` for the three size hints and `ECT` unless `hints` is false, and the browser then
1534
+ sends them with later image requests to the same origin.
1535
+
1536
+ `maxWidth` (2560) is the width for a request that carries no hint, and `false` removes it. `png`
1537
+ is `'lossy'` by default. `'lossless'` encodes every PNG without loss, and `'auto'` encodes a PNG
1538
+ under 200 KB both ways and serves the smaller file, which suits screenshots and flat graphics.
1539
+ Requests for the same file, quality and width share one encoder call while it runs. The proxy
1540
+ waits `timeoutMs` (10,000) for the encoder and then serves the origin's file, and the late result
1541
+ is cached for the next request. `timeoutMs: false` waits without limit.
1542
+
1543
+ Drupal's video formatter has no `preload` setting, and `preload="none"` does not stop `autoplay`.
1544
+ `autoplay: 'defer'` removes the attribute, adds `controls` and marks the tag
1545
+ `data-spool-autoplay`. With `when: 'always'` the page the spool keeps carries the rewrite. With
1546
+ `'save-data'` or `'slow'` the rewritten page is private to that visitor: it gets `private` in
1547
+ `Cache-Control` and `Save-Data, ECT` in `Vary`, and the spool does not keep it. A device's stored
1548
+ copy of that page keeps the origin's tags.
1549
+
1550
+ `proxy.images` counts `converted`, `bytesIn` and `bytesOut` (converted responses only),
1551
+ `cacheHits`, `coalesced`, `lazied`, `responsive`, and `skipped` by reason. `proxy.video` counts
1552
+ `pages` and `rewritten`. Read the saving as `bytesIn - bytesOut` over real traffic on the site. A
1553
+ request for any other path counts under `skipped.path`, so that key follows total traffic.
1554
+ [docs/security.md](docs/security.md#images-and-video) covers the decoder.
1555
+
1556
+ ### Page Rewrites
1557
+
1558
+ Three options change the HTML the origin sends. Each edits start tags only and leaves every other
1559
+ byte as it was, and a rewritten page gets a weak `ETag`.
1560
+
1561
+ ```ts
1562
+ import { type ImageEncoder } from '@drupflare/spool/media';
1563
+ import { spoolProxy } from '@drupflare/spool/proxy';
1564
+ import { memoryStore } from '@drupflare/spool/stores';
1565
+
1566
+ export function rewriteProxy(encoder: ImageEncoder) {
1567
+ return spoolProxy({
1568
+ origin: 'https://origin.example.edu',
1569
+ spool: { store: memoryStore() },
1570
+ images: {
1571
+ encoder,
1572
+ png: 'auto',
1573
+ maxWidth: 1920,
1574
+ timeoutMs: 5000,
1575
+ lazy: { skip: 3 },
1576
+ responsive: { widths: [480, 960, 1440], sizes: '(min-width: 60em) 50vw, 100vw' }
1577
+ },
1578
+ embeds: { providers: ['youtube'], thumbnail: false }
1579
+ });
1580
+ }
1581
+ ```
1582
+
1583
+ `lazy` adds `loading="lazy"` and `decoding="async"` to each `<img>` after the first `skip` (2 by
1584
+ default), and `iframes: true` does the same for `<iframe>`. It leaves a tag that has `loading`,
1585
+ `fetchpriority` or a lazy-loading library's `data-src`, a tag inside a `<header>` or `<noscript>`,
1586
+ and an image that a `<link rel="preload" as="image">` names. A browser that defers the largest
1587
+ image of a page paints it later, so `skip` is the only guard and the option is off until set. In a
1588
+ crawl of 70 pages per profile on 16 sites, the default `skip` of 2 made the largest image lazy on 2
1589
+ of 23 desktop pages and 2 of 20 phone pages that had an image as their largest element, and no
1590
+ `skip` from 2 to 4 reached zero on both profiles.
1591
+
1592
+ `responsive` adds a `srcset` of `?spool-w=<width>` variants to a same-origin `<img>` that has none,
1593
+ one per entry of `widths` (320, 480, 640, 960, 1280 and 1920 by default), and a `sizes` of `100vw`
1594
+ unless the tag has one. The proxy removes `spool-w` before it asks the origin, answers only widths
1595
+ from the list and never sends a file larger than the origin's. Firefox and Safari send no
1596
+ `Sec-CH-Width`, and this is how they get a resized file. Name the layout width in `sizes`, since
1597
+ `100vw` makes the browser pick the widest candidate it can use. A tag with `srcset` or `data-src`,
1598
+ and any tag inside `<picture>`, stays as it is.
1599
+
1600
+ `embeds` replaces a server-rendered YouTube or Vimeo `<iframe>` with one whose `srcdoc` holds a
1601
+ link to the player. YouTube shows its thumbnail (`thumbnail: false` shows a plain frame) and the
1602
+ player loads on click. A page that sends `Content-Security-Policy` is left alone unless
1603
+ `ignoreCsp` is true, and so is an embed with `enablejsapi=1`. `proxy.embeds` counts `pages`,
1604
+ `rewritten` and `skipped`. [docs/security.md](docs/security.md#embed-facades) covers the rules.
1605
+
1606
+ ### Dictionary Transport
1607
+
1608
+ A visitor who holds an earlier stylesheet or script of a directory can fetch the next one as the
1609
+ difference from it. `dictionary` implements this for Chromium 130 and later
1610
+ ([RFC 9842](https://www.rfc-editor.org/rfc/rfc9842)). The proxy marks public `.css` and `.js`
1611
+ responses with `Use-As-Dictionary` and answers a request that names one of them with
1612
+ `Content-Encoding: dcz`. spool has no compression library, so the caller supplies the `encoder`,
1613
+ and Node's `zlib` does zstd:
1614
+
1615
+ ```ts
1616
+ import { promisify } from 'node:util';
1617
+ import { zstdCompress } from 'node:zlib';
1618
+ import { spoolProxy } from '@drupflare/spool/proxy';
1619
+ import { memoryStore } from '@drupflare/spool/stores';
1620
+
1621
+ const compress = promisify(zstdCompress);
1622
+
1623
+ export const proxy = spoolProxy({
1624
+ origin: 'https://origin.example.edu',
1625
+ spool: { store: memoryStore() },
1626
+ dictionary: {
1627
+ encoder: async (dictionary, input) => new Uint8Array(await compress(input, { dictionary }))
1628
+ }
1629
+ });
1630
+ ```
1631
+
1632
+ The `encoder` gets the dictionary, the new file and the coding (`'dcz'`, or `'dcb'` when `formats`
1633
+ lists it) and returns the compressed stream. spool adds the coding's header. An encoder that
1634
+ throws, or whose output is no smaller, leaves the plain file. Only responses the proxy would keep
1635
+ as public ones, with no cookie, ever become dictionaries. `proxy.dictionary` counts `registered`,
1636
+ `encoded`, `bytesIn`, `bytesOut` and `skipped`.
1637
+ [docs/security.md](docs/security.md#dictionary-transport) covers the exposure.
1638
+
1639
+ `base` names the files that register as dictionaries, as a function of the pathname, a regular
1640
+ expression or a list of them. Without it the browser holds the latest file of each directory it
1641
+ fetched, and the sizing in [docs/impact.md](docs/impact.md#savings-today-and-at-maximum) shows that
1642
+ choice recovers little. With it the browser holds only the files you name, one per directory, and
1643
+ every other file of the directory is encoded against the base the request names.
1644
+ `scripts/measure/dictionary-size.ts` records the best base of each directory of a site.
1645
+
1646
+ ### Defaults
1647
+
1648
+ Every option is absent by default. The table shows what a feature does once its parent option is
1649
+ set and how to change it.
1650
+
1651
+ | Feature | Option | Default once the parent is set | Leave or enter |
1652
+ | ------------------------------------------ | ------------------- | ------------------------------------------- | ----------------------------------------------------- |
1653
+ | WebP conversion, `304` and `X-Spool-Image` | `images` | on, needs an `encoder` | leave `images` out |
1654
+ | `Accept-CH` hints and `Vary` | `images.hints` | on | `hints: false` |
1655
+ | Quality by `Save-Data` and `ECT` | `images.quality` | 80, 65 and 70 | give all three one number |
1656
+ | Width ceiling for a request with no width | `images.maxWidth` | 2560 | `maxWidth: false`, or another number |
1657
+ | Shared encodes and the encoder time limit | `images.timeoutMs` | 10,000 ms, identical encodes share one call | `timeoutMs: false` removes the limit |
1658
+ | PNG mode | `images.png` | `'lossy'` | `'auto'` or `'lossless'` |
1659
+ | `loading="lazy"` on images and iframes | `images.lazy` | off | `lazy: {}` or `{ skip, iframes }` |
1660
+ | `srcset` variants | `images.responsive` | off | `responsive: {}` or `{ widths, sizes }` |
1661
+ | `preload="none"` on video | `video.preload` | `'none'` | `preload: false` |
1662
+ | Video autoplay deferral | `video.autoplay` | off | `autoplay: 'defer'` |
1663
+ | YouTube and Vimeo facades | `embeds` | off | `embeds: {}` or `{ providers, thumbnail, ignoreCsp }` |
1664
+ | Dictionary transport | `dictionary` | off | `dictionary: { encoder }` |
1665
+ | Which files become dictionaries | `dictionary.base` | every `.css` and `.js` response | `base: /\/base\.js$/`, a list or a function |
1666
+
1667
+ ---
1668
+
1669
+ ## ๐Ÿšซ Out of Scope
1670
+
1671
+ - spool never authorises on the client. The device holds only what the server already sent that
1672
+ principal.
1673
+ - It never shows a hard route past its bound without validating it first.
1674
+ - It never writes. Your application owns every write, and `invalidate` only announces one.
1675
+ - It never infers dependencies from opaque HTML. A route names its tags, or the records it
1676
+ reads, and in proxy mode the origin names them in its cache tag headers.
1677
+ - It never replaces a published release file on the CDN.
1678
+
1679
+ ---
1680
+
1681
+ ## ๐ŸŒ Browser Support
1682
+
1683
+ | Engine | Controlled navigation |
1684
+ | -------- | ------------------------------------------------------------------------------------------------------------------ |
1685
+ | Chromium | no request, new tabs included |
1686
+ | Firefox | no request, new tabs included |
1687
+ | WebKit | one request to re-check `/spool-sw.js`, and one refetch of each cacheable subresource on the first controlled load |
1688
+
1689
+ The worker registers with `updateViaCache: 'all'` and the script is served at
1690
+ `max-age=86400`, which is what lets Chromium and Firefox skip the update check. A deploy changes
1691
+ the script bytes and reaches a browser within that day. A browser without service workers gets the
1692
+ page it always got.
1693
+
1694
+ A page that loads a resource from another origin is not a zero-request view. spool counts those
1695
+ loads per view and reports the view as such.
1696
+
1697
+ ---
1698
+
1699
+ ## ๐Ÿงญ Subpath Exports
1700
+
1701
+ | Import | What is in it |
1702
+ | ---------------------------------------- | -------------------------------------------------------------------- |
1703
+ | `@drupflare/spool` | the protocol and report modules |
1704
+ | `@drupflare/spool/protocol` | envelopes, artifacts, patterns, templates, the manifest, view events |
1705
+ | `@drupflare/spool/server` | `createSpool`, `defineRoute`, sinks, identity and work series |
1706
+ | `@drupflare/spool/node` | `toNodeListener`, `toRequest`, `writeResponse` |
1707
+ | `@drupflare/spool/proxy` | `spoolProxy`, the tag readers and the eligibility verdict |
1708
+ | `@drupflare/spool/stores` | `memoryStore` and the `VersionStore` type |
1709
+ | `@drupflare/spool/stores/durable-object` | `durableObjectStore` and the `SpoolVersions` class |
1710
+ | `@drupflare/spool/sw` | `serve`, for a site that bundles its own worker |
1711
+ | `@drupflare/spool/client` | `register` and the page handle |
1712
+ | `@drupflare/spool/report` | the energy model |
1713
+ | `@drupflare/spool/trim` | `buildTrimManifest`, `trimCss` and `guardPage` |
1714
+ | `@drupflare/spool/media` | `tinyimgEncoder`, `imageVariant` and `rewriteVideo` |
1715
+
1716
+ ---
1717
+
1718
+ ## ๐Ÿงช Testing
1719
+
1720
+ ```sh
1721
+ bun run typecheck
1722
+ bun run test
1723
+ bun run test:coverage
1724
+ bun run test:browser
1725
+ bun run prettier:check
1726
+ bun run docs:build
1727
+ bun run build
1728
+ ```
1729
+
1730
+ `test` runs the unit project in workerd and the node project, which includes a test that packs the
1731
+ package and imports every subpath in plain Node. `test:browser` runs Chromium, Firefox and WebKit
1732
+ against real servers and counts the requests that reach them. `bunx playwright install chromium
1733
+ firefox webkit` fetches the browsers.
1734
+
1735
+ ---
1736
+
1737
+ ## ๐Ÿ”— Related Repositories
1738
+
1739
+ | Repository | What it is |
1740
+ | --------------------------------------------------------------- | -------------------------------------------------------- |
1741
+ | [`drupflare/worker`](https://github.com/drupflare/worker) | Drupal on Cloudflare Workers |
1742
+ | [`drupflare/cartridge`](https://github.com/drupflare/cartridge) | runs a blocking wasm interpreter inside a Durable Object |
1743
+ | [`drupflare/durabledb`](https://github.com/drupflare/durabledb) | the limits of Durable Object SQLite, encoded as a codec |
1744
+ | [`drupflare/burrow`](https://github.com/drupflare/burrow) | executes WebAssembly on Workers |
1745
+
1746
+ ---
1747
+
1748
+ ## ๐Ÿ“„ License
1749
+
1750
+ MIT (c) Gregory Mitchell 2026. See [LICENSE](LICENSE).