@agentshouse/mdruntime 0.1.0-c09bf842921ff → 0.1.0-c0aa19c04da09

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 (341) hide show
  1. package/README.md +21 -19
  2. package/dist/acceptance.d.ts +3 -0
  3. package/dist/acceptance.d.ts.map +1 -0
  4. package/dist/acceptance.js +299 -0
  5. package/dist/act-lanes.d.ts +30 -0
  6. package/dist/act-lanes.d.ts.map +1 -0
  7. package/dist/act-lanes.js +225 -0
  8. package/dist/actions.d.ts +26 -0
  9. package/dist/actions.d.ts.map +1 -0
  10. package/dist/actions.js +350 -0
  11. package/dist/adapter.d.ts +164 -83
  12. package/dist/adapter.d.ts.map +1 -1
  13. package/dist/attached-model.d.ts +0 -1
  14. package/dist/attached-model.d.ts.map +1 -1
  15. package/dist/attached-model.js +2 -7
  16. package/dist/authored.d.ts +88 -0
  17. package/dist/authored.d.ts.map +1 -0
  18. package/dist/authored.js +347 -0
  19. package/dist/binary.d.ts +6 -2
  20. package/dist/binary.d.ts.map +1 -1
  21. package/dist/binary.js +10 -3
  22. package/dist/bootstrap.d.ts +9 -5
  23. package/dist/bootstrap.d.ts.map +1 -1
  24. package/dist/bootstrap.js +204 -86
  25. package/dist/cell.d.ts +6 -0
  26. package/dist/cell.d.ts.map +1 -0
  27. package/dist/cell.js +9 -0
  28. package/dist/chain.d.ts +1 -1
  29. package/dist/chain.d.ts.map +1 -1
  30. package/dist/chain.js +5 -2
  31. package/dist/change-set.d.ts +4 -0
  32. package/dist/change-set.d.ts.map +1 -1
  33. package/dist/change-set.js +6 -0
  34. package/dist/change.d.ts +7 -2
  35. package/dist/change.d.ts.map +1 -1
  36. package/dist/change.js +7 -2
  37. package/dist/chat-types.d.ts +3 -0
  38. package/dist/chat-types.d.ts.map +1 -0
  39. package/dist/chat-types.js +11 -0
  40. package/dist/client.d.ts +35 -23
  41. package/dist/client.d.ts.map +1 -1
  42. package/dist/client.js +56 -68
  43. package/dist/collection.d.ts +27 -4
  44. package/dist/collection.d.ts.map +1 -1
  45. package/dist/collection.js +34 -10
  46. package/dist/column.d.ts +5 -0
  47. package/dist/column.d.ts.map +1 -0
  48. package/dist/column.js +9 -0
  49. package/dist/compile.d.ts +9 -1
  50. package/dist/compile.d.ts.map +1 -1
  51. package/dist/compile.js +283 -114
  52. package/dist/connection.d.ts +6 -144
  53. package/dist/connection.d.ts.map +1 -1
  54. package/dist/connection.js +115 -5019
  55. package/dist/context.d.ts.map +1 -1
  56. package/dist/context.js +1 -1
  57. package/dist/conversation-live.d.ts +149 -0
  58. package/dist/conversation-live.d.ts.map +1 -0
  59. package/dist/conversation-live.js +259 -0
  60. package/dist/conversation-row.d.ts +40 -0
  61. package/dist/conversation-row.d.ts.map +1 -0
  62. package/dist/conversation-row.js +66 -0
  63. package/dist/conversation.d.ts +71 -46
  64. package/dist/conversation.d.ts.map +1 -1
  65. package/dist/conversation.js +1001 -884
  66. package/dist/declaration.d.ts +10 -0
  67. package/dist/declaration.d.ts.map +1 -0
  68. package/dist/declaration.js +24 -0
  69. package/dist/discovery.d.ts +12 -0
  70. package/dist/discovery.d.ts.map +1 -0
  71. package/dist/discovery.js +175 -0
  72. package/dist/download.d.ts +6 -0
  73. package/dist/download.d.ts.map +1 -0
  74. package/dist/download.js +42 -0
  75. package/dist/durability.d.ts +14 -0
  76. package/dist/durability.d.ts.map +1 -1
  77. package/dist/durability.js +7 -0
  78. package/dist/entry.d.ts +16 -1
  79. package/dist/entry.d.ts.map +1 -1
  80. package/dist/entry.js +75 -29
  81. package/dist/expectation.d.ts +26 -13
  82. package/dist/expectation.d.ts.map +1 -1
  83. package/dist/expectation.js +72 -19
  84. package/dist/failure.d.ts +3 -0
  85. package/dist/failure.d.ts.map +1 -1
  86. package/dist/failure.js +8 -0
  87. package/dist/figures.d.ts +49 -0
  88. package/dist/figures.d.ts.map +1 -0
  89. package/dist/figures.js +199 -0
  90. package/dist/file.d.ts +1 -1
  91. package/dist/file.d.ts.map +1 -1
  92. package/dist/file.js +3 -2
  93. package/dist/holdings.d.ts +29 -0
  94. package/dist/holdings.d.ts.map +1 -0
  95. package/dist/holdings.js +95 -0
  96. package/dist/host.d.ts +25 -4
  97. package/dist/host.d.ts.map +1 -1
  98. package/dist/host.js +115 -36
  99. package/dist/house-query.d.ts +24 -0
  100. package/dist/house-query.d.ts.map +1 -0
  101. package/dist/house-query.js +82 -0
  102. package/dist/index.d.ts +38 -15
  103. package/dist/index.d.ts.map +1 -1
  104. package/dist/index.js +18 -6
  105. package/dist/install.d.ts +60 -0
  106. package/dist/install.d.ts.map +1 -0
  107. package/dist/install.js +537 -0
  108. package/dist/lifecycle.d.ts +7 -0
  109. package/dist/lifecycle.d.ts.map +1 -0
  110. package/dist/lifecycle.js +290 -0
  111. package/dist/listing.d.ts +60 -0
  112. package/dist/listing.d.ts.map +1 -0
  113. package/dist/listing.js +168 -0
  114. package/dist/live.d.ts +22 -6
  115. package/dist/live.d.ts.map +1 -1
  116. package/dist/live.js +130 -34
  117. package/dist/loaded.d.ts +7 -0
  118. package/dist/loaded.d.ts.map +1 -0
  119. package/dist/loaded.js +46 -0
  120. package/dist/locks.d.ts +7 -0
  121. package/dist/locks.d.ts.map +1 -0
  122. package/dist/locks.js +34 -0
  123. package/dist/lost.d.ts +5 -0
  124. package/dist/lost.d.ts.map +1 -0
  125. package/dist/lost.js +49 -0
  126. package/dist/media.d.ts +20 -4
  127. package/dist/media.d.ts.map +1 -1
  128. package/dist/media.js +170 -36
  129. package/dist/memory.d.ts +11 -4
  130. package/dist/memory.d.ts.map +1 -1
  131. package/dist/memory.js +110 -40
  132. package/dist/messages.d.ts +38 -3
  133. package/dist/messages.d.ts.map +1 -1
  134. package/dist/messages.js +105 -25
  135. package/dist/modal.d.ts +2 -0
  136. package/dist/modal.d.ts.map +1 -0
  137. package/dist/modal.js +11 -0
  138. package/dist/model.d.ts +4 -5
  139. package/dist/model.d.ts.map +1 -1
  140. package/dist/model.js +6 -11
  141. package/dist/models.d.ts +10 -0
  142. package/dist/models.d.ts.map +1 -0
  143. package/dist/models.js +153 -0
  144. package/dist/name.d.ts +0 -1
  145. package/dist/name.d.ts.map +1 -1
  146. package/dist/name.js +3 -7
  147. package/dist/observation.d.ts +29 -12
  148. package/dist/observation.d.ts.map +1 -1
  149. package/dist/observation.js +217 -85
  150. package/dist/online.d.ts +7 -0
  151. package/dist/online.d.ts.map +1 -0
  152. package/dist/online.js +29 -0
  153. package/dist/opened.d.ts +1 -1
  154. package/dist/opened.d.ts.map +1 -1
  155. package/dist/opened.js +5 -5
  156. package/dist/opening.d.ts +4 -0
  157. package/dist/opening.d.ts.map +1 -0
  158. package/dist/opening.js +69 -0
  159. package/dist/outcome.d.ts +28 -5
  160. package/dist/outcome.d.ts.map +1 -1
  161. package/dist/outcome.js +36 -3
  162. package/dist/overlay.d.ts +10 -5
  163. package/dist/overlay.d.ts.map +1 -1
  164. package/dist/overlay.js +48 -24
  165. package/dist/page-metadata.d.ts +8 -0
  166. package/dist/page-metadata.d.ts.map +1 -0
  167. package/dist/page-metadata.js +19 -0
  168. package/dist/parts.d.ts +6 -0
  169. package/dist/parts.d.ts.map +1 -0
  170. package/dist/parts.js +36 -0
  171. package/dist/paths.d.ts +1 -0
  172. package/dist/paths.d.ts.map +1 -1
  173. package/dist/paths.js +22 -0
  174. package/dist/preparation.d.ts +46 -0
  175. package/dist/preparation.d.ts.map +1 -0
  176. package/dist/preparation.js +344 -0
  177. package/dist/presence.d.ts +58 -0
  178. package/dist/presence.d.ts.map +1 -0
  179. package/dist/presence.js +231 -0
  180. package/dist/queries.d.ts +16 -0
  181. package/dist/queries.d.ts.map +1 -0
  182. package/dist/queries.js +330 -0
  183. package/dist/query.d.ts +12 -3
  184. package/dist/query.d.ts.map +1 -1
  185. package/dist/questions.d.ts +30 -0
  186. package/dist/questions.d.ts.map +1 -0
  187. package/dist/questions.js +117 -0
  188. package/dist/queue.d.ts +40 -0
  189. package/dist/queue.d.ts.map +1 -0
  190. package/dist/queue.js +480 -0
  191. package/dist/reach.d.ts +20 -9
  192. package/dist/reach.d.ts.map +1 -1
  193. package/dist/reach.js +327 -126
  194. package/dist/react.d.ts +18 -2
  195. package/dist/react.d.ts.map +1 -1
  196. package/dist/react.js +33 -1
  197. package/dist/read.d.ts +7 -0
  198. package/dist/read.d.ts.map +1 -0
  199. package/dist/read.js +17 -0
  200. package/dist/readiness.d.ts +20 -5
  201. package/dist/readiness.d.ts.map +1 -1
  202. package/dist/readiness.js +17 -10
  203. package/dist/reads.d.ts +39 -0
  204. package/dist/reads.d.ts.map +1 -0
  205. package/dist/reads.js +178 -0
  206. package/dist/recovery.d.ts +4 -1
  207. package/dist/recovery.d.ts.map +1 -1
  208. package/dist/recovery.js +40 -9
  209. package/dist/reference-forms.d.ts +4 -0
  210. package/dist/reference-forms.d.ts.map +1 -0
  211. package/dist/reference-forms.js +74 -0
  212. package/dist/refresh.d.ts +1 -1
  213. package/dist/refresh.d.ts.map +1 -1
  214. package/dist/refresh.js +10 -6
  215. package/dist/refusal.d.ts +5 -0
  216. package/dist/refusal.d.ts.map +1 -0
  217. package/dist/refusal.js +55 -0
  218. package/dist/replica.d.ts +5 -13
  219. package/dist/replica.d.ts.map +1 -1
  220. package/dist/replica.js +42 -26
  221. package/dist/retried.d.ts +30 -0
  222. package/dist/retried.d.ts.map +1 -0
  223. package/dist/retried.js +72 -0
  224. package/dist/room-draft.d.ts +31 -8
  225. package/dist/room-draft.d.ts.map +1 -1
  226. package/dist/room-draft.js +278 -68
  227. package/dist/room-drafts.d.ts +24 -0
  228. package/dist/room-drafts.d.ts.map +1 -0
  229. package/dist/room-drafts.js +222 -0
  230. package/dist/room-list.d.ts +10 -0
  231. package/dist/room-list.d.ts.map +1 -0
  232. package/dist/room-list.js +45 -0
  233. package/dist/rows.d.ts +11 -2
  234. package/dist/rows.d.ts.map +1 -1
  235. package/dist/rows.js +27 -14
  236. package/dist/running.d.ts +5 -0
  237. package/dist/running.d.ts.map +1 -0
  238. package/dist/running.js +10 -0
  239. package/dist/runtime.d.ts +37 -0
  240. package/dist/runtime.d.ts.map +1 -0
  241. package/dist/runtime.js +1 -0
  242. package/dist/save.d.ts +43 -86
  243. package/dist/save.d.ts.map +1 -1
  244. package/dist/save.js +332 -228
  245. package/dist/saves.d.ts +34 -0
  246. package/dist/saves.d.ts.map +1 -0
  247. package/dist/saves.js +463 -0
  248. package/dist/seed.d.ts +11 -2
  249. package/dist/seed.d.ts.map +1 -1
  250. package/dist/seed.js +71 -1
  251. package/dist/shared.d.ts +1 -6
  252. package/dist/shared.d.ts.map +1 -1
  253. package/dist/shared.js +13 -95
  254. package/dist/shown.d.ts +35 -0
  255. package/dist/shown.d.ts.map +1 -0
  256. package/dist/shown.js +326 -0
  257. package/dist/socket/admission.d.ts +7 -0
  258. package/dist/socket/admission.d.ts.map +1 -0
  259. package/dist/socket/admission.js +39 -0
  260. package/dist/socket/answers.d.ts +6 -0
  261. package/dist/socket/answers.d.ts.map +1 -0
  262. package/dist/socket/answers.js +20 -0
  263. package/dist/socket/lanes.d.ts +28 -0
  264. package/dist/socket/lanes.d.ts.map +1 -0
  265. package/dist/socket/lanes.js +103 -0
  266. package/dist/socket/reads.d.ts +10 -0
  267. package/dist/socket/reads.d.ts.map +1 -0
  268. package/dist/socket/reads.js +31 -0
  269. package/dist/socket/session.d.ts +41 -0
  270. package/dist/socket/session.d.ts.map +1 -0
  271. package/dist/socket/session.js +26 -0
  272. package/dist/socket.d.ts +68 -0
  273. package/dist/socket.d.ts.map +1 -0
  274. package/dist/socket.js +165 -0
  275. package/dist/source.d.ts +61 -0
  276. package/dist/source.d.ts.map +1 -0
  277. package/dist/source.js +95 -0
  278. package/dist/status.d.ts +0 -2
  279. package/dist/status.d.ts.map +1 -1
  280. package/dist/status.js +0 -6
  281. package/dist/store/installs.d.ts +30 -0
  282. package/dist/store/installs.d.ts.map +1 -0
  283. package/dist/store/installs.js +40 -0
  284. package/dist/store/readiness.d.ts +11 -0
  285. package/dist/store/readiness.d.ts.map +1 -0
  286. package/dist/store/readiness.js +68 -0
  287. package/dist/store/records.d.ts +229 -0
  288. package/dist/store/records.d.ts.map +1 -0
  289. package/dist/store/records.js +474 -0
  290. package/dist/store/room-held.d.ts +8 -0
  291. package/dist/store/room-held.d.ts.map +1 -0
  292. package/dist/store/room-held.js +17 -0
  293. package/dist/store/rooms-shown.d.ts +8 -0
  294. package/dist/store/rooms-shown.d.ts.map +1 -0
  295. package/dist/store/rooms-shown.js +13 -0
  296. package/dist/store/space.d.ts +11 -0
  297. package/dist/store/space.d.ts.map +1 -0
  298. package/dist/store/space.js +41 -0
  299. package/dist/store/watchers.d.ts +17 -0
  300. package/dist/store/watchers.d.ts.map +1 -0
  301. package/dist/store/watchers.js +56 -0
  302. package/dist/store/writes.d.ts +24 -0
  303. package/dist/store/writes.d.ts.map +1 -0
  304. package/dist/store/writes.js +125 -0
  305. package/dist/store.d.ts +116 -141
  306. package/dist/store.d.ts.map +1 -1
  307. package/dist/store.js +174 -360
  308. package/dist/stored.d.ts +84 -32
  309. package/dist/stored.d.ts.map +1 -1
  310. package/dist/stored.js +398 -115
  311. package/dist/surface.d.ts +94 -0
  312. package/dist/surface.d.ts.map +1 -0
  313. package/dist/surface.js +255 -0
  314. package/dist/sync.d.ts +21 -0
  315. package/dist/sync.d.ts.map +1 -0
  316. package/dist/sync.js +557 -0
  317. package/dist/tables.d.ts +120 -59
  318. package/dist/tables.d.ts.map +1 -1
  319. package/dist/tables.js +196 -277
  320. package/dist/tallies.d.ts +18 -0
  321. package/dist/tallies.d.ts.map +1 -0
  322. package/dist/tallies.js +128 -0
  323. package/dist/validation.d.ts +2 -0
  324. package/dist/validation.d.ts.map +1 -1
  325. package/dist/validation.js +51 -11
  326. package/dist/wire.d.ts +79 -13
  327. package/dist/wire.d.ts.map +1 -1
  328. package/dist/wire.js +34 -14
  329. package/package.json +4 -3
  330. package/dist/attempt.d.ts +0 -16
  331. package/dist/attempt.d.ts.map +0 -1
  332. package/dist/attempt.js +0 -70
  333. package/dist/fence.d.ts +0 -6
  334. package/dist/fence.d.ts.map +0 -1
  335. package/dist/fence.js +0 -10
  336. package/dist/job.d.ts +0 -14
  337. package/dist/job.d.ts.map +0 -1
  338. package/dist/job.js +0 -28
  339. package/dist/log.d.ts +0 -5
  340. package/dist/log.d.ts.map +0 -1
  341. package/dist/log.js +0 -14
