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,100 @@
1
+ import { KIssueInput, KSafeParseResult } from "./issues.mjs";
2
+ import { KPlan } from "./parse.mjs";
3
+ import { KArg, KMessage, KNode, KOp, KOutputRequired, KRefineOptions, KRequiredValidator, KType, OutputNativeOf } from "./types.mjs";
4
+ import { GenericValidator, VAny, VNull, VUnion } from "convex/values";
5
+ import { StandardSchemaV1 } from "@standard-schema/spec";
6
+ /**
7
+ * An immutable chain record. A root has `prev === null` and a kind op; every chained call allocates one
8
+ * record pointing at its predecessor. Nothing is compiled until `validator`, `outputValidator` or a
9
+ * parse first needs it; each product is memoised in its own pre-declared slot.
10
+ *
11
+ * Type arguments: `Out` the parsed output, `R` the required native validator, `D` whether a default or
12
+ * transform sits inside, `N` the input-side native validator (`R` unless the chain is optional or
13
+ * defaulted), `T` whether a transform or pipe sits inside.
14
+ */
15
+ export declare abstract class KSchema<Out = any, R extends KRequiredValidator = KRequiredValidator, D extends boolean = false, N extends GenericValidator = R, T extends boolean = false> implements KType {
16
+ readonly _output: Out;
17
+ readonly _input: N['type'];
18
+ readonly _req: R;
19
+ readonly _d: D;
20
+ readonly _t: T;
21
+ /** Required output-side native validator; read only when `D` is true. */
22
+ readonly _or: KRequiredValidator;
23
+ /** Output-side native validator; read only when `D` is true. */
24
+ readonly _oo: GenericValidator;
25
+ readonly prev: KNode | null;
26
+ readonly op: KOp;
27
+ readonly arg: KArg;
28
+ readonly message: KMessage;
29
+ /** Memo slot for the input-side native validator. */
30
+ native: GenericValidator | undefined;
31
+ /** Memo slot for the output-side native validator. */
32
+ outputNative: GenericValidator | undefined;
33
+ /** Memo slot for the parse plan. */
34
+ plan: KPlan | undefined;
35
+ constructor(prev: KNode | null, op: KOp, arg: KArg, message: KMessage);
36
+ get validator(): N;
37
+ get outputValidator(): D extends true ? this['_oo'] : N;
38
+ optional(): KOptional<this>;
39
+ nullable(): KNullable<this>;
40
+ default(value: Exclude<Out, undefined>): KDefault<this>;
41
+ /** A check on the parsed value; `options.path` attaches the issue below this value (object refinements). */
42
+ refine(check: (value: Out) => boolean, message?: string | KRefineOptions): this;
43
+ /** A check that may add several issues through `context.addIssue`. */
44
+ check(check: (value: Out, context: KCheckContext) => void): this;
45
+ /** A type-preserving normaliser; allowed everywhere, including table fields. */
46
+ overwrite(normalise: (value: Out) => Out): this;
47
+ /** A type-changing step. Produces a distinct kind that table fields and return shapes reject. */
48
+ transform<O>(map: (value: Out) => O): KTransform<this, O>;
49
+ /** Parse this schema's output with `target`. Produces a distinct kind, like `transform`. */
50
+ pipe<P extends KType>(target: P): KPipe<this, P>;
51
+ parse(input: unknown): Out;
52
+ safeParse(input: unknown): KSafeParseResult<Out>;
53
+ /** A description for JSON Schema and tooling; it changes neither the validators nor parsing. */
54
+ describe(text: string): this;
55
+ /** The nearest description declared on this chain. */
56
+ get description(): string | undefined;
57
+ /** Standard Schema v1, so contracts and form libraries consume `k` schemas directly. */
58
+ get '~standard'(): StandardSchemaV1.Props<N['type'], Out>;
59
+ protected link(op: KOp, arg: KArg, message: KMessage): this;
60
+ protected wrapped<W>(op: KOp): W;
61
+ }
62
+ /** The context handed to `.check()`; `addIssue` may be called any number of times. */
63
+ export interface KCheckContext {
64
+ addIssue(issue: KIssueInput): void;
65
+ }
66
+ declare global {
67
+ /**
68
+ * Methods that optional cvx-kit entries add to every `k` schema; `cvx-kit/zod` adds `toZod()`. Empty
69
+ * in core, so core declarations never name an optional peer's types.
70
+ */
71
+ interface CvxKitSchemaMethods {}
72
+ }
73
+ /** Adds the optional entries' methods to the class type; the entries install them at runtime. */
74
+ export interface KSchema<Out = any, R extends KRequiredValidator = KRequiredValidator, D extends boolean = false, N extends GenericValidator = R, T extends boolean = false> extends CvxKitSchemaMethods {}
75
+ export declare class KOptional<I extends KType> extends KSchema<I['_output'] | undefined, I['_req'], I['_d'], ReturnType<I['_req']['optional']>, I['_t']> {
76
+ readonly _or: KOutputRequired<I>;
77
+ readonly _oo: ReturnType<KOutputRequired<I>['optional']>;
78
+ unwrap(): I;
79
+ }
80
+ export declare class KDefault<I extends KType> extends KSchema<Exclude<I['_output'], undefined>, I['_req'], true, ReturnType<I['_req']['optional']>, I['_t']> {
81
+ readonly _or: KOutputRequired<I>;
82
+ readonly _oo: KOutputRequired<I>;
83
+ unwrap(): I;
84
+ }
85
+ export declare class KNullable<I extends KType> extends KSchema<I['_output'] | null, NullableOf<I['_req']>, I['_d'], I['validator']['isOptional'] extends 'optional' ? ReturnType<NullableOf<I['_req']>['optional']> : NullableOf<I['_req']>, I['_t']> {
86
+ readonly _or: NullableOf<KOutputRequired<I>>;
87
+ readonly _oo: OutputNativeOf<I>['isOptional'] extends 'optional' ? ReturnType<NullableOf<KOutputRequired<I>>['optional']> : NullableOf<KOutputRequired<I>>;
88
+ unwrap(): I;
89
+ }
90
+ export declare class KTransform<I extends KType, O> extends KSchema<O, I['_req'], true, I['validator'], true> {
91
+ readonly _or: VAny<O>;
92
+ readonly _oo: VAny<O>;
93
+ }
94
+ export declare class KPipe<I extends KType, P extends KType> extends KSchema<P['_output'], I['_req'], true, I['validator'], true> {
95
+ readonly _or: KOutputRequired<P>;
96
+ readonly _oo: OutputNativeOf<P>;
97
+ }
98
+ type NullableOf<V extends KRequiredValidator> = VUnion<V['type'] | null, [V, VNull<null>]>;
99
+ export {};
100
+ //# sourceMappingURL=schema.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{compileNative as e,compileOutput as t}from"./compile.mjs";import{parseSchema as n,safeParseSchema as r}from"./parse.mjs";import{standardProps as i}from"./standard.mjs";var a=class{prev;op;arg;message;native;outputNative;plan;constructor(e,t,n,r){this.prev=e,this.op=t,this.arg=n,this.message=r,this.native=void 0,this.outputNative=void 0,this.plan=void 0}get validator(){return this.native??=e(this)}get outputValidator(){return this.outputNative??=t(this)}optional(){return new o(this,`optional`,void 0,void 0)}nullable(){return new c(this,`nullable`,void 0,void 0)}default(e){return new s(this,`default`,e,void 0)}refine(e,t){return this.link(`refine`,e,d(t))}check(e){return this.link(`check`,e,void 0)}overwrite(e){return this.link(`overwrite`,e,void 0)}transform(e){return new l(this,`transform`,e,void 0)}pipe(e){return new u(this,`pipe`,e,void 0)}parse(e){return n(this,e)}safeParse(e){return r(this,e)}describe(e){return this.link(`describe`,e,void 0)}get description(){return p(this)}get"~standard"(){return i(this)}link(e,t,n){let r=this.constructor,i=new r(this,e,t,n);return this.op!==`any`&&(i.native=this.native),i}wrapped(e){return m(this,e)}};Object.defineProperty(a.prototype,"toZod",{value:f,writable:!0,configurable:!0});var o=class extends a{unwrap(){return this.wrapped(`optional`)}},s=class extends a{unwrap(){return this.wrapped(`default`)}},c=class extends a{unwrap(){return this.wrapped(`nullable`)}},l=class extends a{},u=class extends a{};function d(e){return e===void 0||typeof e==`string`?e:(e.path!==void 0&&Object.freeze(e.path),Object.freeze(e))}function f(){throw Error("k: .toZod() needs the Zod interop entry; add `import 'cvx-kit/zod'` first")}function p(e){for(let t=e;t!==null;t=t.prev)if(t.op===`describe`)return t.arg}function m(e,t){let n=e;for(;n.op!==t&&(t!==`optional`||n.op!==`partial`);)n=h(n);return h(n)}function h(e){if(e.prev===null)throw Error(`k: no '${e.op}' wrapper to unwrap`);return e.prev}export{s as KDefault,c as KNullable,o as KOptional,u as KPipe,a as KSchema,l as KTransform};
2
+ //# sourceMappingURL=schema.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.mjs","names":["KSchema","prev","op","arg","message","compileNative","compileOutput","KOptional","KNullable","KDefault","value","check","frozenMessage","normalise","KTransform","map","KPipe","target","parseSchema","input","safeParseSchema","text","descriptionOf","standardProps","Next","next","wrappedBy","missingZodEntry","current","node","prevOf"],"sources":["../../src/k/schema.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { GenericValidator, VAny, VNull, VUnion } from 'convex/values'\nimport { compileNative, compileOutput } from './compile'\nimport type { KIssueInput, KSafeParseResult } from './issues'\nimport { parseSchema, safeParseSchema, type KPlan } from './parse'\nimport { standardProps } from './standard'\nimport type {\n\tKArg,\n\tKMessage,\n\tKOp,\n\tKOutputRequired,\n\tKRefineOptions,\n\tKRequiredValidator,\n\tKNode,\n\tKType,\n\tOutputNativeOf,\n} from './types'\n\n/**\n * An immutable chain record. A root has `prev === null` and a kind op; every chained call allocates one\n * record pointing at its predecessor. Nothing is compiled until `validator`, `outputValidator` or a\n * parse first needs it; each product is memoised in its own pre-declared slot.\n *\n * Type arguments: `Out` the parsed output, `R` the required native validator, `D` whether a default or\n * transform sits inside, `N` the input-side native validator (`R` unless the chain is optional or\n * defaulted), `T` whether a transform or pipe sits inside.\n */\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- the merged interface only adds methods that cvx-kit/zod installs on the prototype.\nexport abstract class KSchema<\n\tOut = any,\n\tR extends KRequiredValidator = KRequiredValidator,\n\tD extends boolean = false,\n\tN extends GenericValidator = R,\n\tT extends boolean = false,\n> implements KType {\n\tdeclare readonly _output: Out\n\tdeclare readonly _input: N['type']\n\tdeclare readonly _req: R\n\tdeclare readonly _d: D\n\tdeclare readonly _t: T\n\t/** Required output-side native validator; read only when `D` is true. */\n\tdeclare readonly _or: KRequiredValidator\n\t/** Output-side native validator; read only when `D` is true. */\n\tdeclare readonly _oo: GenericValidator\n\treadonly prev: KNode | null\n\treadonly op: KOp\n\treadonly arg: KArg\n\treadonly message: KMessage\n\t/** Memo slot for the input-side native validator. */\n\tnative: GenericValidator | undefined\n\t/** Memo slot for the output-side native validator. */\n\toutputNative: GenericValidator | undefined\n\t/** Memo slot for the parse plan. */\n\tplan: KPlan | undefined\n\n\tconstructor(prev: KNode | null, op: KOp, arg: KArg, message: KMessage) {\n\t\tthis.prev = prev\n\t\tthis.op = op\n\t\tthis.arg = arg\n\t\tthis.message = message\n\t\tthis.native = undefined\n\t\tthis.outputNative = undefined\n\t\tthis.plan = undefined\n\t}\n\n\tget validator(): N {\n\t\t// SAFETY: compileNative builds the validator that this record's class declares as N.\n\t\treturn (this.native ??= compileNative(this)) as N\n\t}\n\n\tget outputValidator(): D extends true ? this['_oo'] : N {\n\t\t// SAFETY: compileOutput builds the output-side validator this record's class declares.\n\t\treturn (this.outputNative ??= compileOutput(this)) as D extends true ? this['_oo'] : N\n\t}\n\n\toptional(): KOptional<this> {\n\t\treturn new KOptional(this, 'optional', undefined, undefined)\n\t}\n\n\tnullable(): KNullable<this> {\n\t\treturn new KNullable(this, 'nullable', undefined, undefined)\n\t}\n\n\tdefault(value: Exclude<Out, undefined>): KDefault<this> {\n\t\t// SAFETY: a default is a Convex value of this schema's output type.\n\t\treturn new KDefault(this, 'default', value as KArg, undefined)\n\t}\n\n\t/** A check on the parsed value; `options.path` attaches the issue below this value (object refinements). */\n\trefine(check: (value: Out) => boolean, message?: string | KRefineOptions): this {\n\t\treturn this.link('refine', check, frozenMessage(message))\n\t}\n\n\t/** A check that may add several issues through `context.addIssue`. */\n\tcheck(check: (value: Out, context: KCheckContext) => void): this {\n\t\treturn this.link('check', check, undefined)\n\t}\n\n\t/** A type-preserving normaliser; allowed everywhere, including table fields. */\n\toverwrite(normalise: (value: Out) => Out): this {\n\t\treturn this.link('overwrite', normalise, undefined)\n\t}\n\n\t/** A type-changing step. Produces a distinct kind that table fields and return shapes reject. */\n\ttransform<O>(map: (value: Out) => O): KTransform<this, O> {\n\t\treturn new KTransform(this, 'transform', map, undefined)\n\t}\n\n\t/** Parse this schema's output with `target`. Produces a distinct kind, like `transform`. */\n\tpipe<P extends KType>(target: P): KPipe<this, P> {\n\t\treturn new KPipe(this, 'pipe', target, undefined)\n\t}\n\n\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- parse is the decoding boundary for undecoded input.\n\tparse(input: unknown): Out {\n\t\t// SAFETY: a successful walk of this schema produces its declared output.\n\t\treturn parseSchema(this, input) as Out\n\t}\n\n\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- safeParse is the decoding boundary for undecoded input.\n\tsafeParse(input: unknown): KSafeParseResult<Out> {\n\t\t// SAFETY: a successful walk of this schema produces its declared output.\n\t\treturn safeParseSchema(this, input) as KSafeParseResult<Out>\n\t}\n\n\t/** A description for JSON Schema and tooling; it changes neither the validators nor parsing. */\n\tdescribe(text: string): this {\n\t\treturn this.link('describe', text, undefined)\n\t}\n\n\t/** The nearest description declared on this chain. */\n\tget description(): string | undefined {\n\t\treturn descriptionOf(this)\n\t}\n\n\t/** Standard Schema v1, so contracts and form libraries consume `k` schemas directly. */\n\tget '~standard'(): StandardSchemaV1.Props<N['type'], Out> {\n\t\treturn standardProps(this)\n\t}\n\n\tprotected link(op: KOp, arg: KArg, message: KMessage): this {\n\t\t// SAFETY: every subclass inherits this constructor unchanged, so the record keeps its predecessor's class.\n\t\tconst Next = this.constructor as new (\n\t\t\tprev: KNode,\n\t\t\top: KOp,\n\t\t\targ: KArg,\n\t\t\tmessage: KMessage,\n\t\t) => this\n\t\tconst next = new Next(this, op, arg, message)\n\t\t// link only records checks, normalisers and descriptions: its native shape is unchanged.\n\t\t// Private filter boundaries use an any root with a lazy native accessor. Do not force it here.\n\t\tif (this.op !== 'any') next.native = this.native\n\t\treturn next\n\t}\n\n\tprotected wrapped<W>(op: KOp): W {\n\t\t// SAFETY: the record below a wrapper record is the schema the wrapper's class names as W.\n\t\treturn wrappedBy(this, op) as W\n\t}\n}\n\n/** The context handed to `.check()`; `addIssue` may be called any number of times. */\nexport interface KCheckContext {\n\taddIssue(issue: KIssueInput): void\n}\n\ndeclare global {\n\t/**\n\t * Methods that optional cvx-kit entries add to every `k` schema; `cvx-kit/zod` adds `toZod()`. Empty\n\t * in core, so core declarations never name an optional peer's types.\n\t */\n\tinterface CvxKitSchemaMethods {}\n}\n\n/* oxlint-disable no-unused-vars -- A merged declaration must repeat the class's type parameters. */\n/** Adds the optional entries' methods to the class type; the entries install them at runtime. */\nexport interface KSchema<\n\tOut = any,\n\tR extends KRequiredValidator = KRequiredValidator,\n\tD extends boolean = false,\n\tN extends GenericValidator = R,\n\tT extends boolean = false,\n> extends CvxKitSchemaMethods {}\n/* oxlint-enable no-unused-vars */\n\n/**\n * `.toZod()` exists only once `cvx-kit/zod` is imported, which also adds its type. Until then this stub\n * names the entry; core declarations stay free of Zod types.\n */\nObject.defineProperty(KSchema.prototype, 'toZod', {\n\tvalue: missingZodEntry,\n\twritable: true,\n\tconfigurable: true,\n})\n\nexport class KOptional<I extends KType> extends KSchema<\n\tI['_output'] | undefined,\n\tI['_req'],\n\tI['_d'],\n\tReturnType<I['_req']['optional']>,\n\tI['_t']\n> {\n\tdeclare readonly _or: KOutputRequired<I>\n\tdeclare readonly _oo: ReturnType<KOutputRequired<I>['optional']>\n\n\tunwrap(): I {\n\t\treturn this.wrapped<I>('optional')\n\t}\n}\n\nexport class KDefault<I extends KType> extends KSchema<\n\tExclude<I['_output'], undefined>,\n\tI['_req'],\n\ttrue,\n\tReturnType<I['_req']['optional']>,\n\tI['_t']\n> {\n\tdeclare readonly _or: KOutputRequired<I>\n\tdeclare readonly _oo: KOutputRequired<I>\n\n\tunwrap(): I {\n\t\treturn this.wrapped<I>('default')\n\t}\n}\n\nexport class KNullable<I extends KType> extends KSchema<\n\tI['_output'] | null,\n\tNullableOf<I['_req']>,\n\tI['_d'],\n\tI['validator']['isOptional'] extends 'optional'\n\t\t? ReturnType<NullableOf<I['_req']>['optional']>\n\t\t: NullableOf<I['_req']>,\n\tI['_t']\n> {\n\tdeclare readonly _or: NullableOf<KOutputRequired<I>>\n\tdeclare readonly _oo: OutputNativeOf<I>['isOptional'] extends 'optional'\n\t\t? ReturnType<NullableOf<KOutputRequired<I>>['optional']>\n\t\t: NullableOf<KOutputRequired<I>>\n\n\tunwrap(): I {\n\t\treturn this.wrapped<I>('nullable')\n\t}\n}\n\nexport class KTransform<I extends KType, O> extends KSchema<\n\tO,\n\tI['_req'],\n\ttrue,\n\tI['validator'],\n\ttrue\n> {\n\tdeclare readonly _or: VAny<O>\n\tdeclare readonly _oo: VAny<O>\n}\n\nexport class KPipe<I extends KType, P extends KType> extends KSchema<\n\tP['_output'],\n\tI['_req'],\n\ttrue,\n\tI['validator'],\n\ttrue\n> {\n\tdeclare readonly _or: KOutputRequired<P>\n\tdeclare readonly _oo: OutputNativeOf<P>\n}\n\ntype NullableOf<V extends KRequiredValidator> = VUnion<V['type'] | null, [V, VNull<null>]>\n\n/** Freezes a refine options object and its path in place, like every other container a record holds. */\nfunction frozenMessage(message: string | KRefineOptions | undefined): KMessage {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- refine takes either its message or an options object.\n\tif (message === undefined || typeof message === 'string') return message\n\tif (message.path !== undefined) Object.freeze(message.path)\n\treturn Object.freeze(message)\n}\n\nfunction missingZodEntry(): never {\n\tthrow new Error(\"k: .toZod() needs the Zod interop entry; add `import 'cvx-kit/zod'` first\")\n}\n\nfunction descriptionOf(node: KNode): string | undefined {\n\tfor (let current: KNode | null = node; current !== null; current = current.prev) {\n\t\tif (current.op === 'describe') {\n\t\t\t// SAFETY: a describe record stores its text as the record argument.\n\t\t\treturn current.arg as string\n\t\t}\n\t}\n\treturn undefined\n}\n\nfunction wrappedBy(node: KNode, op: KOp): KNode {\n\tlet current = node\n\twhile (current.op !== op && !(op === 'optional' && current.op === 'partial'))\n\t\tcurrent = prevOf(current)\n\treturn prevOf(current)\n}\n\nfunction prevOf(node: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AU,EAAa,EAAgB,CAC/C,IAAIE,EAAUC,EACd,KAAOD,EAAQ,KAAO1B,IAAQA,IAAO,YAAc0B,EAAQ,KAAO,YACjE,EAAUE,EAAOF,CAAO,EACzB,OAAOE,EAAOF,CAAO,CACtB,CAEA,SAASE,EAAO,EAAoB,CACnC,GAAID,EAAK,OAAS,KAAM,MAAU,MAAM,UAAUA,EAAK,GAAG,oBAAoB,EAC9E,OAAOA,EAAK,IACb,C"}
@@ -0,0 +1,8 @@
1
+ import { KNode } from "./types.mjs";
2
+ import { StandardSchemaV1 } from "@standard-schema/spec";
3
+ /**
4
+ * The Standard Schema v1 props of a schema, built when `~standard` is read; nothing is stored on the
5
+ * schema. `validate` delegates to the same walker as `safeParse`.
6
+ */
7
+ export declare function standardProps<In, Out>(schema: KNode): StandardSchemaV1.Props<In, Out>;
8
+ //# sourceMappingURL=standard.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{safeParseSchema as e}from"./parse.mjs";function t(e){return{version:1,vendor:`cvx-kit`,validate:t=>n(e,t)}}function n(t,n){let i=e(t,n);return i.success?{value:i.data}:{issues:i.issues.map(r)}}function r(e){return{message:e.message,path:e.path}}export{t as standardProps};
2
+ //# sourceMappingURL=standard.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standard.mjs","names":["standardProps","standardResult","schema","value","result","safeParseSchema","standardIssue","issue"],"sources":["../../src/k/standard.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@standard-schema/spec'\nimport { safeParseSchema } from './parse'\nimport type { KNode } from './types'\n\n/**\n * The Standard Schema v1 props of a schema, built when `~standard` is read; nothing is stored on the\n * schema. `validate` delegates to the same walker as `safeParse`.\n */\nexport function standardProps<In, Out>(schema: KNode): StandardSchemaV1.Props<In, Out> {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: 'cvx-kit',\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Standard Schema validates undecoded input.\n\t\tvalidate: (value: unknown) => standardResult<Out>(schema, value),\n\t}\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Standard Schema validates undecoded input.\nfunction standardResult<Out>(schema: KNode, value: unknown): StandardSchemaV1.Result<Out> {\n\tconst result = safeParseSchema(schema, value)\n\tif (result.success) {\n\t\t// SAFETY: a successful walk of the schema produces its declared output.\n\t\treturn { value: result.data as Out }\n\t}\n\treturn { issues: result.issues.map(standardIssue) }\n}\n\nfunction standardIssue(issue: {\n\treadonly message: string\n\treadonly path: readonly (string | number)[]\n}): StandardSchemaV1.Issue {\n\treturn { message: issue.message, path: issue.path }\n}\n"],"mappings":"A,8CAQA,SAAgBA,EAAuB,EAAgD,CACtF,MAAO,CACN,QAAS,EACT,OAAQ,UAER,SAAW,GAAmBC,EAAoBC,EAAQC,CAAK,CAChE,CACD,CAGA,SAASF,EAAoB,EAAe,EAA8C,CACzF,IAAMG,EAASC,EAAgBH,EAAQC,CAAK,EAK5C,OAJIC,EAAO,QAEH,CAAE,MAAOA,EAAO,IAAY,EAE7B,CAAE,OAAQA,EAAO,OAAO,IAAIE,CAAa,CAAE,CACnD,CAEA,SAASA,EAAc,EAGI,CAC1B,MAAO,CAAE,QAASC,EAAM,QAAS,KAAMA,EAAM,IAAK,CACnD,C"}
@@ -0,0 +1,64 @@
1
+ import { KPlan } from "./parse.mjs";
2
+ import { GenericValidator, Validator, Value } from "convex/values";
3
+ /** Runtime record operation. Roots (`prev === null`) carry a kind op; every other record carries a chain op. */
4
+ export type KOp = 'string' | 'number' | 'int' | 'int64' | 'boolean' | 'null' | 'bytes' | 'any' | 'json' | 'isoDate' | 'isoDateTime' | 'timestamp' | 'literal' | 'enum' | 'id' | 'array' | 'object' | 'record' | 'union' | 'discriminatedUnion' | 'min' | 'max' | 'length' | 'regex' | 'refine' | 'check' | 'trim' | 'lower' | 'upper' | 'overwrite' | 'optional' | 'partial' | 'describe' | 'nullable' | 'default' | 'strip' | 'transform' | 'pipe';
5
+ export type KRequiredValidator = Validator<any, 'required', any>;
6
+ /**
7
+ * Structural constraint for any `k` schema. Every member is a plain read of a class type argument:
8
+ * `_req` is the required native validator, `validator` the input-side one (optional when the chain is
9
+ * optional or defaulted), `_d` whether a default or transform sits anywhere inside (the only case where
10
+ * the output side differs from the input side) and `_t` whether a transform or pipe does.
11
+ */
12
+ export interface KType extends KNode {
13
+ readonly _output: any;
14
+ readonly _req: KRequiredValidator;
15
+ readonly _d: boolean;
16
+ readonly _t: boolean;
17
+ }
18
+ /**
19
+ * The runtime view of any chain record, used by the compilers and the walker without the schema
20
+ * generics. The memo slots are written once, on first use.
21
+ */
22
+ export interface KNode {
23
+ readonly prev: KNode | null;
24
+ readonly op: KOp;
25
+ readonly arg: KArg;
26
+ readonly message: KMessage;
27
+ native: GenericValidator | undefined;
28
+ outputNative: GenericValidator | undefined;
29
+ plan: KPlan | undefined;
30
+ readonly validator: GenericValidator;
31
+ }
32
+ export type KFields = Readonly<Record<string, KType>>;
33
+ export type KLiteralValue = string | number | bigint | boolean;
34
+ export type KPath = (string | number)[];
35
+ /** Options for `refine`: a replacement message and a path, relative to the refined value, for the issue. */
36
+ export type KRefineOptions = {
37
+ readonly message?: string;
38
+ readonly path?: KPath;
39
+ };
40
+ export type KMessage = string | KRefineOptions | undefined;
41
+ export type KCallback = (...args: never[]) => any;
42
+ export type KDiscriminated = {
43
+ readonly key: string;
44
+ readonly options: readonly KType[];
45
+ };
46
+ export type KArg = Value | undefined | RegExp | KType | readonly KType[] | readonly string[] | KFields | KCallback | KDiscriminated;
47
+ /** Input-side native Convex validator type of a `k` schema: a defaulted field is optional. */
48
+ export type NativeOf<T extends KType> = T['validator'];
49
+ /** Output-side native Convex validator type of a `k` schema: a defaulted field is required. */
50
+ export type OutputNativeOf<T extends KType> = T['_d'] extends true ? T extends {
51
+ readonly _oo: infer O extends GenericValidator;
52
+ } ? O : never : T['validator'];
53
+ /** Required output-side native validator, for array elements, union members and record values. */
54
+ export type KOutputRequired<T extends KType> = T['_d'] extends true ? T extends {
55
+ readonly _or: infer O extends KRequiredValidator;
56
+ } ? O : never : T['_req'];
57
+ export type KNativeFields<F extends KFields> = { [K in keyof F]: F[K]['validator']; };
58
+ export type KOutputFields<F extends KFields> = { [K in keyof F]: OutputNativeOf<F[K]>; };
59
+ export type KAnyDiffers<F extends KFields> = true extends F[keyof F]['_d'] ? true : false;
60
+ export type KAnyTransform<F extends KFields> = true extends F[keyof F]['_t'] ? true : false;
61
+ /** Output of an object that holds a default or transform somewhere: a defaulted field is required. */
62
+ export type KObjectOutput<F extends KFields> = Flat<{ [K in keyof F as undefined extends F[K]['_output'] ? K : never]?: Exclude<F[K]['_output'], undefined>; } & { [K in keyof F as undefined extends F[K]['_output'] ? never : K]: F[K]['_output']; }>;
63
+ export type Flat<T> = { [K in keyof T]: T[K]; };
64
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ export{};
package/dist/k.d.mts ADDED
@@ -0,0 +1,8 @@
1
+ import { k } from "./k/index.mjs";
2
+ import { KIssue, KIssueCode, KIssueInput, KSafeParseResult, KValidationData, KValidationError } from "./k/issues.mjs";
3
+ import { KAny, KArray, KBoolean, KBytes, KDiscriminatedUnion, KEnum, KId, KInt64, KJson, KLiteral, KNull, KNumber, KRecord, KString, KUnion } from "./k/kinds.mjs";
4
+ import { KIsoDate, KIsoDateTime, KTimestamp } from "./k/dates.mjs";
5
+ import { KObject } from "./k/object.mjs";
6
+ import { KCheckContext, KDefault, KNullable, KOptional, KPipe, KSchema, KTransform } from "./k/schema.mjs";
7
+ import { KFields, KPath, KRefineOptions, KType, NativeOf, OutputNativeOf } from "./k/types.mjs";
8
+ export { type KAny, type KArray, type KBoolean, type KBytes, type KCheckContext, type KDefault, type KDiscriminatedUnion, type KEnum, type KFields, type KId, type KInt64, type KIsoDate, type KIsoDateTime, type KIssue, type KIssueCode, type KIssueInput, type KJson, type KLiteral, type KNull, type KNullable, type KNumber, type KObject, type KOptional, type KPath, type KPipe, type KRecord, type KRefineOptions, type KSafeParseResult, type KSchema, type KString, type KTimestamp, type KTransform, type KType, type KUnion, type KValidationData, KValidationError, type NativeOf, type OutputNativeOf, k };
package/dist/k.mjs ADDED
@@ -0,0 +1 @@
1
+ import{k as e}from"./k/index.mjs";import{KValidationError as t}from"./k/issues.mjs";export{t as KValidationError,e as k};
@@ -1,12 +1,11 @@
1
1
  import { ErrorFactory } from "./errors.mjs";
