@tier0/sdk-v2 0.0.0-stage → 0.2.1

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 (310) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +7 -0
  3. package/README.md +201 -2
  4. package/dist/cjs/app-identity-contract.generated.d.ts +22 -0
  5. package/dist/cjs/app-identity-contract.generated.js +51 -0
  6. package/dist/cjs/app-identity-contract.generated.js.map +1 -0
  7. package/dist/cjs/capabilities.d.ts +54 -0
  8. package/dist/cjs/capabilities.js +134 -0
  9. package/dist/cjs/capabilities.js.map +1 -0
  10. package/dist/cjs/client.d.ts +604 -0
  11. package/dist/cjs/client.js +35 -0
  12. package/dist/cjs/client.js.map +1 -0
  13. package/dist/cjs/cloud-server.d.ts +31 -0
  14. package/dist/cjs/cloud-server.js +114 -0
  15. package/dist/cjs/cloud-server.js.map +1 -0
  16. package/dist/cjs/cloud-transport.d.ts +67 -0
  17. package/dist/cjs/cloud-transport.js +272 -0
  18. package/dist/cjs/cloud-transport.js.map +1 -0
  19. package/dist/cjs/controls.d.ts +93 -0
  20. package/dist/cjs/controls.js +169 -0
  21. package/dist/cjs/controls.js.map +1 -0
  22. package/dist/cjs/data/bootstrap.d.ts +70 -0
  23. package/dist/cjs/data/bootstrap.js +291 -0
  24. package/dist/cjs/data/bootstrap.js.map +1 -0
  25. package/dist/cjs/data/call.d.ts +33 -0
  26. package/dist/cjs/data/call.js +216 -0
  27. package/dist/cjs/data/call.js.map +1 -0
  28. package/dist/cjs/data/client.d.ts +134 -0
  29. package/dist/cjs/data/client.js +185 -0
  30. package/dist/cjs/data/client.js.map +1 -0
  31. package/dist/cjs/data/collection.d.ts +335 -0
  32. package/dist/cjs/data/collection.js +601 -0
  33. package/dist/cjs/data/collection.js.map +1 -0
  34. package/dist/cjs/data/context.d.ts +12 -0
  35. package/dist/cjs/data/context.js +50 -0
  36. package/dist/cjs/data/context.js.map +1 -0
  37. package/dist/cjs/data/declarations.d.ts +11 -0
  38. package/dist/cjs/data/declarations.js +18 -0
  39. package/dist/cjs/data/declarations.js.map +1 -0
  40. package/dist/cjs/data/define.d.ts +77 -0
  41. package/dist/cjs/data/define.js +31 -0
  42. package/dist/cjs/data/define.js.map +1 -0
  43. package/dist/cjs/data/error.d.ts +78 -0
  44. package/dist/cjs/data/error.js +182 -0
  45. package/dist/cjs/data/error.js.map +1 -0
  46. package/dist/cjs/data/index.d.ts +24 -0
  47. package/dist/cjs/data/index.js +49 -0
  48. package/dist/cjs/data/index.js.map +1 -0
  49. package/dist/cjs/data/schema.d.ts +88 -0
  50. package/dist/cjs/data/schema.js +657 -0
  51. package/dist/cjs/data/schema.js.map +1 -0
  52. package/dist/cjs/data/sort.d.ts +8 -0
  53. package/dist/cjs/data/sort.js +21 -0
  54. package/dist/cjs/data/sort.js.map +1 -0
  55. package/dist/cjs/data/subscribe.d.ts +108 -0
  56. package/dist/cjs/data/subscribe.js +270 -0
  57. package/dist/cjs/data/subscribe.js.map +1 -0
  58. package/dist/cjs/files.d.ts +67 -0
  59. package/dist/cjs/files.js +119 -0
  60. package/dist/cjs/files.js.map +1 -0
  61. package/dist/cjs/framework-scope.d.ts +1 -0
  62. package/dist/cjs/framework-scope.js +14 -0
  63. package/dist/cjs/framework-scope.js.map +1 -0
  64. package/dist/cjs/index.d.ts +14 -0
  65. package/dist/cjs/index.js +33 -0
  66. package/dist/cjs/index.js.map +1 -0
  67. package/dist/cjs/mq/broker.d.ts +65 -0
  68. package/dist/cjs/mq/broker.js +115 -0
  69. package/dist/cjs/mq/broker.js.map +1 -0
  70. package/dist/cjs/mq/client.d.ts +37 -0
  71. package/dist/cjs/mq/client.js +321 -0
  72. package/dist/cjs/mq/client.js.map +1 -0
  73. package/dist/cjs/mq/index.d.ts +5 -0
  74. package/dist/cjs/mq/index.js +11 -0
  75. package/dist/cjs/mq/index.js.map +1 -0
  76. package/dist/cjs/mq/types.d.ts +48 -0
  77. package/dist/cjs/mq/types.js +3 -0
  78. package/dist/cjs/mq/types.js.map +1 -0
  79. package/dist/cjs/openapi/api.generated.d.ts +820 -0
  80. package/dist/cjs/openapi/api.generated.js +607 -0
  81. package/dist/cjs/openapi/api.generated.js.map +1 -0
  82. package/dist/cjs/openapi/client.d.ts +56 -0
  83. package/dist/cjs/openapi/client.js +219 -0
  84. package/dist/cjs/openapi/client.js.map +1 -0
  85. package/dist/cjs/openapi/codecs.generated.d.ts +2234 -0
  86. package/dist/cjs/openapi/codecs.generated.js +6 -0
  87. package/dist/cjs/openapi/codecs.generated.js.map +1 -0
  88. package/dist/cjs/openapi/index.d.ts +5 -0
  89. package/dist/cjs/openapi/index.js +12 -0
  90. package/dist/cjs/openapi/index.js.map +1 -0
  91. package/dist/cjs/openapi/types.generated.d.ts +3227 -0
  92. package/dist/cjs/openapi/types.generated.js +3 -0
  93. package/dist/cjs/openapi/types.generated.js.map +1 -0
  94. package/dist/cjs/package.json +1 -0
  95. package/dist/cjs/react.d.ts +9 -0
  96. package/dist/cjs/react.js +16 -0
  97. package/dist/cjs/react.js.map +1 -0
  98. package/dist/cjs/runtime-context.d.ts +9 -0
  99. package/dist/cjs/runtime-context.js +25 -0
  100. package/dist/cjs/runtime-context.js.map +1 -0
  101. package/dist/cjs/runtime-env.d.ts +1 -0
  102. package/dist/cjs/runtime-env.js +18 -0
  103. package/dist/cjs/runtime-env.js.map +1 -0
  104. package/dist/cjs/source.d.ts +39 -0
  105. package/dist/cjs/source.js +29 -0
  106. package/dist/cjs/source.js.map +1 -0
  107. package/dist/cjs/stream.d.ts +40 -0
  108. package/dist/cjs/stream.js +33 -0
  109. package/dist/cjs/stream.js.map +1 -0
  110. package/dist/cjs/uns-v2/client.d.ts +132 -0
  111. package/dist/cjs/uns-v2/client.js +352 -0
  112. package/dist/cjs/uns-v2/client.js.map +1 -0
  113. package/dist/cjs/uns-v2/codec.d.ts +11 -0
  114. package/dist/cjs/uns-v2/codec.js +290 -0
  115. package/dist/cjs/uns-v2/codec.js.map +1 -0
  116. package/dist/cjs/uns-v2/data-client.d.ts +10 -0
  117. package/dist/cjs/uns-v2/data-client.js +18 -0
  118. package/dist/cjs/uns-v2/data-client.js.map +1 -0
  119. package/dist/cjs/uns-v2/generated.d.ts +18178 -0
  120. package/dist/cjs/uns-v2/generated.js +144 -0
  121. package/dist/cjs/uns-v2/generated.js.map +1 -0
  122. package/dist/cjs/uns-v2/index.d.ts +5 -0
  123. package/dist/cjs/uns-v2/index.js +24 -0
  124. package/dist/cjs/uns-v2/index.js.map +1 -0
  125. package/dist/cjs/uns-v2/sse.d.ts +20 -0
  126. package/dist/cjs/uns-v2/sse.js +65 -0
  127. package/dist/cjs/uns-v2/sse.js.map +1 -0
  128. package/dist/cjs/vue.d.ts +9 -0
  129. package/dist/cjs/vue.js +39 -0
  130. package/dist/cjs/vue.js.map +1 -0
  131. package/dist/esm/app-identity-contract.generated.d.ts +22 -0
  132. package/dist/esm/app-identity-contract.generated.js +48 -0
  133. package/dist/esm/app-identity-contract.generated.js.map +1 -0
  134. package/dist/esm/capabilities.d.ts +54 -0
  135. package/dist/esm/capabilities.js +129 -0
  136. package/dist/esm/capabilities.js.map +1 -0
  137. package/dist/esm/client.d.ts +604 -0
  138. package/dist/esm/client.js +32 -0
  139. package/dist/esm/client.js.map +1 -0
  140. package/dist/esm/cloud-server.d.ts +31 -0
  141. package/dist/esm/cloud-server.js +109 -0
  142. package/dist/esm/cloud-server.js.map +1 -0
  143. package/dist/esm/cloud-transport.d.ts +67 -0
  144. package/dist/esm/cloud-transport.js +267 -0
  145. package/dist/esm/cloud-transport.js.map +1 -0
  146. package/dist/esm/controls.d.ts +93 -0
  147. package/dist/esm/controls.js +163 -0
  148. package/dist/esm/controls.js.map +1 -0
  149. package/dist/esm/data/bootstrap.d.ts +70 -0
  150. package/dist/esm/data/bootstrap.js +286 -0
  151. package/dist/esm/data/bootstrap.js.map +1 -0
  152. package/dist/esm/data/call.d.ts +33 -0
  153. package/dist/esm/data/call.js +211 -0
  154. package/dist/esm/data/call.js.map +1 -0
  155. package/dist/esm/data/client.d.ts +134 -0
  156. package/dist/esm/data/client.js +181 -0
  157. package/dist/esm/data/client.js.map +1 -0
  158. package/dist/esm/data/collection.d.ts +335 -0
  159. package/dist/esm/data/collection.js +594 -0
  160. package/dist/esm/data/collection.js.map +1 -0
  161. package/dist/esm/data/context.d.ts +12 -0
  162. package/dist/esm/data/context.js +44 -0
  163. package/dist/esm/data/context.js.map +1 -0
  164. package/dist/esm/data/declarations.d.ts +11 -0
  165. package/dist/esm/data/declarations.js +10 -0
  166. package/dist/esm/data/declarations.js.map +1 -0
  167. package/dist/esm/data/define.d.ts +77 -0
  168. package/dist/esm/data/define.js +27 -0
  169. package/dist/esm/data/define.js.map +1 -0
  170. package/dist/esm/data/error.d.ts +78 -0
  171. package/dist/esm/data/error.js +176 -0
  172. package/dist/esm/data/error.js.map +1 -0
  173. package/dist/esm/data/index.d.ts +24 -0
  174. package/dist/esm/data/index.js +20 -0
  175. package/dist/esm/data/index.js.map +1 -0
  176. package/dist/esm/data/schema.d.ts +88 -0
  177. package/dist/esm/data/schema.js +646 -0
  178. package/dist/esm/data/schema.js.map +1 -0
  179. package/dist/esm/data/sort.d.ts +8 -0
  180. package/dist/esm/data/sort.js +18 -0
  181. package/dist/esm/data/sort.js.map +1 -0
  182. package/dist/esm/data/subscribe.d.ts +108 -0
  183. package/dist/esm/data/subscribe.js +265 -0
  184. package/dist/esm/data/subscribe.js.map +1 -0
  185. package/dist/esm/files.d.ts +67 -0
  186. package/dist/esm/files.js +113 -0
  187. package/dist/esm/files.js.map +1 -0
  188. package/dist/esm/framework-scope.d.ts +1 -0
  189. package/dist/esm/framework-scope.js +11 -0
  190. package/dist/esm/framework-scope.js.map +1 -0
  191. package/dist/esm/index.d.ts +14 -0
  192. package/dist/esm/index.js +10 -0
  193. package/dist/esm/index.js.map +1 -0
  194. package/dist/esm/mq/broker.d.ts +65 -0
  195. package/dist/esm/mq/broker.js +109 -0
  196. package/dist/esm/mq/broker.js.map +1 -0
  197. package/dist/esm/mq/client.d.ts +37 -0
  198. package/dist/esm/mq/client.js +314 -0
  199. package/dist/esm/mq/client.js.map +1 -0
  200. package/dist/esm/mq/index.d.ts +5 -0
  201. package/dist/esm/mq/index.js +3 -0
  202. package/dist/esm/mq/index.js.map +1 -0
  203. package/dist/esm/mq/types.d.ts +48 -0
  204. package/dist/esm/mq/types.js +2 -0
  205. package/dist/esm/mq/types.js.map +1 -0
  206. package/dist/esm/openapi/api.generated.d.ts +820 -0
  207. package/dist/esm/openapi/api.generated.js +603 -0
  208. package/dist/esm/openapi/api.generated.js.map +1 -0
  209. package/dist/esm/openapi/client.d.ts +56 -0
  210. package/dist/esm/openapi/client.js +210 -0
  211. package/dist/esm/openapi/client.js.map +1 -0
  212. package/dist/esm/openapi/codecs.generated.d.ts +2234 -0
  213. package/dist/esm/openapi/codecs.generated.js +3 -0
  214. package/dist/esm/openapi/codecs.generated.js.map +1 -0
  215. package/dist/esm/openapi/index.d.ts +5 -0
  216. package/dist/esm/openapi/index.js +3 -0
  217. package/dist/esm/openapi/index.js.map +1 -0
  218. package/dist/esm/openapi/types.generated.d.ts +3227 -0
  219. package/dist/esm/openapi/types.generated.js +2 -0
  220. package/dist/esm/openapi/types.generated.js.map +1 -0
  221. package/dist/esm/package.json +1 -0
  222. package/dist/esm/react.d.ts +9 -0
  223. package/dist/esm/react.js +12 -0
  224. package/dist/esm/react.js.map +1 -0
  225. package/dist/esm/runtime-context.d.ts +9 -0
  226. package/dist/esm/runtime-context.js +22 -0
  227. package/dist/esm/runtime-context.js.map +1 -0
  228. package/dist/esm/runtime-env.d.ts +1 -0
  229. package/dist/esm/runtime-env.js +15 -0
  230. package/dist/esm/runtime-env.js.map +1 -0
  231. package/dist/esm/source.d.ts +39 -0
  232. package/dist/esm/source.js +25 -0
  233. package/dist/esm/source.js.map +1 -0
  234. package/dist/esm/stream.d.ts +40 -0
  235. package/dist/esm/stream.js +29 -0
  236. package/dist/esm/stream.js.map +1 -0
  237. package/dist/esm/uns-v2/client.d.ts +132 -0
  238. package/dist/esm/uns-v2/client.js +343 -0
  239. package/dist/esm/uns-v2/client.js.map +1 -0
  240. package/dist/esm/uns-v2/codec.d.ts +11 -0
  241. package/dist/esm/uns-v2/codec.js +284 -0
  242. package/dist/esm/uns-v2/codec.js.map +1 -0
  243. package/dist/esm/uns-v2/data-client.d.ts +10 -0
  244. package/dist/esm/uns-v2/data-client.js +14 -0
  245. package/dist/esm/uns-v2/data-client.js.map +1 -0
  246. package/dist/esm/uns-v2/generated.d.ts +18178 -0
  247. package/dist/esm/uns-v2/generated.js +141 -0
  248. package/dist/esm/uns-v2/generated.js.map +1 -0
  249. package/dist/esm/uns-v2/index.d.ts +5 -0
  250. package/dist/esm/uns-v2/index.js +5 -0
  251. package/dist/esm/uns-v2/index.js.map +1 -0
  252. package/dist/esm/uns-v2/sse.d.ts +20 -0
  253. package/dist/esm/uns-v2/sse.js +60 -0
  254. package/dist/esm/uns-v2/sse.js.map +1 -0
  255. package/dist/esm/vue.d.ts +9 -0
  256. package/dist/esm/vue.js +36 -0
  257. package/dist/esm/vue.js.map +1 -0
  258. package/docs/acceptance-2026-10-22.md +88 -0
  259. package/package.json +243 -4
  260. package/skills/tier0-sdk-v2/SKILL.md +66 -0
  261. package/skills/tier0-sdk-v2/references/integration.md +72 -0
  262. package/skills/tier0-sdk-v2/tier0-sdk-v2-agent/SKILL.md +73 -0
  263. package/skills/tier0-sdk-v2/tier0-sdk-v2-agent/references/results.md +45 -0
  264. package/skills/tier0-sdk-v2/tier0-sdk-v2-controls/SKILL.md +63 -0
  265. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/SKILL.md +58 -0
  266. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/consistency.md +70 -0
  267. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/errors.md +82 -0
  268. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +113 -0
  269. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/read-write.md +168 -0
  270. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/schema-evolution.md +36 -0
  271. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/SKILL.md +85 -0
  272. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/delete.md +22 -0
  273. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/download.md +49 -0
  274. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/multipart.md +42 -0
  275. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/upload.md +27 -0
  276. package/skills/tier0-sdk-v2/tier0-sdk-v2-files/references/url.md +22 -0
  277. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/SKILL.md +56 -0
  278. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/references/app-members.md +41 -0
  279. package/skills/tier0-sdk-v2/tier0-sdk-v2-members/references/platform-members.md +56 -0
  280. package/skills/tier0-sdk-v2/tier0-sdk-v2-mq/SKILL.md +78 -0
  281. package/skills/tier0-sdk-v2/tier0-sdk-v2-mq/references/quickstart.md +69 -0
  282. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/SKILL.md +42 -0
  283. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/references/get.md +34 -0
  284. package/skills/tier0-sdk-v2/tier0-sdk-v2-notifications/references/send.md +72 -0
  285. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/SKILL.md +38 -0
  286. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/changes.md +40 -0
  287. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/create.md +63 -0
  288. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/delete.md +47 -0
  289. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/protocols.md +36 -0
  290. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/read.md +34 -0
  291. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/state.md +37 -0
  292. package/skills/tier0-sdk-v2/tier0-sdk-v2-source/references/update.md +62 -0
  293. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/SKILL.md +43 -0
  294. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/create.md +56 -0
  295. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/delete.md +35 -0
  296. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/deploy.md +64 -0
  297. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/lifecycle.md +26 -0
  298. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/read.md +35 -0
  299. package/skills/tier0-sdk-v2/tier0-sdk-v2-stream/references/update.md +36 -0
  300. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/SKILL.md +64 -0
  301. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/references/info.md +23 -0
  302. package/skills/tier0-sdk-v2/tier0-sdk-v2-system/references/whoami.md +21 -0
  303. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/SKILL.md +55 -0
  304. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/create.md +56 -0
  305. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/data-workflows.md +69 -0
  306. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/delete.md +53 -0
  307. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md +38 -0
  308. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/read.md +34 -0
  309. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/restore.md +39 -0
  310. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/update.md +62 -0