package/dist/compile.js CHANGED
@@ -1,19 +1,24 @@
1
1
  import { ARRAY_INDEX, bodied, byCodePoint, compared, cursorOf, heldKind, parse, pointerSegments, sql, } from '@agentshouse/mdmodel';
2
2
  import { binaryRecord } from './binary.js';
3
+ import { definitionsAt, UNTYPED } from './collection.js';
3
4
  import { documentKey, pathOfKey, roomOfKey } from './rows.js';
5
+ import { ROOM_HANDLE } from './stored.js';
4
6
  import { FROM_START, MAXIMUM_WINDOW } from './windows.js';
5
7
  const { all, any, exists, fragment, grouped, joined, listed } = sql;
6
- const VISIBLE = (alias) => `${alias}.visible = 1 AND ${alias}.present = 1 AND ${alias}.queried = 1`;
8
+ export const VISIBLE = (alias) => `${alias}.visible = 1 AND ${alias}.present = 1`;
7
9
  function located(alias) {
8
10
  return fragment(`(SELECT k.locator FROM replica_keys k WHERE k.key = ${alias}.key)`);
9
11
  }
10
- function within(alias, path) {
11
- return fragment(`(${alias}.path = ? OR (${alias}.path >= ? AND ${alias}.path < ?))`, [
12
- path,
13
- `${path}/`,
14
- `${path}0`,
12
+ function inside(path, directory) {
13
+ return fragment(`(${path} = ? OR (${path} >= ? AND ${path} < ?))`, [
14
+ directory,
15
+ `${directory}/`,
16
+ `${directory}0`,
15
17
  ]);
16
18
  }
19
+ export function within(alias, path) {
20
+ return inside(`${alias}.path`, path);
21
+ }
17
22
  function ancestors(area) {
18
23
  const depth = area.path.split('/').length;
19
24
  return area.open.flatMap((open) => {
@@ -21,18 +26,18 @@ function ancestors(area) {
21
26
  return segments.slice(depth - 1, -1).map((_, at) => segments.slice(0, depth + at).join('/'));
22
27
  });
23
28
  }
24
- function fenced(alias, key, area, folders) {
29
+ function fenced(key, path, held, area, folders) {
25
30
  const opened = any([
26
- ...area.open.map((open) => within(alias, open)),
27
- ...(folders ? ancestors(area).map((path) => fragment(`${alias}.path = ?`, [path])) : []),
31
+ ...area.open.map((open) => inside(path, open)),
32
+ ...(folders ? ancestors(area).map((ancestor) => fragment(`${path} = ?`, [ancestor])) : []),
28
33
  ]);
29
34
  return all([
30
- fragment(`${alias}.key = ?`, [key]),
31
- within(alias, area.path),
35
+ fragment(`${key} = ?`, [held]),
36
+ inside(path, area.path),
32
37
  fragment(`NOT ${grouped(opened).sql}`, opened.bind),
33
38
  ]);
34
39
  }
35
- function reached(bound, alias) {
40
+ function reached(bound, key, path) {
36
41
  const reach = bound.reach;
37
42
  if (reach === null)
38
43
  return fragment('1');
@@ -45,49 +50,65 @@ function reached(bound, alias) {
45
50
  return key === undefined ? [] : [[key, pathOfKey(held)]];
46
51
  });
47
52
  const outside = any(reach.areas.flatMap((area) => {
48
- const key = bound.keys.get(area.room);
49
- return key === undefined ? [] : [fenced(alias, key, area, false)];
53
+ const held = bound.keys.get(area.room);
54
+ return held === undefined ? [] : [fenced(key, path, held, area, false)];
50
55
  }));
51
56
  return all([
52
57
  any([
53
- ...(rooms.length === 0 ? [] : [fragment(`${alias}.key IN ${listed(rooms).sql}`, rooms)]),
58
+ ...(rooms.length === 0 ? [] : [fragment(`${key} IN ${listed(rooms).sql}`, rooms)]),
54
59
  ...(documents.length === 0
55
60
  ? []
56
61
  : [
57
- fragment(`EXISTS (SELECT 1 FROM json_each(?) j WHERE j.value ->> 0 = ${alias}.key AND j.value ->> 1 = ${alias}.path)`, [JSON.stringify(documents)]),
62
+ fragment(`EXISTS (SELECT 1 FROM json_each(?) j WHERE j.value ->> 0 = ${key} AND j.value ->> 1 = ${path})`, [JSON.stringify(documents)]),
58
63
  ]),
59
64
  ]),
60
65
  ...(reach.areas.length === 0 ? [] : [fragment(`NOT ${grouped(outside).sql}`, outside.bind)]),
61
66
  ]);
62
67
  }
68
+ function handled(bound, link) {
69
+ return fragment(`FROM replica_rooms h WHERE ${ROOM_HANDLE('h')} = ${link}.handle AND h.key IN (SELECT value FROM json_each(?))`, [bound.follows]);
70
+ }
71
+ function followed(bound) {
72
+ return {
73
+ targets: (link, document) => {
74
+ const room = handled(bound, link);
75
+ return joined([
76
+ fragment(`replica_entries ${document} ON ${document}.key = CASE WHEN ${link}.handle IS NULL THEN d.key ELSE (SELECT h.key ${room.sql}) END AND ${document}.path = ${link}.target AND ${VISIBLE(document)} AND`, room.bind),
77
+ grouped(reached(bound, `${document}.key`, `${document}.path`)),
78
+ ], ' ');
79
+ },
80
+ unfollowed: (link) => {
81
+ const own = reached(bound, 'd.key', `${link}.target`);
82
+ const room = handled(bound, link);
83
+ const other = reached(bound, 'h.key', `${link}.target`);
84
+ return fragment(`NOT ((${link}.handle IS NULL AND ${own.sql}) OR EXISTS (SELECT 1 ${room.sql} AND ${other.sql}))`, [...own.bind, ...room.bind, ...other.bind]);
85
+ },
86
+ };
87
+ }
63
88
  function related(bound, plan) {
64
89
  const parts = [];
65
- if (plan.hop !== null) {
66
- parts.push(exists(joined([
67
- fragment(`SELECT 1 FROM replica_links l JOIN replica_entries m ON m.key = d.key AND m.path = l.target AND ${VISIBLE('m')} WHERE l.doc = d.id AND l.kind = 'field' AND`),
68
- grouped(sql.placed('l', plan.hop.field, 'link')),
69
- fragment('AND'),
70
- grouped(all([sql.scoped('m', plan.hop), reached(bound, 'm')])),
71
- ], ' ')));
72
- }
90
+ if (plan.hop !== null)
91
+ parts.push(sql.hopped('d', plan.hop, followed(bound)));
73
92
  if (plan.backlinks !== null) {
74
93
  const field = plan.backlinks.field;
75
94
  parts.push(exists(joined([
76
- fragment(`SELECT 1 FROM replica_links l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE l.key = d.key AND l.target = d.path AND l.kind = 'field' AND`),
95
+ fragment(`SELECT 1 FROM replica_links l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE l.key = d.key AND l.handle IS NULL AND l.target = d.path AND l.kind = 'field' AND`),
77
96
  ...(field === null ? [] : [grouped(sql.placed('l', field, 'link')), fragment('AND')]),
78
- grouped(all([sql.scoped('s', plan.backlinks), reached(bound, 's')])),
97
+ grouped(all([sql.scoped('s', plan.backlinks), reached(bound, 's.key', 's.path')])),
79
98
  ], ' ')));
80
99
  }
81
100
  return parts;
82
101
  }
83
- function filtered(bound, plan) {
102
+ function tested(bound, plan) {
84
103
  const keys = bound.rooms.map(({ key }) => key);
85
- return all([
104
+ return [
86
105
  fragment(`d.key IN ${listed(keys).sql} AND ${VISIBLE('d')}`, keys),
87
- reached(bound, 'd'),
106
+ reached(bound, 'd.key', 'd.path'),
88
107
  sql.tests('d', plan),
89
- ...related(bound, plan),
90
- ]);
108
+ ];
109
+ }
110
+ function filtered(bound, plan) {
111
+ return all([...tested(bound, plan), ...related(bound, plan)]);
91
112
  }
92
113
  function orderingOf(options) {
93
114
  const stringSort = options.stringSort ?? 'locale';
@@ -116,7 +137,18 @@ const GROUP_TIES = {
116
137
  locale: undefined,
117
138
  localeOptions: undefined,
118
139
  };
119
- function keyTerm(key, ordering, index) {
140
+ const GREATEST = { ...GROUP_ORDER, direction: 'desc', nulls: 'last' };
141
+ const TIMES = {
142
+ created: { value: 'd.created', instant: 'd.created_instant' },
143
+ updated: { value: "(d.change ->> '$.time')", instant: 'd.changed_instant' },
144
+ };
145
+ function subfolderOf(column, prefix) {
146
+ const root = prefix ?? '';
147
+ const base = root === '' ? '' : `${root}/`;
148
+ const rest = `substr(${column}, length(?) + 1)`;
149
+ return fragment(`(CASE WHEN ${column} = ? THEN NULL WHEN instr(${rest}, '/') = 0 THEN ${column} ELSE ? || substr(${rest}, 1, instr(${rest}, '/') - 1) END)`, [root, base, base, base, base]);
150
+ }
151
+ function keyTerm(key, ordering, index, prefix) {
120
152
  if (key.of === 'field') {
121
153
  const alias = `o${index}`;
122
154
  return {
@@ -133,13 +165,37 @@ function keyTerm(key, ordering, index) {
133
165
  ], ''),
134
166
  };
135
167
  }
168
+ if (key.of === 'size') {
169
+ return {
170
+ term: {
171
+ ordering,
172
+ kind: fragment("(CASE WHEN d.bytes IS NULL THEN 'null' ELSE 'number' END)"),
173
+ value: fragment('d.bytes'),
174
+ },
175
+ join: null,
176
+ };
177
+ }
178
+ if (key.of === 'created' || key.of === 'updated') {
179
+ const { value, instant } = TIMES[key.of];
180
+ return {
181
+ term: {
182
+ ordering,
183
+ kind: fragment(`(CASE WHEN ${value} IS NULL THEN 'null' ELSE 'string' END)`),
184
+ value: fragment(value),
185
+ instant: fragment(instant),
186
+ },
187
+ join: null,
188
+ };
189
+ }
136
190
  const expression = key.of === 'room'
137
191
  ? located('d')
138
192
  : key.of === 'path'
139
193
  ? fragment('d.path')
140
194
  : key.of === 'type'
141
195
  ? fragment('d.type')
142
- : fragment('d.folder');
196
+ : key.of === 'subfolder'
197
+ ? subfolderOf('d.folder', prefix)
198
+ : fragment('d.folder');
143
199
  return {
144
200
  term: {
145
201
  ordering,
@@ -160,16 +216,17 @@ function decoded(kind, value) {
160
216
  return JSON.parse(value);
161
217
  return null;
162
218
  }
219
+ function sortedOf(kind, value, instant) {
220
+ return sql.sortValue(kind, decoded(kind, value), instant);
221
+ }
163
222
  function sortedValue(row, index) {
164
- const kind = row[`k${index}`];
165
- return sql.sortValue(kind, decoded(kind, row[`v${index}`]), row[`i${index}`]);
223
+ return sortedOf(row[`k${index}`], row[`v${index}`], row[`i${index}`]);
166
224
  }
167
225
  function decodedKey(key, row, index) {
168
- if (key.of === 'field') {
169
- const kind = row[`k${index}`];
170
- return kind === null || kind === undefined ? undefined : sortedValue(row, index);
171
- }
172
- return row[`v${index}`] ?? null;
226
+ const kind = row[`k${index}`];
227
+ if (key.of === 'field' && (kind === null || kind === undefined))
228
+ return undefined;
229
+ return sortedValue(row, index);
173
230
  }
174
231
  function instantOf(term) {
175
232
  return term.instant ?? fragment('NULL');
@@ -274,11 +331,20 @@ function sectionsOf(sections, names) {
274
331
  return sections;
275
332
  return Object.fromEntries(names.flatMap((name) => (Object.hasOwn(sections, name) ? [[name, sections[name]]] : [])));
276
333
  }
277
- function documentOf(shape, room, row, linked) {
334
+ function freeParts(room, path, type, content) {
335
+ const definitions = room.composition === undefined ? undefined : definitionsAt(room.composition, path);
336
+ const definition = definitions?.(type === UNTYPED ? undefined : type);
337
+ if (definition === undefined && type !== UNTYPED)
338
+ return null;
339
+ const read = parse(content, path, definition);
340
+ return read.ok ? read.document : null;
341
+ }
342
+ function documentOf(shape, queried, row, linked) {
343
+ const room = queried.locator;
278
344
  const path = row.path;
279
345
  const type = row.type;
280
- const fileId = row.file_id ?? null;
281
- const revision = row.revision ?? null;
346
+ const fileId = row.file_id;
347
+ const revision = row.revision;
282
348
  if (type === null) {
283
349
  const binary = row.binary === null ? null : JSON.parse(row.binary);
284
350
  const content = row.content ?? null;
@@ -288,15 +354,18 @@ function documentOf(shape, room, row, linked) {
288
354
  ...(binary === null
289
355
  ? {}
290
356
  : {
291
- binaryFile: binaryRecord(path, binary, revision ?? undefined),
357
+ attachment: binaryRecord(path, binary, revision ?? undefined),
292
358
  }),
293
359
  ...(shape.markdown && content !== null ? { markdown: content } : {}),
360
+ ...(shape.change ? { change: changeOf(row) } : {}),
294
361
  ...(shape.fileId ? { fileId } : {}),
295
362
  ...(shape.revision ? { revision } : {}),
363
+ ...heldFacts(shape, row),
296
364
  };
297
365
  }
298
- const read = bodied(shape) ? parse(row.content, path) : null;
299
- const body = read?.ok === true ? read.document : null;
366
+ const body = shape.sections !== null || shape.preamble
367
+ ? freeParts(queried, path, type, row.content)
368
+ : null;
300
369
  const fields = JSON.parse(row.fields ?? '{}');
301
370
  return {
302
371
  room,
@@ -315,13 +384,19 @@ function documentOf(shape, room, row, linked) {
315
384
  ...(shape.preamble && body !== null ? { preamble: body.preamble } : {}),
316
385
  ...(shape.markdown ? { markdown: row.content } : {}),
317
386
  ...(shape.backlinks ? { backlinks: linked.get(documentKey(room, path)) ?? [] } : {}),
318
- ...(shape.change
319
- ? {
320
- change: row.change === null ? null : JSON.parse(row.change),
321
- }
322
- : {}),
387
+ ...(shape.change ? { change: changeOf(row) } : {}),
323
388
  ...(shape.fileId ? { fileId } : {}),
324
389
  ...(shape.revision ? { revision } : {}),
390
+ ...heldFacts(shape, row),
391
+ };
392
+ }
393
+ function changeOf(row) {
394
+ return row.change === null ? null : JSON.parse(row.change);
395
+ }
396
+ function heldFacts(shape, row) {
397
+ return {
398
+ ...(shape.size ? { size: row.bytes === null ? null : Number(row.bytes) } : {}),
399
+ ...(shape.created ? { created: row.created } : {}),
325
400
  };
326
401
  }
327
402
  function backlinksOf(connection, bound, rows) {
@@ -333,10 +408,10 @@ function backlinksOf(connection, bound, rows) {
333
408
  held.push(row.path);
334
409
  byKey.set(key, held);
335
410
  }
411
+ const reach = reached(bound, 's.key', 's.path');
336
412
  for (const [key, targets] of byKey) {
337
- const reach = reached(bound, 's');
338
413
  const room = bound.rooms.find((one) => one.key === key).locator;
339
- const found = connection.rows(`SELECT target, path, type, field FROM (SELECT l.target, s.path, s.type, l.field, ROW_NUMBER() OVER (PARTITION BY l.target ORDER BY s.path, l.field) AS rank FROM (SELECT DISTINCT doc, target, field FROM replica_links WHERE key = ? AND kind = 'field' AND target IN (SELECT value FROM json_each(?))) l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE ${reach.sql}) WHERE rank <= ? ORDER BY target, path, field`, [key, JSON.stringify(targets), ...reach.bind, MAXIMUM_WINDOW]);
414
+ const found = connection.rows(`SELECT target, path, type, field FROM (SELECT l.target, s.path, s.type, l.field, ROW_NUMBER() OVER (PARTITION BY l.target ORDER BY s.path, l.field) AS rank FROM (SELECT DISTINCT doc, target, field FROM replica_links WHERE key = ? AND kind = 'field' AND handle IS NULL AND target IN (SELECT value FROM json_each(?))) l JOIN replica_entries s ON s.id = l.doc AND ${VISIBLE('s')} WHERE ${reach.sql}) WHERE rank <= ? ORDER BY target, path, field`, [key, JSON.stringify(targets), ...reach.bind, MAXIMUM_WINDOW]);
340
415
  for (const row of found) {
341
416
  const at = documentKey(room, row.target);
342
417
  const held = linked.get(at) ?? [];
@@ -347,28 +422,25 @@ function backlinksOf(connection, bound, rows) {
347
422
  return linked;
348
423
  }
349
424
  function documents(connection, bound, plan, shape, budget) {
350
- const terms = shape.orderBy.map(({ key, options }, index) => keyTerm(key, orderingOf(options), index));
425
+ const terms = shape.orderBy.map(({ key, options }, index) => keyTerm(key, orderingOf(options), index, plan.root.pathPrefix));
351
426
  const filter = filtered(bound, plan);
352
427
  const cursor = plan.after?.values ?? null;
353
428
  const room = located('d');
354
- const tie = cursor === null
429
+ const after = cursor === null
355
430
  ? null
356
431
  : (() => {
357
432
  const key = cursor[shape.orderBy.length];
358
- return any([
433
+ return sql.following(terms.map(({ term }, index) => sql.beyond(bound.collate, term, cursor[index])), any([
359
434
  fragment(`${room.sql} > ?`, [...room.bind, roomOfKey(key)]),
360
435
  fragment(`${room.sql} = ? AND d.path > ?`, [
361
436
  ...room.bind,
362
437
  roomOfKey(key),
363
438
  pathOfKey(key),
364
439
  ]),
365
- ]);
440
+ ]));
366
441
  })();
367
- const after = cursor === null || tie === null
368
- ? null
369
- : sql.following(terms.map(({ term }, index) => sql.beyond(bound.collate, term, cursor[index])), tie);
370
442
  const selected = joined([
371
- fragment('SELECT d.id, d.key, d.path, d.type, d.binary, d.revision, d.fields, d.change, d.file_id'),
443
+ fragment('SELECT d.id, d.key, d.path, d.type, d.binary, d.revision, d.fields, d.change, d.file_id, d.bytes, d.created'),
372
444
  ...terms.map(({ term }, index) => joined([
373
445
  fragment(`, ${term.kind.sql} AS k${index}`, term.kind.bind),
374
446
  fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
@@ -387,8 +459,9 @@ function documents(connection, bound, plan, shape, budget) {
387
459
  const kept = bodied(shape) ? withContent(connection, windowed, budget) : windowed;
388
460
  const cut = kept.length;
389
461
  const roomOf = new Map(bound.rooms.map(({ key, locator }) => [key, locator]));
462
+ const queried = new Map(bound.rooms.map((one) => [one.key, one]));
390
463
  const linked = shape.backlinks ? backlinksOf(connection, bound, kept) : new Map();
391
- const found = kept.map((row) => documentOf(shape, roomOf.get(Number(row.key)), row, linked));
464
+ const found = kept.map((row) => documentOf(shape, queried.get(Number(row.key)), row, linked));
392
465
  const last = kept.at(-1);
393
466
  const cursorAt = (row) => cursorOf([
394
467
  ...shape.orderBy.map(({ key }, index) => decodedKey(key, row, index)),
@@ -437,44 +510,70 @@ function withContent(connection, rows, budget) {
437
510
  .map((row) => [row.id, row.content]));
438
511
  return kept.map((row) => ({ ...row, content: held.get(row.id) ?? null }));
439
512
  }
440
- function storedFolders(bound, plan) {
513
+ function storedFolders(bound, plan, subfolder) {
441
514
  if (plan.paths !== null || plan.fileIds !== null)
442
515
  return null;
443
516
  if (plan.hop !== null || plan.backlinks !== null)
444
517
  return null;
518
+ if (subfolder && plan.folder !== null)
519
+ return null;
445
520
  const whole = bound.rooms.filter(({ locator }) => bound.reach === null || bound.reach.rooms.includes(locator));
446
521
  if (whole.length === 0)
447
522
  return null;
448
523
  const keys = whole.map(({ key }) => key);
449
- const prefix = plan.root.pathPrefix;
524
+ const prefix = plan.root.pathPrefix ?? '';
450
525
  const outside = (bound.reach?.areas ?? []).flatMap((area) => {
451
526
  const key = bound.keys.get(area.room);
452
527
  if (key === undefined)
453
528
  return [];
454
- const fence = fenced('f', key, area, true);
529
+ const fence = fenced('f.key', 'f.path', key, area, true);
455
530
  return [fragment(`NOT ${grouped(fence).sql}`, fence.bind)];
456
531
  });
532
+ const under = prefix === ''
533
+ ? subfolder
534
+ ? [fragment("f.path <> ''")]
535
+ : []
536
+ : [
537
+ subfolder
538
+ ? fragment('(f.path >= ? AND f.path < ?)', [`${prefix}/`, `${prefix}0`])
539
+ : within('f', prefix),
540
+ ];
457
541
  return all([
458
542
  fragment(`f.key IN ${listed(keys).sql} AND f.layer = 0 AND f.present = 1`, keys),
459
543
  ...outside,
460
- ...(prefix === null || prefix === ''
461
- ? []
462
- : [
463
- fragment('(f.path = ? OR (f.path >= ? AND f.path < ?))', [
464
- prefix,
465
- `${prefix}/`,
466
- `${prefix}0`,
467
- ]),
468
- ]),
544
+ ...under,
545
+ ...(plan.outside ?? []).map((folder) => fragment(`NOT ${within('f', folder).sql}`, within('f', folder).bind)),
469
546
  ...(plan.folder === null ? [] : [fragment('f.path = ?', [plan.folder])]),
470
547
  ]);
471
548
  }
549
+ const SIZES = [
550
+ 'CASE WHEN d.binary IS NULL THEN 1 ELSE 0 END AS dn',
551
+ 'CASE WHEN d.binary IS NULL THEN d.bytes ELSE 0 END AS ds',
552
+ 'CASE WHEN d.binary IS NULL THEN 0 ELSE 1 END AS fn',
553
+ 'CASE WHEN d.binary IS NULL THEN 0 ELSE d.bytes END AS fs',
554
+ ];
555
+ const LATEST = "d.changed_instant || ' ' || (d.change ->> '$.time') AS u";
556
+ function greatestTerm(ordering) {
557
+ return { ordering, kind: fragment('gk'), value: fragment('gv'), instant: fragment('gi') };
558
+ }
559
+ function latestOf(held) {
560
+ if (typeof held !== 'string')
561
+ return null;
562
+ return held.slice(held.indexOf(' ') + 1);
563
+ }
472
564
  function groups(connection, bound, plan, shape) {
565
+ const prefix = plan.root.pathPrefix;
473
566
  const keyed = shape.groupBy.map((key, index) => {
474
- const { term, join } = keyTerm(key, GROUP_ORDER, index);
567
+ const { term, join } = keyTerm(key, GROUP_ORDER, index, prefix);
475
568
  const kind = fragment(`COALESCE(${term.kind.sql}, 'null')`, term.kind.bind);
476
569
  return { term: { ...term, kind }, join };
477
570
  });
571
+ const ordering = shape.orderBy.map(({ by }) => by);
572
+ const sized = shape.size || ordering.includes('size');
573
+ const dated = shape.updated || ordering.includes('updated');
574
+ const greatest = shape.greatest === null
575
+ ? null
576
+ : keyTerm({ of: 'field', field: shape.greatest }, GREATEST, keyed.length, prefix);
478
577
  const filter = filtered(bound, plan);
479
578
  const inner = joined([
480
579
  fragment('SELECT '),
@@ -483,57 +582,107 @@ function groups(connection, bound, plan, shape) {
483
582
  fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
484
583
  fragment(`, ${instantOf(term).sql} AS i${index}`, instantOf(term).bind),
485
584
  ], '')), ', '),
486
- fragment(', 1 AS n FROM replica_entries d'),
487
- ...keyed.flatMap(({ join }) => (join === null ? [] : [fragment(' '), join])),
585
+ fragment(['', '1 AS n', ...(sized ? SIZES : []), ...(dated ? [LATEST] : [])].join(', ')),
586
+ ...(greatest === null
587
+ ? []
588
+ : [
589
+ fragment(`, ${greatest.term.kind.sql} AS gk`, greatest.term.kind.bind),
590
+ fragment(`, ${greatest.term.value.sql} AS gv`, greatest.term.value.bind),
591
+ fragment(`, ${instantOf(greatest.term).sql} AS gi`, instantOf(greatest.term).bind),
592
+ ]),
593
+ fragment(' FROM replica_entries d'),
594
+ ...[...keyed, ...(greatest === null ? [] : [greatest])].flatMap(({ join }) => join === null ? [] : [fragment(' '), join]),
488
595
  fragment(' WHERE '),
489
596
  filter,
490
597
  ], '');
491
- const folders = shape.groupBy.length === 1 && shape.groupBy[0].of === 'folder'
492
- ? storedFolders(bound, plan)
493
- : null;
598
+ const only = shape.groupBy.length === 1 ? shape.groupBy[0].of : null;
599
+ const subfolder = only === 'subfolder';
600
+ const folders = only === 'folder' || subfolder ? storedFolders(bound, plan, subfolder) : null;
601
+ const folderKey = subfolder ? subfolderOf('f.path', prefix) : fragment('f.path');
602
+ const zeros = [
603
+ ...(sized ? ['0', '0', '0', '0'] : []),
604
+ ...(dated ? ['NULL'] : []),
605
+ ...(greatest === null ? [] : ['NULL', 'NULL', 'NULL']),
606
+ ];
494
607
  const source = folders === null
495
608
  ? inner
496
609
  : joined([
497
610
  inner,
498
- fragment(" UNION ALL SELECT 'string' AS k0, f.path AS v0, NULL AS i0, 0 AS n FROM replica_folders f WHERE "),
611
+ fragment(` UNION ALL SELECT 'string' AS k0, ${folderKey.sql} AS v0, NULL AS i0, 0 AS n${zeros.map((one) => `, ${one}`).join('')} FROM replica_folders f WHERE `, folderKey.bind),
499
612
  folders,
500
613
  ], '');
501
- const columns = keyed
502
- .map((_, index) => `k${index}, min(v${index}) AS v${index}, i${index}`)
503
- .join(', ');
504
614
  const held = keyed
505
615
  .map((_, index) => `k${index}, i${index}, CASE WHEN i${index} IS NULL THEN v${index} END`)
506
616
  .join(', ');
507
- const counted = {
508
- ordering: { ...GROUP_ORDER },
509
- kind: fragment("'number'"),
510
- value: fragment('n'),
511
- };
512
- const outer = (index, ordering) => ({
513
- ordering,
617
+ const ranked = greatest === null
618
+ ? source
619
+ : joined([
620
+ fragment(`SELECT *, ROW_NUMBER() OVER (PARTITION BY ${held} ORDER BY `),
621
+ sql.sorted(bound.collate, greatestTerm(GREATEST)),
622
+ fragment(', gv) AS gr FROM ('),
623
+ source,
624
+ fragment(')'),
625
+ ], '');
626
+ const columns = [
627
+ ...keyed.map((_, index) => `k${index}, min(v${index}) AS v${index}, i${index}`),
628
+ 'sum(n) AS n',
629
+ ...(sized ? ['sum(dn) AS dn', 'sum(ds) AS ds', 'sum(fn) AS fn', 'sum(fs) AS fs'] : []),
630
+ ...(dated ? ['max(u) AS u'] : []),
631
+ ...(greatest === null
632
+ ? []
633
+ : ['gk', 'gv', 'gi'].map((column) => `min(CASE WHEN gr = 1 THEN ${column} END) AS ${column}`)),
634
+ ].join(', ');
635
+ const outer = (index, order) => ({
636
+ ordering: order,
514
637
  kind: fragment(`k${index}`),
515
638
  value: fragment(`v${index}`),
516
639
  });
517
- const ordered = shape.orderBy.map(({ by, direction }) => by === 'count'
518
- ? { ...counted, ordering: { ...GROUP_ORDER, direction } }
519
- : { ...outer(by, { ...GROUP_ORDER, direction }), instant: fragment(`i${by}`) });
640
+ const termOf = (by, order) => {
641
+ if (by === 'count')
642
+ return { ordering: order, kind: fragment("'number'"), value: fragment('n') };
643
+ if (by === 'size') {
644
+ return { ordering: order, kind: fragment("'number'"), value: fragment('(ds + fs)') };
645
+ }
646
+ if (by === 'updated') {
647
+ return {
648
+ ordering: order,
649
+ kind: fragment("(CASE WHEN u IS NULL THEN 'null' ELSE 'string' END)"),
650
+ value: fragment("substr(u, instr(u, ' ') + 1)"),
651
+ instant: fragment("substr(u, 1, instr(u, ' ') - 1)"),
652
+ };
653
+ }
654
+ if (by === 'greatest')
655
+ return greatestTerm(order);
656
+ return { ...outer(by, order), instant: fragment(`i${by}`) };
657
+ };
658
+ const valueOf = (row, by) => {
659
+ if (by === 'count')
660
+ return Number(row.n);
661
+ if (by === 'size')
662
+ return Number(row.ds) + Number(row.fs);
663
+ if (by === 'updated') {
664
+ const text = latestOf(row.u);
665
+ return text === null ? null : sql.sortValue('string', text, row.u.split(' ')[0]);
666
+ }
667
+ if (by === 'greatest')
668
+ return sortedOf(row.gk, row.gv, row.gi);
669
+ return sortedValue(row, by);
670
+ };
671
+ const ordered = shape.orderBy.map(({ by, direction, nulls }) => termOf(by, { ...GROUP_ORDER, direction, nulls: nulls ?? GROUP_ORDER.nulls }));
520
672
  const ties = keyed.flatMap((_, index) => [
521
673
  { ...outer(index, GROUP_TIES), total: true },
522
674
  { ordering: GROUP_TIES, kind: fragment("'string'"), value: fragment(`k${index}`) },
523
675
  ]);
524
676
  const cursor = plan.after?.values ?? null;
525
- const tieValues = cursor === null
677
+ const after = cursor === null
526
678
  ? null
527
- : cursor[shape.orderBy.length].flatMap((value) => [
528
- value,
529
- heldKind(value ?? null),
530
- ]);
531
- const after = cursor === null || tieValues === null
532
- ? null
533
- : sql.following(ordered.map((term, index) => sql.beyond(bound.collate, term, cursor[index])), sql.following(ties
534
- .slice(0, -1)
535
- .map((term, index) => sql.beyond(bound.collate, term, tieValues[index])), sql.beyond(bound.collate, ties.at(-1), tieValues.at(-1)).beyond));
536
- const grouping = joined([fragment(`SELECT ${columns}, sum(n) AS n FROM (`), source, fragment(`) GROUP BY ${held}`)], '');
679
+ : (() => {
680
+ const tieValues = cursor[shape.orderBy.length].flatMap((value) => [value, heldKind(value ?? null)]);
681
+ return sql.following(ordered.map((term, index) => sql.beyond(bound.collate, term, cursor[index])), sql.following(ties
682
+ .slice(0, -1)
683
+ .map((term, index) => sql.beyond(bound.collate, term, tieValues[index])), sql.beyond(bound.collate, ties.at(-1), tieValues.at(-1)).beyond));
684
+ })();
685
+ const grouping = joined([fragment(`SELECT ${columns} FROM (`), ranked, fragment(`) GROUP BY ${held}`)], '');
537
686
  const windowed = joined([
538
687
  fragment('SELECT * FROM ('),
539
688
  grouping,
@@ -546,16 +695,24 @@ function groups(connection, bound, plan, shape) {
546
695
  const rows = connection.rows(windowed.sql, windowed.bind);
547
696
  const kept = plan.limit === null ? rows : rows.slice(0, plan.limit);
548
697
  const keyOf = (row) => keyed.map((_, index) => decoded(row[`k${index}`], row[`v${index}`]));
549
- const found = kept.map((row) => ({ key: keyOf(row), count: Number(row.n) }));
698
+ const found = kept.map((row) => ({
699
+ key: keyOf(row),
700
+ count: Number(row.n),
701
+ ...(shape.size
702
+ ? {
703
+ documents: { count: Number(row.dn), size: Number(row.ds) },
704
+ files: { count: Number(row.fn), size: Number(row.fs) },
705
+ }
706
+ : {}),
707
+ ...(shape.updated ? { updated: latestOf(row.u) } : {}),
708
+ ...(shape.greatest === null ? {} : { greatest: decoded(row.gk, row.gv) }),
709
+ }));
550
710
  const last = kept.at(-1);
551
711
  const next = plan.limit === null || rows.length <= plan.limit
552
712
  ? undefined
553
713
  : last === undefined
554
714
  ? (plan.after?.text ?? FROM_START)
555
- : cursorOf([
556
- ...shape.orderBy.map(({ by }) => by === 'count' ? Number(last.n) : sortedValue(last, by)),
557
- keyOf(last),
558
- ]);
715
+ : cursorOf([...shape.orderBy.map(({ by }) => valueOf(last, by)), keyOf(last)]);
559
716
  const total = plan.total
560
717
  ? Number(connection.rows(joined([fragment('SELECT count(*) AS held FROM ('), grouping, fragment(')')], '').sql, grouping.bind)[0].held)
561
718
  : undefined;
@@ -565,16 +722,28 @@ function groups(connection, bound, plan, shape) {
565
722
  ...(total === undefined ? {} : { total }),
566
723
  };
567
724
  }
568
- function boundOf(connection, plan, rooms) {
725
+ function boundOf(connection, plan, rooms, follows) {
569
726
  return {
570
727
  rooms: [...rooms].sort((left, right) => left.locator < right.locator ? -1 : left.locator > right.locator ? 1 : 0),
571
- keys: new Map(rooms.map(({ locator, key }) => [locator, key])),
728
+ keys: new Map([...rooms, ...follows].map(({ locator, key }) => [locator, key])),
729
+ follows: JSON.stringify(follows.map(({ key }) => key)),
572
730
  reach: plan.reach,
573
731
  collate: collating(connection),
574
732
  };
575
733
  }
576
- export function answerQuery(connection, plan, rooms, budget = null) {
577
- const bound = boundOf(connection, plan, rooms);
734
+ export function namedHandles(connection, plan, rooms, handles) {
735
+ if (plan.hop === null)
736
+ return [];
737
+ const statement = joined([
738
+ fragment("SELECT DISTINCT l.handle FROM replica_entries d JOIN replica_links l ON l.doc = d.id AND l.kind = 'field' AND l.handle IN (SELECT value FROM json_each(?)) AND ", [JSON.stringify(handles)]),
739
+ grouped(sql.placed('l', plan.hop.field, 'link')),
740
+ fragment(' WHERE '),
741
+ all(tested(boundOf(connection, plan, rooms, []), plan)),
742
+ ], '');
743
+ return connection.rows(statement.sql, statement.bind).map((row) => row.handle);
744
+ }
745
+ export function answerQuery(connection, plan, rooms, budget = null, follows = []) {
746
+ const bound = boundOf(connection, plan, rooms, follows);
578
747
  if (rooms.length === 0) {
579
748
  return plan.shape.kind === 'groups'
580
749
  ? { groups: [], ...(plan.total ? { total: 0 } : {}) }