@yaks/reach 0.0.0-stage → 0.2.36

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.
package/mod.ts ADDED
@@ -0,0 +1,1520 @@
1
+ // A graph made of graphs. An entity is one eid wherever it is kept, so the
2
+ // recipe one member holds and the loan another holds about it are one entity
3
+ // wearing two components. A read that names no member is therefore one
4
+ // question asked of every member, answered as one bundle per eid; a write is
5
+ // split by component and each part sent to the member that word lives in.
6
+ //
7
+ // A member is a value: it reads a line, applies bundles, and says its own
8
+ // words. Where it is (a Durable Object, a remote host, a graph in memory) is
9
+ // the caller's business; everything here is the fan-out, the split a mixed
10
+ // filter needs, the merge, and the routing of a write.
11
+ //
12
+ // The split is here and not in a member: a member refuses a word it never
13
+ // planted ("unknown prop: .book"), so `.recipe&.book` cannot be asked of
14
+ // either whole. The line is cut on its own `&` seams, one part per component
15
+ // named, each part asked of every member that speaks it, and the eids in
16
+ // common are the answer. For a disjunction, the alternatives contribute
17
+ // their union of eids. Every member reads ordinary filter lines.
18
+ //
19
+ // Two things this does that no single member can. An order over a spanning
20
+ // answer is settled over the merged bundles, with @yaks/match: each member can
21
+ // only order what it holds. And the vocabulary is the union of what the
22
+ // members declare, the language a merged bundle is written in.
23
+ import { archetypes } from '@yaks/archetype'
24
+ import { edges, stated as statedEdges } from '@yaks/edge'
25
+ import type { Bundle, Entity, Projection } from 'jsr:@yaks/graph@0.2.36'
26
+ import { callerAlias, dead } from '@yaks/graph/bundle'
27
+ import { status } from '@yaks/graph/errors'
28
+ import { derivedEid, identities, isAlias, resolve } from '@yaks/graph/identity'
29
+ import { flat, projection } from '@yaks/graph/read'
30
+ import { keys } from '@yaks/key'
31
+ import { matcher, rows } from '@yaks/match'
32
+ import {
33
+ and,
34
+ bareLine,
35
+ type Clause,
36
+ directive,
37
+ parse,
38
+ stringify,
39
+ tokens,
40
+ windowOf,
41
+ } from '@yaks/query'
42
+ import { CallError } from '@yaks/tools/errors'
43
+ import {
44
+ loadVocab,
45
+ type PropSchema,
46
+ type Vocab,
47
+ type VocabDoc,
48
+ } from '@yaks/vocab'
49
+
50
+ /** One graph in the composition. */
51
+ export type Member = {
52
+ /** What a merged bundle names as a component's home (`_stores`). */
53
+ at: string
54
+ /** What a caller calls it when asked to choose one. Defaults to `at`. */
55
+ name?: string
56
+ /** The members whose words agree on their shapes: a word two spaces
57
+ * declare with different properties is two words (`apartIn`). Defaults to
58
+ * `at`. */
59
+ space?: string
60
+ /** The bundles a filter line selects, or a reduction (`{count}`). `said`
61
+ * is the line the caller asked, which this member's answer is shaped by
62
+ * when it was asked only a part of it. Throws to refuse. */
63
+ read: (
64
+ line: string,
65
+ opts?: { said?: string; live?: boolean },
66
+ ) => Promise<unknown>
67
+ /** The batch as applied; `check` rehearses it and keeps nothing. */
68
+ apply: (bundles: Bundle[], check: boolean) => Promise<Bundle[]>
69
+ /** The words this member declares as its own. */
70
+ vocab: () => Promise<VocabDoc>
71
+ /** Watch a line live: `sink` is sent each frame the answer moves by, in
72
+ * the frames @yaks/api's subscriptions speak. Returns what stops it. A
73
+ * member without one is read, and never heard from again. */
74
+ watch?: (line: string, sink: (frame: Frame) => void) => () => void
75
+ /** A copy that takes only the writes aimed at it. */
76
+ sandboxed?: boolean
77
+ /** A graph other than the caller's own, such as another host: a bundle
78
+ * wearing any piece of it says so in `_stores`, and names it as the home of
79
+ * `entity` when the spine came from it, since a `num` is its store's own. */
80
+ remote?: boolean
81
+ }
82
+
83
+ /** Where a bundle's `entity`, and so its `num`, lives when that is a remote
84
+ * member rather than the caller's own graph (`_stores.entity`). A `num` is
85
+ * its store's own, so one from elsewhere is shown with its home.
86
+ *
87
+ * ```ts
88
+ * import { homeOf } from '@yaks/reach'
89
+ * import { assertEquals } from '@std/assert'
90
+ *
91
+ * let eid = 'a3f19c02-4b00-4000-8000-000000000001'
92
+ * assertEquals(
93
+ * homeOf({ entity: { eid, num: 12 }, _stores: { entity: 'yaks.app' } }),
94
+ * 'yaks.app',
95
+ * )
96
+ * assertEquals(homeOf({ entity: { eid, num: 5 } }), undefined)
97
+ * ```
98
+ */
99
+ export let homeOf = (b: Bundle): string | undefined => {
100
+ let at = (b._stores as Record<string, unknown> | undefined)?.entity
101
+ return typeof at == 'string' ? at : undefined
102
+ }
103
+
104
+ /** A frame of a live watch, as @yaks/api's subscriptions send one: rows
105
+ * (all of them with `reset`) and the eids `gone`, a reduction (`count`,
106
+ * `tally`, `distinct`), or the error the line was refused with. `revision`
107
+ * is the store's revision the rows were read at, and `since` the one the
108
+ * frame before it said: one number from a member, and from a watch, each
109
+ * member's under its `at` ({@link named}). */
110
+ export type Frame = {
111
+ bundles?: Bundle[]
112
+ gone?: string[]
113
+ reset?: boolean
114
+ refused?: unknown
115
+ revision?: number | Record<string, number>
116
+ since?: number | Record<string, number>
117
+ [more: string]: unknown
118
+ }
119
+
120
+ /** A member's frame as a watch says it: its revisions under the member's
121
+ * `at`, since a revision orders one store's frames and no other's.
122
+ *
123
+ * ```ts
124
+ * import { named } from '@yaks/reach'
125
+ * import { assertEquals } from '@std/assert'
126
+ *
127
+ * assertEquals(
128
+ * named({ bundles: [], revision: 7, since: 6 }, 'home/books'),
129
+ * { bundles: [], revision: { 'home/books': 7 }, since: { 'home/books': 6 } },
130
+ * )
131
+ * ```
132
+ */
133
+ export let named = (frame: Frame, at: string): Frame => {
134
+ let out = { ...frame }
135
+ if (typeof frame.revision == 'number') out.revision = { [at]: frame.revision }
136
+ if (typeof frame.since == 'number') out.since = { [at]: frame.since }
137
+ return out
138
+ }
139
+
140
+ /** The language every member shares, and how the composition reports. */
141
+ export type Words = {
142
+ /** The words every member speaks. A word outside it was declared by a
143
+ * member, which makes it the most specific thing said about a row. */
144
+ core: Vocab
145
+ /** The members' own words as one vocabulary: `defs` is each word once,
146
+ * from its first declarer, and `docs` is every member's document. Defaults
147
+ * to `core` with `defs` beneath it. */
148
+ union?: (defs: Record<string, PropSchema>, docs: VocabDoc[]) => Vocab
149
+ /** Whether a member's answer to `line` leaves `comp` off (a listing rule's
150
+ * stamps), so a component fetched only to order by leaves with it. */
151
+ hidden?: (comp: string, line: string) => boolean
152
+ /** A member left out of a read because it refused or failed. */
153
+ silent?: (error: unknown, member: Member) => void
154
+ /** Whether a member's failure fails the whole read rather than leaving the
155
+ * member out: it holds rows it could not send, such as a page over its
156
+ * read budget, so an answer without them would be short. */
157
+ stops?: (error: unknown) => boolean
158
+ }
159
+
160
+ /** A refusal of the caller's own line. */
161
+ let refuse = (text: string) => new CallError('arguments', text)
162
+
163
+ // A member answering 503 is not one with nothing to say: the caller is told,
164
+ // and asks again.
165
+ let down = (e: unknown) =>
166
+ e != null && typeof e == 'object' && 'status' in e && e.status === 503
167
+
168
+ // An error a vocabulary raised reading the caller's line is that line refused.
169
+ let refusing = (e: unknown) =>
170
+ status(e) < 500 ? refuse((e as Error).message) : e
171
+
172
+ // The words a dotted segment can open with that belong to the whole line: the
173
+ // grammar's own riders, its aggregates, and the spine every member's entities
174
+ // share (`.entity.eid=`, which is what `id=` becomes). `.edges`, a retired
175
+ // rider that parses to nothing, is still the line's rather than a component.
176
+ // Everything else after a dot is a component, and it is the segment's part.
177
+ let RIDERS = ['order', 'near', 'limit', 'after', 'edges', 'kind', 'fields']
178
+ let AGGS = ['count', 'distinct', 'tally']
179
+ let LINE = ['entity', ...RIDERS, ...AGGS]
180
+
181
+ let firstWord = (seg: string) => /^[.!?]([a-z0-9_]+)/i.exec(seg)?.[1] ?? ''
182
+
183
+ // The part a segment belongs to: the component it names, or '' for a segment
184
+ // that is the whole line's business — `id=`, `limit=`, a bare word, a rider.
185
+ let partOf = (seg: string) => {
186
+ if (!/^[.!?]/.test(seg)) return ''
187
+ let word = firstWord(seg)
188
+ return LINE.includes(word) ? '' : word
189
+ }
190
+
191
+ // Groups and quoted values stay whole. An OR run also stays one part: its
192
+ // alternatives are asked together, rather than intersected as separate parts.
193
+ let segsOf = (line: string): string[] => {
194
+ let segs: string[] = []
195
+ for (let tok of tokens(bareLine(line))) {
196
+ let last = segs.length - 1
197
+ if (last >= 0 && (tok == '|' || segs[last].endsWith('|'))) {
198
+ segs[last] += tok
199
+ } else segs.push(tok)
200
+ }
201
+ return segs
202
+ }
203
+
204
+ let aggOf = (line: string) =>
205
+ segsOf(line).map(firstWord).find((w) => AGGS.includes(w))
206
+
207
+ let limitOf = (line: string) =>
208
+ Number(segsOf(line).find((s) => /^\.?limit=/.test(s))?.split('=')[1]) ||
209
+ undefined
210
+
211
+ // Does this line ask for every component? `*` is a directive in the grammar
212
+ // (@yaks/query), not a word cut out of the line, so this asks the parser
213
+ // rather than the text, the same question @yaks/graph `wanted` asks. A line
214
+ // handed over in pieces need not parse; one that does not asks for nothing
215
+ // wider than what it named.
216
+ let every = (line: string) => {
217
+ try {
218
+ return parse(line).clauses.some((c) => c.kind == 'every')
219
+ } catch {
220
+ return false
221
+ }
222
+ }
223
+
224
+ // The directives that settle a sequence rather than a set. An `.order=` moves
225
+ // that decision past the merge: the property it names may be a word only
226
+ // another member speaks, so no member can be asked to sort by it, and none may
227
+ // cut its answer short, or the rows the order wanted would be gone before the
228
+ // merge saw them. So when the caller asks for an order, these leave the
229
+ // per-member lines and @yaks/match settles them once, over the merged bundles.
230
+ let ORDERS = ['order', 'limit', 'after']
231
+
232
+ let orderWord = (seg: string) => {
233
+ let w = /^\.([a-z0-9_]+)(?:\[last\])?=/i.exec(seg)?.[1] ?? ''
234
+ return ORDERS.includes(w) ? w : ''
235
+ }
236
+
237
+ type Window = { segs: string[]; order: boolean }
238
+
239
+ let window = (line: string): Window => {
240
+ let segs = segsOf(line).filter(orderWord)
241
+ return { segs, order: segs.some((s) => orderWord(s) == 'order') }
242
+ }
243
+
244
+ // The order and its window, over the merged bundles, in the union's words.
245
+ // @yaks/match evaluates the same grammar a store compiles to SQL, so a line
246
+ // ordered here and one ordered in one member agree. A directive this
247
+ // vocabulary cannot answer exactly refuses the caller's line, as a single
248
+ // member would: an answer quietly in some other order would be worse.
249
+ let sorting = (
250
+ orders: Window,
251
+ vocab: Vocab,
252
+ ): (bundles: Bundle[]) => Bundle[] => {
253
+ if (!orders.order) return (bundles) => bundles
254
+ try {
255
+ return matcher(orders.segs.join('&'), vocab)
256
+ } catch (e) {
257
+ throw refusing(e)
258
+ }
259
+ }
260
+
261
+ // The component an order reads. A store sorts by a column it never answers,
262
+ // but the merge can only sort what it holds, so this rides the gather whether
263
+ // or not the caller asked to see it, and leaves before the answer does
264
+ // (`unasked`).
265
+ let orderedBy = (orders: Window, vocab: Vocab): string | null => {
266
+ let seg = orders.segs.find((s) => orderWord(s) == 'order')
267
+ let path = seg?.slice(seg.indexOf('=') + 1).replace(/^-/, '')
268
+ return path ? vocab.aim(path)[0]?.comp ?? null : null
269
+ }
270
+
271
+ /** A filter line cut into parts: the segments that name each component, and
272
+ * the ones that ride with every part. A part whose every segment is a request
273
+ * (`?loan`) narrows nothing: it asks for the component, so it is fetched and
274
+ * never intersected.
275
+ *
276
+ * ```ts
277
+ * import { assertEquals } from '@std/assert'
278
+ * let { parts, global } = split('.book&?loan&.limit=5')
279
+ * assertEquals([...parts.keys()], ['book', 'loan'])
280
+ * assertEquals(parts.get('loan')?.asks, true)
281
+ * assertEquals(global, ['.limit=5'])
282
+ * ```
283
+ */
284
+ export let split = (line: string): {
285
+ parts: Map<string, { segs: string[]; asks: boolean }>
286
+ global: string[]
287
+ } => {
288
+ let parts = new Map<string, { segs: string[]; asks: boolean }>()
289
+ let global: string[] = []
290
+ for (let seg of segsOf(line)) {
291
+ let key = partOf(seg)
292
+ if (!key) global.push(seg)
293
+ else {
294
+ let one = parts.get(key) ?? { segs: [], asks: true }
295
+ one.segs.push(seg)
296
+ one.asks &&= seg.startsWith('?')
297
+ parts.set(key, one)
298
+ }
299
+ }
300
+ return { parts, global }
301
+ }
302
+
303
+ // Only the head of a path is in the store being asked. A reverse clause's
304
+ // child condition is about a different row, not another top-level filter.
305
+ let head = (c: Clause): string | undefined => {
306
+ if (c.kind != 'pred' && c.kind != 'walk') return
307
+ let name = c.path[0]
308
+ if (!LINE.includes(name)) return name
309
+ }
310
+
311
+ let namesIn = (c: Clause): string[] => {
312
+ if (c.kind == 'or' || c.kind == 'and') return c.clauses.flatMap(namesIn)
313
+ let name = head(c)
314
+ return name ? [name] : []
315
+ }
316
+
317
+ let disjunction = (line: string) => {
318
+ if (!line.includes('|')) return
319
+ let q = parse(bareLine(line))
320
+ if (q.clauses.some((c) => c.kind == 'or')) return q
321
+ }
322
+
323
+ /** The words a line names that another member keeps (`uses`, word → its
324
+ * home), in the line's order.
325
+ *
326
+ * ```ts
327
+ * import { assertEquals } from '@std/assert'
328
+ * assertEquals(borrowed('.fire&?doc&.ash', { ash: 'a', fire: 'b' }), [
329
+ * 'fire',
330
+ * 'ash',
331
+ * ])
332
+ * assertEquals(borrowed('.constructor', {}), [])
333
+ * ```
334
+ */
335
+ export let borrowed = (
336
+ line: string,
337
+ uses: Record<string, string>,
338
+ ): string[] => {
339
+ let q
340
+ try {
341
+ q = disjunction(line)
342
+ } catch {
343
+ // Syntax refusals still come from the read door.
344
+ }
345
+ let names = q ? new Set(namesIn(q)) : split(line).parts.keys()
346
+ return [...names].filter((name) => Object.hasOwn(uses, name))
347
+ }
348
+
349
+ /** Whether a line names a word another member keeps, which one member cannot
350
+ * answer alone.
351
+ *
352
+ * ```ts
353
+ * import { assertEquals } from '@std/assert'
354
+ * assertEquals(borrows('.fire&?doc', { fire: 'probe' }), true)
355
+ * assertEquals(borrows('.doc&.limit=5', { fire: 'probe' }), false)
356
+ * ```
357
+ */
358
+ export let borrows = (
359
+ line: string,
360
+ uses: Record<string, string>,
361
+ ): boolean => borrowed(line, uses).length > 0
362
+
363
+ /** A page speaks each borrowed component as its home declares it. A draft's
364
+ * own documents can still carry the declaration from its source manifest. */
365
+ export let withBorrowedDocs = (
366
+ own: VocabDoc[],
367
+ homes: VocabDoc[],
368
+ ): VocabDoc[] => {
369
+ if (!homes.length) return own
370
+ let borrowed = new Set(
371
+ homes.flatMap((doc) =>
372
+ Object.entries(doc.$defs ?? {}).filter(([, def]) =>
373
+ def.component === true
374
+ )
375
+ .map(([name]) => name)
376
+ ),
377
+ )
378
+ return [
379
+ ...own.map((doc) => {
380
+ let defs = Object.entries(doc.$defs ?? {})
381
+ let local = defs.filter(([name, def]) =>
382
+ def.component !== true || !borrowed.has(name)
383
+ )
384
+ return local.length == defs.length
385
+ ? doc
386
+ : { ...doc, $defs: Object.fromEntries(local) }
387
+ }),
388
+ ...homes,
389
+ ]
390
+ }
391
+
392
+ let eidOf = (b: Bundle) => b.entity?.eid ?? ''
393
+
394
+ type Heard = { at: string; bundles: Bundle[] }
395
+
396
+ // The ranking a text query painted on its hits (a query-only `rank`), kept
397
+ // off the candidate rows: the composing read addresses eids and carries no
398
+ // text pred, so the snippet and the score would be lost between the two
399
+ // halves of one search.
400
+ let ranksIn = (heard: Heard[]) => {
401
+ let ranks = new Map<string, unknown>()
402
+ for (let h of heard) {
403
+ for (let b of h.bundles) {
404
+ if (b.rank && !ranks.has(eidOf(b))) ranks.set(eidOf(b), b.rank)
405
+ }
406
+ }
407
+ return ranks
408
+ }
409
+
410
+ // The eids one fan-out selects, in the order the answer keeps. Ranked hits
411
+ // interleave: a score is one member's own measure and means nothing beside
412
+ // another's, so the merge takes each member's best, then each one's second,
413
+ // the only ordering they all agree with. Everything else is member by member,
414
+ // each in its own order.
415
+ let ordered = (heard: Heard[]) => {
416
+ let lists = heard.map((h) => h.bundles)
417
+ let ranked = lists.some((bundles) => bundles.some((b) => 'rank' in b))
418
+ let out: string[] = []
419
+ if (ranked) {
420
+ for (let i = 0; i < Math.max(0, ...lists.map((l) => l.length)); i++) {
421
+ for (let bundles of lists) if (bundles[i]) out.push(eidOf(bundles[i]))
422
+ }
423
+ } else for (let bundles of lists) for (let b of bundles) out.push(eidOf(b))
424
+ return [...new Set(out.filter(Boolean))]
425
+ }
426
+
427
+ // One component's properties as its schema declares them: property → the type
428
+ // word, which is all a disagreement is read out of.
429
+ let propsOf = (schema: PropSchema): Record<string, string> =>
430
+ Object.fromEntries(
431
+ Object.entries(schema.properties ?? {}).map((
432
+ [prop, p],
433
+ ) => [prop, p.enum ? p.enum.join('|') : String(p.type ?? '?')]),
434
+ )
435
+
436
+ let spaceOf = (m: Member) => m.space ?? m.at
437
+
438
+ // Where one name means two things: the same word declared in two spaces with
439
+ // a property they spell differently. Within a space a word has one home and
440
+ // the other members use it, so a disagreement can only be across spaces, and
441
+ // there the name is two words. Properties only one side declares agree by
442
+ // construction: a vocabulary only ever grows.
443
+ let apartIn = (vocabs: { m: Member; doc: VocabDoc }[]): Set<string> => {
444
+ let seen = new Map<string, Map<string, Record<string, string>>>()
445
+ for (let { m, doc } of vocabs) {
446
+ for (let [name, schema] of Object.entries(doc.$defs ?? {})) {
447
+ let by = seen.get(name) ?? new Map()
448
+ seen.set(name, by)
449
+ by.set(spaceOf(m), { ...by.get(spaceOf(m)), ...propsOf(schema) })
450
+ }
451
+ }
452
+ let apart = new Set<string>()
453
+ for (let [name, by] of seen) {
454
+ let sides = [...by.values()]
455
+ for (let i = 0; i < sides.length; i++) {
456
+ for (let j = i + 1; j < sides.length; j++) {
457
+ for (let [prop, type] of Object.entries(sides[i])) {
458
+ if (sides[j][prop] && sides[j][prop] != type) apart.add(name)
459
+ }
460
+ }
461
+ }
462
+ }
463
+ return apart
464
+ }
465
+
466
+ type Held = {
467
+ // The spine as the first member that answered gave it: the eid is what the
468
+ // entity is called everywhere.
469
+ entity: Entity
470
+ comps: Record<string, unknown>
471
+ // The kind each member called the row, by the member that said it.
472
+ kinds: Record<string, string>
473
+ // The archetype each member assigned the row: a pointer at the tables that
474
+ // member holds, so the composition answers one of them, never a merge.
475
+ arch: Record<string, string>
476
+ // The member each component came from, which a write routes by.
477
+ home: Record<string, string>
478
+ // Where each component is said to live (`_stores`): its member, or within
479
+ // it where a member composed of others says so in its own `_stores`. The
480
+ // spine's is `entity`, and only when its `num` is a remote member's.
481
+ where: Record<string, string>
482
+ // A word two spaces mean two things by (`apartIn`), held per space instead
483
+ // of merged: space → the member that has it and what it holds.
484
+ split: Record<
485
+ string,
486
+ Record<string, { at: string; where: string; comp: unknown }>
487
+ >
488
+ }
489
+
490
+ // `_stores`, on a bundle that must say where it lives: its pieces live in
491
+ // more than one place, or its number is a remote member's (`entity`).
492
+ let storesOf = (where: Record<string, string>) =>
493
+ where.entity || new Set(Object.values(where)).size > 1
494
+ ? { _stores: where }
495
+ : {}
496
+
497
+ /** What the caller asked, which the gather would otherwise lose: the
498
+ * components the answer keeps (`want`), the words two spaces mean two things
499
+ * by (`apart`), the line a member's answer is shaped by (`said`), and the
500
+ * words the filter required (`must`), which is what names the kind. */
501
+ export type Ask = {
502
+ want?: Set<string> | null
503
+ apart?: Set<string>
504
+ said?: string
505
+ must?: string[]
506
+ live?: boolean
507
+ }
508
+
509
+ /** Which members declare which word, the words two spaces mean two things
510
+ * by, and the union of every member's words. */
511
+ export type Spoken = {
512
+ words: Map<string, Member[]>
513
+ apart: Set<string>
514
+ vocab: Vocab
515
+ }
516
+
517
+ /** A write cut into one part per member it lands in, and the eid each
518
+ * `$alias` was given. */
519
+ export type Routed = {
520
+ parts: { member: Member; entities: Bundle[] }[]
521
+ aliases: Record<string, string>
522
+ }
523
+
524
+ /** The operations every set of members is asked through. */
525
+ export type Reach = {
526
+ read: (members: Member[], line: string, live?: boolean) => Promise<unknown>
527
+ watch: (
528
+ members: Member[],
529
+ line: string,
530
+ sink: (frame: Frame) => void,
531
+ ) => () => void
532
+ composed: (members: Member[], eids: string[], ask?: Ask) => Promise<Bundle[]>
533
+ /** The merged rows and the members that supplied them. */
534
+ located: (
535
+ members: Member[],
536
+ eids: string[],
537
+ ask?: Ask,
538
+ ) => Promise<{ bundles: Bundle[]; sources: Set<string> }>
539
+ routed: (
540
+ members: Member[],
541
+ named: Member | undefined,
542
+ bundles: Bundle[],
543
+ key?: string,
544
+ ) => Promise<Routed>
545
+ written: (
546
+ members: Member[],
547
+ named: Member | undefined,
548
+ bundles: Bundle[],
549
+ opts?: WriteOpts,
550
+ ) => Promise<{
551
+ bundles: Bundle[]
552
+ aliases: Record<string, string>
553
+ where: string
554
+ }>
555
+ spoken: (members: Member[]) => Promise<Spoken>
556
+ }
557
+
558
+ type DefaultSpace = () => Promise<string | undefined>
559
+ type WriteOpts = {
560
+ key?: string
561
+ check?: boolean
562
+ /** The caller's own space, considered when a write has no home. */
563
+ defaultSpace?: DefaultSpace
564
+ }
565
+
566
+ // Keep same-component predicates together for the store, but evaluate ORs
567
+ // across homes on entity ids. Top-level text and spine filters ride every
568
+ // part, just as in an ordinary spanning conjunction.
569
+ type Selection =
570
+ | { kind: 'ask'; name?: string; line: string }
571
+ | { kind: 'and' | 'or'; parts: Selection[] }
572
+
573
+ let optional = (c: Clause) =>
574
+ c.kind == 'pred' && c.op == '?' &&
575
+ c.path.length == 1 && !c.where && !c.not
576
+
577
+ let oneWord = (c: Clause): string | undefined => {
578
+ if (c.kind != 'and' && c.kind != 'or') return head(c)
579
+ let [first, ...rest] = c.clauses.map(oneWord)
580
+ return first && rest.every((word) => word == first) ? first : undefined
581
+ }
582
+
583
+ let selectionOf = (clauses: Clause[], rides: Clause[] = []): Selection => {
584
+ let by = new Map<string, Clause[]>()
585
+ let global = [...rides]
586
+ let mixed: Clause[][] = []
587
+ for (let c of clauses) {
588
+ if (optional(c)) continue
589
+ let name = oneWord(c)
590
+ if (name) by.set(name, [...by.get(name) ?? [], c])
591
+ else if (c.kind == 'or') mixed.push(c.clauses)
592
+ else global.push(c)
593
+ }
594
+ let ask = (cs: Clause[], name?: string): Selection => ({
595
+ kind: 'ask',
596
+ name,
597
+ line: stringify(and(...cs)),
598
+ })
599
+ let parts = [...by].map(([name, cs]) => ask([...cs, ...global], name))
600
+ for (let arms of mixed) {
601
+ parts.push({
602
+ kind: 'or',
603
+ parts: arms.map((c) =>
604
+ selectionOf(c.kind == 'and' ? c.clauses : [c], global)
605
+ ),
606
+ })
607
+ }
608
+ if (parts.length == 1) return parts[0]
609
+ if (parts.length) return { kind: 'and', parts }
610
+ return ask(global.length ? global : parse('.entity').clauses)
611
+ }
612
+
613
+ let selectors = (clauses: Clause[]) =>
614
+ selectionOf(clauses.filter((c) => !directive(c) || c.kind == 'near'))
615
+
616
+ let intersect = ([first, ...rest]: string[][]): string[] =>
617
+ rest.reduce((kept, set) => {
618
+ let have = new Set(set)
619
+ return kept.filter((e) => have.has(e))
620
+ }, first ?? [])
621
+
622
+ let selected = async (
623
+ selection: Selection,
624
+ ask: (name: string | undefined, line: string) => Promise<string[]>,
625
+ ): Promise<string[]> => {
626
+ if (selection.kind == 'ask') return ask(selection.name, selection.line)
627
+ let sets = await Promise.all(selection.parts.map((p) => selected(p, ask)))
628
+ return selection.kind == 'or' ? [...new Set(sets.flat())] : intersect(sets)
629
+ }
630
+
631
+ /** A composition over a shared language: the operations every set of
632
+ * members is asked through. */
633
+ export let reach = (words: Words): Reach => {
634
+ let { core, hidden = () => false, silent = () => {}, stops = () => false } =
635
+ words
636
+ let union = words.union ??
637
+ ((defs: Record<string, PropSchema>) =>
638
+ loadVocab([...core.docs, { title: 'space', $defs: defs }]))
639
+
640
+ // One line, asked of every member at once. One that refuses contributes
641
+ // nothing (the word is another's, or this one is not the caller's to read),
642
+ // but a line every member refuses is a line nobody can answer, and then the
643
+ // first member's refusal is what the caller reads. A member that is down,
644
+ // or that `stops` the read, fails it: its rows exist and were not sent.
645
+ let asked = async (
646
+ members: Member[],
647
+ line: string,
648
+ said?: string,
649
+ live = false,
650
+ ): Promise<Heard[]> => {
651
+ let tried = await Promise.all(members.map(async (m) => {
652
+ try {
653
+ let out = await m.read(line, { said, live })
654
+ return {
655
+ at: m.at,
656
+ bundles: (Array.isArray(out) ? out : []) as Bundle[],
657
+ }
658
+ } catch (e) {
659
+ // A member left out of the merge is a quieter answer, never a silent
660
+ // one; one answering 503 is not left out at all.
661
+ silent(e, m)
662
+ return { at: m.at, why: e }
663
+ }
664
+ }))
665
+ let gone = tried.find((t) => 'why' in t && (down(t.why) || stops(t.why))) as
666
+ | { why: unknown }
667
+ | undefined
668
+ if (gone) throw gone.why
669
+ let heard = tried.filter((t) => 'bundles' in t) as Heard[]
670
+ if (!heard.length && tried.length) {
671
+ throw (tried[0] as { why: unknown }).why
672
+ }
673
+ return heard
674
+ }
675
+
676
+ // A member's own word is the most specific thing said about a row, wherever
677
+ // it was said (@yaks/vocab kindOf), so a member's kind outranks a core kind
678
+ // from another, and the union decides the rest. Between two members' words
679
+ // the filter decides, and `must` names the components it required:
680
+ // `?loan&.book` asks for books, so a book is what each answer is. `at` is
681
+ // the member whose word won, whose archetype the composed bundle carries.
682
+ let kindFrom = (
683
+ kinds: [string, string][],
684
+ comps: Record<string, unknown>,
685
+ must: string[] = [],
686
+ ): { kind: string; at?: string } => {
687
+ let own = kinds.filter(([, k]) => k && !core.kinds.includes(k))
688
+ let said = own.find(([, k]) => must.includes(k)) ?? own[0]
689
+ return {
690
+ kind: said?.[1] ?? core.kinds.find((k) => k in comps) ?? 'entity',
691
+ at: said?.[0] ?? kinds[0]?.[0],
692
+ }
693
+ }
694
+
695
+ // What every member holds about these eids, gathered in one fan-out: the
696
+ // components, the kind each member called the row, and where each component
697
+ // lives. The read composes bundles out of it; the write routes by it.
698
+ // `apart` names the words kept per space rather than merged, because one
699
+ // name meaning two things is two answers, not one bundle.
700
+ let gathered = async (
701
+ members: Member[],
702
+ eids: string[],
703
+ apart: Set<string> = new Set(),
704
+ said?: string,
705
+ live = false,
706
+ ) => {
707
+ let held = new Map<string, Held>()
708
+ if (!eids.length) return held
709
+ let spaces = new Map(members.map((m) => [m.at, spaceOf(m)]))
710
+ let remote = new Set(members.filter((m) => m.remote).map((m) => m.at))
711
+ let heard = await asked(
712
+ members,
713
+ `.entity.eid=${eids.join(',')}`,
714
+ said,
715
+ live,
716
+ )
717
+ for (let { at, bundles } of heard) {
718
+ for (let row of bundles) {
719
+ let eid = eidOf(row)
720
+ if (!eid) continue
721
+ // The spine is held once, here: its archetype is the answering
722
+ // member's and is chosen with the kind, so no merge of the components
723
+ // may spell it a second time.
724
+ let { archetype, ...spine } = row.entity
725
+ // A member composed of others (yaks.app across its stores) says
726
+ // where within it each piece lives, which is said here within it.
727
+ let inner = (row._stores ?? {}) as Record<string, string>
728
+ let within = (name: string) => inner[name] ? `${at}/${inner[name]}` : at
729
+ let one = held.get(eid)
730
+ if (!one) {
731
+ one = {
732
+ entity: spine,
733
+ comps: {},
734
+ kinds: {},
735
+ arch: {},
736
+ home: {},
737
+ where: {},
738
+ split: {},
739
+ }
740
+ if (remote.has(at) || inner.entity) {
741
+ one.where.entity = within('entity')
742
+ }
743
+ held.set(eid, one)
744
+ }
745
+ if (archetype != null) one.arch[at] ??= archetype
746
+ for (let [name, comp] of Object.entries(row)) {
747
+ if (name == 'kind' || name == 'entity' || name == '_stores') continue
748
+ if (apart.has(name)) {
749
+ one.split[name] ??= {}
750
+ one.split[name][spaces.get(at) ?? at] ??= {
751
+ at,
752
+ where: within(name),
753
+ comp,
754
+ }
755
+ continue
756
+ }
757
+ if (name in one.comps) continue
758
+ one.comps[name] = comp
759
+ one.home[name] = at
760
+ one.where[name] = within(name)
761
+ }
762
+ one.kinds[at] ??= String(row.kind ?? '')
763
+ }
764
+ }
765
+ return held
766
+ }
767
+
768
+ /** One bundle per eid, out of every member that holds a piece of it. The
769
+ * first member that answers a component owns it here; `entity` is the
770
+ * first member's, whose archetype comes from the member whose word named
771
+ * the kind. `_stores` says which member holds which component, and rides
772
+ * on a bundle that spans two or wears a remote member's piece; it names
773
+ * `entity` too when the spine, and so the `num`, is a remote member's. */
774
+ let gatheredRows = async (
775
+ members: Member[],
776
+ eids: string[],
777
+ ask: Ask = {},
778
+ ) => {
779
+ let { want = null, apart = new Set<string>(), said, must, live = false } =
780
+ ask
781
+ let spaces = new Map(members.map((m) => [m.at, spaceOf(m)]))
782
+ let held = await gathered(members, eids, apart, said, live)
783
+ let keeps = (name: string) => !want || want.has(name)
784
+ let bundle = (
785
+ one: Held,
786
+ extra: Record<string, unknown>,
787
+ home: Record<string, string>,
788
+ space?: string,
789
+ ): Bundle => {
790
+ let comps = Object.fromEntries([
791
+ ...Object.entries(one.comps).filter(([n]) => keeps(n)),
792
+ ...Object.entries(extra).filter(([n]) => keeps(n)),
793
+ ])
794
+ let where = Object.fromEntries(
795
+ Object.entries({ ...one.where, ...home }).filter(([n]) =>
796
+ n == 'entity' || keeps(n)
797
+ ),
798
+ )
799
+ let said = kindFrom(
800
+ Object.entries(one.kinds).filter(([at]) =>
801
+ !space || spaces.get(at) == space
802
+ ),
803
+ comps,
804
+ must,
805
+ )
806
+ let archetype = said.at ? one.arch[said.at] : undefined
807
+ return {
808
+ kind: said.kind,
809
+ entity: archetype ? { ...one.entity, archetype } : one.entity,
810
+ // Two spaces mean two things by this word, so the row says which one
811
+ // it is answering for.
812
+ ...(space ? { space } : {}),
813
+ ...comps,
814
+ ...storesOf(where),
815
+ }
816
+ }
817
+ let parted = (one: Held, space?: string) => {
818
+ let mine = Object.entries(one.split).flatMap(([n, by]) =>
819
+ space
820
+ ? by[space] ? [[n, by[space]] as const] : []
821
+ : Object.values(by).map((h) => [n, h] as const)
822
+ )
823
+ return bundle(
824
+ one,
825
+ Object.fromEntries(mine.map(([n, h]) => [n, h.comp])),
826
+ Object.fromEntries(mine.map(([n, h]) => [n, h.where])),
827
+ space,
828
+ )
829
+ }
830
+ let bundles = eids.filter((e) => held.has(e)).flatMap((eid) => {
831
+ let one = held.get(eid)!
832
+ // The spaces this entity wears a disputed word in. None, and the bundle
833
+ // is one; two, and it is one per space: the same eid, answered twice,
834
+ // because the name is not one word.
835
+ let spaces = [
836
+ ...new Set(
837
+ Object.entries(one.split).filter(([n]) => keeps(n))
838
+ .flatMap(([, by]) => Object.keys(by)),
839
+ ),
840
+ ]
841
+ return spaces.length < 2
842
+ ? [parted(one)]
843
+ : spaces.map((space) => parted(one, space))
844
+ })
845
+ return { bundles, held }
846
+ }
847
+
848
+ let composed: Reach['composed'] = async (members, eids, ask) =>
849
+ (await gatheredRows(members, eids, ask)).bundles
850
+
851
+ let located: Reach['located'] = async (members, eids, ask) => {
852
+ let { bundles, held } = await gatheredRows(members, eids, ask)
853
+ let sources = new Set<string>()
854
+ for (let row of held.values()) {
855
+ for (let source of Object.keys(row.kinds)) sources.add(source)
856
+ }
857
+ return { bundles, sources }
858
+ }
859
+
860
+ // Every word in reach as one vocabulary: the core plus each member's own. A
861
+ // word two members declare is loaded once, from its first declarer: a word
862
+ // has one home, and @yaks/vocab refuses a name declared twice.
863
+ let unioned = (docs: VocabDoc[]): Vocab => {
864
+ let defs: Record<string, PropSchema> = {}
865
+ for (let doc of docs) {
866
+ for (let [name, schema] of Object.entries(doc.$defs ?? {})) {
867
+ if (name in defs || core.all.includes(name)) continue
868
+ defs[name] = schema
869
+ }
870
+ }
871
+ return union(defs, docs)
872
+ }
873
+
874
+ let declarations = (members: Member[]) =>
875
+ Promise.all(members.map(async (m) => ({ m, doc: await m.vocab() })))
876
+
877
+ /** Which members declare which word, in member order, so the first
878
+ * declarer is the word's home; the words two spaces mean two things by
879
+ * (`apart`); and the union of every member's words (`vocab`).
880
+ *
881
+ * A core word is nobody's: a member that held it before the core said it
882
+ * keeps it in its own graph, but every other member speaks the core's, so
883
+ * it is not that member's to home. */
884
+ let spoken = async (
885
+ members: Member[],
886
+ own?: Awaited<ReturnType<typeof declarations>>,
887
+ ): Promise<Spoken> => {
888
+ own ??= await declarations(members)
889
+ let words = new Map<string, Member[]>()
890
+ for (let { m, doc } of own) {
891
+ for (let w of Object.keys(doc.$defs ?? {})) {
892
+ if (core.all.includes(w)) continue
893
+ words.set(w, [...(words.get(w) ?? []), m])
894
+ }
895
+ }
896
+ return {
897
+ words,
898
+ apart: apartIn(own),
899
+ vocab: unioned(own.map((o) => o.doc)),
900
+ }
901
+ }
902
+
903
+ // The line's `.fields` projection in the union's words, or none. A path
904
+ // those words cannot read is the caller's line refused, as a member
905
+ // refuses it.
906
+ let planned = (line: string, vocab: Vocab): Projection | null => {
907
+ try {
908
+ return projection(vocab, bareLine(line))
909
+ } catch (e) {
910
+ throw refusing(e)
911
+ }
912
+ }
913
+
914
+ // A `.fields` projection over the merge. The members chose the entities and
915
+ // the merge holds them whole, so each entity a path reaches is gathered
916
+ // here, hop by hop and from every member, and the paths are read off the
917
+ // lot the way a store reads them off its own rows.
918
+ let projected = async (
919
+ members: Member[],
920
+ vocab: Vocab,
921
+ p: Projection,
922
+ found: Bundle[],
923
+ live: boolean,
924
+ ): Promise<Bundle[]> => {
925
+ if (!found.length) return []
926
+ let held = new Map(found.map((b) => [eidOf(b), b]))
927
+ let read = rows({
928
+ kind: 'and',
929
+ clauses: [
930
+ ...parse(`.entity.eid=${[...held.keys()].join(',')}`).clauses,
931
+ ...p.query.clauses.filter((c) => c.kind == 'fields'),
932
+ ],
933
+ }, vocab)
934
+ let seen = new Set(held.keys())
935
+ while (true) {
936
+ let got = read([...held.values()])
937
+ let more = [...new Set(got.flatMap((r) => p.reaches.map((c) => r[c])))]
938
+ .filter((e): e is string => typeof e == 'string' && !seen.has(e))
939
+ if (!more.length) {
940
+ return flat(p.fold(got)).map((b) => {
941
+ let kind = held.get(eidOf(b))?.kind
942
+ return kind ? { kind, ...b } : b
943
+ })
944
+ }
945
+ for (let e of more) seen.add(e)
946
+ for (let b of await composed(members, more, { live })) {
947
+ held.set(eidOf(b), b)
948
+ }
949
+ }
950
+ }
951
+
952
+ // A component off a merged bundle the caller's own line would not carry:
953
+ // one it did not name when it named any (@yaks/graph `wanted`), or one the
954
+ // members' answers leave off unless named (`hidden`).
955
+ let unasked = (comp: string, want: Set<string> | null, line: string) => {
956
+ let kept = (want ? want.has(comp) : true) && !hidden(comp, line)
957
+ return (b: Bundle): Bundle => {
958
+ if (kept) return b
959
+ let out: Bundle = { ...b }
960
+ let homes = Object.entries((b._stores ?? {}) as Record<string, string>)
961
+ .filter(([name]) => name != comp)
962
+ delete out[comp]
963
+ delete out._stores
964
+ return { ...out, ...storesOf(Object.fromEntries(homes)) }
965
+ }
966
+ }
967
+
968
+ /** The read, whole. One member and this is that member's own answer,
969
+ * untouched. Several, and the line is split, each part asked of the members
970
+ * that speak it, the eids in common taken (a filter's `&` is an
971
+ * intersection), and the bundles composed.
972
+ *
973
+ * A window is the one place the split shows: `limit=` bounds each part
974
+ * before the parts meet. Unless the caller asked for an order, and then the
975
+ * sequence is nobody's to cut until the bundles are one: the order and the
976
+ * window run over the merged answer, in the union's words. */
977
+ let read = async (
978
+ members: Member[],
979
+ line: string,
980
+ live = false,
981
+ ): Promise<unknown> => {
982
+ if (members.length == 1) return await members[0].read(line, { live })
983
+ let or = disjunction(line)
984
+ let shaped = or ? stringify(or) : line
985
+ let agg = aggOf(shaped)
986
+ if (agg && agg != 'count') {
987
+ throw refuse(
988
+ `a ${agg} reads one app at a time and this reads them all — ask for ` +
989
+ 'the rows and reduce them',
990
+ )
991
+ }
992
+ let { parts, global } = split(shaped)
993
+ let orders = window(shaped)
994
+ // A projection is read off the merge (`projected`), so the members are
995
+ // asked only which entities the filter selects.
996
+ let plain = global.filter((s) =>
997
+ !AGGS.includes(firstWord(s)) && !(orders.order && orderWord(s)) &&
998
+ firstWord(s) != 'fields'
999
+ )
1000
+ // Which members a word is asked of: the ones whose vocabulary declares
1001
+ // it, and every member for a word nobody declares, which is the core's
1002
+ // and spoken everywhere.
1003
+ let { words, apart, vocab } = await spoken(members)
1004
+ let sorted = sorting(orders, vocab)
1005
+ let p = planned(line, vocab)
1006
+ let speak = (name: string) => words.get(name) ?? members
1007
+ let need = [...parts].filter(([, part]) => !part.asks)
1008
+ let lines: [Member[], string][] = need.length
1009
+ ? need.map((
1010
+ [name, part],
1011
+ ) => [speak(name), [...part.segs, ...plain].join('&')])
1012
+ : [[members, plain.join('&')]]
1013
+ let ranks = new Map<string, unknown>()
1014
+ let matches = async (who: Member[], query: string) => {
1015
+ let heard = await asked(who, query, undefined, live)
1016
+ for (let [eid, rank] of ranksIn(heard)) ranks.set(eid, rank)
1017
+ return ordered(heard)
1018
+ }
1019
+ let eids = or
1020
+ ? await selected(
1021
+ selectors(or.clauses),
1022
+ (name, query) =>
1023
+ matches(name ? speak(name) : members, `${query}&.fields=entity.eid`),
1024
+ )
1025
+ : intersect(
1026
+ await Promise.all(lines.map(([who, query]) => matches(who, query))),
1027
+ )
1028
+ let { limit, after } = or ? windowOf(or) : { limit: limitOf(line) }
1029
+ // An OR's window belongs to the union, not to any arm. An eid cursor
1030
+ // already identifies the anchor in that sequence; a numeric cursor needs
1031
+ // the composed spine. An explicit order is settled on the merged rows.
1032
+ let numeric = or && !orders.order && typeof after == 'number'
1033
+ if (or && agg == 'count') return { count: eids.length }
1034
+ if (!orders.order && !numeric) {
1035
+ let start = typeof after == 'string' ? eids.indexOf(after) + 1 : 0
1036
+ eids = eids.slice(start, limit == null ? undefined : start + limit)
1037
+ }
1038
+ if (agg == 'count') return { count: eids.length }
1039
+ // The bundle is read from the members that speak a word the line named,
1040
+ // and carries those components (@yaks/graph `wanted`). A part this cannot
1041
+ // confirm is a component asks for the whole bundle rather than guess, and
1042
+ // `*` is the grammar's widest projection. A `.fields` projection reads
1043
+ // its properties off the whole merge, wherever they live.
1044
+ let named = or ? [...new Set(namesIn(or))] : [...parts.keys()]
1045
+ let want = named.length && !every(line) && !p &&
1046
+ named.every((n) => words.has(n) || core.all.includes(n))
1047
+ ? new Set(named)
1048
+ : null
1049
+ // In reach order, whatever order the line names its words in: the first
1050
+ // member holding the entity gives its spine, and so its `num`.
1051
+ let by = orderedBy(orders, vocab)
1052
+ let asks = new Set([...named, ...(by ? [by] : [])].flatMap(speak))
1053
+ let from = !or && named.length && !p
1054
+ ? members.filter((m) => asks.has(m))
1055
+ : members
1056
+ let bundles = await composed(
1057
+ from,
1058
+ eids,
1059
+ {
1060
+ want: want && by ? new Set([...want, by]) : want,
1061
+ apart,
1062
+ said: by ? `${line}&?${by}` : line,
1063
+ must: or
1064
+ ? or.clauses.flatMap((c) => !optional(c) && head(c) ? [head(c)!] : [])
1065
+ : need.map(([name]) => name),
1066
+ live,
1067
+ },
1068
+ )
1069
+ let out = sorted(
1070
+ bundles.map((b) => {
1071
+ let rank = ranks.get(eidOf(b))
1072
+ return rank ? { ...b, rank } : b
1073
+ }),
1074
+ )
1075
+ if (numeric) {
1076
+ let start = out.findIndex((b) => b.entity.num == after) + 1
1077
+ out = out.slice(start, limit == null ? undefined : start + limit)
1078
+ }
1079
+ if (p) return await projected(members, vocab, p, out, live)
1080
+ return by ? out.map(unasked(by, want, line)) : out
1081
+ }
1082
+
1083
+ /** The batch, split by component into one part per member, with every
1084
+ * `$alias` minted once for all of them. `key` derives the mints, so the
1085
+ * same batch sent again mints the same eids. */
1086
+ let routed = async (
1087
+ members: Member[],
1088
+ named: Member | undefined,
1089
+ bundles: Bundle[],
1090
+ key?: string,
1091
+ defaultSpace?: DefaultSpace,
1092
+ ): Promise<Routed> => {
1093
+ // A sandboxed copy owns only writes aimed at it, and a write aimed at a
1094
+ // member stays in its space: spaces share no home, so another space's
1095
+ // declarer, holder or mate is never where a part goes. Every routing
1096
+ // decision chooses from the same eligible members.
1097
+ members = members.filter((m) =>
1098
+ (!m.sandboxed || m == named) &&
1099
+ (!named || spaceOf(m) == spaceOf(named))
1100
+ )
1101
+ let scope = await declarations(members)
1102
+ let target = scope.find(({ m }) => m === named)
1103
+ let own = target?.doc.local
1104
+ ? [target]
1105
+ : scope.filter(({ doc }) => !doc.local)
1106
+ members = own.map(({ m }) => m)
1107
+ let { words, apart, vocab } = await spoken(members, own)
1108
+ let { entities, eids, aliases } = await minted(
1109
+ bundles,
1110
+ vocab,
1111
+ key,
1112
+ async (eids) => {
1113
+ let held = await gathered(members, eids)
1114
+ return [...held.values()].map((b) => ({ entity: b.entity, ...b.comps }))
1115
+ },
1116
+ )
1117
+ // Where the entity already lives, read only when the answer depends on
1118
+ // it: a death fans out to whoever holds the eid, and a shared word with no
1119
+ // member named goes to the one that already wears it.
1120
+ let asking = entities.flatMap((e, i) =>
1121
+ eids[i] && (dead(e) ||
1122
+ (!named && Object.keys(e).some((k) => isComp(k) && !words.has(k))))
1123
+ ? [eids[i]!]
1124
+ : []
1125
+ )
1126
+ let held = await gathered(members, asking)
1127
+ let by = (label: string) => members.find((m) => m.at == label)
1128
+ // What `$app` takes for a member: its name, or its `at` where another
1129
+ // member answers to the same name, as two spaces' `recipes` do.
1130
+ let called = (m: Member) =>
1131
+ members.filter((o) => (o.name ?? o.at) == (m.name ?? m.at)).length > 1
1132
+ ? m.at
1133
+ : m.name ?? m.at
1134
+ let slugs = (ms = members) =>
1135
+ ms.length > 3 ? `${ms.length} candidate apps` : ms.map(called).join(', ')
1136
+ let onBundle = (m?: Member) =>
1137
+ m ? `on the bundle, as "$app": "${called(m)}"` : 'on the bundle with $app'
1138
+ let remembered: Promise<Member | undefined> | undefined
1139
+ let preferred = () =>
1140
+ remembered ??=
1141
+ (members.length > 1 ? defaultSpace?.() : undefined)?.then((space) => {
1142
+ let there = members.filter((m) => spaceOf(m) == space)
1143
+ return there.length == 1 ? there[0] : undefined
1144
+ }) ?? Promise.resolve(undefined)
1145
+ let available = () => {
1146
+ if (!members.length) throw refuse('no app in reach — deploy an app first')
1147
+ }
1148
+ // The one member a bundle that cannot be split goes to.
1149
+ let only = async () => {
1150
+ if (named) return named
1151
+ if (members.length == 1) return members[0]
1152
+ let there = await preferred()
1153
+ if (there) return there
1154
+ available()
1155
+ throw refuse(
1156
+ `name the app this goes in ${onBundle(members[0])} — ${slugs()}`,
1157
+ )
1158
+ }
1159
+ let home = async (
1160
+ name: string,
1161
+ eid: string | null,
1162
+ mates: Member[],
1163
+ ): Promise<Member> => {
1164
+ let declared = words.get(name) ?? []
1165
+ let mine = eid ? held.get(eid)?.home ?? {} : {}
1166
+ if (declared.length) {
1167
+ // A word has one home: the first member to declare it. A second
1168
+ // member declaring the same word is a use of it, and its writes land
1169
+ // in the home. Where the entity already wears the word wins over
1170
+ // birth order, and a named member wins over both when it is one of
1171
+ // the declarers, since across spaces two members may mean two things
1172
+ // by one name.
1173
+ let where = mine[name] && by(mine[name])
1174
+ if (where && declared.includes(where)) return where
1175
+ if (named && declared.includes(named)) return named
1176
+ // Across spaces the shapes may disagree, and then the name is two
1177
+ // words: nothing here can pick between them, so the caller does.
1178
+ let homes = [...new Set(declared.map(spaceOf))]
1179
+ .map((s) => declared.find((m) => spaceOf(m) == s)!)
1180
+ if (apart.has(name) && homes.length > 1) {
1181
+ let there = await preferred()
1182
+ if (there && declared.includes(there)) return there
1183
+ throw refuse(
1184
+ `${name} has different declarations across spaces; name an app ` +
1185
+ `${onBundle(homes[0])} — ${slugs(homes)}`,
1186
+ )
1187
+ }
1188
+ return declared[0]
1189
+ }
1190
+ if (named) return named
1191
+ let where = mine[name] && by(mine[name])
1192
+ if (where) return where
1193
+ let holders = [...new Set(Object.values(mine))].map(by).filter(Boolean)
1194
+ if (holders.length == 1) return holders[0]!
1195
+ // A title beside a recipe is the recipe's title: a shared word with
1196
+ // nowhere else to go rides with the member whose own words are in the
1197
+ // same bundle, which is what makes writing a new entity one call.
1198
+ if (mates.length == 1) return mates[0]
1199
+ if (members.length == 1) return members[0]
1200
+ if (!holders.length && !mates.length) {
1201
+ let there = await preferred()
1202
+ if (there) return there
1203
+ }
1204
+ available()
1205
+ throw refuse(
1206
+ `which app should ${name} go in? name it ${
1207
+ onBundle(mates[0] ?? members[0])
1208
+ } — ${slugs(mates.length ? mates : members)}`,
1209
+ )
1210
+ }
1211
+ let parts = new Map<Member, Bundle[]>()
1212
+ let add = (m: Member, e: Bundle) =>
1213
+ parts.set(m, [...(parts.get(m) ?? []), e])
1214
+ for (let [i, e] of entities.entries()) {
1215
+ let eid = eids[i]
1216
+ if (!eid) {
1217
+ add(await only(), e)
1218
+ continue
1219
+ }
1220
+ // Death is the whole entity's, so it goes wherever the entity is: every
1221
+ // member holding a piece of it, and the one named when none does yet.
1222
+ if (dead(e)) {
1223
+ let holders = [...new Set(Object.values(held.get(eid)?.home ?? {}))]
1224
+ .map(by).filter(Boolean) as Member[]
1225
+ for (let m of holders.length ? holders : [await only()]) {
1226
+ add(m, { entity: { eid }, tombstone: {} })
1227
+ }
1228
+ continue
1229
+ }
1230
+ // A `$was` guard rides with the component it guards, whether or not
1231
+ // this batch also writes that component: a precondition that lost its
1232
+ // part would silently stop guarding.
1233
+ let guards = (e.$was ?? {}) as Record<string, unknown>
1234
+ let names = [
1235
+ ...new Set([...Object.keys(e).filter(isComp), ...Object.keys(guards)]),
1236
+ ]
1237
+ let mine = new Map<Member, string[]>()
1238
+ let take = (m: Member, name: string) =>
1239
+ mine.set(m, [...(mine.get(m) ?? []), name])
1240
+ // The members' own words first: they are what a shared word rides with.
1241
+ for (let name of names.filter((n) => words.has(n))) {
1242
+ take(await home(name, eid, []), name)
1243
+ }
1244
+ let mates = [...mine.keys()]
1245
+ for (let name of names.filter((n) => !words.has(n))) {
1246
+ take(await home(name, eid, mates), name)
1247
+ }
1248
+ for (let [m, keys] of mine) {
1249
+ let was = Object.fromEntries(
1250
+ Object.entries(guards).filter(([n]) => keys.includes(n)),
1251
+ )
1252
+ add(m, {
1253
+ entity: { ...e.entity, eid },
1254
+ ...Object.fromEntries(
1255
+ keys.filter((n) => n in e)
1256
+ .map((n) => [n, (e as Record<string, unknown>)[n]]),
1257
+ ),
1258
+ ...(Object.keys(was).length ? { $was: was } : {}),
1259
+ // and the alias the caller named it by, which every part carries:
1260
+ // it is how a store tells an id this picked from one the caller
1261
+ // wrote down (@yaks/alias).
1262
+ ...(typeof e.$alias == 'string' ? { $alias: e.$alias } : {}),
1263
+ } as Bundle)
1264
+ }
1265
+ }
1266
+ return {
1267
+ parts: [...parts].map(([member, entities]) => ({ member, entities })),
1268
+ aliases,
1269
+ }
1270
+ }
1271
+
1272
+ /** The write, whole: routed, rehearsed in every member, then committed. A
1273
+ * refusal in any member leaves every other unwritten, because the rehearsal
1274
+ * went first; a single part needs no second round trip, since its commit is
1275
+ * its rehearsal. A refusal after the rehearsal may follow another part's
1276
+ * commit, so it comes back marked `partial`: the caller must not send the
1277
+ * batch again. `check` stops at the rehearsal, which is then the answer. */
1278
+ let written = async (
1279
+ members: Member[],
1280
+ named: Member | undefined,
1281
+ bundles: Bundle[],
1282
+ opts: WriteOpts = {},
1283
+ ): Promise<{
1284
+ bundles: Bundle[]
1285
+ aliases: Record<string, string>
1286
+ where: string
1287
+ }> => {
1288
+ let { key, check = false, defaultSpace } = opts
1289
+ if (!bundles.length) {
1290
+ return { bundles: [], aliases: {}, where: '' }
1291
+ }
1292
+ let { parts, aliases } = await routed(
1293
+ members,
1294
+ named,
1295
+ bundles,
1296
+ key,
1297
+ defaultSpace,
1298
+ )
1299
+ if (!parts.length) {
1300
+ throw refuse(
1301
+ 'No bundle has a change to route. Send a component patch, ' +
1302
+ 'a $delete, or a $was guard alongside the entity address. ' +
1303
+ 'For example, bundles: [{"entity":{"eid":"<eid>"},"doc":{"title":"…"}}].',
1304
+ )
1305
+ }
1306
+ if (parts.length > 1 && !check) {
1307
+ await Promise.all(parts.map((p) => p.member.apply(p.entities, true)))
1308
+ }
1309
+ let outs = await Promise.all(
1310
+ parts.map((p) => p.member.apply(p.entities, check)),
1311
+ ).catch((e) => {
1312
+ throw parts.length > 1 && !check ? Object.assign(e, { partial: true }) : e
1313
+ })
1314
+ let applied = outs.flat()
1315
+ // Where a `$alias` landed. A member may put a bundle somewhere other than
1316
+ // the id minted for it: one carrying a name somebody already holds is a
1317
+ // patch of that entity (@yaks/alias), and the batch as applied says so.
1318
+ for (let b of applied) {
1319
+ if (callerAlias(b.$alias)) aliases[b.$alias] = b.entity.eid
1320
+ }
1321
+ return {
1322
+ bundles: applied,
1323
+ aliases,
1324
+ where: parts.map((p) => p.member.at).join(' and '),
1325
+ }
1326
+ }
1327
+
1328
+ /** The read, live. One member and this is that member's own watch. With
1329
+ * several, each member that speaks a word the line names watches its part
1330
+ * of the line, and any frame one sends is news: the line is read again,
1331
+ * whole, and its answer sent with `reset` when it moved. So a watch answers
1332
+ * exactly what the read does, its merge, order and count included. Reads
1333
+ * the news raises while one is out share the next. Each frame's revisions
1334
+ * are under their members' `at` ({@link named}); a read again says the
1335
+ * newest each member's news had said when it began, which its rows are no
1336
+ * older than. */
1337
+ let watch = (
1338
+ members: Member[],
1339
+ line: string,
1340
+ sink: (frame: Frame) => void,
1341
+ ): () => void => {
1342
+ let [one] = members
1343
+ if (members.length == 1 && one.watch) {
1344
+ return one.watch(line, (frame) => sink(named(frame, one.at)))
1345
+ }
1346
+ let closed = false, reading = false, again = false
1347
+ let said: string | undefined
1348
+ let heard: Record<string, number> = {}
1349
+ let send = (frame: Frame, key: string) => {
1350
+ if (closed || key == said) return
1351
+ said = key
1352
+ sink(frame)
1353
+ }
1354
+ let ask = async () => {
1355
+ if (reading) return void (again = true)
1356
+ reading = true
1357
+ do {
1358
+ again = false
1359
+ let at = { ...heard }
1360
+ try {
1361
+ let out = await read(members, line, true)
1362
+ let frame = Array.isArray(out)
1363
+ ? { bundles: out as Bundle[], reset: true }
1364
+ : out as Frame
1365
+ let key = JSON.stringify(frame)
1366
+ if (Object.keys(at).length) frame = { ...frame, revision: at }
1367
+ send(frame, key)
1368
+ } catch (e) {
1369
+ send({ refused: e }, `refused ${(e as Error)?.message}`)
1370
+ }
1371
+ } while (again && !closed)
1372
+ reading = false
1373
+ }
1374
+ let stops: (() => void)[] = []
1375
+ void ask()
1376
+ void news(members, line).then((lines) => {
1377
+ for (let [m, part] of lines) {
1378
+ if (closed) continue
1379
+ stops.push(m.watch!(part, (frame) => {
1380
+ let revision = named(frame, m.at).revision as
1381
+ | Record<string, number>
1382
+ | undefined
1383
+ for (let [at, n] of Object.entries(revision ?? {})) {
1384
+ heard[at] = Math.max(heard[at] ?? n, n)
1385
+ }
1386
+ void ask()
1387
+ }))
1388
+ }
1389
+ }, (e) => send({ refused: e }, `refused ${(e as Error)?.message}`))
1390
+ return () => {
1391
+ closed = true
1392
+ for (let stop of stops) stop()
1393
+ }
1394
+ }
1395
+
1396
+ // Who tells a watch across members that its answer may have moved, and
1397
+ // what each watches: every member speaking a word the line names, its part
1398
+ // of the line (a request, `?loan`, as the presence of the word), with the
1399
+ // filters every part rides with. A line naming no word is watched whole by
1400
+ // every member. Riders and reductions shape an answer, not which rows
1401
+ // move it, so they stay out.
1402
+ let news = async (
1403
+ members: Member[],
1404
+ line: string,
1405
+ ): Promise<[Member, string][]> => {
1406
+ let live = members.filter((m) => m.watch)
1407
+ let or = disjunction(line)
1408
+ if (or) {
1409
+ let { words } = await spoken(live)
1410
+ let homes = (name?: string) => name && words.get(name) || live
1411
+ let watch = (s: Selection): [Member, string][] =>
1412
+ s.kind == 'ask'
1413
+ ? homes(s.name).map((m) => [m, s.line])
1414
+ : s.parts.flatMap(watch)
1415
+ return [
1416
+ ...watch(selectors(or.clauses)),
1417
+ ...or.clauses.filter(optional).flatMap((c) =>
1418
+ homes(head(c)).map((m): [Member, string] => [m, `.${head(c)}`])
1419
+ ),
1420
+ ]
1421
+ }
1422
+ let { parts, global } = split(line)
1423
+ let rides = global.filter((s) =>
1424
+ ![...RIDERS, ...AGGS].includes(firstWord(s))
1425
+ )
1426
+ if (!parts.size) return live.map((m) => [m, rides.join('&') || '.entity'])
1427
+ let { words } = await spoken(live)
1428
+ return [...parts].flatMap(([name, part]) => {
1429
+ let segs = part.asks ? [`.${name}`] : part.segs
1430
+ let one = [...segs, ...rides].join('&')
1431
+ return (words.get(name) ?? live).map((m) => [m, one] as [Member, string])
1432
+ })
1433
+ }
1434
+
1435
+ return { read, watch, composed, located, routed, written, spoken }
1436
+ }
1437
+
1438
+ // The keys of a bundle that name no component: its address and its death.
1439
+ // Everything a `$` opens is the wire's own (`$was`, `$delete`, `$actor`).
1440
+ let NOT_A_COMP = ['entity', 'tombstone']
1441
+
1442
+ let isComp = (k: string) => !NOT_A_COMP.includes(k) && !k.startsWith('$')
1443
+
1444
+ // Every `$alias` in the batch, minted here. A bundle that lands in two members
1445
+ // must land under one eid, so content-addressed ids are derived by the same
1446
+ // rules as a store, the rest are minted, and every member gets the one
1447
+ // answer. A bundle with no address at all is minted the same way.
1448
+ let minted = async (
1449
+ bundles: Bundle[],
1450
+ vocab: Vocab,
1451
+ key: string | undefined,
1452
+ held: (eids: string[]) => Promise<Bundle[]>,
1453
+ ) => {
1454
+ let ordinal = 0
1455
+ let mint = () =>
1456
+ key
1457
+ ? derivedEid(JSON.stringify(['outbox', key, ordinal++]))
1458
+ : crypto.randomUUID()
1459
+ let stated = bundles.map((e): Bundle => {
1460
+ let eid = e.entity?.eid
1461
+ if (typeof eid == 'string') return e
1462
+ // An eid is the only address that holds across members: a num is one
1463
+ // store's, so a bundle naming one names nothing here, and minting an eid
1464
+ // for it would write a new entity where the caller meant an existing one.
1465
+ if (e.entity?.num != null) {
1466
+ throw refuse(
1467
+ 'entity.num addresses nothing here — name the entity by its eid',
1468
+ )
1469
+ }
1470
+ return { ...e, entity: { ...e.entity, eid: mint() } }
1471
+ })
1472
+ let derive = {
1473
+ ...identities(vocab),
1474
+ ...(vocab.comp('archetype') ? archetypes().derive : {}),
1475
+ ...edges(vocab).derive,
1476
+ ...keys(vocab).derive,
1477
+ }
1478
+ // The store sees only the tombstone. Check the relation before the router
1479
+ // discards it, so an unknown relation cannot mint a fresh id for a drop.
1480
+ let drops = stated.filter((b) => dead(b) && b.edge && isAlias(b.entity.eid))
1481
+ if (drops.length) statedEdges(vocab)(drops)
1482
+ let resolved = await resolve(stated, vocab, derive, mint, held)
1483
+ let aliases = Object.fromEntries(
1484
+ resolved.flatMap((e) =>
1485
+ callerAlias(e.$alias) ? [[e.$alias, e.entity.eid]] : []
1486
+ ),
1487
+ )
1488
+ let eids = resolved.map((e) => e.entity.eid)
1489
+ // An alias stands wherever an eid goes (a ref property, an edge's end, a
1490
+ // nested bundle's address), so the swap is the whole batch's, by value.
1491
+ let swap = (v: unknown): unknown =>
1492
+ typeof v == 'string'
1493
+ ? (Object.hasOwn(aliases, v) ? aliases[v] : v)
1494
+ : Array.isArray(v)
1495
+ ? v.map(swap)
1496
+ : v && typeof v == 'object'
1497
+ ? Object.fromEntries(
1498
+ Object.entries(v as Record<string, unknown>).map((
1499
+ [k, x],
1500
+ ) => [k, swap(x)]),
1501
+ )
1502
+ : v
1503
+ let entities = stated.map((e, i) => {
1504
+ let one = swap(resolved[i]) as Bundle
1505
+ if (!eids[i]) return one
1506
+ // The alias rides along. A store's own mint phase reads `$alias` to tell
1507
+ // an id the graph picked from one a caller wrote down, which decides
1508
+ // whether a name somebody already holds moves this entity onto theirs or
1509
+ // is refused as a clash.
1510
+ let said = e.entity?.eid
1511
+ return {
1512
+ ...one,
1513
+ entity: { ...one.entity, eid: eids[i]! },
1514
+ ...(typeof said == 'string' && said.startsWith('$')
1515
+ ? { $alias: said }
1516
+ : {}),
1517
+ }
1518
+ })
1519
+ return { entities, eids, aliases }
1520
+ }