@agentshouse/mdruntime 0.1.0-c9b1e59e5baeb → 0.1.0-ca10e63188fc5

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