@drupflare/spool 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +279 -1607
  2. package/dist/angular/index.d.ts +13 -0
  3. package/dist/angular/index.js +25 -0
  4. package/dist/angular/pages.d.ts +28 -0
  5. package/dist/angular/pages.js +85 -0
  6. package/dist/cdn/client.js +1 -1
  7. package/dist/cdn/location.d.ts +6 -0
  8. package/dist/cdn/location.js +8 -0
  9. package/dist/cdn/manifest.json +7 -7
  10. package/dist/cdn/spool-sw.js +1 -1
  11. package/dist/client/bootstrap.d.ts +57 -0
  12. package/dist/client/bootstrap.js +307 -0
  13. package/dist/client/contact.d.ts +24 -0
  14. package/dist/client/contact.js +66 -0
  15. package/dist/client/declared.d.ts +23 -0
  16. package/dist/client/declared.js +68 -0
  17. package/dist/client/entry.js +123 -2
  18. package/dist/client/gate.d.ts +1 -0
  19. package/dist/client/gate.js +148 -0
  20. package/dist/client/index.d.ts +25 -0
  21. package/dist/client/index.js +1 -0
  22. package/dist/client/live.d.ts +66 -0
  23. package/dist/client/live.js +225 -0
  24. package/dist/client/navigate-entry.d.ts +1 -0
  25. package/dist/client/navigate-entry.js +4 -0
  26. package/dist/client/navigate.d.ts +54 -0
  27. package/dist/client/navigate.js +272 -0
  28. package/dist/client/persist.d.ts +2 -0
  29. package/dist/client/persist.js +9 -0
  30. package/dist/client/register.d.ts +34 -2
  31. package/dist/client/register.js +64 -7
  32. package/dist/express/index.d.ts +11 -0
  33. package/dist/express/index.js +209 -0
  34. package/dist/hono/index.d.ts +19 -0
  35. package/dist/hono/index.js +49 -0
  36. package/dist/next/index.d.ts +33 -0
  37. package/dist/next/index.js +41 -0
  38. package/dist/next/pages.d.ts +22 -0
  39. package/dist/next/pages.js +39 -0
  40. package/dist/node/listener.d.ts +3 -0
  41. package/dist/node/listener.js +57 -2
  42. package/dist/nuxt/index.d.ts +22 -0
  43. package/dist/nuxt/index.js +104 -0
  44. package/dist/nuxt/pages.d.ts +26 -0
  45. package/dist/nuxt/pages.js +48 -0
  46. package/dist/nuxt/runtime/index.d.ts +24 -0
  47. package/dist/nuxt/runtime/index.js +58 -0
  48. package/dist/plugins/coverage.d.ts +14 -0
  49. package/dist/plugins/coverage.js +27 -0
  50. package/dist/plugins/mode.d.ts +19 -0
  51. package/dist/plugins/mode.js +20 -0
  52. package/dist/plugins/path.d.ts +16 -0
  53. package/dist/plugins/path.js +139 -0
  54. package/dist/plugins/report.d.ts +22 -0
  55. package/dist/plugins/report.js +18 -0
  56. package/dist/plugins/routes.d.ts +38 -0
  57. package/dist/plugins/routes.js +52 -0
  58. package/dist/plugins/static.d.ts +42 -0
  59. package/dist/plugins/static.js +97 -0
  60. package/dist/protocol/bundle.d.ts +111 -0
  61. package/dist/protocol/bundle.js +428 -0
  62. package/dist/protocol/config.d.ts +80 -1
  63. package/dist/protocol/config.js +31 -1
  64. package/dist/protocol/dataset.d.ts +189 -0
  65. package/dist/protocol/dataset.js +212 -0
  66. package/dist/protocol/envelope.d.ts +34 -1
  67. package/dist/protocol/envelope.js +16 -1
  68. package/dist/protocol/errors.d.ts +1 -1
  69. package/dist/protocol/graph.d.ts +23 -4
  70. package/dist/protocol/graph.js +34 -3
  71. package/dist/protocol/index-rows.d.ts +22 -0
  72. package/dist/protocol/index-rows.js +53 -0
  73. package/dist/protocol/index.d.ts +5 -0
  74. package/dist/protocol/index.js +5 -0
  75. package/dist/protocol/normalise.d.ts +4 -4
  76. package/dist/protocol/normalise.js +9 -5
  77. package/dist/protocol/plan.d.ts +100 -0
  78. package/dist/protocol/plan.js +661 -0
  79. package/dist/protocol/provision.d.ts +46 -0
  80. package/dist/protocol/provision.js +38 -0
  81. package/dist/protocol/query.d.ts +66 -5
  82. package/dist/protocol/query.js +103 -4
  83. package/dist/protocol/ring.d.ts +58 -0
  84. package/dist/protocol/ring.js +6 -0
  85. package/dist/protocol/route.d.ts +63 -13
  86. package/dist/protocol/route.js +126 -6
  87. package/dist/protocol/tag.d.ts +22 -2
  88. package/dist/protocol/tag.js +25 -4
  89. package/dist/protocol/view.d.ts +2 -0
  90. package/dist/protocol/view.js +8 -2
  91. package/dist/protocol/views.d.ts +6 -0
  92. package/dist/protocol/views.js +15 -0
  93. package/dist/protocol/write.d.ts +234 -0
  94. package/dist/protocol/write.js +343 -0
  95. package/dist/proxy/eligible.d.ts +22 -1
  96. package/dist/proxy/eligible.js +62 -15
  97. package/dist/proxy/proxy.js +28 -18
  98. package/dist/react-router/index.d.ts +20 -0
  99. package/dist/react-router/index.js +60 -0
  100. package/dist/react-router/pages.d.ts +34 -0
  101. package/dist/react-router/pages.js +83 -0
  102. package/dist/report/dataset.d.ts +48 -0
  103. package/dist/report/dataset.js +93 -0
  104. package/dist/report/demand.d.ts +49 -0
  105. package/dist/report/demand.js +60 -0
  106. package/dist/report/derive.d.ts +285 -0
  107. package/dist/report/derive.js +676 -1
  108. package/dist/report/economics.d.ts +66 -1
  109. package/dist/report/economics.js +208 -1
  110. package/dist/report/headline.d.ts +158 -0
  111. package/dist/report/headline.js +473 -0
  112. package/dist/report/index.d.ts +4 -0
  113. package/dist/report/index.js +4 -0
  114. package/dist/report/inputs.d.ts +176 -0
  115. package/dist/report/inputs.js +248 -0
  116. package/dist/report/institution.d.ts +188 -1
  117. package/dist/report/institution.js +146 -0
  118. package/dist/report/loops.d.ts +73 -0
  119. package/dist/report/loops.js +101 -0
  120. package/dist/report/measurement.d.ts +1 -1
  121. package/dist/report/measurement.js +7 -1
  122. package/dist/report/model.d.ts +2 -0
  123. package/dist/report/model.js +4 -0
  124. package/dist/report/thirdparty.d.ts +57 -0
  125. package/dist/report/thirdparty.js +111 -0
  126. package/dist/report/traffic.d.ts +8 -0
  127. package/dist/report/traffic.js +7 -0
  128. package/dist/report/trim.d.ts +56 -0
  129. package/dist/report/trim.js +83 -1
  130. package/dist/server/bundle.d.ts +55 -0
  131. package/dist/server/bundle.js +172 -0
  132. package/dist/server/dataset.d.ts +54 -0
  133. package/dist/server/dataset.js +355 -0
  134. package/dist/server/embedded.d.ts +7 -3
  135. package/dist/server/embedded.js +7 -3
  136. package/dist/server/index.d.ts +6 -0
  137. package/dist/server/index.js +6 -0
  138. package/dist/server/live-sockets.d.ts +54 -0
  139. package/dist/server/live-sockets.js +131 -0
  140. package/dist/server/live.d.ts +146 -0
  141. package/dist/server/live.js +228 -0
  142. package/dist/server/ring.d.ts +77 -0
  143. package/dist/server/ring.js +311 -0
  144. package/dist/server/spool.d.ts +158 -3
  145. package/dist/server/spool.js +578 -41
  146. package/dist/server/static.d.ts +42 -0
  147. package/dist/server/static.js +29 -0
  148. package/dist/server/stub.d.ts +43 -5
  149. package/dist/server/stub.js +126 -8
  150. package/dist/server/write.d.ts +49 -0
  151. package/dist/server/write.js +223 -0
  152. package/dist/stores/durable-object.d.ts +46 -0
  153. package/dist/stores/durable-object.js +114 -0
  154. package/dist/sw/analytics.d.ts +7 -1
  155. package/dist/sw/analytics.js +16 -2
  156. package/dist/sw/coverage.d.ts +6 -0
  157. package/dist/sw/coverage.js +34 -0
  158. package/dist/sw/dataset-sync.d.ts +76 -0
  159. package/dist/sw/dataset-sync.js +149 -0
  160. package/dist/sw/dataset.d.ts +91 -0
  161. package/dist/sw/dataset.js +318 -0
  162. package/dist/sw/family.d.ts +15 -0
  163. package/dist/sw/family.js +48 -0
  164. package/dist/sw/graph/index.d.ts +31 -1
  165. package/dist/sw/graph/index.js +57 -5
  166. package/dist/sw/graph/invalidate.d.ts +15 -3
  167. package/dist/sw/graph/invalidate.js +42 -4
  168. package/dist/sw/idb.d.ts +2 -0
  169. package/dist/sw/idb.js +80 -11
  170. package/dist/sw/index.d.ts +2 -0
  171. package/dist/sw/index.js +1 -0
  172. package/dist/sw/pack/store.d.ts +128 -0
  173. package/dist/sw/pack/store.js +737 -0
  174. package/dist/sw/partition.d.ts +6 -1
  175. package/dist/sw/partition.js +21 -2
  176. package/dist/sw/policy.d.ts +2 -0
  177. package/dist/sw/policy.js +11 -0
  178. package/dist/sw/principal-dataset.d.ts +64 -0
  179. package/dist/sw/principal-dataset.js +254 -0
  180. package/dist/sw/probe.d.ts +16 -0
  181. package/dist/sw/probe.js +25 -0
  182. package/dist/sw/render.d.ts +7 -2
  183. package/dist/sw/render.js +19 -5
  184. package/dist/sw/replica.d.ts +12 -3
  185. package/dist/sw/replica.js +40 -5
  186. package/dist/sw/router.d.ts +3 -2
  187. package/dist/sw/router.js +15 -2
  188. package/dist/sw/runtime.d.ts +90 -2
  189. package/dist/sw/runtime.js +857 -61
  190. package/dist/sw/scheduler.d.ts +6 -1
  191. package/dist/sw/scheduler.js +22 -5
  192. package/dist/sw/seal.d.ts +13 -0
  193. package/dist/sw/seal.js +13 -4
  194. package/dist/sw/static.d.ts +18 -0
  195. package/dist/sw/static.js +84 -1
  196. package/dist/sw/storage.d.ts +51 -1
  197. package/dist/sw/storage.js +33 -1
  198. package/dist/sw/write.d.ts +147 -0
  199. package/dist/sw/write.js +625 -0
  200. package/dist/version.d.ts +1 -1
  201. package/dist/version.js +1 -2
  202. package/dist/vite/index.d.ts +26 -0
  203. package/dist/vite/index.js +66 -0
  204. package/dist/vue/index.d.ts +36 -0
  205. package/dist/vue/index.js +53 -0
  206. package/package.json +65 -4
