cvx-kit 0.2.0 → 2.0.0-beta.0

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 (372) hide show
  1. package/README.md +556 -99
  2. package/dist/agent-tools.d.mts +39 -26
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +120 -308
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +7 -9
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +1 -4
  11. package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
  12. package/dist/components/approvals/_generated/server.d.mts +12 -15
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +8 -9
  15. package/dist/components/approvals/audit.mjs +1 -1
  16. package/dist/components/approvals/audit.mjs.map +1 -1
  17. package/dist/components/approvals/client.d.mts +11 -12
  18. package/dist/components/approvals/client.mjs +1 -1
  19. package/dist/components/approvals/client.mjs.map +1 -1
  20. package/dist/components/approvals/constants.d.mts +30 -31
  21. package/dist/components/approvals/constants.mjs.map +1 -1
  22. package/dist/components/approvals/convex.config.d.mts +0 -2
  23. package/dist/components/approvals/convex.config.mjs.map +1 -1
  24. package/dist/components/approvals/decisions.d.mts +13 -17
  25. package/dist/components/approvals/decisions.mjs +1 -1
  26. package/dist/components/approvals/decisions.mjs.map +1 -1
  27. package/dist/components/approvals/functions.d.mts +3 -4
  28. package/dist/components/approvals/functions.mjs +1 -1
  29. package/dist/components/approvals/functions.mjs.map +1 -1
  30. package/dist/components/approvals/health.d.mts +2 -3
  31. package/dist/components/approvals/health.mjs.map +1 -1
  32. package/dist/components/approvals/requests.d.mts +114 -131
  33. package/dist/components/approvals/requests.mjs +1 -1
  34. package/dist/components/approvals/requests.mjs.map +1 -1
  35. package/dist/components/approvals/schema.d.ts +106 -315
  36. package/dist/components/approvals/schema.js +1 -1
  37. package/dist/components/approvals/validators.d.mts +323 -395
  38. package/dist/components/approvals/validators.mjs +1 -1
  39. package/dist/components/approvals/validators.mjs.map +1 -1
  40. package/dist/components/approvals/workflow.d.mts +4 -5
  41. package/dist/components/approvals/workflow.mjs +1 -1
  42. package/dist/components/approvals/workflow.mjs.map +1 -1
  43. package/dist/components/approvals/workflow_steps.d.mts +16 -17
  44. package/dist/components/approvals/workflow_steps.mjs +1 -1
  45. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/api.d.mts +6 -8
  47. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  48. package/dist/components/foundation/_generated/component.d.mts +1 -4
  49. package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
  50. package/dist/components/foundation/_generated/server.d.mts +12 -15
  51. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  52. package/dist/components/foundation/client.d.mts +45 -38
  53. package/dist/components/foundation/client.mjs +1 -1
  54. package/dist/components/foundation/client.mjs.map +1 -1
  55. package/dist/components/foundation/convex.config.d.mts +0 -2
  56. package/dist/components/foundation/convex.config.mjs.map +1 -1
  57. package/dist/components/foundation/functions.d.mts +2 -3
  58. package/dist/components/foundation/functions.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/command.d.mts +65 -17
  60. package/dist/components/foundation/modules/command/command.mjs +1 -1
  61. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  62. package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
  63. package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
  64. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
  65. package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
  66. package/dist/components/foundation/modules/observability/observability.mjs +1 -1
  67. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  68. package/dist/components/foundation/modules/query/query.d.mts +11 -12
  69. package/dist/components/foundation/modules/query/query.mjs +1 -1
  70. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  71. package/dist/components/foundation/operation.d.mts +72 -0
  72. package/dist/components/foundation/operation.mjs +2 -0
  73. package/dist/components/foundation/operation.mjs.map +1 -0
  74. package/dist/components/foundation/result.d.mts +7 -8
  75. package/dist/components/foundation/result.mjs.map +1 -1
  76. package/dist/components/foundation/schema.d.ts +0 -2
  77. package/dist/components/foundation/telemetry.d.mts +2 -3
  78. package/dist/components/foundation/telemetry.mjs +1 -1
  79. package/dist/components/foundation/telemetry.mjs.map +1 -1
  80. package/dist/contracts.d.mts +5 -0
  81. package/dist/contracts.mjs +1 -0
  82. package/dist/crud.d.mts +185 -27
  83. package/dist/crud.mjs +1 -1
  84. package/dist/crud.mjs.map +1 -1
  85. package/dist/effect.d.mts +16 -0
  86. package/dist/effect.mjs +1 -0
  87. package/dist/errors.d.mts +6 -6
  88. package/dist/errors.mjs +1 -1
  89. package/dist/errors.mjs.map +1 -1
  90. package/dist/filters.d.mts +4 -0
  91. package/dist/filters.mjs +1 -0
  92. package/dist/idempotency.d.mts +2 -0
  93. package/dist/idempotency.mjs +1 -0
  94. package/dist/index.d.mts +14 -7
  95. package/dist/index.mjs +1 -1
  96. package/dist/json-schema.d.mts +40 -0
  97. package/dist/json-schema.mjs +2 -0
  98. package/dist/json-schema.mjs.map +1 -0
  99. package/dist/k/compile.d.mts +17 -0
  100. package/dist/k/compile.mjs +2 -0
  101. package/dist/k/compile.mjs.map +1 -0
  102. package/dist/k/dates.d.mts +23 -0
  103. package/dist/k/dates.mjs +2 -0
  104. package/dist/k/dates.mjs.map +1 -0
  105. package/dist/k/formats.d.mts +24 -0
  106. package/dist/k/formats.mjs +2 -0
  107. package/dist/k/formats.mjs.map +1 -0
  108. package/dist/k/index.d.mts +32 -0
  109. package/dist/k/index.mjs +2 -0
  110. package/dist/k/index.mjs.map +1 -0
  111. package/dist/k/issues.d.mts +31 -0
  112. package/dist/k/issues.mjs +2 -0
  113. package/dist/k/issues.mjs.map +1 -0
  114. package/dist/k/kinds.d.mts +81 -0
  115. package/dist/k/kinds.mjs +2 -0
  116. package/dist/k/kinds.mjs.map +1 -0
  117. package/dist/k/object.d.mts +43 -0
  118. package/dist/k/object.mjs +2 -0
  119. package/dist/k/object.mjs.map +1 -0
  120. package/dist/k/parse.d.mts +29 -0
  121. package/dist/k/parse.mjs +2 -0
  122. package/dist/k/parse.mjs.map +1 -0
  123. package/dist/k/schema.d.mts +100 -0
  124. package/dist/k/schema.mjs +2 -0
  125. package/dist/k/schema.mjs.map +1 -0
  126. package/dist/k/standard.d.mts +8 -0
  127. package/dist/k/standard.mjs +2 -0
  128. package/dist/k/standard.mjs.map +1 -0
  129. package/dist/k/types.d.mts +64 -0
  130. package/dist/k/types.mjs +1 -0
  131. package/dist/k.d.mts +8 -0
  132. package/dist/k.mjs +1 -0
  133. package/dist/middleware.d.mts +8 -11
  134. package/dist/middleware.mjs +1 -1
  135. package/dist/middleware.mjs.map +1 -1
  136. package/dist/modules/contracts/binding.d.mts +23 -0
  137. package/dist/modules/contracts/binding.mjs +2 -0
  138. package/dist/modules/contracts/binding.mjs.map +1 -0
  139. package/dist/modules/contracts/contract.d.mts +67 -0
  140. package/dist/modules/contracts/contract.mjs +2 -0
  141. package/dist/modules/contracts/contract.mjs.map +1 -0
  142. package/dist/modules/contracts/convex.d.mts +18 -0
  143. package/dist/modules/contracts/convex.mjs +2 -0
  144. package/dist/modules/contracts/convex.mjs.map +1 -0
  145. package/dist/modules/contracts/domain.d.mts +62 -0
  146. package/dist/modules/contracts/domain.mjs +2 -0
  147. package/dist/modules/contracts/domain.mjs.map +1 -0
  148. package/dist/modules/contracts/errors.d.mts +737 -0
  149. package/dist/modules/contracts/errors.mjs +2 -0
  150. package/dist/modules/contracts/errors.mjs.map +1 -0
  151. package/dist/modules/contracts/exposure.d.mts +103 -0
  152. package/dist/modules/contracts/exposure.mjs +2 -0
  153. package/dist/modules/contracts/exposure.mjs.map +1 -0
  154. package/dist/modules/contracts/idempotency.d.mts +85 -0
  155. package/dist/modules/contracts/idempotency.mjs +2 -0
  156. package/dist/modules/contracts/idempotency.mjs.map +1 -0
  157. package/dist/modules/contracts/lazy.d.mts +6 -0
  158. package/dist/modules/contracts/lazy.mjs +2 -0
  159. package/dist/modules/contracts/lazy.mjs.map +1 -0
  160. package/dist/modules/contracts/standard.d.mts +17 -0
  161. package/dist/modules/contracts/standard.mjs +2 -0
  162. package/dist/modules/contracts/standard.mjs.map +1 -0
  163. package/dist/modules/contracts/workflow.d.mts +165 -0
  164. package/dist/modules/contracts/workflow.mjs +2 -0
  165. package/dist/modules/contracts/workflow.mjs.map +1 -0
  166. package/dist/modules/effect/action.d.mts +63 -0
  167. package/dist/modules/effect/action.mjs +2 -0
  168. package/dist/modules/effect/action.mjs.map +1 -0
  169. package/dist/modules/effect/agent-tools.d.mts +2 -0
  170. package/dist/modules/effect/agent-tools.mjs +1 -0
  171. package/dist/modules/effect/api-runtime.d.mts +36 -0
  172. package/dist/modules/effect/api-runtime.mjs +2 -0
  173. package/dist/modules/effect/api-runtime.mjs.map +1 -0
  174. package/dist/modules/effect/api.d.mts +46 -0
  175. package/dist/modules/effect/api.mjs +2 -0
  176. package/dist/modules/effect/api.mjs.map +1 -0
  177. package/dist/modules/effect/auth.d.mts +46 -0
  178. package/dist/modules/effect/auth.mjs +2 -0
  179. package/dist/modules/effect/auth.mjs.map +1 -0
  180. package/dist/modules/effect/client.d.mts +15 -0
  181. package/dist/modules/effect/client.mjs +1 -0
  182. package/dist/modules/effect/command.d.mts +108 -0
  183. package/dist/modules/effect/command.mjs +2 -0
  184. package/dist/modules/effect/command.mjs.map +1 -0
  185. package/dist/modules/effect/crud.d.mts +885 -0
  186. package/dist/modules/effect/crud.mjs +2 -0
  187. package/dist/modules/effect/crud.mjs.map +1 -0
  188. package/dist/modules/effect/domain.d.mts +82 -0
  189. package/dist/modules/effect/domain.mjs +2 -0
  190. package/dist/modules/effect/domain.mjs.map +1 -0
  191. package/dist/modules/effect/errors.d.mts +13 -0
  192. package/dist/modules/effect/errors.mjs +2 -0
  193. package/dist/modules/effect/errors.mjs.map +1 -0
  194. package/dist/modules/effect/failure-audit.d.mts +48 -0
  195. package/dist/modules/effect/failure-audit.mjs +2 -0
  196. package/dist/modules/effect/failure-audit.mjs.map +1 -0
  197. package/dist/modules/effect/failures.d.mts +21 -0
  198. package/dist/modules/effect/failures.mjs +2 -0
  199. package/dist/modules/effect/failures.mjs.map +1 -0
  200. package/dist/modules/effect/foundation.d.mts +23 -0
  201. package/dist/modules/effect/foundation.mjs +2 -0
  202. package/dist/modules/effect/foundation.mjs.map +1 -0
  203. package/dist/modules/effect/idempotency.d.mts +29 -0
  204. package/dist/modules/effect/idempotency.mjs +2 -0
  205. package/dist/modules/effect/idempotency.mjs.map +1 -0
  206. package/dist/modules/effect/input.d.mts +10 -0
  207. package/dist/modules/effect/input.mjs +2 -0
  208. package/dist/modules/effect/input.mjs.map +1 -0
  209. package/dist/modules/effect/normalize.d.mts +7 -0
  210. package/dist/modules/effect/normalize.mjs +2 -0
  211. package/dist/modules/effect/normalize.mjs.map +1 -0
  212. package/dist/modules/effect/operation.d.mts +148 -0
  213. package/dist/modules/effect/operation.mjs +2 -0
  214. package/dist/modules/effect/operation.mjs.map +1 -0
  215. package/dist/modules/effect/query.d.mts +90 -0
  216. package/dist/modules/effect/query.mjs +2 -0
  217. package/dist/modules/effect/query.mjs.map +1 -0
  218. package/dist/modules/effect/schema.d.mts +30 -0
  219. package/dist/modules/effect/schema.mjs +2 -0
  220. package/dist/modules/effect/schema.mjs.map +1 -0
  221. package/dist/modules/effect/scope.d.mts +25 -0
  222. package/dist/modules/effect/scope.mjs +2 -0
  223. package/dist/modules/effect/scope.mjs.map +1 -0
  224. package/dist/modules/effect/workflow.d.mts +75 -0
  225. package/dist/modules/effect/workflow.mjs +2 -0
  226. package/dist/modules/effect/workflow.mjs.map +1 -0
  227. package/dist/modules/foundation/foundation.d.mts +108 -0
  228. package/dist/modules/foundation/foundation.mjs +2 -0
  229. package/dist/modules/foundation/foundation.mjs.map +1 -0
  230. package/dist/modules/foundation/operation.d.mts +139 -0
  231. package/dist/modules/foundation/operation.mjs +2 -0
  232. package/dist/modules/foundation/operation.mjs.map +1 -0
  233. package/dist/namespace.d.mts +104 -0
  234. package/dist/namespace.mjs +2 -0
  235. package/dist/namespace.mjs.map +1 -0
  236. package/dist/oxlint/architecture.d.mts +23 -0
  237. package/dist/oxlint/architecture.mjs +2 -0
  238. package/dist/oxlint/architecture.mjs.map +1 -0
  239. package/dist/oxlint/ast.d.mts +51 -0
  240. package/dist/oxlint/ast.mjs +2 -0
  241. package/dist/oxlint/ast.mjs.map +1 -0
  242. package/dist/oxlint/components.d.mts +4 -0
  243. package/dist/oxlint/components.mjs +2 -0
  244. package/dist/oxlint/components.mjs.map +1 -0
  245. package/dist/oxlint/ownership.d.mts +59 -0
  246. package/dist/oxlint/ownership.mjs +2 -0
  247. package/dist/oxlint/ownership.mjs.map +1 -0
  248. package/dist/oxlint/reserved-files.d.mts +4 -0
  249. package/dist/oxlint/reserved-files.mjs +2 -0
  250. package/dist/oxlint/reserved-files.mjs.map +1 -0
  251. package/dist/oxlint.d.mts +9 -0
  252. package/dist/oxlint.mjs +2 -0
  253. package/dist/oxlint.mjs.map +1 -0
  254. package/dist/querying/cursors.d.mts +94 -0
  255. package/dist/querying/cursors.mjs +2 -0
  256. package/dist/querying/cursors.mjs.map +1 -0
  257. package/dist/querying/execution.d.mts +40 -0
  258. package/dist/querying/execution.mjs +2 -0
  259. package/dist/querying/execution.mjs.map +1 -0
  260. package/dist/querying/failures.d.mts +11 -0
  261. package/dist/querying/failures.mjs +2 -0
  262. package/dist/querying/failures.mjs.map +1 -0
  263. package/dist/querying/filter-boundary.d.mts +25 -0
  264. package/dist/querying/filter-boundary.mjs +2 -0
  265. package/dist/querying/filter-boundary.mjs.map +1 -0
  266. package/dist/querying/filters.d.mts +180 -0
  267. package/dist/querying/filters.mjs +2 -0
  268. package/dist/querying/filters.mjs.map +1 -0
  269. package/dist/querying/planner.d.mts +61 -0
  270. package/dist/querying/planner.mjs +2 -0
  271. package/dist/querying/planner.mjs.map +1 -0
  272. package/dist/querying/relationships.d.mts +58 -0
  273. package/dist/querying/relationships.mjs +2 -0
  274. package/dist/querying/relationships.mjs.map +1 -0
  275. package/dist/querying/search.d.mts +69 -0
  276. package/dist/querying/search.mjs +2 -0
  277. package/dist/querying/search.mjs.map +1 -0
  278. package/dist/querying/security.d.mts +123 -0
  279. package/dist/querying/security.mjs +2 -0
  280. package/dist/querying/security.mjs.map +1 -0
  281. package/dist/querying/shared/ast.d.mts +26 -0
  282. package/dist/querying/shared/ast.mjs +2 -0
  283. package/dist/querying/shared/ast.mjs.map +1 -0
  284. package/dist/querying/shared/contract.d.mts +98 -0
  285. package/dist/querying/shared/contract.mjs +2 -0
  286. package/dist/querying/shared/contract.mjs.map +1 -0
  287. package/dist/querying/shared/evaluate.d.mts +5 -0
  288. package/dist/querying/shared/evaluate.mjs +2 -0
  289. package/dist/querying/shared/evaluate.mjs.map +1 -0
  290. package/dist/querying/shared/filters.d.mts +65 -0
  291. package/dist/querying/shared/filters.mjs +2 -0
  292. package/dist/querying/shared/filters.mjs.map +1 -0
  293. package/dist/querying/shared/native-json.d.mts +7 -0
  294. package/dist/querying/shared/native-json.mjs +2 -0
  295. package/dist/querying/shared/native-json.mjs.map +1 -0
  296. package/dist/querying/shared/page.d.mts +20 -0
  297. package/dist/querying/shared/page.mjs +2 -0
  298. package/dist/querying/shared/page.mjs.map +1 -0
  299. package/dist/querying.d.mts +82 -0
  300. package/dist/querying.mjs +2 -0
  301. package/dist/querying.mjs.map +1 -0
  302. package/dist/react/failures.d.mts +24 -0
  303. package/dist/react/failures.mjs +2 -0
  304. package/dist/react/failures.mjs.map +1 -0
  305. package/dist/react/optimistic.d.mts +46 -0
  306. package/dist/react/optimistic.mjs +2 -0
  307. package/dist/react/optimistic.mjs.map +1 -0
  308. package/dist/react/pagination-state.d.mts +39 -0
  309. package/dist/react/pagination-state.mjs +2 -0
  310. package/dist/react/pagination-state.mjs.map +1 -0
  311. package/dist/react/use-command.d.mts +22 -0
  312. package/dist/react/use-command.mjs +2 -0
  313. package/dist/react/use-command.mjs.map +1 -0
  314. package/dist/react/use-paginated-list.d.mts +34 -0
  315. package/dist/react/use-paginated-list.mjs +2 -0
  316. package/dist/react/use-paginated-list.mjs.map +1 -0
  317. package/dist/react.d.mts +6 -0
  318. package/dist/react.mjs +1 -0
  319. package/dist/registration.d.mts +65 -0
  320. package/dist/registration.mjs +2 -0
  321. package/dist/registration.mjs.map +1 -0
  322. package/dist/relations-public.d.mts +2 -0
  323. package/dist/relations-public.mjs +1 -0
  324. package/dist/relations.d.mts +274 -0
  325. package/dist/relations.mjs +2 -0
  326. package/dist/relations.mjs.map +1 -0
  327. package/dist/state-machine.d.mts +1 -4
  328. package/dist/state-machine.mjs.map +1 -1
  329. package/dist/table.d.mts +222 -0
  330. package/dist/table.mjs +2 -0
  331. package/dist/table.mjs.map +1 -0
  332. package/dist/tenancy.d.mts +6 -8
  333. package/dist/tenancy.mjs +1 -1
  334. package/dist/tenancy.mjs.map +1 -1
  335. package/dist/triggers.d.mts +12 -10
  336. package/dist/triggers.mjs +1 -1
  337. package/dist/triggers.mjs.map +1 -1
  338. package/dist/webhooks.d.mts +22 -112
  339. package/dist/webhooks.mjs +1 -1
  340. package/dist/webhooks.mjs.map +1 -1
  341. package/dist/workflow.d.mts +2 -0
  342. package/dist/workflow.mjs +1 -0
  343. package/dist/zod.d.mts +30 -0
  344. package/dist/zod.mjs +2 -0
  345. package/dist/zod.mjs.map +1 -0
  346. package/package.json +145 -33
  347. package/src/test.ts +9 -17
  348. package/CHANGELOG.md +0 -145
  349. package/ROADMAP.md +0 -126
  350. package/dist/zod-table.d.mts +0 -175
  351. package/dist/zod-table.mjs +0 -2
  352. package/dist/zod-table.mjs.map +0 -1
  353. package/docs/agent-tools.md +0 -41
  354. package/docs/approvals.md +0 -200
  355. package/docs/architecture.md +0 -124
  356. package/docs/auth.md +0 -218
  357. package/docs/commands.md +0 -278
  358. package/docs/conventions.md +0 -291
  359. package/docs/crud.md +0 -62
  360. package/docs/llms.md +0 -220
  361. package/docs/maintainability.md +0 -124
  362. package/docs/migration.md +0 -351
  363. package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
  364. package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
  365. package/docs/tenancy.md +0 -179
  366. package/docs/triggers.md +0 -75
  367. package/docs/upgrading.md +0 -175
  368. package/docs/webhooks.md +0 -58
  369. package/docs/zod-table.md +0 -173
  370. package/scripts/convex-config-bridge.mjs +0 -55
  371. package/scripts/extract-changelog.mjs +0 -29
  372. package/scripts/smoke-packed-components.mjs +0 -374