2
- //#region src/middleware.d.ts
3
2
  /**
4
3
  * Structural surface of @convex-dev/rate-limiter's RateLimiter (checked
5
4
  * against 0.3.x; re-verify at install). The host mounts the component and
6
5
  * constructs the limiter; the kit only ever receives the instance —
7
6
  * injection keeps the kit dependency-free.
8
7
  */
9
- type RateLimiterLike = {
8
+ export type RateLimiterLike = {
10
9
  limit: (ctx: never, name: string, options?: {
11
10
  key?: string;
12
11
  }) => Promise<{
@@ -24,23 +23,21 @@ type RateLimiterLike = {
24
23
  * The returned middleware is shape-compatible with both AnyCommandMiddleware
25
24
  * and AnyQueryMiddleware.
26
25
  */
27
- declare function rateLimit(config: {
26
+ export declare function rateLimit<Context = never>(config: {
28
27
  limiter: RateLimiterLike;
29
28
  name: string;
30
29
  /** Defaults to ctx.tenant. */
31
- key?: (context: never) => string;
30
+ key?: (context: Context) => string;
32
31
  /** Observe a rejection before the throw (metrics, headers). */
33
32
  onLimit?: (status: {
34
33
  ok: boolean;
35
34
  retryAfter?: number;
36
- }, context: never) => void | Promise<void>;
35
+ }, context: Context) => void | Promise<void>;
37
36
  errors?: ErrorFactory;
38
- }): (input: {
37
+ }): <Result>(input: {
39
38
  context: never;
40
39
  next: (options?: {
41
- context?: unknown;
42
- }) => Promise<unknown>;
43
- }) => Promise<unknown>;
44
- //#endregion
45
- export { RateLimiterLike, rateLimit };
40
+ context?: object;
41
+ }) => Promise<Result>;
42
+ }) => Promise<Result>;
46
43
  //# sourceMappingURL=middleware.d.mts.map
