@agentshouse/mdruntime 0.1.0-cfb2ae0107054 → 0.1.0-cfbb7fe185208

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 (424) 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 +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 +292 -126
  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/{binary.d.ts → attachment.d.ts} +8 -9
  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 +347 -0
  22. package/dist/bootstrap.d.ts +31 -11
  23. package/dist/bootstrap.d.ts.map +1 -1
  24. package/dist/bootstrap.js +309 -109
  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 +67 -0
  31. package/dist/change-set.d.ts +13 -14
  32. package/dist/change-set.d.ts.map +1 -1
  33. package/dist/change-set.js +17 -63
  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 +59 -31
  41. package/dist/client.d.ts.map +1 -1
  42. package/dist/client.js +105 -29
  43. package/dist/collection.d.ts +36 -9
  44. package/dist/collection.d.ts.map +1 -1
  45. package/dist/collection.js +62 -79
  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 +19 -0
  50. package/dist/compile.d.ts.map +1 -0
  51. package/dist/compile.js +755 -0
  52. package/dist/connection.d.ts +8 -117
  53. package/dist/connection.d.ts.map +1 -1
  54. package/dist/connection.js +117 -2599
  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 +92 -47
  65. package/dist/conversation.d.ts.map +1 -1
  66. package/dist/conversation.js +1113 -649
  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 +24 -1
  80. package/dist/durability.d.ts.map +1 -1
  81. package/dist/durability.js +12 -0
  82. package/dist/entry.d.ts +31 -4
  83. package/dist/entry.d.ts.map +1 -1
  84. package/dist/entry.js +121 -39
  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 +32 -4
  101. package/dist/host.d.ts.map +1 -1
  102. package/dist/host.js +214 -31
  103. package/dist/house-query.d.ts +24 -0
  104. package/dist/house-query.d.ts.map +1 -0
  105. package/dist/house-query.js +102 -0
  106. package/dist/identity.d.ts +1 -1
  107. package/dist/identity.d.ts.map +1 -1
  108. package/dist/identity.js +1 -1
  109. package/dist/index.d.ts +49 -14
  110. package/dist/index.d.ts.map +1 -1
  111. package/dist/index.js +25 -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 +39 -0
  122. package/dist/live.d.ts.map +1 -0
  123. package/dist/live.js +223 -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 +365 -0
  136. package/dist/memory.d.ts +27 -8
  137. package/dist/memory.d.ts.map +1 -1
  138. package/dist/memory.js +327 -115
  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 +17 -15
  146. package/dist/model.d.ts.map +1 -1
  147. package/dist/model.js +12 -14
  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 +44 -9
  155. package/dist/observation.d.ts.map +1 -1
  156. package/dist/observation.js +271 -33
  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 +71 -10
  167. package/dist/outcome.d.ts.map +1 -1
  168. package/dist/outcome.js +75 -3
  169. package/dist/overlay.d.ts +25 -10
  170. package/dist/overlay.d.ts.map +1 -1
  171. package/dist/overlay.js +190 -190
  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 +330 -0
  190. package/dist/query.d.ts +51 -185
  191. package/dist/query.d.ts.map +1 -1
  192. package/dist/query.js +3 -464
  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 +30 -7
  200. package/dist/reach.d.ts.map +1 -1
  201. package/dist/reach.js +445 -101
  202. package/dist/react.d.ts +27 -7
  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 +68 -0
  209. package/dist/readiness.d.ts.map +1 -0
  210. package/dist/readiness.js +35 -0
  211. package/dist/reads.d.ts +39 -0
  212. package/dist/reads.d.ts.map +1 -0
  213. package/dist/reads.js +179 -0
  214. package/dist/recovery.d.ts +29 -0
  215. package/dist/recovery.d.ts.map +1 -0
  216. package/dist/recovery.js +255 -0
  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 -53
  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 +45 -33
  227. package/dist/replica.d.ts.map +1 -1
  228. package/dist/replica.js +341 -164
  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 +67 -13
  233. package/dist/room-draft.d.ts.map +1 -1
  234. package/dist/room-draft.js +424 -127
  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 +39 -37
  242. package/dist/rows.d.ts.map +1 -1
  243. package/dist/rows.js +73 -127
  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 +37 -0
  248. package/dist/runtime.d.ts.map +1 -0
  249. package/dist/runtime.js +1 -0
  250. package/dist/save.d.ts +44 -43
  251. package/dist/save.d.ts.map +1 -1
  252. package/dist/save.js +759 -288
  253. package/dist/saves.d.ts +34 -0
  254. package/dist/saves.d.ts.map +1 -0
  255. package/dist/saves.js +463 -0
  256. package/dist/search.d.ts +15 -55
  257. package/dist/search.d.ts.map +1 -1
  258. package/dist/search.js +10 -121
  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/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 +10 -0
  266. package/dist/shared.d.ts.map +1 -0
  267. package/dist/shared.js +339 -0
  268. package/dist/shown.d.ts +35 -0
  269. package/dist/shown.d.ts.map +1 -0
  270. package/dist/shown.js +326 -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 +68 -0
  287. package/dist/socket.d.ts.map +1 -0
  288. package/dist/socket.js +165 -0
  289. package/dist/source.d.ts +61 -0
  290. package/dist/source.d.ts.map +1 -0
  291. package/dist/source.js +95 -0
  292. package/dist/status.d.ts +5 -2
  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 +115 -133
  320. package/dist/store.d.ts.map +1 -1
  321. package/dist/store.js +165 -611
  322. package/dist/stored.d.ts +181 -0
  323. package/dist/stored.d.ts.map +1 -0
  324. package/dist/stored.js +807 -0
  325. package/dist/surface.d.ts +94 -0
  326. package/dist/surface.d.ts.map +1 -0
  327. package/dist/surface.js +255 -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 +388 -0
  332. package/dist/tables.d.ts.map +1 -0
  333. package/dist/tables.js +506 -0
  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/turn.d.ts +9 -0
  340. package/dist/turn.d.ts.map +1 -0
  341. package/dist/turn.js +75 -0
  342. package/dist/validation.d.ts +31 -0
  343. package/dist/validation.d.ts.map +1 -0
  344. package/dist/validation.js +144 -0
  345. package/dist/windows.d.ts +11 -0
  346. package/dist/windows.d.ts.map +1 -0
  347. package/dist/windows.js +16 -0
  348. package/dist/wire.d.ts +243 -36
  349. package/dist/wire.d.ts.map +1 -1
  350. package/dist/wire.js +80 -33
  351. package/package.json +20 -20
  352. package/AGENTS.md +0 -299
  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/binary.d.ts.map +0 -1
  357. package/dist/binary.js +0 -8
  358. package/dist/chat/acts.d.ts +0 -33
  359. package/dist/chat/acts.d.ts.map +0 -1
  360. package/dist/chat/acts.js +0 -36
  361. package/dist/chat/context.d.ts +0 -3
  362. package/dist/chat/context.d.ts.map +0 -1
  363. package/dist/chat/input.d.ts +0 -9
  364. package/dist/chat/input.d.ts.map +0 -1
  365. package/dist/chat/input.js +0 -99
  366. package/dist/chat/kit.d.ts +0 -60
  367. package/dist/chat/kit.d.ts.map +0 -1
  368. package/dist/chat/kit.js +0 -123
  369. package/dist/chat/lasting.d.ts +0 -6
  370. package/dist/chat/lasting.d.ts.map +0 -1
  371. package/dist/chat/lasting.js +0 -19
  372. package/dist/chat/list.d.ts +0 -26
  373. package/dist/chat/list.d.ts.map +0 -1
  374. package/dist/chat/list.js +0 -62
  375. package/dist/chat/markdown.d.ts +0 -20
  376. package/dist/chat/markdown.d.ts.map +0 -1
  377. package/dist/chat/markdown.js +0 -188
  378. package/dist/chat/message.d.ts +0 -6
  379. package/dist/chat/message.d.ts.map +0 -1
  380. package/dist/chat/message.js +0 -192
  381. package/dist/chat/messages.d.ts +0 -21
  382. package/dist/chat/messages.d.ts.map +0 -1
  383. package/dist/chat/messages.js +0 -151
  384. package/dist/chat/name.d.ts +0 -6
  385. package/dist/chat/name.d.ts.map +0 -1
  386. package/dist/chat/name.js +0 -37
  387. package/dist/chat/opened.d.ts +0 -11
  388. package/dist/chat/opened.d.ts.map +0 -1
  389. package/dist/chat/opened.js +0 -17
  390. package/dist/chat/overlay.d.ts +0 -31
  391. package/dist/chat/overlay.d.ts.map +0 -1
  392. package/dist/chat/overlay.js +0 -97
  393. package/dist/chat/parts.d.ts +0 -57
  394. package/dist/chat/parts.d.ts.map +0 -1
  395. package/dist/chat/parts.js +0 -119
  396. package/dist/chat/process.d.ts +0 -20
  397. package/dist/chat/process.d.ts.map +0 -1
  398. package/dist/chat/process.js +0 -32
  399. package/dist/chat/provider.d.ts +0 -63
  400. package/dist/chat/provider.d.ts.map +0 -1
  401. package/dist/chat/provider.js +0 -620
  402. package/dist/chat/question.d.ts +0 -9
  403. package/dist/chat/question.d.ts.map +0 -1
  404. package/dist/chat/question.js +0 -80
  405. package/dist/chat/questions.d.ts.map +0 -1
  406. package/dist/chat/read.d.ts.map +0 -1
  407. package/dist/chat/ready.d.ts +0 -33
  408. package/dist/chat/ready.d.ts.map +0 -1
  409. package/dist/chat/ready.js +0 -91
  410. package/dist/chat/style.d.ts +0 -4
  411. package/dist/chat/style.d.ts.map +0 -1
  412. package/dist/chat/style.js +0 -302
  413. package/dist/chat.d.ts +0 -14
  414. package/dist/chat.d.ts.map +0 -1
  415. package/dist/chat.js +0 -8
  416. package/dist/fence.d.ts +0 -6
  417. package/dist/fence.d.ts.map +0 -1
  418. package/dist/fence.js +0 -10
  419. package/dist/log.d.ts +0 -5
  420. package/dist/log.d.ts.map +0 -1
  421. package/dist/log.js +0 -14
  422. package/dist/read-side.d.ts +0 -18
  423. package/dist/read-side.d.ts.map +0 -1
  424. package/dist/read-side.js +0 -440
