@agentshouse/mdruntime 0.1.0-c5d81e5d5cb58 → 0.1.0-c5e756efec46e

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