@moq/net 0.4.1 → 0.4.2

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 (173) hide show
  1. package/broadcast.d.ts +21 -7
  2. package/broadcast.d.ts.map +1 -1
  3. package/broadcast.js +38 -16
  4. package/broadcast.js.map +1 -1
  5. package/connection/accept.js +6 -4
  6. package/connection/accept.js.map +1 -1
  7. package/connection/connect.d.ts.map +1 -1
  8. package/connection/connect.js +5 -4
  9. package/connection/connect.js.map +1 -1
  10. package/connection/forward.js +54 -47
  11. package/connection/forward.js.map +1 -1
  12. package/connection/goaway.d.ts +34 -0
  13. package/connection/goaway.d.ts.map +1 -0
  14. package/connection/goaway.js +176 -0
  15. package/connection/goaway.js.map +1 -0
  16. package/connection/handshake.d.ts +4 -2
  17. package/connection/handshake.d.ts.map +1 -1
  18. package/connection/handshake.js +42 -10
  19. package/connection/handshake.js.map +1 -1
  20. package/connection/pool.d.ts +16 -1
  21. package/connection/pool.d.ts.map +1 -1
  22. package/connection/pool.js +32 -10
  23. package/connection/pool.js.map +1 -1
  24. package/connection/reload.d.ts.map +1 -1
  25. package/connection/reload.js +184 -30
  26. package/connection/reload.js.map +1 -1
  27. package/error.d.ts +11 -0
  28. package/error.d.ts.map +1 -1
  29. package/error.js +14 -0
  30. package/error.js.map +1 -1
  31. package/errors.d.ts +1 -1
  32. package/errors.d.ts.map +1 -1
  33. package/errors.js +1 -1
  34. package/errors.js.map +1 -1
  35. package/group.d.ts.map +1 -1
  36. package/group.js +5 -4
  37. package/group.js.map +1 -1
  38. package/hop.d.ts +8 -0
  39. package/hop.d.ts.map +1 -1
  40. package/hop.js +16 -0
  41. package/hop.js.map +1 -1
  42. package/ietf/adapter.d.ts +4 -0
  43. package/ietf/adapter.d.ts.map +1 -1
  44. package/ietf/adapter.js +19 -8
  45. package/ietf/adapter.js.map +1 -1
  46. package/ietf/cluster.d.ts +3 -3
  47. package/ietf/cluster.js +3 -3
  48. package/ietf/cluster.js.map +1 -1
  49. package/ietf/connection.d.ts.map +1 -1
  50. package/ietf/connection.js +110 -37
  51. package/ietf/connection.js.map +1 -1
  52. package/ietf/fetch.d.ts +7 -20
  53. package/ietf/fetch.d.ts.map +1 -1
  54. package/ietf/fetch.js +52 -22
  55. package/ietf/fetch.js.map +1 -1
  56. package/ietf/filter.d.ts +2 -0
  57. package/ietf/filter.d.ts.map +1 -1
  58. package/ietf/filter.js +4 -0
  59. package/ietf/filter.js.map +1 -1
  60. package/ietf/goaway.d.ts +9 -1
  61. package/ietf/goaway.d.ts.map +1 -1
  62. package/ietf/goaway.js +20 -0
  63. package/ietf/goaway.js.map +1 -1
  64. package/ietf/hidden.js +1 -1
  65. package/ietf/hidden.js.map +1 -1
  66. package/ietf/index.d.ts +1 -1
  67. package/ietf/index.d.ts.map +1 -1
  68. package/ietf/index.js +1 -1
  69. package/ietf/index.js.map +1 -1
  70. package/ietf/object.d.ts +7 -6
  71. package/ietf/object.d.ts.map +1 -1
  72. package/ietf/object.js +37 -33
  73. package/ietf/object.js.map +1 -1
  74. package/ietf/parameters.d.ts +7 -0
  75. package/ietf/parameters.d.ts.map +1 -1
  76. package/ietf/parameters.js +62 -12
  77. package/ietf/parameters.js.map +1 -1
  78. package/ietf/publish_namespace.d.ts +2 -2
  79. package/ietf/publish_namespace.js +2 -2
  80. package/ietf/publish_namespace.js.map +1 -1
  81. package/ietf/publisher.js +287 -172
  82. package/ietf/publisher.js.map +1 -1
  83. package/ietf/subscribe.d.ts +7 -1
  84. package/ietf/subscribe.d.ts.map +1 -1
  85. package/ietf/subscribe.js +22 -14
  86. package/ietf/subscribe.js.map +1 -1
  87. package/ietf/subscribe_namespace.d.ts.map +1 -1
  88. package/ietf/subscribe_namespace.js +2 -3
  89. package/ietf/subscribe_namespace.js.map +1 -1
  90. package/ietf/subscriber.js +57 -42
  91. package/ietf/subscriber.js.map +1 -1
  92. package/ietf/token.d.ts +2 -0
  93. package/ietf/token.d.ts.map +1 -0
  94. package/ietf/token.js +99 -0
  95. package/ietf/token.js.map +1 -0
  96. package/ietf/track.d.ts +4 -0
  97. package/ietf/track.d.ts.map +1 -1
  98. package/ietf/track.js +6 -20
  99. package/ietf/track.js.map +1 -1
  100. package/index.d.ts +1 -1
  101. package/index.d.ts.map +1 -1
  102. package/index.js.map +1 -1
  103. package/internal.d.ts +12 -3
  104. package/internal.d.ts.map +1 -1
  105. package/internal.js +32 -0
  106. package/internal.js.map +1 -1
  107. package/lite/announce.d.ts.map +1 -1
  108. package/lite/announce.js +7 -4
  109. package/lite/announce.js.map +1 -1
  110. package/lite/connection.d.ts.map +1 -1
  111. package/lite/connection.js +22 -7
  112. package/lite/connection.js.map +1 -1
  113. package/lite/datagram.d.ts +3 -2
  114. package/lite/datagram.d.ts.map +1 -1
  115. package/lite/datagram.js +7 -8
  116. package/lite/datagram.js.map +1 -1
  117. package/lite/group.d.ts +12 -8
  118. package/lite/group.d.ts.map +1 -1
  119. package/lite/group.js +37 -16
  120. package/lite/group.js.map +1 -1
  121. package/lite/message.d.ts +2 -2
  122. package/lite/message.d.ts.map +1 -1
  123. package/lite/message.js +14 -5
  124. package/lite/message.js.map +1 -1
  125. package/lite/publisher.js +19 -37
  126. package/lite/publisher.js.map +1 -1
  127. package/lite/setup.d.ts +1 -1
  128. package/lite/setup.d.ts.map +1 -1
  129. package/lite/setup.js +22 -19
  130. package/lite/setup.js.map +1 -1
  131. package/lite/subscriber.d.ts.map +1 -1
  132. package/lite/subscriber.js +206 -127
  133. package/lite/subscriber.js.map +1 -1
  134. package/origin.d.ts +9 -1
  135. package/origin.d.ts.map +1 -1
  136. package/origin.js +341 -146
  137. package/origin.js.map +1 -1
  138. package/package.json +2 -2
  139. package/stream.d.ts +77 -12
  140. package/stream.d.ts.map +1 -1
  141. package/stream.js +359 -122
  142. package/stream.js.map +1 -1
  143. package/tail.d.ts +7 -0
  144. package/tail.d.ts.map +1 -1
  145. package/tail.js +68 -22
  146. package/tail.js.map +1 -1
  147. package/track.d.ts +14 -3
  148. package/track.d.ts.map +1 -1
  149. package/track.js +170 -76
  150. package/track.js.map +1 -1
  151. package/util/abort.d.ts +2 -0
  152. package/util/abort.d.ts.map +1 -0
  153. package/util/abort.js +20 -0
  154. package/util/abort.js.map +1 -0
  155. package/util/u64.d.ts +39 -0
  156. package/util/u64.d.ts.map +1 -0
  157. package/util/u64.js +83 -0
  158. package/util/u64.js.map +1 -0
  159. package/util/varint.d.ts +29 -0
  160. package/util/varint.d.ts.map +1 -0
  161. package/util/varint.js +198 -0
  162. package/util/varint.js.map +1 -0
  163. package/varint.d.ts +10 -6
  164. package/varint.d.ts.map +1 -1
  165. package/varint.js +40 -237
  166. package/varint.js.map +1 -1
  167. package/wire.d.ts +17 -3
  168. package/wire.d.ts.map +1 -1
  169. package/wire.js.map +1 -1
  170. package/ietf/control.d.ts +0 -135
  171. package/ietf/control.d.ts.map +0 -1
  172. package/ietf/control.js +0 -242
  173. package/ietf/control.js.map +0 -1
