@agentshouse/mdruntime 0.1.0-ca6edc1abd618 → 0.1.0-ca73fc3c2800a

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