@@ -0,0 +1,343 @@
1
+ import { ProtocolError } from './errors.js';
2
+ import { checkPattern, matchPattern } from './pattern.js';
3
+ import { defineRoute } from './route.js';
4
+ /** the header that names one flush of one key; a retry of the same flush sends the same id */
5
+ export const WRITE_HEADERS = { id: 'spool-write-id', digest: 'spool-write-digest' };
6
+ /** a write class name is 1 to 64 of letters, digits, `_` and `-` */
7
+ export const WRITE_NAME = /^[A-Za-z0-9_-]{1,64}$/;
8
+ const VERSION = /^[A-Za-z0-9._:~-]{1,128}$/;
9
+ const WRITE_ID = /^[A-Za-z0-9_-]{16,64}$/;
10
+ /** the most characters in a key */
11
+ export const MAX_WRITE_KEY = 256;
12
+ /** the most bytes `maxBytes` may declare for one value's JSON body */
13
+ export const MAX_WRITE_BYTES = 1_048_576;
14
+ /** the most records `maxPending` may declare per class and partition */
15
+ export const MAX_WRITE_PENDING = 1000;
16
+ /** the status the server answers each refusal with */
17
+ export const WRITE_STATUS = {
18
+ 'writes-off': 403,
19
+ 'unknown-write': 404,
20
+ 'bad-method': 405,
21
+ 'bad-key': 400,
22
+ 'missing-version': 428,
23
+ 'bad-version': 400,
24
+ 'bad-id': 400,
25
+ 'bad-body': 400,
26
+ 'too-large': 413,
27
+ 'too-many': 429,
28
+ 'id-reused': 422,
29
+ forbidden: 403,
30
+ 'sign-in': 401,
31
+ 'no-partition': 409,
32
+ 'no-record': 404,
33
+ 'not-conflicted': 409,
34
+ unavailable: 503
35
+ };
36
+ function bad(name, message) {
37
+ throw new ProtocolError('bad-write', `${name}: ${message}`);
38
+ }
39
+ export function defineWrite(first, second) {
40
+ if (typeof first === 'string')
41
+ return defineResourceWrite(first, second);
42
+ return defineQueuedWrite(first);
43
+ }
44
+ function defineQueuedWrite(declaration) {
45
+ const name = String(declaration?.name);
46
+ if (typeof declaration?.name !== 'string' || !WRITE_NAME.test(declaration.name)) {
47
+ return bad(name, 'a write name is 1 to 64 of letters, digits, _ and -');
48
+ }
49
+ const scope = declaration.scope;
50
+ if (scope !== 'principal') {
51
+ return bad(name, `scope must be "principal"; a "${scope}" write is never queued`);
52
+ }
53
+ const kind = declaration.kind ?? 'last-value';
54
+ if (kind !== 'last-value') {
55
+ return bad(name, `kind "${kind}" does not exist; the only kind is "last-value"`);
56
+ }
57
+ if (typeof declaration.path !== 'string')
58
+ return bad(name, 'path must be a route pattern');
59
+ checkPattern(declaration.path);
60
+ for (const fn of ['key', 'read', 'apply']) {
61
+ if (typeof declaration[fn] !== 'function')
62
+ return bad(name, `${fn} must be a function`);
63
+ }
64
+ const caps = { maxBytes: MAX_WRITE_BYTES, maxPending: MAX_WRITE_PENDING };
65
+ for (const limit of ['maxBytes', 'maxPending']) {
66
+ const value = declaration[limit];
67
+ if (!Number.isSafeInteger(value) || value < 1 || value > caps[limit]) {
68
+ return bad(name, `${limit} must be an integer from 1 to ${caps[limit]}`);
69
+ }
70
+ }
71
+ const delay = declaration.maxDelayMs;
72
+ if (delay !== undefined && (!Number.isSafeInteger(delay) || delay < 0)) {
73
+ return bad(name, 'maxDelayMs must be a non-negative integer');
74
+ }
75
+ return Object.freeze({ ...declaration, kind: 'last-value' });
76
+ }
77
+ /** the config entry the worker gets for a class */
78
+ export function serializeWrite(write) {
79
+ const config = { name: write.name, maxBytes: write.maxBytes, maxPending: write.maxPending };
80
+ return write.maxDelayMs === undefined ? config : { ...config, maxDelayMs: write.maxDelayMs };
81
+ }
82
+ /** whether `key` is a key the wire carries: a non-empty string of at most {@link MAX_WRITE_KEY} characters without NUL */
83
+ export function isWriteKey(key) {
84
+ return (typeof key === 'string' &&
85
+ key.length > 0 &&
86
+ key.length <= MAX_WRITE_KEY &&
87
+ !key.includes('\u0000'));
88
+ }
89
+ /** whether `version` is a version the wire carries */
90
+ export const isWriteVersion = (version) => typeof version === 'string' && VERSION.test(version);
91
+ /** whether `id` is a write id the wire carries */
92
+ export const isWriteId = (id) => typeof id === 'string' && WRITE_ID.test(id);
93
+ /** the `If-Match` value for a version: a strong entity tag */
94
+ export const ifMatch = (version) => `"${version}"`;
95
+ /** the version in an `If-Match` value, or null when it is not one strong entity tag of a valid version */
96
+ export function readIfMatch(header) {
97
+ const match = header === null ? null : /^"([^"]*)"$/.exec(header.trim());
98
+ return match && isWriteVersion(match[1]) ? match[1] : null;
99
+ }
100
+ /** a random write id: 22 base64url characters of 128 random bits */
101
+ export function newWriteId() {
102
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
103
+ let binary = '';
104
+ for (const byte of bytes)
105
+ binary += String.fromCharCode(byte);
106
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
107
+ }
108
+ /** the methods a resource write may declare */
109
+ export const RESOURCE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
110
+ /** how a declared write changes the held rows; `invalidate` marks the touched rows stale */
111
+ export const RESOURCE_APPLY = ['response', 'merge', 'delete', 'invalidate'];
112
+ function defineResourceWrite(pattern, declaration) {
113
+ checkPattern(pattern);
114
+ if (!declaration)
115
+ return bad(pattern, 'a resource write needs a declaration');
116
+ if (!RESOURCE_METHODS.includes(declaration.method)) {
117
+ return bad(pattern, `method must be one of ${RESOURCE_METHODS.join(', ')}`);
118
+ }
119
+ if (typeof declaration.dataset !== 'string' || declaration.dataset === '') {
120
+ return bad(pattern, 'dataset must be a dataset name');
121
+ }
122
+ if (typeof declaration.key !== 'string' || declaration.key === '') {
123
+ return bad(pattern, 'key must be a param name');
124
+ }
125
+ const apply = declaration.apply;
126
+ if (isObject(apply))
127
+ checkPatch(pattern, apply);
128
+ else if (typeof apply !== 'string' || !RESOURCE_APPLY.includes(apply)) {
129
+ return bad(pattern, `apply must be one of ${RESOURCE_APPLY.join(', ')}, or a patch`);
130
+ }
131
+ if (!Array.isArray(declaration.updates)) {
132
+ return bad(pattern, 'updates must be a list of route patterns');
133
+ }
134
+ for (const update of declaration.updates)
135
+ checkPattern(update);
136
+ if (declaration.origin !== undefined)
137
+ checkOrigin(pattern, declaration.origin);
138
+ return Object.freeze({ ...declaration, updates: [...declaration.updates], pattern });
139
+ }
140
+ const PATCH_KEYS = ['set', 'inc', 'unset'];
141
+ const UNSAFE_FIELDS = ['__proto__'];
142
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
143
+ const isBodyRef = (value) => isObject(value) && Object.keys(value).length === 1 && typeof value.body === 'string';
144
+ function isJson(value) {
145
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
146
+ return true;
147
+ if (typeof value === 'number')
148
+ return Number.isFinite(value);
149
+ if (Array.isArray(value))
150
+ return value.every(isJson);
151
+ return isObject(value) && Object.values(value).every(isJson);
152
+ }
153
+ function checkField(pattern, field) {
154
+ if (typeof field !== 'string' ||
155
+ field === '' ||
156
+ field.includes('.') ||
157
+ UNSAFE_FIELDS.includes(field)) {
158
+ bad(pattern, `patch field "${String(field)}" must be a field name with no dot`);
159
+ }
160
+ }
161
+ function checkPatch(pattern, patch) {
162
+ const keys = Object.keys(patch);
163
+ if (keys.length === 0)
164
+ bad(pattern, 'a patch needs set, inc or unset');
165
+ for (const key of keys) {
166
+ if (!PATCH_KEYS.includes(key))
167
+ bad(pattern, `patch key "${key}" is not set, inc or unset`);
168
+ }
169
+ if (patch.set !== undefined) {
170
+ if (!isObject(patch.set))
171
+ bad(pattern, 'set must be an object');
172
+ for (const [field, value] of Object.entries(patch.set)) {
173
+ checkField(pattern, field);
174
+ if (isBodyRef(value)) {
175
+ for (const segment of value.body.split('.'))
176
+ checkField(pattern, segment);
177
+ }
178
+ else if (!isJson(value)) {
179
+ bad(pattern, `set "${field}" must be a JSON value or { body: "<path>" }`);
180
+ }
181
+ }
182
+ }
183
+ if (patch.inc !== undefined) {
184
+ if (!isObject(patch.inc))
185
+ bad(pattern, 'inc must be an object');
186
+ for (const [field, amount] of Object.entries(patch.inc)) {
187
+ checkField(pattern, field);
188
+ if (typeof amount !== 'number' || !Number.isFinite(amount)) {
189
+ bad(pattern, `inc "${field}" must be a finite number`);
190
+ }
191
+ }
192
+ }
193
+ if (patch.unset !== undefined) {
194
+ if (!Array.isArray(patch.unset))
195
+ bad(pattern, 'unset must be a list of field names');
196
+ for (const field of patch.unset)
197
+ checkField(pattern, field);
198
+ }
199
+ }
200
+ /** the JSON value at a dotted path of the body, or undefined when a segment is missing or not an object */
201
+ function readBodyPath(body, path) {
202
+ let at = body;
203
+ for (const segment of path.split('.')) {
204
+ if (!isObject(at) || !Object.prototype.hasOwnProperty.call(at, segment))
205
+ return undefined;
206
+ at = at[segment];
207
+ }
208
+ return at;
209
+ }
210
+ /**
211
+ * The row a declared patch makes of `row` for a request `body`. It is pure, so the worker and any caller
212
+ * get the same row. Returns undefined when a body path names no value or an `inc` field is not a number.
213
+ */
214
+ export function applyPatch(row, body, patch) {
215
+ const next = { ...row };
216
+ for (const [field, value] of Object.entries(patch.set ?? {})) {
217
+ if (!isBodyRef(value)) {
218
+ next[field] = structuredClone(value);
219
+ continue;
220
+ }
221
+ const found = readBodyPath(body, value.body);
222
+ if (found === undefined)
223
+ return undefined;
224
+ next[field] = found;
225
+ }
226
+ for (const [field, amount] of Object.entries(patch.inc ?? {})) {
227
+ const held = next[field] === undefined ? 0 : next[field];
228
+ if (typeof held !== 'number')
229
+ return undefined;
230
+ next[field] = held + amount;
231
+ }
232
+ for (const field of patch.unset ?? [])
233
+ delete next[field];
234
+ return next;
235
+ }
236
+ function checkOrigin(pattern, origin) {
237
+ if (typeof origin !== 'string')
238
+ return bad(pattern, 'origin must be a string');
239
+ let parsed;
240
+ try {
241
+ parsed = new URL(origin);
242
+ }
243
+ catch {
244
+ return bad(pattern, `origin "${origin}" is not a URL`);
245
+ }
246
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.origin !== origin) {
247
+ return bad(pattern, `origin "${origin}" must be an http or https origin with no path`);
248
+ }
249
+ }
250
+ /**
251
+ * Declares a resource. `GET <pattern>` is the collection of the dataset, with no query string; a query
252
+ * string is not answered locally. `GET <pattern>/:key` is a data family of the dataset; `POST <pattern>`
253
+ * inserts; `PUT` and `PATCH <pattern>/:key` replace and update; `DELETE <pattern>/:key` removes. Any
254
+ * `POST`, `PUT`, `PATCH` or `DELETE` of `<pattern>/:key/:action` is a write on that item. Every write
255
+ * updates the collection and the item.
256
+ */
257
+ export function defineResource(pattern, declaration) {
258
+ checkPattern(pattern);
259
+ const { dataset, key, origin } = declaration;
260
+ const item = `${pattern}/:${key}`;
261
+ const action = `${item}/:action`;
262
+ const families = [pattern, item];
263
+ const extra = origin === undefined ? {} : { origin };
264
+ const routes = [
265
+ defineRoute(pattern, {
266
+ strategy: 'data',
267
+ load: () => ({}),
268
+ query: { list: dataset, dataset },
269
+ ...(origin === undefined ? {} : { origin })
270
+ }),
271
+ defineRoute(item, {
272
+ strategy: 'data',
273
+ family: { dataset, key },
274
+ ...(origin === undefined ? {} : { origin })
275
+ })
276
+ ];
277
+ const writes = [
278
+ defineResourceWrite(pattern, {
279
+ method: 'POST',
280
+ dataset,
281
+ key,
282
+ apply: 'response',
283
+ updates: families,
284
+ ...extra
285
+ }),
286
+ defineResourceWrite(item, {
287
+ method: 'PUT',
288
+ dataset,
289
+ key,
290
+ apply: 'response',
291
+ updates: families,
292
+ ...extra
293
+ }),
294
+ defineResourceWrite(item, {
295
+ method: 'PATCH',
296
+ dataset,
297
+ key,
298
+ apply: 'response',
299
+ updates: families,
300
+ ...extra
301
+ }),
302
+ defineResourceWrite(item, {
303
+ method: 'DELETE',
304
+ dataset,
305
+ key,
306
+ apply: 'delete',
307
+ updates: families,
308
+ ...extra
309
+ }),
310
+ ...RESOURCE_METHODS.map((method) => defineResourceWrite(action, {
311
+ method,
312
+ dataset,
313
+ key,
314
+ apply: 'invalidate',
315
+ updates: families,
316
+ ...extra
317
+ }))
318
+ ];
319
+ return Object.freeze({ pattern, dataset, key, routes, writes });
320
+ }
321
+ /**
322
+ * The resource write a request matches: its method, a pattern that matches its path, and its origin.
323
+ * A write with no origin matches only the page's own origin; one with an origin matches that origin.
324
+ */
325
+ export function writeFor(writes, method, url, pageOrigin) {
326
+ return writes.find((write) => write.method === method &&
327
+ matchPattern(write.pattern, url.pathname) !== null &&
328
+ url.origin === (write.origin ?? pageOrigin));
329
+ }
330
+ /**
331
+ * For each write a page made, the resource it couples to and the GET families it updates. A write that
332
+ * couples to no resource reports `resource: null` and no families; that is the uncovered case.
333
+ */
334
+ export function couplingReport(writes, resources, pageOrigin) {
335
+ return writes.map(({ method, url }) => {
336
+ for (const resource of resources) {
337
+ const hit = writeFor(resource.writes, method, new URL(url), pageOrigin);
338
+ if (hit)
339
+ return { method, url, resource: resource.pattern, families: [...hit.updates] };
340
+ }
341
+ return { method, url, resource: null, families: [] };
342
+ });
343
+ }
@@ -1,4 +1,5 @@
1
- /** why the proxy will not keep a response on the device */
1
+ import type { Sink } from '../server/sink.js';
2
+ /** why spool will not keep a response on the device, from the proxy or `decorate` */
2
3
  export type Decline = 'method' | 'query' | 'authorization' | 'cookie' | 'status' | 'type' | 'set-cookie' | 'private' | 'no-store' | 'vary' | 'tags' | 'size' | 'charset';
