@yaks/api 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.
Files changed (152) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +956 -2
  3. package/_dist/actor.d.ts +59 -0
  4. package/_dist/actor.d.ts.map +1 -0
  5. package/_dist/address.d.ts +33 -0
  6. package/_dist/address.d.ts.map +1 -0
  7. package/_dist/asset.d.ts +15 -0
  8. package/_dist/asset.d.ts.map +1 -0
  9. package/_dist/batches.d.ts +4 -0
  10. package/_dist/batches.d.ts.map +1 -0
  11. package/_dist/body.d.ts +7 -0
  12. package/_dist/body.d.ts.map +1 -0
  13. package/_dist/deno.d.ts +38 -0
  14. package/_dist/deno.d.ts.map +1 -0
  15. package/_dist/doors.d.ts +134 -0
  16. package/_dist/doors.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +17 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/headers.d.ts +5 -0
  20. package/_dist/headers.d.ts.map +1 -0
  21. package/_dist/log.d.ts +253 -0
  22. package/_dist/log.d.ts.map +1 -0
  23. package/_dist/mod.d.ts +71 -0
  24. package/_dist/mod.d.ts.map +1 -0
  25. package/_dist/publish.d.ts +7 -0
  26. package/_dist/publish.d.ts.map +1 -0
  27. package/_dist/reached.d.ts +145 -0
  28. package/_dist/reached.d.ts.map +1 -0
  29. package/_dist/receipts.d.ts +153 -0
  30. package/_dist/receipts.d.ts.map +1 -0
  31. package/_dist/refuse.d.ts +51 -0
  32. package/_dist/refuse.d.ts.map +1 -0
  33. package/_dist/relay.d.ts +3 -0
  34. package/_dist/relay.d.ts.map +1 -0
  35. package/_dist/request.d.ts +79 -0
  36. package/_dist/request.d.ts.map +1 -0
  37. package/_dist/requests.d.ts +7 -0
  38. package/_dist/requests.d.ts.map +1 -0
  39. package/_dist/route.d.ts +71 -0
  40. package/_dist/route.d.ts.map +1 -0
  41. package/_dist/routed.d.ts +33 -0
  42. package/_dist/routed.d.ts.map +1 -0
  43. package/_dist/routes.d.ts +46 -0
  44. package/_dist/routes.d.ts.map +1 -0
  45. package/_dist/save.d.ts +6 -0
  46. package/_dist/save.d.ts.map +1 -0
  47. package/_dist/socket.d.ts +73 -0
  48. package/_dist/socket.d.ts.map +1 -0
  49. package/_dist/subs.d.ts +134 -0
  50. package/_dist/subs.d.ts.map +1 -0
  51. package/_dist/timing.d.ts +8 -0
  52. package/_dist/timing.d.ts.map +1 -0
  53. package/_dist/tools.d.ts +80 -0
  54. package/_dist/tools.d.ts.map +1 -0
  55. package/_dist/vocab.d.ts +6 -0
  56. package/_dist/vocab.d.ts.map +1 -0
  57. package/access.js +32 -0
  58. package/access.js.map +1 -0
  59. package/access.ts +42 -0
  60. package/actor.js +75 -0
  61. package/actor.js.map +1 -0
  62. package/actor.ts +106 -0
  63. package/address.js +42 -0
  64. package/address.js.map +1 -0
  65. package/address.ts +49 -0
  66. package/admission.js +71 -0
  67. package/admission.js.map +1 -0
  68. package/admission.ts +64 -0
  69. package/asset.js +37 -0
  70. package/asset.js.map +1 -0
  71. package/asset.ts +47 -0
  72. package/batches.js +92 -0
  73. package/batches.js.map +1 -0
  74. package/batches.ts +96 -0
  75. package/body.js +51 -0
  76. package/body.js.map +1 -0
  77. package/body.ts +82 -0
  78. package/deno.js +88 -0
  79. package/deno.js.map +1 -0
  80. package/deno.json +1 -0
  81. package/deno.ts +150 -0
  82. package/doors.js +435 -0
  83. package/doors.js.map +1 -0
  84. package/doors.ts +570 -0
  85. package/graph.js +12 -0
  86. package/graph.js.map +1 -0
  87. package/graph.ts +23 -0
  88. package/headers.js +5 -0
  89. package/headers.js.map +1 -0
  90. package/headers.ts +9 -0
  91. package/interest.js +224 -0
  92. package/interest.js.map +1 -0
  93. package/interest.ts +264 -0
  94. package/log.js +1011 -0
  95. package/log.js.map +1 -0
  96. package/log.ts +1035 -0
  97. package/mod.js +69 -0
  98. package/mod.js.map +1 -0
  99. package/mod.ts +142 -0
  100. package/package.json +75 -4
  101. package/peer_query.js +164 -0
  102. package/peer_query.js.map +1 -0
  103. package/peer_query.ts +158 -0
  104. package/publish.js +7 -0
  105. package/publish.js.map +1 -0
  106. package/publish.ts +16 -0
  107. package/reached.js +456 -0
  108. package/reached.js.map +1 -0
  109. package/reached.ts +549 -0
  110. package/receipts.js +543 -0
  111. package/receipts.js.map +1 -0
  112. package/receipts.ts +749 -0
  113. package/refuse.js +120 -0
  114. package/refuse.js.map +1 -0
  115. package/refuse.ts +179 -0
  116. package/relay.js +249 -0
  117. package/relay.js.map +1 -0
  118. package/relay.ts +284 -0
  119. package/request.js +218 -0
  120. package/request.js.map +1 -0
  121. package/request.ts +235 -0
  122. package/requests.js +250 -0
  123. package/requests.js.map +1 -0
  124. package/requests.ts +257 -0
  125. package/route.js +139 -0
  126. package/route.js.map +1 -0
  127. package/route.ts +228 -0
  128. package/routed.js +25 -0
  129. package/routed.js.map +1 -0
  130. package/routed.ts +53 -0
  131. package/routes.js +154 -0
  132. package/routes.js.map +1 -0
  133. package/routes.ts +201 -0
  134. package/save.js +341 -0
  135. package/save.js.map +1 -0
  136. package/save.ts +393 -0
  137. package/socket.js +398 -0
  138. package/socket.js.map +1 -0
  139. package/socket.ts +496 -0
  140. package/subs.js +2295 -0
  141. package/subs.js.map +1 -0
  142. package/subs.ts +2979 -0
  143. package/timing.js +17 -0
  144. package/timing.js.map +1 -0
  145. package/timing.ts +26 -0
  146. package/tools.js +251 -0
  147. package/tools.js.map +1 -0
  148. package/tools.ts +315 -0
  149. package/vocab.js +18 -0
  150. package/vocab.js.map +1 -0
  151. package/vocab.json +93 -0
  152. package/vocab.ts +18 -0
