@agentshouse/mdruntime 0.1.0-c5d3fa6fb67bc → 0.1.0-c5e756efec46e

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