3
4
  /** what the verdict reads; `principal` is a route the caller declared for a signed-in visitor */
4
5
  export type Candidate = {
@@ -33,6 +34,12 @@ export declare function headerCharset(contentType: string | null): string | null
33
34
  export declare function htmlCharset(headers: Headers, bytes: Uint8Array): string | null;
34
35
  /** whether `charset` is UTF-8; a page that declares none is read as UTF-8 */
35
36
  export declare function isUtf8(charset: string | null): boolean;
37
+ /**
38
+ * The first reason a response's own headers keep it from being kept: a `Set-Cookie` off the
39
+ * allowlist, `private` unless `principal`, `no-store`, or a `Vary` other than encoding or cookies.
40
+ * `decorate` runs it for a public route with an empty allowlist, so any cookie declines there.
41
+ */
42
+ export declare function responseDecline(headers: Headers, publicCookies: ReadonlySet<string>, principal: boolean): Decline | null;
36
43
  /**
37
44
  * The first reason the response may not be answered locally, or `null` when it may. Everything
38
45
  * here declines: a request with a cookie outside the allowlist or an `Authorization` header, a
@@ -43,3 +50,17 @@ export declare function isUtf8(charset: string | null): boolean;
43
50
  * `private` rules do not apply to it.
44
51
  */
45
52
  export declare function decline(input: Candidate, gate: Gate): Decline | null;
53
+ /** where a declined response is written to the sink, as JSON `{ kind: 'decline', reason, route, source }` */
54
+ export declare const DECLINE_PATH = "/.spool/decline";
55
+ /**
56
+ * Which check declined: `gate` is `decorate`'s check of an in-process response, `navigation` the
57
+ * proxy's check of the page a visitor asked for, `artifact` the proxy's check of the copy it fetches
58
+ * for `/.spool/artifact`. The proxy declines one page at both when a worker asks for its artifact.
59
+ */
60
+ export type DeclineSource = 'gate' | 'navigation' | 'artifact';
61
+ /**
62
+ * Writes one decline event to `sink` and waits for it, as `/.spool/beacon` does. `route` is the
63
+ * declared route pattern, never the request path, so the event carries no id from a URL. A sink that
64
+ * throws or rejects never breaks the response. Does nothing without a sink.
65
+ */
66
+ export declare function recordDecline(sink: Sink | undefined, reason: Decline, route: string, source: DeclineSource): Promise<void>;
@@ -1,5 +1,17 @@
1
- /** `Vary` members that do not change the body once cookies are checked by name */
2
- const STABLE_VARY = new Set(['accept-encoding', 'cookie']);
1
+ /**
2
+ * `Vary` members that do not change the body once cookies are checked by name. The four `next-router`
3
+ * and `rsc` names are the request headers Next uses to choose its RSC payload over the document; a
4
+ * response to a request without them is the same HTML for every visitor, and a payload response is
5
+ * not HTML, so `decorate` never keeps it.
6
+ */
7
+ const STABLE_VARY = new Set([
8
+ 'accept-encoding',
9
+ 'cookie',
10
+ 'rsc',
11
+ 'next-router-state-tree',
12
+ 'next-router-prefetch',
13
+ 'next-router-segment-prefetch'
14
+ ]);
3
15
  /** the cookie names a `Cookie` header carries */
4
16
  export function cookieNames(header) {
5
17
  if (!header)
@@ -44,6 +56,27 @@ function directives(value) {
44
56
  .map((part) => (part.split('=')[0] ?? '').trim().toLowerCase())
45
57
  .filter((name) => name !== ''));
46
58
  }
59
+ /**
60
+ * The first reason a response's own headers keep it from being kept: a `Set-Cookie` off the
61
+ * allowlist, `private` unless `principal`, `no-store`, or a `Vary` other than encoding or cookies.
62
+ * `decorate` runs it for a public route with an empty allowlist, so any cookie declines there.
63
+ */
64
+ export function responseDecline(headers, publicCookies, principal) {
65
+ if (setsPrivateCookie(headers, publicCookies))
66
+ return 'set-cookie';
67
+ const control = directives(headers.get('cache-control'));
68
+ if (!principal && control.has('private'))
69
+ return 'private';
70
+ if (control.has('no-store'))
71
+ return 'no-store';
72
+ const vary = (headers.get('vary') ?? '')
73
+ .split(',')
74
+ .map((name) => name.trim().toLowerCase())
75
+ .filter((name) => name !== '');
76
+ if (vary.some((name) => !STABLE_VARY.has(name)))
77
+ return 'vary';
78
+ return null;
79
+ }
47
80
  /**
48
81
  * The first reason the response may not be answered locally, or `null` when it may. Everything
49
82
  * here declines: a request with a cookie outside the allowlist or an `Authorization` header, a
@@ -74,19 +107,9 @@ export function decline(input, gate) {
74
107
  // the stored copy is UTF-8 text, so a page in another charset would come back garbled
75
108
  if (!input.data && !isUtf8(headerCharset(type)))
76
109
  return 'charset';
77
- if (setsPrivateCookie(response.headers, gate.publicCookies))
78
- return 'set-cookie';
79
- const control = directives(response.headers.get('cache-control'));
80
- if (!principal && control.has('private'))
81
- return 'private';
82
- if (control.has('no-store'))
83
- return 'no-store';
84
- const vary = (response.headers.get('vary') ?? '')
85
- .split(',')
86
- .map((name) => name.trim().toLowerCase())
87
- .filter((name) => name !== '');
88
- if (vary.some((name) => !STABLE_VARY.has(name)))
89
- return 'vary';
110
+ const why = responseDecline(response.headers, gate.publicCookies, principal);
111
+ if (why)
112
+ return why;
90
113
  if (input.tags.length > gate.maxTags)
91
114
  return 'tags';
92
115
  const length = Number(response.headers.get('content-length'));
@@ -94,3 +117,27 @@ export function decline(input, gate) {
94
117
  return 'size';
95
118
  return null;
96
119
  }
120
+ /** where a declined response is written to the sink, as JSON `{ kind: 'decline', reason, route, source }` */
121
+ export const DECLINE_PATH = '/.spool/decline';
122
+ /**
123
+ * Writes one decline event to `sink` and waits for it, as `/.spool/beacon` does. `route` is the
124
+ * declared route pattern, never the request path, so the event carries no id from a URL. A sink that
125
+ * throws or rejects never breaks the response. Does nothing without a sink.
126
+ */
127
+ export async function recordDecline(sink, reason, route, source) {
128
+ if (!sink)
129
+ return;
130
+ try {
131
+ await sink.write([
132
+ {
133
+ path: DECLINE_PATH,
134
+ body: JSON.stringify({ kind: 'decline', reason, route, source }),
135
+ contentType: 'application/json',
136
+ at: Date.now()
137
+ }
138
+ ]);
139
+ }
140
+ catch {
141
+ // a failing sink never breaks a page
142
+ }
143
+ }
@@ -13,7 +13,7 @@ import { artifactTag } from '../protocol/sync.js';
13
13
  import { createSpool } from '../server/spool.js';
14
14
  import { guardPage, sourceHash, stripTrimParam, TRIM_PARAM, trimKey } from '../trim/index.js';
15
15
  import { createDictionaries } from './dictionary.js';
16
- import { decline, htmlCharset, isUtf8, setsPrivateCookie } from './eligible.js';
16
+ import { decline, htmlCharset, isUtf8, recordDecline, setsPrivateCookie } from './eligible.js';
17
17
  import { PURGE_PATH, respondPurge } from './purge.js';
18
18
  import { pathTag, readTags, stripTags } from './tags.js';
19
19
  const HOP_BY_HOP = [
@@ -248,7 +248,12 @@ export function spoolProxy(options) {
248
248
  await spool.invalidate([...new Set([...prior.tags, ...tags])]);
249
249
  }
250
250
  }
251
- async function fetchPage(ctx, data, principal) {
251
+ /** records the decline for the route pattern, then fails the artifact build with the reason */
252
+ async function refuse(route, why, path) {
253
+ await recordDecline(options.spool.sink, why, route, 'artifact');
254
+ throw new ProtocolError('bad-artifact', `${path} is not kept (${why})`);
255
+ }
256
+ async function fetchPage(ctx, data, principal, route) {
252
257
  const path = ctx.url.pathname;
253
258
  const headers = originHeaders(ctx.request.headers, new URL(ctx.request.url));
254
259
  for (const name of [
@@ -276,10 +281,10 @@ export function spoolProxy(options) {
276
281
  principal
277
282
  }, gate);
278
283
  if (why)
279
- throw new ProtocolError('bad-artifact', `${path} is not kept (${why})`);
284
+ return refuse(route, why, path);
280
285
  const bytes = new Uint8Array(await response.arrayBuffer());
281
286
  if (!data && !isUtf8(htmlCharset(response.headers, bytes))) {
282
- throw new ProtocolError('bad-artifact', `${path} is not kept (charset)`);
287
+ return refuse(route, 'charset', path);
283
288
  }
284
289
  let text = guarded(new TextDecoder().decode(bytes), ctx.url.href);
285
290
  // a signal-triggered rewrite is never part of a held copy
@@ -288,19 +293,18 @@ export function spoolProxy(options) {
288
293
  }
289
294
  if (!data)
290
295
  text = rewriteMarkup(text, response.headers, ctx.url.href, false);
291
- if (text.length > gate.maxBytes) {
292
- throw new ProtocolError('bad-artifact', `${path} is not kept (size)`);
293
- }
296
+ if (text.length > gate.maxBytes)
297
+ return refuse(route, 'size', path);
294
298
  const effective = tags.length > 0 ? tags : [pathTag(path)];
295
299
  if (!principal)
296
300
  await settle(path, text, effective);
297
301
  return { text, tags: effective };
298
302
  }
299
- function pageFor(ctx, data, principal) {
303
+ function pageFor(ctx, data, principal, route) {
300
304
  const known = pages.get(ctx.request);
301
305
  if (known && known.path === ctx.url.pathname)
302
306
  return known.page;
303
- const page = fetchPage(ctx, data, principal);
307
+ const page = fetchPage(ctx, data, principal, route);
304
308
  pages.set(ctx.request, { path: ctx.url.pathname, page });
305
309
  return page;
306
310
  }
@@ -312,7 +316,7 @@ export function spoolProxy(options) {
312
316
  }
313
317
  const extra = declaration?.depends;
314
318
  const depends = async (ctx) => [
315
- ...(await pageFor(ctx, data, principal)).tags,
319
+ ...(await pageFor(ctx, data, principal, pattern)).tags,
316
320
  ...(extra ? await extra(ctx) : [])
317
321
  ];
318
322
  if (declaration?.strategy === 'data') {
@@ -321,7 +325,7 @@ export function spoolProxy(options) {
321
325
  strategy: 'data',
322
326
  depends,
323
327
  load: async (ctx) => {
324
- const { text } = await pageFor(ctx, true, principal);
328
+ const { text } = await pageFor(ctx, true, principal, pattern);
325
329
  try {
326
330
  return JSON.parse(text);
327
331
  }
@@ -335,7 +339,7 @@ export function spoolProxy(options) {
335
339
  ...declaration,
336
340
  strategy: 'assembly',
337
341
  depends,
338
- load: async (ctx) => ({ shell: (await pageFor(ctx, false, principal)).text })
342
+ load: async (ctx) => ({ shell: (await pageFor(ctx, false, principal, pattern)).text })
339
343
  });
340
344
  }
341
345
  const routes = [
@@ -344,7 +348,9 @@ export function spoolProxy(options) {
344
348
  ];
345
349
  const spool = createSpool({ ...options.spool, routes });
346
350
  /** a page the proxy declines tells the worker to drop its copy of that path, in the same response */
347
- async function unfit(response, path, why, page) {
351
+ async function unfit(response, path, why, page, route) {
352
+ if (page)
353
+ await recordDecline(options.spool.sink, why, route, 'navigation');
348
354
  if (!page || why === 'query')
349
355
  return response;
350
356
  const headers = new Headers(response.headers);
@@ -371,7 +377,7 @@ export function spoolProxy(options) {
371
377
  if (answered)
372
378
  return answered;
373
379
  if (url.pathname === PATHS.worker && request.method === 'GET')
374
- return spool.stub();
380
+ return spool.stub(request);
375
381
  const converting = images !== undefined && imageRequest(images, request);
376
382
  let visitorRewrite = false;
377
383
  let upstream;
@@ -474,16 +480,17 @@ export function spoolProxy(options) {
474
480
  data,
475
481
  principal
476
482
  }, gate);
483
+ const route = hit.route.pattern;
477
484
  if (why)
478
- return unfit(new Response(upstream.body, init), url.pathname, why, page);
485
+ return unfit(new Response(upstream.body, init), url.pathname, why, page, route);
479
486
  const bytes = new Uint8Array(await upstream.arrayBuffer());
480
487
  if (!data && !isUtf8(htmlCharset(upstream.headers, bytes))) {
481
- return unfit(new Response(bytes, init), url.pathname, 'charset', page);
488
+ return unfit(new Response(bytes, init), url.pathname, 'charset', page, route);
482
489
  }
483
490
  const text = new TextDecoder().decode(bytes);
484
491
  headers.delete('content-length');
485
492
  if (text.length > gate.maxBytes) {
486
- return unfit(new Response(text, init), url.pathname, 'size', page);
493
+ return unfit(new Response(text, init), url.pathname, 'size', page, route);
487
494
  }
488
495
  const effective = tags.length > 0 ? tags : [pathTag(url.pathname)];
489
496
  if (request.method === 'GET' && !principal)
@@ -494,7 +501,10 @@ export function spoolProxy(options) {
494
501
  });
495
502
  // a visitor-signal rewrite is not in the copy /.spool/artifact builds, so the worker asks for it
496
503
  const same = !visitorRewrite && !data && !principal;
497
- return spool.decorate(request, new Response(text, init), same ? { assembled: text } : {});
504
+ return spool.decorate(request, new Response(text, init), {
505
+ judged: true,
506
+ ...(same ? { assembled: text } : {})
507
+ });
498
508
  }
499
509
  return Object.assign(handle, {
500
510
  spool,
@@ -0,0 +1,20 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { Spool } from '../server/spool.js';
3
+ import { type StaticOption } from '../vite/index.js';
4
+ export { flattenRoutes, reactRouterPages } from './pages.js';
5
+ export type { PrerenderPaths, ReactRouterSettings, RouteEntryInput, RouteRegistration } from './pages.js';
6
+ /** what `spoolReactRouter` takes */
7
+ export type SpoolReactRouterOptions = {
8
+ /** the instance the app's routes were declared for; the dev server answers from it */
9
+ spool: Spool;
10
+ /** the build-time static tier, as `spoolVite` takes it; on by default, `false` turns it off */
11
+ static?: StaticOption;
12
+ };
13
+ /**
14
+ * The React Router integration for the dev server. It serves the worker script and spool's paths
15
+ * from `spool`, and prints the routes it registered, the ones it left to the network and why. A
16
+ * production response gets spool's envelope and tag from `spool.handle`, which wraps the React
17
+ * Router request handler; the Vite plugin does not reach server-rendered HTML. The client build
18
+ * also publishes the static tier into its output directory (see `static`).
19
+ */
20
+ export declare function spoolReactRouter(options: SpoolReactRouterOptions): Plugin[];