@@ -0,0 +1,657 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SCHEMA_LIMITS = exports.CollectionSchemaError = void 0;
4
+ exports.zodJsonSchema = zodJsonSchema;
5
+ exports.toRecordSchema = toRecordSchema;
6
+ exports.recordSchemaAt = recordSchemaAt;
7
+ exports.compileCollection = compileCollection;
8
+ exports.validateDocument = validateDocument;
9
+ exports.validateStepData = validateStepData;
10
+ exports.validateUpdate = validateUpdate;
11
+ /**
12
+ * Zod 4 → UNS record schema normalizer, plus write-time validation.
13
+ *
14
+ * UNS stores one closed JSON-schema subset per collection: `type`,
15
+ * `properties`, `required`, `additionalProperties: false`, `items`, `enum`,
16
+ * `minimum`, `maximum`, declared `format`, `title`, `description`. `toRecordSchema` converts the
17
+ * `z.toJSONSchema` output into exactly that subset and rejects every other
18
+ * keyword with a concrete replacement, so a declaration that cannot be stored
19
+ * fails when it is compiled (an App can compile its declarations at build
20
+ * time) instead of on the first request.
21
+ */
22
+ const zod_1 = require("zod");
23
+ const define_js_1 = require("./define.js");
24
+ class CollectionSchemaError extends Error {
25
+ alias;
26
+ issues;
27
+ constructor(alias, issues) {
28
+ super([
29
+ `Collection "${alias}" cannot be stored in UNS:`,
30
+ ...issues.map((issue) => ` - ${issue.path || '(root)'}: ${issue.message}`),
31
+ ].join('\n'));
32
+ this.name = 'CollectionSchemaError';
33
+ this.alias = alias;
34
+ this.issues = issues;
35
+ }
36
+ }
37
+ exports.CollectionSchemaError = CollectionSchemaError;
38
+ /** UNS limits (unsmeta Schema.validate and collection indexes); title/description are UTF-8 bytes. */
39
+ exports.SCHEMA_LIMITS = {
40
+ depth: 8,
41
+ properties: 128,
42
+ enumValues: 100,
43
+ title: 512,
44
+ description: 2048,
45
+ indexes: 16,
46
+ indexPaths: 3,
47
+ ttlIndexes: 1,
48
+ minExpireAfterSeconds: 60,
49
+ maxExpireAfterSeconds: 31_536_000,
50
+ };
51
+ const SAFE_INTEGER_BOUND = Number.MAX_SAFE_INTEGER;
52
+ const SCHEMA_TYPES = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean']);
53
+ const KEPT_KEYWORDS = new Set([
54
+ 'type',
55
+ 'format',
56
+ 'title',
57
+ 'description',
58
+ 'properties',
59
+ 'required',
60
+ 'additionalProperties',
61
+ 'items',
62
+ 'enum',
63
+ 'minimum',
64
+ 'maximum',
65
+ ]);
66
+ const RESERVED_FIELDS = new Set(['_id', '_meta']);
67
+ const NULLABLE_HINT = '`.nullable()`, `.nullish()` and `z.union()` are not storable. Make the field `.optional()` and leave it out instead of storing null; model alternatives as one type or as separate optional fields.';
68
+ const API_INPUT_HINT = 'Keep the collection schema plain and enforce this rule in the API input schema.';
69
+ const OPEN_OBJECT_HINT = '`z.record()`, `z.looseObject()` and `.catchall()` are not storable: every stored object is closed. Declare fixed properties, or store an array of `{ key, value }` objects.';
70
+ const KEYWORD_HINTS = {
71
+ anyOf: NULLABLE_HINT,
72
+ oneOf: NULLABLE_HINT,
73
+ allOf: '`z.intersection()` / `.and()` is not storable. Merge the objects with `.extend()`.',
74
+ not: 'Negated schemas are not storable.',
75
+ default: '`.default()` / `.prefault()` / `.catch()` is not storable. Apply defaults in the service when building the document.',
76
+ format: `Strings only support the declaration \`z.string().meta({ format: 'date-time' })\`, which does not validate or convert dates. Other string formats (\`z.email()\`, \`z.uuid()\`...) are not storable. ${API_INPUT_HINT}`,
77
+ pattern: `\`.regex()\`, \`.startsWith()\` and similar patterns are not storable. Use \`z.string()\`. ${API_INPUT_HINT}`,
78
+ minLength: `String length limits are not storable. Use \`z.string()\`. ${API_INPUT_HINT}`,
79
+ maxLength: `String length limits are not storable. Use \`z.string()\`. ${API_INPUT_HINT}`,
80
+ contentEncoding: 'Encoded string content is not storable. Use `z.string()`.',
81
+ const: '`z.literal()` is not storable. Use `z.enum([...])`.',
82
+ exclusiveMinimum: '`.gt()` / `.positive()` (exclusive bounds) are not storable. Use inclusive `.min()` (`.min(1)` for a positive integer).',
83
+ exclusiveMaximum: '`.lt()` / `.negative()` are not storable. Use inclusive `.max()`.',
84
+ multipleOf: `\`.multipleOf()\` / \`.step()\` is not storable. ${API_INPUT_HINT}`,
85
+ minItems: `Array length limits are not storable. ${API_INPUT_HINT}`,
86
+ maxItems: `Array length limits are not storable. ${API_INPUT_HINT}`,
87
+ uniqueItems: `Array uniqueness is not storable. ${API_INPUT_HINT}`,
88
+ prefixItems: '`z.tuple()` is not storable. Use an object with named fields.',
89
+ propertyNames: OPEN_OBJECT_HINT,
90
+ patternProperties: OPEN_OBJECT_HINT,
91
+ minProperties: OPEN_OBJECT_HINT,
92
+ maxProperties: OPEN_OBJECT_HINT,
93
+ $ref: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',
94
+ $defs: 'Recursive or shared `$ref` schemas are not storable. Inline the structure or keep child records in their own collection.',
95
+ readOnly: '`.readonly()` is not storable; remove it from the collection schema.',
96
+ };
97
+ const encoder = new TextEncoder();
98
+ function utf8Bytes(value) {
99
+ return encoder.encode(value).length;
100
+ }
101
+ function isPlainObject(value) {
102
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
103
+ }
104
+ function joinPath(base, key) {
105
+ if (typeof key === 'number')
106
+ return `${base}[${key}]`;
107
+ return base ? `${base}.${key}` : key;
108
+ }
109
+ function validFieldName(key) {
110
+ if (RESERVED_FIELDS.has(key))
111
+ return `"${key}" is a system field and cannot be declared.`;
112
+ if (key.length === 0 || key === '[]')
113
+ return `Field name "${key}" is reserved.`;
114
+ if (/[.$\\]/.test(key))
115
+ return `Field name "${key}" must not contain ".", "$" or "\\".`;
116
+ return null;
117
+ }
118
+ function inferEnumType(values) {
119
+ if (values.length === 0)
120
+ return null;
121
+ if (values.every((value) => typeof value === 'string'))
122
+ return 'string';
123
+ if (values.every((value) => typeof value === 'boolean'))
124
+ return 'boolean';
125
+ if (values.every((value) => typeof value === 'number')) {
126
+ return values.every((value) => Number.isInteger(value)) ? 'integer' : 'number';
127
+ }
128
+ return null;
129
+ }
130
+ function normalizeNode(node, path, depth, issues) {
131
+ if (!isPlainObject(node)) {
132
+ issues.push({ path, message: 'Expected a schema object.' });
133
+ return null;
134
+ }
135
+ if (depth > exports.SCHEMA_LIMITS.depth) {
136
+ issues.push({ path, message: `Nesting deeper than ${exports.SCHEMA_LIMITS.depth} levels is not storable. Flatten the structure.` });
137
+ return null;
138
+ }
139
+ let valid = true;
140
+ for (const key of Object.keys(node)) {
141
+ if (KEPT_KEYWORDS.has(key) || (depth === 0 && key === '$schema'))
142
+ continue;
143
+ valid = false;
144
+ issues.push({
145
+ path,
146
+ message: `\`${key}\` is not supported. ${KEYWORD_HINTS[key] ?? 'Only type, properties, items, enum, minimum, maximum, declared format, title and description are storable; remove this constraint from the collection schema.'}`,
147
+ });
148
+ }
149
+ const rawEnum = Array.isArray(node.enum) ? node.enum : undefined;
150
+ let type = node.type;
151
+ if (type === undefined && rawEnum)
152
+ type = inferEnumType(rawEnum) ?? undefined;
153
+ if (Array.isArray(type)) {
154
+ issues.push({ path, message: `A field must have one type, got [${type.join(', ')}]. ${NULLABLE_HINT}` });
155
+ return null;
156
+ }
157
+ if (type === 'null') {
158
+ issues.push({ path, message: '`z.null()` is not storable. Make the field optional and leave it out.' });
159
+ return null;
160
+ }
161
+ if (typeof type !== 'string' || !SCHEMA_TYPES.has(type)) {
162
+ if (type === undefined && !('anyOf' in node) && !('oneOf' in node) && !('allOf' in node)) {
163
+ issues.push({
164
+ path,
165
+ message: 'Every field needs a concrete type; `z.any()`, `z.unknown()` and `z.json()` are not storable. Declare the actual shape.',
166
+ });
167
+ }
168
+ return null;
169
+ }
170
+ const out = { type: type };
171
+ const format = node.format;
172
+ if (format !== undefined) {
173
+ if ((type === 'integer' && format === 'int32') || (type === 'number' && (format === 'float' || format === 'double')) || (type === 'string' && format === 'date-time')) {
174
+ out.format = format;
175
+ }
176
+ else {
177
+ issues.push({
178
+ path,
179
+ message: type === 'string'
180
+ ? KEYWORD_HINTS.format
181
+ : '`format` must be "int32" on integer fields, "float" / "double" on number fields, or "date-time" on string fields. Other types and formats are not storable.',
182
+ });
183
+ valid = false;
184
+ }
185
+ }
186
+ for (const key of ['title', 'description']) {
187
+ const value = node[key];
188
+ if (value === undefined)
189
+ continue;
190
+ const limit = key === 'title' ? exports.SCHEMA_LIMITS.title : exports.SCHEMA_LIMITS.description;
191
+ // UNS measures these with Go len(): UTF-8 bytes, so CJK text uses 3 per character.
192
+ if (typeof value !== 'string' || utf8Bytes(value) > limit) {
193
+ issues.push({ path, message: `\`${key}\` must be a string of at most ${limit} UTF-8 bytes.` });
194
+ valid = false;
195
+ }
196
+ else if (value) {
197
+ out[key] = value;
198
+ }
199
+ }
200
+ if (type === 'object') {
201
+ if (node.additionalProperties !== undefined && node.additionalProperties !== false) {
202
+ issues.push({ path, message: OPEN_OBJECT_HINT });
203
+ valid = false;
204
+ }
205
+ const rawProperties = isPlainObject(node.properties) ? node.properties : {};
206
+ const names = Object.keys(rawProperties);
207
+ if (names.length > exports.SCHEMA_LIMITS.properties) {
208
+ issues.push({ path, message: `More than ${exports.SCHEMA_LIMITS.properties} properties is not storable. Split the object.` });
209
+ valid = false;
210
+ }
211
+ const properties = {};
212
+ for (const name of names) {
213
+ const fieldPath = joinPath(path, name);
214
+ const nameProblem = validFieldName(name);
215
+ if (nameProblem) {
216
+ issues.push({ path: fieldPath, message: nameProblem });
217
+ valid = false;
218
+ continue;
219
+ }
220
+ const child = normalizeNode(rawProperties[name], fieldPath, depth + 1, issues);
221
+ if (child)
222
+ properties[name] = child;
223
+ else
224
+ valid = false;
225
+ }
226
+ out.properties = properties;
227
+ const required = Array.isArray(node.required)
228
+ ? [...new Set(node.required.filter((name) => typeof name === 'string' && name in rawProperties))].sort()
229
+ : [];
230
+ if (required.length > 0)
231
+ out.required = required;
232
+ out.additionalProperties = false;
233
+ }
234
+ else if (node.properties !== undefined || node.required !== undefined || node.additionalProperties !== undefined) {
235
+ issues.push({ path, message: 'Only objects may declare properties.' });
236
+ valid = false;
237
+ }
238
+ if (type === 'array') {
239
+ const items = node.items;
240
+ if (!isPlainObject(items)) {
241
+ issues.push({ path, message: 'Arrays need one item schema (`z.array(item)`).' });
242
+ valid = false;
243
+ }
244
+ else {
245
+ const child = normalizeNode(items, `${path}[]`, depth + 1, issues);
246
+ if (child)
247
+ out.items = child;
248
+ else
249
+ valid = false;
250
+ }
251
+ }
252
+ if (rawEnum) {
253
+ const values = [];
254
+ for (const value of rawEnum) {
255
+ const scalar = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
256
+ const fits = scalar &&
257
+ (type === 'string'
258
+ ? typeof value === 'string'
259
+ : type === 'boolean'
260
+ ? typeof value === 'boolean'
261
+ : type === 'integer'
262
+ ? Number.isInteger(value)
263
+ : type === 'number'
264
+ ? typeof value === 'number'
265
+ : false);
266
+ if (!fits) {
267
+ issues.push({ path, message: `Enum value ${JSON.stringify(value)} does not match type ${type}.` });
268
+ valid = false;
269
+ }
270
+ else if (!values.some((existing) => existing === value)) {
271
+ values.push(value);
272
+ }
273
+ }
274
+ if (values.length > exports.SCHEMA_LIMITS.enumValues) {
275
+ issues.push({ path, message: `More than ${exports.SCHEMA_LIMITS.enumValues} enum values is not storable. Use a reference collection.` });
276
+ valid = false;
277
+ }
278
+ if (values.length > 0)
279
+ out.enum = values;
280
+ }
281
+ for (const key of ['minimum', 'maximum']) {
282
+ const value = node[key];
283
+ if (value === undefined)
284
+ continue;
285
+ if (type !== 'number' && type !== 'integer') {
286
+ issues.push({ path, message: `\`${key}\` is only valid on numbers.` });
287
+ valid = false;
288
+ continue;
289
+ }
290
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
291
+ issues.push({ path, message: `\`${key}\` must be a finite number.` });
292
+ valid = false;
293
+ continue;
294
+ }
295
+ // z.number().int() always emits the safe-integer range; it is not a business bound.
296
+ if (type === 'integer' && Math.abs(value) === SAFE_INTEGER_BOUND)
297
+ continue;
298
+ out[key] = value;
299
+ }
300
+ if (out.minimum !== undefined && out.maximum !== undefined && out.minimum > out.maximum) {
301
+ issues.push({ path, message: '`minimum` is greater than `maximum`.' });
302
+ valid = false;
303
+ }
304
+ return valid ? out : null;
305
+ }
306
+ /** Raw `z.toJSONSchema` output; exported for the snapshot tests. */
307
+ function zodJsonSchema(schema) {
308
+ return zod_1.z.toJSONSchema(schema, { io: 'output', unrepresentable: 'throw', cycles: 'throw' });
309
+ }
310
+ /** Converts a Zod object schema to the UNS record-schema subset or throws `CollectionSchemaError`. */
311
+ function toRecordSchema(alias, schema) {
312
+ let raw;
313
+ try {
314
+ raw = zodJsonSchema(schema);
315
+ }
316
+ catch (error) {
317
+ throw new CollectionSchemaError(alias, [
318
+ {
319
+ path: '',
320
+ message: `${error instanceof Error ? error.message : String(error)}. \`z.date()\`, \`z.bigint()\`, \`.transform()\`, \`z.map()\`, \`z.set()\`, \`z.custom()\` and recursive schemas are not storable; store instants as ISO-8601 UTC strings from \`toISOString()\` and dates as "YYYY-MM-DD" strings, and keep transforms in the API input schema.`,
321
+ },
322
+ ]);
323
+ }
324
+ const issues = [];
325
+ const normalized = normalizeNode(raw, '', 0, issues);
326
+ if (normalized && normalized.type !== 'object') {
327
+ issues.push({ path: '', message: 'A collection schema must be `z.object({...})`.' });
328
+ }
329
+ if (issues.length > 0 || !normalized)
330
+ throw new CollectionSchemaError(alias, issues);
331
+ return normalized;
332
+ }
333
+ /** Resolves a dotted business path in a record schema; array levels accept index segments. */
334
+ function recordSchemaAt(schema, path) {
335
+ let current = schema;
336
+ for (const segment of path.split('.')) {
337
+ if (!current)
338
+ return undefined;
339
+ if (current.type === 'array' && isArraySegment(segment)) {
340
+ current = current.items;
341
+ }
342
+ else if (current.type === 'object') {
343
+ current = current.properties?.[segment];
344
+ }
345
+ else {
346
+ return undefined;
347
+ }
348
+ }
349
+ return current;
350
+ }
351
+ function isArraySegment(segment) {
352
+ return /^(?:\d+|\$|\$\[[A-Za-z0-9_]*\])$/.test(segment);
353
+ }
354
+ /**
355
+ * Index paths follow object properties only: a path that continues past an
356
+ * array (`items.sku`) would index values inside array items, which UNS
357
+ * expression indexes cannot do.
358
+ */
359
+ function indexPathProblem(alias, schema, path, kind) {
360
+ const segments = path.split('.');
361
+ let current = schema;
362
+ for (const [position, segment] of segments.entries()) {
363
+ if (current?.type === 'array') {
364
+ const arrayPath = segments.slice(0, position).join('.');
365
+ return `"${path}" reaches into the items of array "${arrayPath}"; index the array itself with kind: "gin", or copy the value to a top-level field.`;
366
+ }
367
+ current = current?.type === 'object' ? current.properties?.[segment] : undefined;
368
+ if (!current)
369
+ return `"${path}" is not a declared field of "${alias}".`;
370
+ }
371
+ const target = current;
372
+ if (kind === 'btree' && (target.type === 'object' || target.type === 'array')) {
373
+ return `"${path}" is an ${target.type}; index a scalar field or use kind: "gin".`;
374
+ }
375
+ if (kind === 'gin' && target.type !== 'object' && target.type !== 'array') {
376
+ return `"${path}" is a ${target.type}; a GIN index covers an object or array field.`;
377
+ }
378
+ return null;
379
+ }
380
+ /** A TTL index expires records by one integer field of Unix milliseconds. */
381
+ function ttlProblem(alias, schema, index, kind) {
382
+ const seconds = index.expireAfterSeconds;
383
+ if (!Number.isInteger(seconds) || seconds < exports.SCHEMA_LIMITS.minExpireAfterSeconds || seconds > exports.SCHEMA_LIMITS.maxExpireAfterSeconds) {
384
+ return `\`expireAfterSeconds\` is an integer from ${exports.SCHEMA_LIMITS.minExpireAfterSeconds} to ${exports.SCHEMA_LIMITS.maxExpireAfterSeconds} (one year).`;
385
+ }
386
+ if (index.path === undefined || kind !== 'btree' || index.unique)
387
+ return 'A TTL index covers a single `path` and is neither unique nor GIN.';
388
+ const target = recordSchemaAt(schema, index.path);
389
+ if (target?.type !== 'integer') {
390
+ return `TTL field "${index.path}" of "${alias}" must be declared \`z.number().int()\` holding Unix milliseconds (e.g. \`Date.now()\`).`;
391
+ }
392
+ return null;
393
+ }
394
+ function normalizeIndexes(alias, indexes, schema, issues) {
395
+ const out = [];
396
+ const seen = new Set();
397
+ let ttl = 0;
398
+ if (indexes.length > exports.SCHEMA_LIMITS.indexes) {
399
+ issues.push({ path: 'indexes', message: `At most ${exports.SCHEMA_LIMITS.indexes} indexes per collection.` });
400
+ }
401
+ indexes.forEach((index, position) => {
402
+ const at = `indexes[${position}]`;
403
+ const paths = index.paths ?? (index.path !== undefined ? [index.path] : []);
404
+ if ((index.path !== undefined) === (index.paths !== undefined)) {
405
+ issues.push({ path: at, message: 'Set exactly one of `path` or `paths`.' });
406
+ return;
407
+ }
408
+ if (paths.length === 0 || paths.length > exports.SCHEMA_LIMITS.indexPaths) {
409
+ issues.push({ path: at, message: `A compound index has 1–${exports.SCHEMA_LIMITS.indexPaths} paths.` });
410
+ return;
411
+ }
412
+ const kind = index.kind ?? 'btree';
413
+ if (kind !== 'btree' && kind !== 'gin') {
414
+ issues.push({ path: at, message: '`kind` is "btree" or "gin".' });
415
+ return;
416
+ }
417
+ if (kind === 'gin' && (paths.length !== 1 || index.unique)) {
418
+ issues.push({ path: at, message: 'A GIN index covers one object/array path and cannot be unique.' });
419
+ return;
420
+ }
421
+ if (new Set(paths).size !== paths.length) {
422
+ issues.push({ path: at, message: 'A compound index lists each path once.' });
423
+ return;
424
+ }
425
+ for (const fieldPath of paths) {
426
+ const problem = indexPathProblem(alias, schema, fieldPath, kind);
427
+ if (problem) {
428
+ issues.push({ path: at, message: problem });
429
+ return;
430
+ }
431
+ }
432
+ if (index.expireAfterSeconds !== undefined) {
433
+ const problem = ttlProblem(alias, schema, index, kind);
434
+ if (problem) {
435
+ issues.push({ path: at, message: problem });
436
+ return;
437
+ }
438
+ ttl += 1;
439
+ if (ttl > exports.SCHEMA_LIMITS.ttlIndexes) {
440
+ issues.push({ path: at, message: 'A collection has at most one TTL index (`expireAfterSeconds`).' });
441
+ return;
442
+ }
443
+ }
444
+ const normalized = index.paths ? { paths: [...paths] } : { path: paths[0] };
445
+ if (index.unique)
446
+ normalized.unique = true;
447
+ if (kind === 'gin')
448
+ normalized.kind = 'gin';
449
+ if (index.expireAfterSeconds !== undefined)
450
+ normalized.expireAfterSeconds = index.expireAfterSeconds;
451
+ const key = JSON.stringify(normalized);
452
+ if (!seen.has(key)) {
453
+ seen.add(key);
454
+ out.push(normalized);
455
+ }
456
+ });
457
+ // A TTL index is an ordinary B-tree on its path as well: a plain index on the same path would duplicate it.
458
+ const ttlPaths = new Set(out.filter((index) => index.expireAfterSeconds !== undefined).map((index) => index.path));
459
+ return out.filter((index) => index.expireAfterSeconds !== undefined || index.unique || index.kind || !ttlPaths.has(index.path));
460
+ }
461
+ const compiled = new WeakMap();
462
+ /** Ensure payload for one declaration; memoized per definition object. */
463
+ function compileCollection(definition) {
464
+ const cached = compiled.get(definition);
465
+ if (cached)
466
+ return cached;
467
+ if (!define_js_1.ALIAS_PATTERN.test(definition.alias)) {
468
+ throw new CollectionSchemaError(definition.alias, [{ path: 'alias', message: `Alias must match ${define_js_1.ALIAS_PATTERN}.` }]);
469
+ }
470
+ const recordSchema = toRecordSchema(definition.alias, definition.schema);
471
+ const issues = [];
472
+ const indexes = normalizeIndexes(definition.alias, definition.indexes, recordSchema, issues);
473
+ if (issues.length > 0)
474
+ throw new CollectionSchemaError(definition.alias, issues);
475
+ const result = {
476
+ alias: definition.alias,
477
+ recordSchema,
478
+ indexes,
479
+ ...(definition.description ? { description: definition.description } : {}),
480
+ };
481
+ compiled.set(definition, result);
482
+ return result;
483
+ }
484
+ function unknownKeyIssues(schema, value, path, out) {
485
+ if (!schema)
486
+ return;
487
+ if (schema.type === 'object' && isPlainObject(value)) {
488
+ const properties = schema.properties ?? {};
489
+ const unknown = Object.keys(value).filter((key) => !(key in properties));
490
+ if (unknown.length > 0) {
491
+ out.push({
492
+ code: 'unrecognized_keys',
493
+ keys: unknown,
494
+ path,
495
+ message: `Unknown field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `"${key}"`).join(', ')}: declare ${unknown.length > 1 ? 'them' : 'it'} in the collection schema first.`,
496
+ input: value,
497
+ });
498
+ }
499
+ for (const [key, child] of Object.entries(value)) {
500
+ if (key in properties)
501
+ unknownKeyIssues(properties[key], child, [...path, key], out);
502
+ }
503
+ }
504
+ else if (schema.type === 'array' && Array.isArray(value)) {
505
+ value.forEach((item, index) => unknownKeyIssues(schema.items, item, [...path, index], out));
506
+ }
507
+ }
508
+ function strictParse(zodSchema, recordSchema, value, path) {
509
+ const issues = [];
510
+ unknownKeyIssues(recordSchema, value, path, issues);
511
+ const result = zodSchema.safeParse(value);
512
+ if (!result.success) {
513
+ for (const issue of result.error.issues)
514
+ issues.push({ ...issue, path: [...path, ...issue.path] });
515
+ }
516
+ if (issues.length > 0)
517
+ throw new zod_1.z.ZodError(issues);
518
+ return result.data;
519
+ }
520
+ function zodAt(schema, path) {
521
+ let current = schema;
522
+ for (const segment of path.split('.')) {
523
+ while (current instanceof zod_1.z.ZodOptional)
524
+ current = current.unwrap();
525
+ if (current instanceof zod_1.z.ZodObject) {
526
+ current = current.shape[segment];
527
+ }
528
+ else if (current instanceof zod_1.z.ZodArray && isArraySegment(segment)) {
529
+ current = current.element;
530
+ }
531
+ else {
532
+ return undefined;
533
+ }
534
+ if (!current)
535
+ return undefined;
536
+ }
537
+ return current;
538
+ }
539
+ function validationError(path, message, input) {
540
+ return new zod_1.z.ZodError([{ code: 'custom', path, message, input }]);
541
+ }
542
+ /** Splits `_id` / `_meta` off a document and strictly validates the body. */
543
+ function validateDocument(definition, document) {
544
+ if (!isPlainObject(document))
545
+ throw validationError([], 'Expected a document object.', document);
546
+ const { _id, _meta, ...body } = document;
547
+ void _meta;
548
+ if (_id !== undefined && (typeof _id !== 'string' || _id.length === 0 || _id.length > 128)) {
549
+ throw validationError(['_id'], '`_id` must be a string of 1–128 characters.', _id);
550
+ }
551
+ const { recordSchema } = compileCollection(definition);
552
+ const data = strictParse(definition.schema, recordSchema, body, []);
553
+ return { ...(typeof _id === 'string' ? { id: _id } : {}), data };
554
+ }
555
+ /**
556
+ * Validates `data` of a transaction step. Fields filled by `bindings`
557
+ * (`data.<field>...`) are checked only for being declared; every literal
558
+ * field is strictly validated, and other required fields must be present.
559
+ */
560
+ function validateStepData(definition, data, boundFields) {
561
+ if (!isPlainObject(data))
562
+ throw validationError(['data'], 'Expected a document object.', data);
563
+ if ('_id' in data || '_meta' in data) {
564
+ throw validationError(['data', '_id' in data ? '_id' : '_meta'], 'A transaction step sets the record ID with `id`, not `data._id`; `_meta` is read-only.', data);
565
+ }
566
+ const { recordSchema } = compileCollection(definition);
567
+ const properties = recordSchema.properties ?? {};
568
+ const bound = new Set(boundFields.filter((field) => field in properties));
569
+ const unknownBound = boundFields.filter((field) => !(field in properties));
570
+ if (unknownBound.length > 0) {
571
+ throw validationError(['bindings'], `Bound field${unknownBound.length > 1 ? 's' : ''} ${unknownBound.join(', ')} not declared in "${definition.alias}".`, boundFields);
572
+ }
573
+ if (bound.size === 0)
574
+ return strictParse(definition.schema, recordSchema, data, ['data']);
575
+ const literal = Object.fromEntries(Object.entries(data).filter(([key]) => !bound.has(key)));
576
+ const omit = Object.fromEntries([...bound].map((field) => [field, true]));
577
+ const literalSchema = {
578
+ ...recordSchema,
579
+ properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !bound.has(key))),
580
+ required: recordSchema.required?.filter((key) => !bound.has(key)),
581
+ };
582
+ const parsed = strictParse(definition.schema.omit(omit), literalSchema, literal, ['data']);
583
+ const boundValues = Object.fromEntries(Object.entries(data).filter(([key]) => bound.has(key)));
584
+ return { ...parsed, ...boundValues };
585
+ }
586
+ const VALUE_OPERATORS = new Set(['$set', '$setOnInsert']);
587
+ const ELEMENT_OPERATORS = new Set(['$push', '$addToSet']);
588
+ const NUMERIC_OPERATORS = new Set(['$inc', '$mul']);
589
+ /** Validates update-operator documents against the declaration (paths and values). */
590
+ function validateUpdate(definition, update) {
591
+ if (!isPlainObject(update) || Object.keys(update).length === 0) {
592
+ throw validationError([], 'An update needs at least one operator such as `$set`.', update);
593
+ }
594
+ const { recordSchema } = compileCollection(definition);
595
+ const out = {};
596
+ for (const [operator, fields] of Object.entries(update)) {
597
+ if (!operator.startsWith('$')) {
598
+ throw validationError([operator], "Updates use operators (`{ $set: { status: \"DONE\" } }`); use replaceOne() to replace a whole document.", update);
599
+ }
600
+ if (!isPlainObject(fields))
601
+ throw validationError([operator], `\`${operator}\` takes an object of field paths.`, fields);
602
+ const next = {};
603
+ for (const [path, value] of Object.entries(fields)) {
604
+ const issuePath = [operator, path];
605
+ if (path === '_id' || path === '_meta' || path.startsWith('_meta.')) {
606
+ throw validationError(issuePath, '`_id` and `_meta` are read-only.', value);
607
+ }
608
+ const target = recordSchemaAt(recordSchema, path);
609
+ const zodTarget = zodAt(definition.schema, path);
610
+ if (!target || !zodTarget) {
611
+ throw validationError(issuePath, `"${path}" is not a declared field of "${definition.alias}".`, value);
612
+ }
613
+ if (VALUE_OPERATORS.has(operator)) {
614
+ if (value === undefined)
615
+ continue;
616
+ next[path] = strictParse(zodTarget, target, value, issuePath);
617
+ }
618
+ else if (ELEMENT_OPERATORS.has(operator)) {
619
+ const element = zodTarget instanceof zod_1.z.ZodOptional ? zodTarget.unwrap() : zodTarget;
620
+ if (target.type !== 'array' || !(element instanceof zod_1.z.ZodArray)) {
621
+ throw validationError(issuePath, `\`${operator}\` needs an array field; "${path}" is ${target.type}.`, value);
622
+ }
623
+ const each = isPlainObject(value) && Array.isArray(value.$each);
624
+ const items = each ? (value.$each) : [value];
625
+ const parsed = items.map((item, index) => strictParse(element.element, target.items, item, each ? [...issuePath, '$each', index] : issuePath));
626
+ next[path] = each ? { ...value, $each: parsed } : parsed[0];
627
+ }
628
+ else if (NUMERIC_OPERATORS.has(operator)) {
629
+ if (target.type !== 'number' && target.type !== 'integer') {
630
+ throw validationError(issuePath, `\`${operator}\` needs a numeric field; "${path}" is ${target.type}.`, value);
631
+ }
632
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
633
+ throw validationError(issuePath, `\`${operator}\` needs a finite number.`, value);
634
+ }
635
+ next[path] = value;
636
+ }
637
+ else if (operator === '$rename') {
638
+ if (typeof value !== 'string' || !recordSchemaAt(recordSchema, value)) {
639
+ throw validationError(issuePath, `\`$rename\` target "${String(value)}" is not a declared field.`, value);
640
+ }
641
+ next[path] = value;
642
+ }
643
+ else {
644
+ // $unset, $min, $max, $currentDate, $pop, $pull, $pullAll: the path is
645
+ // declared; UNS validates the resulting document.
646
+ next[path] = value;
647
+ }
648
+ }
649
+ if (Object.keys(next).length > 0)
650
+ out[operator] = next;
651
+ }
652
+ if (Object.keys(out).length === 0) {
653
+ throw validationError([], 'Nothing to update: undefined values are dropped; clear a field with `$unset`.', update);
654
+ }
655
+ return out;
656
+ }
657
+ //# sourceMappingURL=schema.js.map