@agentshouse/mdruntime 0.1.0-c53207a379315 → 0.1.0-c55eff775df08

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