@@ -1,2 +1,2 @@
1
- import{defaultErrors as e}from"./errors.mjs";function t(t){let n=t.errors??e;return async e=>{let r=t.key?t.key(e.context):e.context.tenant;if(r===void 0)return n.throw({code:`RATE_LIMIT_KEY_MISSING`,message:`rateLimit("${t.name}") has no key: ctx.tenant is undefined and no key fn was configured`});let i=await t.limiter.limit(e.context,t.name,{key:r});return i.ok?e.next():(await t.onLimit?.(i,e.context),n.throw({code:`RATE_LIMITED`,message:`Rate limit "${t.name}" exceeded${i.retryAfter===void 0?``:`; retry after ${Math.ceil(i.retryAfter)}ms`}`}))}}export{t as rateLimit};
1
+ import{defaultErrors as e}from"./errors.mjs";import{k as t}from"./k/index.mjs";function n(t){let n=t.errors??e;return async e=>{let r=t.key?t.key(e.context):i(e.context);if(r===void 0)return n.throw({code:`RATE_LIMIT_KEY_MISSING`,message:`rateLimit("${t.name}") has no key: ctx.tenant is undefined and no key fn was configured`});let a=await t.limiter.limit(e.context,t.name,{key:r});return a.ok?e.next():(await t.onLimit?.(a,e.context),n.throw({code:`RATE_LIMITED`,message:`Rate limit "${t.name}" exceeded${a.retryAfter===void 0?``:`; retry after ${Math.ceil(a.retryAfter)}ms`}`}))}}const r=t.string().optional();function i(e){return r.parse(e.tenant)}export{n as rateLimit};
2
2
  //# sourceMappingURL=middleware.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["import { defaultErrors, type ErrorFactory } from './errors'\n\n/**\n * Structural surface of @convex-dev/rate-limiter's RateLimiter (checked\n * against 0.3.x; re-verify at install). The host mounts the component and\n * constructs the limiter; the kit only ever receives the instance —\n * injection keeps the kit dependency-free.\n */\nexport type RateLimiterLike = {\n\tlimit: (\n\t\tctx: never,\n\t\tname: string,\n\t\toptions?: { key?: string },\n\t) => Promise<{ ok: boolean; retryAfter?: number }>\n}\n\n/**\n * The first packaged middleware: rate limiting on the Command/Query\n * middleware seams. Runs before guards and the handler; a rejected call\n * throws RATE_LIMITED (audit and handler never run). Keyed by ctx.tenant by\n * default — when no key fn is given and ctx.tenant is undefined, this is a\n * configuration error, not a silent shared bucket.\n *\n * The returned middleware is shape-compatible with both AnyCommandMiddleware\n * and AnyQueryMiddleware.\n */\nexport function rateLimit(config: {\n\tlimiter: RateLimiterLike\n\tname: string\n\t/** Defaults to ctx.tenant. */\n\tkey?: (context: never) => string\n\t/** Observe a rejection before the throw (metrics, headers). */\n\tonLimit?: (\n\t\tstatus: { ok: boolean; retryAfter?: number },\n\t\tcontext: never,\n\t) => void | Promise<void>\n\terrors?: ErrorFactory\n}) {\n\tconst errors = config.errors ?? defaultErrors\n\treturn async (input: {\n\t\tcontext: never\n\t\tnext: (options?: { context?: unknown }) => Promise<unknown>\n\t}): Promise<unknown> => {\n\t\tconst key = config.key\n\t\t\t? config.key(input.context)\n\t\t\t: (input.context as { tenant?: string }).tenant\n\t\tif (key === undefined) {\n\t\t\treturn errors.throw({\n\t\t\t\tcode: 'RATE_LIMIT_KEY_MISSING',\n\t\t\t\tmessage: `rateLimit(\"${config.name}\") has no key: ctx.tenant is undefined and no key fn was configured`,\n\t\t\t})\n\t\t}\n\t\tconst status = await config.limiter.limit(input.context, config.name, {\n\t\t\tkey,\n\t\t})\n\t\tif (!status.ok) {\n\t\t\tawait config.onLimit?.(status, input.context)\n\t\t\treturn errors.throw({\n\t\t\t\tcode: 'RATE_LIMITED',\n\t\t\t\tmessage: `Rate limit \"${config.name}\" exceeded${\n\t\t\t\t\tstatus.retryAfter === undefined\n\t\t\t\t\t\t? ''\n\t\t\t\t\t\t: `; retry after ${Math.ceil(status.retryAfter)}ms`\n\t\t\t\t}`,\n\t\t\t})\n\t\t}\n\t\treturn input.next()\n\t}\n}\n"],"mappings":"6CA0BA,SAAgB,EAAU,EAWvB,CACF,IAAM,EAAS,EAAO,QAAU,EAChC,OAAO,KAAO,IAGU,CACvB,IAAM,EAAM,EAAO,IAChB,EAAO,IAAI,EAAM,OAAO,EACvB,EAAM,QAAgC,OAC1C,GAAI,IAAQ,IAAA,GACX,OAAO,EAAO,MAAM,CACnB,KAAM,yBACN,QAAS,cAAc,EAAO,KAAK,oEACpC,CAAC,EAEF,IAAM,EAAS,MAAM,EAAO,QAAQ,MAAM,EAAM,QAAS,EAAO,KAAM,CACrE,KACD,CAAC,EAYD,OAXK,EAAO,GAWL,EAAM,KAAK,GAVjB,MAAM,EAAO,UAAU,EAAQ,EAAM,OAAO,EACrC,EAAO,MAAM,CACnB,KAAM,eACN,QAAS,eAAe,EAAO,KAAK,YACnC,EAAO,aAAe,IAAA,GACnB,GACA,iBAAiB,KAAK,KAAK,EAAO,UAAU,EAAE,KAEnD,CAAC,EAGH,CACD"}