package/save.ts ADDED
@@ -0,0 +1,393 @@
1
+ // Saving is independent of relay cadence: hold the latest admitted value,
2
+ // store it when its stored entity matches the query, even after disconnect.
3
+ import { matcher } from '@yaks/match'
4
+ import { after, isPromise, over } from '@yaks/fp'
5
+ import type { Actor, Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
6
+ import { comps, formed } from '@yaks/graph/bundle'
7
+ import { signed } from '@yaks/graph/provenance'
8
+ import { saveOf, syncOf } from '@yaks/vocab'
9
+ import { and, bare, type Clause, eq, parse, timeEdges } from '@yaks/query'
10
+ import type { Timer } from './relay.ts'
11
+ import { type Interest, interest } from './interest.js'
12
+
13
+ /** The receiving door's identity and vocabulary versions, never client claims. */
14
+ export type PeerWriter = {
15
+ actor?: Actor | null
16
+ speaks?: Record<string, number>
17
+ }
18
+
19
+ type Value<C> = {
20
+ conn: C
21
+ writer: PeerWriter
22
+ row: Bundle
23
+ connected: boolean
24
+ dirty: boolean
25
+ waiting?: boolean
26
+ reading?: boolean
27
+ invalidated?: boolean
28
+ cancel?: () => void
29
+ }
30
+
31
+ /** Latest peer values saved through the graph's ordinary write boundary. */
32
+ export let saving = <C>(
33
+ graph: Graph,
34
+ timer: Timer,
35
+ failed: (conn: C, err: unknown) => void,
36
+ now: () => number = () => Date.now(),
37
+ ) => {
38
+ let values = new Map<string, Value<C>>()
39
+ let conditions = new Map<string, ReturnType<typeof parse>>()
40
+ let fields = new Map<string, string[] | null>()
41
+ let conditionOf = (comp: string) => {
42
+ let condition = conditions.get(comp)
43
+ if (!condition) {
44
+ condition = parse(saveOf(graph.vocab, comp)!)
45
+ conditions.set(comp, condition)
46
+ }
47
+ return condition
48
+ }
49
+ let signedRows = (rows: Bundle[], writer: PeerWriter) =>
50
+ signed(
51
+ rows.map((b) => ({
52
+ ...b,
53
+ ...writer.speaks ? { $speaks: writer.speaks } : {},
54
+ })),
55
+ writer.actor ?? null,
56
+ )
57
+ let forget = (key: string, v: Value<C>) => {
58
+ v.cancel?.()
59
+ v.cancel = undefined
60
+ if (values.get(key) === v) values.delete(key)
61
+ }
62
+ // A clock can move a relative-time comparison only when its property
63
+ // exists and the other eligibility predicates already hold. Preserve those
64
+ // predicates (notably .player) instead of polling every nonmatching entity.
65
+ let clockQuery = (query: Clause): Clause | null => {
66
+ let timed = false
67
+ let relax = (c: Clause): Clause => {
68
+ if (c.kind == 'and' || c.kind == 'or') {
69
+ let clauses = c.clauses.map(relax)
70
+ return clauses.some((part, i) => part !== c.clauses[i])
71
+ ? { ...c, clauses }
72
+ : c
73
+ }
74
+ if (c.kind != 'pred') return c
75
+ if (c.where) {
76
+ // Under a negative quantifier, making the child easier makes the
77
+ // parent harder. A clock-sensitive negative association is possible,
78
+ // not its negated presence approximation.
79
+ let where = relax(c.where)
80
+ let changed = where !== c.where
81
+ if (c.not && changed) return { kind: 'and', clauses: [] }
82
+ return changed ? { ...c, where } : c
83
+ }
84
+ if (!c.value || c.op == '~=') return c
85
+ let assoc = graph.vocab.assoc(c.path[0])
86
+ if (assoc && c.path.length == 1) return c
87
+ let [leaf] = graph.vocab.aim(
88
+ (assoc ? c.path.slice(1) : c.path).join('.'),
89
+ bare(c),
90
+ ).slice(-1)
91
+ let prop = leaf && graph.vocab.prop(leaf.comp, leaf.prop)
92
+ if (prop?.scalar != 'time' && prop?.scalar != 'number') return c
93
+ let op = c.op == '!=' ? '=' : c.op
94
+ let edges = timeEdges(op, c.value, now())
95
+ if (
96
+ !edges ||
97
+ JSON.stringify(edges) ==
98
+ JSON.stringify(timeEdges(op, c.value, now() + 366 * 86_400_000))
99
+ ) return c
100
+ timed = true
101
+ // A negative comparison can hold for a missing value as well.
102
+ return c.not || c.op == '!='
103
+ ? { kind: 'and', clauses: [] }
104
+ : { ...c, op: '!', value: null }
105
+ }
106
+ let out = relax(query)
107
+ return timed ? out : null
108
+ }
109
+ // A simple local relative-time predicate has a known crossing. Hold its
110
+ // deadline, not a one-second SQL poll. Associations, negations and computed
111
+ // predicates keep the general retry path; relevant commits still invalidate
112
+ // either timer through the same eligibility interest.
113
+ let deadline = (query: Clause, row: Bundle): number | null => {
114
+ let waits: number[] = [], uncertain = false
115
+ let visit = (c: Clause) => {
116
+ if (c.kind == 'and' || c.kind == 'or') {
117
+ c.clauses.forEach(visit)
118
+ return
119
+ }
120
+ if (c.kind != 'pred' || !c.value || c.op == '~=') return
121
+ if (c.value.kind != 'scalar' && c.value.kind != 'time') {
122
+ uncertain = true
123
+ return
124
+ }
125
+ let edges = timeEdges(c.op, c.value, now())
126
+ if (!edges) return
127
+ let future = timeEdges(c.op, c.value, now() + 1000)
128
+ if (JSON.stringify(edges) == JSON.stringify(future)) return
129
+ if (c.where || graph.vocab.assoc(c.path[0])) {
130
+ uncertain = true
131
+ return
132
+ }
133
+ let hops = graph.vocab.aim(c.path.join('.'), bare(c))
134
+ let hop = hops[0]
135
+ if (
136
+ c.not || c.where || hops.length != 1 || !hop ||
137
+ graph.vocab.assoc(c.path[0]) ||
138
+ graph.vocab.prop(hop.comp, hop.prop)?.computed ||
139
+ edges.length != 1 || edges[0].length != 1 ||
140
+ !['<', '<='].includes(edges[0][0][0]) ||
141
+ future?.[0]?.[0]?.[1] != edges[0][0][1] + 1000
142
+ ) {
143
+ uncertain = true
144
+ return
145
+ }
146
+ let value = (row[hop.comp] as Comp | undefined)?.[hop.prop]
147
+ let at = graph.vocab.prop(hop.comp, hop.prop)?.scalar == 'time'
148
+ ? Date.parse(String(value))
149
+ : Number(value)
150
+ if (!Number.isFinite(at)) {
151
+ uncertain = true
152
+ return
153
+ }
154
+ let wait = at - edges[0][0][1] + (edges[0][0][0] == '<' ? 1 : 0)
155
+ if (wait > 0) waits.push(wait)
156
+ }
157
+ visit(query)
158
+ return uncertain || !waits.length ? null : Math.min(...waits)
159
+ }
160
+ let later = (key: string, v: Value<C>, ms: number) => {
161
+ v.cancel?.()
162
+ v.cancel = timer(() => {
163
+ v.cancel = undefined
164
+ try {
165
+ let out = save(key, v)
166
+ if (isPromise(out)) return out.catch((err) => failed(v.conn, err))
167
+ } catch (err) {
168
+ failed(v.conn, err)
169
+ }
170
+ }, ms)
171
+ }
172
+ let save = (key: string, v: Value<C>) => {
173
+ v.cancel?.()
174
+ v.cancel = undefined
175
+ v.waiting = false
176
+ if (!v.dirty) return
177
+ v.reading = true
178
+ v.invalidated = false
179
+ let [comp] = comps(v.row)[0]
180
+ let condition = conditionOf(comp)
181
+ let scope = eq('entity.eid', v.row.entity.eid)
182
+ let failedRead = (err: unknown): never => {
183
+ v.reading = false
184
+ v.waiting = true
185
+ throw err
186
+ }
187
+ let rows: Bundle[] | Promise<Bundle[]>
188
+ let local = (c: Clause): boolean => {
189
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(local)
190
+ if (
191
+ c.kind != 'pred' || c.where || graph.vocab.assoc(c.path[0]) ||
192
+ c.path.length > 2
193
+ ) return false
194
+ let name = c.path[0]
195
+ return !!graph.vocab.comp(name) && !graph.vocab.comp(name)?.computed &&
196
+ (c.path.length == 1 ||
197
+ !graph.vocab.prop(name, c.path[1])?.computed &&
198
+ graph.vocab.prop(name, c.path[1])?.category != 'ref')
199
+ }
200
+ let possibleLocal: Bundle[] | undefined
201
+ try {
202
+ if (!fields.has(comp)) {
203
+ fields.set(
204
+ comp,
205
+ local(condition)
206
+ ? [
207
+ ...new Set((function names(c: Clause): string[] {
208
+ return c.kind == 'and' || c.kind == 'or'
209
+ ? c.clauses.flatMap(names)
210
+ : c.kind == 'pred'
211
+ ? [c.path[0]]
212
+ : []
213
+ })(condition)),
214
+ ]
215
+ : null,
216
+ )
217
+ }
218
+ let names = fields.get(comp)
219
+ if (names) {
220
+ rows = after(
221
+ graph.get([v.row.entity.eid], names, { native: true, durable: true }),
222
+ (stored) => {
223
+ possibleLocal = stored
224
+ return matcher(condition, graph.vocab, { now: now() })(
225
+ stored,
226
+ )
227
+ },
228
+ )
229
+ } else {
230
+ rows = graph.read({
231
+ kind: 'and',
232
+ clauses: [
233
+ ...and(scope, condition).clauses,
234
+ ...parse('.fields=entity.eid').clauses,
235
+ ],
236
+ }, { now: now(), native: true })
237
+ }
238
+ } catch (err) {
239
+ return failedRead(err)
240
+ }
241
+ return after(
242
+ isPromise(rows) ? rows.catch(failedRead) : rows,
243
+ (rows) => {
244
+ v.reading = false
245
+ if (!rows.length) {
246
+ v.waiting = true
247
+ if (v.invalidated) {
248
+ later(key, v, 0)
249
+ return
250
+ }
251
+ let clock = clockQuery(condition)
252
+ if (!clock) return
253
+ return after(
254
+ possibleLocal
255
+ ? matcher(and(clock), graph.vocab, { now: now() })(
256
+ possibleLocal,
257
+ )
258
+ : graph.read(and(scope, clock), { now: now(), native: true }),
259
+ (possible) => {
260
+ if (possible.length) {
261
+ later(key, v, deadline(condition, possible[0]) ?? 1000)
262
+ }
263
+ },
264
+ )
265
+ }
266
+ let row = v.row
267
+ return after(graph.apply(signedRows([row], v.writer)), () => {
268
+ if (v.row === row) v.dirty = false
269
+ if (!v.connected || comps(row)[0][1] == null) forget(key, v)
270
+ })
271
+ },
272
+ )
273
+ }
274
+ // A non-clock eligibility change is owed by a commit, not by an endless
275
+ // timer. Recheck after the write releases; graph.apply may be asynchronous
276
+ // and this hook must never wait for registry work that contains that write.
277
+ let interests = new Map<string, Interest | null>()
278
+ let changed = (v: Value<C>, bundles: Bundle[]) => {
279
+ let [comp] = comps(v.row)[0]
280
+ if (!interests.has(comp)) {
281
+ interests.set(
282
+ comp,
283
+ interest(
284
+ conditionOf(comp),
285
+ graph.vocab,
286
+ () => true,
287
+ ),
288
+ )
289
+ }
290
+ let i = interests.get(comp)
291
+ return !i || i.unseen ||
292
+ bundles.some((b) =>
293
+ comps(b).some(([name]) =>
294
+ i.far.has(name) || i.via.has(name) ||
295
+ (b.entity.eid == v.row.entity.eid && i.near.has(name))
296
+ )
297
+ )
298
+ }
299
+ graph.use({
300
+ name: '@yaks/api/save',
301
+ hooks: {
302
+ effect: (bundles) => {
303
+ for (let [key, v] of values) {
304
+ if (!v.dirty || !changed(v, bundles)) continue
305
+ if (v.reading) v.invalidated = true
306
+ else if (v.waiting) later(key, v, 0)
307
+ }
308
+ return bundles
309
+ },
310
+ },
311
+ })
312
+ let write = (
313
+ conn: C,
314
+ bundles: Bundle[],
315
+ writer: PeerWriter = {},
316
+ held: Bundle[] = [],
317
+ ) => {
318
+ bundles = formed(bundles)
319
+ // Pending saves survive disconnect; current relay values also supply the
320
+ // complete proposed component for checking a partial patch.
321
+ let overlay = bundles.flatMap((b) =>
322
+ comps(b).flatMap(([comp]) => {
323
+ let v = values.get(b.entity.eid + ' ' + comp)
324
+ return v ? [v.row] : []
325
+ })
326
+ ).concat(held)
327
+ return after(
328
+ graph.admit(signedRows(bundles, writer), { overlay }),
329
+ (admitted) => {
330
+ let accepted = admitted.flatMap((b) => {
331
+ let row: Bundle = { entity: { eid: b.entity.eid } }
332
+ for (let [comp, patch] of comps(b)) {
333
+ if (syncOf(graph.vocab, comp) == 'peers') row[comp] = patch
334
+ }
335
+ return comps(row).length ? [row] : []
336
+ })
337
+ let rows = accepted.flatMap((b) =>
338
+ comps(b).flatMap(([comp, patch]) =>
339
+ saveOf(graph.vocab, comp) == null ? [] : [{
340
+ entity: b.entity,
341
+ [comp]: patch == null ? null : {
342
+ ...values.get(b.entity.eid + ' ' + comp)?.row[comp] as Comp,
343
+ ...patch,
344
+ },
345
+ }]
346
+ )
347
+ )
348
+ return after(
349
+ over(rows, (row) => {
350
+ let [comp] = comps(row)[0]
351
+ let key = row.entity.eid + ' ' + comp
352
+ let was = values.get(key)
353
+ let v: Value<C> = was ??
354
+ { conn, writer, row, connected: true, dirty: false }
355
+ v.connected = true
356
+ v.conn = conn
357
+ v.writer = writer
358
+ v.row = row
359
+ v.dirty = true
360
+ values.set(key, v)
361
+ // Eligibility reads stored state, never this incoming peer value.
362
+ // A pending clock/commit retry already owns the next read; new
363
+ // patches only replace the value it will save. Re-reading here
364
+ // both duplicates the retry and cancels/restarts its clock.
365
+ if (v.waiting || v.reading || v.cancel) return
366
+ return save(key, v)
367
+ }),
368
+ () => accepted,
369
+ )
370
+ },
371
+ )
372
+ }
373
+ let drop = (conn: C) =>
374
+ after(
375
+ over([...values], ([key, v]) => {
376
+ if (v.conn !== conn) return
377
+ v.connected = false
378
+ if (!v.dirty) return forget(key, v)
379
+ let refused = (err: unknown) => {
380
+ forget(key, v)
381
+ failed(conn, err)
382
+ }
383
+ try {
384
+ let out = save(key, v)
385
+ return isPromise(out) ? out.catch(refused) : out
386
+ } catch (err) {
387
+ refused(err)
388
+ }
389
+ }),
390
+ () => {},
391
+ )
392
+ return { write, drop }
393
+ }