@@ -0,0 +1,755 @@
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
+ ]);
18
+ }
19
+ export function within(alias, path) {
20
+ return inside(`${alias}.path`, path);
21
+ }
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
+ });
28
+ }
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
+ ]);
39
+ }
40
+ function reached(bound, key, path) {
41
+ const reach = bound.reach;
42
+ if (reach === null)
43
+ return fragment('1');
44
+ const rooms = reach.rooms.flatMap((locator) => {
45
+ const key = bound.keys.get(locator);
46
+ return key === undefined ? [] : [key];
47
+ });
48
+ const documents = reach.documents.flatMap((held) => {
49
+ const key = bound.keys.get(roomOfKey(held));
50
+ return key === undefined ? [] : [[key, pathOfKey(held)]];
51
+ });
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
+ }));
56
+ return all([
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)]),
63
+ ]),
64
+ ]),
65
+ ...(reach.areas.length === 0 ? [] : [fragment(`NOT ${grouped(outside).sql}`, outside.bind)]),
66
+ ]);
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
+ }
88
+ function related(bound, plan) {
89
+ const parts = [];
90
+ if (plan.hop !== null)
91
+ parts.push(sql.hopped('d', plan.hop, followed(bound)));
92
+ if (plan.backlinks !== null) {
93
+ const field = plan.backlinks.field;
94
+ parts.push(exists(joined([
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')])),
98
+ ], ' ')));
99
+ }
100
+ return parts;
101
+ }
102
+ function tested(bound, plan) {
103
+ const keys = bound.rooms.map(({ key }) => key);
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)]);
112
+ }
113
+ function orderingOf(options) {
114
+ const stringSort = options.stringSort ?? 'locale';
115
+ const collated = stringSort === 'locale';
116
+ return {
117
+ direction: options.direction,
118
+ nulls: options.nulls ?? 'first',
119
+ stringSort,
120
+ locale: collated ? options.locale : undefined,
121
+ localeOptions: collated
122
+ ? options.localeOptions
123
+ : undefined,
124
+ };
125
+ }
126
+ const GROUP_ORDER = {
127
+ direction: 'asc',
128
+ nulls: 'first',
129
+ stringSort: 'locale',
130
+ locale: undefined,
131
+ localeOptions: undefined,
132
+ };
133
+ const GROUP_TIES = {
134
+ direction: 'asc',
135
+ nulls: 'last',
136
+ stringSort: 'lexical',
137
+ locale: undefined,
138
+ localeOptions: undefined,
139
+ };
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]);
150
+ }
151
+ function keyTerm(key, ordering, index, prefix) {
152
+ if (key.of === 'field') {
153
+ const alias = `o${index}`;
154
+ return {
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
+ ], ''),
166
+ };
167
+ }
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
+ };
177
+ }
178
+ if (key.of === 'created' || key.of === 'updated') {
179
+ const { value, instant } = TIMES[key.of];
180
+ return {
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,
188
+ };
189
+ }
190
+ const expression = key.of === 'room'
191
+ ? located('d')
192
+ : key.of === 'path'
193
+ ? fragment('d.path')
194
+ : key.of === 'type'
195
+ ? fragment('d.type')
196
+ : key.of === 'subfolder'
197
+ ? subfolderOf('d.folder', prefix)
198
+ : fragment('d.folder');
199
+ return {
200
+ term: {
201
+ ordering,
202
+ kind: fragment(`(CASE WHEN ${expression.sql} IS NULL THEN 'null' ELSE 'string' END)`, expression.bind),
203
+ value: expression,
204
+ },
205
+ join: null,
206
+ };
207
+ }
208
+ function decoded(kind, value) {
209
+ if (kind === 'string')
210
+ return value;
211
+ if (kind === 'number')
212
+ return typeof value === 'bigint' ? Number(value) : value;
213
+ if (kind === 'boolean')
214
+ return Number(value) === 1;
215
+ if (kind === 'array')
216
+ return JSON.parse(value);
217
+ return null;
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
+ }
225
+ function decodedKey(key, row, index) {
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');
233
+ }
234
+ const registered = new WeakMap();
235
+ function hashed(text) {
236
+ let hash = 0x811c9dc5;
237
+ for (let index = 0; index < text.length; index += 1) {
238
+ hash ^= text.charCodeAt(index);
239
+ hash = Math.imul(hash, 0x01000193);
240
+ }
241
+ return (hash >>> 0).toString(36);
242
+ }
243
+ function collating(connection) {
244
+ let held = registered.get(connection);
245
+ if (held === undefined) {
246
+ held = new Set();
247
+ registered.set(connection, held);
248
+ }
249
+ const names = held;
250
+ return (ordering, lists, total) => {
251
+ if (!lists && ordering.stringSort !== 'locale')
252
+ return null;
253
+ const inner = lists
254
+ ? {
255
+ ...ordering,
256
+ direction: 'asc',
257
+ nulls: ordering.direction === 'desc'
258
+ ? ordering.nulls === 'first'
259
+ ? 'last'
260
+ : 'first'
261
+ : ordering.nulls,
262
+ }
263
+ : ordering;
264
+ const spec = JSON.stringify([
265
+ lists,
266
+ total,
267
+ inner.nulls,
268
+ inner.stringSort,
269
+ inner.locale ?? null,
270
+ inner.localeOptions ?? null,
271
+ ]);
272
+ const name = `mdr_${lists ? 'l' : 's'}${hashed(spec)}`;
273
+ if (!names.has(name)) {
274
+ const collator = new Intl.Collator(inner.locale, inner.localeOptions);
275
+ connection.collate(name, lists
276
+ ? (left, right) => Math.sign(compared(JSON.parse(left), JSON.parse(right), inner)) || (total ? Math.sign(byCodePoint(left, right)) : 0)
277
+ : (left, right) => Math.sign(collator.compare(left, right)));
278
+ names.add(name);
279
+ }
280
+ return name;
281
+ };
282
+ }
283
+ function masked(pointers) {
284
+ const root = { whole: false, members: new Map() };
285
+ for (const pointer of pointers) {
286
+ let mask = root;
287
+ for (const token of pointerSegments(pointer)) {
288
+ const next = mask.members.get(token) ?? { whole: false, members: new Map() };
289
+ mask.members.set(token, next);
290
+ mask = next;
291
+ }
292
+ mask.whole = true;
293
+ }
294
+ return root;
295
+ }
296
+ function merged(left, right) {
297
+ if (left === undefined)
298
+ return right;
299
+ const members = new Map(left.members);
300
+ for (const [token, mask] of right.members)
301
+ members.set(token, merged(members.get(token), mask));
302
+ return { whole: left.whole || right.whole, members };
303
+ }
304
+ function cut(value, mask) {
305
+ if (mask.whole)
306
+ return value;
307
+ if (Array.isArray(value)) {
308
+ const each = {
309
+ whole: false,
310
+ members: new Map([...mask.members].filter(([token]) => !ARRAY_INDEX.test(token))),
311
+ };
312
+ const kept = [];
313
+ value.forEach((item, index) => {
314
+ const part = cut(item, merged(mask.members.get(String(index)), each));
315
+ if (part !== undefined)
316
+ kept[index] = part;
317
+ });
318
+ return kept.length === 0 ? undefined : kept;
319
+ }
320
+ if (typeof value !== 'object' || value === null)
321
+ return undefined;
322
+ const kept = Object.entries(value).flatMap(([key, held]) => {
323
+ const member = mask.members.get(key);
324
+ const part = member === undefined ? undefined : cut(held, member);
325
+ return part === undefined ? [] : [[key, part]];
326
+ });
327
+ return kept.length === 0 ? undefined : Object.fromEntries(kept);
328
+ }
329
+ function sectionsOf(sections, names) {
330
+ if (names === 'all')
331
+ return sections;
332
+ return Object.fromEntries(names.flatMap((name) => (Object.hasOwn(sections, name) ? [[name, sections[name]]] : [])));
333
+ }
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;
344
+ const path = row.path;
345
+ const type = row.type;
346
+ const fileId = row.file_id;
347
+ const revision = row.revision;
348
+ if (type === null) {
349
+ const binary = row.binary === null ? null : JSON.parse(row.binary);
350
+ const content = row.content ?? null;
351
+ return {
352
+ room,
353
+ path,
354
+ ...(binary === null
355
+ ? {}
356
+ : {
357
+ attachment: attachmentRecord(path, binary, revision ?? undefined),
358
+ }),
359
+ ...(shape.markdown && content !== null ? { markdown: content } : {}),
360
+ ...(shape.change ? { change: changeOf(row) } : {}),
361
+ ...(shape.fileId ? { fileId } : {}),
362
+ ...(shape.revision ? { revision } : {}),
363
+ ...heldFacts(shape, row),
364
+ };
365
+ }
366
+ const body = shape.sections !== null || shape.preamble
367
+ ? freeParts(queried, path, type, row.content)
368
+ : null;
369
+ const fields = JSON.parse(row.fields ?? '{}');
370
+ return {
371
+ room,
372
+ path,
373
+ type,
374
+ ...(shape.fields === null
375
+ ? {}
376
+ : {
377
+ fields: shape.fields === 'all'
378
+ ? fields
379
+ : (cut(fields, masked(shape.fields)) ?? {}),
380
+ }),
381
+ ...(shape.sections === null || body === null
382
+ ? {}
383
+ : { sections: sectionsOf(body.sections, shape.sections) }),
384
+ ...(shape.preamble && body !== null ? { preamble: body.preamble } : {}),
385
+ ...(shape.markdown ? { markdown: row.content } : {}),
386
+ ...(shape.backlinks ? { backlinks: linked.get(documentKey(room, path)) ?? [] } : {}),
387
+ ...(shape.change ? { change: changeOf(row) } : {}),
388
+ ...(shape.fileId ? { fileId } : {}),
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 } : {}),
400
+ };
401
+ }
402
+ function backlinksOf(connection, bound, rows) {
403
+ const linked = new Map();
404
+ const byKey = new Map();
405
+ for (const row of rows) {
406
+ const key = Number(row.key);
407
+ const held = byKey.get(key) ?? [];
408
+ held.push(row.path);
409
+ byKey.set(key, held);
410
+ }
411
+ const reach = reached(bound, 's.key', 's.path');
412
+ for (const [key, targets] of byKey) {
413
+ const room = bound.rooms.find((one) => one.key === key).locator;
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]);
415
+ for (const row of found) {
416
+ const at = documentKey(room, row.target);
417
+ const held = linked.get(at) ?? [];
418
+ held.push({ path: row.path, type: row.type, field: row.field });
419
+ linked.set(at, held);
420
+ }
421
+ }
422
+ return linked;
423
+ }
424
+ function documents(connection, bound, plan, shape, budget) {
425
+ const terms = shape.orderBy.map(({ key, options }, index) => keyTerm(key, orderingOf(options), index, plan.root.pathPrefix));
426
+ const filter = filtered(bound, plan);
427
+ const cursor = plan.after?.values ?? null;
428
+ const room = located('d');
429
+ const after = cursor === null
430
+ ? null
431
+ : (() => {
432
+ const key = cursor[shape.orderBy.length];
433
+ return sql.following(terms.map(({ term }, index) => sql.beyond(bound.collate, term, cursor[index])), any([
434
+ fragment(`${room.sql} > ?`, [...room.bind, roomOfKey(key)]),
435
+ fragment(`${room.sql} = ? AND d.path > ?`, [
436
+ ...room.bind,
437
+ roomOfKey(key),
438
+ pathOfKey(key),
439
+ ]),
440
+ ]));
441
+ })();
442
+ const selected = joined([
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'),
444
+ ...terms.map(({ term }, index) => joined([
445
+ fragment(`, ${term.kind.sql} AS k${index}`, term.kind.bind),
446
+ fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
447
+ fragment(`, ${instantOf(term).sql} AS i${index}`, instantOf(term).bind),
448
+ ], '')),
449
+ fragment(' FROM replica_entries d'),
450
+ ...terms.flatMap(({ join }) => (join === null ? [] : [fragment(' '), join])),
451
+ fragment(' WHERE '),
452
+ after === null ? filter : all([filter, after]),
453
+ fragment(' ORDER BY '),
454
+ joined([...terms.map(({ term }) => sql.sorted(bound.collate, term)), room, fragment('d.path')], ', '),
455
+ ...(plan.limit === null ? [] : [fragment(' LIMIT ?', [plan.limit + 1])]),
456
+ ], '');
457
+ const rows = connection.rows(selected.sql, selected.bind);
458
+ const windowed = plan.limit === null ? rows : rows.slice(0, plan.limit);
459
+ const kept = bodied(shape) ? withContent(connection, windowed, budget) : windowed;
460
+ const cut = kept.length;
461
+ const roomOf = new Map(bound.rooms.map(({ key, locator }) => [key, locator]));
462
+ const queried = new Map(bound.rooms.map((one) => [one.key, one]));
463
+ const linked = shape.backlinks ? backlinksOf(connection, bound, kept) : new Map();
464
+ const found = kept.map((row) => documentOf(shape, queried.get(Number(row.key)), row, linked));
465
+ const last = kept.at(-1);
466
+ const cursorAt = (row) => cursorOf([
467
+ ...shape.orderBy.map(({ key }, index) => decodedKey(key, row, index)),
468
+ documentKey(roomOf.get(Number(row.key)), row.path),
469
+ ]);
470
+ const more = cut < windowed.length && last !== undefined ? cursorAt(last) : undefined;
471
+ const next = more !== undefined || plan.limit === null || rows.length <= plan.limit
472
+ ? undefined
473
+ : last === undefined
474
+ ? (plan.after?.text ?? FROM_START)
475
+ : cursorAt(last);
476
+ const total = plan.total
477
+ ? (() => {
478
+ const counted = joined([fragment('SELECT count(*) AS held FROM replica_entries d WHERE '), filter], '');
479
+ return Number(connection.rows(counted.sql, counted.bind)[0].held);
480
+ })()
481
+ : undefined;
482
+ return {
483
+ documents: found,
484
+ ...(next === undefined ? {} : { next }),
485
+ ...(more === undefined ? {} : { more }),
486
+ ...(total === undefined ? {} : { total }),
487
+ };
488
+ }
489
+ function withContent(connection, rows, budget) {
490
+ if (rows.length === 0)
491
+ return rows;
492
+ const ids = rows.map((row) => row.id);
493
+ const sizes = new Map(connection
494
+ .rows(`SELECT id, octet_length(content) AS size FROM replica_entries WHERE id IN ${listed(ids).sql}`, ids)
495
+ .map((row) => [row.id, Number(row.size ?? 0)]));
496
+ let cut = rows.length;
497
+ let spent = 0;
498
+ for (let at = 0; budget !== null && at < rows.length; at += 1) {
499
+ const size = sizes.get(rows[at].id) ?? 0;
500
+ if (at > 0 && spent + size > budget) {
501
+ cut = at;
502
+ break;
503
+ }
504
+ spent += size;
505
+ }
506
+ const kept = rows.slice(0, cut);
507
+ const read = kept.map((row) => row.id);
508
+ const held = new Map(connection
509
+ .rows(`SELECT id, content FROM replica_entries WHERE id IN ${listed(read).sql}`, read)
510
+ .map((row) => [row.id, row.content]));
511
+ return kept.map((row) => ({ ...row, content: held.get(row.id) ?? null }));
512
+ }
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)
519
+ return null;
520
+ const whole = bound.rooms.filter(({ locator }) => bound.reach === null || bound.reach.rooms.includes(locator));
521
+ if (whole.length === 0)
522
+ return null;
523
+ const keys = whole.map(({ key }) => key);
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
+ ];
541
+ return all([
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)),
546
+ ...(plan.folder === null ? [] : [fragment('f.path = ?', [plan.folder])]),
547
+ ]);
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
+ }
564
+ function groups(connection, bound, plan, shape) {
565
+ const prefix = plan.root.pathPrefix;
566
+ const keyed = shape.groupBy.map((key, index) => {
567
+ const { term, join } = keyTerm(key, GROUP_ORDER, index, prefix);
568
+ const kind = fragment(`COALESCE(${term.kind.sql}, 'null')`, term.kind.bind);
569
+ return { term: { ...term, kind }, join };
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);
577
+ const filter = filtered(bound, plan);
578
+ const inner = joined([
579
+ fragment('SELECT '),
580
+ joined(keyed.map(({ term }, index) => joined([
581
+ fragment(`${term.kind.sql} AS k${index}`, term.kind.bind),
582
+ fragment(`, ${term.value.sql} AS v${index}`, term.value.bind),
583
+ fragment(`, ${instantOf(term).sql} AS i${index}`, instantOf(term).bind),
584
+ ], '')), ', '),
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]),
595
+ fragment(' WHERE '),
596
+ filter,
597
+ ], '');
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
+ ];
607
+ const source = folders === null
608
+ ? inner
609
+ : joined([
610
+ inner,
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),
612
+ folders,
613
+ ], '');
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,
637
+ kind: fragment(`k${index}`),
638
+ value: fragment(`v${index}`),
639
+ });
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 }));
672
+ const ties = keyed.flatMap((_, index) => [
673
+ { ...outer(index, GROUP_TIES), total: true },
674
+ { ordering: GROUP_TIES, kind: fragment("'string'"), value: fragment(`k${index}`) },
675
+ ]);
676
+ const cursor = plan.after?.values ?? null;
677
+ const after = cursor === null
678
+ ? null
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}`)], '');
686
+ const windowed = joined([
687
+ fragment('SELECT * FROM ('),
688
+ grouping,
689
+ fragment(')'),
690
+ ...(after === null ? [] : [fragment(' WHERE '), after]),
691
+ fragment(' ORDER BY '),
692
+ joined([...ordered, ...ties].map((term) => sql.sorted(bound.collate, term)), ', '),
693
+ ...(plan.limit === null ? [] : [fragment(' LIMIT ?', [plan.limit + 1])]),
694
+ ], '');
695
+ const rows = connection.rows(windowed.sql, windowed.bind);
696
+ const kept = plan.limit === null ? rows : rows.slice(0, plan.limit);
697
+ const keyOf = (row) => keyed.map((_, index) => decoded(row[`k${index}`], row[`v${index}`]));
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
+ }));
710
+ const last = kept.at(-1);
711
+ const next = plan.limit === null || rows.length <= plan.limit
712
+ ? undefined
713
+ : last === undefined
714
+ ? (plan.after?.text ?? FROM_START)
715
+ : cursorOf([...shape.orderBy.map(({ by }) => valueOf(last, by)), keyOf(last)]);
716
+ const total = plan.total
717
+ ? Number(connection.rows(joined([fragment('SELECT count(*) AS held FROM ('), grouping, fragment(')')], '').sql, grouping.bind)[0].held)
718
+ : undefined;
719
+ return {
720
+ groups: found,
721
+ ...(next === undefined ? {} : { next }),
722
+ ...(total === undefined ? {} : { total }),
723
+ };
724
+ }
725
+ function boundOf(connection, plan, rooms, follows) {
726
+ return {
727
+ rooms: [...rooms].sort((left, right) => left.locator < right.locator ? -1 : left.locator > right.locator ? 1 : 0),
728
+ keys: new Map([...rooms, ...follows].map(({ locator, key }) => [locator, key])),
729
+ follows: JSON.stringify(follows.map(({ key }) => key)),
730
+ reach: plan.reach,
731
+ collate: collating(connection),
732
+ };
733
+ }
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);
744
+ }
745
+ export function answerQuery(connection, plan, rooms, budget = null, follows = []) {
746
+ const bound = boundOf(connection, plan, rooms, follows);
747
+ if (rooms.length === 0) {
748
+ return plan.shape.kind === 'groups'
749
+ ? { groups: [], ...(plan.total ? { total: 0 } : {}) }
750
+ : { documents: [], ...(plan.total ? { total: 0 } : {}) };
751
+ }
752
+ return plan.shape.kind === 'groups'
753
+ ? groups(connection, bound, plan, plan.shape)
754
+ : documents(connection, bound, plan, plan.shape, budget);
755
+ }