1
+ {"version":3,"file":"middleware.mjs","names":["rateLimit","errors","config","defaultErrors","key","input","contextTenant","status","tenantField","k","context"],"sources":["../src/middleware.ts"],"sourcesContent":["import { defaultErrors, type ErrorFactory } from './errors'\nimport { k } from './k'\n\n/**\n * Structural surface of @convex-dev/rate-limiter's RateLimiter (checked\n * against 0.3.x; re-verify at install). The host mounts the component and\n * constructs the limiter; the kit only ever receives the instance —\n * injection keeps the kit dependency-free.\n */\nexport type RateLimiterLike = {\n\tlimit: (\n\t\tctx: never,\n\t\tname: string,\n\t\toptions?: { key?: string },\n\t) => Promise<{ ok: boolean; retryAfter?: number }>\n}\n\n/**\n * The first packaged middleware: rate limiting on the Command/Query\n * middleware seams. Runs before guards and the handler; a rejected call\n * throws RATE_LIMITED (audit and handler never run). Keyed by ctx.tenant by\n * default — when no key fn is given and ctx.tenant is undefined, this is a\n * configuration error, not a silent shared bucket.\n *\n * The returned middleware is shape-compatible with both AnyCommandMiddleware\n * and AnyQueryMiddleware.\n */\nexport function rateLimit<Context = never>(config: {\n\tlimiter: RateLimiterLike\n\tname: string\n\t/** Defaults to ctx.tenant. */\n\tkey?: (context: Context) => string\n\t/** Observe a rejection before the throw (metrics, headers). */\n\tonLimit?: (status: { ok: boolean; retryAfter?: number }, context: Context) => void | Promise<void>\n\terrors?: ErrorFactory\n}) {\n\tconst errors = config.errors ?? defaultErrors\n\treturn async <Result>(input: {\n\t\tcontext: never\n\t\tnext: (options?: { context?: object }) => Promise<Result>\n\t}): Promise<Result> => {\n\t\tconst key = config.key ? config.key(input.context) : contextTenant(input.context)\n\t\tif (key === undefined) {\n\t\t\treturn errors.throw({\n\t\t\t\tcode: 'RATE_LIMIT_KEY_MISSING',\n\t\t\t\tmessage: `rateLimit(\"${config.name}\") has no key: ctx.tenant is undefined and no key fn was configured`,\n\t\t\t})\n\t\t}\n\t\tconst status = await config.limiter.limit(input.context, config.name, {\n\t\t\tkey,\n\t\t})\n\t\tif (!status.ok) {\n\t\t\tawait config.onLimit?.(status, input.context)\n\t\t\treturn errors.throw({\n\t\t\t\tcode: 'RATE_LIMITED',\n\t\t\t\tmessage: `Rate limit \"${config.name}\" exceeded${\n\t\t\t\t\tstatus.retryAfter === undefined ? '' : `; retry after ${Math.ceil(status.retryAfter)}ms`\n\t\t\t\t}`,\n\t\t\t})\n\t\t}\n\t\treturn input.next()\n\t}\n}\n\nconst tenantField = k.string().optional()\n\n/** The only context member the default key reads; the rest of the context is never inspected. */\ntype TenantCarrier = { readonly tenant?: unknown }\n\n/** `ctx.tenant`, which must be a string when present (VALIDATION otherwise). */\nfunction contextTenant(context: TenantCarrier): string | undefined {\n\treturn tenantField.parse(context.tenant)\n}\n"],"mappings":"A,+EA2BA,SAAgBA,EAA2B,EAQxC,CACF,IAAMC,EAASC,EAAO,QAAUC,EAChC,OAAO,KAAe,IAGC,CACtB,IAAMC,EAAMF,EAAO,IAAMA,EAAO,IAAIG,EAAM,OAAO,EAAIC,EAAcD,EAAM,OAAO,EAChF,GAAID,IAAQ,IAAA,GACX,OAAOH,EAAO,MAAM,CACnB,KAAM,yBACN,QAAS,cAAcC,EAAO,KAAK,oEACpC,CAAC,EAEF,IAAMK,EAAS,MAAML,EAAO,QAAQ,MAAMG,EAAM,QAASH,EAAO,KAAM,CACrE,KACD,CAAC,EAUD,OATKK,EAAO,GASLF,EAAM,KAAK,GARjB,MAAMH,EAAO,UAAUK,EAAQF,EAAM,OAAO,EACrCJ,EAAO,MAAM,CACnB,KAAM,eACN,QAAS,eAAeC,EAAO,KAAK,YACnCK,EAAO,aAAe,IAAA,GAAY,GAAK,iBAAiB,KAAK,KAAKA,EAAO,UAAU,EAAE,KAEvF,CAAC,EAGH,CACD,CAEA,MAAMC,EAAcC,EAAE,OAAO,CAAC,CAAC,SAAS,EAMxC,SAASH,EAAc,EAA4C,CAClE,OAAOE,EAAY,MAAME,EAAQ,MAAM,CACxC,C"}
@@ -0,0 +1,23 @@
1
+ import { DomainContract, DomainOperationContract } from "./domain.mjs";
2
+ declare const declaredSchemas: unique symbol;
3
+ /** Private evidence for contextual inference; schemas are installed only at registration. */
4
+ export type DeclaredSchemas<Entry> = {
5
+ readonly [declaredSchemas]: Entry;
6
+ };
7
+ export type BoundOperations<Operations extends Readonly<Record<keyof Entries, {
8
+ handler: (...arguments_: never[]) => unknown;
9
+ }>>, Entries extends Readonly<Record<string, DomainOperationContract>>> = { [Key in keyof Entries]: Entries[Key] & Operations[Key] & {
10
+ input: Entries[Key]['input'];
11
+ result: Entries[Key]['result'];
12
+ handler: Operations[Key]['handler'];
13
+ }; };
14
+ /** Both adapters bind declarations through the same configuration boundary. */
15
+ export declare function domainHelpers(entries: Readonly<Record<string, object>>): {
16
+ [k: string]: (implementation: object) => {};
17
+ };
18
+ /** Bind only opaque schema references; never invoke user callbacks at construction. */
19
+ export declare function bindDomainImplementation(key: string, declaration: object, implementation: object): {};
20
+ /** Snapshot records and verify key ownership before the executor closes over them. */
21
+ export declare function snapshotOperations(operations: Readonly<Record<string, object>>, contract: DomainContract | undefined, section: 'commands' | 'queries' | 'actions', audit?: (resolution: never, context: never, scope: never) => unknown): Readonly<Record<string, Readonly<Record<string, unknown>>>>;
22
+ export {};
23
+ //# sourceMappingURL=binding.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{memoize as e}from"./lazy.mjs";const t=[`input`,`result`,`classification`,`replayResult`,`wire`],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new WeakMap;function a(e){let t=Object.fromEntries(Object.keys(e).map(t=>[t,n=>{if(!c(e,t))return o(t,e[t],n);let r={...n};return i.set(r,{key:t,entries:e}),r}])),n=t.handler;return t.handler=(t,i)=>{if(typeof t!=`function`&&n)return n(t);if(typeof t!=`function`)throw Error(`Invalid operation handler`);let a={...i,handler:t};return r.set(a,e),a},t}function o(e,r,i){for(let t of[`handler`,`audit`,`prepare`,`guard`,`middleware`,`context`])if(Object.prototype.hasOwnProperty.call(r,t))throw Error(`Domain contract ${e} cannot contain ${t}`);for(let n of t)if(Object.prototype.hasOwnProperty.call(i,n))throw Error(`Contracted operation ${e} cannot override ${n}`);let a={...i,...r};return n.set(a,{key:e,declaration:r}),a}function s(a,s,l,u){if(u!==void 0&&typeof u!=`function`)throw Error(`Invalid registry audit callback`);let d=s?.[l];if(s&&!d)throw Error(`Domain contract has no ${l} section`);let f=Object.keys(a);if(d&&(f.length!==Object.keys(d).length||f.some(e=>!Object.prototype.hasOwnProperty.call(d,e))))throw Error(`Contract operation keys must match exactly`);let p=e=>{let s=a[e],c=i.get(s);if(c&&(s=o(c.key,c.entries[c.key],s)),d){if(r.has(s)){if(r.get(s)!==d)throw Error(`Operation ${e} must use its own contract helper`);s=o(e,d[e],s)}let i=n.get(s);if(!i||i.key!==e||i.declaration!==d[e]||t.some(t=>s[t]!==d[e][t]))throw Error(`Operation ${e} must use its own contract helper`)}let f={...s};if(f.wire&&=Object.freeze({...f.wire}),l===`commands`||l===`actions`){let t=f.audit;if(t!==void 0&&typeof t!=`function`)throw Error(`Invalid audit for ${e}`);if(t===void 0&&!u&&l===`commands`)throw Error(`Command ${e} requires an audit callback`);t===void 0&&u&&(f.audit=(t,n,r)=>u({operation:e,input:t.command,result:t.result},n,r))}return Object.freeze(f)},m={};for(let t of f)d&&c(d,t)?Object.defineProperty(m,t,{enumerable:!0,get:e(()=>p(t))}):m[t]=p(t);return Object.freeze(m)}function c(e,n){let r=Object.getOwnPropertyDescriptor(e,n);if(!r)return!1;if(r.get)return!0;let i=r.value;return!!i&&typeof i==`object`&&t.some(e=>!!Object.getOwnPropertyDescriptor(i,e)?.get)}export{o as bindDomainImplementation,a as domainHelpers,s as snapshotOperations};
2
+ //# sourceMappingURL=binding.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.mjs","names":["protectedFields","bindings","pending","deferred","domainHelpers","helpers","entries","key","isLazyOperation","bindDomainImplementation","implementation","draft","namedHandler","handler","options","field","declaration","definition","snapshotOperations","audit","declarations","contract","section","keys","operations","bind","original","binding","override","resolution","context","scope","snapshot","memoize","descriptor","value"],"sources":["../../../src/modules/contracts/binding.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unsafe-dictionary-type, anti-slop/no-known-value-widening, anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Configuration boundary validates heterogeneous own-key records and callback presence; validators remain opaque identities. */\nimport { memoize } from './lazy'\nimport type { DomainContract, DomainOperationContract } from './domain'\n\ndeclare const declaredSchemas: unique symbol\n/** Private evidence for contextual inference; schemas are installed only at registration. */\nexport type DeclaredSchemas<Entry> = { readonly [declaredSchemas]: Entry }\nexport type BoundOperations<\n\tOperations extends Readonly<\n\t\tRecord<keyof Entries, { handler: (...arguments_: never[]) => unknown }>\n\t>,\n\tEntries extends Readonly<Record<string, DomainOperationContract>>,\n> = {\n\t[Key in keyof Entries]: Entries[Key] &\n\t\tOperations[Key] & {\n\t\t\tinput: Entries[Key]['input']\n\t\t\tresult: Entries[Key]['result']\n\t\t\thandler: Operations[Key]['handler']\n\t\t}\n}\n\n// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\nconst protectedFields = ['input', 'result', 'classification', 'replayResult', 'wire'] as const\nconst bindings = new WeakMap<object, { key: string; declaration: object }>()\nconst pending = new WeakMap<object, Readonly<Record<string, object>>>()\nconst deferred = new WeakMap<object, { key: string; entries: Readonly<Record<string, object>> }>()\n\n/** Both adapters bind declarations through the same configuration boundary. */\nexport function domainHelpers(entries: Readonly<Record<string, object>>) {\n\tconst helpers = Object.fromEntries(\n\t\tObject.keys(entries).map((key) => [\n\t\t\tkey,\n\t\t\t(implementation: object) => {\n\t\t\t\tif (!isLazyOperation(entries, key))\n\t\t\t\t\treturn bindDomainImplementation(key, entries[key], implementation)\n\t\t\t\tconst draft = { ...implementation }\n\t\t\t\tdeferred.set(draft, { key, entries })\n\t\t\t\treturn draft\n\t\t\t},\n\t\t]),\n\t)\n\tconst namedHandler = helpers.handler\n\thelpers.handler = (handler: Function | object, options?: object) => {\n\t\tif (typeof handler !== 'function' && namedHandler) return namedHandler(handler)\n\t\tif (typeof handler !== 'function') throw Error('Invalid operation handler')\n\t\tconst implementation = { ...options, handler }\n\t\tpending.set(implementation, entries)\n\t\treturn implementation\n\t}\n\treturn helpers\n}\n\n/** Bind only opaque schema references; never invoke user callbacks at construction. */\nexport function bindDomainImplementation(key: string, declaration: object, implementation: object) {\n\tfor (const field of ['handler', 'audit', 'prepare', 'guard', 'middleware', 'context']) {\n\t\tif (Object.prototype.hasOwnProperty.call(declaration, field))\n\t\t\tthrow Error(`Domain contract ${key} cannot contain ${field}`)\n\t}\n\tfor (const field of protectedFields) {\n\t\tif (Object.prototype.hasOwnProperty.call(implementation, field))\n\t\t\tthrow Error(`Contracted operation ${key} cannot override ${field}`)\n\t}\n\tconst definition = { ...implementation, ...declaration }\n\tbindings.set(definition, { key, declaration })\n\treturn definition\n}\n\n/** Snapshot records and verify key ownership before the executor closes over them. */\nexport function snapshotOperations(\n\toperations: Readonly<Record<string, object>>,\n\tcontract: DomainContract | undefined,\n\tsection: 'commands' | 'queries' | 'actions',\n\taudit?: (resolution: never, context: never, scope: never) => unknown,\n) {\n\tif (audit !== undefined && typeof audit !== 'function')\n\t\tthrow Error('Invalid registry audit callback')\n\tconst declarations = contract?.[section]\n\tif (contract && !declarations) throw Error(`Domain contract has no ${section} section`)\n\tconst keys = Object.keys(operations)\n\tif (\n\t\tdeclarations &&\n\t\t(keys.length !== Object.keys(declarations).length ||\n\t\t\tkeys.some((key) => !Object.prototype.hasOwnProperty.call(declarations, key)))\n\t)\n\t\tthrow Error('Contract operation keys must match exactly')\n\tconst bind = (key: string) => {\n\t\tlet original = operations[key]\n\t\t// A deferred helper result binds to its own declaration wherever it is registered.\n\t\tconst draft = deferred.get(original)\n\t\tif (draft) original = bindDomainImplementation(draft.key, draft.entries[draft.key], original)\n\t\tif (declarations) {\n\t\t\tif (pending.has(original)) {\n\t\t\t\tif (pending.get(original) !== declarations)\n\t\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t\t\toriginal = bindDomainImplementation(key, declarations[key], original)\n\t\t\t}\n\t\t\tconst binding = bindings.get(original)\n\t\t\tif (\n\t\t\t\t!binding ||\n\t\t\t\tbinding.key !== key ||\n\t\t\t\tbinding.declaration !== declarations[key] ||\n\t\t\t\tprotectedFields.some(\n\t\t\t\t\t(field) =>\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(original as Record<string, unknown>)[field] !==\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(declarations[key] as Record<string, unknown>)[field],\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\tconst definition = { ...original } as Record<string, unknown>\n\t\tif (definition.wire) {\n\t\t\t// SAFETY: wire is configuration, while its schema stays an opaque reference.\n\t\t\tdefinition.wire = Object.freeze({ ...(definition.wire as object) })\n\t\t}\n\t\tif (section === 'commands' || section === 'actions') {\n\t\t\tconst override = definition.audit\n\t\t\tif (override !== undefined && typeof override !== 'function')\n\t\t\t\tthrow Error(`Invalid audit for ${key}`)\n\t\t\tif (override === undefined && !audit && section === 'commands')\n\t\t\t\tthrow Error(`Command ${key} requires an audit callback`)\n\t\t\tif (override === undefined && audit) {\n\t\t\t\tdefinition.audit = (\n\t\t\t\t\tresolution: { command: unknown; result: unknown },\n\t\t\t\t\tcontext: unknown,\n\t\t\t\t\tscope: unknown,\n\t\t\t\t) =>\n\t\t\t\t\taudit(\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t{ operation: key, input: resolution.command, result: resolution.result } as never,\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t\t// SAFETY: the registry audit signature declares the scope its executor passes.\n\t\t\t\t\t\tscope as never,\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\treturn Object.freeze(definition)\n\t}\n\tconst snapshot: Record<string, Readonly<Record<string, unknown>>> = {}\n\tfor (const key of keys) {\n\t\tif (declarations && isLazyOperation(declarations, key))\n\t\t\tObject.defineProperty(snapshot, key, { enumerable: true, get: memoize(() => bind(key)) })\n\t\telse snapshot[key] = bind(key)\n\t}\n\treturn Object.freeze(snapshot)\n}\n\n/** Getter-declared operations, or operations with getter-declared protected fields, bind on first access. */\nfunction isLazyOperation(entries: Readonly<Record<string, object>>, key: string) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(entries, key)\n\tif (!descriptor) return false\n\tif (descriptor.get) return true\n\tconst value: unknown = descriptor.value\n\treturn (\n\t\t!!value &&\n\t\ttypeof value === 'object' &&\n\t\tprotectedFields.some((field) => !!Object.getOwnPropertyDescriptor(value, field)?.get)\n\t)\n}\n"],"mappings":"A,qCAsBA,MAAMA,EAAkB,CAAC,QAAS,SAAU,iBAAkB,eAAgB,MAAM,EAC9EC,kBAAW,IAAI,QACfC,kBAAU,IAAI,QACdC,kBAAW,IAAI,QAGrB,SAAgBC,EAAc,EAA2C,CACxE,IAAMC,EA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ACA,IAEAA,EAEC,CAAE,UAAWZ,EAAK,MAAOsB,EAAW,QAAS,OAAQA,EAAW,MAAO,EAEvEC,EAEAC,CACD,EAEH,CAEA,OAAO,OAAO,OAAOd,CAAU,CAChC,EACMe,EAA8D,CAAC,EACrE,IAAK,IAAMzB,KAAOgB,EACbH,GAAgBZ,EAAgBY,EAAcb,CAAG,EACpD,OAAO,eAAeyB,EAAUzB,EAAK,CAAE,WAAY,GAAM,IAAK0B,MAAcR,EAAKlB,CAAG,CAAC,CAAE,CAAC,EACpF,EAASA,GAAOkB,EAAKlB,CAAG,EAE9B,OAAO,OAAO,OAAOyB,CAAQ,CAC9B,CAGA,SAASxB,EAAgB,EAA2C,EAAa,CAChF,IAAM0B,EAAa,OAAO,yBAAyB5B,EAASC,CAAG,EAC/D,GAAI,CAAC2B,EAAY,MAAO,GACxB,GAAIA,EAAW,IAAK,MAAO,GAC3B,IAAMC,EAAiBD,EAAW,MAClC,MACC,CAAC,CAACC,GACF,OAAOA,GAAU,UACjBnC,EAAgB,KAAM,GAAU,CAAC,CAAC,OAAO,yBAAyBmC,EAAOpB,CAAK,CAAC,EAAE,GAAG,CAEtF,C"}
@@ -0,0 +1,67 @@
1
+ /** Structural contracts keep the optional Effect peer out of this module. */
2
+ export interface StandardSchema<Input = unknown, Output = Input> {
3
+ readonly '~standard': {
4
+ readonly version: 1;
5
+ readonly vendor: string;
6
+ readonly types?: {
7
+ readonly input: Input;
8
+ readonly output: Output;
9
+ };
10
+ readonly validate: (value: unknown) => ValidationResult<Output> | Promise<ValidationResult<Output>>;
11
+ };
12
+ }
13
+ export interface ValidationIssue {
14
+ readonly message: string;
15
+ readonly path?: readonly (PropertyKey | {
16
+ readonly key: PropertyKey;
17
+ })[];
18
+ }
19
+ export type ValidationResult<Output> = {
20
+ readonly value: Output;
21
+ readonly issues?: undefined;
22
+ } | {
23
+ readonly issues: readonly ValidationIssue[];
24
+ };
25
+ export interface LegacyParser<Output = unknown> {
26
+ readonly parse: (value: unknown) => Output;
27
+ readonly parseAsync?: (value: unknown) => Promise<Output>;
28
+ }
29
+ /** Decode execution is an opaque channel here; optional adapters give it concrete semantics. */
30
+ export interface Decoder<Input = unknown, Output = unknown, Execution = unknown> {
31
+ readonly kind: 'contract' | 'effect-contract';
32
+ readonly types?: {
33
+ readonly input: Input;
34
+ readonly output: Output;
35
+ };
36
+ readonly decode: (value: unknown) => Execution;
37
+ }
38
+ export type ContractSchema = LegacyParser | StandardSchema<unknown, unknown> | Decoder;
39
+ export type NeutralSchema = LegacyParser | StandardSchema<unknown, unknown> | (Decoder<unknown, unknown, ValidationResult<unknown> | Promise<ValidationResult<unknown>>> & {
40
+ readonly kind: 'contract';
41
+ });
42
+ export type ContractInput<S> = S extends Decoder<infer Input, unknown, unknown> ? Input : S extends StandardSchema<infer Input, unknown> ? Input : S extends {
43
+ readonly _input: infer Input;
44
+ } ? Input : S extends LegacyParser<infer Output> ? Awaited<Output> : never;
45
+ export type ContractOutput<S> = S extends Decoder<unknown, infer Output, unknown> ? Output : S extends StandardSchema<unknown, infer Output> ? Output : S extends LegacyParser<infer Output> ? Awaited<Output> : never;
46
+ export type ContractExecution<S> = S extends Decoder<unknown, unknown, infer Execution> ? Execution : never;
47
+ /** Validation failures are values. Throws/rejections are deliberately left as defects. */
48
+ export declare function decodeContract<S extends NeutralSchema>(schema: S, value: unknown): Promise<ValidationResult<ContractOutput<S>>>;
49
+ /** Independent final and wire contracts never reuse the fresh-result transform. */
50
+ export declare function operationContract<const Input extends ContractSchema, const Result extends ContractSchema, const Replay extends ContractSchema, const Wire extends ContractSchema, const Definition extends object>(definition: Definition & {
51
+ input: Input;
52
+ result: Result;
53
+ replayResult: Replay & (ContractOutput<Replay> extends ContractOutput<Result> ? unknown : never);
54
+ wire: {
55
+ project: (value: ContractOutput<Result>) => ContractInput<Wire>;
56
+ schema: Wire;
57
+ };
58
+ }): Definition & {
59
+ input: Input;
60
+ result: Result;
61
+ replayResult: Replay & (ContractOutput<Replay> extends ContractOutput<Result> ? unknown : never);
62
+ wire: {
63
+ project: (value: ContractOutput<Result>) => ContractInput<Wire>;
64
+ schema: Wire;
65
+ };
66
+ };
67
+ //# sourceMappingURL=contract.d.mts.map
@@ -0,0 +1,2 @@
1
+ async function e(e,t){let n;return n=`kind`in e?await e.decode(t):`parse`in e?{value:await(e.parseAsync?e.parseAsync(t):e.parse(t))}:await e[`~standard`].validate(t),n}function t(e){return e}export{e as decodeContract,t as operationContract};
2
+ //# sourceMappingURL=contract.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.mjs","names":["decodeContract","result","schema","value","operationContract","definition"],"sources":["../../../src/modules/contracts/contract.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters -- These explicit validation boundaries receive untrusted transport values before schema decoding. */\n/** Structural contracts keep the optional Effect peer out of this module. */\nexport interface StandardSchema<Input = unknown, Output = Input> {\n\treadonly '~standard': {\n\t\treadonly version: 1\n\t\treadonly vendor: string\n\t\treadonly types?: { readonly input: Input; readonly output: Output }\n\t\treadonly validate: (\n\t\t\tvalue: unknown,\n\t\t) => ValidationResult<Output> | Promise<ValidationResult<Output>>\n\t}\n}\nexport interface ValidationIssue {\n\treadonly message: string\n\treadonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[]\n}\nexport type ValidationResult<Output> =\n\t| { readonly value: Output; readonly issues?: undefined }\n\t| { readonly issues: readonly ValidationIssue[] }\nexport interface LegacyParser<Output = unknown> {\n\treadonly parse: (value: unknown) => Output\n\treadonly parseAsync?: (value: unknown) => Promise<Output>\n}\n/** Decode execution is an opaque channel here; optional adapters give it concrete semantics. */\nexport interface Decoder<Input = unknown, Output = unknown, Execution = unknown> {\n\treadonly kind: 'contract' | 'effect-contract'\n\treadonly types?: { readonly input: Input; readonly output: Output }\n\treadonly decode: (value: unknown) => Execution\n}\nexport type ContractSchema = LegacyParser | StandardSchema<unknown, unknown> | Decoder\nexport type NeutralSchema =\n\t| LegacyParser\n\t| StandardSchema<unknown, unknown>\n\t| (Decoder<unknown, unknown, ValidationResult<unknown> | Promise<ValidationResult<unknown>>> & {\n\t\t\treadonly kind: 'contract'\n\t })\nexport type ContractInput<S> =\n\tS extends Decoder<infer Input, unknown, unknown>\n\t\t? Input\n\t\t: S extends StandardSchema<infer Input, unknown>\n\t\t\t? Input\n\t\t\t: S extends { readonly _input: infer Input }\n\t\t\t\t? Input\n\t\t\t\t: S extends LegacyParser<infer Output>\n\t\t\t\t\t? Awaited<Output>\n\t\t\t\t\t: never\nexport type ContractOutput<S> =\n\tS extends Decoder<unknown, infer Output, unknown>\n\t\t? Output\n\t\t: S extends StandardSchema<unknown, infer Output>\n\t\t\t? Output\n\t\t\t: S extends LegacyParser<infer Output>\n\t\t\t\t? Awaited<Output>\n\t\t\t\t: never\nexport type ContractExecution<S> =\n\tS extends Decoder<unknown, unknown, infer Execution> ? Execution : never\n\n/** Validation failures are values. Throws/rejections are deliberately left as defects. */\nexport async function decodeContract<S extends NeutralSchema>(\n\tschema: S,\n\tvalue: unknown,\n): Promise<ValidationResult<ContractOutput<S>>> {\n\tlet result: ValidationResult<unknown>\n\tif ('kind' in schema) result = await schema.decode(value)\n\telse if ('parse' in schema)\n\t\tresult = { value: await (schema.parseAsync ? schema.parseAsync(value) : schema.parse(value)) }\n\telse result = await schema['~standard'].validate(value)\n\t// SAFETY: each branch returns the output associated with this exact schema.\n\treturn result as ValidationResult<ContractOutput<S>>\n}\n\n/** Independent final and wire contracts never reuse the fresh-result transform. */\nexport function operationContract<\n\tconst Input extends ContractSchema,\n\tconst Result extends ContractSchema,\n\tconst Replay extends ContractSchema,\n\tconst Wire extends ContractSchema,\n\tconst Definition extends object,\n>(\n\tdefinition: Definition & {\n\t\tinput: Input\n\t\tresult: Result\n\t\treplayResult: Replay & (ContractOutput<Replay> extends ContractOutput<Result> ? unknown : never)\n\t\twire: { project: (value: ContractOutput<Result>) => ContractInput<Wire>; schema: Wire }\n\t},\n) {\n\treturn definition\n}\n"],"mappings":"AA0DA,eAAsBA,EACrB,EACA,EAC+C,CAC/C,IAAIC,EAMJ,MALA,CAGKA,EAHD,SAAUC,EAAiB,MAAMA,EAAO,OAAOC,CAAK,EAC/C,UAAWD,EACV,CAAE,MAAO,MAAOA,EAAO,WAAaA,EAAO,WAAWC,CAAK,EAAID,EAAO,MAAMC,CAAK,EAAG,EAChF,MAAMD,EAAO,YAAY,CAAC,SAASC,CAAK,EAE/CF,CACR,CAGA,SAAgBG,EAOf,EAMC,CACD,OAAOC,CACR,C"}
@@ -0,0 +1,18 @@
1
+ import { ValidationResult } from "./contract.mjs";
2
+ import { Infer, Validator } from "convex/values";
3
+ import { GenericDataModel, GenericDatabaseReader } from "convex/server";
4
+ /** Keep native registration authoritative, especially for actions with no db. */
5
+ export declare function convexContract<const V extends Validator<unknown, 'required' | 'optional', string>>(validator: V, options?: {
6
+ db?: GenericDatabaseReader<GenericDataModel>;
7
+ }): {
8
+ kind: "contract";
9
+ types?: {
10
+ readonly input: Infer<V>;
11
+ readonly output: Infer<V>;
12
+ } | undefined;
13
+ decode: (value: unknown) => Promise<ValidationResult<Infer<V>>> | ValidationResult<Infer<V>>;
14
+ schema: import("@standard-schema/spec").StandardSchemaV1<Infer<V>, Infer<V>>;
15
+ nativeValidator: V;
16
+ };
17
+ export type ConvexContractValue<V extends Validator<unknown, 'required' | 'optional', string>> = Infer<V>;
18
+ //# sourceMappingURL=convex.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{standardContract as e}from"./standard.mjs";import{toStandardSchema as t}from"convex-helpers/standardSchema";function n(n,r){return{...e(t(n,r)),nativeValidator:n}}export{n as convexContract};
2
+ //# sourceMappingURL=convex.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convex.mjs","names":["convexContract","standardContract","toStandardSchema","validator","options"],"sources":["../../../src/modules/contracts/convex.ts"],"sourcesContent":["import type { GenericDatabaseReader, GenericDataModel } from 'convex/server'\nimport type { Infer, Validator } from 'convex/values'\nimport { toStandardSchema } from 'convex-helpers/standardSchema'\nimport { standardContract } from './standard'\n\n/** Keep native registration authoritative, especially for actions with no db. */\nexport function convexContract<const V extends Validator<unknown, 'required' | 'optional', string>>(\n\tvalidator: V,\n\toptions?: { db?: GenericDatabaseReader<GenericDataModel> },\n) {\n\treturn { ...standardContract(toStandardSchema(validator, options)), nativeValidator: validator }\n}\nexport type ConvexContractValue<V extends Validator<unknown, 'required' | 'optional', string>> =\n\tInfer<V>\n"],"mappings":"A,mHAMA,SAAgBA,EACf,EACA,EACC,CACD,MAAO,CAAE,GAAGC,EAAiBC,EAAiBC,EAAWC,CAAO,CAAC,EAAG,gBAAiBD,CAAU,CAChG,C"}
@@ -0,0 +1,62 @@
1
+ import { ContractInput, ContractOutput, ContractSchema } from "./contract.mjs";
2
+ import { ErrorContract, ErrorDefinitions } from "./errors.mjs";
3
+ /** Schema-only domain vocabulary; implementations and host policies live in registries. */
4
+ export type DomainOperationContract = {
5
+ readonly input: ContractSchema;
6
+ readonly result: ContractSchema;
7
+ readonly classification?: string;
8
+ readonly wire?: {
9
+ readonly schema: ContractSchema;
10
+ readonly project: Function;
11
+ };
12
+ };
13
+ export type DomainCommandContract = DomainOperationContract & {
14
+ readonly classification: string;
15
+ readonly replayResult?: ContractSchema;
16
+ };
17
+ export type DomainQueryContract = DomainOperationContract & {
18
+ readonly replayResult?: never;
19
+ };
20
+ export type DomainActionContract = DomainOperationContract & {
21
+ readonly replayResult?: never;
22
+ };
23
+ export type DomainContract = {
24
+ readonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>;
25
+ readonly commands?: Readonly<Record<string, DomainCommandContract>>;
26
+ readonly queries?: Readonly<Record<string, DomainQueryContract>>;
27
+ readonly actions?: Readonly<Record<string, DomainActionContract>>;
28
+ };
29
+ type CheckedEntry<Entry extends DomainOperationContract> = {
30
+ readonly handler?: never;
31
+ readonly audit?: never;
32
+ readonly prepare?: never;
33
+ readonly guard?: never;
34
+ readonly middleware?: never;
35
+ readonly context?: never;
36
+ readonly wire?: Entry extends {
37
+ wire: {
38
+ schema: infer Wire;
39
+ };
40
+ } ? {
41
+ readonly schema: Wire;
42
+ readonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>;
43
+ } : never;
44
+ } & (Entry extends {
45
+ replayResult: infer Replay;
46
+ } ? {
47
+ readonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']> ? Replay : never;
48
+ } : {});
49
+ type CheckedSection<Section> = { readonly [Key in keyof Section]: Section[Key] extends DomainOperationContract ? CheckedEntry<Section[Key]> : never; };
50
+ type CheckedDomain<Definition> = { readonly [Section in Extract<keyof Definition, 'commands' | 'queries' | 'actions'>]: CheckedSection<Definition[Section]>; };
51
+ /** Preserve the declaration's literal keys and opaque validator/error-contract identities. */
52
+ export declare function defineDomainContract<const Definition extends DomainContract>(definition: (Definition & NoInfer<CheckedDomain<Definition>>) | (() => Definition & NoInfer<CheckedDomain<Definition>>)): Definition;
53
+ /** Exactness applies to variables as well as fresh object literals. */
54
+ export type ExactOperationKeys<Operations, Contracts> = Exclude<keyof Operations, keyof Contracts> extends never ? Exclude<keyof Contracts, keyof Operations> extends never ? string extends keyof Contracts ? never : unknown : never : never;
55
+ /** Correlated callback envelope for registry-level command audit. */
56
+ export type DomainAuditInput<Commands> = { [Key in Extract<keyof Commands, string>]: Commands[Key] extends DomainOperationContract ? {
57
+ operation: Key;
58
+ input: ContractOutput<Commands[Key]['input']>;
59
+ result: ContractOutput<Commands[Key]['result']>;
60
+ } : never; }[Extract<keyof Commands, string>];
61
+ export {};
62
+ //# sourceMappingURL=domain.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{memoize as e}from"./lazy.mjs";function t(t){if(typeof t!=`function`)return a(t);let n={},r=e(()=>{let e=a(t());return Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),Object.setPrototypeOf(n,Object.getPrototypeOf(e)),n});return new Proxy(n,{get:(e,t,n)=>Reflect.get(r(),t,n),has:(e,t)=>Reflect.has(r(),t),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(r(),t),set:(e,t,n)=>Reflect.set(r(),t,n),defineProperty:(e,t,n)=>Reflect.defineProperty(r(),t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r(),t),getPrototypeOf:()=>Reflect.getPrototypeOf(r()),setPrototypeOf:(e,t)=>Reflect.setPrototypeOf(r(),t),preventExtensions:()=>Reflect.preventExtensions(r()),isExtensible:()=>Reflect.isExtensible(r())})}const n=[`input`,`result`,`replayResult`,`wire`];function r(t,n,r){for(let i of n){let n=Object.getOwnPropertyDescriptor(t,i);if(!n?.get||!n.configurable)continue;let a=n.get;Object.defineProperty(t,i,{configurable:!0,enumerable:n.enumerable,get:e(()=>r(a.call(t)))})}}function i(e){return e&&typeof e==`object`&&r(e,n,e=>e),e}function a(e){for(let t of[`commands`,`queries`,`actions`]){let n=e?.[t];if(n&&typeof n==`object`){for(let e of Object.keys(n)){let t=Object.getOwnPropertyDescriptor(n,e);t&&`value`in t&&i(t.value)}r(n,Object.keys(n),i)}}return e}export{t as defineDomainContract};
2
+ //# sourceMappingURL=domain.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"domain.mjs","names":["defineDomainContract","definition","memoizeAccessors","target","read","memoize","value","key","receiver","descriptor","prototype","lazyFields","memoizeGetters","keys","get","wrap","memoizeOperation","operation","name","section"],"sources":["../../../src/modules/contracts/domain.ts"],"sourcesContent":["import { memoize } from './lazy'\nimport type { ContractSchema, ContractInput, ContractOutput } from './contract'\nimport type { ErrorContract, ErrorDefinitions } from './errors'\n\n/** Schema-only domain vocabulary; implementations and host policies live in registries. */\nexport type DomainOperationContract = {\n\treadonly input: ContractSchema\n\treadonly result: ContractSchema\n\treadonly classification?: string\n\treadonly wire?: { readonly schema: ContractSchema; readonly project: Function }\n}\nexport type DomainCommandContract = DomainOperationContract & {\n\treadonly classification: string\n\treadonly replayResult?: ContractSchema\n}\nexport type DomainQueryContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainActionContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainContract = {\n\treadonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\treadonly commands?: Readonly<Record<string, DomainCommandContract>>\n\treadonly queries?: Readonly<Record<string, DomainQueryContract>>\n\treadonly actions?: Readonly<Record<string, DomainActionContract>>\n}\n\ntype CheckedEntry<Entry extends DomainOperationContract> = {\n\treadonly handler?: never\n\treadonly audit?: never\n\treadonly prepare?: never\n\treadonly guard?: never\n\treadonly middleware?: never\n\treadonly context?: never\n\treadonly wire?: Entry extends { wire: { schema: infer Wire } }\n\t\t? {\n\t\t\t\treadonly schema: Wire\n\t\t\t\treadonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>\n\t\t\t}\n\t\t: never\n} & (Entry extends { replayResult: infer Replay }\n\t? {\n\t\t\treadonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']>\n\t\t\t\t? Replay\n\t\t\t\t: never\n\t\t}\n\t: {})\ntype CheckedSection<Section> = {\n\treadonly [Key in keyof Section]: Section[Key] extends DomainOperationContract\n\t\t? CheckedEntry<Section[Key]>\n\t\t: never\n}\ntype CheckedDomain<Definition> = {\n\treadonly [\n\t\tSection in Extract<keyof Definition, 'commands' | 'queries' | 'actions'>\n\t]: CheckedSection<Definition[Section]>\n}\n\n/** Preserve the declaration's literal keys and opaque validator/error-contract identities. */\nexport function defineDomainContract<const Definition extends DomainContract>(\n\tdefinition:\n\t\t| (Definition & NoInfer<CheckedDomain<Definition>>)\n\t\t| (() => Definition & NoInfer<CheckedDomain<Definition>>),\n): Definition {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- The public input is a checked declaration or its explicitly supported thunk.\n\tif (typeof definition !== 'function') return memoizeAccessors(definition)\n\t// SAFETY: the first read installs the inferred declaration's own descriptors on this target.\n\tconst target = {} as Definition\n\tconst read = memoize(() => {\n\t\tconst value = memoizeAccessors(definition())\n\t\tObject.defineProperties(target, Object.getOwnPropertyDescriptors(value))\n\t\tObject.setPrototypeOf(target, Object.getPrototypeOf(value))\n\t\treturn target\n\t})\n\treturn new Proxy(target, {\n\t\t// oxlint-disable-next-line anti-slop/no-reflect-get -- Preserve accessor receiver semantics for the forwarded declaration.\n\t\tget: (_target, key, receiver) => Reflect.get(read(), key, receiver),\n\t\thas: (_target, key) => Reflect.has(read(), key),\n\t\townKeys: () => Reflect.ownKeys(read()),\n\t\tgetOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(read(), key),\n\t\tset: (_target, key, value) => Reflect.set(read(), key, value),\n\t\tdefineProperty: (_target, key, descriptor) => Reflect.defineProperty(read(), key, descriptor),\n\t\tdeleteProperty: (_target, key) => Reflect.deleteProperty(read(), key),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(read()),\n\t\tsetPrototypeOf: (_target, prototype) => Reflect.setPrototypeOf(read(), prototype),\n\t\tpreventExtensions: () => Reflect.preventExtensions(read()),\n\t\tisExtensible: () => Reflect.isExtensible(read()),\n\t})\n}\n\n/** Exactness applies to variables as well as fresh object literals. */\nexport type ExactOperationKeys<Operations, Contracts> =\n\tExclude<keyof Operations, keyof Contracts> extends never\n\t\t? Exclude<keyof Contracts, keyof Operations> extends never\n\t\t\t? string extends keyof Contracts\n\t\t\t\t? never\n\t\t\t\t: unknown\n\t\t\t: never\n\t\t: never\n\n/** Correlated callback envelope for registry-level command audit. */\nexport type DomainAuditInput<Commands> = {\n\t[Key in Extract<keyof Commands, string>]: Commands[Key] extends DomainOperationContract\n\t\t? {\n\t\t\t\toperation: Key\n\t\t\t\tinput: ContractOutput<Commands[Key]['input']>\n\t\t\t\tresult: ContractOutput<Commands[Key]['result']>\n\t\t\t}\n\t\t: never\n}[Extract<keyof Commands, string>]\n\n/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof -- Wrapping walks checked declarations by descriptor and keeps schemas as opaque identities. */\nconst lazyFields = ['input', 'result', 'replayResult', 'wire'] as const\n\n/** Replace configurable getters with memoized ones in place, without invoking any of them. */\nfunction memoizeGetters(\n\ttarget: object,\n\tkeys: readonly PropertyKey[],\n\twrap: (value: unknown) => unknown,\n) {\n\tfor (const key of keys) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(target, key)\n\t\tif (!descriptor?.get || !descriptor.configurable) continue\n\t\tconst get = descriptor.get\n\t\tObject.defineProperty(target, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: descriptor.enumerable,\n\t\t\tget: memoize(() => wrap(get.call(target))),\n\t\t})\n\t}\n}\n\nfunction memoizeOperation(operation: unknown) {\n\tif (operation && typeof operation === 'object')\n\t\tmemoizeGetters(operation, lazyFields, (value) => value)\n\treturn operation\n}\n\n/** Getter-declared operations and fields build at most once and keep a stable identity. */\nfunction memoizeAccessors<Definition>(definition: Definition): Definition {\n\tfor (const name of ['commands', 'queries', 'actions'] as const) {\n\t\t// SAFETY: the checked declaration's sections are plain records of operation declarations.\n\t\tconst section = (definition as Record<string, unknown> | undefined)?.[name]\n\t\tif (!section || typeof section !== 'object') continue\n\t\tfor (const key of Object.keys(section)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(section, key)\n\t\t\tif (descriptor && 'value' in descriptor) memoizeOperation(descriptor.value)\n\t\t}\n\t\tmemoizeGetters(section, Object.keys(section), memoizeOperation)\n\t}\n\treturn definition\n}\n/* oxlint-enable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof */\n"],"mappings":"A,qCAwDA,SAAgBA,EACf,EAGa,CAEb,GAAI,OAAOC,GAAe,WAAY,OAAOC,EAAiBD,CAAU,EAExE,IAAME,EAAS,CAAC,EACVC,EAAOC,MAAc,CAC1B,IAAMC,EAAQJ,EAAiBD,EAAW,CAAC,EAG3C,OAFA,OAAO,iBAAiBE,EAAQ,OAAO,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