package/origin.js CHANGED
@@ -20,6 +20,136 @@ import { hiddenBelow, hooks, scopeCaptures, scopeHead, scopeOverlaps } from "./i
20
20
  import * as Path from "./path.js";
21
21
  import { registerWire, wireOf } from "./wire.js";
22
22
  export { isAnonymous } from "./hop.js";
23
+ /** The rooted permissions shared by a handle and every route it inserts. */
24
+ class Scope {
25
+ static all = new Scope(Path.empty());
26
+ root;
27
+ allowed;
28
+ constructor(root, allowed) {
29
+ this.root = root;
30
+ this.allowed = allowed;
31
+ }
32
+ narrow(root, patterns) {
33
+ const joined = Path.encode(Path.join(this.root, root));
34
+ const rooted = patterns.rooted(joined);
35
+ const allowed = this.allowed?.intersect(rooted) ?? rooted;
36
+ if (allowed.size === 0)
37
+ throw new Error("origin scopes do not overlap");
38
+ return new Scope(joined, allowed);
39
+ }
40
+ matches(path) {
41
+ return this.allowed?.matches(path) ?? true;
42
+ }
43
+ path(path) {
44
+ const joined = Path.encode(Path.join(this.root, path));
45
+ if (!this.matches(joined))
46
+ throw new Error("path is outside the origin scope");
47
+ return joined;
48
+ }
49
+ prefix(prefix) {
50
+ const joined = Path.encode(Path.join(this.root, prefix));
51
+ if (this.allowed && !this.allowed.overlaps(Path.Pattern.subtree(joined))) {
52
+ throw new Error("prefix is outside the origin scope");
53
+ }
54
+ return joined;
55
+ }
56
+ patterns(pattern = Path.Pattern.all()) {
57
+ const rooted = new Path.Patterns([pattern.rooted(this.root)]);
58
+ return this.allowed?.intersect(rooted) ?? rooted;
59
+ }
60
+ /** Omit nested heads because the outer subscription already carries their routes. */
61
+ heads() {
62
+ if (!this.allowed)
63
+ return [Path.empty()];
64
+ const heads = [...new Set([...this.allowed.rebase(this.root)].map(scopeHead))].sort();
65
+ return heads.filter((head) => !heads.some((other) => other !== head && Path.hasPrefix(other, head)));
66
+ }
67
+ /** The exact paths within this scope, relative to its root. */
68
+ projectPaths(values) {
69
+ if (!values || this === Scope.all)
70
+ return values;
71
+ const out = new Map();
72
+ for (const [path, value] of values) {
73
+ if (!this.matches(path))
74
+ continue;
75
+ const relative = Path.stripPrefix(this.root, path);
76
+ if (relative !== null)
77
+ out.set(relative, value);
78
+ }
79
+ return out;
80
+ }
81
+ /**
82
+ * The advertisements that may serve this scope, relative to its root. Every prefix at or
83
+ * above the root presents as the empty path, most specific first, since that is the order
84
+ * a request beneath the root resolves in.
85
+ */
86
+ projectRoutes(values) {
87
+ if (!values || this === Scope.all)
88
+ return values;
89
+ const out = new Map();
90
+ const covering = [];
91
+ const allowed = this.allowed && [...this.allowed];
92
+ for (const [path, candidates] of values) {
93
+ const relative = Path.stripPrefix(this.root, path);
94
+ const above = relative === null || relative === Path.empty();
95
+ if (above && !Path.hasPrefix(path, this.root))
96
+ continue;
97
+ const visible = candidates
98
+ .filter((value) => !allowed || allowed.some((pattern) => advertOverlaps(value, path, pattern)))
99
+ // The claim moves with the key, so it compares against root-relative requests.
100
+ .map((value) => (value.claim ? { ...value, claim: value.claim.rebase(this.root) } : value));
101
+ if (visible.length === 0)
102
+ continue;
103
+ if (!above) {
104
+ out.set(relative, visible);
105
+ continue;
106
+ }
107
+ // Hold the empty path's place in the order until every covering prefix is known.
108
+ if (covering.length === 0)
109
+ out.set(Path.empty(), []);
110
+ covering.push([path, visible]);
111
+ }
112
+ if (covering.length > 0) {
113
+ covering.sort(([a], [b]) => b.length - a.length);
114
+ out.set(Path.empty(), covering.flatMap(([, visible]) => visible));
115
+ }
116
+ return out;
117
+ }
118
+ }
119
+ /** Whether the route advertised at `prefix` may serve any path `pattern` admits. */
120
+ function advertOverlaps(advert, prefix, pattern) {
121
+ return advert.claim ? advert.claim.overlaps(pattern) : scopeOverlaps(pattern, prefix);
122
+ }
123
+ /**
124
+ * Presents advertised prefixes relative to a root. Every prefix at or above the root
125
+ * collapses to the empty path, where the most specific one wins, since that is the route
126
+ * a request beneath the root resolves through.
127
+ */
128
+ class CoveringRoot {
129
+ #root;
130
+ #covering;
131
+ constructor(root) {
132
+ this.#root = root;
133
+ }
134
+ /** The presented path for `path`, or undefined when it is outside the root or a broader cover. */
135
+ relative(path) {
136
+ const relative = Path.stripPrefix(this.#root, path);
137
+ if (relative !== null && relative !== Path.empty())
138
+ return relative;
139
+ if (relative === null && !Path.hasPrefix(path, this.#root))
140
+ return undefined;
141
+ if (this.#covering !== undefined && !Path.hasPrefix(this.#covering, path))
142
+ return undefined;
143
+ this.#covering = path;
144
+ return Path.empty();
145
+ }
146
+ }
147
+ /** Orders advertisements at one prefix: the better route, then a local broadcast on a tie, then fewer hops. */
148
+ function compareCandidates(a, b) {
149
+ return (compareRoutes(a.route, b.route) ||
150
+ Number(b.exact) - Number(a.exact) ||
151
+ a.route.hops.length - b.route.hops.length);
152
+ }
23
153
  /** Orders two routes by preference: identified before anonymous, then lower warm cost, then lower cold cost. */
24
154
  function compareRoutes(a, b) {
25
155
  const anonymous = Number(isAnonymous(a)) - Number(isAnonymous(b));
@@ -58,6 +188,10 @@ function noCapacity() {
58
188
  }
59
189
  /** A served route from {@link Producer.dynamic}: the queue a handler drains. */
60
190
  class ServeState {
191
+ root;
192
+ constructor(root) {
193
+ this.root = root;
194
+ }
61
195
  queue = new Signal([]);
62
196
  pending = new Map();
63
197
  served = new Map();
@@ -79,42 +213,44 @@ class ServeState {
79
213
  const live = this.served.get(path);
80
214
  if (live && live.closed.peek() === undefined)
81
215
  return;
82
- const request = makeRequest(path, this);
216
+ const request = makeRequest(Path.stripPrefix(this.root, path) ?? Path.empty(), this);
83
217
  this.pending.set(path, request);
84
218
  this.queue.mutate((queue) => {
85
219
  queue.push(request);
86
220
  });
87
221
  }
88
222
  accept(request, front) {
89
- if (this.closed.peek() !== undefined || this.pending.get(request.path) !== request) {
223
+ const path = Path.join(this.root, request.path);
224
+ if (this.closed.peek() !== undefined || this.pending.get(path) !== request) {
90
225
  front.close();
91
226
  return;
92
227
  }
93
- this.pending.delete(request.path);
94
- const existing = this.served.get(request.path);
228
+ this.pending.delete(path);
229
+ const existing = this.served.get(path);
95
230
  if (existing && existing.closed.peek() === undefined) {
96
231
  front.close();
97
- this.onChange(request.path);
232
+ this.onChange(path);
98
233
  this.settled.update((n) => n + 1);
99
234
  return;
100
235
  }
101
- this.served.set(request.path, front);
236
+ this.served.set(path, front);
102
237
  void front.closed.then(() => {
103
- if (this.served.get(request.path) !== front)
238
+ if (this.served.get(path) !== front)
104
239
  return;
105
- this.served.delete(request.path);
106
- this.onChange(request.path);
240
+ this.served.delete(path);
241
+ this.onChange(path);
107
242
  });
108
- this.onChange(request.path);
243
+ this.onChange(path);
109
244
  this.settled.update((n) => n + 1);
110
245
  }
111
246
  reject(request, err) {
112
- if (this.pending.get(request.path) !== request)
247
+ const path = Path.join(this.root, request.path);
248
+ if (this.pending.get(path) !== request)
113
249
  return;
114
- this.pending.delete(request.path);
115
- if (this.demanding.has(request.path))
116
- this.rejected.set(request.path, err);
117
- this.onReject(request.path);
250
+ this.pending.delete(path);
251
+ if (this.demanding.has(path))
252
+ this.rejected.set(path, err);
253
+ this.onReject(path, err);
118
254
  this.settled.update((n) => n + 1);
119
255
  }
120
256
  close(abort) {
@@ -131,7 +267,7 @@ class ServeState {
131
267
  finishRequest(request, err);
132
268
  }
133
269
  for (const [path, front] of this.served) {
134
- front.close(abort);
270
+ front.close();
135
271
  this.onChange(path);
136
272
  }
137
273
  this.served.clear();
@@ -166,12 +302,7 @@ class OriginState {
166
302
  advertisedLocal = new VersionedSignal(new Map());
167
303
  routes = new VersionedSignal(new Map());
168
304
  #snapshotVersion = "";
169
- #snapshot = {
170
- remote: new Map(),
171
- local: new Map(),
172
- routes: new Map(),
173
- visible: new Map(),
174
- };
305
+ #snapshot = { candidates: new Map(), routes: new Map(), visible: new Map() };
175
306
  /** The full route table is built once per mutation, regardless of observer count. */
176
307
  available = new Derived([this.local, this.advertisedLocal, this.routes], () => this.snapshot().routes);
177
308
  /** {@link available} without hidden routes, for unscoped readers that did not opt in. */
@@ -180,34 +311,51 @@ class OriginState {
180
311
  const version = `${this.local.version}/${this.advertisedLocal.version}/${this.routes.version}`;
181
312
  if (version === this.#snapshotVersion)
182
313
  return this.#snapshot;
183
- const remote = new Map();
184
- const local = new Map();
314
+ const candidates = this.candidates();
185
315
  const available = new Map();
186
- for (const [path, routes] of this.routes.peek() ?? []) {
187
- const entry = preferredEntry(routes);
188
- if (!entry)
189
- continue;
190
- const value = { identity: entry.identity, route: entry.route.peek() };
191
- remote.set(path, value);
192
- available.set(path, value.route);
193
- }
194
- for (const [path, front] of this.local.peek() ?? []) {
195
- const routes = this.routes.peek()?.get(path);
196
- if (!this.localWins(path, routes && preferredEntry(routes)))
197
- continue;
198
- const value = { identity: front, route: this.advertisedLocal.peek()?.get(path) ?? Route.default };
199
- local.set(path, value);
200
- available.set(path, value.route);
201
- }
202
316
  const visible = new Map();
203
- for (const [path, route] of available) {
317
+ for (const [path, [best]] of candidates) {
318
+ available.set(path, best.route);
204
319
  if (!hiddenBelow(Path.empty(), path))
205
- visible.set(path, route);
320
+ visible.set(path, best.route);
206
321
  }
207
- this.#snapshot = { remote, local, routes: available, visible };
322
+ this.#snapshot = { candidates, routes: available, visible };
208
323
  this.#snapshotVersion = version;
209
324
  return this.#snapshot;
210
325
  }
326
+ /**
327
+ * Every advertisement per prefix, most preferred first, without the `skip`ped entries.
328
+ * Readers select after filtering by their scope, so a cheaper route they cannot see
329
+ * never hides one they can.
330
+ */
331
+ candidates(skip) {
332
+ const out = new Map();
333
+ for (const [path, entries] of this.routes.peek() ?? []) {
334
+ const list = [];
335
+ for (const entry of entries) {
336
+ if (skip?.(entry))
337
+ continue;
338
+ list.push({ identity: entry.identity, route: entry.route.peek(), claim: entry.claim, exact: false });
339
+ }
340
+ if (list.length > 0)
341
+ out.set(path, list);
342
+ }
343
+ const advertised = this.advertisedLocal.peek();
344
+ for (const [path, front] of this.local.peek() ?? []) {
345
+ const local = { identity: front, route: advertised?.get(path) ?? Route.default, exact: true };
346
+ const list = out.get(path);
347
+ if (list)
348
+ list.push(local);
349
+ else
350
+ out.set(path, [local]);
351
+ }
352
+ for (const list of out.values()) {
353
+ // Stable, so equal routes keep the table's newest-first order.
354
+ if (list.length > 1)
355
+ list.sort(compareCandidates);
356
+ }
357
+ return out;
358
+ }
211
359
  // Originated advertisements sessions should forward: exact-path announces plus
212
360
  // originated dynamics. Identity is the local front or the route entry, so a
213
361
  // republish diffs as retract-then-announce and a re-price as another active.
@@ -242,60 +390,55 @@ class OriginState {
242
390
  return;
243
391
  slot.route.set(this.route(path, slot));
244
392
  }
245
- /** Record that `entry` refused `path` and re-route the requests watching it. */
246
- refuse(path, entry) {
393
+ /**
394
+ * `entry` refused `path` with `err`. A request still serving another source skips the
395
+ * refuser; one with nothing serving ends with `err`.
396
+ */
397
+ refuse(path, entry, err) {
247
398
  const slot = this.requests.peek()?.get(path);
248
399
  if (!slot)
249
400
  return;
250
- slot.refused.add(entry);
251
- slot.route.set(this.route(path, slot));
401
+ // Only the route the request is waiting on speaks for it; a superseded one's answer is moot.
402
+ if (this.bestEntry(path, (candidate) => slot.refused.has(candidate)) !== entry)
403
+ return;
404
+ const serving = slot.route.peek();
405
+ if (serving && serving.closed.peek() === undefined) {
406
+ slot.refused.add(entry);
407
+ slot.route.set(this.route(path, slot));
408
+ return;
409
+ }
410
+ this.requests.mutate((map) => {
411
+ if (map?.get(path) === slot)
412
+ map.delete(path);
413
+ });
414
+ slot.answer?.close();
415
+ slot.answer = undefined;
416
+ slot.route.set(undefined);
417
+ this.releaseMaterialized(path);
418
+ for (const closed of slot.handles)
419
+ closed.set(err);
420
+ slot.handles.clear();
252
421
  }
253
422
  /**
254
423
  * Recompute every open request covered by `prefix`, after a route was inserted or
255
424
  * removed there: a route covers many paths, so a single-path refresh is not enough.
256
- * Materialized broadcasts whose provider changed are released here too, so a
257
- * retracted route's session subscription closes even when nothing reads it again.
425
+ * Every materialized broadcast belongs to an open request, so rerouting them also
426
+ * releases a retracted route's session subscription even when nothing reads it again.
258
427
  */
259
428
  refreshPrefix(prefix) {
260
- const requests = this.requests.peek();
261
- for (const [path, cached] of [...this.materialized]) {
262
- if (!Path.hasPrefix(prefix, path))
263
- continue;
264
- const refused = requests?.get(path)?.refused;
265
- if (cached.entry !== this.bestEntry(path, (entry) => refused?.has(entry) ?? false)) {
266
- this.materialized.delete(path);
267
- cached.front.close();
268
- }
269
- }
270
- for (const [path, slot] of requests ?? []) {
429
+ for (const [path, slot] of this.requests.peek() ?? []) {
271
430
  if (Path.hasPrefix(prefix, path))
272
431
  slot.route.set(this.route(path, slot));
273
432
  }
274
433
  }
275
434
  /** Rebuild the publisher-facing originated table after an advertisement write. */
276
435
  rebuildOriginated() {
277
- const local = this.local.peek();
278
- const advertised = this.advertisedLocal.peek();
279
- const routes = this.routes.peek();
280
- if (!local && !advertised && !routes) {
436
+ if (!this.local.peek() && !this.advertisedLocal.peek() && !this.routes.peek()) {
281
437
  this.originated.set(undefined);
282
438
  return;
283
439
  }
284
- const next = new Map();
285
- for (const [prefix, entries] of routes ?? []) {
286
- const mine = preferredEntry(entries, received);
287
- if (mine)
288
- next.set(prefix, { identity: mine.identity, route: mine.route.peek() });
289
- }
290
440
  // A local broadcast and an originated dynamic at one path compete on cost, as they do for requests.
291
- for (const [path, route] of advertised ?? []) {
292
- const front = local?.get(path);
293
- const entries = routes?.get(path);
294
- if (front && this.localWins(path, entries && preferredEntry(entries, received))) {
295
- next.set(path, { identity: front, route });
296
- }
297
- }
298
- this.originated.set(next);
441
+ this.originated.set(this.candidates(received));
299
442
  }
300
443
  /**
301
444
  * Release the materialized broadcast for `path`, once its last request is gone: the
@@ -316,7 +459,7 @@ class OriginState {
316
459
  for (const [prefix, entries] of this.routes.peek() ?? []) {
317
460
  if (!Path.hasPrefix(prefix, path))
318
461
  continue;
319
- const entry = preferredEntry(entries, skip);
462
+ const entry = preferredEntry(entries, (candidate) => !candidate.scope.matches(path) || (skip?.(candidate) ?? false));
320
463
  if (!entry)
321
464
  continue;
322
465
  if (bestPrefix === undefined || prefix.length > bestPrefix.length) {
@@ -346,8 +489,9 @@ class OriginState {
346
489
  * the best covering route, or the blind answer.
347
490
  *
348
491
  * Materialization is lazy and cached per path: the first request under a route opens
349
- * the providing session's subscription, repeats share it, and a provider change (the
350
- * route retracting, a better session taking over) swaps it out.
492
+ * the providing session's subscription and repeats share it. A better route is made
493
+ * before the old one breaks: the current front keeps serving until the new route
494
+ * answers (then swaps) or refuses (then is skipped). A retracted route swaps at once.
351
495
  */
352
496
  route(path, slot) {
353
497
  const entry = this.bestEntry(path, (candidate) => slot.refused.has(candidate));
@@ -357,25 +501,25 @@ class OriginState {
357
501
  this.releaseMaterialized(path);
358
502
  return local;
359
503
  }
360
- const cached = this.materialized.get(path);
361
- if (cached && cached.entry === entry) {
362
- if (cached.front.closed.peek() === undefined)
363
- return cached.front;
364
- this.materialized.delete(path);
365
- }
366
- else if (cached) {
504
+ let cached = this.materialized.get(path);
505
+ if (cached && cached.front.closed.peek() !== undefined) {
367
506
  this.materialized.delete(path);
368
- cached.front.close();
507
+ cached = undefined;
369
508
  }
370
- if (!entry?.server)
509
+ if (cached && cached.entry === entry)
510
+ return cached.front;
511
+ if (!entry?.server) {
512
+ this.releaseMaterialized(path);
371
513
  return slot.answer;
514
+ }
372
515
  const served = entry.server.served.get(path);
373
516
  if (served && served.closed.peek() === undefined) {
517
+ cached?.front.close();
374
518
  this.materialized.set(path, { entry, front: served });
375
519
  return served;
376
520
  }
377
521
  entry.server.enqueue(path);
378
- return undefined;
522
+ return cached?.front;
379
523
  }
380
524
  }
381
525
  /**
@@ -395,24 +539,41 @@ class OriginState {
395
539
  */
396
540
  export class Producer {
397
541
  #state = new OriginState();
542
+ #scope = Scope.all;
543
+ #requests;
398
544
  // The reader backing the passthroughs, so holding a Producer never requires the
399
545
  // consume().x() stutter for everyday reads. One instance, so `discovery` keeps its
400
546
  // identity across reads.
401
- #reader = makeConsumer(this.#state);
547
+ #reader = makeConsumer(this.#state, this.#scope);
402
548
  constructor() {
403
549
  const thisProducer = this;
404
550
  registerWire(this, {
405
551
  receive: (prefix, route) => this.#receive(prefix, route),
552
+ interests: () => this.#scope.heads(),
553
+ accepts: (prefix) => !this.#scope.allowed ||
554
+ this.#scope.allowed.overlaps(Path.Pattern.subtree(Path.join(this.#scope.root, prefix))),
406
555
  attach: (discovery) => this.#attach(discovery),
407
556
  expect: () => this.#expect(),
408
557
  get requests() {
409
- return thisProducer.#state.requests;
558
+ if (thisProducer.#scope === Scope.all)
559
+ return thisProducer.#state.requests;
560
+ thisProducer.#requests ??= new Derived([thisProducer.#state.requests], (requests) => thisProducer.#scope.projectPaths(requests));
561
+ return thisProducer.#requests;
410
562
  },
411
563
  changed: () => this.#changed(),
412
- answer: (path, front) => this.#answer(path, front),
564
+ answer: (path, front) => this.#answer(this.#scope.path(path), front),
413
565
  routes: (path) => wireOf(this.#reader).routes(path),
414
566
  });
415
567
  }
568
+ /** Narrow this handle to patterns beneath root, presenting paths relative to that root. */
569
+ scope(root, patterns) {
570
+ const scope = this.#scope.narrow(root, patterns);
571
+ const producer = new Producer();
572
+ producer.#state = this.#state;
573
+ producer.#scope = scope;
574
+ producer.#reader = makeConsumer(this.#state, scope);
575
+ return producer;
576
+ }
416
577
  /**
417
578
  * Settles once the origin closes: `null` on a clean close, or the abort {@link Error}.
418
579
  * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
@@ -434,10 +595,12 @@ export class Producer {
434
595
  * a remote route at the same path on cost, winning ties.
435
596
  */
436
597
  createBroadcast(path) {
598
+ path = this.#scope.path(path);
437
599
  const created = this.#state.created;
438
600
  if (!created)
439
601
  throw new Error("origin is closed");
440
602
  const producer = new broadcast.Producer();
603
+ hooks.stampPath(producer, path);
441
604
  const front = producer.consume();
442
605
  hooks.attachAnnouncer(producer, {
443
606
  announce: (route) => this.#advertiseExact(path, front, route),
@@ -509,15 +672,18 @@ export class Producer {
509
672
  return this.#insertRoute(prefix, Route.normalize(route), false);
510
673
  }
511
674
  #insertRoute(prefix, route, originated) {
512
- const server = new ServeState();
675
+ prefix = this.#scope.prefix(prefix);
676
+ const server = new ServeState(this.#scope.root);
513
677
  server.onChange = (path) => this.#state.refresh(path);
514
678
  const entry = {
515
679
  identity: {},
680
+ scope: this.#scope,
681
+ claim: this.#scope.allowed?.intersect(new Path.Patterns([Path.Pattern.subtree(prefix)])),
516
682
  route: new Signal(route),
517
683
  originated,
518
684
  server,
519
685
  };
520
- server.onReject = (path) => this.#state.refuse(path, entry);
686
+ server.onReject = (path, err) => this.#state.refuse(path, entry, err);
521
687
  let closed = false;
522
688
  this.#state.routes.mutate((routes) => {
523
689
  if (!routes) {
@@ -646,7 +812,7 @@ export class Producer {
646
812
  }
647
813
  /** A read handle for this origin, the side a connection's `publish` option borrows. */
648
814
  consume() {
649
- return makeConsumer(this.#state);
815
+ return makeConsumer(this.#state, this.#scope);
650
816
  }
651
817
  /** Whether every attached session announces into the table; see {@link Consumer.discovery}. */
652
818
  get discovery() {
@@ -670,7 +836,7 @@ export class Producer {
670
836
  return;
671
837
  this.#state.closed.set(abort ?? null);
672
838
  for (const front of this.#state.created?.values() ?? []) {
673
- front.close(abort);
839
+ front.close();
674
840
  }
675
841
  this.#state.created = undefined;
676
842
  this.#state.local.update(() => undefined);
@@ -741,25 +907,32 @@ export class Requesting {
741
907
  * set, and false while a connection is still coming up, so the ordinary page-load window
742
908
  * before the first handshake reads as pending rather than as a missing broadcast. Waiting
743
909
  * on this is futile by definition; wait for an announcement instead, via the origin's
744
- * `announced`.
910
+ * `announced`. True once the request is refused.
745
911
  */
746
912
  unroutable;
913
+ /**
914
+ * Settles with the error a route's handler refused the path with, or `null` once you
915
+ * {@link close} the request. A refusal is final: no other route is asked, and a fresh
916
+ * request is needed to try again.
917
+ */
918
+ closed;
747
919
  #dispose;
748
- #closed = false;
749
- constructor(path, active, unroutable, dispose) {
920
+ #disposed = false;
921
+ constructor(path, active, unroutable, closed, dispose) {
750
922
  this.path = path;
751
923
  this.active = active;
752
924
  this.unroutable = unroutable;
925
+ this.closed = closed;
753
926
  this.#dispose = dispose;
754
927
  }
755
928
  static {
756
- makeRequesting = (path, active, unroutable, dispose) => new Requesting(path, active, unroutable, dispose);
929
+ makeRequesting = (path, active, unroutable, closed, dispose) => new Requesting(path, active, unroutable, closed, dispose);
757
930
  }
758
931
  /** Withdraw the request. The path stays routed for any other open request. Idempotent. */
759
932
  close() {
760
- if (this.#closed)
933
+ if (this.#disposed)
761
934
  return;
762
- this.#closed = true;
935
+ this.#disposed = true;
763
936
  this.#dispose();
764
937
  }
765
938
  }
@@ -774,26 +947,26 @@ export class Requesting {
774
947
  */
775
948
  export class Consumer {
776
949
  #state;
777
- constructor(state) {
950
+ #scope;
951
+ constructor(state, scope) {
778
952
  this.#state = state;
953
+ this.#scope = scope;
779
954
  // True only when every attached session announces. One session that cannot means the
780
955
  // table is an incomplete picture, so a consumer gated on it has to keep its blind
781
956
  // fallback: the paths only that session carries never reach the table at all.
782
957
  this.#discovery = new Derived([state.sessions], ({ total, discovery }) => total === 0 ? undefined : discovery === total);
783
958
  registerWire(this, {
784
- routes: (path) => this.#routes(path),
785
- get broadcasts() {
786
- return state.local;
787
- },
788
- get advertised() {
789
- return state.originated;
790
- },
791
- local: (path) => this.#local(path),
792
- demand: (path) => this.#demand(path),
959
+ routes: (path) => this.#routes(scope.path(path)),
960
+ broadcasts: scope === Scope.all ? state.local : new Derived([state.local], (local) => scope.projectPaths(local)),
961
+ advertised: scope === Scope.all
962
+ ? state.originated
963
+ : new Derived([state.originated], (routes) => scope.projectRoutes(routes)),
964
+ local: (path) => this.#local(scope.path(path)),
965
+ demand: (path) => this.#demand(scope.path(path)),
793
966
  });
794
967
  }
795
968
  static {
796
- makeConsumer = (state) => new Consumer(state);
969
+ makeConsumer = (state, scope) => new Consumer(state, scope);
797
970
  }
798
971
  /** Settles once the origin closes; see {@link Producer.closed}. */
799
972
  get closed() {
@@ -851,10 +1024,13 @@ export class Consumer {
851
1024
  * feeds from more than one connection.
852
1025
  */
853
1026
  request(path, options = {}) {
1027
+ const relative = path;
1028
+ path = this.#scope.path(path);
854
1029
  const requests = this.#state.requests.peek();
855
1030
  if (!requests) {
856
1031
  // Closed origin: a request that can never resolve, and says so.
857
- return makeRequesting(path, new Signal(undefined), getter(true), () => { });
1032
+ const closed = new Once();
1033
+ return makeRequesting(relative, new Signal(undefined), getter(true), closed, () => closed.set(null));
858
1034
  }
859
1035
  let slot = requests.get(path);
860
1036
  if (!slot) {
@@ -865,8 +1041,8 @@ export class Consumer {
865
1041
  // notify nobody.
866
1042
  const refused = new Set();
867
1043
  const created = {
868
- count: 0,
869
1044
  blind: 0,
1045
+ handles: new Set(),
870
1046
  refused,
871
1047
  route: new Signal(this.#state.route(path, { refused })),
872
1048
  };
@@ -875,7 +1051,8 @@ export class Consumer {
875
1051
  map?.set(path, created);
876
1052
  });
877
1053
  }
878
- slot.count += 1;
1054
+ const closed = new Once();
1055
+ slot.handles.add(closed);
879
1056
  let blind = !options.announced || this.#discovery.peek() === false;
880
1057
  if (blind)
881
1058
  slot.blind += 1;
@@ -911,6 +1088,8 @@ export class Consumer {
911
1088
  const previous = handle;
912
1089
  source = front;
913
1090
  handle = front?.clone();
1091
+ if (handle)
1092
+ hooks.stampPath(handle, relative);
914
1093
  previous?.close();
915
1094
  }
916
1095
  return handle;
@@ -925,8 +1104,8 @@ export class Consumer {
925
1104
  // Only meaningful while nothing is routed, so it reads the route rather than `active`:
926
1105
  // the two cannot disagree, since a routed path always has an answerer-independent
927
1106
  // answer.
928
- const unroutable = new Derived([route, this.#state.answerers], (front, answerers) => !front && answerers === 0);
929
- return makeRequesting(path, active, unroutable, () => {
1107
+ const unroutable = new Derived([route, this.#state.answerers, closed], (front, answerers, ended) => ended !== undefined || (!front && answerers === 0));
1108
+ return makeRequesting(relative, active, unroutable, closed, () => {
930
1109
  // Releases this request's handle; the route itself belongs to the table.
931
1110
  released = true;
932
1111
  unsubscribeDiscovery();
@@ -934,21 +1113,25 @@ export class Consumer {
934
1113
  handle?.close();
935
1114
  handle = undefined;
936
1115
  source = undefined;
937
- taken.count -= 1;
1116
+ taken.handles.delete(closed);
1117
+ if (closed.peek() === undefined)
1118
+ closed.set(null);
938
1119
  if (blind)
939
1120
  taken.blind -= 1;
940
1121
  this.#state.requests.mutate(() => { });
941
- if (taken.count > 0)
1122
+ if (taken.handles.size > 0)
942
1123
  return;
943
1124
  // Defer the teardown a microtask: an effect whose rerun was triggered by the
944
1125
  // answer resolving closes its old request and takes a new one in the same tick,
945
1126
  // and tearing down in between would drop the answer it is about to read.
946
1127
  queueMicrotask(() => {
947
- if (taken.count > 0)
1128
+ if (taken.handles.size > 0)
1129
+ return;
1130
+ // A refused slot already tore itself down, and the path may hold a newer one.
1131
+ if (this.#state.requests.peek()?.get(path) !== taken)
948
1132
  return;
949
1133
  this.#state.requests.mutate((map) => {
950
- if (map?.get(path) === taken)
951
- map.delete(path);
1134
+ map?.delete(path);
952
1135
  });
953
1136
  taken.answer?.close();
954
1137
  taken.answer = undefined;
@@ -966,11 +1149,12 @@ export class Consumer {
966
1149
  */
967
1150
  broadcasts(scope, options) {
968
1151
  const hidden = options?.hidden ?? false;
969
- if (!scope)
1152
+ if (!scope && this.#scope === Scope.all)
970
1153
  return hidden ? this.#state.available : this.#state.visible;
1154
+ const patterns = this.#scope.patterns(scope);
971
1155
  return new Derived([this.#state.available], () => {
972
1156
  const routes = new Map();
973
- for (const [path, entry] of this.#listed(scope, hidden))
1157
+ for (const [path, entry] of this.#listed(patterns, hidden))
974
1158
  routes.set(path, entry.route);
975
1159
  return routes;
976
1160
  });
@@ -985,31 +1169,42 @@ export class Consumer {
985
1169
  */
986
1170
  announced(scope = Path.Pattern.all(), options) {
987
1171
  const producer = new announce.Producer();
988
- void this.#runAnnounced(producer, scope, options?.hidden ?? false);
1172
+ void this.#runAnnounced(producer, this.#scope.patterns(scope), options?.hidden ?? false);
989
1173
  return producer.consume();
990
1174
  }
991
1175
  /** One snapshot shared by map readers and announcement-stream diffing. */
992
- #listed(scope, hidden) {
1176
+ #listed(patterns, hidden) {
993
1177
  const next = new Map();
994
- const { remote, local } = this.#state.snapshot();
995
- const head = scopeHead(scope);
996
- for (const [path, entry] of remote) {
997
- if (!scopeOverlaps(scope, path))
998
- continue;
999
- if (!hidden && hiddenBelow(head, path))
1000
- continue;
1001
- next.set(path, { identity: entry.identity, route: entry.route, captures: scopeCaptures(scope, path) });
1002
- }
1003
- for (const [path, entry] of local) {
1004
- if (!scope.matches(path))
1178
+ const covering = new CoveringRoot(this.#scope.root);
1179
+ const scopes = [...patterns]
1180
+ .sort((a, b) => Path.compareSpecificity(b.specificity(), a.specificity()))
1181
+ .map((pattern) => ({ pattern, head: scopeHead(pattern) }));
1182
+ for (const [path, candidates] of this.#state.snapshot().candidates) {
1183
+ // The first candidate this reader can see wins, since the preferred one overall may not be.
1184
+ let entry;
1185
+ let scope;
1186
+ for (const candidate of candidates) {
1187
+ scope = scopes.find(({ pattern, head }) => (candidate.exact ? pattern.matches(path) : advertOverlaps(candidate, path, pattern)) &&
1188
+ (hidden || !hiddenBelow(head, path)));
1189
+ if (scope) {
1190
+ entry = candidate;
1191
+ break;
1192
+ }
1193
+ }
1194
+ if (!entry || !scope)
1005
1195
  continue;
1006
- if (!hidden && hiddenBelow(head, path))
1196
+ const relative = covering.relative(path);
1197
+ if (relative === undefined)
1007
1198
  continue;
1008
- next.set(path, { identity: entry.identity, route: entry.route, captures: scopeCaptures(scope, path) });
1199
+ next.set(relative, {
1200
+ identity: entry.identity,
1201
+ route: entry.route,
1202
+ captures: scopeCaptures(scope.pattern, path),
1203
+ });
1009
1204
  }
1010
1205
  return next;
1011
1206
  }
1012
- async #runAnnounced(producer, scope, hidden) {
1207
+ async #runAnnounced(producer, patterns, hidden) {
1013
1208
  // Keyed by the presented path (from the origin, not the scope), valued by identity
1014
1209
  // plus route. Diffing identity rather than mere presence means a republish emits a
1015
1210
  // retraction then a fresh announcement; a re-price of the same identity emits an
@@ -1022,7 +1217,7 @@ export class Consumer {
1022
1217
  const routes = this.#state.routes.peek();
1023
1218
  if (local === undefined && advertisedLocal === undefined && routes === undefined)
1024
1219
  break;
1025
- const next = this.#listed(scope, hidden);
1220
+ const next = this.#listed(patterns, hidden);
1026
1221
  for (const [path, snap] of active) {
1027
1222
  const cur = next.get(path);
1028
1223
  if (!cur || cur.identity !== snap.identity)
@@ -1149,7 +1344,7 @@ export class Dynamic {
1149
1344
  #retract;
1150
1345
  #closed = false;
1151
1346
  constructor(prefix, entry, state, retract) {
1152
- this.prefix = prefix;
1347
+ this.prefix = Path.stripPrefix(entry.scope.root, prefix) ?? Path.empty();
1153
1348
  this.#entry = entry;
1154
1349
  this.#state = state;
1155
1350
  this.#retract = retract;
@@ -1163,7 +1358,7 @@ export class Dynamic {
1163
1358
  throw new Error("dynamic is closed");
1164
1359
  this.#entry.route.set(Route.normalize(route));
1165
1360
  this.#state.rebuildOriginated();
1166
- this.#state.refreshPrefix(this.prefix);
1361
+ this.#state.refreshPrefix(Path.join(this.#entry.scope.root, this.prefix));
1167
1362
  this.#state.routes.mutate(() => { });
1168
1363
  }
1169
1364
  /** Retract the route and reject anything still waiting. Idempotent. */