@yaks/sqlite 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 (289) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1596 -2
  3. package/_dist/archetype.d.ts +75 -0
  4. package/_dist/archetype.d.ts.map +1 -0
  5. package/_dist/branches.d.ts +23 -0
  6. package/_dist/branches.d.ts.map +1 -0
  7. package/_dist/budget.d.ts +52 -0
  8. package/_dist/budget.d.ts.map +1 -0
  9. package/_dist/bundle.d.ts +2 -0
  10. package/_dist/bundle.d.ts.map +1 -0
  11. package/_dist/cache.d.ts +24 -0
  12. package/_dist/cache.d.ts.map +1 -0
  13. package/_dist/catalog.d.ts +9 -0
  14. package/_dist/catalog.d.ts.map +1 -0
  15. package/_dist/check.d.ts +4 -0
  16. package/_dist/check.d.ts.map +1 -0
  17. package/_dist/db.d.ts +36 -0
  18. package/_dist/db.d.ts.map +1 -0
  19. package/_dist/ddl.d.ts +143 -0
  20. package/_dist/ddl.d.ts.map +1 -0
  21. package/_dist/doom.d.ts +22 -0
  22. package/_dist/doom.d.ts.map +1 -0
  23. package/_dist/follow.d.ts +74 -0
  24. package/_dist/follow.d.ts.map +1 -0
  25. package/_dist/history-shapes.d.ts +3 -0
  26. package/_dist/history-shapes.d.ts.map +1 -0
  27. package/_dist/history.d.ts +18 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/inspect.d.ts +43 -0
  30. package/_dist/inspect.d.ts.map +1 -0
  31. package/_dist/jsonb.d.ts +17 -0
  32. package/_dist/jsonb.d.ts.map +1 -0
  33. package/_dist/layout.d.ts +7 -0
  34. package/_dist/layout.d.ts.map +1 -0
  35. package/_dist/ledger.d.ts +41 -0
  36. package/_dist/ledger.d.ts.map +1 -0
  37. package/_dist/meta.d.ts +89 -0
  38. package/_dist/meta.d.ts.map +1 -0
  39. package/_dist/migration.d.ts +41 -0
  40. package/_dist/migration.d.ts.map +1 -0
  41. package/_dist/mod.d.ts +201 -0
  42. package/_dist/mod.d.ts.map +1 -0
  43. package/_dist/mode.d.ts +14 -0
  44. package/_dist/mode.d.ts.map +1 -0
  45. package/_dist/overlay.d.ts +30 -0
  46. package/_dist/overlay.d.ts.map +1 -0
  47. package/_dist/owe.d.ts +180 -0
  48. package/_dist/owe.d.ts.map +1 -0
  49. package/_dist/physical.d.ts +89 -0
  50. package/_dist/physical.d.ts.map +1 -0
  51. package/_dist/point.d.ts +10 -0
  52. package/_dist/point.d.ts.map +1 -0
  53. package/_dist/raise.d.ts +22 -0
  54. package/_dist/raise.d.ts.map +1 -0
  55. package/_dist/read-db.d.ts +9 -0
  56. package/_dist/read-db.d.ts.map +1 -0
  57. package/_dist/read-store.d.ts +10 -0
  58. package/_dist/read-store.d.ts.map +1 -0
  59. package/_dist/read.d.ts +59 -0
  60. package/_dist/read.d.ts.map +1 -0
  61. package/_dist/reader.d.ts +11 -0
  62. package/_dist/reader.d.ts.map +1 -0
  63. package/_dist/rules.d.ts +19 -0
  64. package/_dist/rules.d.ts.map +1 -0
  65. package/_dist/service.d.ts +12 -0
  66. package/_dist/service.d.ts.map +1 -0
  67. package/_dist/shape.d.ts +12 -0
  68. package/_dist/shape.d.ts.map +1 -0
  69. package/_dist/statements.d.ts +4 -0
  70. package/_dist/statements.d.ts.map +1 -0
  71. package/_dist/survey.d.ts +31 -0
  72. package/_dist/survey.d.ts.map +1 -0
  73. package/_dist/tools.d.ts +15 -0
  74. package/_dist/tools.d.ts.map +1 -0
  75. package/_dist/trash.d.ts +18 -0
  76. package/_dist/trash.d.ts.map +1 -0
  77. package/_dist/unit.d.ts +11 -0
  78. package/_dist/unit.d.ts.map +1 -0
  79. package/_dist/vocab.d.ts +6 -0
  80. package/_dist/vocab.d.ts.map +1 -0
  81. package/_dist/write.d.ts +169 -0
  82. package/_dist/write.d.ts.map +1 -0
  83. package/answer.js +110 -0
  84. package/answer.js.map +1 -0
  85. package/answer.ts +122 -0
  86. package/archetype.js +730 -0
  87. package/archetype.js.map +1 -0
  88. package/archetype.ts +790 -0
  89. package/binary_cases.ts +240 -0
  90. package/branches.js +195 -0
  91. package/branches.js.map +1 -0
  92. package/branches.ts +257 -0
  93. package/budget.js +89 -0
  94. package/budget.js.map +1 -0
  95. package/budget.ts +117 -0
  96. package/builtin.js +34 -0
  97. package/builtin.js.map +1 -0
  98. package/builtin.ts +31 -0
  99. package/bundle.js +21 -0
  100. package/bundle.js.map +1 -0
  101. package/bundle.ts +22 -0
  102. package/buried.js +95 -0
  103. package/buried.js.map +1 -0
  104. package/buried.ts +124 -0
  105. package/cache.js +153 -0
  106. package/cache.js.map +1 -0
  107. package/cache.ts +154 -0
  108. package/cache_worker.ts +16 -0
  109. package/catalog.js +173 -0
  110. package/catalog.js.map +1 -0
  111. package/catalog.ts +224 -0
  112. package/check.js +80 -0
  113. package/check.js.map +1 -0
  114. package/check.ts +92 -0
  115. package/checkpoint.js +98 -0
  116. package/checkpoint.js.map +1 -0
  117. package/checkpoint.ts +129 -0
  118. package/checkpoint_worker.ts +37 -0
  119. package/db.js +170 -0
  120. package/db.js.map +1 -0
  121. package/db.ts +173 -0
  122. package/ddl.js +1441 -0
  123. package/ddl.js.map +1 -0
  124. package/ddl.ts +1508 -0
  125. package/deno.json +1 -0
  126. package/doom.js +59 -0
  127. package/doom.js.map +1 -0
  128. package/doom.ts +75 -0
  129. package/driver.js +69 -0
  130. package/driver.js.map +1 -0
  131. package/driver.ts +101 -0
  132. package/error.js +30 -0
  133. package/error.js.map +1 -0
  134. package/error.ts +46 -0
  135. package/ffi/LICENSE +202 -0
  136. package/ffi/blob.js +99 -0
  137. package/ffi/blob.js.map +1 -0
  138. package/ffi/blob.ts +156 -0
  139. package/ffi/constants.js +65 -0
  140. package/ffi/constants.js.map +1 -0
  141. package/ffi/constants.ts +67 -0
  142. package/ffi/database.js +613 -0
  143. package/ffi/database.js.map +1 -0
  144. package/ffi/database.ts +931 -0
  145. package/ffi/ffi.js +535 -0
  146. package/ffi/ffi.js.map +1 -0
  147. package/ffi/ffi.ts +604 -0
  148. package/ffi/mod.js +15 -0
  149. package/ffi/mod.js.map +1 -0
  150. package/ffi/mod.ts +28 -0
  151. package/ffi/statement.js +555 -0
  152. package/ffi/statement.js.map +1 -0
  153. package/ffi/statement.ts +788 -0
  154. package/ffi/util.js +32 -0
  155. package/ffi/util.js.map +1 -0
  156. package/ffi/util.ts +48 -0
  157. package/follow.js +342 -0
  158. package/follow.js.map +1 -0
  159. package/follow.ts +401 -0
  160. package/history-branch.js +166 -0
  161. package/history-branch.js.map +1 -0
  162. package/history-branch.ts +140 -0
  163. package/history-shapes.js +254 -0
  164. package/history-shapes.js.map +1 -0
  165. package/history-shapes.ts +268 -0
  166. package/history.js +620 -0
  167. package/history.js.map +1 -0
  168. package/history.ts +674 -0
  169. package/inspect.js +120 -0
  170. package/inspect.js.map +1 -0
  171. package/inspect.ts +164 -0
  172. package/jsonb.js +73 -0
  173. package/jsonb.js.map +1 -0
  174. package/jsonb.ts +108 -0
  175. package/layout.js +22 -0
  176. package/layout.js.map +1 -0
  177. package/layout.ts +26 -0
  178. package/ledger.js +210 -0
  179. package/ledger.js.map +1 -0
  180. package/ledger.ts +210 -0
  181. package/legacy.js +4 -0
  182. package/legacy.js.map +1 -0
  183. package/legacy.ts +3 -0
  184. package/maintenance.js +148 -0
  185. package/maintenance.js.map +1 -0
  186. package/maintenance.ts +154 -0
  187. package/measure.js +133 -0
  188. package/measure.js.map +1 -0
  189. package/measure.ts +167 -0
  190. package/measure_worker.ts +18 -0
  191. package/memo.js +1250 -0
  192. package/memo.js.map +1 -0
  193. package/memo.ts +1480 -0
  194. package/meta.js +265 -0
  195. package/meta.js.map +1 -0
  196. package/meta.ts +321 -0
  197. package/migration.js +272 -0
  198. package/migration.js.map +1 -0
  199. package/migration.ts +286 -0
  200. package/mod.js +1103 -0
  201. package/mod.js.map +1 -0
  202. package/mod.ts +1762 -0
  203. package/mode.js +192 -0
  204. package/mode.js.map +1 -0
  205. package/mode.ts +207 -0
  206. package/native.js +544 -0
  207. package/native.js.map +1 -0
  208. package/native.ts +544 -0
  209. package/overlay.js +408 -0
  210. package/overlay.js.map +1 -0
  211. package/overlay.ts +485 -0
  212. package/owe.js +719 -0
  213. package/owe.js.map +1 -0
  214. package/owe.ts +873 -0
  215. package/package.json +99 -4
  216. package/physical.js +350 -0
  217. package/physical.js.map +1 -0
  218. package/physical.ts +434 -0
  219. package/plan.js +78 -0
  220. package/plan.js.map +1 -0
  221. package/plan.ts +104 -0
  222. package/point.js +81 -0
  223. package/point.js.map +1 -0
  224. package/point.ts +52 -0
  225. package/population.js +639 -0
  226. package/population.js.map +1 -0
  227. package/population.ts +630 -0
  228. package/purge.js +117 -0
  229. package/purge.js.map +1 -0
  230. package/purge.ts +127 -0
  231. package/raise.js +270 -0
  232. package/raise.js.map +1 -0
  233. package/raise.ts +316 -0
  234. package/read-db.js +381 -0
  235. package/read-db.js.map +1 -0
  236. package/read-db.ts +282 -0
  237. package/read-store.js +74 -0
  238. package/read-store.js.map +1 -0
  239. package/read-store.ts +86 -0
  240. package/read.js +1100 -0
  241. package/read.js.map +1 -0
  242. package/read.ts +1441 -0
  243. package/reader.js +141 -0
  244. package/reader.js.map +1 -0
  245. package/reader.ts +159 -0
  246. package/rules.js +88 -0
  247. package/rules.js.map +1 -0
  248. package/rules.ts +113 -0
  249. package/service.js +27 -0
  250. package/service.js.map +1 -0
  251. package/service.ts +41 -0
  252. package/shape.js +76 -0
  253. package/shape.js.map +1 -0
  254. package/shape.ts +108 -0
  255. package/sparse_presence_fixture.ts +45 -0
  256. package/sqlitepath.js +24 -0
  257. package/sqlitepath.js.map +1 -0
  258. package/sqlitepath.ts +29 -0
  259. package/statements.js +78 -0
  260. package/statements.js.map +1 -0
  261. package/statements.ts +96 -0
  262. package/survey.js +135 -0
  263. package/survey.js.map +1 -0
  264. package/survey.ts +196 -0
  265. package/tools.js +17 -0
  266. package/tools.js.map +1 -0
  267. package/tools.ts +50 -0
  268. package/trash.js +144 -0
  269. package/trash.js.map +1 -0
  270. package/trash.ts +187 -0
  271. package/unit.js +215 -0
  272. package/unit.js.map +1 -0
  273. package/unit.ts +211 -0
  274. package/versions.js +115 -0
  275. package/versions.js.map +1 -0
  276. package/versions.ts +110 -0
  277. package/vocab.js +19 -0
  278. package/vocab.js.map +1 -0
  279. package/vocab.json +27 -0
  280. package/vocab.ts +19 -0
  281. package/watch.js +33 -0
  282. package/watch.js.map +1 -0
  283. package/watch.ts +42 -0
  284. package/write.js +1164 -0
  285. package/write.js.map +1 -0
  286. package/write.ts +1356 -0
  287. package/written.js +200 -0
  288. package/written.js.map +1 -0
  289. package/written.ts +202 -0
