@agentshouse/mdruntime 0.1.0-cdf06805b9658 → 0.1.0-cdf6e063566ab

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