@agentshouse/mdruntime 0.1.0-cc8c6d652ec3b → 0.1.0-ccb3e30d19ce2

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