package/memo.ts ADDED
@@ -0,0 +1,1480 @@
1
+ // Whole entities a store has read, kept in memory while nothing has written
2
+ // them: the hero a page relays ten times a second is read once, not once per
3
+ // relay. An entity is let go when a write through this package names it
4
+ // (`writes`); every entity is let go when a statement writes a component table
5
+ // any other way and when the schema moves. When another connection commits
6
+ // (@yaks/sql `revision`'s `outside`), a file's log of which entity each write
7
+ // named (./written.ts) says which to let go; where it can't say, every one.
8
+ //
9
+ // A transaction can roll back what it wrote, so its known writes stay in its
10
+ // pending image until commit. A getter for stored components can read that
11
+ // image while classification is still owed; a whole or dynamic read uses SQL.
12
+ // A write this package cannot attribute leaves the image unknown until the
13
+ // transaction ends. The transactions
14
+ // are the ones this connection says: `begin` and savepoints through `query`,
15
+ // and the driver's own `tx`.
16
+ //
17
+ // Spines (./write.ts `spines`: an eid's integer id, number and grave) are kept
18
+ // for the connection too, so the patches one transaction makes read each
19
+ // entity's spine once. A statement that may move one lets every spine go,
20
+ // except a plain mint, which this package tells (`spined().learn`), and a
21
+ // write that names its entities (`writes`), which lets just theirs go; those
22
+ // kept during a transaction go if it rolls back.
23
+ //
24
+ // So are the classes births finish in (`classed`): the archetype an entity
25
+ // first written holding some tables was pointed at by the end of its
26
+ // transaction, so the next birth of that shape is minted in it (./write.ts
27
+ // `Births`). A class learned while a transaction is open goes if it rolls
28
+ // back, since the descriptor it names may go with it.
29
+ //
30
+ // A query's rows are kept too, once it is asked again, while no table its
31
+ // answer stands on has been written (`answer`, `basis`): a page walking back
32
+ // over tiles it has watched asks them again for nothing while nobody has
33
+ // written a place. Every write
34
+ // statement moves its table's count, so nothing a write says has to be
35
+ // trusted; what memory can't follow (text, nearness, edges, computed and
36
+ // derived properties, time phrases) is read every time. An answer about each
37
+ // entity alone stands through a patch or a removal whose entities it selects
38
+ // neither before nor after (`local`, `stand`).
39
+ // Whole and named gets with SQL-state-only derivations use that same bounded
40
+ // answer pool through one global data revision; every mutation ends reuse.
41
+ //
42
+ // What a patch leaves an entity holding is worked out from what memory held
43
+ // and what the patch said, the way a read returns it (`patch`), and kept once
44
+ // the transaction commits: an entity written is not read back to be known. A
45
+ // value a read could return differently (a number into a text column, a
46
+ // derived property, a default the clock fills) leaves the entity to be read,
47
+ // though which components it holds is still known. What memory says an entity
48
+ // holds is the patch's to choose its statements by (./write.ts `patch`'s
49
+ // `had`).
50
+ //
51
+ // Every driver naming one connection (@yaks/sql `Driver.connection`) tells one
52
+ // memory what it ran, so a write through any of them is seen by all.
53
+ //
54
+ // A get naming components is cut from a whole entity held, or from one held
55
+ // in part: what earlier gets naming at least those read, together. Returned
56
+ // bundles are copies, made without a look at each value where what memory
57
+ // holds is JSON; dynamic components (computed, or derived from anything but this
58
+ // connection's rows) are read again on every hit, of the entities holding
59
+ // them. Bounded by bytes (`memoized`'s `memory`) and by an entity for every
60
+ // 2 KiB of them, the longest unread let go first; a scan is read through, not
61
+ // kept.
62
+ import type { Bundle, Comp, Entity } from 'jsr:@yaks/graph@0.2.36'
63
+ import { comps, dead } from '@yaks/graph/bundle'
64
+ import type { Hop, Prop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
65
+ import {
66
+ type And,
67
+ and,
68
+ bare,
69
+ type Clause,
70
+ drifts,
71
+ type Pred,
72
+ } from '@yaks/query'
73
+ import {
74
+ col,
75
+ type Derived,
76
+ type Driver,
77
+ revision,
78
+ type Row,
79
+ type Stmt,
80
+ } from '@yaks/sql/core'
81
+ import { derivedOf, storedOnly, tablesOf } from '@yaks/sql/query'
82
+ import { type Filter, filter } from '@yaks/match'
83
+ import { tables } from './layout.js'
84
+ import { BESIDE } from './history.js'
85
+ import { type Answer as Packed, copied, packed } from './answer.js'
86
+ import type { Known, Spine } from './write.ts'
87
+ import { follows, newest, since } from './written.js'
88
+ import { surveyed } from './survey.js'
89
+
90
+ type Get = (eids: string[], comps?: string[]) => Bundle[]
91
+
92
+ /** A store's memory of whole entities. */
93
+ export type Memo = {
94
+ /** The physical component tables an entity holds, where memory knows its
95
+ * whole after-state and reads every component table the file carries. Value
96
+ * coercion can leave a row's values unknown without losing its presence. */
97
+ presence: (eid: string, tables: readonly string[]) => string[] | undefined
98
+ /** These entities through `get`: whole ones from memory where held. A
99
+ * reader replacing dynamic components itself can defer their refresh. */
100
+ get: (
101
+ get: Get,
102
+ eids: string[],
103
+ comps?: string[],
104
+ refresh?: boolean,
105
+ ) => Bundle[]
106
+ /** A completed get with SQL-state-only policies. Its caller keys every
107
+ * effective read input and keeps authorization/masks inside `run`. */
108
+ view: (key: () => string, run: () => Bundle[], comps?: string[]) => Bundle[]
109
+ /** Run a write that changes the entities `eids` names, given what it
110
+ * returned: they are let go, and kept out until its transaction ends. A
111
+ * write that may make entities it does not name (`mints`, or what it says
112
+ * of what the write returned) lets go of every one remembered as missing. */
113
+ writes: <R>(
114
+ body: () => R,
115
+ eids: (out: R) => Iterable<string>,
116
+ mints?: boolean | ((out: R) => boolean),
117
+ ) => R
118
+ /** Run a patch of `bundles`, which returns the entities it minted or
119
+ * numbered: they and every entity it names are let go as `writes` lets
120
+ * them go, and what each now holds is kept once the transaction commits.
121
+ * `body` is told what memory says each entity held before it. */
122
+ patch: (bundles: Bundle[], body: (known: Known) => Entity[]) => Entity[]
123
+ /** A birth's mint already wrote its final pointer. Keep that metadata with
124
+ * the authoritative after-state before it becomes a committed cache row. */
125
+ pointed: (eid: string, archetype: string) => void
126
+ /** Run a removal of the entities `eids`, buried at `at`: they are let go as
127
+ * `writes` lets them go, and an answer that selected none of them, alive
128
+ * or buried, stands. */
129
+ removes: (eids: string[], at: string, body: () => void) => void
130
+ /** The rows `run` answers the query `key` names with, from memory while no
131
+ * table `tables` names has been written since, or while what was written
132
+ * moved nothing `query` selects; `tables` left out (a query memory can't
133
+ * follow, `basis`), from `run` every time. */
134
+ answer: (
135
+ key: string,
136
+ tables: (() => string[] | undefined) | undefined,
137
+ run: () => Row[],
138
+ proof?: () => {
139
+ query?: And | Filter
140
+ membership?: boolean
141
+ strict?: string[]
142
+ shape?: Filter
143
+ },
144
+ ) => Row[]
145
+ }
146
+
147
+ type Answer = {
148
+ prove?: () => Pick<Answer, 'test' | 'shape' | 'membership' | 'strict'>
149
+ tables: [string, number][]
150
+ rows: Packed
151
+ /** Whole/named gets with SQL-state-only derivations, under all DML. */
152
+ epoch?: number
153
+ /** whether an entity is one the query selects, where memory can tell */
154
+ test?: Filter
155
+ /** Necessary component-presence tests, safe over unknown property values. */
156
+ shape?: Filter
157
+ /** An identity set depends on predicate truth, not selected values. */
158
+ membership?: boolean
159
+ /** Sources whose changes cannot be decided by this row's predicate. */
160
+ strict?: string[]
161
+ }
162
+
163
+ /** The spines a connection keeps. */
164
+ export type Spines = {
165
+ /** These eids' spines: held ones from memory, the rest through `read`. */
166
+ get: (
167
+ eids: string[],
168
+ read: (eids: string[]) => Map<string, Spine>,
169
+ ) => Map<string, Spine>
170
+ /** A spine this connection's own statement just minted. */
171
+ learn: (eid: string, spine: Spine) => void
172
+ }
173
+
174
+ /** What a store's memory of whole entities keeps, in bytes, unless its opener
175
+ * says otherwise (./mod.ts `Opts.memory`): what a Durable Object can spare. */
176
+ export const MEMORY = 4 << 20
177
+ const SPINES = 8192, CLASSES = 256
178
+ // Answers are bounded by count, and one too large to keep is read every time.
179
+ const ANSWERS = 256, ANSWER = 16 << 10
180
+ // How many queries asked once are remembered, waiting to be asked again.
181
+ const ASKED = 4 * ANSWERS
182
+
183
+ // A cache proof only classifies vocabulary paths. Associations and extension
184
+ // paths belong to the compiler; an unroutable one declines the proof.
185
+ let routed = (
186
+ vocab: Vocab,
187
+ path: string[],
188
+ facet = false,
189
+ ): Hop[] | undefined => {
190
+ try {
191
+ return vocab.aim(path.join('.'), facet)
192
+ } catch {
193
+ return undefined
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The tables a query's answer stands on, or `undefined` for one memory can't
199
+ * follow: text, nearness, backlinks, edges, walks and rule clauses; a path
200
+ * nothing declares; a computed or derived property; a time phrase, whose
201
+ * answer moves with the clock. Every answer stands on the graves and, where
202
+ * it is `catalogued`, on the archetype catalog. One that requires no component
203
+ * row (`!product`, `.doc|!doc`) may take in any new entity, so it stands on
204
+ * every entity. A number or an eid moving lets every answer go (`moves`).
205
+ */
206
+ export let basis = (
207
+ vocab: Vocab,
208
+ q: And,
209
+ derived: Derived = {},
210
+ catalogued = false,
211
+ within = false,
212
+ ): string[] | undefined => {
213
+ let out = new Set(['tombstone'])
214
+ let path = (segs: string[], facet = false): boolean => {
215
+ // A backlink is no path aim() answers: say so without the refusal.
216
+ if (!vocab.comp(segs[0]) && vocab.assoc(segs[0])) return false
217
+ let hops = routed(vocab, segs, facet)
218
+ if (!hops) return false
219
+ for (let { comp, prop } of hops) {
220
+ out.add(comp)
221
+ if (comp == 'entity') continue
222
+ if (!vocab.comp(comp) || vocab.comp(comp)!.computed) return false
223
+ if (
224
+ prop &&
225
+ (vocab.prop(comp, prop)?.computed || derived[`${comp}.${prop}`])
226
+ ) return false
227
+ }
228
+ return true
229
+ }
230
+ let visit = (c: Clause): boolean => {
231
+ switch (c.kind) {
232
+ case 'and':
233
+ case 'or':
234
+ return c.clauses.every(visit)
235
+ case 'pred':
236
+ if (catalogued && bare(c)) out.add('archetype')
237
+ return !c.where && path(c.path, bare(c))
238
+ case 'fields':
239
+ return c.fields.every((f) => path(f.path))
240
+ case 'distinct':
241
+ case 'tally':
242
+ return path(c.path)
243
+ case 'order':
244
+ return path(c.value.replace(/^-/, '').split('.'))
245
+ case 'count':
246
+ case 'limit':
247
+ case 'after':
248
+ case 'every':
249
+ case 'never':
250
+ return true
251
+ default:
252
+ return false
253
+ }
254
+ }
255
+ let scalar = (p: Pred) => {
256
+ let leaf = vocab.aim(p.path.join('.'), bare(p)).at(-1)
257
+ return leaf && vocab.prop(leaf.comp, leaf.prop)?.scalar
258
+ }
259
+ // Whether a clause holds only for an entity with a row of some component:
260
+ // one it must hold (`.doc`, parsed as `!` with no value) or a value it must
261
+ // have, under every arm of an `or`. An absence (`!doc`, `= ''`) is not one.
262
+ let anchored = (c: Clause): boolean =>
263
+ c.kind == 'and'
264
+ ? c.clauses.some(anchored)
265
+ : c.kind == 'or'
266
+ ? c.clauses.length > 0 && c.clauses.every(anchored)
267
+ : c.kind == 'pred' && !c.not && c.path[0] != 'entity' &&
268
+ (c.op == '!'
269
+ ? !c.value
270
+ : ['=', '~=', '<', '<=', '>', '>='].includes(c.op) &&
271
+ !(c.value?.kind == 'scalar' && c.value.raw == ''))
272
+ if (!visit(q) || drifts(q, scalar)) return undefined
273
+ if (!within && !anchored(q)) out.add('entity')
274
+ return [...out]
275
+ }
276
+
277
+ // A local identity selection reads no referenced target and has no window.
278
+ export let simple = (vocab: Vocab, query: Clause): boolean => {
279
+ let visit = (c: Clause): boolean => {
280
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(visit)
281
+ if (c.kind == 'every') return true
282
+ if (c.kind != 'pred' || c.where) return false
283
+ let hops = routed(vocab, c.path, bare(c)), h = hops?.[0]
284
+ return hops?.length == 1 && !!h &&
285
+ (!h.prop || vocab.prop(h.comp, h.prop)?.category != 'ref')
286
+ }
287
+ return visit(query)
288
+ }
289
+
290
+ /**
291
+ * Whether what a query selects is told by each entity alone: every path ends
292
+ * on the entity's own components, through no reference, and no `.after`
293
+ * cursor, whose anchor ranks by values a write may move. A write that leaves
294
+ * every entity it moved unselected before and after then moves nothing in its
295
+ * answer. The query is one `basis` follows.
296
+ */
297
+ export let local = (vocab: Vocab, q: And): boolean => {
298
+ let own = (segs: string[], facet = false) => {
299
+ let hops = routed(vocab, segs, facet)
300
+ return !!hops && hops.length <= 1
301
+ }
302
+ let visit = (c: Clause): boolean => {
303
+ switch (c.kind) {
304
+ case 'and':
305
+ case 'or':
306
+ return c.clauses.every(visit)
307
+ case 'pred':
308
+ return own(c.path, bare(c))
309
+ case 'fields':
310
+ return c.fields.every((f) => own(f.path))
311
+ case 'order':
312
+ return own(c.value.replace(/^-/, '').split('.'))
313
+ case 'count':
314
+ case 'limit':
315
+ return true
316
+ default:
317
+ return false
318
+ }
319
+ }
320
+ return visit(q)
321
+ }
322
+
323
+ // A necessary owner test can rule a write out even when the exact predicate
324
+ // follows references. Every referent table remains a strict dependency: a
325
+ // write there can change a selected owner's answer without touching it.
326
+ export let rooted = (
327
+ vocab: Vocab,
328
+ query: And,
329
+ ): { test: Filter; shape: Filter; strict: string[] } | undefined => {
330
+ let strict = new Set<string>()
331
+ let path = (segs: string[], facet = false) => {
332
+ let hops = vocab.aim(segs.join('.'), facet)
333
+ for (let h of hops.slice(1)) strict.add(h.comp)
334
+ return hops.length <= 1
335
+ }
336
+ // A predicate the proof cannot test stands as true, the empty conjunction,
337
+ // wherever it sits. `every` is a projection, which @yaks/match drops at the
338
+ // top and refuses inside a disjunction.
339
+ let visit = (c: Clause, shapes = false): Clause => {
340
+ if (c.kind == 'and' || c.kind == 'or') {
341
+ return { ...c, clauses: c.clauses.map((c) => visit(c, shapes)) }
342
+ }
343
+ if (c.kind == 'pred') {
344
+ return path(c.path, bare(c)) &&
345
+ (!shapes || !vocab.aim(c.path.join('.'), bare(c))[0].prop)
346
+ ? c
347
+ : and()
348
+ }
349
+ if (c.kind == 'fields') {
350
+ c.fields.forEach((f) => path(f.path))
351
+ return { kind: 'every' }
352
+ }
353
+ if (c.kind == 'order') {
354
+ path(c.value.replace(/^-/, '').split('.'))
355
+ return { kind: 'every' }
356
+ }
357
+ if (['every', 'count', 'limit'].includes(c.kind)) return c
358
+ throw new Error('not an owner-local proof')
359
+ }
360
+ try {
361
+ return {
362
+ test: filter(
363
+ { ...query, clauses: query.clauses.map((c) => visit(c)) },
364
+ vocab,
365
+ ),
366
+ shape: filter({
367
+ ...query,
368
+ clauses: query.clauses.map((c) => visit(c, true)),
369
+ }, vocab),
370
+ strict: [...strict],
371
+ }
372
+ } catch {
373
+ return undefined
374
+ }
375
+ }
376
+
377
+ // The blob table a content-addressed property's text is read from.
378
+ const BLOBS = 'blob_text'
379
+
380
+ // An entity a transaction wrote whose state memory can't work out.
381
+ const LOST: unique symbol = Symbol('lost')
382
+
383
+ // A component a patch gave an entity whose values memory can't work out: the
384
+ // entity holds one, which is what a patch's statements are chosen by, but
385
+ // nothing a read asks is answered from it.
386
+ const HOLE = '\0hole'
387
+ let holed = (b: Bundle): boolean =>
388
+ comps(b).some(([, c]) => c != null && HOLE in c)
389
+
390
+ type Kept = {
391
+ /** an entity as read, or `null` for one storage does not hold */
392
+ held: Map<string, Bundle | null>
393
+ /** the components a read naming them asked of an entity held in part; an
394
+ * entity held whole has no entry */
395
+ part: Map<string, Set<string>>
396
+ /** what the open transaction's patches leave each entity holding */
397
+ after: Map<string, Bundle | null | typeof LOST>
398
+ /** components known in an after-state held only in part */
399
+ afterPart: Map<string, Set<string>>
400
+ /** keep what the transaction that just committed left */
401
+ commit: () => void
402
+ sizes: Map<string, number>
403
+ bytes: number
404
+ answers: Map<string, Answer>
405
+ /** queries asked once and not kept, oldest first */
406
+ asked: Set<string>
407
+ tables: Set<string>
408
+ /** whether the file's log follows every table it reads (./written.ts):
409
+ * none beside the store's own but the blob table, whose text no write
410
+ * changes under an address */
411
+ logged: boolean
412
+ /** whether the file has the log's triggers on every one of them, asked
413
+ * once while the schema stands at `schema` */
414
+ follows: (schema: number) => boolean
415
+ clear: () => void
416
+ /** let go of what another connection may have written: the entities
417
+ * `eids` names, or every one, and every answer */
418
+ drop: (eids?: Set<string>) => void
419
+ }
420
+
421
+ // What one connection says about its transactions and writes, shared by every
422
+ // store bound to it.
423
+ type Connection = {
424
+ kept: Set<Kept>
425
+ depth: number
426
+ writing: number
427
+ dirty: Set<string>
428
+ blind: boolean
429
+ spines: Map<string, Spine>
430
+ /** eids whose spine was kept while a transaction is open */
431
+ since: Set<string>
432
+ /** how many statements have written each table */
433
+ versions: Map<string, number>
434
+ /** how many statements have moved a spine */
435
+ shifts: number
436
+ /** answers kept while a transaction is open, by where they are kept */
437
+ answered: [Map<string, Answer>, string][]
438
+ /** the class a birth's opening shape last finished in, by shape */
439
+ classes: Map<string, number>
440
+ /** shapes whose class was learned while a transaction is open */
441
+ learned: Set<string>
442
+ /** the `outside` revision the classes were learned at */
443
+ classedAt: number
444
+ /** the `outside` and `schema` revisions what memory holds was brought to
445
+ * (`follow`) */
446
+ seen: number
447
+ schema: number
448
+ /** the newest row of the file's log (./written.ts) whose entity memory let
449
+ * go, or `undefined` where it read none */
450
+ cursor?: number
451
+ /** the cursor the open transaction began at: a row read inside it may be
452
+ * its own, whose seq another takes if it rolls back */
453
+ began?: number
454
+ /** let go of everything, as when the schema moves */
455
+ moved?: () => void
456
+ }
457
+
458
+ // By connection (@yaks/sql `Driver.connection`): every driver speaking
459
+ // through one tells the same memory what it ran.
460
+ let connections = new WeakMap<object, Connection>()
461
+ let told = new WeakSet<Driver>()
462
+
463
+ let connect = (driver: Driver): Connection => {
464
+ let at = driver.connection ?? driver
465
+ let c = connections.get(at) ?? opened()
466
+ connections.set(at, c)
467
+ if (!told.has(driver)) {
468
+ told.add(driver)
469
+ tell(driver, c)
470
+ }
471
+ return c
472
+ }
473
+
474
+ /** Let go of everything the connection `driver` is holds: what it reads now
475
+ * reads otherwise, as a mode's driver bound to another mode does (./mode.ts). */
476
+ export let turned = (driver: Driver): void =>
477
+ connections.get(driver.connection ?? driver)?.moved?.()
478
+
479
+ let opened = (): Connection => ({
480
+ kept: new Set(),
481
+ depth: 0,
482
+ writing: 0,
483
+ dirty: new Set(),
484
+ blind: false,
485
+ spines: new Map(),
486
+ since: new Set(),
487
+ classes: new Map(),
488
+ learned: new Set(),
489
+ classedAt: -1,
490
+ versions: new Map(),
491
+ shifts: 0,
492
+ answered: [],
493
+ seen: -1,
494
+ schema: -1,
495
+ })
496
+
497
+ // Have `driver` tell the connection `c` each statement and transaction it runs.
498
+ let tell = (driver: Driver, c: Connection) => {
499
+ // What a rolled-back transaction had kept of spines and answers may be gone
500
+ // with it.
501
+ let undone = () => {
502
+ for (let eid of c.since) c.spines.delete(eid)
503
+ c.since.clear()
504
+ for (let shape of c.learned) c.classes.delete(shape)
505
+ c.learned.clear()
506
+ for (let [answers, key] of c.answered) answers.delete(key)
507
+ c.answered = []
508
+ for (let k of c.kept) {
509
+ for (let eid of k.after.keys()) k.after.set(eid, LOST)
510
+ }
511
+ c.cursor = c.began
512
+ }
513
+ let begin = () => {
514
+ if (!c.depth++) c.began = c.cursor
515
+ }
516
+ let ended = (committed: boolean) => {
517
+ if (!committed) undone()
518
+ for (let k of c.kept) {
519
+ if (committed && !c.blind) k.commit()
520
+ k.after.clear()
521
+ k.afterPart.clear()
522
+ }
523
+ c.depth = 0
524
+ c.dirty.clear()
525
+ c.blind = false
526
+ c.since.clear()
527
+ c.learned.clear()
528
+ c.answered = []
529
+ }
530
+ let bump = (table: string) =>
531
+ c.versions.set(table, (c.versions.get(table) ?? 0) + 1)
532
+ let unspine = () => {
533
+ c.spines.clear()
534
+ c.since.clear()
535
+ }
536
+ // The blob table holds text by its address (@yaks/blob): a row added there
537
+ // is text no entity read before, since an address is written after its
538
+ // text, so only a write changing or removing one moves what memory holds.
539
+ let adds = (s: Stmt): boolean => s.t == 'insert' && s.into == BLOBS
540
+ // Whether a write may move an id, a number or a grave: anything but a plain
541
+ // mint into `entity` and a pointer to its archetype.
542
+ let moves = (s: Stmt): boolean =>
543
+ s.t == 'insert'
544
+ ? s.into == 'tombstone' ||
545
+ s.into == 'entity' && (!!s.or || !!s.upsert?.some((u) => u.set))
546
+ : s.t == 'update'
547
+ ? s.table == 'tombstone' ||
548
+ s.table == 'entity' && Object.keys(s.set).some((k) => k != 'archetype')
549
+ : s.t == 'delete' && (s.from == 'entity' || s.from == 'tombstone')
550
+ let forget = (table?: string) => {
551
+ let held = false
552
+ for (let k of c.kept) {
553
+ if (table && !k.tables.has(table)) continue
554
+ k.clear()
555
+ held = true
556
+ }
557
+ if (held && c.depth) c.blind = true
558
+ }
559
+ let held = <W extends Stmt>(w: W): W =>
560
+ w.t == 'insert' && w.into.endsWith(BESIDE)
561
+ ? { ...w, into: w.into.slice(0, -BESIDE.length) }
562
+ : w.t == 'update' && w.table.endsWith(BESIDE)
563
+ ? { ...w, table: w.table.slice(0, -BESIDE.length) }
564
+ : w.t == 'delete' && w.from.endsWith(BESIDE)
565
+ ? { ...w, from: w.from.slice(0, -BESIDE.length) }
566
+ : w
567
+ // Everything read may read otherwise now: the schema moved, or a mode's
568
+ // driver was bound to another mode (./mode.ts, `turned`).
569
+ let moved = c.moved = () => {
570
+ forget()
571
+ grew()
572
+ }
573
+ // A table or index made now holds no row: what memory holds of each entity
574
+ // stands, while what was answered or learned of the schema may not.
575
+ let grew = () => {
576
+ unspine()
577
+ c.classes.clear()
578
+ c.learned.clear()
579
+ for (let k of c.kept) k.answers.clear()
580
+ }
581
+ let observe = (s: Stmt): void => {
582
+ if (s.t == 'raw') return s.origin && observe(s.origin)
583
+ if (s.t == 'begin' || s.t == 'savepoint') begin()
584
+ else if (s.t == 'commit') ended(true)
585
+ else if (s.t == 'rollback') s.to ? undone() : ended(false)
586
+ else if (s.t == 'release' && --c.depth <= 0) ended(true)
587
+ else if (s.t == 'insert' || s.t == 'update' || s.t == 'delete') {
588
+ // A write beside a component's table (./history.ts) is, to what memory
589
+ // holds, a write of it: on a branch it is the component's whole state.
590
+ s = held(s)
591
+ let table = s.t == 'insert' ? s.into : s.t == 'update' ? s.table : s.from
592
+ bump(table)
593
+ if (moves(s)) {
594
+ c.shifts++
595
+ // A write that says which entities it wrote (`writes`) lets go of
596
+ // just their spines.
597
+ if (!c.writing) unspine()
598
+ // A number, an eid or an id itself moved: what any answer ordered,
599
+ // paged or compared a reference by.
600
+ if (table == 'entity') { for (let k of c.kept) k.answers.clear() }
601
+ }
602
+ if (!c.writing && !adds(s)) forget(table)
603
+ } else if (s.t == 'create table' || s.t == 'create index') grew()
604
+ else if (
605
+ s.t.startsWith('create ') || s.t == 'alter table' || s.t == 'drop'
606
+ ) moved()
607
+ }
608
+ let query = driver.query.bind(driver)
609
+ driver.query = (s) => {
610
+ let rows = query(s)
611
+ observe(s)
612
+ return rows
613
+ }
614
+ if (driver.run) {
615
+ let run = driver.run.bind(driver)
616
+ driver.run = (s) => {
617
+ let n = run(s)
618
+ observe(s)
619
+ return n
620
+ }
621
+ }
622
+ // A driver's own transaction is synchronous: it has ended when `tx`
623
+ // returns, whatever its body left running.
624
+ if (driver.tx) {
625
+ let tx = driver.tx.bind(driver)
626
+ driver.tx = (body) => {
627
+ begin()
628
+ let committed = false
629
+ try {
630
+ let out = tx(body)
631
+ committed = true
632
+ return out
633
+ } finally {
634
+ // One nested in another rolls back to where it began.
635
+ if (--c.depth <= 0) ended(committed)
636
+ else if (!committed) undone()
637
+ }
638
+ }
639
+ }
640
+ }
641
+
642
+ // Bring what memory holds of the connection `c` past what other connections
643
+ // committed since it last looked: let go of the entities the file's log says
644
+ // they wrote (./written.ts), or of every one where it can't say, as when the
645
+ // schema moved, which nothing logs.
646
+ let follow = (driver: Driver, c: Connection) => {
647
+ let now = revision(driver, 'outside')
648
+ if (now == c.seen) return
649
+ let schema = revision(driver, 'schema')
650
+ // A store in memory keeps no log: its one connection sees every statement.
651
+ let logged = !!driver.file &&
652
+ [...c.kept].every((k) => k.logged && k.follows(schema))
653
+ let written = logged && schema == c.schema && c.cursor != null
654
+ ? since(driver, c.cursor)
655
+ : undefined
656
+ for (let k of c.kept) k.drop(written?.eids)
657
+ if (written) {
658
+ for (let eid of written.eids) c.spines.delete(eid)
659
+ } else {
660
+ c.spines.clear()
661
+ c.since.clear()
662
+ }
663
+ c.cursor = written ? written.at : logged ? newest(driver) : undefined
664
+ c.seen = now
665
+ c.schema = schema
666
+ }
667
+
668
+ /** The spines kept for the connection `driver` is. */
669
+ export let spined = (driver: Driver): Spines => {
670
+ let c = connect(driver)
671
+ let keep = (eid: string, spine: Spine) => {
672
+ c.spines.delete(eid)
673
+ c.spines.set(eid, spine)
674
+ if (c.depth) c.since.add(eid)
675
+ if (c.spines.size > SPINES) c.spines.delete(c.spines.keys().next().value!)
676
+ }
677
+ return {
678
+ get: (eids, read) => {
679
+ follow(driver, c)
680
+ let out = new Map<string, Spine>()
681
+ let missing = eids.filter((eid) => {
682
+ let held = c.spines.get(eid)
683
+ if (held) out.set(eid, { ...held })
684
+ return !held
685
+ })
686
+ if (missing.length) {
687
+ for (let [eid, spine] of read(missing)) {
688
+ out.set(eid, spine)
689
+ keep(eid, { ...spine })
690
+ }
691
+ }
692
+ return out
693
+ },
694
+ learn: (eid, spine) => keep(eid, { ...spine }),
695
+ }
696
+ }
697
+
698
+ /** The classes births finish in, kept for a connection (./write.ts `Births`). */
699
+ export type Classes = {
700
+ /** The archetype's integer id a birth opening in `shape` last finished in. */
701
+ get: (shape: string) => number | undefined
702
+ /** A birth opening in `shape` finished in the archetype `id`. */
703
+ learn: (shape: string, id: number) => void
704
+ }
705
+
706
+ /** The classes kept for the connection `driver` is. */
707
+ export let classed = (driver: Driver): Classes => {
708
+ let c = connect(driver)
709
+ // Another connection's commit or a schema change may have moved the file
710
+ // under what was learned.
711
+ let current = () => {
712
+ let now = revision(driver, 'outside')
713
+ if (now == c.classedAt) return
714
+ c.classes.clear()
715
+ c.learned.clear()
716
+ c.classedAt = now
717
+ }
718
+ return {
719
+ get: (shape) => {
720
+ current()
721
+ return c.classes.get(shape)
722
+ },
723
+ learn: (shape, id) => {
724
+ current()
725
+ c.classes.delete(shape)
726
+ c.classes.set(shape, id)
727
+ if (c.depth) c.learned.add(shape)
728
+ if (c.classes.size > CLASSES) {
729
+ c.classes.delete(c.classes.keys().next().value!)
730
+ }
731
+ },
732
+ }
733
+ }
734
+
735
+ // What a bundle takes in memory, about as many bytes as its JSON spelled out
736
+ // in UTF-16, worked out without spelling it: a bundle may hold a transcript.
737
+ let sizeOf = (b: Bundle) => chars(b) * 2
738
+
739
+ let chars = (value: unknown): number => {
740
+ if (typeof value == 'string') return value.length + 2
741
+ if (value == null || typeof value != 'object') return String(value).length
742
+ if (ArrayBuffer.isView(value)) return value.byteLength
743
+ let n = 2
744
+ if (Array.isArray(value)) { for (let v of value) n += chars(v) + 1 }
745
+ else {
746
+ for (let [k, v] of Object.entries(value)) n += k.length + 4 + chars(v)
747
+ }
748
+ return n
749
+ }
750
+
751
+ // What `cloned` answers for a value it leaves to structuredClone.
752
+ const OTHER = Symbol('other')
753
+
754
+ // A JSON value copied: primitives, plain objects and arrays, each object met
755
+ // once. Anything else (a Date, bytes, a Map, a hole, an object met twice) is
756
+ // OTHER, since structuredClone copies those as a read of them expects.
757
+ let cloned = (value: unknown, seen: Set<object>): unknown => {
758
+ if (typeof value != 'object' || value === null) {
759
+ return typeof value == 'function' || typeof value == 'symbol'
760
+ ? OTHER
761
+ : value
762
+ }
763
+ if (seen.has(value)) return OTHER
764
+ seen.add(value)
765
+ let proto = Object.getPrototypeOf(value)
766
+ if (proto == Array.prototype) {
767
+ let from = value as unknown[], out = new Array(from.length)
768
+ for (let i = 0; i < from.length; i++) {
769
+ let v = i in from ? cloned(from[i], seen) : OTHER
770
+ if (v === OTHER) return OTHER
771
+ out[i] = v
772
+ }
773
+ return out
774
+ }
775
+ if (proto != Object.prototype && proto != null) return OTHER
776
+ let out: Record<string, unknown> = {}
777
+ for (let key of Object.keys(value)) {
778
+ let v = cloned((value as Record<string, unknown>)[key], seen)
779
+ if (v === OTHER) return OTHER
780
+ out[key] = v
781
+ }
782
+ return out
783
+ }
784
+
785
+ // The components `names` of a bundle copied as JSON, or undefined where one
786
+ // holds anything else.
787
+ let json = (b: Bundle, names: string[]): Bundle | undefined => {
788
+ let out: Record<string, unknown> = {}, seen = new Set<object>()
789
+ for (let name of names) {
790
+ let comp = cloned(b[name], seen)
791
+ if (comp === OTHER) return undefined
792
+ out[name] = comp
793
+ }
794
+ return out as Bundle
795
+ }
796
+
797
+ // A copy of a value that is JSON and shares no object.
798
+ let dup = (value: unknown): unknown => {
799
+ if (typeof value != 'object' || value === null) return value
800
+ if (Array.isArray(value)) return value.map(dup)
801
+ let out: Record<string, unknown> = {}
802
+ for (let key in value) out[key] = dup((value as Record<string, unknown>)[key])
803
+ return out
804
+ }
805
+
806
+ // The bundles memory holds that are JSON throughout and share no object
807
+ // (`json` made them), whose copies need not look at each value. No caller
808
+ // is handed one.
809
+ let trees = new WeakSet<Bundle>()
810
+
811
+ // What memory holds of a bundle it is given: a copy, marked when it is JSON.
812
+ let kept = (b: Bundle): Bundle => {
813
+ let tree = json(b, Object.keys(b))
814
+ if (!tree) return structuredClone(b)
815
+ trees.add(tree)
816
+ return tree
817
+ }
818
+
819
+ // Copy only the facets this read exposes, each value fresh. Values other than
820
+ // JSON keep structuredClone's semantics, shared references included, across
821
+ // the selected bundle.
822
+ let copy = (
823
+ b: Bundle,
824
+ wanted?: Set<string>,
825
+ omitted: string[] = [],
826
+ ): Bundle => {
827
+ let names = Object.keys(b).filter((name) =>
828
+ (!omitted.length || !omitted.includes(name)) &&
829
+ (!wanted || name == 'entity' || name == 'tombstone' || wanted.has(name))
830
+ )
831
+ if (trees.has(b)) {
832
+ let out: Record<string, unknown> = {}
833
+ for (let name of names) out[name] = dup(b[name])
834
+ return out as Bundle
835
+ }
836
+ return json(b, names) ??
837
+ structuredClone(Object.fromEntries(names.map((n) => [n, b[n]]))) as Bundle
838
+ }
839
+
840
+ /** The memory of whole entities for a store bound to `driver` and `vocab`,
841
+ * keeping up to `memory` bytes of them. */
842
+ export let memoized = (
843
+ driver: Driver,
844
+ vocab: Vocab,
845
+ given?: Derived,
846
+ memory = MEMORY,
847
+ ): Memo => {
848
+ let derived = given ?? {}
849
+ let c = connect(driver)
850
+ let count = Math.floor(memory / 2048)
851
+ // A read of more entities than this is a scan: what it reads is not kept,
852
+ // so it does not push out what is read again and again.
853
+ let scan = Math.floor(count / 4)
854
+ let own = new Set(['entity', 'tombstone', BLOBS, ...tables(vocab)])
855
+ let through = Object.values(derived).flatMap((d) =>
856
+ storedOnly(d, vocab) ? tablesOf(d.expr(col('__owner'))) ?? [] : []
857
+ )
858
+ // Whether the log follows the tables kept here, while the schema stands:
859
+ // as the file's survey says where it is current (./survey.ts), or else as
860
+ // the file itself does.
861
+ let logs: { schema: number; follows: boolean } | undefined
862
+ let k: Kept = {
863
+ held: new Map(),
864
+ part: new Map(),
865
+ sizes: new Map(),
866
+ bytes: 0,
867
+ answers: new Map(),
868
+ asked: new Set(),
869
+ after: new Map(),
870
+ afterPart: new Map(),
871
+ tables: new Set([...own, ...through]),
872
+ logged: through.every((name) => own.has(name)),
873
+ follows: (schema) => {
874
+ if (logs?.schema !== schema) {
875
+ let found = surveyed(driver, vocab, given)
876
+ logs = {
877
+ schema,
878
+ follows: found
879
+ ? !found.unlogged.length
880
+ : follows(driver, [...k.tables].filter((name) => name != BLOBS)),
881
+ }
882
+ }
883
+ return logs.follows
884
+ },
885
+ clear: () => {
886
+ k.held.clear()
887
+ k.part.clear()
888
+ k.sizes.clear()
889
+ k.bytes = 0
890
+ },
891
+ drop: (eids) => {
892
+ k.answers.clear()
893
+ if (!eids) k.clear()
894
+ for (let eid of eids ?? k.after.keys()) {
895
+ if (eids) evict(eid)
896
+ if (k.after.has(eid)) k.after.set(eid, LOST)
897
+ }
898
+ },
899
+ // What a transaction writing more than a scan reads is not kept either.
900
+ commit: () => {
901
+ if (k.after.size > scan) return
902
+ for (let [eid, b] of k.after) {
903
+ if (b !== LOST && !(b && holed(b))) hold(eid, b, k.afterPart.get(eid))
904
+ }
905
+ trim()
906
+ },
907
+ }
908
+ c.kept.add(k)
909
+ let evict = (eid: string) => {
910
+ k.bytes -= k.sizes.get(eid) ?? 0
911
+ k.sizes.delete(eid)
912
+ k.held.delete(eid)
913
+ k.part.delete(eid)
914
+ }
915
+ // Held whole, or in part: only the components `asked` names. What memory
916
+ // already holds of it in part still stands, since nothing wrote it, and
917
+ // is held beside them: two reads naming different components of one
918
+ // entity are each answered from memory.
919
+ let hold = (eid: string, b: Bundle | null, asked?: Set<string>) => {
920
+ let had = k.part.get(eid), was = k.held.get(eid)
921
+ if (b && asked && had && was) {
922
+ b = { ...was, ...b }
923
+ asked = new Set([...had, ...asked])
924
+ }
925
+ evict(eid)
926
+ let size = b ? sizeOf(b) : 64
927
+ k.sizes.set(eid, size)
928
+ k.bytes += size
929
+ k.held.set(eid, b && kept(b))
930
+ if (asked) k.part.set(eid, asked)
931
+ }
932
+ // Whether memory holds what a read asks of an entity: all of it, or the
933
+ // components `wanted` names.
934
+ let holds = (eid: string, wanted?: Set<string>) => {
935
+ let part = k.part.get(eid)
936
+ if (!k.held.has(eid)) return false
937
+ if (!part) return true
938
+ if (!wanted) return false
939
+ for (let name of wanted) if (!part.has(name)) return false
940
+ return true
941
+ }
942
+ // Oldest first, through one iterator: V8 keeps the slot of each entry a Map
943
+ // deletes until it rehashes, and a fresh iterator steps over every such slot
944
+ // before the oldest entry left, so an iterator per eviction stepped over the
945
+ // same slots again for each entry a large bundle evicted.
946
+ let trim = () => {
947
+ let oldest = k.held.keys()
948
+ while (k.held.size > count || k.bytes > memory) {
949
+ evict(oldest.next().value!)
950
+ }
951
+ }
952
+ let providers = derivedOf(vocab, derived)
953
+ let dynamic = new Set(
954
+ Object.entries(providers).filter(([, d]) => !storedOnly(d, vocab)).map((
955
+ [p],
956
+ ) => p.split('.')[0]),
957
+ )
958
+ for (let name of vocab.comps) {
959
+ if (
960
+ vocab.comp(name)?.computed ||
961
+ vocab.props(name).some((p) =>
962
+ vocab.prop(name, p)?.computed && !derived[`${name}.${p}`]?.stable
963
+ )
964
+ ) dynamic.add(name)
965
+ }
966
+ let writes = <R>(
967
+ body: () => R,
968
+ eids: (out: R) => Iterable<string>,
969
+ mints: boolean | ((out: R) => boolean) = false,
970
+ ): R => {
971
+ c.writing++
972
+ let shifts = c.shifts
973
+ let out
974
+ try {
975
+ out = body()
976
+ } catch (error) {
977
+ // What it wrote before it failed is not known: keep nothing until
978
+ // its transaction ends.
979
+ k.clear()
980
+ for (let other of c.kept) other.clear()
981
+ if (c.shifts != shifts) {
982
+ c.spines.clear()
983
+ c.since.clear()
984
+ }
985
+ if (c.depth) c.blind = true
986
+ throw error
987
+ } finally {
988
+ c.writing--
989
+ }
990
+ let gone = (other: Kept, eid: string) => {
991
+ other.bytes -= other.sizes.get(eid) ?? 0
992
+ other.sizes.delete(eid)
993
+ other.held.delete(eid)
994
+ other.part.delete(eid)
995
+ other.afterPart.delete(eid)
996
+ if (c.depth) other.after.set(eid, LOST)
997
+ }
998
+ for (let eid of eids(out)) {
999
+ for (let other of c.kept) gone(other, eid)
1000
+ if (c.depth) c.dirty.add(eid)
1001
+ // An id, a number or a grave it moved is one of these entities'.
1002
+ if (c.shifts != shifts) c.spines.delete(eid)
1003
+ }
1004
+ if (typeof mints == 'function' ? mints(out) : mints) {
1005
+ // What it minted is not named: neither is whose spine it moved.
1006
+ if (c.shifts != shifts) {
1007
+ c.spines.clear()
1008
+ c.since.clear()
1009
+ }
1010
+ for (let other of c.kept) {
1011
+ for (let [eid, b] of other.held) if (!b) gone(other, eid)
1012
+ for (let [eid, b] of other.after) if (b === null) gone(other, eid)
1013
+ }
1014
+ if (c.depth) c.blind = true
1015
+ }
1016
+ return out
1017
+ }
1018
+ // What an entity held before this transaction's next patch: what its
1019
+ // patches so far left it, or what memory held while nothing wrote it.
1020
+ let prior = (eid: string): Bundle | null | typeof LOST =>
1021
+ k.afterPart.has(eid)
1022
+ ? LOST
1023
+ : k.after.has(eid)
1024
+ ? k.after.get(eid)!
1025
+ : c.dirty.has(eid) || !holds(eid)
1026
+ ? LOST
1027
+ : k.held.get(eid)!
1028
+ let numbered = !!vocab.prop('entity', 'num')
1029
+ let typed = !!vocab.comp('archetype')
1030
+ // A component's stored properties, where what a patch gives them is what a
1031
+ // read returns: not one with a derived property, which a read works out
1032
+ // itself, unless it is read again on every hit anyway.
1033
+ let shapes = new Map<string, Map<string, Prop> | null>()
1034
+ let shape = (name: string): Map<string, Prop> | null => {
1035
+ if (!shapes.has(name)) {
1036
+ let props = vocab.comp(name) && k.tables.has(name)
1037
+ ? vocab.props(name).map((p) => vocab.prop(name, p)!)
1038
+ : undefined
1039
+ let exact = props && (dynamic.has(name) ||
1040
+ !props.some((p) => p.computed || derived[`${name}.${p.prop}`]))
1041
+ shapes.set(
1042
+ name,
1043
+ props && exact
1044
+ ? new Map(props.filter((p) => !p.computed).map((p) => [p.prop, p]))
1045
+ : null,
1046
+ )
1047
+ }
1048
+ return shapes.get(name)!
1049
+ }
1050
+ // A value as a read returns it once a patch has stored it, where that is
1051
+ // certain: what SQLite would convert on the way in is not.
1052
+ let cast = (p: Prop, v: unknown): unknown => {
1053
+ if (v == null) return null
1054
+ if (p.category == 'ref') return typeof v == 'string' ? v : LOST
1055
+ if (p.scalar == 'jsonb') {
1056
+ let text = JSON.stringify(v)
1057
+ return text === undefined ? LOST : JSON.parse(text)
1058
+ }
1059
+ if (p.scalar == 'binary') return v instanceof Uint8Array ? v.slice() : LOST
1060
+ if (p.scalar == 'bool') return typeof v == 'boolean' ? v : LOST
1061
+ if (p.affinity == 'text') return typeof v == 'string' ? v : LOST
1062
+ if (p.affinity == 'integer' || p.affinity == 'real') {
1063
+ return typeof v == 'number' && Number.isFinite(v) && !Object.is(v, -0) &&
1064
+ (!Number.isInteger(v) || Number.isSafeInteger(v))
1065
+ ? v
1066
+ : LOST
1067
+ }
1068
+ return LOST
1069
+ }
1070
+ // What one bundle of a patch leaves an entity holding, from what it held
1071
+ // (`null`: nothing) and the spine the patch minted or numbered for it.
1072
+ // Memory owns both snapshots. A patch replaces each changed component
1073
+ // and reads copy the values they hand out, so untouched values can be shared.
1074
+ let fold = (
1075
+ base: Bundle | null,
1076
+ b: Bundle,
1077
+ mint?: Entity,
1078
+ ): Bundle | null | typeof LOST => {
1079
+ let out = base
1080
+ ? { ...base }
1081
+ : mint
1082
+ ? { entity: { eid: b.entity.eid } }
1083
+ : null
1084
+ if (!out) return comps(b).length || b.entity.archetype ? LOST : null
1085
+ if (mint && numbered && mint.num != null) {
1086
+ out.entity = {
1087
+ ...out.entity,
1088
+ num: mint.num,
1089
+ ...mint.prefix == null ? {} : { prefix: mint.prefix },
1090
+ }
1091
+ }
1092
+ if (typed && b.entity.archetype !== undefined) {
1093
+ let { archetype: _, ...entity } = out.entity
1094
+ out.entity = b.entity.archetype == null
1095
+ ? entity
1096
+ : { ...entity, archetype: String(b.entity.archetype) }
1097
+ }
1098
+ // A patch writes no rows to the dead (./write.ts `patch`).
1099
+ if ('tombstone' in out) return out
1100
+ for (let [name, comp] of comps(b)) {
1101
+ if (comp == null) {
1102
+ delete out[name]
1103
+ continue
1104
+ }
1105
+ out[name] = put(out[name] as Comp | undefined, name, comp)
1106
+ }
1107
+ return out
1108
+ }
1109
+ // What a component holds once a patch gives it `comp`, from what it held.
1110
+ let put = (had: Comp | undefined, name: string, comp: Comp): Comp => {
1111
+ let props = shape(name)
1112
+ if (!props) return { [HOLE]: true }
1113
+ let next: Comp = had ? { ...had } : {}
1114
+ // A row this patch brings takes each default it does not give.
1115
+ for (let [p, prop] of had ? [] : props) {
1116
+ if (p in comp) continue
1117
+ let d = prop.default
1118
+ let v = !d ? null : 'now' in d ? LOST : cast(prop, d.value)
1119
+ if (v === LOST) return { [HOLE]: true }
1120
+ if (v != null) next[p] = v
1121
+ }
1122
+ for (let [p, v] of Object.entries(comp)) {
1123
+ let prop = props.get(p)
1124
+ let value = prop ? cast(prop, v) : LOST
1125
+ if (value === LOST) return { [HOLE]: true }
1126
+ if (value == null) delete next[p]
1127
+ else next[p] = value
1128
+ }
1129
+ return next
1130
+ }
1131
+ // An answer whose query the entities a patch moved were selected by neither
1132
+ // before nor after it stands where it stood: its tables moved, its rows did
1133
+ // not. `before` is the tables' counts the patch began at.
1134
+ let stand = (
1135
+ was: Map<string, Bundle | null | typeof LOST>,
1136
+ now: Map<string, Bundle | null | typeof LOST>,
1137
+ before: Map<string, number>,
1138
+ ) => {
1139
+ let selects = (a: Answer, b: Bundle | null | typeof LOST | undefined) =>
1140
+ b === LOST || b === undefined ||
1141
+ (b != null && (holed(b) ? a.shape?.(b) ?? true : a.test!(b)))
1142
+ for (let a of k.answers.values()) {
1143
+ if (a.tables.some(([t, n]) => (before.get(t) ?? 0) != n)) continue
1144
+ if (a.tables.every(([t, n]) => (c.versions.get(t) ?? 0) == n)) continue
1145
+ if (a.prove) {
1146
+ Object.assign(a, a.prove())
1147
+ delete a.prove
1148
+ }
1149
+ if (!a.test) continue
1150
+ if (
1151
+ a.strict?.some((t) => (before.get(t) ?? 0) != (c.versions.get(t) ?? 0))
1152
+ ) {
1153
+ continue
1154
+ }
1155
+ let moved = [...now.keys()].some((eid) => {
1156
+ let before = was.get(eid), after = now.get(eid)
1157
+ if (a.membership) {
1158
+ if (
1159
+ [before, after].some((b) =>
1160
+ typeof b == 'symbol' || b === undefined ||
1161
+ b && holed(b) && (a.shape?.(b) ?? true)
1162
+ )
1163
+ ) return true
1164
+ return selects(a, before) != selects(a, after)
1165
+ }
1166
+ return selects(a, before) || selects(a, after)
1167
+ })
1168
+ if (!moved) a.tables = a.tables.map(([t]) => [t, c.versions.get(t) ?? 0])
1169
+ }
1170
+ }
1171
+ // Another connection's commit, or anything else this one cannot see.
1172
+ let sync = () => follow(driver, c)
1173
+ // A stable relation can change when another entity is patched. Such
1174
+ // components refresh on every miss; only this global revision can reuse the
1175
+ // completed answer. Unproven providers remain uncached.
1176
+ let related = Object.entries(providers).filter(([, d]) =>
1177
+ !storedOnly(d, vocab)
1178
+ )
1179
+ let reusable = new Set(
1180
+ related.filter(([, d]) => d.stable).map(([p]) => p.split('.')[0]),
1181
+ )
1182
+ let safe = (rows: Bundle[], comps?: string[]) => {
1183
+ let names = new Set(rows.flatMap((b) => Object.keys(b)))
1184
+ if (
1185
+ [...names].some((n) =>
1186
+ vocab.comp(n)?.computed || vocab.props(n).some((p) => {
1187
+ let ref = vocab.prop(n, p)?.ref
1188
+ return ref && vocab.comp(ref)?.computed
1189
+ })
1190
+ )
1191
+ ) return false
1192
+ let reads = related.filter(([p, d]) =>
1193
+ names.has(p.split('.')[0]) && (!!comps || d.whole !== false)
1194
+ )
1195
+ return reads.length > 0 && reads.every(([, d]) => d.stable)
1196
+ }
1197
+ let remember = (key: string, a: Answer) => {
1198
+ k.answers.set(key, a)
1199
+ if (c.depth) c.answered.push([k.answers, key])
1200
+ if (k.answers.size > ANSWERS) {
1201
+ k.answers.delete(k.answers.keys().next().value!)
1202
+ }
1203
+ }
1204
+ let getting = (
1205
+ get: Get,
1206
+ eids: string[],
1207
+ comps?: string[],
1208
+ refresh = true,
1209
+ ) => {
1210
+ // A get naming components is answered from an entity held whole, or
1211
+ // held in part with them, cut to them. What one reads is held in part,
1212
+ // unless it says all there is: an entity storage lacks, or a dead one.
1213
+ let wanted = comps && new Set(comps)
1214
+ // This transaction already knows the aspects its own patches produced.
1215
+ // A whole read can use them when none are missing or need deriving.
1216
+ let written = new Map<string, Bundle | null>()
1217
+ if (c.depth && !c.blind && !comps?.some((n) => dynamic.has(n))) {
1218
+ for (let eid of eids) {
1219
+ let b = k.after.get(eid), part = k.afterPart.get(eid)
1220
+ if (
1221
+ b === undefined || b === LOST ||
1222
+ part && !comps?.every((n) => part.has(n))
1223
+ ) continue
1224
+ if (
1225
+ b &&
1226
+ (comps
1227
+ ? comps.some((n) => b[n] != null && HOLE in (b[n] as Comp))
1228
+ // A mint may have picked a pointer the patch did not state.
1229
+ : (typed && !b.entity.archetype) || holed(b) ||
1230
+ Object.keys(b).some((n) => dynamic.has(n)))
1231
+ ) continue
1232
+ written.set(eid, b)
1233
+ }
1234
+ }
1235
+ let missing = [...new Set(eids)].filter((eid) =>
1236
+ !written.has(eid) && !holds(eid, wanted)
1237
+ )
1238
+ let read = new Set(missing)
1239
+ let fresh = new Map(
1240
+ (missing.length ? get(missing, comps) : []).map((
1241
+ b,
1242
+ ) => [b.entity.eid, b]),
1243
+ )
1244
+ if (!c.blind && missing.length <= scan) {
1245
+ for (let eid of missing) {
1246
+ if (c.dirty.has(eid)) continue
1247
+ let b = fresh.get(eid) ?? null
1248
+ hold(eid, b, wanted && b && !dead(b) ? wanted : undefined)
1249
+ }
1250
+ }
1251
+ let hits = eids.filter((eid) =>
1252
+ !written.has(eid) && !read.has(eid) && k.held.get(eid)
1253
+ )
1254
+ // A hit's dynamic components are read now, in one statement, of the hits
1255
+ // holding any.
1256
+ let changing = refresh &&
1257
+ (!wanted || [...wanted].some((name) => dynamic.has(name)))
1258
+ let stale = new Map(
1259
+ (changing ? hits : []).flatMap((eid) => {
1260
+ let names = Object.keys(k.held.get(eid)!).filter((name) =>
1261
+ dynamic.has(name) && (!wanted || wanted.has(name))
1262
+ )
1263
+ return names.length ? [[eid, names] as const] : []
1264
+ }),
1265
+ )
1266
+ let names = [...new Set([...stale.values()].flat())]
1267
+ let current = new Map(
1268
+ (names.length ? get([...stale.keys()], names) : []).map((
1269
+ b,
1270
+ ) => [b.entity.eid, b]),
1271
+ )
1272
+ let out = eids.flatMap((eid) => {
1273
+ if (written.has(eid)) {
1274
+ let b = written.get(eid)
1275
+ return b ? [copy(b, wanted)] : []
1276
+ }
1277
+ if (read.has(eid)) return fresh.has(eid) ? [fresh.get(eid)!] : []
1278
+ let held = k.held.get(eid)!
1279
+ k.held.delete(eid)
1280
+ k.held.set(eid, held)
1281
+ if (!held) return []
1282
+ let b = copy(held, wanted, names), now = current.get(eid)
1283
+ return [now ? Object.assign(b, now) : b]
1284
+ })
1285
+ trim()
1286
+ return out
1287
+ }
1288
+ let viewed = (keyOf: () => string, run: () => Bundle[], comps?: string[]) => {
1289
+ sync()
1290
+ if (
1291
+ !reusable.size ||
1292
+ comps && !comps.some((n) => reusable.has(n))
1293
+ ) return run()
1294
+ let key = keyOf()
1295
+ let limit = ANSWER - key.length * 2
1296
+ if (limit <= 0) return run()
1297
+ let epoch = revision(driver, 'data')
1298
+ let held = k.answers.get(key)
1299
+ if (held?.epoch == epoch) {
1300
+ k.answers.delete(key)
1301
+ k.answers.set(key, held)
1302
+ return copied(held.rows) as Bundle[]
1303
+ }
1304
+ if (held) k.answers.delete(key)
1305
+ let rows = run()
1306
+ if (!safe(rows, comps) || epoch != revision(driver, 'data')) return rows
1307
+ if (!held && !k.asked.delete(key)) {
1308
+ k.asked.add(key)
1309
+ if (k.asked.size > ASKED) k.asked.delete(k.asked.values().next().value!)
1310
+ return rows
1311
+ }
1312
+ let kept = packed(rows, limit)
1313
+ if (kept) remember(key, { tables: [], epoch, rows: kept })
1314
+ return rows
1315
+ }
1316
+ let stored = new Set(['tombstone', ...tables(vocab)])
1317
+ return {
1318
+ pointed: (eid, archetype) => {
1319
+ let b = k.after.get(eid)
1320
+ if (b && b !== LOST) {
1321
+ k.after.set(eid, { ...b, entity: { ...b.entity, archetype } })
1322
+ }
1323
+ },
1324
+ presence: (eid, tables) => {
1325
+ sync()
1326
+ if (c.blind || !tables.every((name) => stored.has(name))) {
1327
+ return undefined
1328
+ }
1329
+ let b = prior(eid)
1330
+ return b === LOST || b == null
1331
+ ? undefined
1332
+ : tables.filter((name) => b[name] != null)
1333
+ },
1334
+ answer: (key, dependencies, run, prove) => {
1335
+ if (!dependencies) return run()
1336
+ sync()
1337
+ let current = (table: string) => c.versions.get(table) ?? 0
1338
+ let held = k.answers.get(key)
1339
+ if (held && held.tables.every(([t, n]) => current(t) == n)) {
1340
+ k.answers.delete(key)
1341
+ k.answers.set(key, held)
1342
+ return copied(held.rows)
1343
+ }
1344
+ if (held) k.answers.delete(key)
1345
+ // Most of what a write asks is asked once: the dependents of the entity
1346
+ // it wrote, what points at one it deletes, the page after a cursor.
1347
+ // Keeping an answer costs a copy of it and a test for it, so an answer
1348
+ // is kept once its query is asked again.
1349
+ else if (!k.asked.delete(key)) {
1350
+ k.asked.add(key)
1351
+ if (k.asked.size > ASKED) {
1352
+ k.asked.delete(k.asked.values().next().value!)
1353
+ }
1354
+ return run()
1355
+ }
1356
+ let tables = dependencies()
1357
+ if (!tables) return run()
1358
+ let at = tables.map((t): [string, number] => [t, current(t)])
1359
+ let rows = run()
1360
+ if (at.some(([t, n]) => current(t) != n)) return rows
1361
+ let kept = packed(rows, ANSWER)
1362
+ if (!kept) return rows
1363
+ remember(key, {
1364
+ tables: at,
1365
+ rows: kept,
1366
+ prove: () => {
1367
+ let { query, membership, strict, shape } = prove?.() ?? {}
1368
+ let proof = typeof query == 'function' || !query
1369
+ ? undefined
1370
+ : rooted(vocab, query)
1371
+ return {
1372
+ test: typeof query == 'function' ? query : proof?.test,
1373
+ shape: shape ?? proof?.shape,
1374
+ membership: membership &&
1375
+ (typeof query == 'function' || !!query && local(vocab, query)),
1376
+ strict: [
1377
+ ...new Set([
1378
+ ...strict ?? [],
1379
+ ...proof?.strict ?? [],
1380
+ ]),
1381
+ ],
1382
+ }
1383
+ },
1384
+ })
1385
+ return rows
1386
+ },
1387
+ get: (get, eids, comps, refresh = true) => {
1388
+ sync()
1389
+ return getting(get, eids, comps, refresh)
1390
+ },
1391
+ view: viewed,
1392
+ writes,
1393
+ removes: (eids, at, body) => {
1394
+ sync()
1395
+ let was = new Map<string, Bundle | null | typeof LOST>(
1396
+ eids.map((eid) => [eid, prior(eid)]),
1397
+ )
1398
+ let before = new Map(c.versions)
1399
+ writes(body, () => eids)
1400
+ if (!c.depth || c.blind) return
1401
+ // What each holds once buried: its grave, and nothing else.
1402
+ let buried = (eid: string, b: Bundle | null): Bundle => ({
1403
+ entity: b ? { ...b.entity } : { eid },
1404
+ tombstone: { deleted_at: at },
1405
+ })
1406
+ let now = new Map<string, Bundle | null | typeof LOST>()
1407
+ for (let [eid, b] of was) {
1408
+ now.set(eid, b === LOST || b == null ? b : buried(eid, b))
1409
+ }
1410
+ for (let [eid, b] of now) {
1411
+ k.after.set(
1412
+ eid,
1413
+ b && b !== LOST ? { entity: b.entity, tombstone: {} } : b,
1414
+ )
1415
+ }
1416
+ stand(was, now, before)
1417
+ },
1418
+ patch: (bundles, body) => {
1419
+ sync()
1420
+ let eids = [...new Set(bundles.map((b) => b.entity.eid))]
1421
+ let partial = new Map(eids.flatMap((eid) => {
1422
+ let names = k.afterPart.get(eid) ??
1423
+ (!c.dirty.has(eid) ? k.part.get(eid) : undefined)
1424
+ let b = k.afterPart.has(eid) ? k.after.get(eid) : k.held.get(eid)
1425
+ return names && b && b !== LOST
1426
+ ? [[eid, { names: new Set(names), b }] as const]
1427
+ : []
1428
+ }))
1429
+ // What each held before, taken before the write lets it go.
1430
+ let now = new Map<string, Bundle | null | typeof LOST>(
1431
+ eids.map((eid) => [eid, prior(eid)]),
1432
+ )
1433
+ let known: Known = (eid, name) => {
1434
+ let b = now.get(eid)
1435
+ if (b === LOST || b === undefined || c.blind) return undefined
1436
+ let held = b?.[name] as Comp | undefined
1437
+ // A row whose values memory can't work out vouches for none of them.
1438
+ return held == null ? null : HOLE in held ? {} : held
1439
+ }
1440
+ let shifts = c.shifts, before = new Map(c.versions)
1441
+ let born = writes(
1442
+ () => body(known),
1443
+ (born) => [...eids, ...born.map((e) => e.eid)],
1444
+ )
1445
+ if (!c.depth || c.blind) return born
1446
+ // A number the patch took away, or one it gave an entity a reference
1447
+ // minted, is not in what it said.
1448
+ if (c.shifts != shifts) return born
1449
+ let minted = new Map(born.map((e) => [e.eid, e]))
1450
+ // An entity the patch minted or first numbered held nothing before it.
1451
+ for (let eid of minted.keys()) if (now.has(eid)) now.set(eid, null)
1452
+ let was = new Map(now)
1453
+ for (let b of bundles) {
1454
+ let eid = b.entity.eid, base = now.get(eid)!
1455
+ let part = partial.get(eid)
1456
+ if (part) {
1457
+ // Unknown aspects stay unknown. Only values whose entire aspect
1458
+ // was read can be folded through a patch without another lookup.
1459
+ let patch = Object.fromEntries(
1460
+ Object.entries(b).filter(([name]) =>
1461
+ name == 'entity' || part.names.has(name)
1462
+ ),
1463
+ ) as Bundle
1464
+ let next = fold(part.b, patch)
1465
+ now.set(eid, next)
1466
+ if (next && next !== LOST) {
1467
+ partial.set(eid, { names: part.names, b: next })
1468
+ }
1469
+ k.afterPart.set(eid, part.names)
1470
+ } else {
1471
+ now.set(eid, base === LOST ? LOST : fold(base, b, minted.get(eid)))
1472
+ }
1473
+ }
1474
+ for (let [eid, b] of now) k.after.set(eid, b)
1475
+ // A spine a reference minted holds what memory can't say.
1476
+ if (born.every((e) => now.has(e.eid))) stand(was, now, before)
1477
+ return born
1478
+ },
1479
+ }
1480
+ }