@@ -0,0 +1,2 @@
1
+ import{forceRegistry as e}from"./modules/contracts/lazy.mjs";import{createResolver as t,inspectArchitecture as n,narrowRootDeclaration as r,resolveImport as i}from"./oxlint/architecture.mjs";import{reservedDomainFiles as a}from"./oxlint/reserved-files.mjs";import{ownershipRules as o}from"./oxlint/ownership.mjs";import{TABLE_SOURCES as s,appFile as c,binding as l,componentRoot as u,consumerOptions as d,exportName as f,exportedNames as p,imported as m,isDbWrite as h,isFunctionsImport as g,isTableChain as _,kFactory as v,localInitializer as y,metadata as b,propertyName as x,readProvenance as S,sourceVisitors as C,staticString as w}from"./oxlint/ast.mjs";import{basename as T,dirname as E,relative as D,sep as O}from"node:path";function k(t={}){for(let n of t.registries??[])e(n);return n(t)}const A=M({...o,"root-wiring-only":{...o[`root-wiring-only`],create(e){let t=c(e)??``;return[`relations.ts`,`querying.ts`].includes(t)?r(t,e.sourceCode.text)?{}:{Program(n){e.report({node:n,messageId:`ownership`,data:{reason:`${t} must export one kit factory declaration and contain only declarative configuration`}})}}:o[`root-wiring-only`].create(e)}},"reserved-domain-file-anatomy":a,"root-facade-ownership":{meta:b(`Configure shared kit infrastructure once in its root facade.`,{facade:`Configure {{name}} once in convex/{{file}}; import that facade elsewhere.`}),create(e){let t=u(e,e.filename),n=/* @__PURE__ */ new Set;function r(r){let i=m(e,r.callee);if(!i)return;let a=null;[`cvx-kit`,`cvx-kit/querying`].includes(i.source)&&i.name===`createQueryEngine`&&(a=`querying.ts`),[`cvx-kit`,`cvx-kit/relations`].includes(i.source)&&i.name===`defineRelations`&&(a=`relations.ts`),[`cvx-kit`,`cvx-kit/auth`].includes(i.source)&&i.name===`createAuthFunctions`&&(a=`functions.ts`),[`cvx-kit`,`cvx-kit/triggers`].includes(i.source)&&i.name===`createTriggers`&&(a=`triggers.ts`),[`cvx-kit`,`cvx-kit/components/foundation`].includes(i.source)&&i.name===`Foundation`&&(a=`foundation.ts`),(i.source===`cvx-kit/effect`&&i.name===`createEffectFoundation`||i.source===`cvx-kit`&&i.name===`createFoundation`)&&(a=`foundation.ts`),a&&(((t?D(t,e.filename).split(O).join(`/`):c(e))!==a||n.has(i.name))&&e.report({node:r,messageId:`facade`,data:{name:i.name,file:a}}),n.add(i.name))}return{CallExpression:r,NewExpression:r}}},"no-raw-builders":{meta:b(`Build host functions through the auth-aware root constructors.`,{builder:`Import raw builders only in convex/functions.ts; use auth*/role*/admin* or system* elsewhere.`}),create(e){let n=u(e,e.filename);if((n?D(n,e.filename).split(O).join(`/`):c(e))===`functions.ts`)return{};let r=t();return{ImportDeclaration(t){if(t.importKind===`type`)return;let a=t.source.value,o=i(r,e.filename,a),s=o?n?D(n,o).split(O).join(`/`):c(e,o):null,l=s?.startsWith(`_generated/`)?s:a;if(/(?:^|\/)_generated\/server(?:\.[cm]?[jt]s)?$/.test(l)||l===`convex/server`)for(let n of t.specifiers){if(n.type===`ImportSpecifier`&&n.importKind===`type`)continue;let t=n.type===`ImportSpecifier`?f(n.imported):null;(t===null&&l!==`convex/server`||t&&/^(?:internal)?(?:Query|Mutation|Action)(?:Generic)?$|^(?:query|mutation|action)(?:Generic)?$/.test(t))&&e.report({node:n,messageId:`builder`})}},CallExpression(t){let n=m(e,t.callee);n?.source===`convex/server`&&/^(?:internal)?(?:Query|Mutation|Action)Generic$|^(?:query|mutation|action)Generic$/.test(n.name)&&t.callee.type===`MemberExpression`&&e.report({node:t,messageId:`builder`})}}}},"no-handwritten-references":{meta:b(`Use generated api/internal references.`,{reference:`Use generated api/internal references instead of makeFunctionReference.`}),create(e){return{CallExpression(t){let n=m(e,t.callee);n?.source===`convex/server`&&n.name===`makeFunctionReference`&&e.report({node:t,messageId:`reference`})}}}},"domain-import-boundaries":{meta:b(`Keep api, application, domain, and shared dependencies directed.`,{boundary:`Follow api → application/domain → shared; sibling modules expose only rules.ts and queries.ts.`}),create(e){let{domainPublicFiles:n}=d.parse(e.options[0]??{}),r=c(e);if(u(e,e.filename))return{};let a=t();return C(e,(t,o)=>{if(!r)return;let s=i(a,e.filename,o);if(!s)return;let l=c(e,s)?.replace(/\.[cm]?[jt]s$/,``);if(!l){s.split(O).includes(`node_modules`)||e.report({node:t,messageId:`boundary`});return}let u=r.split(`/`),d=l.split(`/`),f=!1;u[0]===`domain`?(f=[`api`,`application`,`migrations`].includes(d[0]),d[0]===`domain`&&u[1]!==d[1]&&d[1]!==`shared`&&u[1]!==`table.ts`&&(f=u[1]===`shared`||![`rules`,`queries`,`contracts`].includes(d.slice(2).join(`/`))&&!n[d[1]]?.includes(d.slice(2).join(`/`)))):u[0]===`api`?f=[`api`,`migrations`].includes(d[0])||d[0]===`domain`&&d[1]!==`shared`&&d[1]!==(u.length>2?u[1]:T(r).replace(/\.[cm]?[jt]s$/,``)):u[0]===`application`?f=[`api`,`migrations`].includes(d[0]):[`relations.ts`,`querying.ts`].includes(r)&&d[0]===`domain`&&(f=!(r===`relations.ts`?[`schema`,`table`]:[`queries`,`contracts`]).includes(d.slice(2).join(`/`))&&(r!==`relations.ts`||l!==`domain/table`)),d[0]===`migrations`&&u[0]!==`migrations`&&(f=!0),[`api`,`domain`,`application`].includes(u[0])&&d.length>1&&![`api`,`domain`,`application`,`_generated`,`components`,`migrations`].includes(d[0])&&(f=!0),f&&e.report({node:t,messageId:`boundary`})})}},"public-functions-in-api":{meta:b(`Expose authenticated public functions only through api/.`,{public:`Declare public auth*/role*/admin* functions in convex/api/<module>.ts.`}),create(e){return c(e)?.startsWith(`api/`)?{}:{CallExpression(t){let n=m(e,t.callee);t.callee.type!==`CallExpression`&&n&&g(e,n.source)&&/^(auth|role|admin)(Query|Mutation|Action)$/.test(n.name)&&e.report({node:t,messageId:`public`})}}}},"thin-api-adapters":{meta:b(`Keep business decisions and writes in domain executors.`,{adapter:`Move business branches, private helpers, and database writes into the owning domain executor.`}),create(e){return c(e)?.startsWith(`api/`)?{IfStatement(t){e.report({node:t,messageId:`adapter`})},SwitchStatement(t){e.report({node:t,messageId:`adapter`})},ConditionalExpression(t){e.report({node:t,messageId:`adapter`})},Program(t){let n=p(t);for(let r of t.body)if(r.type===`FunctionDeclaration`&&r.id&&!n.has(r.id.name)&&e.report({node:r,messageId:`adapter`}),r.type===`VariableDeclaration`)for(let t of r.declarations)t.id.type===`Identifier`&&!n.has(t.id.name)&&[`ArrowFunctionExpression`,`FunctionExpression`].includes(t.init?.type??``)&&e.report({node:t,messageId:`adapter`})},CallExpression(t){h(t)&&e.report({node:t,messageId:`adapter`})}}:{}}},"no-inline-enums":{meta:b(`Keep vocabularies in named constants.ts tuples.`,{vocabulary:`Define a named readonly tuple in constants.ts and pass it to k.enum().`}),create(e){return{CallExpression(t){let n=t.arguments[0];for(;n?.type===`TSAsExpression`||n?.type===`TSSatisfiesExpression`;)n=n.expression;v(e,t)===`enum`&&n?.type===`ArrayExpression`&&e.report({node:t,messageId:`vocabulary`})}}}},"no-unbounded-reads":{meta:b(`Bound collection reads through include or pagination.`,{bounded:`Use include(...).execute(limit) or bounded pagination; do not collect() or resolve() an unbounded query.`,order:`Apply eligibility filters in the indexed query before take(), execute(), or paginate(); filtering a bounded result can omit eligible rows. Do not move the predicate automatically.`}),create(e){return{CallExpression(t){if(t.callee.type!==`MemberExpression`)return;let n=x(t.callee),r=S(e,t.callee.object);n===`filter`&&r===`bounded`&&e.report({node:t,messageId:`order`}),(n===`collect`&&(r===`stream`||r===`relationship`)||n===`resolve`&&r===`stream`)&&e.report({node:t,messageId:`bounded`})}}}},"no-manual-id-projection":{meta:b(`Use the table DTO boundary to project public IDs.`,{projection:`Use toPublicDto(row, true) to include _id; do not add IDs manually after a table DTO parse or projection.`}),create(e){return{ObjectExpression(t){if(t.properties.some(t=>t.type===`SpreadElement`&&S(e,t.argument)===`dto`))for(let n of t.properties)n.type===`Property`&&[`id`,`_id`].includes((n.computed?w(n.key):f(n.key))??``)&&e.report({node:n,messageId:`projection`})},AssignmentExpression(t){t.left.type===`MemberExpression`&&[`id`,`_id`].includes(x(t.left)??``)&&S(e,t.left.object)===`dto`&&e.report({node:t,messageId:`projection`})}}}},"no-copied-pagination":{meta:b(`Use native or table pagination schemas instead of copying their shape.`,{pagination:`Use the native paginationOptsValidator (or paginated(table.dto())) for native pagination, or table.paginationOpts(selection) for table queries; do not copy pagination fields.`}),create(e){return{CallExpression(t){let n=m(e,t.callee);if(!(v(e,t)===`object`||n?.name===`object`&&n.source===`convex/values`))return;let r=t.arguments[0],i=r&&(y(e,r)??r);if(i?.type!==`ObjectExpression`)return;let a=new Set(i.properties.flatMap(e=>e.type===`Property`?[e.computed?w(e.key):f(e.key)]:[]));(a.has(`numItems`)&&a.has(`cursor`)||[`page`,`isDone`,`continueCursor`].every(e=>a.has(e)))&&e.report({node:t,messageId:`pagination`})}}}},"no-manual-timestamps":{meta:b(`Let timestamps triggers own createdAt and updatedAt.`,{timestamp:`Remove {{field}} from this write; register the timestamps trigger instead.`}),create(e){return{CallExpression(t){if(!h(t))return;let n=t.arguments.at(-1);if(n?.type===`ObjectExpression`)for(let t of n.properties){if(t.type!==`Property`)continue;let n=t.computed?w(t.key):f(t.key);(n===`createdAt`||n===`updatedAt`)&&e.report({node:t,messageId:`timestamp`,data:{field:n}})}}}}},"component-boundaries":{meta:b(`Keep portable components isolated and consume their client facades.`,{boundary:`Components may import only their own files and npm dependencies; inject host policy through the client API.`,facade:`Import a component through its client.ts facade, not its private implementation.`}),create(e){let n=u(e,e.filename),r=t(!1);return C(e,(t,a)=>{a.startsWith(`.`)||/^cvx-kit\/components\/[^/]+\//.test(a)&&!/^cvx-kit\/components\/[^/]+\/convex\.config(?:\.js)?$/.test(a)&&e.report({node:t,messageId:`facade`});let o=i(r,e.filename,a);o&&!o.split(O).includes(`node_modules`)&&(n&&(D(n,o).startsWith(`..${O}`)||o===E(n))?e.report({node:t,messageId:`boundary`}):!n&&u(e,o)&&!/^client(?:\.[cm]?[jt]s)?$/.test(T(o))&&!(c(e)===`convex.config.ts`&&/^convex\.config(?:\.[cm]?[jt]s)?$/.test(T(o)))&&e.report({node:t,messageId:`facade`}))})}},"no-component-env":{meta:b(`Pass environment configuration into portable components.`,{env:`Portable components must receive configuration through arguments; do not read process.env.`}),create(e){if(!u(e,e.filename))return{};function t(t){if(t.type!==`Identifier`)return!1;let n=l(e,t);return t.name===`process`&&!n?.defs.length||n?.defs.some(e=>e.type===`ImportBinding`&&e.parent?.type===`ImportDeclaration`&&[`node:process`,`process`].includes(e.parent.source.value)&&[`ImportDefaultSpecifier`,`ImportNamespaceSpecifier`].includes(e.node.type))}return{ImportDeclaration(t){if([`node:process`,`process`].includes(t.source.value))for(let n of t.specifiers)n.type===`ImportSpecifier`&&f(n.imported)===`env`&&e.report({node:n,messageId:`env`})},MemberExpression(n){if(x(n)!==`env`)return;let r=n.object,i=r.type===`MemberExpression`&&x(r)===`process`&&r.object.type===`Identifier`&&r.object.name===`globalThis`&&!l(e,r.object)?.defs.length;(t(r)||i)&&e.report({node:n,messageId:`env`})},VariableDeclarator(n){if(n.init&&t(n.init)&&n.id.type===`ObjectPattern`)for(let t of n.id.properties)t.type===`Property`&&(t.computed?w(t.key):f(t.key))===`env`&&e.report({node:t,messageId:`env`})}}}},"schema-file-boundaries":{meta:b(`Keep storage shapes and indexes in their documented owners.`,{schema:`{{builder}} belongs in {{file}}.`}),create(e){return{CallExpression(t){let n=m(e,t.callee),r=c(e);if(!r)return;let i=null;n?.source===`convex/server`&&(n.name===`defineSchema`&&r!==`schema.ts`&&!(u(e,e.filename)&&T(r)===`schema.ts`)&&(i=`the root schema.ts (or a component schema.ts)`),n.name===`defineTable`&&!(u(e,e.filename)&&[`schema.ts`,`table.ts`].includes(T(r)))&&(i=`a component schema.ts/table.ts; host tables use kTable in domain/<module>/schema.ts`)),n&&s.includes(n.source)&&[`kTable`,`tenantTable`,`kVariantTable`].includes(n.name)&&!/^domain\/[^/]+\/schema\.ts$/.test(r)&&!(u(e,e.filename)&&[`schema.ts`,`table.ts`].includes(T(r)))&&(i=`domain/<module>/schema.ts or a component schema.ts/table.ts`),i&&e.report({node:t,messageId:`schema`,data:{builder:n?.name??`table`,file:i}}),t.callee.type===`MemberExpression`&&[`index`,`searchIndex`,`vectorIndex`].includes(x(t.callee)??``)&&_(t.callee.object)&&!(u(e,e.filename)?T(r)===`table.ts`:/^domain\/[^/]+\/table\.ts$/.test(r))&&e.report({node:t,messageId:`schema`,data:{builder:`Table indexes`,file:u(e,e.filename)?`a component table.ts`:`domain/<module>/table.ts`}})}}}},"no-internal-reexports":{meta:b(`Import from owning modules directly; consumer apps have no barrels.`,{reexport:`Import from the owning file directly; do not re-export imports inside convex/.`}),create(e){function t(t){if(t.source)e.report({node:t,messageId:`reexport`});else for(let n of t.type===`ExportNamedDeclaration`?t.specifiers:[])l(e,n.local)?.defs.some(e=>e.type===`ImportBinding`)&&e.report({node:n,messageId:`reexport`})}return{ExportNamedDeclaration:t,ExportAllDeclaration:t,ExportDefaultDeclaration(t){t.declaration.type===`Identifier`&&l(e,t.declaration)?.defs.some(e=>e.type===`ImportBinding`)&&e.report({node:t,messageId:`reexport`})}}}},"public-api-first":{meta:b(`Place private helper implementations after the exported API.`,{order:`Move this private helper below the exported API so the file reads from public purpose to implementation.`}),create(e){return{Program(t){let n=p(t),r=t.body.findLastIndex(e=>e.type.startsWith(`Export`));for(let i of t.body.slice(0,r<0?0:r))i.type===`FunctionDeclaration`&&i.id&&!n.has(i.id.name)&&e.report({node:i,messageId:`order`})}}}},"named-private-helpers":{meta:b(`Use named declarations for top-level private helper functions.`,{helper:`Declare this private helper with function name(...) at the bottom of the file.`}),create(e){return{Program(t){let n=p(t);for(let r of t.body)if(r.type===`VariableDeclaration`)for(let t of r.declarations)t.id.type!==`Identifier`||n.has(t.id.name)||t.init?.type!==`ArrowFunctionExpression`&&t.init?.type!==`FunctionExpression`||e.report({node:t,messageId:`helper`})}}}}}),j={meta:{name:`cvx`},rules:A};function M(e){let t={...e},n=Object.keys(e);for(let r of n){let n={convexDir:{type:`string`,minLength:1},componentDirs:{type:`array`,items:{type:`string`,minLength:1}}},i=e[r];t[r]={meta:{...i.meta,schema:[{type:`object`,properties:r===`domain-import-boundaries`?{...n,domainPublicFiles:{type:`object`,additionalProperties:{type:`array`,items:{type:`string`,minLength:1}}}}:n,additionalProperties:!1}]},create(e){let t=c(e);return!t||/(?:^|\/)(?:_generated|__tests__)(?:\/|$)/.test(t)||/\.(?:test|spec)\.[cm]?[jt]s$/.test(t)?{}:i.create(e)}}}return t}export{k as checkArchitecture,j as default,A as rules};
2
+ //# sourceMappingURL=oxlint.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oxlint.mjs","names":["checkArchitecture","registry","options","forceRegistry","inspectArchitecture","rules","scopeRules","ownershipRules","file","appFile","context","narrowRootDeclaration","reservedDomainFiles","metadata","owner","componentRoot","seen","check","ref","imported","node","relative","sep","resolver","createResolver","importedSource","target","resolveImport","localTarget","source","specifier","name","exportName","consumerOptions","sourceVisitors","resolved","from","to","forbidden","domainPublicFiles","basename","isFunctionsImport","exported","exportedNames","statement","declaration","isDbWrite","values","kFactory","propertyName","origin","readProvenance","property","staticString","argument","fieldsNode","localInitializer","fields","field","data","dirname","isProcess","variable","binding","def","object","globalProcess","expected","TABLE_SOURCES","isTableChain","exports","lastExport","plugin","scoped","names","commonProperties","rule"],"sources":["../src/oxlint.ts"],"sourcesContent":["import { forceRegistry } from './modules/contracts/lazy'\nimport { basename, dirname, relative, sep } from 'node:path'\nimport type { CreateRule, ESTree, Plugin, Rule } from '@oxlint/plugins'\nimport {\n\tinspectArchitecture,\n\tcreateResolver,\n\tresolveImport,\n\tnarrowRootDeclaration,\n\ttype ArchitectureOptions,\n\ttype ArchitectureDiagnostic,\n} from './oxlint/architecture'\nimport { reservedDomainFiles } from './oxlint/reserved-files'\nimport { ownershipRules, type OwnershipRuleName } from './oxlint/ownership'\nimport {\n\tappFile,\n\tconsumerOptions,\n\timported,\n\tsourceVisitors,\n\tisFunctionsImport,\n\tisTableChain,\n\tisDbWrite,\n\tkFactory,\n\tTABLE_SOURCES,\n\tmetadata,\n\tcomponentRoot,\n\tstaticString,\n\tpropertyName,\n\tbinding,\n\treadProvenance,\n\tlocalInitializer,\n\texportedNames,\n\texportName,\n} from './oxlint/ast'\n\nexport type { ArchitectureOptions, ArchitectureDiagnostic } from './oxlint/architecture'\n\nexport function checkArchitecture(options: ArchitectureOptions = {}): ArchitectureDiagnostic[] {\n\tfor (const registry of options.registries ?? []) forceRegistry(registry)\n\treturn inspectArchitecture(options)\n}\n\nexport type RuleName =\n\t| OwnershipRuleName\n\t| 'component-boundaries'\n\t| 'no-component-env'\n\t| 'schema-file-boundaries'\n\t| 'no-internal-reexports'\n\t| 'public-api-first'\n\t| 'named-private-helpers'\n\t| 'no-raw-builders'\n\t| 'no-handwritten-references'\n\t| 'domain-import-boundaries'\n\t| 'public-functions-in-api'\n\t| 'thin-api-adapters'\n\t| 'no-inline-enums'\n\t| 'no-unbounded-reads'\n\t| 'no-manual-timestamps'\n\t| 'reserved-domain-file-anatomy'\n\t| 'root-facade-ownership'\n\t| 'no-manual-id-projection'\n\t| 'no-copied-pagination'\n\n/** Consumer application rules derived from docs/conventions.md. */\nconst applicationRules: Record<RuleName, CreateRule> = {\n\t...ownershipRules,\n\t'root-wiring-only': {\n\t\t...ownershipRules['root-wiring-only'],\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context) ?? ''\n\t\t\tif (['relations.ts', 'querying.ts'].includes(file)) {\n\t\t\t\tif (narrowRootDeclaration(file, context.sourceCode.text)) return {}\n\t\t\t\treturn {\n\t\t\t\t\tProgram(node) {\n\t\t\t\t\t\tcontext.report({\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tmessageId: 'ownership',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\treason: `${file} must export one kit factory declaration and contain only declarative configuration`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ownershipRules['root-wiring-only'].create(context)\n\t\t},\n\t},\n\t'reserved-domain-file-anatomy': reservedDomainFiles,\n\t'root-facade-ownership': {\n\t\tmeta: metadata('Configure shared kit infrastructure once in its root facade.', {\n\t\t\tfacade: 'Configure {{name}} once in convex/{{file}}; import that facade elsewhere.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst owner = componentRoot(context, context.filename)\n\t\t\tconst seen = new Set<string>()\n\t\t\tfunction check(node: ESTree.CallExpression | ESTree.NewExpression) {\n\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\tif (!ref) return\n\t\t\t\tlet file: string | null = null\n\t\t\t\tif (\n\t\t\t\t\t['cvx-kit', 'cvx-kit/querying'].includes(ref.source) &&\n\t\t\t\t\tref.name === 'createQueryEngine'\n\t\t\t\t)\n\t\t\t\t\tfile = 'querying.ts'\n\t\t\t\tif (['cvx-kit', 'cvx-kit/relations'].includes(ref.source) && ref.name === 'defineRelations')\n\t\t\t\t\tfile = 'relations.ts'\n\t\t\t\tif (['cvx-kit', 'cvx-kit/auth'].includes(ref.source) && ref.name === 'createAuthFunctions')\n\t\t\t\t\tfile = 'functions.ts'\n\t\t\t\tif (['cvx-kit', 'cvx-kit/triggers'].includes(ref.source) && ref.name === 'createTriggers')\n\t\t\t\t\tfile = 'triggers.ts'\n\t\t\t\tif (\n\t\t\t\t\t['cvx-kit', 'cvx-kit/components/foundation'].includes(ref.source) &&\n\t\t\t\t\tref.name === 'Foundation'\n\t\t\t\t)\n\t\t\t\t\tfile = 'foundation.ts'\n\t\t\t\tif (\n\t\t\t\t\t(ref.source === 'cvx-kit/effect' && ref.name === 'createEffectFoundation') ||\n\t\t\t\t\t(ref.source === 'cvx-kit' && ref.name === 'createFoundation')\n\t\t\t\t)\n\t\t\t\t\tfile = 'foundation.ts'\n\t\t\t\tif (!file) return\n\t\t\t\tif (\n\t\t\t\t\t(owner ? relative(owner, context.filename).split(sep).join('/') : appFile(context)) !==\n\t\t\t\t\t\tfile ||\n\t\t\t\t\tseen.has(ref.name)\n\t\t\t\t)\n\t\t\t\t\tcontext.report({ node, messageId: 'facade', data: { name: ref.name, file } })\n\t\t\t\tseen.add(ref.name)\n\t\t\t}\n\t\t\treturn { CallExpression: check, NewExpression: check }\n\t\t},\n\t},\n\t'no-raw-builders': {\n\t\tmeta: metadata('Build host functions through the auth-aware root constructors.', {\n\t\t\tbuilder:\n\t\t\t\t'Import raw builders only in convex/functions.ts; use auth*/role*/admin* or system* elsewhere.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst owner = componentRoot(context, context.filename)\n\t\t\tif (\n\t\t\t\t(owner ? relative(owner, context.filename).split(sep).join('/') : appFile(context)) ===\n\t\t\t\t'functions.ts'\n\t\t\t)\n\t\t\t\treturn {}\n\t\t\tconst resolver = createResolver()\n\t\t\treturn {\n\t\t\t\tImportDeclaration(node) {\n\t\t\t\t\tif (node.importKind === 'type') return\n\t\t\t\t\tconst importedSource = node.source.value\n\t\t\t\t\tconst target = resolveImport(resolver, context.filename, importedSource)\n\t\t\t\t\tconst localTarget = target\n\t\t\t\t\t\t? owner\n\t\t\t\t\t\t\t? relative(owner, target).split(sep).join('/')\n\t\t\t\t\t\t\t: appFile(context, target)\n\t\t\t\t\t\t: null\n\t\t\t\t\tconst source = localTarget?.startsWith('_generated/') ? localTarget : importedSource\n\t\t\t\t\tif (\n\t\t\t\t\t\t!/(?:^|\\/)_generated\\/server(?:\\.[cm]?[jt]s)?$/.test(source) &&\n\t\t\t\t\t\tsource !== 'convex/server'\n\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\tfor (const specifier of node.specifiers) {\n\t\t\t\t\t\tif (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type') continue\n\t\t\t\t\t\tconst name =\n\t\t\t\t\t\t\tspecifier.type === 'ImportSpecifier' ? exportName(specifier.imported) : null\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t(name === null && source !== 'convex/server') ||\n\t\t\t\t\t\t\t(name &&\n\t\t\t\t\t\t\t\t/^(?:internal)?(?:Query|Mutation|Action)(?:Generic)?$|^(?:query|mutation|action)(?:Generic)?$/.test(\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcontext.report({ node: specifier, messageId: 'builder' })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tref?.source === 'convex/server' &&\n\t\t\t\t\t\t/^(?:internal)?(?:Query|Mutation|Action)Generic$|^(?:query|mutation|action)Generic$/.test(\n\t\t\t\t\t\t\tref.name,\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression'\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontext.report({ node, messageId: 'builder' })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-handwritten-references': {\n\t\tmeta: metadata('Use generated api/internal references.', {\n\t\t\treference: 'Use generated api/internal references instead of makeFunctionReference.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (ref?.source === 'convex/server' && ref.name === 'makeFunctionReference')\n\t\t\t\t\t\tcontext.report({ node, messageId: 'reference' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'domain-import-boundaries': {\n\t\tmeta: metadata('Keep api, application, domain, and shared dependencies directed.', {\n\t\t\tboundary:\n\t\t\t\t'Follow api → application/domain → shared; sibling modules expose only rules.ts and queries.ts.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst { domainPublicFiles } = consumerOptions.parse(context.options[0] ?? {})\n\t\t\tconst file = appFile(context)\n\t\t\tif (componentRoot(context, context.filename)) return {}\n\t\t\tconst resolver = createResolver()\n\t\t\treturn sourceVisitors(context, (node, source) => {\n\t\t\t\tif (!file) return\n\t\t\t\tconst resolved = resolveImport(resolver, context.filename, source)\n\t\t\t\tif (!resolved) return\n\t\t\t\tconst target = appFile(context, resolved)?.replace(/\\.[cm]?[jt]s$/, '')\n\t\t\t\tif (!target) {\n\t\t\t\t\tif (!resolved.split(sep).includes('node_modules'))\n\t\t\t\t\t\tcontext.report({ node, messageId: 'boundary' })\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst from = file.split('/')\n\t\t\t\tconst to = target.split('/')\n\t\t\t\tlet forbidden = false\n\t\t\t\tif (from[0] === 'domain') {\n\t\t\t\t\tforbidden = ['api', 'application', 'migrations'].includes(to[0])\n\t\t\t\t\tif (\n\t\t\t\t\t\tto[0] === 'domain' &&\n\t\t\t\t\t\tfrom[1] !== to[1] &&\n\t\t\t\t\t\tto[1] !== 'shared' &&\n\t\t\t\t\t\tfrom[1] !== 'table.ts'\n\t\t\t\t\t) {\n\t\t\t\t\t\tforbidden =\n\t\t\t\t\t\t\tfrom[1] === 'shared' ||\n\t\t\t\t\t\t\t(!['rules', 'queries', 'contracts'].includes(to.slice(2).join('/')) &&\n\t\t\t\t\t\t\t\t!domainPublicFiles[to[1]]?.includes(to.slice(2).join('/')))\n\t\t\t\t\t}\n\t\t\t\t} else if (from[0] === 'api') {\n\t\t\t\t\tforbidden =\n\t\t\t\t\t\t['api', 'migrations'].includes(to[0]) ||\n\t\t\t\t\t\t(to[0] === 'domain' &&\n\t\t\t\t\t\t\tto[1] !== 'shared' &&\n\t\t\t\t\t\t\tto[1] !== (from.length > 2 ? from[1] : basename(file).replace(/\\.[cm]?[jt]s$/, '')))\n\t\t\t\t} else if (from[0] === 'application') forbidden = ['api', 'migrations'].includes(to[0])\n\t\t\t\telse if (['relations.ts', 'querying.ts'].includes(file) && to[0] === 'domain') {\n\t\t\t\t\tconst allowed = file === 'relations.ts' ? ['schema', 'table'] : ['queries', 'contracts']\n\t\t\t\t\tforbidden =\n\t\t\t\t\t\t!allowed.includes(to.slice(2).join('/')) &&\n\t\t\t\t\t\t!(file === 'relations.ts' && target === 'domain/table')\n\t\t\t\t}\n\t\t\t\tif (to[0] === 'migrations' && from[0] !== 'migrations') forbidden = true\n\t\t\t\tif (\n\t\t\t\t\t['api', 'domain', 'application'].includes(from[0]) &&\n\t\t\t\t\tto.length > 1 &&\n\t\t\t\t\t!['api', 'domain', 'application', '_generated', 'components', 'migrations'].includes(\n\t\t\t\t\t\tto[0],\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\tforbidden = true\n\t\t\t\tif (forbidden) context.report({ node, messageId: 'boundary' })\n\t\t\t})\n\t\t},\n\t},\n\t'public-functions-in-api': {\n\t\tmeta: metadata('Expose authenticated public functions only through api/.', {\n\t\t\tpublic: 'Declare public auth*/role*/admin* functions in convex/api/<module>.ts.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tif (appFile(context)?.startsWith('api/')) return {}\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.callee.type !== 'CallExpression' &&\n\t\t\t\t\t\tref &&\n\t\t\t\t\t\tisFunctionsImport(context, ref.source) &&\n\t\t\t\t\t\t/^(auth|role|admin)(Query|Mutation|Action)$/.test(ref.name)\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'public' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'thin-api-adapters': {\n\t\tmeta: metadata('Keep business decisions and writes in domain executors.', {\n\t\t\tadapter:\n\t\t\t\t'Move business branches, private helpers, and database writes into the owning domain executor.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tif (!appFile(context)?.startsWith('api/')) return {}\n\t\t\treturn {\n\t\t\t\tIfStatement(node) {\n\t\t\t\t\tcontext.report({ node, messageId: 'adapter' })\n\t\t\t\t},\n\t\t\t\tSwitchStatement(node) {\n\t\t\t\t\tcontext.report({ node, messageId: 'adapter' })\n\t\t\t\t},\n\t\t\t\tConditionalExpression(node) {\n\t\t\t\t\tcontext.report({ node, messageId: 'adapter' })\n\t\t\t\t},\n\t\t\t\tProgram(node) {\n\t\t\t\t\tconst exported = exportedNames(node)\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' &&\n\t\t\t\t\t\t\tstatement.id &&\n\t\t\t\t\t\t\t!exported.has(statement.id.name)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tcontext.report({ node: statement, messageId: 'adapter' })\n\t\t\t\t\t\tif (statement.type === 'VariableDeclaration')\n\t\t\t\t\t\t\tfor (const declaration of statement.declarations) {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tdeclaration.id.type === 'Identifier' &&\n\t\t\t\t\t\t\t\t\t!exported.has(declaration.id.name) &&\n\t\t\t\t\t\t\t\t\t['ArrowFunctionExpression', 'FunctionExpression'].includes(\n\t\t\t\t\t\t\t\t\t\tdeclaration.init?.type ?? '',\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontext.report({ node: declaration, messageId: 'adapter' })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (isDbWrite(node)) context.report({ node, messageId: 'adapter' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-inline-enums': {\n\t\tmeta: metadata('Keep vocabularies in named constants.ts tuples.', {\n\t\t\tvocabulary: 'Define a named readonly tuple in constants.ts and pass it to k.enum().',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tlet values = node.arguments[0]\n\t\t\t\t\twhile (values?.type === 'TSAsExpression' || values?.type === 'TSSatisfiesExpression')\n\t\t\t\t\t\tvalues = values.expression\n\t\t\t\t\tif (kFactory(context, node) === 'enum' && values?.type === 'ArrayExpression')\n\t\t\t\t\t\tcontext.report({ node, messageId: 'vocabulary' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-unbounded-reads': {\n\t\tmeta: metadata('Bound collection reads through include or pagination.', {\n\t\t\tbounded:\n\t\t\t\t'Use include(...).execute(limit) or bounded pagination; do not collect() or resolve() an unbounded query.',\n\t\t\torder:\n\t\t\t\t'Apply eligibility filters in the indexed query before take(), execute(), or paginate(); filtering a bounded result can omit eligible rows. Do not move the predicate automatically.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (node.callee.type !== 'MemberExpression') return\n\t\t\t\t\tconst name = propertyName(node.callee)\n\t\t\t\t\tconst origin = readProvenance(context, node.callee.object)\n\t\t\t\t\tif (name === 'filter' && origin === 'bounded')\n\t\t\t\t\t\tcontext.report({ node, messageId: 'order' })\n\t\t\t\t\tif (\n\t\t\t\t\t\t(name === 'collect' && (origin === 'stream' || origin === 'relationship')) ||\n\t\t\t\t\t\t(name === 'resolve' && origin === 'stream')\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'bounded' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-manual-id-projection': {\n\t\tmeta: metadata('Use the table DTO boundary to project public IDs.', {\n\t\t\tprojection:\n\t\t\t\t'Use toPublicDto(row, true) to include _id; do not add IDs manually after a table DTO parse or projection.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tObjectExpression(node) {\n\t\t\t\t\tconst dto = node.properties.some(\n\t\t\t\t\t\t(property) =>\n\t\t\t\t\t\t\tproperty.type === 'SpreadElement' &&\n\t\t\t\t\t\t\treadProvenance(context, property.argument) === 'dto',\n\t\t\t\t\t)\n\t\t\t\t\tif (!dto) return\n\t\t\t\t\tfor (const property of node.properties) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tproperty.type === 'Property' &&\n\t\t\t\t\t\t\t['id', '_id'].includes(\n\t\t\t\t\t\t\t\t(property.computed ? staticString(property.key) : exportName(property.key)) ?? '',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tcontext.report({ node: property, messageId: 'projection' })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tAssignmentExpression(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.left.type === 'MemberExpression' &&\n\t\t\t\t\t\t['id', '_id'].includes(propertyName(node.left) ?? '') &&\n\t\t\t\t\t\treadProvenance(context, node.left.object) === 'dto'\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'projection' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-copied-pagination': {\n\t\tmeta: metadata('Use native or table pagination schemas instead of copying their shape.', {\n\t\t\tpagination:\n\t\t\t\t'Use the native paginationOptsValidator (or paginated(table.dto())) for native pagination, or table.paginationOpts(selection) for table queries; do not copy pagination fields.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tconst isObject =\n\t\t\t\t\t\tkFactory(context, node) === 'object' ||\n\t\t\t\t\t\t(ref?.name === 'object' && ref.source === 'convex/values')\n\t\t\t\t\tif (!isObject) return\n\t\t\t\t\tconst argument = node.arguments[0]\n\t\t\t\t\tconst fieldsNode = argument && (localInitializer(context, argument) ?? argument)\n\t\t\t\t\tif (fieldsNode?.type !== 'ObjectExpression') return\n\t\t\t\t\tconst fields = new Set(\n\t\t\t\t\t\tfieldsNode.properties.flatMap((property) =>\n\t\t\t\t\t\t\tproperty.type === 'Property'\n\t\t\t\t\t\t\t\t? [property.computed ? staticString(property.key) : exportName(property.key)]\n\t\t\t\t\t\t\t\t: [],\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\tif (\n\t\t\t\t\t\t(fields.has('numItems') && fields.has('cursor')) ||\n\t\t\t\t\t\t['page', 'isDone', 'continueCursor'].every((field) => fields.has(field))\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'pagination' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-manual-timestamps': {\n\t\tmeta: metadata('Let timestamps triggers own createdAt and updatedAt.', {\n\t\t\ttimestamp: 'Remove {{field}} from this write; register the timestamps trigger instead.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (!isDbWrite(node)) return\n\t\t\t\t\tconst data = node.arguments.at(-1)\n\t\t\t\t\tif (data?.type !== 'ObjectExpression') return\n\t\t\t\t\tfor (const property of data.properties) {\n\t\t\t\t\t\tif (property.type !== 'Property') continue\n\t\t\t\t\t\tconst field = property.computed ? staticString(property.key) : exportName(property.key)\n\t\t\t\t\t\tif (field === 'createdAt' || field === 'updatedAt')\n\t\t\t\t\t\t\tcontext.report({ node: property, messageId: 'timestamp', data: { field } })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'component-boundaries': {\n\t\tmeta: metadata('Keep portable components isolated and consume their client facades.', {\n\t\t\tboundary:\n\t\t\t\t'Components may import only their own files and npm dependencies; inject host policy through the client API.',\n\t\t\tfacade: 'Import a component through its client.ts facade, not its private implementation.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst owner = componentRoot(context, context.filename)\n\t\t\tconst resolver = createResolver(false)\n\n\t\t\treturn sourceVisitors(context, (node, specifier) => {\n\t\t\t\tif (!specifier.startsWith('.')) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t/^cvx-kit\\/components\\/[^/]+\\//.test(specifier) &&\n\t\t\t\t\t\t!/^cvx-kit\\/components\\/[^/]+\\/convex\\.config(?:\\.js)?$/.test(specifier)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontext.report({ node, messageId: 'facade' })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst target = resolveImport(resolver, context.filename, specifier)\n\t\t\t\tif (!target || target.split(sep).includes('node_modules')) return\n\t\t\t\tif (\n\t\t\t\t\towner &&\n\t\t\t\t\t(relative(owner, target).startsWith(`..${sep}`) || target === dirname(owner))\n\t\t\t\t) {\n\t\t\t\t\tcontext.report({ node, messageId: 'boundary' })\n\t\t\t\t} else if (\n\t\t\t\t\t!owner &&\n\t\t\t\t\tcomponentRoot(context, target) &&\n\t\t\t\t\t!/^client(?:\\.[cm]?[jt]s)?$/.test(basename(target)) &&\n\t\t\t\t\t!(\n\t\t\t\t\t\tappFile(context) === 'convex.config.ts' &&\n\t\t\t\t\t\t/^convex\\.config(?:\\.[cm]?[jt]s)?$/.test(basename(target))\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tcontext.report({ node, messageId: 'facade' })\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t},\n\t'no-component-env': {\n\t\tmeta: metadata('Pass environment configuration into portable components.', {\n\t\t\tenv: 'Portable components must receive configuration through arguments; do not read process.env.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tif (!componentRoot(context, context.filename)) return {}\n\t\t\tfunction isProcess(node: ESTree.Node) {\n\t\t\t\tif (node.type !== 'Identifier') return false\n\t\t\t\tconst variable = binding(context, node)\n\t\t\t\tif (node.name === 'process' && !variable?.defs.length) return true\n\t\t\t\treturn variable?.defs.some(\n\t\t\t\t\t(def) =>\n\t\t\t\t\t\tdef.type === 'ImportBinding' &&\n\t\t\t\t\t\tdef.parent?.type === 'ImportDeclaration' &&\n\t\t\t\t\t\t['node:process', 'process'].includes(def.parent.source.value) &&\n\t\t\t\t\t\t['ImportDefaultSpecifier', 'ImportNamespaceSpecifier'].includes(def.node.type),\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tImportDeclaration(node) {\n\t\t\t\t\tif (['node:process', 'process'].includes(node.source.value)) {\n\t\t\t\t\t\tfor (const specifier of node.specifiers) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tspecifier.type === 'ImportSpecifier' &&\n\t\t\t\t\t\t\t\texportName(specifier.imported) === 'env'\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontext.report({ node: specifier, messageId: 'env' })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tMemberExpression(node) {\n\t\t\t\t\tif (propertyName(node) !== 'env') return\n\t\t\t\t\tconst object = node.object\n\t\t\t\t\tconst globalProcess =\n\t\t\t\t\t\tobject.type === 'MemberExpression' &&\n\t\t\t\t\t\tpropertyName(object) === 'process' &&\n\t\t\t\t\t\tobject.object.type === 'Identifier' &&\n\t\t\t\t\t\tobject.object.name === 'globalThis' &&\n\t\t\t\t\t\t!binding(context, object.object)?.defs.length\n\t\t\t\t\tif (isProcess(object) || globalProcess) context.report({ node, messageId: 'env' })\n\t\t\t\t},\n\t\t\t\tVariableDeclarator(node) {\n\t\t\t\t\tif (node.init && isProcess(node.init) && node.id.type === 'ObjectPattern') {\n\t\t\t\t\t\tfor (const property of node.id.properties) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tproperty.type === 'Property' &&\n\t\t\t\t\t\t\t\t(property.computed ? staticString(property.key) : exportName(property.key)) ===\n\t\t\t\t\t\t\t\t\t'env'\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontext.report({ node: property, messageId: 'env' })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'schema-file-boundaries': {\n\t\tmeta: metadata('Keep storage shapes and indexes in their documented owners.', {\n\t\t\tschema: '{{builder}} belongs in {{file}}.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tconst file = appFile(context)\n\t\t\t\t\tif (!file) return\n\t\t\t\t\tlet expected: string | null = null\n\t\t\t\t\tif (ref?.source === 'convex/server') {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tref.name === 'defineSchema' &&\n\t\t\t\t\t\t\tfile !== 'schema.ts' &&\n\t\t\t\t\t\t\t!(componentRoot(context, context.filename) && basename(file) === 'schema.ts')\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\texpected = 'the root schema.ts (or a component schema.ts)'\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tref.name === 'defineTable' &&\n\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\tcomponentRoot(context, context.filename) &&\n\t\t\t\t\t\t\t\t['schema.ts', 'table.ts'].includes(basename(file))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\texpected =\n\t\t\t\t\t\t\t\t'a component schema.ts/table.ts; host tables use kTable in domain/<module>/schema.ts'\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tref &&\n\t\t\t\t\t\tTABLE_SOURCES.includes(ref.source) &&\n\t\t\t\t\t\t['kTable', 'tenantTable', 'kVariantTable'].includes(ref.name) &&\n\t\t\t\t\t\t!/^domain\\/[^/]+\\/schema\\.ts$/.test(file) &&\n\t\t\t\t\t\t!(\n\t\t\t\t\t\t\tcomponentRoot(context, context.filename) &&\n\t\t\t\t\t\t\t['schema.ts', 'table.ts'].includes(basename(file))\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\texpected = 'domain/<module>/schema.ts or a component schema.ts/table.ts'\n\t\t\t\t\tif (expected)\n\t\t\t\t\t\tcontext.report({\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tmessageId: 'schema',\n\t\t\t\t\t\t\tdata: { builder: ref?.name ?? 'table', file: expected },\n\t\t\t\t\t\t})\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression' &&\n\t\t\t\t\t\t['index', 'searchIndex', 'vectorIndex'].includes(propertyName(node.callee) ?? '') &&\n\t\t\t\t\t\tisTableChain(node.callee.object) &&\n\t\t\t\t\t\t!(componentRoot(context, context.filename)\n\t\t\t\t\t\t\t? basename(file) === 'table.ts'\n\t\t\t\t\t\t\t: /^domain\\/[^/]+\\/table\\.ts$/.test(file))\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontext.report({\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tmessageId: 'schema',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tbuilder: 'Table indexes',\n\t\t\t\t\t\t\t\tfile: componentRoot(context, context.filename)\n\t\t\t\t\t\t\t\t\t? 'a component table.ts'\n\t\t\t\t\t\t\t\t\t: 'domain/<module>/table.ts',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'no-internal-reexports': {\n\t\tmeta: metadata('Import from owning modules directly; consumer apps have no barrels.', {\n\t\t\treexport: 'Import from the owning file directly; do not re-export imports inside convex/.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tfunction check(node: ESTree.ExportNamedDeclaration | ESTree.ExportAllDeclaration) {\n\t\t\t\tif (node.source) {\n\t\t\t\t\tcontext.report({ node, messageId: 'reexport' })\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor (const specifier of node.type === 'ExportNamedDeclaration' ? node.specifiers : []) {\n\t\t\t\t\tif (binding(context, specifier.local)?.defs.some((def) => def.type === 'ImportBinding')) {\n\t\t\t\t\t\tcontext.report({ node: specifier, messageId: 'reexport' })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tExportNamedDeclaration: check,\n\t\t\t\tExportAllDeclaration: check,\n\t\t\t\tExportDefaultDeclaration(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.declaration.type === 'Identifier' &&\n\t\t\t\t\t\tbinding(context, node.declaration)?.defs.some((def) => def.type === 'ImportBinding')\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontext.report({ node, messageId: 'reexport' })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'public-api-first': {\n\t\tmeta: metadata('Place private helper implementations after the exported API.', {\n\t\t\torder:\n\t\t\t\t'Move this private helper below the exported API so the file reads from public purpose to implementation.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tconst exports = exportedNames(node)\n\t\t\t\t\tconst lastExport = node.body.findLastIndex((statement) =>\n\t\t\t\t\t\tstatement.type.startsWith('Export'),\n\t\t\t\t\t)\n\t\t\t\t\tfor (const statement of node.body.slice(0, lastExport < 0 ? 0 : lastExport)) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' &&\n\t\t\t\t\t\t\tstatement.id &&\n\t\t\t\t\t\t\t!exports.has(statement.id.name)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcontext.report({ node: statement, messageId: 'order' })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'named-private-helpers': {\n\t\tmeta: metadata('Use named declarations for top-level private helper functions.', {\n\t\t\thelper: 'Declare this private helper with function name(...) at the bottom of the file.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tconst exports = exportedNames(node)\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (statement.type !== 'VariableDeclaration') continue\n\t\t\t\t\t\tfor (const declaration of statement.declarations) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tdeclaration.id.type === 'Identifier' &&\n\t\t\t\t\t\t\t\t!exports.has(declaration.id.name) &&\n\t\t\t\t\t\t\t\t(declaration.init?.type === 'ArrowFunctionExpression' ||\n\t\t\t\t\t\t\t\t\tdeclaration.init?.type === 'FunctionExpression')\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontext.report({ node: declaration, messageId: 'helper' })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n}\n\nexport const rules: Record<RuleName, Rule> = scopeRules(applicationRules)\nconst plugin: Plugin = { meta: { name: 'cvx' }, rules }\nexport default plugin\n\nfunction scopeRules(source: Record<RuleName, CreateRule>): Record<RuleName, Rule> {\n\tconst scoped = { ...source }\n\t// SAFETY: source is the closed applicationRules record; its own keys are exactly RuleName.\n\tconst names = Object.keys(source) as RuleName[]\n\tfor (const name of names) {\n\t\tconst commonProperties = {\n\t\t\tconvexDir: { type: 'string', minLength: 1 },\n\t\t\tcomponentDirs: { type: 'array', items: { type: 'string', minLength: 1 } },\n\t\t}\n\t\tconst rule = source[name]\n\t\tscoped[name] = {\n\t\t\tmeta: {\n\t\t\t\t...rule.meta,\n\t\t\t\tschema: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties:\n\t\t\t\t\t\t\tname === 'domain-import-boundaries'\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t...commonProperties,\n\t\t\t\t\t\t\t\t\t\tdomainPublicFiles: {\n\t\t\t\t\t\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\t\t\t\t\t\tadditionalProperties: {\n\t\t\t\t\t\t\t\t\t\t\t\ttype: 'array',\n\t\t\t\t\t\t\t\t\t\t\t\titems: { type: 'string', minLength: 1 },\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: commonProperties,\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\tcreate(context) {\n\t\t\t\tconst file = appFile(context)\n\t\t\t\tif (\n\t\t\t\t\t!file ||\n\t\t\t\t\t/(?:^|\\/)(?:_generated|__tests__)(?:\\/|$)/.test(file) ||\n\t\t\t\t\t/\\.(?:test|spec)\\.[cm]?[jt]s$/.test(file)\n\t\t\t\t)\n\t\t\t\t\treturn {}\n\t\t\t\treturn rule.create(context)\n\t\t\t},\n\t\t}\n\t}\n\treturn scoped\n}\n"],"mappings":"A,4tBAoCA,SAAgBA,EAAkB,EAA+B,CAAC,EAA6B,CAC9F,IAAK,IAAMC,KAAYC,EAAQ,YAAc,CAAC,EAAGC,EAAcF,CAAQ,EACvE,OAAOG,EAAoBF,CAAO,CACnC,CA2pBA,MAAaG,EAAgCC,EAAW,CAloBvD,GAAGC,EACH,mBAAoB,CACnB,GAAGA,EAAe,oBAClB,OAAO,EAAS,CACf,IAAMC,EAAOC,EAAQC,CAAO,GAAK,GAejC,MAdI,CAAC,eAAgB,aAAa,CAAC,CAAC,SAASF,CAAI,EAC5CG,EAAsBH,EAAME,EAAQ,WAAW,IAAI,EAAU,CAAC,EAC3D,CACN,QAAQ,EAAM,CACbA,EAAQ,OAAO,CACd,OACA,UAAW,YACX,KAAM,CACL,OAAQ,GAAGF,EAAK,oFACjB,CACD,CAAC,CACF,CACD,EAEMD,EAAe,mBAAmB,CAAC,OAAOG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{ ManagedScope } from "./security.mjs";
4
+ import { Value } from "convex/values";
5
+ /** A `k` schema whose parsed output is a Convex value, as a cursor payload must be. */
6
+ export type KCursorSchema = KType & {
7
+ readonly _output: Value;
8
+ };
9
+ /** Private engine contract. Bindings must come from trusted normalized engine state, never query args. */
10
+ export interface CursorBinding {
11
+ readonly table: string;
12
+ readonly index?: string | null;
13
+ readonly order: 'asc' | 'desc';
14
+ readonly clientFilters: Value;
15
+ readonly serverFilters: Value;
16
+ readonly relationPath: readonly string[];
17
+ readonly parent?: string | null;
18
+ readonly principal: string;
19
+ readonly tenant?: string | null;
20
+ readonly policyVersion: string;
21
+ readonly engineVersion: string;
22
+ readonly registryVersion: string;
23
+ /** Deliberately excluded from authenticated identity. */
24
+ readonly pageSize?: number;
25
+ }
26
+ export interface CursorCodecConfig {
27
+ readonly version: string;
28
+ readonly currentKeyId: string;
29
+ readonly keys: Readonly<Record<string, Uint8Array>>;
30
+ }
31
+ export declare class CursorError extends Error {
32
+ readonly _tag = "CursorError";
33
+ readonly code = "invalid-cursor";
34
+ constructor();
35
+ }
36
+ export declare class CursorConfigurationError extends Error {
37
+ readonly _tag = "CursorConfigurationError";
38
+ constructor();
39
+ }
40
+ /** Internal pagination boundary. The binding and its nested values are engine-owned for this operation. */
41
+ export declare function prepareCursorBinding(binding: CursorBinding): CursorBinding;
42
+ /** Private lazy server configuration. Call only at the first pagination boundary. */
43
+ export declare function createEnvironmentCursorCodec(): Readonly<{
44
+ seal: (raw: string, binding: CursorBinding) => string;
45
+ open: (token: string, binding: CursorBinding) => string;
46
+ custom: Readonly<{
47
+ seal(raw: string, binding: CursorBinding): string;
48
+ open(token: string, binding: CursorBinding): string;
49
+ }>;
50
+ }>;
51
+ /**
52
+ * Deterministic RFC 5297 AES-SIV: equal plaintext and binding leak equality.
53
+ * One navigation-boundary family permits native split/continue tokens in start/end
54
+ * slots. Relation identity remains in the binding. No nonce/randomness or plaintext fallback. Opening is not authorization: the engine
55
+ * must recheck current policy on every future request, including nested continuations.
56
+ */
57
+ export declare function createCursorCodec(config: CursorCodecConfig): Readonly<{
58
+ seal: (raw: string, binding: CursorBinding) => string;
59
+ open: (token: string, binding: CursorBinding) => string;
60
+ custom: Readonly<{
61
+ seal(raw: string, binding: CursorBinding): string;
62
+ open(token: string, binding: CursorBinding): string;
63
+ }>;
64
+ }>;
65
+ /** Server-derived binding supplements managed scope; opening never grants row access. */
66
+ export interface ScopedCursorOptions<S extends KCursorSchema> {
67
+ readonly domain: string;
68
+ readonly bind: Value;
69
+ /** A `k` schema, applied on seal AND open. Outputs must be bounded Convex values. */
70
+ readonly schema: S;
71
+ }
72
+ /** Integrity only: consumers must recheck current authorization on every request. */
73
+ export interface ScopedCursorCodec<S extends KCursorSchema> {
74
+ seal(payload: S['validator']['type']): string;
75
+ open(token: string): S['_output'];
76
+ }
77
+ /** Internal construction uses the configured engine's already captured key ring. */
78
+ export declare function createScopedCursorCodec<S extends KCursorSchema>(transport: ReturnType<typeof createCursorCodec>['custom'], scope: ManagedScope & {
79
+ readonly policyVersion: string;
80
+ }, options: ScopedCursorOptions<S>): ScopedCursorCodec<S>;
81
+ /** The parse step a scoped codec applies on seal and open; it must be synchronous. */
82
+ export interface ScopedCursorParser<Output> {
83
+ readonly domain: string;
84
+ readonly bind: Value;
85
+ parse(value: unknown): Output;
86
+ }
87
+ /** The scoped codec around any synchronous parser; `createScopedCursorCodec` supplies the `k` parse. */
88
+ export declare function scopedCursorCodec<Input, Output>(transport: ReturnType<typeof createCursorCodec>['custom'], scope: ManagedScope & {
89
+ readonly policyVersion: string;
90
+ }, options: ScopedCursorParser<Output>): {
91
+ seal(payload: Input): string;
92
+ open(token: string): Output;
93
+ };
94
+ //# sourceMappingURL=cursors.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{canonicalConvexBytes as e}from"../modules/contracts/idempotency.mjs";import{jsonToConvex as t}from"convex/values";import{aessiv as n}from"@noble/ciphers/aes.js";import{bytesToHex as r,hexToBytes as i}from"@noble/ciphers/utils.js";var a=class extends Error{_tag=`CursorError`;code=`invalid-cursor`;constructor(){super(`Invalid cursor`),this.name=`CursorError`}},o=class extends Error{_tag=`CursorConfigurationError`;constructor(){super(`Invalid cursor server configuration`),this.name=`CursorConfigurationError`}};const s=Object.freeze({maxDepth:24,maxNodes:2048,maxBytes:16384,maxArrayLength:512,maxObjectFields:128}),c=8192,l=new TextEncoder,u=new TextDecoder(`utf-8`,{fatal:!0}),d=/^[A-Za-z0-9_-]{1,32}$/;let f;function p(e){if(f??=/* @__PURE__ */ new WeakMap,f.has(e))return e;let t=Object.freeze({...e});return f.set(t,/* @__PURE__ */ new Map),t}function m(){try{let e=process.env.CVX_QUERY_CURSOR_KEYS_JSON,t=process.env.CVX_QUERY_CURSOR_CURRENT_KEY_ID;if(!e||!t)throw new o;let n=JSON.parse(e);if(typeof n!=`object`||!n||Array.isArray(n))throw new o;return h({version:`1`,currentKeyId:t,keys:Object.fromEntries(Object.entries(n).map(([e,t])=>{if(typeof t!=`string`||!/^[0-9a-fA-F]{128}$/.test(t))throw new o;return[e,i(t)]}))})}catch{throw new o}}function h(e){let t,s,f=/* @__PURE__ */ new Map;try{if(t=e.version,s=e.currentKeyId,typeof t!=`string`||typeof s!=`string`||!d.test(t)||!d.test(s))throw new o;let n=Object.entries(e.keys);if(!n.length)throw new o;for(let[e,t]of n){if(!d.test(e)||!(t instanceof Uint8Array)||t.byteLength!==64)throw new o;f.set(e,Uint8Array.from(t))}if(!f.has(s))throw new o}catch{throw new o}function p(e){return Object.freeze({seal(i,o){try{if(typeof i!=`string`||i.length>c||l.encode(i).length>c)throw new a;let u=l.encode(JSON.stringify(i)),d=n(f.get(s),C(t,s,o,e));return`${e}.${t}.${s}.${r(d.encrypt(u))}`}catch{throw new a}},open(r,o){try{if(typeof r!=`string`||r.length>98410)throw new a;let s=r.split(`.`);if(s.length!==4||s[0]!==e||s[1]!==t||!d.test(s[2]))throw new a;let p=s[2],m=s[3],h=f.get(p);if(!h||m.length<36||m.length>98340||m.length%2||!/^[0-9a-f]+$/.test(m))throw new a;let g=n(h,C(t,p,o,e)).decrypt(i(m));if(g.length>49154)throw new a;let _=u.decode(g),v=JSON.parse(_);if(typeof v!=`string`||v.length>c||l.encode(v).length>c||JSON.stringify(v)!==_)throw new a;return v}catch{throw new a}}})}return Object.freeze({...p(`pc`),custom:p(`cc`)})}function g(e,t,n){let r=y(n.schema);return _(e,t,{domain:n.domain,bind:n.bind,parse:e=>v(r.parse(e))})}function _(t,n,r){try{if(x(r.bind),typeof r.domain!=`string`||!r.domain.length||r.domain.length>256)throw new a;let i={table:r.domain,order:`asc`,principal:`custom`,policyVersion:n.policyVersion,engineVersion:`custom-1`,registryVersion:`custom-1`,relationPath:[],clientFilters:b(JSON.parse(e(r.bind,s))),serverFilters:{...n}};S(`1`,`validation`,i,`cc`);let o=r.parse;function l(t){return x(t),e(t,{...s,maxBytes:c})}function u(e){l(e);let t=o(e);return l(t),t}return Object.freeze({seal(e){try{return u(e),t.seal(l(e),i)}catch{throw new a}},open(e){try{let n=t.open(e,i),r=b(JSON.parse(n));if(l(r)!==n)throw new a;return u(r)}catch{throw new a}}})}catch{throw new a}}function v(e){let t=[e],n=0;for(;t.length;){let e=t.pop();if(++n>s.maxNodes)throw new a;if(!(e===null||typeof e!=`object`&&typeof e!=`function`)){if(`then`in e&&typeof e.then==`function`)throw Promise.resolve(e).catch(()=>{}),new a;if(!(typeof e==`function`||e instanceof ArrayBuffer))for(let n of Object.values(Object.getOwnPropertyDescriptors(e)))`value`in n&&t.push(n.value)}}return e}function y(e){return e}function b(e,n=0){if(n>s.maxDepth)throw new a;if(Array.isArray(e))return e.map(e=>b(e,n+1));if(typeof e==`object`&&e){let r=Object.entries(e);return r.some(([e])=>e.startsWith(`$`))?t(e):Object.fromEntries(r.map(([e,t])=>[e,b(t,n+1)]))}return t(e)}function x(e){let t=/* @__PURE__ */ new Set,n=0;function r(e,i){if(++n>s.maxNodes||i>s.maxDepth)throw new a;if(typeof e!=`object`||!e)return;if(e instanceof ArrayBuffer){if(Object.getPrototypeOf(e)!==ArrayBuffer.prototype||Object.getOwnPropertyNames(e).length||Object.getOwnPropertySymbols(e).length)throw new a;return}if(t.has(e))throw new a;let o=Array.isArray(e);if(o&&Object.getPrototypeOf(e)!==Array.prototype||!o&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Object.getOwnPropertySymbols(e).length)throw new a;let c=Object.getOwnPropertyNames(e);if(c.length>(o?s.maxArrayLength+1:s.maxObjectFields))throw new a;t.add(e);try{for(let t of c){let n=Object.getOwnPropertyDescriptor(e,t);if(!(`value`in n))throw new a;if(o&&t===`length`){if(n.value>s.maxArrayLength)throw new a}else{if(!n.enumerable||o&&(!/^(0|[1-9][0-9]*)$/.test(t)||Number(t)>=e.length))throw new a;r(n.value,i+1)}}}finally{t.delete(e)}}r(e,0)}function S(t,n,r,i){if(x(r),r.clientFilters===void 0||r.serverFilters===void 0)throw new a;let{table:o,order:c,principal:u,policyVersion:d,engineVersion:f,registryVersion:p}=r;for(let e of[o,u,d,f,p])if(typeof e!=`string`||!e.length)throw new a;if(c!==`asc`&&c!==`desc`)throw new a;for(let e of[r.index,r.parent,r.tenant])if(e!=null&&typeof e!=`string`)throw new a;if(!Array.isArray(r.relationPath)||r.relationPath.some(e=>typeof e!=`string`))throw new a;return l.encode(e({domain:i===`pc`?`cvx-query-cursor`:`cvx-custom-cursor`,version:t,keyId:n,table:o,index:r.index??null,order:c,clientFilters:r.clientFilters,serverFilters:r.serverFilters,relationPath:r.relationPath,parent:r.parent??null,principal:u,tenant:r.tenant??null,policyVersion:d,engineVersion:f,registryVersion:p},s))}function C(e,t,n,r){let i=f?.get(n);if(!i)return S(e,t,n,r);let a=`${r}:${e}:${t}`,o=i.get(a);return o||(o=S(e,t,n,r),i.set(a,o)),o}export{o as CursorConfigurationError,a as CursorError,h as createCursorCodec,m as createEnvironmentCursorCodec,g as createScopedCursorCodec,p as prepareCursorBinding,_ as scopedCursorCodec};
2
+ //# sourceMappingURL=cursors.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cursors.mjs","names":["CursorError","CursorConfigurationError","bounds","maxPlaintextBytes","encoder","decoder","identifier","operationBindings","prepareCursorBinding","binding","prepared","createEnvironmentCursorCodec","encoded","currentKeyId","parsed","createCursorCodec","id","key","hexToBytes","version","keys","config","entries","transport","raw","payload","cipher","aessiv","associatedData","namespace","bytesToHex","token","parts","keyId","plaintext","json","createScopedCursorCodec","schema","schemaOf","options","scopedCursorCodec","scope","synchronous","value","checkDescriptors","jsonToValue","canonicalConvexBytes","aad","parse","encode","validate","pending","result","nodes","current","descriptor","depth","item","jsonToConvex","ancestors","visit","array","names","name","field","table","principal","policyVersion","engineVersion","registryVersion","order","part","data"],"sources":["../../src/querying/cursors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters -- Cursor transport and canonical values are explicit validation boundaries. */\nimport { aessiv } from '@noble/ciphers/aes.js'\nimport { bytesToHex, hexToBytes } from '@noble/ciphers/utils.js'\nimport { jsonToConvex, type Value, type JSONValue } from 'convex/values'\nimport type { KSchema, KType } from '../k'\n\n/** A `k` schema whose parsed output is a Convex value, as a cursor payload must be. */\nexport type KCursorSchema = KType & { readonly _output: Value }\nimport type { ManagedScope } from './security'\nimport { canonicalConvexBytes } from '../modules/contracts/idempotency'\n\n/** Private engine contract. Bindings must come from trusted normalized engine state, never query args. */\nexport interface CursorBinding {\n\treadonly table: string\n\treadonly index?: string | null\n\treadonly order: 'asc' | 'desc'\n\treadonly clientFilters: Value\n\treadonly serverFilters: Value\n\treadonly relationPath: readonly string[]\n\treadonly parent?: string | null\n\treadonly principal: string\n\treadonly tenant?: string | null\n\treadonly policyVersion: string\n\treadonly engineVersion: string\n\treadonly registryVersion: string\n\t/** Deliberately excluded from authenticated identity. */\n\treadonly pageSize?: number\n}\nexport interface CursorCodecConfig {\n\treadonly version: string\n\treadonly currentKeyId: string\n\treadonly keys: Readonly<Record<string, Uint8Array>>\n}\nexport class CursorError extends Error {\n\treadonly _tag = 'CursorError'\n\treadonly code = 'invalid-cursor'\n\tconstructor() {\n\t\tsuper('Invalid cursor')\n\t\tthis.name = 'CursorError'\n\t}\n}\nexport class CursorConfigurationError extends Error {\n\treadonly _tag = 'CursorConfigurationError'\n\tconstructor() {\n\t\tsuper('Invalid cursor server configuration')\n\t\tthis.name = 'CursorConfigurationError'\n\t}\n}\n\nconst bounds = Object.freeze({\n\tmaxDepth: 24,\n\tmaxNodes: 2048,\n\tmaxBytes: 16384,\n\tmaxArrayLength: 512,\n\tmaxObjectFields: 128,\n})\nconst maxPlaintextBytes = 8192\n// JSON string encoding preserves even lone UTF-16 surrogates without lossy UTF-8 replacement.\nconst maxPayloadBytes = maxPlaintextBytes * 6 + 2\nconst maxCiphertextBytes = maxPayloadBytes + 16\nconst maxTokenLength = maxCiphertextBytes * 2 + 70\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder('utf-8', { fatal: true })\nconst identifier = /^[A-Za-z0-9_-]{1,32}$/\n\n// Only the fresh, engine-owned binding for a single operation can reuse AAD.\nlet operationBindings: WeakMap<CursorBinding, Map<string, Uint8Array>> | undefined\n\n/** Internal pagination boundary. The binding and its nested values are engine-owned for this operation. */\nexport function prepareCursorBinding(binding: CursorBinding): CursorBinding {\n\toperationBindings ??= new WeakMap()\n\tif (operationBindings.has(binding)) return binding\n\tconst prepared = Object.freeze({ ...binding })\n\toperationBindings.set(prepared, new Map())\n\treturn prepared\n}\n\n/** Private lazy server configuration. Call only at the first pagination boundary. */\nexport function createEnvironmentCursorCodec() {\n\ttry {\n\t\tconst encoded = process.env.CVX_QUERY_CURSOR_KEYS_JSON\n\t\tconst currentKeyId = process.env.CVX_QUERY_CURSOR_CURRENT_KEY_ID\n\t\tif (!encoded || !currentKeyId) throw new CursorConfigurationError()\n\t\tconst parsed: unknown = JSON.parse(encoded)\n\t\tif (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))\n\t\t\tthrow new CursorConfigurationError()\n\t\tconst keys = Object.fromEntries(\n\t\t\tObject.entries(parsed).map(([id, key]) => {\n\t\t\t\tif (typeof key !== 'string' || !/^[0-9a-fA-F]{128}$/.test(key))\n\t\t\t\t\tthrow new CursorConfigurationError()\n\t\t\t\treturn [id, hexToBytes(key)]\n\t\t\t}),\n\t\t)\n\t\treturn createCursorCodec({ version: '1', currentKeyId, keys })\n\t} catch {\n\t\t// Parsing/runtime failures must never expose key material or environment values.\n\t\tthrow new CursorConfigurationError()\n\t}\n}\n\n/**\n * Deterministic RFC 5297 AES-SIV: equal plaintext and binding leak equality.\n * One navigation-boundary family permits native split/continue tokens in start/end\n * slots. Relation identity remains in the binding. No nonce/randomness or plaintext fallback. Opening is not authorization: the engine\n * must recheck current policy on every future request, including nested continuations.\n */\nexport function createCursorCodec(config: CursorCodecConfig) {\n\tlet version: string, currentKeyId: string\n\tconst keys = new Map<string, Uint8Array>()\n\ttry {\n\t\tversion = config.version\n\t\tcurrentKeyId = config.currentKeyId\n\t\tif (\n\t\t\ttypeof version !== 'string' ||\n\t\t\ttypeof currentKeyId !== 'string' ||\n\t\t\t!identifier.test(version) ||\n\t\t\t!identifier.test(currentKeyId)\n\t\t)\n\t\t\tthrow new CursorConfigurationError()\n\t\tconst entries = Object.entries(config.keys)\n\t\tif (!entries.length) throw new CursorConfigurationError()\n\t\tfor (const [id, key] of entries) {\n\t\t\tif (!identifier.test(id) || !(key instanceof Uint8Array) || key.byteLength !== 64)\n\t\t\t\tthrow new CursorConfigurationError()\n\t\t\tkeys.set(id, Uint8Array.from(key))\n\t\t}\n\t\tif (!keys.has(currentKeyId)) throw new CursorConfigurationError()\n\t} catch {\n\t\tthrow new CursorConfigurationError()\n\t}\n\tfunction transport(namespace: 'pc' | 'cc') {\n\t\treturn Object.freeze({\n\t\t\tseal(raw: string, binding: CursorBinding): string {\n\t\t\t\ttry {\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof raw !== 'string' ||\n\t\t\t\t\t\traw.length > maxPlaintextBytes ||\n\t\t\t\t\t\tencoder.encode(raw).length > maxPlaintextBytes\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new CursorError()\n\t\t\t\t\tconst payload = encoder.encode(JSON.stringify(raw))\n\t\t\t\t\tconst cipher = aessiv(\n\t\t\t\t\t\tkeys.get(currentKeyId)!,\n\t\t\t\t\t\tassociatedData(version, currentKeyId, binding, namespace),\n\t\t\t\t\t)\n\t\t\t\t\treturn `${namespace}.${version}.${currentKeyId}.${bytesToHex(cipher.encrypt(payload))}`\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new CursorError()\n\t\t\t\t}\n\t\t\t},\n\t\t\topen(token: string, binding: CursorBinding): string {\n\t\t\t\ttry {\n\t\t\t\t\tif (typeof token !== 'string' || token.length > maxTokenLength) throw new CursorError()\n\t\t\t\t\tconst parts = token.split('.')\n\t\t\t\t\tif (\n\t\t\t\t\t\tparts.length !== 4 ||\n\t\t\t\t\t\tparts[0] !== namespace ||\n\t\t\t\t\t\tparts[1] !== version ||\n\t\t\t\t\t\t!identifier.test(parts[2]!)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new CursorError()\n\t\t\t\t\tconst keyId = parts[2]!,\n\t\t\t\t\t\tencoded = parts[3]!,\n\t\t\t\t\t\tkey = keys.get(keyId)\n\t\t\t\t\tif (\n\t\t\t\t\t\t!key ||\n\t\t\t\t\t\tencoded.length < 36 ||\n\t\t\t\t\t\tencoded.length > maxCiphertextBytes * 2 ||\n\t\t\t\t\t\tencoded.length % 2 ||\n\t\t\t\t\t\t!/^[0-9a-f]+$/.test(encoded)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new CursorError()\n\t\t\t\t\tconst cipher = aessiv(key, associatedData(version, keyId, binding, namespace))\n\t\t\t\t\tconst plaintext = cipher.decrypt(hexToBytes(encoded))\n\t\t\t\t\tif (plaintext.length > maxPayloadBytes) throw new CursorError()\n\t\t\t\t\tconst json = decoder.decode(plaintext)\n\t\t\t\t\tconst raw: unknown = JSON.parse(json)\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof raw !== 'string' ||\n\t\t\t\t\t\traw.length > maxPlaintextBytes ||\n\t\t\t\t\t\tencoder.encode(raw).length > maxPlaintextBytes ||\n\t\t\t\t\t\tJSON.stringify(raw) !== json\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new CursorError()\n\t\t\t\t\treturn raw\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new CursorError()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\treturn Object.freeze({ ...transport('pc'), custom: transport('cc') })\n}\n\n/** Server-derived binding supplements managed scope; opening never grants row access. */\nexport interface ScopedCursorOptions<S extends KCursorSchema> {\n\treadonly domain: string\n\treadonly bind: Value\n\t/** A `k` schema, applied on seal AND open. Outputs must be bounded Convex values. */\n\treadonly schema: S\n}\n/** Integrity only: consumers must recheck current authorization on every request. */\nexport interface ScopedCursorCodec<S extends KCursorSchema> {\n\tseal(payload: S['validator']['type']): string\n\topen(token: string): S['_output']\n}\n\n/** Internal construction uses the configured engine's already captured key ring. */\nexport function createScopedCursorCodec<S extends KCursorSchema>(\n\ttransport: ReturnType<typeof createCursorCodec>['custom'],\n\tscope: ManagedScope & { readonly policyVersion: string },\n\toptions: ScopedCursorOptions<S>,\n): ScopedCursorCodec<S> {\n\tconst schema = schemaOf(options.schema)\n\treturn scopedCursorCodec<S['validator']['type'], S['_output']>(transport, scope, {\n\t\tdomain: options.domain,\n\t\tbind: options.bind,\n\t\tparse: (value): S['_output'] => synchronous(schema.parse(value)),\n\t})\n}\n\n/** The parse step a scoped codec applies on seal and open; it must be synchronous. */\nexport interface ScopedCursorParser<Output> {\n\treadonly domain: string\n\treadonly bind: Value\n\tparse(value: unknown): Output\n}\n\n/** The scoped codec around any synchronous parser; `createScopedCursorCodec` supplies the `k` parse. */\nexport function scopedCursorCodec<Input, Output>(\n\ttransport: ReturnType<typeof createCursorCodec>['custom'],\n\tscope: ManagedScope & { readonly policyVersion: string },\n\toptions: ScopedCursorParser<Output>,\n): { seal(payload: Input): string; open(token: string): Output } {\n\ttry {\n\t\tcheckDescriptors(options.bind)\n\t\tif (typeof options.domain !== 'string' || !options.domain.length || options.domain.length > 256)\n\t\t\tthrow new CursorError()\n\t\t// Snapshot bind bytes before returning: later caller mutation cannot change identity.\n\t\tconst binding: CursorBinding = {\n\t\t\ttable: options.domain,\n\t\t\torder: 'asc',\n\t\t\tprincipal: 'custom',\n\t\t\tpolicyVersion: scope.policyVersion,\n\t\t\tengineVersion: 'custom-1',\n\t\t\tregistryVersion: 'custom-1',\n\t\t\trelationPath: [],\n\t\t\tclientFilters: jsonToValue(JSON.parse(canonicalConvexBytes(options.bind, bounds))),\n\t\t\tserverFilters: { ...scope },\n\t\t}\n\t\t// Validate the combined identity even before any seal/open call.\n\t\taad('1', 'validation', binding, 'cc')\n\t\tconst parse = options.parse\n\t\tfunction encode(value: unknown): string {\n\t\t\tcheckDescriptors(value)\n\t\t\treturn canonicalConvexBytes(value, { ...bounds, maxBytes: maxPlaintextBytes })\n\t\t}\n\t\tfunction validate(value: unknown): Output {\n\t\t\tencode(value)\n\t\t\tconst parsed = parse(value)\n\t\t\tencode(parsed)\n\t\t\treturn parsed\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tseal(payload: Input): string {\n\t\t\t\ttry {\n\t\t\t\t\t// Validate output too, but retain input bytes so open applies transforms once.\n\t\t\t\t\tvalidate(payload)\n\t\t\t\t\treturn transport.seal(encode(payload), binding)\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new CursorError()\n\t\t\t\t}\n\t\t\t},\n\t\t\topen(token: string): Output {\n\t\t\t\ttry {\n\t\t\t\t\tconst raw = transport.open(token, binding)\n\t\t\t\t\tconst value = jsonToValue(JSON.parse(raw))\n\t\t\t\t\tif (encode(value) !== raw) throw new CursorError()\n\t\t\t\t\treturn validate(value)\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new CursorError()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t} catch {\n\t\tthrow new CursorError()\n\t}\n}\n\n/**\n * A `k` parse never awaits, but a transform may still return a promise. Reject it, and any promise\n * nested in the output, before encoding, and contain its rejection so no detail escapes.\n */\nfunction synchronous<Output>(result: Output): Output {\n\tconst pending: unknown[] = [result]\n\tlet nodes = 0\n\twhile (pending.length) {\n\t\tconst current = pending.pop()\n\t\tif (++nodes > bounds.maxNodes) throw new CursorError()\n\t\tif (current === null || (typeof current !== 'object' && typeof current !== 'function')) continue\n\t\tif ('then' in current && typeof current.then === 'function') {\n\t\t\tvoid Promise.resolve(current).catch(() => {})\n\t\t\tthrow new CursorError()\n\t\t}\n\t\tif (typeof current === 'function' || current instanceof ArrayBuffer) continue\n\t\tfor (const descriptor of Object.values(Object.getOwnPropertyDescriptors(current)))\n\t\t\tif ('value' in descriptor) pending.push(descriptor.value)\n\t}\n\treturn result\n}\n\nfunction schemaOf(schema: KType): KSchema<any, any, any, any, any> {\n\t// SAFETY: every KType at runtime is a k schema record, whose parse is synchronous and yields its output.\n\treturn schema as KSchema<any, any, any, any, any>\n}\n\n/** Preserve own __proto__ fields; SDK scalar conversion handles integer/binary/float tags. */\nfunction jsonToValue(value: JSONValue, depth = 0): Value {\n\tif (depth > bounds.maxDepth) throw new CursorError()\n\tif (Array.isArray(value)) return value.map((item) => jsonToValue(item, depth + 1))\n\tif (value !== null && typeof value === 'object') {\n\t\tconst entries = Object.entries(value)\n\t\tif (entries.some(([key]) => key.startsWith('$'))) return jsonToConvex(value)\n\t\treturn Object.fromEntries(entries.map(([key, item]) => [key, jsonToValue(item, depth + 1)]))\n\t}\n\treturn jsonToConvex(value)\n}\n\n/** Reject accessor-bearing arrays/dictionaries before the shared canonical encoder reads values. */\nfunction checkDescriptors(value: unknown): void {\n\tconst ancestors = new Set<object>()\n\tlet nodes = 0\n\tfunction visit(current: unknown, depth: number): void {\n\t\tif (++nodes > bounds.maxNodes || depth > bounds.maxDepth) throw new CursorError()\n\t\tif (current === null || typeof current !== 'object') return\n\t\tif (current instanceof ArrayBuffer) {\n\t\t\tif (\n\t\t\t\tObject.getPrototypeOf(current) !== ArrayBuffer.prototype ||\n\t\t\t\tObject.getOwnPropertyNames(current).length ||\n\t\t\t\tObject.getOwnPropertySymbols(current).length\n\t\t\t)\n\t\t\t\tthrow new CursorError()\n\t\t\treturn\n\t\t}\n\t\tif (ancestors.has(current)) throw new CursorError()\n\t\tconst array = Array.isArray(current)\n\t\tif (array && Object.getPrototypeOf(current) !== Array.prototype) throw new CursorError()\n\t\tif (\n\t\t\t!array &&\n\t\t\tObject.getPrototypeOf(current) !== Object.prototype &&\n\t\t\tObject.getPrototypeOf(current) !== null\n\t\t)\n\t\t\tthrow new CursorError()\n\t\tif (Object.getOwnPropertySymbols(current).length) throw new CursorError()\n\t\tconst names = Object.getOwnPropertyNames(current)\n\t\tif (names.length > (array ? bounds.maxArrayLength + 1 : bounds.maxObjectFields))\n\t\t\tthrow new CursorError()\n\t\tancestors.add(current)\n\t\ttry {\n\t\t\tfor (const name of names) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(current, name)!\n\t\t\t\tif (!('value' in descriptor)) throw new CursorError()\n\t\t\t\tif (array && name === 'length') {\n\t\t\t\t\tif (descriptor.value > bounds.maxArrayLength) throw new CursorError()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!descriptor.enumerable ||\n\t\t\t\t\t(array && (!/^(0|[1-9][0-9]*)$/.test(name) || Number(name) >= current.length))\n\t\t\t\t)\n\t\t\t\t\tthrow new CursorError()\n\t\t\t\tvisit(descriptor.value, depth + 1)\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(current)\n\t\t}\n\t}\n\tvisit(value, 0)\n}\nfunction aad(\n\tversion: string,\n\tkeyId: string,\n\tbinding: CursorBinding,\n\tnamespace: 'pc' | 'cc',\n): Uint8Array {\n\tcheckDescriptors(binding)\n\tif (binding.clientFilters === undefined || binding.serverFilters === undefined)\n\t\tthrow new CursorError()\n\tconst { table, order, principal, policyVersion, engineVersion, registryVersion } = binding\n\tfor (const field of [table, principal, policyVersion, engineVersion, registryVersion])\n\t\tif (typeof field !== 'string' || !field.length) throw new CursorError()\n\tif (order !== 'asc' && order !== 'desc') throw new CursorError()\n\tfor (const field of [binding.index, binding.parent, binding.tenant])\n\t\tif (field != null && typeof field !== 'string') throw new CursorError()\n\tif (\n\t\t!Array.isArray(binding.relationPath) ||\n\t\tbinding.relationPath.some((part) => typeof part !== 'string')\n\t)\n\t\tthrow new CursorError()\n\treturn encoder.encode(\n\t\tcanonicalConvexBytes(\n\t\t\t{\n\t\t\t\tdomain: namespace === 'pc' ? 'cvx-query-cursor' : 'cvx-custom-cursor',\n\t\t\t\tversion,\n\t\t\t\tkeyId,\n\t\t\t\ttable,\n\t\t\t\tindex: binding.index ?? null,\n\t\t\t\torder,\n\t\t\t\tclientFilters: binding.clientFilters,\n\t\t\t\tserverFilters: binding.serverFilters,\n\t\t\t\trelationPath: binding.relationPath,\n\t\t\t\tparent: binding.parent ?? null,\n\t\t\t\tprincipal,\n\t\t\t\ttenant: binding.tenant ?? null,\n\t\t\t\tpolicyVersion,\n\t\t\t\tengineVersion,\n\t\t\t\tregistryVersion,\n\t\t\t},\n\t\t\tbounds,\n\t\t),\n\t)\n}\n\nfunction associatedData(\n\tversion: string,\n\tkeyId: string,\n\tbinding: CursorBinding,\n\tnamespace: 'pc' | 'cc',\n) {\n\tconst prepared = operationBindings?.get(binding)\n\tif (!prepared) return aad(version, keyId, binding, namespace)\n\tconst key = `${namespace}:${version}:${keyId}`\n\tlet data = prepared.get(key)\n\tif (!data) {\n\t\tdata = aad(version, keyId, binding, namespace)\n\t\tprepared.set(key, data)\n\t}\n\treturn data\n}\n"],"mappings":"A,6OAiCA,IAAaA,EAAb,cAAiC,KAAM,CACtC,KAAgB,cAChB,KAAgB,iBAChB,aAAc,CACb,MAAM,gBAAgB,EACtB,KAAK,KAAO,aACb,CACD,EACaC,EAAb,cAA8C,K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U,UAAY,CAACA,EAAM,OAAQ,MAAM,IAAIhE,EAC3D,GAAIsE,IAAU,OAASA,IAAU,OAAQ,MAAM,IAAItE,EACnD,IAAK,IAAMgE,IAAS,CAACvD,EAAQ,MAAOA,EAAQ,OAAQA,EAAQ,MAAM,EACjE,GAAIuD,GAAS,MAAQ,OAAOA,GAAU,SAAU,MAAM,IAAIhE,EAC3D,GACC,CAAC,MAAM,QAAQS,EAAQ,YAAY,GACnCA,EAAQ,aAAa,KAAM,GAAS,OAAO8D,GAAS,QAAQ,EAE5D,MAAM,IAAIvE,EACX,OAAOI,EAAQ,OACd0C,EACC,CACC,OAAQjB,IAAc,KAAO,mBAAqB,oBAClD,UACA,QACA,QACA,MAAOpB,EAAQ,OAAS,KACxB,QACA,cAAeA,EAAQ,cACvB,cAAeA,EAAQ,cACvB,aAAcA,EAAQ,aACtB,OAAQA,EAAQ,QAAU,KAC1B,YACA,OAAQA,EAAQ,QAAU,KAC1B,gBACA,gBACA,iBACD,EACAP,CACD,CACD,CACD,CAEA,SAAS0B,EACR,EACA,EACA,EACA,EACC,CACD,IAAMlB,EAAWH,GAAmB,IAAIE,CAAO,EAC/C,GAAI,CAACC,EAAU,OAAOqC,EAAI5B,EAASc,EAAOxB,EAASoB,CAAS,EAC5D,IAAMZ,EAAM,GAAGY,EAAU,GAAGV,EAAQ,GAAGc,IACnCuC,EAAO9D,EAAS,IAAIO,CAAG,EAK3B,OAJKuD,IACJ,EAAOzB,EAAI5B,EAASc,EAAOxB,EAASoB,CAAS,EAC7CnB,EAAS,IAAIO,EAAKuD,CAAI,GAEhBA,CACR,C"}
@@ -0,0 +1,40 @@
1
+ import { FilterScalar } from "./shared/ast.mjs";
2
+ import { createPlanner } from "./planner.mjs";
3
+ import { ManagedReadRequest } from "./security.mjs";
4
+ import { CursorBinding, createCursorCodec } from "./cursors.mjs";
5
+ import { NativePagination, NativeRange } from "./filters.mjs";
6
+ import { PageCompleteness } from "../table.mjs";
7
+ import { Value } from "convex/values";
8
+ import { GenericDataModel, GenericDatabaseReader, GenericSchema, IndexRangeBuilder, SchemaDefinition } from "convex/server";
9
+ import { QueryStream } from "convex-helpers/server/stream";
10
+ type Plan = ReturnType<ReturnType<typeof createPlanner>['plan']>;
11
+ type Codec = ReturnType<typeof createCursorCodec>;
12
+ export type ExecutionRequest = ManagedReadRequest<GenericDataModel>;
13
+ type Request = Omit<ExecutionRequest, 'db'>;
14
+ /** Private shared boundary: only the established fixed typed errors are public. */
15
+ export declare function rethrowQueryError(error: unknown): never;
16
+ export declare function executeQuery(schema: SchemaDefinition<GenericSchema, boolean>, request: Request, table: string, plan: Plan, planner: ReturnType<typeof createPlanner>, codec: Codec, binding: CursorBinding, complete?: (document: Record<string, Value>, permitted: boolean) => Promise<Record<string, Value> | null>): Promise<{
17
+ page: Record<string, Value>[];
18
+ isDone: boolean;
19
+ splitCursor?: import("convex/server").Cursor | null;
20
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
21
+ paginationMode?: 'native-search';
22
+ completeness: PageCompleteness;
23
+ continueCursor: string;
24
+ }>;
25
+ export declare function executeStream(schema: SchemaDefinition<GenericSchema, boolean>, request: Request, table: string, plan: Plan, planner: ReturnType<typeof createPlanner>, codec: Codec, binding: CursorBinding, args: NativePagination, complete?: (document: Record<string, Value>, permitted: boolean) => Promise<Record<string, Value> | null>, seal?: (raw: string, binding: CursorBinding) => string, transform?: (source: QueryStream<Record<string, Value>>, db: GenericDatabaseReader<any>) => QueryStream<Record<string, Value>>, authorizationTable?: string): Promise<{
26
+ page: Record<string, Value>[];
27
+ isDone: boolean;
28
+ splitCursor?: import("convex/server").Cursor | null;
29
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
30
+ paginationMode?: 'native-search';
31
+ completeness: PageCompleteness;
32
+ continueCursor: string;
33
+ }>;
34
+ /** Private adapter shared by root and relationship streams; the planner owns admission. */
35
+ export declare function nativeIndexRange(q: IndexRangeBuilder<any, string[], number>, prefix: readonly {
36
+ field: string;
37
+ value: FilterScalar;
38
+ }[], bounds: NativeRange | null): import('convex/server').IndexRange;
39
+ export {};
40
+ //# sourceMappingURL=execution.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{ManagedReadError as e}from"./security.mjs";import{CursorError as t,prepareCursorBinding as n}from"./cursors.mjs";import{rangeForIndex as r}from"./filters.mjs";import{SearchError as i}from"./search.mjs";import{RelationshipError as a}from"./relationships.mjs";import{EmptyStream as o,QueryStream as s,getIndexFields as c,mergedStream as l,stream as u}from"convex-helpers/server/stream";function d(n){throw n instanceof i||n instanceof e||n instanceof t||n instanceof a?n:Error(`Query execution failed`)}async function f(e,t,r,i,a,o,s,c){let l=i.args.cursor!==null||i.args.endCursor!=null?n(s):s;return p(e,t,r,i,a,o,l,{...i.args,cursor:i.args.cursor===null?null:o.open(i.args.cursor,l),endCursor:i.args.endCursor==null?i.args.endCursor:o.open(i.args.endCursor,l)},c)}async function p(e,t,i,a,s,f,p,g,_,y,b,x=i){let S=h(t,s),C={completed:[]};try{let d=e,h=u(S.db,d).query(i),w=a.index?h.withIndex(a.index.name,e=>m(e,a.prefix,a.range)):h,T=a.args.order??`asc`,E=a.expansion,D=E&&a.index&&!a.unsatisfiable?l(E.values.map(e=>{let t=[...a.prefix,{field:E.field,value:e}];return h.withIndex(a.index.name,e=>m(e,t,r(a.index,t,a.ranges))).order(T)}),E.comparator===`full-index`?c(i,a.index.name,d):c(i,a.index.name,d).slice(a.prefix.length+1)):w.order(T),O=b?b(D,S.db):D,k=a.unsatisfiable?await new o(O.getOrder(),O.getIndexFields(),O.getEqualityIndexFilter()).paginate(g):await new v(O,t,x,a,s,C,_).paginate(g),A=k.splitCursor==null?p:n(p),j=e=>y?y(e,A):f.seal(e,A),M={...k,completeness:k.completeness??`complete`,continueCursor:j(k.continueCursor)};return k.splitCursor!=null&&(M.splitCursor=j(k.splitCursor)),M}catch(e){d(e)}finally{await S.close()}}function m(e,t,n){let r=e;for(let{field:e,value:n}of t)r=r.eq(e,n);let i=r;if(n?.lower){let{field:e,lower:t}=n;i=t.inclusive?r.gte(e,t.value):r.gt(e,t.value)}if(n?.upper){let{field:e,upper:t}=n;return t.inclusive?i.lte(e,t.value):i.lt(e,t.value)}return i}function h(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;function i(e,a){return new Proxy({},{get(o,s){let c=a;if(s===`withIndex`&&`withIndex`in c)return(...t)=>{let n=c.withIndex;return i(e,n.apply(c,t))};if(s===`order`&&`order`in c)return(...t)=>{let n=c.order;return i(e,n.apply(c,t))};if(s===Symbol.asyncIterator)return()=>{let i=c[Symbol.asyncIterator]();return n.add(i),{next:()=>{t.beforeLeaf(e);let n=i.next();return r.add(n),n.then(()=>r.delete(n),()=>r.delete(n)),n}}};throw Error(`Unsupported private query operation`)}})}return{db:{query:n=>(t.beforeLeaf(n),i(n,e.leafQuery(n)))},async close(){await Promise.allSettled(r);let e=!1;for(let t of n)try{await t.return?.()}catch{e=!0}if(n.clear(),e)throw Error(`Query execution failed`)}}}function g(e){let t=e.counters,n=e.budgets;if(t.readOperations>=n.readOperations||t.rawCandidates>=n.rawCandidates)return`row-budget`;if(t.documentBytesObserved+t.documentBytesReserved+1048576>n.documentBytes)return`byte-budget`}var _=class extends s{entry;source;constructor(e,t){super(),this.entry=e,this.source=t}getOrder(){return this.source.getOrder()}getIndexFields(){return this.source.getIndexFields()}getEqualityIndexFilter(){return this.source.getEqualityIndexFilter()}narrow(e){if(e.lowerBound.length||e.upperBound.length||!e.lowerBoundInclusive||!e.upperBoundInclusive)throw Error(`Invalid cursor encoder range`);return this}async*iterWithKeys(){yield[{},this.entry[1],this.entry[2]]}},v=class t extends s{source;request;table;plan;planner;progress;complete;constructor(e,t,n,r,i,a,o){super(),this.source=e,this.request=t,this.table=n,this.plan=r,this.planner=i,this.progress=a,this.complete=o}getOrder(){return this.source.getOrder()}getIndexFields(){return this.source.getIndexFields()}getEqualityIndexFilter(){return this.source.getEqualityIndexFilter()}narrow(e){return new t(this.source.narrow(e),this.request,this.table,this.plan,this.planner,this.progress,this.complete)}async*iterWithKeys(){let t=this.source.iterWithKeys(!0)[Symbol.asyncIterator]();try{for(;;){let n=g(this.request);if(n){if(!this.progress.completed.length)throw new e(`MANAGED_READ_BUDGET`);this.progress.stopReason=n;return}let r,i=this.request.counters.rawCandidates;try{r=await t.next()}catch(t){if(t instanceof e&&t.code===`MANAGED_READ_BUDGET`&&this.request.leafBudgetFailure(t)&&this.progress.completed.length&&this.request.counters.rawCandidates===i){this.progress.stopReason=this.request.leafBudgetFailure(t);return}throw t}if(r.done)return;let[a,o,s]=r.value,c=null;if(a){let e=await this.request.authorize(this.table,a);c=this.complete?await this.complete(a,e):this.planner.complete(this.table,a,e,this.plan.residual)}let l=[c,o,s];this.progress.completed.push(l),yield l}}finally{await t.return?.()}}async paginate(t){let n=await super.paginate(t),r=this.progress.completed,i=async e=>(await new _(e,this.source).paginate({numItems:1,cursor:null})).continueCursor,a=t.endCursor?!!r.length&&await i(r.at(-1))===t.endCursor:n.page.length>=t.numItems;if(this.request.atomicCompletion&&(this.progress.stopReason&&!a||n.pageStatus===`SplitRequired`&&!a))throw new e(`MANAGED_READ_BUDGET`);if(!this.progress.stopReason)return{...n,completeness:n.pageStatus===`SplitRequired`&&!a?`native-limit`:`complete`};if(!r.length)throw new e(`MANAGED_READ_BUDGET`);let o=await i(r.at(-1));return{...n,completeness:a?`complete`:this.progress.stopReason,isDone:!1,pageStatus:`SplitRequired`,continueCursor:o,splitCursor:await i(r[Math.floor((r.length-1)/2)])}}};export{f as executeQuery,p as executeStream,m as nativeIndexRange,d as rethrowQueryError};
2
+ //# sourceMappingURL=execution.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.mjs","names":["rethrowQueryError","error","SearchError","ManagedReadError","CursorError","RelationshipError","executeQuery","operationBinding","plan","prepareCursorBinding","binding","executeStream","schema","request","table","planner","codec","complete","leaves","leafReader","progress","nativeSchema","base","stream","selected","nativeIndexRange","q","order","expansion","ordered","mergedStream","prefix","rangeForIndex","getIndexFields","source","transform","result","EmptyStream","args","EligibleStream","authorizationTable","sealBinding","sealBoundary","seal","raw","protectedResult","range","field","value","bounded","bounds","lower","upper","active","pending","wrap","target","key","withIndex","iterator","next","failed","fetchStopReason","c","b","CapturedKey","QueryStream","entry","reason","candidatesBefore","document","bytes","output","permitted","completed","encode","fulfilled","continuation"],"sources":["../../src/querying/execution.ts"],"sourcesContent":["import {\n\tEmptyStream,\n\tmergedStream,\n\tgetIndexFields,\n\tQueryStream,\n\tstream,\n\ttype IndexBounds,\n\ttype IndexKey,\n} from 'convex-helpers/server/stream'\nimport type {\n\tGenericDatabaseReader,\n\tGenericDataModel,\n\tGenericDocument,\n\tQueryInitializer,\n\tSchemaDefinition,\n\tGenericSchema,\n\tTableDefinition,\n\tIndexRangeBuilder,\n} from 'convex/server'\nimport type { Value } from 'convex/values'\nimport type { createPlanner } from './planner'\nimport { MAX_DOCUMENT_BYTES, ManagedReadError, type ManagedReadRequest } from './security'\nimport {\n\tCursorError,\n\tprepareCursorBinding,\n\ttype CursorBinding,\n\ttype createCursorCodec,\n} from './cursors'\nimport {\n\trangeForIndex,\n\ttype NativePagination,\n\ttype NativeRange,\n\ttype FilterScalar,\n} from './filters'\nimport { SearchError } from './search'\nimport { RelationshipError } from './relationships'\nimport type { EnginePaginationResult, PageCompleteness } from '../table'\n\ntype Entry = [Record<string, Value> | null, IndexKey, number]\ntype Plan = ReturnType<ReturnType<typeof createPlanner>['plan']>\ntype Codec = ReturnType<typeof createCursorCodec>\nexport type ExecutionRequest = ManagedReadRequest<GenericDataModel>\ntype Request = Omit<ExecutionRequest, 'db'>\ntype ExecutionSchema = SchemaDefinition<\n\tRecord<string, TableDefinition<any, Record<string, string[]>>>,\n\tboolean\n>\n\n/** Private shared boundary: only the established fixed typed errors are public. */\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Thrown values enter this error boundary untrusted; the class checks below admit only the fixed public error contracts.\nexport function rethrowQueryError(error: unknown): never {\n\tif (\n\t\terror instanceof SearchError ||\n\t\terror instanceof ManagedReadError ||\n\t\terror instanceof CursorError ||\n\t\terror instanceof RelationshipError\n\t)\n\t\tthrow error\n\t// Native/policy errors may contain traversal values or structured private data.\n\tthrow new Error('Query execution failed')\n}\n\nexport async function executeQuery(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: Request,\n\ttable: string,\n\tplan: Plan,\n\tplanner: ReturnType<typeof createPlanner>,\n\tcodec: Codec,\n\tbinding: CursorBinding,\n\tcomplete?: (\n\t\tdocument: Record<string, Value>,\n\t\tpermitted: boolean,\n\t) => Promise<Record<string, Value> | null>,\n) {\n\t// Authenticate BOTH navigation slots before constructing or consuming native queries.\n\tconst operationBinding =\n\t\tplan.args.cursor !== null || plan.args.endCursor != null\n\t\t\t? prepareCursorBinding(binding)\n\t\t\t: binding\n\tconst args = {\n\t\t...plan.args,\n\t\tcursor: plan.args.cursor === null ? null : codec.open(plan.args.cursor, operationBinding),\n\t\tendCursor:\n\t\t\tplan.args.endCursor == null\n\t\t\t\t? plan.args.endCursor\n\t\t\t\t: codec.open(plan.args.endCursor, operationBinding),\n\t}\n\treturn executeStream(\n\t\tschema,\n\t\trequest,\n\t\ttable,\n\t\tplan,\n\t\tplanner,\n\t\tcodec,\n\t\toperationBinding,\n\t\targs,\n\t\tcomplete,\n\t)\n}\n\nexport async function executeStream(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: Request,\n\ttable: string,\n\tplan: Plan,\n\tplanner: ReturnType<typeof createPlanner>,\n\tcodec: Codec,\n\tbinding: CursorBinding,\n\targs: NativePagination,\n\tcomplete?: (\n\t\tdocument: Record<string, Value>,\n\t\tpermitted: boolean,\n\t) => Promise<Record<string, Value> | null>,\n\tseal?: (raw: string, binding: CursorBinding) => string,\n\ttransform?: (\n\t\tsource: QueryStream<Record<string, Value>>,\n\t\tdb: GenericDatabaseReader<any>,\n\t) => QueryStream<Record<string, Value>>,\n\tauthorizationTable = table,\n) {\n\tconst leaves = leafReader(request, planner)\n\tconst progress: Progress = { completed: [] }\n\ttry {\n\t\t// SAFETY: runtime ownership/index validation precedes this dynamic table\n\t\t// adapter. Public generics retain the original application's schema.\n\t\tconst nativeSchema = schema as ExecutionSchema\n\t\tconst base = stream(leaves.db, nativeSchema).query(table)\n\t\tconst selected = plan.index\n\t\t\t? base.withIndex(plan.index.name, (q) => nativeIndexRange(q, plan.prefix, plan.range))\n\t\t\t: base\n\t\tconst order = plan.args.order ?? 'asc'\n\t\tconst expansion = plan.expansion\n\t\tconst ordered =\n\t\t\texpansion && plan.index && !plan.unsatisfiable\n\t\t\t\t? mergedStream(\n\t\t\t\t\t\texpansion.values.map((value) => {\n\t\t\t\t\t\t\tconst prefix = [...plan.prefix, { field: expansion.field, value }]\n\t\t\t\t\t\t\t// SAFETY: each stream binds the same admitted index at one consecutive position.\n\t\t\t\t\t\t\treturn base\n\t\t\t\t\t\t\t\t.withIndex(plan.index!.name, (q) =>\n\t\t\t\t\t\t\t\t\tnativeIndexRange(q, prefix, rangeForIndex(plan.index!, prefix, plan.ranges)),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.order(order)\n\t\t\t\t\t\t}),\n\t\t\t\t\t\texpansion.comparator === 'full-index'\n\t\t\t\t\t\t\t? getIndexFields(table, plan.index.name, nativeSchema)\n\t\t\t\t\t\t\t: getIndexFields(table, plan.index.name, nativeSchema).slice(plan.prefix.length + 1),\n\t\t\t\t\t)\n\t\t\t\t: selected.order(order)\n\t\tconst source = transform ? transform(ordered, leaves.db) : ordered\n\t\tconst result: EnginePaginationResult<Record<string, Value>> = plan.unsatisfiable\n\t\t\t? await new EmptyStream<Record<string, Value>>(\n\t\t\t\t\tsource.getOrder(),\n\t\t\t\t\tsource.getIndexFields(),\n\t\t\t\t\tsource.getEqualityIndexFilter(),\n\t\t\t\t).paginate(args)\n\t\t\t: await new EligibleStream(\n\t\t\t\t\tsource,\n\t\t\t\t\trequest,\n\t\t\t\t\tauthorizationTable,\n\t\t\t\t\tplan,\n\t\t\t\t\tplanner,\n\t\t\t\t\tprogress,\n\t\t\t\t\tcomplete,\n\t\t\t\t).paginate(args)\n\t\tconst sealBinding = result.splitCursor == null ? binding : prepareCursorBinding(binding)\n\t\tconst sealBoundary = (raw: string) =>\n\t\t\tseal ? seal(raw, sealBinding) : codec.seal(raw, sealBinding)\n\t\tconst protectedResult = {\n\t\t\t...result,\n\t\t\tcompleteness: result.completeness ?? 'complete',\n\t\t\tcontinueCursor: sealBoundary(result.continueCursor),\n\t\t}\n\t\tif (result.splitCursor != null) protectedResult.splitCursor = sealBoundary(result.splitCursor)\n\t\treturn protectedResult\n\t} catch (error) {\n\t\trethrowQueryError(error)\n\t} finally {\n\t\tawait leaves.close()\n\t}\n}\n\n/** Private adapter shared by root and relationship streams; the planner owns admission. */\nexport function nativeIndexRange(\n\tq: IndexRangeBuilder<any, string[], number>,\n\tprefix: readonly { field: string; value: FilterScalar }[],\n\tbounds: NativeRange | null,\n): import('convex/server').IndexRange {\n\tlet range = q\n\tfor (const { field, value } of prefix) {\n\t\t// SAFETY: every equality advances the validated consecutive native prefix.\n\t\trange = range.eq(field, value) as IndexRangeBuilder<any, string[], number>\n\t}\n\t// SAFETY: an equality builder also admits upper bounds; lower methods retain that interface.\n\tlet bounded = range as ReturnType<typeof range.gte>\n\tif (bounds?.lower) {\n\t\tconst { field, lower } = bounds\n\t\tbounded = lower.inclusive ? range.gte(field, lower.value) : range.gt(field, lower.value)\n\t}\n\tif (bounds?.upper) {\n\t\tconst { field, upper } = bounds\n\t\treturn upper.inclusive ? bounded.lte(field, upper.value) : bounded.lt(field, upper.value)\n\t}\n\treturn bounded\n}\n\n/** Retain the actual metered leaf, since the helper's public key iterator does\n * not forward return(). This private reader only constructs raw metered queries.\n */\nfunction leafReader(request: Request, planner: ReturnType<typeof createPlanner>) {\n\tconst active = new Set<AsyncIterator<GenericDocument>>()\n\tconst pending = new Set<Promise<IteratorResult<GenericDocument>>>()\n\tfunction wrap<Source extends AsyncIterable<GenericDocument>>(\n\t\ttable: string,\n\t\tsource: Source,\n\t): Source {\n\t\t// SAFETY: the empty proxy shell is private; supported methods forward to the real native source below.\n\t\treturn new Proxy({} as Source, {\n\t\t\tget(_target, key) {\n\t\t\t\tconst target = source\n\t\t\t\tif (key === 'withIndex' && 'withIndex' in target)\n\t\t\t\t\treturn (...args: Parameters<QueryInitializer<any>['withIndex']>) => {\n\t\t\t\t\t\t// SAFETY: the private facade forwards an existing native index constructor only.\n\t\t\t\t\t\tconst withIndex = target.withIndex as QueryInitializer<any>['withIndex']\n\t\t\t\t\t\treturn wrap(table, withIndex.apply(target, args))\n\t\t\t\t\t}\n\t\t\t\tif (key === 'order' && 'order' in target)\n\t\t\t\t\treturn (...args: Parameters<QueryInitializer<any>['order']>) => {\n\t\t\t\t\t\t// SAFETY: the private facade forwards the existing native order method only.\n\t\t\t\t\t\tconst order = target.order as QueryInitializer<any>['order']\n\t\t\t\t\t\treturn wrap(table, order.apply(target, args))\n\t\t\t\t\t}\n\t\t\t\tif (key === Symbol.asyncIterator)\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tconst iterator = target[Symbol.asyncIterator]()\n\t\t\t\t\t\tactive.add(iterator)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tnext: () => {\n\t\t\t\t\t\t\t\tplanner.beforeLeaf(table)\n\t\t\t\t\t\t\t\tconst next = iterator.next()\n\t\t\t\t\t\t\t\tpending.add(next)\n\t\t\t\t\t\t\t\tvoid next.then(\n\t\t\t\t\t\t\t\t\t() => pending.delete(next),\n\t\t\t\t\t\t\t\t\t() => pending.delete(next),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn next\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tthrow new Error('Unsupported private query operation')\n\t\t\t},\n\t\t})\n\t}\n\n\t// SAFETY: stream() uses only query to construct the indexed stream. The\n\t// request's authorized reader handles policy gets separately; never publish this facade.\n\tconst db = {\n\t\tquery: (table: string) => {\n\t\t\tplanner.beforeLeaf(table)\n\t\t\treturn wrap(table, request.leafQuery(table))\n\t\t},\n\t} as GenericDatabaseReader<any>\n\treturn {\n\t\tdb,\n\t\tasync close() {\n\t\t\tawait Promise.allSettled(pending)\n\t\t\tlet failed = false\n\t\t\tfor (const iterator of active) {\n\t\t\t\ttry {\n\t\t\t\t\tawait iterator.return?.()\n\t\t\t\t} catch {\n\t\t\t\t\tfailed = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tactive.clear()\n\t\t\tif (failed) throw new Error('Query execution failed')\n\t\t},\n\t}\n}\n\nfunction fetchStopReason(request: Request): 'row-budget' | 'byte-budget' | undefined {\n\tconst c = request.counters,\n\t\tb = request.budgets\n\t// Row checks precede byte reservation, matching the managed leaf admission order.\n\tif (c.readOperations >= b.readOperations || c.rawCandidates >= b.rawCandidates)\n\t\treturn 'row-budget'\n\tif (c.documentBytesObserved + c.documentBytesReserved + MAX_DOCUMENT_BYTES > b.documentBytes)\n\t\treturn 'byte-budget'\n\treturn undefined\n}\n\n/** Encoder-only use of public native pagination; no private cursor wire format,\n * artificial bandwidth, lookahead, or database read.\n */\nclass CapturedKey extends QueryStream<object> {\n\tconstructor(\n\t\tprivate readonly entry: Entry,\n\t\tprivate readonly source: QueryStream<Record<string, Value>>,\n\t) {\n\t\tsuper()\n\t}\n\tgetOrder() {\n\t\treturn this.source.getOrder()\n\t}\n\tgetIndexFields() {\n\t\treturn this.source.getIndexFields()\n\t}\n\tgetEqualityIndexFilter() {\n\t\treturn this.source.getEqualityIndexFilter()\n\t}\n\tnarrow(bounds: IndexBounds) {\n\t\tif (\n\t\t\tbounds.lowerBound.length ||\n\t\t\tbounds.upperBound.length ||\n\t\t\t!bounds.lowerBoundInclusive ||\n\t\t\t!bounds.upperBoundInclusive\n\t\t)\n\t\t\tthrow new Error('Invalid cursor encoder range')\n\t\treturn this\n\t}\n\tasync *iterWithKeys(): AsyncGenerator<[object, IndexKey, number], undefined> {\n\t\tyield [{}, this.entry[1], this.entry[2]]\n\t}\n}\n\ninterface Progress {\n\tcompleted: Entry[]\n\tstopReason?: PageCompleteness\n}\nclass EligibleStream extends QueryStream<Record<string, Value>> {\n\tconstructor(\n\t\tprivate readonly source: QueryStream<Record<string, Value>>,\n\t\tprivate readonly request: Request,\n\t\tprivate readonly table: string,\n\t\tprivate readonly plan: Plan,\n\t\tprivate readonly planner: ReturnType<typeof createPlanner>,\n\t\tprivate readonly progress: Progress,\n\t\tprivate readonly complete?: (\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t) => Promise<Record<string, Value> | null>,\n\t) {\n\t\tsuper()\n\t}\n\tgetOrder() {\n\t\treturn this.source.getOrder()\n\t}\n\tgetIndexFields() {\n\t\treturn this.source.getIndexFields()\n\t}\n\tgetEqualityIndexFilter() {\n\t\treturn this.source.getEqualityIndexFilter()\n\t}\n\tnarrow(bounds: IndexBounds): QueryStream<Record<string, Value>> {\n\t\treturn new EligibleStream(\n\t\t\tthis.source.narrow(bounds),\n\t\t\tthis.request,\n\t\t\tthis.table,\n\t\t\tthis.plan,\n\t\t\tthis.planner,\n\t\t\tthis.progress,\n\t\t\tthis.complete,\n\t\t)\n\t}\n\tasync *iterWithKeys(): AsyncGenerator<Entry, undefined> {\n\t\t// Always request actual root bandwidth, even without a native byte option.\n\t\tconst iterator = this.source.iterWithKeys(true)[Symbol.asyncIterator]()\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst reason = fetchStopReason(this.request)\n\t\t\t\tif (reason) {\n\t\t\t\t\tif (!this.progress.completed.length) throw new ManagedReadError('MANAGED_READ_BUDGET')\n\t\t\t\t\tthis.progress.stopReason = reason\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlet next: IteratorResult<Entry>\n\t\t\t\tconst candidatesBefore = this.request.counters.rawCandidates\n\t\t\t\ttry {\n\t\t\t\t\tnext = await iterator.next()\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A reservation failure BEFORE the next root is safe to stop at\n\t\t\t\t\t// completed progress. Authorization errors below are never partialized.\n\t\t\t\t\tif (\n\t\t\t\t\t\terror instanceof ManagedReadError &&\n\t\t\t\t\t\terror.code === 'MANAGED_READ_BUDGET' &&\n\t\t\t\t\t\tthis.request.leafBudgetFailure(error) &&\n\t\t\t\t\t\tthis.progress.completed.length &&\n\t\t\t\t\t\tthis.request.counters.rawCandidates === candidatesBefore\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.progress.stopReason = this.request.leafBudgetFailure(error)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t\tif (next.done) return\n\t\t\t\tconst [document, key, bytes] = next.value\n\t\t\t\tlet output: Record<string, Value> | null = null\n\t\t\t\tif (document) {\n\t\t\t\t\t// SAFETY: metered native stream documents contain their system IDs.\n\t\t\t\t\tconst permitted = await this.request.authorize(this.table, document as GenericDocument)\n\t\t\t\t\t// SAFETY: the registry DTO validates declared public native values only.\n\t\t\t\t\toutput = this.complete\n\t\t\t\t\t\t? await this.complete(document, permitted)\n\t\t\t\t\t\t: (this.planner.complete(this.table, document, permitted, this.plan.residual) as Record<\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\tValue\n\t\t\t\t\t\t\t> | null)\n\t\t\t\t}\n\t\t\t\t// Complete policy, residual, and required DTO before recording the key.\n\t\t\t\tconst entry: Entry = [output, key, bytes]\n\t\t\t\tthis.progress.completed.push(entry)\n\t\t\t\tyield entry\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.()\n\t\t}\n\t}\n\toverride async paginate(\n\t\targs: NativePagination,\n\t): Promise<EnginePaginationResult<Record<string, Value>>> {\n\t\tconst result = await super.paginate(args)\n\t\tconst completed = this.progress.completed\n\t\tconst encode = async (entry: Entry) =>\n\t\t\t(\n\t\t\t\tawait new CapturedKey(entry, this.source).paginate({\n\t\t\t\t\tnumItems: 1,\n\t\t\t\t\tcursor: null,\n\t\t\t\t})\n\t\t\t).continueCursor\n\t\tconst fulfilled = args.endCursor\n\t\t\t? !!completed.length && (await encode(completed.at(-1)!)) === args.endCursor\n\t\t\t: result.page.length >= args.numItems\n\t\tif (\n\t\t\tthis.request.atomicCompletion &&\n\t\t\t((this.progress.stopReason && !fulfilled) ||\n\t\t\t\t(result.pageStatus === 'SplitRequired' && !fulfilled))\n\t\t)\n\t\t\tthrow new ManagedReadError('MANAGED_READ_BUDGET')\n\t\tif (!this.progress.stopReason)\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\t// A helper limit can coincide with the requested final row. That page\n\t\t\t\t// is fulfilled; preserve the native split/isDone/cursor metadata separately.\n\t\t\t\tcompleteness:\n\t\t\t\t\tresult.pageStatus === 'SplitRequired' && !fulfilled ? 'native-limit' : 'complete',\n\t\t\t}\n\t\tif (!completed.length) throw new ManagedReadError('MANAGED_READ_BUDGET')\n\t\tconst continuation = await encode(completed.at(-1)!)\n\t\treturn {\n\t\t\t...result,\n\t\t\tcompleteness: fulfilled ? 'complete' : this.progress.stopReason,\n\t\t\tisDone: false,\n\t\t\tpageStatus: 'SplitRequired',\n\t\t\tcontinueCursor: continuation,\n\t\t\tsplitCursor: await encode(completed[Math.floor((completed.length - 1) / 2)]),\n\t\t}\n\t}\n}\n"],"mappings":"A,uYAkDA,SAAgBA,EAAkB,EAAuB,CASxD,MAPCC,aAAiBC,GACjBD,aAAiBE,GACjBF,aAAiBG,GACjBH,aAAiBI,EAEXJ,EAEG,MAAM,wBAAwB,CACzC,CAEA,eAAsBK,EACrB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAIC,CAED,IAAMC,EACLC,EAAK,KAAK,SAAW,MAAQA,EAAK,KAAK,WAAa,KACjDC,EAAqBC,CAAO,EAC5BA,EASJ,OAAOC,EACNC,EACAC,EACAC,EACAN,EACAO,EACAC,EACAT,EACA,CAfA,GAAGC,EAAK,KACR,OAAQA,EAAK,KAAK,SAAW,KAAO,KAAOQ,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,CAACoC,EAAU,QAAW,MAAMC,EAAOD,EAAU,GAAG,EAAE,CAAE,IAAOpC,EAAK,UACjEF,EAAO,KAAK,QAAUE,EAAK,SAC9B,GACC,KAAK,QAAQ,mBACX,KAAK,SAAS,YAAc,CAACsC,GAC7BxC,EAAO,aAAe,iBAAmB,CAACwC,GAE5C,MAAM,IAAIzE,EAAiB,qBAAqB,EACjD,GAAI,CAAC,KAAK,SAAS,WAClB,MAAO,CACN,GAAGiC,EAGH,aACCA,EAAO,aAAe,iBAAmB,CAACwC,EAAY,eAAiB,UACzE,EACD,GAAI,CAACF,EAAU,OAAQ,MAAM,IAAIvE,EAAiB,qBAAqB,EACvE,IAAM0E,EAAe,MAAMF,EAAOD,EAAU,GAAG,EAAE,CAAE,EACnD,MAAO,CACN,GAAGtC,EACH,aAAcwC,EAAY,WAAa,KAAK,SAAS,WACrD,OAAQ,GACR,WAAY,gBACZ,eAAgBC,EAChB,YAAa,MAAMF,EAAOD,EAAU,KAAK,OAAOA,EAAU,OAAS,GAAK,CAAC,EAAE,CAC5E,CACD,CACD,E"}
@@ -0,0 +1,11 @@
1
+ import { queryErrors } from "../modules/contracts/errors.mjs";
2
+ /**
3
+ * Explicit endpoint adapter for the query.errors policy in createEffectAuthFunctions.
4
+ * Promise handlers must use Effect.tryPromise({ try: () => engine(ctx).table.paginate(args), catch: error => error })
5
+ * so native failures enter the expected-error channel; ordinary throws/rejections remain defects.
6
+ * Ordinary authQuery handlers can throw new ConvexError(queryFailureContract.project(error)) in their catch.
7
+ * Do not throw an already-transported ConvexError inside an Effect builder with a different errors policy:
8
+ * that policy intentionally normalizes foreign failures. Direct engine callers keep their native errors.
9
+ */
10
+ export declare const queryFailureContract: typeof queryErrors;
11
+ //# sourceMappingURL=failures.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{queryErrors as e}from"../modules/contracts/errors.mjs";import{SearchError as t}from"./search.mjs";import{CursorError as n}from"./cursors.mjs";import{FieldGroupError as r}from"../querying.mjs";import{isQueryFanoutError as i}from"./filters.mjs";const a={...e,project(a){try{return a instanceof t?e.project(e.create(a.code,{})):a instanceof n?e.project(e.create(`invalid-cursor`,{})):a instanceof r?e.project(e.create(`FIELD_GROUP_DENIED`,{})):i(a)?e.project(e.create(`QUERY_FANOUT`,{})):e.project(a)}catch{return{_tag:`UnknownFailure`,version:1}}}};export{a as queryFailureContract};
2
+ //# sourceMappingURL=failures.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"failures.mjs","names":["queryFailureContract","queryErrors","error","SearchError","CursorError","FieldGroupError","isQueryFanoutError"],"sources":["../../src/querying/failures.ts"],"sourcesContent":["import { queryErrors } from '../modules/contracts/errors'\nimport { SearchError } from './search'\nimport { CursorError } from './cursors'\nimport { FieldGroupError } from '../querying'\nimport { isQueryFanoutError } from './filters'\n\n/**\n * Explicit endpoint adapter for the query.errors policy in createEffectAuthFunctions.\n * Promise handlers must use Effect.tryPromise({ try: () => engine(ctx).table.paginate(args), catch: error => error })\n * so native failures enter the expected-error channel; ordinary throws/rejections remain defects.\n * Ordinary authQuery handlers can throw new ConvexError(queryFailureContract.project(error)) in their catch.\n * Do not throw an already-transported ConvexError inside an Effect builder with a different errors policy:\n * that policy intentionally normalizes foreign failures. Direct engine callers keep their native errors.\n */\nexport const queryFailureContract: typeof queryErrors = {\n\t...queryErrors,\n\tproject(error) {\n\t\ttry {\n\t\t\tif (error instanceof SearchError)\n\t\t\t\treturn queryErrors.project(queryErrors.create(error.code, {}))\n\t\t\tif (error instanceof CursorError)\n\t\t\t\treturn queryErrors.project(queryErrors.create('invalid-cursor', {}))\n\t\t\tif (error instanceof FieldGroupError)\n\t\t\t\treturn queryErrors.project(queryErrors.create('FIELD_GROUP_DENIED', {}))\n\t\t\tif (isQueryFanoutError(error))\n\t\t\t\treturn queryErrors.project(queryErrors.create('QUERY_FANOUT', {}))\n\t\t\treturn queryErrors.project(error)\n\t\t} catch {\n\t\t\treturn { _tag: 'UnknownFailure', version: 1 }\n\t\t}\n\t},\n}\n"],"mappings":"A,0PAcA,MAAaA,EAA2C,CACvD,GAAGC,EACH,QAAQ,EAAO,CACd,GAAI,CASH,OARIC,aAAiBC,EACbF,EAAY,QAAQA,EAAY,OAAOC,EAAM,KAAM,CAAC,CAAC,CAAC,EAC1DA,aAAiBE,EACbH,EAAY,QAAQA,EAAY,OAAO,iBAAkB,CAAC,CAAC,CAAC,EAChEC,aAAiBG,EACbJ,EAAY,QAAQA,EAAY,OAAO,qBAAsB,CAAC,CAAC,CAAC,EACpEK,EAAmBJ,CAAK,EACpBD,EAAY,QAAQA,EAAY,OAAO,eAAgB,CAAC,CAAC,CAAC,EAC3DA,EAAY,QAAQC,CAAK,CACjC,MAAQ,CACP,MAAO,CAAE,KAAM,iBAAkB,QAAS,CAAE,CAC7C,CACD,CACD,E"}
@@ -0,0 +1,25 @@
1
+ import { KType } from "../k/types.mjs";
2
+ import "../k.mjs";
3
+ import { GenericValidator } from "convex/values";
4
+ /** Private projection. The caller must install the captured semantic preflight. */
5
+ export declare function compactNativeFilter(schema: KType): GenericValidator | undefined;
6
+ /**
7
+ * Conversion and preflight are one registration decision. `validator` is what Convex receives: the
8
+ * declared args with each compact filter projected; `preflight` runs the full structural walker
9
+ * (KTD3) on exactly those projected filters, before customization, and raises the KTD6 error.
10
+ */
11
+ export interface ArgumentBoundary {
12
+ readonly validator: Extract<GenericValidator, {
13
+ kind: 'object';
14
+ }>;
15
+ preflight(value: unknown): void;
16
+ }
17
+ /**
18
+ * The compact projection of an args object, or undefined when no field holds a compact filter.
19
+ * `fields` are the `k` argument fields; `full` builds the native args validator, which may also hold
20
+ * native fields beside them. Args without a compact filter build no native validator here.
21
+ */
22
+ export declare function compactArgumentBoundary(fields: Readonly<Record<string, KType>>, full: () => Extract<GenericValidator, {
23
+ kind: 'object';
24
+ }>): ArgumentBoundary | undefined;
25
+ //# sourceMappingURL=filter-boundary.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{KValidationError as e}from"../k/issues.mjs";import{compactFilterMetadata as t}from"./shared/filters.mjs";import{v as n}from"convex/values";import{vRequired as r}from"convex-helpers/validators";function i(e){let r=t(e);if(!r)return;let i=/* @__PURE__ */ new WeakMap,a=/* @__PURE__ */ new WeakMap;function o(e){let t=a.get(e);if(t)return t;let n=Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,t.validator]));return a.set(e,n),n}function s(e,t){return Object.values(o(e)).some(f)?!0:t<4&&(Object.values(e.relations).some(e=>s(e.target,t+1))||Object.values(e.variants?.options??{}).some(e=>s(e,t+1)))}function c(e,t){let r=i.get(e)?.get(t);if(r)return r;if(t>1&&!s(e,t))return n.any();let a=Object.fromEntries(Object.entries(o(e)).map(([e,r])=>[e,t<=1||f(r)?r:r.isOptional===`optional`?n.optional(n.any()):n.any()])),l={...Object.fromEntries(Object.entries(a).filter(([t])=>![`and`,`or`,`not`,`fields`,...e.variants?[`variant`]:[]].includes(t))),fields:n.optional(n.object(a))};if(t<4){for(let[r,i]of Object.entries(e.relations)){let e=c(i.target,t+1);l[r]=n.optional(i.cardinality===`one`?n.union(e,n.null()):n.union(n.object({some:e}),n.object({none:e})))}e.variants&&Object.keys(e.variants.options).length&&(l.variant=n.optional(n.union(...Object.entries(e.variants.options).map(([e,r])=>n.object({tag:n.literal(e),filters:c(r,t+1)})))));let r=c(e,t+1);l.and=n.optional(n.array(r)),l.or=n.optional(n.array(r)),l.not=n.optional(r)}let u=n.object(l),d=i.get(e);return d||(d=/* @__PURE__ */ new Map,i.set(e,d)),d.set(t,u),u}function l(e,t){return Object.values(o(e)).every(d)&&(t===4||Object.values(e.relations).every(e=>l(e.target,t+1))&&Object.values(e.variants?.options??{}).every(e=>l(e,t+1)))}return l(r.grammar,0)?c(r.grammar,0):void 0}function a(a,c){if(!Object.values(a).some(e=>s(e,/* @__PURE__ */ new Set)))return;let d=/* @__PURE__ */ new WeakMap;function f(a,s){let c=d.get(a);if(c)return c;let p=t(a),m=p&&i(a),h={validator:s};if(m&&p)h={validator:m,guard:(t,n)=>{let r=p.semantic.safeParse(t);if(!r.success)throw new e(r.issues.map(e=>({...e,path:[...n,...e.path]})))}};else if((a.op===`optional`||a.op===`partial`)&&a.prev!==null){let e=f(u(a.prev),r(s));e.guard&&(h={validator:n.optional(e.validator),guard:(t,n)=>{t!==void 0&&e.guard(t,n)}})}else if(s.kind===`object`){let e=l(a);e&&(h=o(e,s,f)??h)}return d.set(a,h),h}let p=o(a,c(),f);if(!p?.guard)return;let m=p.guard;if(p.validator.kind!==`object`)throw Error(`Expected object argument boundary`);return{validator:p.validator,preflight(e){m(e,[])}}}function o(e,t,r){let i=Object.entries(e).map(([e,n])=>[e,r(n,t.fields[e])]);if(i.some(([,e])=>e.guard))return{validator:n.object({...t.fields,...Object.fromEntries(i.map(([e,t])=>[e,t.validator]))}),guard:(e,t)=>{(e===null||Object(e)!==e||Array.isArray(e))&&c(t);let n=e,r=Object.getPrototypeOf(n);r!==Object.prototype&&r!==null&&c(t);for(let[e,r]of i)if(r.guard){let i=Object.getOwnPropertyDescriptor(n,e);!i||`value`in i&&i.enumerable||c([...t,e]),!i&&e in n&&c([...t,e]),r.guard(i?.value,[...t,e])}}}}function s(e,n){if(n.has(e))return!1;if(n.add(e),t(e))return!0;if((e.op===`optional`||e.op===`partial`)&&e.prev!==null)return s(u(e.prev),n);let r=l(e);return r!==void 0&&Object.values(r).some(e=>s(e,n))}function c(t){throw new e([{code:`custom`,path:t,message:`Unsupported filter layout or depth/node budget exceeded`}])}function l(e){let t=e;for(;t.prev!==null;){if(![`describe`,`refine`,`check`,`strip`].includes(t.op))return;t=u(t.prev)}if(t.op===`object`)return t.arg}function u(e){return e}function d(e){switch(e.kind){case`union`:return e.members.every(d);case`object`:return Object.values(e.fields).every(d);case`array`:return d(e.element);case`id`:case`string`:case`float64`:case`int64`:case`boolean`:case`null`:case`literal`:return!0;default:return!1}}function f(e){switch(e.kind){case`id`:return!0;case`union`:return e.members.some(f);case`object`:return Object.values(e.fields).some(f);case`array`:return f(e.element);default:return!1}}export{a as compactArgumentBoundary,i as compactNativeFilter};
2
+ //# sourceMappingURL=filter-boundary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter-boundary.mjs","names":["compactNativeFilter","metadata","compactFilterMetadata","schema","completed","predicates","fields","cached","grammar","result","key","needsIds","hasId","depth","r","g","expression","v","selected","value","properties","name","relation","target","tag","branch","child","depths","known","knownNative","compactArgumentBoundary","holdsCompactFilter","field","visit","node","projected","native","parsed","KValidationError","issue","path","schemaOf","vRequired","memberFields","objectFields","objectPair","pair","full","guard","children","layoutError","object","prototype","descriptor","seen","current","validator"],"sources":["../../src/querying/filter-boundary.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters -- The preflight receives raw registered arguments before any schema has decoded them. */\nimport { v, type GenericValidator, type PropertyValidators } from 'convex/values'\nimport { vRequired } from 'convex-helpers/validators'\nimport { KValidationError, type KPath, type KType } from '../k'\nimport { compactFilterMetadata, MAX_FILTER_DEPTH, type FilterGrammar } from './shared/filters'\n\n/** Private projection. The caller must install the captured semantic preflight. */\nexport function compactNativeFilter(schema: KType): GenericValidator | undefined {\n\tconst metadata = compactFilterMetadata(schema)\n\tif (!metadata) return undefined\n\tconst completed = new WeakMap<FilterGrammar, Map<number, GenericValidator>>()\n\tconst predicates = new WeakMap<FilterGrammar, PropertyValidators>()\n\tfunction fields(grammar: FilterGrammar): PropertyValidators {\n\t\tconst cached = predicates.get(grammar)\n\t\tif (cached) return cached\n\t\tconst result = Object.fromEntries(\n\t\t\tObject.entries(grammar.fields).map(([key, schema]) => [key, schema.validator]),\n\t\t)\n\t\tpredicates.set(grammar, result)\n\t\treturn result\n\t}\n\tfunction needsIds(grammar: FilterGrammar, depth: number): boolean {\n\t\tif (Object.values(fields(grammar)).some(hasId)) return true\n\t\treturn (\n\t\t\tdepth < MAX_FILTER_DEPTH &&\n\t\t\t(Object.values(grammar.relations).some((r) => needsIds(r.target, depth + 1)) ||\n\t\t\t\tObject.values(grammar.variants?.options ?? {}).some((g) => needsIds(g, depth + 1)))\n\t\t)\n\t}\n\tfunction expression(grammar: FilterGrammar, depth: number): GenericValidator {\n\t\tconst cached = completed.get(grammar)?.get(depth)\n\t\tif (cached) return cached\n\t\tif (depth > 1 && !needsIds(grammar, depth)) return v.any()\n\t\tconst selected = Object.fromEntries(\n\t\t\tObject.entries(fields(grammar)).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\tdepth <= 1 || hasId(value)\n\t\t\t\t\t? value\n\t\t\t\t\t: value.isOptional === 'optional'\n\t\t\t\t\t\t? v.optional(v.any())\n\t\t\t\t\t\t: v.any(),\n\t\t\t]),\n\t\t)\n\t\tconst direct = Object.fromEntries(\n\t\t\tObject.entries(selected).filter(\n\t\t\t\t([key]) =>\n\t\t\t\t\t!['and', 'or', 'not', 'fields', ...(grammar.variants ? ['variant'] : [])].includes(key),\n\t\t\t),\n\t\t)\n\t\tconst properties: PropertyValidators = { ...direct, fields: v.optional(v.object(selected)) }\n\t\tif (depth < MAX_FILTER_DEPTH) {\n\t\t\tfor (const [name, relation] of Object.entries(grammar.relations)) {\n\t\t\t\tconst target = expression(relation.target, depth + 1)\n\t\t\t\tproperties[name] = v.optional(\n\t\t\t\t\trelation.cardinality === 'one'\n\t\t\t\t\t\t? v.union(target, v.null())\n\t\t\t\t\t\t: v.union(v.object({ some: target }), v.object({ none: target })),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (grammar.variants && Object.keys(grammar.variants.options).length)\n\t\t\t\tproperties.variant = v.optional(\n\t\t\t\t\tv.union(\n\t\t\t\t\t\t...Object.entries(grammar.variants.options).map(([tag, branch]) =>\n\t\t\t\t\t\t\tv.object({ tag: v.literal(tag), filters: expression(branch, depth + 1) }),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\tconst child = expression(grammar, depth + 1)\n\t\t\tproperties.and = v.optional(v.array(child))\n\t\t\tproperties.or = v.optional(v.array(child))\n\t\t\tproperties.not = v.optional(child)\n\t\t}\n\t\tconst result = v.object(properties)\n\t\tlet depths = completed.get(grammar)\n\t\tif (!depths) {\n\t\t\tdepths = new Map()\n\t\t\tcompleted.set(grammar, depths)\n\t\t}\n\t\tdepths.set(depth, result)\n\t\treturn result\n\t}\n\tfunction known(grammar: FilterGrammar, depth: number): boolean {\n\t\treturn (\n\t\t\tObject.values(fields(grammar)).every(knownNative) &&\n\t\t\t(depth === MAX_FILTER_DEPTH ||\n\t\t\t\t(Object.values(grammar.relations).every((relation) => known(relation.target, depth + 1)) &&\n\t\t\t\t\tObject.values(grammar.variants?.options ?? {}).every((branch) =>\n\t\t\t\t\t\tknown(branch, depth + 1),\n\t\t\t\t\t)))\n\t\t)\n\t}\n\treturn known(metadata.grammar, 0) ? expression(metadata.grammar, 0) : undefined\n}\n\n/**\n * Conversion and preflight are one registration decision. `validator` is what Convex receives: the\n * declared args with each compact filter projected; `preflight` runs the full structural walker\n * (KTD3) on exactly those projected filters, before customization, and raises the KTD6 error.\n */\nexport interface ArgumentBoundary {\n\treadonly validator: Extract<GenericValidator, { kind: 'object' }>\n\tpreflight(value: unknown): void\n}\n\n/**\n * The compact projection of an args object, or undefined when no field holds a compact filter.\n * `fields` are the `k` argument fields; `full` builds the native args validator, which may also hold\n * native fields beside them. Args without a compact filter build no native validator here.\n */\nexport function compactArgumentBoundary(\n\tfields: Readonly<Record<string, KType>>,\n\tfull: () => Extract<GenericValidator, { kind: 'object' }>,\n): ArgumentBoundary | undefined {\n\tif (!Object.values(fields).some((field) => holdsCompactFilter(field, new Set()))) return undefined\n\ttype Guard = (value: unknown, path: KPath) => void\n\tinterface Pair {\n\t\tvalidator: GenericValidator\n\t\tguard?: Guard\n\t}\n\tconst completed = new WeakMap<KType, Pair>()\n\tfunction visit(node: KType, native: GenericValidator): Pair {\n\t\tconst cached = completed.get(node)\n\t\tif (cached) return cached\n\t\tconst metadata = compactFilterMetadata(node)\n\t\tconst projected = metadata && compactNativeFilter(node)\n\t\tlet result: Pair = { validator: native }\n\t\tif (projected && metadata) {\n\t\t\tresult = {\n\t\t\t\tvalidator: projected,\n\t\t\t\tguard: (value, path) => {\n\t\t\t\t\tconst parsed = metadata.semantic.safeParse(value)\n\t\t\t\t\tif (!parsed.success)\n\t\t\t\t\t\tthrow new KValidationError(\n\t\t\t\t\t\t\tparsed.issues.map((issue) => ({ ...issue, path: [...path, ...issue.path] })),\n\t\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t}\n\t\t} else if ((node.op === 'optional' || node.op === 'partial') && node.prev !== null) {\n\t\t\tconst child = visit(schemaOf(node.prev), vRequired(native))\n\t\t\tif (child.guard)\n\t\t\t\tresult = {\n\t\t\t\t\tvalidator: v.optional(child.validator),\n\t\t\t\t\tguard: (value, path) => {\n\t\t\t\t\t\tif (value !== undefined) child.guard!(value, path)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t} else if (native.kind === 'object') {\n\t\t\tconst memberFields = objectFields(node)\n\t\t\tif (memberFields) result = objectPair(memberFields, native, visit) ?? result\n\t\t}\n\t\tcompleted.set(node, result)\n\t\treturn result\n\t}\n\tconst pair = objectPair(fields, full(), visit)\n\tif (!pair?.guard) return undefined\n\tconst guard = pair.guard\n\tif (pair.validator.kind !== 'object') throw new Error('Expected object argument boundary')\n\treturn {\n\t\tvalidator: pair.validator,\n\t\tpreflight(value) {\n\t\t\tguard(value, [])\n\t\t},\n\t}\n}\n\n/** The pair for an object whose `k` fields are `memberFields`; native-only fields keep their validators. */\nfunction objectPair(\n\tmemberFields: Readonly<Record<string, KType>>,\n\tnative: Extract<GenericValidator, { kind: 'object' }>,\n\tvisit: (\n\t\tnode: KType,\n\t\tnative: GenericValidator,\n\t) => { validator: GenericValidator; guard?: (value: unknown, path: KPath) => void },\n) {\n\tconst children = Object.entries(memberFields).map(\n\t\t([key, child]) => [key, visit(child, native.fields[key])] as const,\n\t)\n\tif (!children.some(([, child]) => child.guard)) return undefined\n\treturn {\n\t\tvalidator: v.object({\n\t\t\t...native.fields,\n\t\t\t...Object.fromEntries(children.map(([key, child]) => [key, child.validator])),\n\t\t}),\n\t\tguard: (value: unknown, path: KPath) => {\n\t\t\tif (value === null || Object(value) !== value || Array.isArray(value)) layoutError(path)\n\t\t\t// SAFETY: the boxing check above excludes primitive argument containers.\n\t\t\tconst object = value as object\n\t\t\tconst prototype = Object.getPrototypeOf(object)\n\t\t\tif (prototype !== Object.prototype && prototype !== null) layoutError(path)\n\t\t\tfor (const [key, child] of children)\n\t\t\t\tif (child.guard) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key)\n\t\t\t\t\tif (descriptor && (!('value' in descriptor) || !descriptor.enumerable))\n\t\t\t\t\t\tlayoutError([...path, key])\n\t\t\t\t\tif (!descriptor && key in object) layoutError([...path, key])\n\t\t\t\t\tchild.guard(descriptor?.value, [...path, key])\n\t\t\t\t}\n\t\t},\n\t}\n}\n\n/** Whether a compact filter sits in `node`, through the optional and object records `visit` follows. */\nfunction holdsCompactFilter(node: KType, seen: Set<KType>): boolean {\n\tif (seen.has(node)) return false\n\tseen.add(node)\n\tif (compactFilterMetadata(node)) return true\n\tif ((node.op === 'optional' || node.op === 'partial') && node.prev !== null)\n\t\treturn holdsCompactFilter(schemaOf(node.prev), seen)\n\tconst memberFields = objectFields(node)\n\treturn (\n\t\tmemberFields !== undefined &&\n\t\tObject.values(memberFields).some((child) => holdsCompactFilter(child, seen))\n\t)\n}\n\nfunction layoutError(path: KPath): never {\n\tthrow new KValidationError([\n\t\t{ code: 'custom', path, message: 'Unsupported filter layout or depth/node budget exceeded' },\n\t])\n}\n\n/** The field map of an object schema, through validation-only records chained on its root. */\nfunction objectFields(schema: KType): Readonly<Record<string, KType>> | undefined {\n\tlet current: KType = schema\n\twhile (current.prev !== null) {\n\t\tif (!['describe', 'refine', 'check', 'strip'].includes(current.op)) return undefined\n\t\tcurrent = schemaOf(current.prev)\n\t}\n\tif (current.op !== 'object') return undefined\n\t// SAFETY: k.object stores its field map as the root argument.\n\treturn current.arg as Readonly<Record<string, KType>>\n}\n\nfunction schemaOf(node: KType['prev'] & object): KType {\n\t// SAFETY: every record reachable from a k schema was created by a k factory.\n\treturn node as KType\n}\n\nfunction knownNative(validator: GenericValidator): boolean {\n\tswitch (validator.kind) {\n\t\tcase 'union':\n\t\t\treturn validator.members.every(knownNative)\n\t\tcase 'object':\n\t\t\treturn Object.values(validator.fields).every(knownNative)\n\t\tcase 'array':\n\t\t\treturn knownNative(validator.element)\n\t\tcase 'id':\n\t\tcase 'string':\n\t\tcase 'float64':\n\t\tcase 'int64':\n\t\tcase 'boolean':\n\t\tcase 'null':\n\t\tcase 'literal':\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\nfunction hasId(validator: GenericValidator): boolean {\n\tswitch (validator.kind) {\n\t\tcase 'id':\n\t\t\treturn true\n\t\tcase 'union':\n\t\t\treturn validator.members.some(hasId)\n\t\tcase 'object':\n\t\t\treturn Object.values(validator.fields).some(hasId)\n\t\tcase 'array':\n\t\t\treturn hasId(validator.element)\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n"],"mappings":"A,wMAOA,SAAgBA,EAAoB,EAA6C,CAChF,IAAMC,EAAWC,EAAsBC,CAAM,EAC7C,GAAI,CAACF,EAAU,OACf,IAAMG,kBAAY,IAAI,QAChBC,kBAAa,IAAI,QACvB,SAASC,EAAO,EAA4C,CAC3D,IAAMC,EAASF,EAAW,IAAIG,CAAO,EACrC,GAAID,EAAQ,OAAOA,EACnB,IAAME,EAAS,OAAO,YACrB,OAAO,QAAQD,EAAQ,MAAM,CAAC,CAAC,KAAK,CAACE,EAAKP,KAAY,CAACO,EAAKP,EAAO,SAAS,CAAC,CAC9E,EAEA,OADAE,EAAW,IAAIG,EAASC,CAAM,EACvBA,CACR,CACA,SAASE,EAAS,EAAwB,EAAwB,CAEjE,OADI,OAAO,OAAOL,EAAOE,CAAO,CAAC,CAAC,CAAC,KAAKI,CAAK,EAAU,GAEtDC,EAAA,IACC,OAAO,OAAOL,EAAQ,SAAS,C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