viborm 1.2.3 → 1.3.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 (276) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-Df24l2Bd.mjs +2 -0
  17. package/dist/builder-Df24l2Bd.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-C7c1YTXD.mjs +2 -0
  35. package/dist/chain-C7c1YTXD.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
  39. package/dist/client-DM1UHfYG.mjs +49 -0
  40. package/dist/client-DM1UHfYG.mjs.map +1 -0
  41. package/dist/client-_WKrPNmm.mjs +2 -0
  42. package/dist/client-_WKrPNmm.mjs.map +1 -0
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-Da-efekX.mjs +2 -0
  50. package/dist/controls-Da-efekX.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-1pKZteeB.mjs +2 -0
  67. package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-DsyHNSDS.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
  78. package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D_kagnFv.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
  94. package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
  95. package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
  99. package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  119. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  120. package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
  121. package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
  151. package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-CDgX_vzn.mjs +2 -0
  166. package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
  167. package/dist/scalar-S8yMvdmx.mjs +4 -0
  168. package/dist/scalar-S8yMvdmx.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-9N9jQlVL.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C1PuFIpf.mjs +2 -0
  204. package/dist/to-many-C1PuFIpf.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
  213. package/dist/v-CYTUI0H5.mjs +2 -0
  214. package/dist/v-CYTUI0H5.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-DgffZq9C.mjs +2 -0
  222. package/dist/validator-DgffZq9C.mjs.map +1 -0
  223. package/dist/version-CXuJzC-q.mjs +2 -0
  224. package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
  225. package/package.json +35 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B1p6Le_h.mjs +0 -49
  232. package/dist/client-B1p6Le_h.mjs.map +0 -1
  233. package/dist/client-BLiBmykn.mjs +0 -2
  234. package/dist/client-BLiBmykn.mjs.map +0 -1
  235. package/dist/controls-DXgIn4zh.mjs +0 -2
  236. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  237. package/dist/driver-BlnKXPFF.mjs +0 -2
  238. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  239. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  240. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  241. package/dist/every-DCY4HV0X.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  243. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  244. package/dist/hydration-CAxOL4aI.mjs +0 -2
  245. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs +0 -2
  247. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  248. package/dist/key-BeoOwGr3.mjs +0 -2
  249. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  251. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  252. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  253. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  254. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  255. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  256. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  257. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  258. package/dist/scalar-U0wD5bKy.mjs +0 -2
  259. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  260. package/dist/schema-Cjem1-0f.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs +0 -2
  262. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  264. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  265. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  266. package/dist/terminal-C8cq1WWX.mjs +0 -2
  267. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  268. package/dist/v-D5Z06FKN.mjs +0 -2
  269. package/dist/v-D5Z06FKN.mjs.map +0 -1
  270. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  271. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  272. package/dist/validation-PF9-_nKd.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs +0 -2
  274. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  275. package/dist/version-Bemp-64P.mjs +0 -2
  276. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"execution-context-BKR3bgES.mjs","names":["#values"],"sources":["../src/drivers/execution-context.ts"],"sourcesContent":["import type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { QueryExecutionContext } from \"./types\";\n\ninterface TrustedExecutionContext {\n readonly callsite?: string;\n readonly correlationId?: string;\n readonly correlationIdGetter?: () => string;\n readonly extensionChain?: ResolvedExtensionChain;\n readonly model?: string;\n readonly operation?: string;\n readonly transactionPhases?: TransactionPhaseNotifications;\n}\n\n/** Private exact transaction lifecycle facts attached only to trusted contexts. */\nexport interface TransactionPhaseNotifications {\n readonly readyToCommit: () => void;\n readonly committed: () => void;\n}\n\n/**\n * A context this owner created. The private field is the trust mark: nothing\n * outside this class can set or read it, so a caller cannot forge one, and\n * checking it is cheaper than the per-query WeakMap entry it replaces.\n */\nclass TrustedSnapshot {\n readonly #values: TrustedExecutionContext;\n readonly model?: string;\n readonly operation: string | undefined;\n readonly correlationId?: string;\n constructor(values: TrustedExecutionContext) {\n this.#values = values;\n if (values.model) this.model = values.model;\n this.operation = values.operation;\n if (values.correlationIdGetter) {\n Object.defineProperty(this, \"correlationId\", {\n configurable: false,\n enumerable: true,\n get: values.correlationIdGetter,\n });\n } else if (values.correlationId) this.correlationId = values.correlationId;\n Object.freeze(this);\n }\n static values(context: object): TrustedExecutionContext | undefined {\n return #values in context\n ? (context as TrustedSnapshot).#values\n : undefined;\n }\n}\nconst trusted = (context: object) => TrustedSnapshot.values(context);\n\nexport function createExecutionContext(\n values: QueryExecutionContext,\n correlationIdFactory?: () => string,\n extensionChain?: ResolvedExtensionChain,\n callsite?: string\n): QueryExecutionContext {\n if (!correlationIdFactory) {\n return snapshotExecutionContext(\n values,\n undefined,\n undefined,\n extensionChain\n );\n }\n\n let correlationId: string | undefined;\n const correlationIdGetter = () => {\n correlationId ??= correlationIdFactory();\n return correlationId;\n };\n return createTrustedExecutionContext({\n callsite,\n correlationIdGetter,\n extensionChain,\n model: readString(values, \"model\"),\n operation: readString(values, \"operation\"),\n });\n}\n\nexport function snapshotExecutionContext(\n context: QueryExecutionContext | undefined,\n boundContext?: QueryExecutionContext,\n fallbackOperation?: string,\n extensionChainOverride?: ResolvedExtensionChain\n): QueryExecutionContext {\n const trustedContext = context ? trusted(context) : undefined;\n const contextValues =\n trustedContext ?? snapshotExternalExecutionContext(context);\n const trustedBoundContext = boundContext ? trusted(boundContext) : undefined;\n const boundValues =\n context === boundContext\n ? contextValues\n : (trustedBoundContext ?? snapshotExternalExecutionContext(boundContext));\n const model = contextValues.model ?? boundValues.model;\n const operation =\n contextValues.operation ?? boundValues.operation ?? fallbackOperation;\n const correlationIdGetter =\n contextValues.correlationIdGetter ??\n (contextValues.correlationId === undefined\n ? boundValues.correlationIdGetter\n : undefined);\n const correlationId = correlationIdGetter\n ? undefined\n : (contextValues.correlationId ?? boundValues.correlationId);\n const extensionChain =\n contextValues.extensionChain ??\n boundValues.extensionChain ??\n extensionChainOverride;\n const callsite = contextValues.callsite ?? boundValues.callsite;\n const transactionPhases =\n contextValues.transactionPhases ?? boundValues.transactionPhases;\n\n if (\n context &&\n trustedContext &&\n representsExecutionContext(\n trustedContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite\n )\n ) {\n return context;\n }\n if (\n boundContext &&\n trustedBoundContext &&\n representsExecutionContext(\n trustedBoundContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite\n )\n ) {\n return boundContext;\n }\n\n return createTrustedExecutionContext({\n callsite,\n correlationId,\n correlationIdGetter,\n extensionChain,\n model,\n operation,\n transactionPhases,\n });\n}\n\n/**\n * Re-attribute a trusted context to the model one statement addresses, keeping\n * the correlation id and extension provenance of the operation\n * it belongs to. Only the snapshot owner can do this without losing the private\n * values, which is why the query engine asks for it rather than rebuilding one.\n */\nexport function deriveStatementExecutionContext(\n context: QueryExecutionContext,\n model: string\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, model });\n}\n\n/** Read only the chain attached by the trusted context owner. */\nexport function getExecutionExtensionChain(\n context: QueryExecutionContext | undefined\n): ResolvedExtensionChain | undefined {\n if (!context) return undefined;\n return trusted(context)?.extensionChain;\n}\n\n/** The origin belongs to the exact deferred operation, never caller-spoofed metadata. */\nexport function getExecutionCallsite(\n context: QueryExecutionContext | undefined\n): string | undefined {\n return context ? trusted(context)?.callsite : undefined;\n}\n\n/** Attach private lifecycle notifications without accepting caller-spoofed state. */\nexport function bindExecutionTransactionPhases(\n context: QueryExecutionContext,\n transactionPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, transactionPhases });\n}\n\n/** Add one private lifecycle reader without replacing an existing consumer. */\nexport function appendExecutionTransactionPhases(\n context: QueryExecutionContext,\n appendedPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n const existingPhases = values.transactionPhases;\n if (existingPhases === undefined) {\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: appendedPhases,\n });\n }\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: {\n readyToCommit: () => {\n appendedPhases.readyToCommit();\n existingPhases.readyToCommit();\n },\n committed: () => {\n appendedPhases.committed();\n existingPhases.committed();\n },\n },\n });\n}\n\n/** Read lifecycle notifications only from a context created by this owner. */\nexport function getExecutionTransactionPhases(\n context: QueryExecutionContext | undefined\n): TransactionPhaseNotifications | undefined {\n if (!context) return undefined;\n return trusted(context)?.transactionPhases;\n}\n\nfunction createTrustedExecutionContext(\n values: TrustedExecutionContext\n): QueryExecutionContext {\n return new TrustedSnapshot(values) as QueryExecutionContext;\n}\n\nfunction snapshotExternalExecutionContext(\n value: QueryExecutionContext | undefined\n): TrustedExecutionContext {\n return {\n correlationId: readString(value, \"correlationId\"),\n model: readString(value, \"model\"),\n operation: readString(value, \"operation\"),\n };\n}\n\nfunction representsExecutionContext(\n values: TrustedExecutionContext,\n model: string | undefined,\n operation: string | undefined,\n correlationId: string | undefined,\n correlationIdGetter: (() => string) | undefined,\n extensionChain: ResolvedExtensionChain | undefined,\n transactionPhases: TransactionPhaseNotifications | undefined,\n callsite: string | undefined\n): boolean {\n return (\n values.callsite === callsite &&\n values.model === model &&\n values.operation === operation &&\n values.correlationId === correlationId &&\n values.correlationIdGetter === correlationIdGetter &&\n values.extensionChain === extensionChain &&\n values.transactionPhases === transactionPhases\n );\n}\n\nfunction readString(\n value: QueryExecutionContext | undefined,\n key: keyof QueryExecutionContext\n): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readProperty(value: unknown, key: PropertyKey): unknown {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || !value) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n"],"mappings":"yCAwBA,IAAM,gBAAN,KAAsB,CACpB,GACA,MACA,UACA,cACA,YAAY,EAAiC,CAC3C,MAAA,EAAe,EACX,EAAO,QAAO,KAAK,MAAQ,EAAO,OACtC,KAAK,UAAY,EAAO,UACpB,EAAO,oBACT,OAAO,eAAe,KAAM,gBAAiB,CAC3C,aAAc,GACd,WAAY,GACZ,IAAK,EAAO,oBACb,CAAC,CACO,EAAO,gBAAe,KAAK,cAAgB,EAAO,eAC7D,OAAO,OAAO,KAAK,CAErB,OAAO,OAAO,EAAsD,CAClE,MAAO,MAAW,EACb,GAAA,EACD,IAAA,KAGR,MAAM,QAAW,GAAoB,gBAAgB,OAAO,EAAQ,CAEpE,SAAgB,uBACd,EACA,EACA,EACA,EACuB,CACvB,GAAI,CAAC,EACH,OAAO,yBACL,EACA,IAAA,GACA,IAAA,GACA,EACD,CAGH,IAAI,EACE,yBACJ,IAAkB,GAAsB,CACjC,GAET,OAAO,8BAA8B,CACnC,WACA,oBACA,iBACA,MAAO,WAAW,EAAQ,QAAQ,CAClC,UAAW,WAAW,EAAQ,YAAY,CAC3C,CAAC,CAGJ,SAAgB,yBACd,EACA,EACA,EACA,EACuB,CACvB,IAAM,EAAiB,EAAU,QAAQ,EAAQ,CAAG,IAAA,GAC9C,EACJ,GAAkB,iCAAiC,EAAQ,CACvD,EAAsB,EAAe,QAAQ,EAAa,CAAG,IAAA,GAC7D,EACJ,IAAY,EACR,EACC,GAAuB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AgB,8BACd,EAC2C,CACtC,KACL,OAAO,QAAQ,EAAQ,EAAE,kBAG3B,SAAS,8BACP,EACuB,CACvB,OAAO,IAAI,gBAAgB,EAAO,CAGpC,SAAS,iCACP,EACyB,CACzB,MAAO,CACL,cAAe,WAAW,EAAO,gBAAgB,CACjD,MAAO,WAAW,EAAO,QAAQ,CACjC,UAAW,WAAW,EAAO,YAAY,CAC1C,CAGH,SAAS,2BACP,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACS,CACT,OACE,EAAO,WAAa,GACpB,EAAO,QAAU,GACjB,EAAO,YAAc,GACrB,EAAO,gBAAkB,GACzB,EAAO,sBAAwB,GAC/B,EAAO,iBAAmB,GAC1B,EAAO,oBAAsB,EAIjC,SAAS,WACP,EACA,EACoB,CACpB,IAAM,EAAS,aAAa,EAAO,EAAI,CACvC,OAAO,OAAO,GAAW,SAAW,EAAS,IAAA,GAG/C,SAAS,aAAa,EAAgB,EAA2B,CAC1D,YAAO,GAAU,UAAY,OAAO,GAAU,YAAe,CAAC,GAGnE,GAAI,CACF,OAAO,QAAQ,IAAI,EAAO,EAAI,MACxB,CACN"}
1
+ {"version":3,"file":"execution-context-rJXTRVrJ.mjs","names":["#values"],"sources":["../src/drivers/execution-context.ts"],"sourcesContent":["import type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { QueryExecutionContext } from \"./types\";\n\ninterface TrustedExecutionContext {\n readonly callsite?: string;\n readonly correlationId?: string;\n readonly correlationIdGetter?: () => string;\n readonly extensionChain?: ResolvedExtensionChain;\n readonly model?: string;\n readonly operation?: string;\n readonly transactionPhases?: TransactionPhaseNotifications;\n}\n\n/** Private exact transaction lifecycle facts attached only to trusted contexts. */\nexport interface TransactionPhaseNotifications {\n readonly readyToCommit: () => void;\n readonly committed: () => void;\n}\n\n/**\n * A context this owner created. The private field is the trust mark: nothing\n * outside this class can set or read it, so a caller cannot forge one, and\n * checking it is cheaper than the per-query WeakMap entry it replaces.\n */\nclass TrustedSnapshot {\n readonly #values: TrustedExecutionContext;\n readonly model?: string;\n readonly operation: string | undefined;\n readonly correlationId?: string;\n constructor(values: TrustedExecutionContext) {\n this.#values = values;\n if (values.model) this.model = values.model;\n this.operation = values.operation;\n if (values.correlationIdGetter) {\n Object.defineProperty(this, \"correlationId\", {\n configurable: false,\n enumerable: true,\n get: values.correlationIdGetter,\n });\n } else if (values.correlationId) this.correlationId = values.correlationId;\n Object.freeze(this);\n }\n static values(context: object): TrustedExecutionContext | undefined {\n return #values in context\n ? (context as TrustedSnapshot).#values\n : undefined;\n }\n}\nconst trusted = (context: object) => TrustedSnapshot.values(context);\n\nexport function createExecutionContext(\n values: QueryExecutionContext,\n correlationIdFactory?: () => string,\n extensionChain?: ResolvedExtensionChain,\n callsite?: string\n): QueryExecutionContext {\n if (!correlationIdFactory) {\n return snapshotExecutionContext(\n values,\n undefined,\n undefined,\n extensionChain\n );\n }\n\n let correlationId: string | undefined;\n const correlationIdGetter = () => {\n correlationId ??= correlationIdFactory();\n return correlationId;\n };\n return createTrustedExecutionContext({\n callsite,\n correlationIdGetter,\n extensionChain,\n model: readString(values, \"model\"),\n operation: readString(values, \"operation\"),\n });\n}\n\nexport function snapshotExecutionContext(\n context: QueryExecutionContext | undefined,\n boundContext?: QueryExecutionContext,\n fallbackOperation?: string,\n extensionChainOverride?: ResolvedExtensionChain\n): QueryExecutionContext {\n const trustedContext = context ? trusted(context) : undefined;\n const contextValues =\n trustedContext ?? snapshotExternalExecutionContext(context);\n const trustedBoundContext = boundContext ? trusted(boundContext) : undefined;\n const boundValues =\n context === boundContext\n ? contextValues\n : (trustedBoundContext ?? snapshotExternalExecutionContext(boundContext));\n const model = contextValues.model ?? boundValues.model;\n const operation =\n contextValues.operation ?? boundValues.operation ?? fallbackOperation;\n const correlationIdGetter =\n contextValues.correlationIdGetter ??\n (contextValues.correlationId === undefined\n ? boundValues.correlationIdGetter\n : undefined);\n const correlationId = correlationIdGetter\n ? undefined\n : (contextValues.correlationId ?? boundValues.correlationId);\n const extensionChain =\n contextValues.extensionChain ??\n boundValues.extensionChain ??\n extensionChainOverride;\n const callsite = contextValues.callsite ?? boundValues.callsite;\n const transactionPhases =\n contextValues.transactionPhases ?? boundValues.transactionPhases;\n\n if (\n context &&\n trustedContext &&\n representsExecutionContext(\n trustedContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite\n )\n ) {\n return context;\n }\n if (\n boundContext &&\n trustedBoundContext &&\n representsExecutionContext(\n trustedBoundContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite\n )\n ) {\n return boundContext;\n }\n\n return createTrustedExecutionContext({\n callsite,\n correlationId,\n correlationIdGetter,\n extensionChain,\n model,\n operation,\n transactionPhases,\n });\n}\n\n/**\n * Re-attribute a trusted context to the model one statement addresses, keeping\n * the correlation id and extension provenance of the operation\n * it belongs to. Only the snapshot owner can do this without losing the private\n * values, which is why the query engine asks for it rather than rebuilding one.\n */\nexport function deriveStatementExecutionContext(\n context: QueryExecutionContext,\n model: string\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, model });\n}\n\n/** Read only the chain attached by the trusted context owner. */\nexport function getExecutionExtensionChain(\n context: QueryExecutionContext | undefined\n): ResolvedExtensionChain | undefined {\n if (!context) return undefined;\n return trusted(context)?.extensionChain;\n}\n\n/** The origin belongs to the exact deferred operation, never caller-spoofed metadata. */\nexport function getExecutionCallsite(\n context: QueryExecutionContext | undefined\n): string | undefined {\n return context ? trusted(context)?.callsite : undefined;\n}\n\n/** Attach private lifecycle notifications without accepting caller-spoofed state. */\nexport function bindExecutionTransactionPhases(\n context: QueryExecutionContext,\n transactionPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, transactionPhases });\n}\n\n/** Add one private lifecycle reader without replacing an existing consumer. */\nexport function appendExecutionTransactionPhases(\n context: QueryExecutionContext,\n appendedPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n const existingPhases = values.transactionPhases;\n if (existingPhases === undefined) {\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: appendedPhases,\n });\n }\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: {\n readyToCommit: () => {\n appendedPhases.readyToCommit();\n existingPhases.readyToCommit();\n },\n committed: () => {\n appendedPhases.committed();\n existingPhases.committed();\n },\n },\n });\n}\n\n/** Read lifecycle notifications only from a context created by this owner. */\nexport function getExecutionTransactionPhases(\n context: QueryExecutionContext | undefined\n): TransactionPhaseNotifications | undefined {\n if (!context) return undefined;\n return trusted(context)?.transactionPhases;\n}\n\nfunction createTrustedExecutionContext(\n values: TrustedExecutionContext\n): QueryExecutionContext {\n return new TrustedSnapshot(values) as QueryExecutionContext;\n}\n\nfunction snapshotExternalExecutionContext(\n value: QueryExecutionContext | undefined\n): TrustedExecutionContext {\n return {\n correlationId: readString(value, \"correlationId\"),\n model: readString(value, \"model\"),\n operation: readString(value, \"operation\"),\n };\n}\n\nfunction representsExecutionContext(\n values: TrustedExecutionContext,\n model: string | undefined,\n operation: string | undefined,\n correlationId: string | undefined,\n correlationIdGetter: (() => string) | undefined,\n extensionChain: ResolvedExtensionChain | undefined,\n transactionPhases: TransactionPhaseNotifications | undefined,\n callsite: string | undefined\n): boolean {\n return (\n values.callsite === callsite &&\n values.model === model &&\n values.operation === operation &&\n values.correlationId === correlationId &&\n values.correlationIdGetter === correlationIdGetter &&\n values.extensionChain === extensionChain &&\n values.transactionPhases === transactionPhases\n );\n}\n\nfunction readString(\n value: QueryExecutionContext | undefined,\n key: keyof QueryExecutionContext\n): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readProperty(value: unknown, key: PropertyKey): unknown {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || !value) {\n return undefined;\n }\n try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A,EACA,EACA,EACA,EACS,CACT,OACE,EAAO,WAAa,GACpB,EAAO,QAAU,GACjB,EAAO,YAAc,GACrB,EAAO,gBAAkB,GACzB,EAAO,sBAAwB,GAC/B,EAAO,iBAAmB,GAC1B,EAAO,oBAAsB,EAIjC,SAAS,WACP,EACA,EACoB,CACpB,IAAM,EAAS,aAAa,EAAO,EAAI,CACvC,OAAO,OAAO,GAAW,SAAW,EAAS,IAAA,GAG/C,SAAS,aAAa,EAAgB,EAA2B,CAC1D,YAAO,GAAU,UAAY,OAAO,GAAU,YAAe,CAAC,GAGnE,GAAI,CACF,OAAO,QAAQ,IAAI,EAAO,EAAI,MACxB,CACN"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{a as r,s as i}from"./identity-CLFhCTZx.mjs";import{closeSync as a,constants as o,existsSync as s,fsyncSync as c,linkSync as l,lstatSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,unlinkSync as h,writeSync as g}from"node:fs";import{dirname as _,join as v,resolve as y}from"node:path";const b=`estate.json`;var FsEstateStorage=class{baseDir;constructor(e){this.baseDir=y(e)}async readEstate(){return readOptional(v(this.baseDir,b))}async listStates(){return listHexFiles(v(this.baseDir,`states`),`.json`)}async listSnapshots(){return listHexFiles(v(this.baseDir,`snapshots`),`.json`)}async listSql(){return listHexFiles(v(this.baseDir,`sql`),`.sql`)}async readState(e){return readOptional(v(this.baseDir,`states`,`${e}.json`))}async readSnapshot(e){return readOptional(v(this.baseDir,`snapshots`,`${e}.json`))}async readSql(e){return readOptional(v(this.baseDir,`sql`,`${e}.sql`))}async publishEstate(e){return publishNoReplace(this.baseDir,v(this.baseDir,b),e)}async publishSnapshot(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`snapshots`,`${e}.json`),t)}async publishSql(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`sql`,`${e}.sql`),t)}async publishState(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`states`,`${e}.json`),t)}};function createFsStorageWriter(e){return new FsEstateStorage(e)}function readOptional(e){return s(e)?(refuseSymlink(e),new Uint8Array(p(e))):null}function listHexFiles(e,t){if(!s(e))return[];refuseSymlink(e);let n=m(e),i=[];for(let e of n){if(e.startsWith(`.`)||e.endsWith(`.tmp`)||!e.endsWith(t))continue;let n=e.slice(0,-t.length);r(n)&&i.push(n)}return i.sort()}function publishNoReplace(e,r,u){assertInsideBase(e,r);let m=_(r);if(d(m,{recursive:!0}),refuseSymlink(m),s(r))return refuseSymlink(r),compareExisting(r,u);let y=v(m,`.${randomSuffix()}.tmp`),b=f(y,o.O_CREAT|o.O_EXCL|o.O_WRONLY,420);try{g(b,u),c(b)}finally{a(b)}if(i(p(y))!==i(u))throw h(y),new n(`Temporary estate write did not round-trip`,t.MIGRATION_CORRUPTION);try{l(y,r)}catch(e){if(unlinkQuiet(y),isErrno(e,`EEXIST`))return compareExisting(r,u);throw isErrno(e,`EXDEV`)||isErrno(e,`ENOSYS`)||isErrno(e,`EPERM`)?new n(`Filesystem cannot atomically publish with a no-replace hard link`,t.MIGRATION_STORAGE_REQUIRED,{cause:e instanceof Error?e:void 0}):e}return unlinkQuiet(y),fsyncDirectory(m),{outcome:`created`}}function compareExisting(e,r){if(i(p(e))!==i(r))throw new n(`Content-addressed path ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return fsyncDirectory(_(e)),{outcome:`identical`}}function refuseSymlink(e){if(u(e).isSymbolicLink())throw new n(`Estate storage refuses to follow symlinks`,t.MIGRATION_INVALID_ESTATE)}function fsyncDirectory(e){let t=f(e,o.O_RDONLY|o.O_DIRECTORY);try{c(t)}finally{a(t)}}function unlinkQuiet(e){try{h(e)}catch{}}function isErrno(e,t){return!!(e&&typeof e==`object`&&`code`in e&&e.code===t)}function randomSuffix(){return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function assertInsideBase(e,r){let i=y(r),a=e.endsWith(`/`)?e:`${e}/`;if(i!==y(e)&&!i.startsWith(a))throw new n(`Estate path escapes the storage root`,t.MIGRATION_INVALID_ESTATE)}export{createFsStorageWriter as t};
2
- //# sourceMappingURL=fs-estate-CAhDg7nY.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{a as r,s as i}from"./identity-oQvIe7u8.mjs";import{closeSync as a,constants as o,existsSync as s,fsyncSync as c,linkSync as l,lstatSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,unlinkSync as h,writeSync as g}from"node:fs";import{dirname as _,join as v,resolve as y}from"node:path";const b=`estate.json`;var FsEstateStorage=class{baseDir;constructor(e){this.baseDir=y(e)}async readEstate(){return readOptional(v(this.baseDir,b))}async listStates(){return listHexFiles(v(this.baseDir,`states`),`.json`)}async listSnapshots(){return listHexFiles(v(this.baseDir,`snapshots`),`.json`)}async listSql(){return listHexFiles(v(this.baseDir,`sql`),`.sql`)}async readState(e){return readOptional(v(this.baseDir,`states`,`${e}.json`))}async readSnapshot(e){return readOptional(v(this.baseDir,`snapshots`,`${e}.json`))}async readSql(e){return readOptional(v(this.baseDir,`sql`,`${e}.sql`))}async publishEstate(e){return publishNoReplace(this.baseDir,v(this.baseDir,b),e)}async publishSnapshot(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`snapshots`,`${e}.json`),t)}async publishSql(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`sql`,`${e}.sql`),t)}async publishState(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`states`,`${e}.json`),t)}};function createFsStorageWriter(e){return new FsEstateStorage(e)}function readOptional(e){return s(e)?(refuseSymlink(e),new Uint8Array(p(e))):null}function listHexFiles(e,t){if(!s(e))return[];refuseSymlink(e);let n=m(e),i=[];for(let e of n){if(e.startsWith(`.`)||e.endsWith(`.tmp`)||!e.endsWith(t))continue;let n=e.slice(0,-t.length);r(n)&&i.push(n)}return i.sort()}function publishNoReplace(e,r,u){assertInsideBase(e,r);let m=_(r);if(d(m,{recursive:!0}),refuseSymlink(m),s(r))return refuseSymlink(r),compareExisting(r,u);let y=v(m,`.${randomSuffix()}.tmp`),b=f(y,o.O_CREAT|o.O_EXCL|o.O_WRONLY,420);try{g(b,u),c(b)}finally{a(b)}if(i(p(y))!==i(u))throw h(y),new n(`Temporary estate write did not round-trip`,t.MIGRATION_CORRUPTION);try{l(y,r)}catch(e){if(unlinkQuiet(y),isErrno(e,`EEXIST`))return compareExisting(r,u);throw isErrno(e,`EXDEV`)||isErrno(e,`ENOSYS`)||isErrno(e,`EPERM`)?new n(`Filesystem cannot atomically publish with a no-replace hard link`,t.MIGRATION_STORAGE_REQUIRED,{cause:e instanceof Error?e:void 0}):e}return unlinkQuiet(y),fsyncDirectory(m),{outcome:`created`}}function compareExisting(e,r){if(i(p(e))!==i(r))throw new n(`Content-addressed path ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return fsyncDirectory(_(e)),{outcome:`identical`}}function refuseSymlink(e){if(u(e).isSymbolicLink())throw new n(`Estate storage refuses to follow symlinks`,t.MIGRATION_INVALID_ESTATE)}function fsyncDirectory(e){let t=f(e,o.O_RDONLY|o.O_DIRECTORY);try{c(t)}finally{a(t)}}function unlinkQuiet(e){try{h(e)}catch{}}function isErrno(e,t){return!!(e&&typeof e==`object`&&`code`in e&&e.code===t)}function randomSuffix(){return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function assertInsideBase(e,r){let i=y(r),a=e.endsWith(`/`)?e:`${e}/`;if(i!==y(e)&&!i.startsWith(a))throw new n(`Estate path escapes the storage root`,t.MIGRATION_INVALID_ESTATE)}export{createFsStorageWriter as t};
2
+ //# sourceMappingURL=fs-estate-i8Zlr1OQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fs-estate-CAhDg7nY.mjs","names":[],"sources":["../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"2bA2BA,MAAM,EAAc,cAEpB,IAAM,gBAAN,KAAwD,CACtD,QAEA,YAAY,EAAiB,CAC3B,KAAK,QAAU,EAAQ,EAAQ,CAGjC,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,EAAY,CAAC,CAGtD,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,SAAS,CAAE,QAAQ,CAG5D,MAAM,eAA4C,CAChD,OAAO,aAAa,EAAK,KAAK,QAAS,YAAY,CAAE,QAAQ,CAG/D,MAAM,SAAsC,CAC1C,OAAO,aAAa,EAAK,KAAK,QAAS,MAAM,CAAE,OAAO,CAGxD,MAAM,UAAU,EAAwC,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,SAAU,GAAG,EAAG,OAAO,CAAC,CAGjE,MAAM,aAAa,EAA0C,CAC3D,OAAO,aAAa,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAAC,CAGtE,MAAM,QAAQ,EAA0C,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,MAAO,GAAG,EAAK,MAAM,CAAC,CAG/D,MAAM,cAAc,EAA2C,CAC7D,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,EAAY,CAC/B,EACD,CAGH,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAC/C,EACD,CAGH,MAAM,WAAW,EAAc,EAA2C,CACxE,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,MAAO,GAAG,EAAK,MAAM,CACxC,EACD,CAGH,MAAM,aAAa,EAAY,EAA2C,CACxE,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,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I,EACR,uCACA,EAAgB,yBACjB"}
1
+ {"version":3,"file":"fs-estate-i8Zlr1OQ.mjs","names":[],"sources":["../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"2bA2BA,MAAM,EAAc,cAEpB,IAAM,gBAAN,KAAwD,CACtD,QAEA,YAAY,EAAiB,CAC3B,KAAK,QAAU,EAAQ,EAAQ,CAGjC,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,EAAY,CAAC,CAGtD,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,SAAS,CAAE,QAAQ,CAG5D,MAAM,eAA4C,CAChD,OAAO,aAAa,EAAK,KAAK,QAAS,YAAY,CAAE,QAAQ,CAG/D,MAAM,SAAsC,CAC1C,OAAO,aAAa,EAAK,KAAK,QAAS,MAAM,CAAE,OAAO,CAGxD,MAAM,UAAU,EAAwC,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,SAAU,GAAG,EAAG,OAAO,CAAC,CAGjE,MAAM,aAAa,EAA0C,CAC3D,OAAO,aAAa,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAAC,CAGtE,MAAM,QAAQ,EAA0C,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,MAAO,GAAG,EAAK,MAAM,CAAC,CAG/D,MAAM,cAAc,EAA2C,CAC7D,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,EAAY,CAC/B,EACD,CAGH,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAC/C,EACD,CAGH,MAAM,WAAW,EAAc,EAA2C,CACxE,OAAO,iBACL,KAAK,QACL,EA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AQ,SAAS,IAAI,CAAG,EAAU,GAAG,EAAQ,GAC1D,GAAI,IAAa,EAAQ,EAAQ,EAAI,CAAC,EAAS,WAAW,EAAK,CAC7D,MAAM,IAAI,EACR,uCACA,EAAgB,yBACjB"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{Dt as t,H as n,J as r,Mt as i,U as a,W as o,i as s,m as c,n as l,q as u,r as d,t as f}from"./geo-point-codec-lhxH42SK.mjs";const p=1e-10,m=6371008.8;function geoBoundsForDistance(e,t){if(t<=0)return{south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude};let n=t/m;if(n>=Math.PI)return{south:-90,west:-180,north:90,east:180};let r=e.latitude*Math.PI/180,i=n*180/Math.PI,a=Math.max(-90,e.latitude-i-p),o=Math.min(90,e.latitude+i+p);if(a===-90||o===90)return{south:a,west:-180,north:o,east:180};let s=Math.asin(Math.min(1,Math.sin(n)/Math.cos(r)))*180/Math.PI+p;return{south:a,west:normalizeLongitude(e.longitude-s),north:o,east:normalizeLongitude(e.longitude+s)}}function normalizeLongitude(e){return((e+180)%360+360)%360-180}const h=c({[t[0]]:f,[t[1]]:l,[t[2]]:f,[t[3]]:l},{partial:!1});function validateGeoBounds(e){let t=r(h,e);return t.issues?t:t.value.south>t.value.north?a(`GeoBounds south must be less than or equal to north`,[`south`]):t}function validateRing(e){let t=u(e,o);return t.issues?t:t.value.length<i?a(`A GeoPolygon ring needs at least ${i} vertices`):u(t.value,d)}const g=c({outer:n(`array`,validateRing),holes:s(n(`array`,e=>u(e,validateRing)))},{partial:!1}),_=Math.PI/180,v=1e-9*_,y=2*Math.sin(.005*_);function toVector(e,t){let n=Math.cos(t*_);return[n*Math.cos(e*_),n*Math.sin(e*_),Math.sin(t*_)]}function dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function cross(e,t){let n=e[0]-t[0],r=e[1]-t[1],i=e[2]-t[2],a=e[0]+t[0],o=e[1]+t[1],s=e[2]+t[2];return[(r*s-i*o)/2,(i*a-n*s)/2,(n*o-r*a)/2]}function unit(e){let t=Math.hypot(...e);return[e[0]/t,e[1]/t,e[2]/t]}function chord(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2])}function antipode(e){return[-e[0],-e[1],-e[2]]}function shortWay(e){return e>180?-360:e<-180?360:0}function distinctVertices(e,t){let n=[];for(let[r,i]of e.entries()){let e=toVector(i.longitude,i.latitude);if(Math.hypot(e[0],e[1])<=v)return a(`A GeoPolygon ring cannot contain a pole`,[...t,r]);let o=n.at(-1);(!o||chord(o.vector,e)>v)&&n.push({vertex:i,index:r,vector:e})}let[r]=n,i=n.at(-1);return r&&i&&chord(i.vector,r.vector)>v&&n.push(r),o(n)}function ringArcs(e,t){let n=distinctVertices(e,t);if(n.issues)return n;let r=0;for(let[e,{vertex:t}]of n.value.entries()){let i=n.value[e-1];i&&(r+=shortWay(t.longitude-i.vertex.longitude))}let i=[],s=0,c,l;for(let{vertex:e,index:o,vector:u}of n.value){let n;if(c){let t=e.longitude-c.written;Math.abs(t)===180&&(n=[0,0,Math.sign(e.latitude+c.latitude)],Math.abs(t-r)===180&&(s-=r)),s+=shortWay(t)}let d={longitude:e.longitude+s,latitude:e.latitude,written:e.longitude,vector:u};if(c){if(chord(antipode(c.vector),u)<y)return a(`A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal`,[...t,o]);if(n&&l&&n[2]!==l[2])return a(`A GeoPolygon cannot contain a pole`,[...t]);l??=n,i.push({from:c,to:d,start:c.vector,end:u,normal:unit(cross(c.vector,u)),pole:n})}c=d}if(s!==0)return a(`A GeoPolygon cannot contain a pole`,[...t]);let[u,...d]=i;if(!u||d.length<3&&d.every(({start:e})=>Math.abs(side(u,e))<=v))return a(`A GeoPolygon ring must have non-zero area`,[...t]);let f=u;for(let e of[...d,u]){if(onArc(e.end,f)||onArc(f.start,e))return a(`A GeoPolygon ring cannot self-intersect`,[...t]);f=e}return o([u,...d])}function side(e,t){return dot(e.normal,t)}function onArc(e,t){return Math.abs(side(t,e))<=v&&dot(cross(t.start,e),t.normal)>=-v&&dot(cross(e,t.end),t.normal)>=-v}function opposite(e,t){return e>v&&t<-v||e<-v&&t>v}function crosses(e,t){if(!(opposite(side(e,t.start),side(e,t.end))&&opposite(side(t,e.start),side(t,e.end))))return!1;let n=cross(e.normal,t.normal);return dot(n,e.start)+dot(n,e.end)>0==dot(n,t.start)+dot(n,t.end)>0}function meet(e,t){return crosses(e,t)||onArc(e.start,t)||onArc(e.end,t)||onArc(t.start,e)||onArc(t.end,e)}function createLinks(e){return Array.from({length:e},()=>({previous:void 0,next:void 0}))}function below(e,t){let n=dot(t.north,e.west);return Math.abs(n)>v?n<0:dot(t.north,e.east)<0}function southOf(e,t,n){let r=e;for(let e=n;e>=0;--e){let n=r.links[e]?.next;for(;n?.stretch&&dot(n.stretch.north,t)>v;)r=n,n=r.links[e]?.next}return r}function enter(e,t,n){let r={stretch:t,links:createLinks(n)},i=e;for(let e=23;e>=0;--e){let n=i.links[e]?.next;for(;n?.stretch&&!below(t,n.stretch);)i=n,n=i.links[e]?.next;let a=r.links[e],o=i.links[e];if(a&&o){a.previous=i,a.next=o.next;let t=o.next?.links[e];t&&(t.previous=r),o.next=r}}return r}function leave(e){for(let[t,{previous:n,next:r}]of e.links.entries()){let e=n?.links[t];e&&(e.next=r);let i=r?.links[t];i&&(i.previous=n)}}const b=toVector(180,0);function atAntimeridian(e){let t=unit(cross(e.normal,[-b[1],b[0],0]));return dot(t,b)<0?antipode(t):t}function arcEvents(e){let{from:t,to:n,normal:r,pole:i}=e.arc,a=t.written===180?-180:t.written,o=n.written===180?-180:n.written;if(a===o){let[r,i]=t.latitude<n.latitude?[t,n]:[n,t];return[{longitude:a,rank:2,upright:{placed:e,south:r.vector,north:i.vector}}]}let s=t.longitude<n.longitude,[c,l]=s?[t,n]:[n,t],u=s?r:[-r[0],-r[1],-r[2]],[d,f]=s?[a,o]:[o,a];if(i)return polarEvents(e,i,u,s,d,f);let span=(t,n,r)=>{let i={stretch:{placed:e,west:r,east:l.vector,north:u,eastward:s},entry:void 0};return[{longitude:t,rank:1,slot:i},{longitude:n,rank:3,slot:i}]};return d<f?span(d,f,c.vector):[...span(d,180,c.vector),...span(-180,f,atAntimeridian(e.arc))]}function polarEvents(e,t,n,r,i,a){let o=[e.arc.from,e.arc.to].map(({written:n,vector:r})=>({longitude:n===180?-180:n,rank:2,upright:{placed:e,south:t[2]>0?r:t,north:t[2]>0?t:r}})),across=(i,a)=>{let o={stretch:{placed:e,west:t,east:t,north:n,eastward:r},entry:void 0};return[{longitude:i,rank:1,slot:o},{longitude:a,rank:0,slot:o}]};return i<a?[...o,...across(i,a)]:[...o,...across(i,180),...a>-180?across(-180,a):[]]}function latitude(e){return Math.atan2(e[2],Math.hypot(e[0],e[1]))}function sweep(e,t){let n=e.flatMap(arcEvents);n.sort((e,t)=>e.longitude-t.longitude||e.rank-t.rank);let r={stretch:void 0,links:createLinks(24)},meeting=(e,n)=>{if(e&&n&&!(t(e,n)||!meet(e.arc,n.arc)))return[e,n]},i=[],a=new Map,placeArrivals=()=>{let e=Array.from(a,([e,{entry:t,west:n}])=>{let r=t.links[0]?.next;for(;r?.stretch?.placed.ring===e;)r=r.links[0]?.next;return{ring:e,height:latitude(n),north:r?.stretch}});e.sort((e,t)=>t.height-e.height);for(let{ring:t,north:n}of e)i.push({ring:t,north:n});a.clear()},o=new Set;for(let[e,t]of n.entries())if(t.rank===1){let i=1+Math.floor(-Math.log2(1-Math.random())),s=enter(r,t.slot.stretch,Math.min(24,i));t.slot.entry=s;let[c]=s.links,l=meeting(c?.previous?.stretch?.placed,s.stretch?.placed)??meeting(s.stretch?.placed,c?.next?.stretch?.placed);if(l)return{meeting:l};let{placed:u,west:d}=t.slot.stretch,f=a.get(u.ring);(!o.has(u.ring)||f&&latitude(d)>latitude(f.west))&&(o.add(u.ring),a.set(u.ring,{entry:s,west:d}));let p=n[e+1];(p?.rank!==1||p.longitude!==t.longitude)&&placeArrivals()}else if(t.rank===2){let{upright:e}=t,n=southOf(r,e.south,23);for(n=n.stretch?n:n.links[0]?.next;n?.stretch;){let t=meeting(e.placed,n.stretch.placed);if(t)return{meeting:t};if(dot(n.stretch.north,e.north)<-v)break;n=n.links[0]?.next}}else if(t.slot.entry){let[e]=t.slot.entry.links;leave(t.slot.entry);let n=meeting(e?.previous?.stretch?.placed,e?.next?.stretch?.placed);if(n)return{meeting:n}}return{placements:i}}function signedArea(e){let t=0,n=0,r,i=0;for(let a of e){let e=cross(a.start,a.end)[2],o=1+dot(a.start,a.end),s=a.start[2]+a.end[2];s>=0?(t+=2*Math.atan2(e,o+s),r!==void 0&&(n+=a.from.longitude-r),r=void 0):(t+=2*Math.atan2(-e,o-s),r??=a.from.longitude),i=a.to.longitude}return r!==void 0&&(n+=i-r),t+2*n*_}function wound(e,t,n){return t===n?e:e.reverse()}function ringPath(e){return e===0?[`outer`]:[`holes`,e-1]}function ringNode(e,t,n){return{index:n,hole:n===0?1/0:n-1,points:e,arcs:t,counterClockwise:signedArea(t)>0,around:void 0,inside:!1,firstAround:1/0,firstWithin:1/0}}function validateGeoPolygon(e){let t=r(g,e);if(t.issues)return t;let n=ringArcs(t.value.outer,[`outer`]);if(n.issues)return n;let i=ringNode(t.value.outer,n.value,0),s=[];for(let[e,n]of(t.value.holes??[]).entries()){let t=ringArcs(n,[`holes`,e]);if(t.issues)return t;s.push(ringNode(n,t.value,e+1))}let c=sweep([i,...s].flatMap(e=>e.arcs.map((t,n)=>({arc:t,ring:e,index:n}))),(e,t)=>e.ring===t.ring&&[0,1,e.ring.arcs.length-1].includes(Math.abs(e.index-t.index)));if(c.meeting){let[e,t]=c.meeting,n=ringPath(Math.max(e.ring.index,t.ring.index));return e.ring===t.ring?a(`A GeoPolygon ring cannot self-intersect`,n):Math.min(e.ring.index,t.ring.index)===0?a(`A GeoPolygon hole must be strictly inside its outer ring`,n):a(`GeoPolygon holes cannot touch or overlap`,n)}for(let{ring:e,north:t}of c.placements){let n=t?.placed.ring,r=n===void 0||n.counterClockwise!==t?.eastward?n:n.around;e.around=r,e.inside=r!==void 0&&(r.index===0||r.inside),e.firstAround=r?Math.min(r.hole,r.firstAround):1/0}for(let{ring:e}of c.placements.reverse()){let{around:t}=e;t&&(t.firstWithin=Math.min(t.firstWithin,e.hole,e.firstWithin))}for(let{hole:e,inside:t,firstAround:n,firstWithin:r}of s){if(!t)return a(`A GeoPolygon hole must be strictly inside its outer ring`,[`holes`,e]);if(Math.min(n,r)<e)return a(`GeoPolygon holes cannot touch or overlap`,[`holes`,e])}let l=wound(i.points,i.counterClockwise,!0),u=s.map(({points:e,counterClockwise:t})=>wound(e,t,!1));return o(u.length>0?{outer:l,holes:u}:{outer:l})}const x=c({bounds:n(`object`,validateGeoBounds),polygon:n(`object`,validateGeoPolygon)});function validateGeoArea(e){let t=r(x,e);if(t.issues)return t;let{bounds:n,polygon:i}=t.value;return n&&!i?o({bounds:n}):i&&!n?o({polygon:i}):a(`Expected GeoArea with exactly one of bounds or polygon`)}function geoAreaSchema(){return n(`geo_area`,validateGeoArea)}export{geoAreaSchema as n,geoBoundsForDistance as r,m as t};
2
- //# sourceMappingURL=geo-area-codec-1SY9im7O.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{$ as t,J as n,Q as r,U as i,Z as a,i as o,n as s,nt as c,r as l,rt as u,t as d,z as f}from"./geo-point-codec-DyEHMdJg.mjs";const p=1e-10,m=6371008.8;function geoBoundsForDistance(e,t){if(t<=0)return{south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude};let n=t/m;if(n>=Math.PI)return{south:-90,west:-180,north:90,east:180};let r=e.latitude*Math.PI/180,i=n*180/Math.PI,a=Math.max(-90,e.latitude-i-p),o=Math.min(90,e.latitude+i+p);if(a===-90||o===90)return{south:a,west:-180,north:o,east:180};let s=Math.asin(Math.min(1,Math.sin(n)/Math.cos(r)))*180/Math.PI+p;return{south:a,west:normalizeLongitude(e.longitude-s),north:o,east:normalizeLongitude(e.longitude+s)}}function normalizeLongitude(e){return((e+180)%360+360)%360-180}const h=f({[i[0]]:d,[i[1]]:s,[i[2]]:d,[i[3]]:s},{partial:!1});function validateGeoBounds(e){let t=u(h,e);return t.issues?t:t.value.south>t.value.north?r(`GeoBounds south must be less than or equal to north`,[`south`]):t}function validateRing(e){let i=c(e,t);return i.issues?i:i.value.length<n?r(`A GeoPolygon ring needs at least ${n} vertices`):c(i.value,l)}const g=f({outer:a(`array`,validateRing),holes:o(a(`array`,e=>c(e,validateRing)))},{partial:!1}),_=Math.PI/180,v=1e-9*_,y=2*Math.sin(.005*_);function toVector(e,t){let n=Math.cos(t*_);return[n*Math.cos(e*_),n*Math.sin(e*_),Math.sin(t*_)]}function dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function cross(e,t){let n=e[0]-t[0],r=e[1]-t[1],i=e[2]-t[2],a=e[0]+t[0],o=e[1]+t[1],s=e[2]+t[2];return[(r*s-i*o)/2,(i*a-n*s)/2,(n*o-r*a)/2]}function unit(e){let t=Math.hypot(...e);return[e[0]/t,e[1]/t,e[2]/t]}function chord(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2])}function antipode(e){return[-e[0],-e[1],-e[2]]}function shortWay(e){return e>180?-360:e<-180?360:0}function distinctVertices(e,n){let i=[];for(let[t,a]of e.entries()){let e=toVector(a.longitude,a.latitude);if(Math.hypot(e[0],e[1])<=v)return r(`A GeoPolygon ring cannot contain a pole`,[...n,t]);let o=i.at(-1);(!o||chord(o.vector,e)>v)&&i.push({vertex:a,index:t,vector:e})}let[a]=i,o=i.at(-1);return a&&o&&chord(o.vector,a.vector)>v&&i.push(a),t(i)}function ringArcs(e,n){let i=distinctVertices(e,n);if(i.issues)return i;let a=0;for(let[e,{vertex:t}]of i.value.entries()){let n=i.value[e-1];n&&(a+=shortWay(t.longitude-n.vertex.longitude))}let o=[],s=0,c,l;for(let{vertex:e,index:t,vector:u}of i.value){let i;if(c){let t=e.longitude-c.written;Math.abs(t)===180&&(i=[0,0,Math.sign(e.latitude+c.latitude)],Math.abs(t-a)===180&&(s-=a)),s+=shortWay(t)}let d={longitude:e.longitude+s,latitude:e.latitude,written:e.longitude,vector:u};if(c){if(chord(antipode(c.vector),u)<y)return r(`A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal`,[...n,t]);if(i&&l&&i[2]!==l[2])return r(`A GeoPolygon cannot contain a pole`,[...n]);l??=i,o.push({from:c,to:d,start:c.vector,end:u,normal:unit(cross(c.vector,u)),pole:i})}c=d}if(s!==0)return r(`A GeoPolygon cannot contain a pole`,[...n]);let[u,...d]=o;if(!u||d.length<3&&d.every(({start:e})=>Math.abs(side(u,e))<=v))return r(`A GeoPolygon ring must have non-zero area`,[...n]);let f=u;for(let e of[...d,u]){if(onArc(e.end,f)||onArc(f.start,e))return r(`A GeoPolygon ring cannot self-intersect`,[...n]);f=e}return t([u,...d])}function side(e,t){return dot(e.normal,t)}function onArc(e,t){return Math.abs(side(t,e))<=v&&dot(cross(t.start,e),t.normal)>=-v&&dot(cross(e,t.end),t.normal)>=-v}function opposite(e,t){return e>v&&t<-v||e<-v&&t>v}function crosses(e,t){if(!(opposite(side(e,t.start),side(e,t.end))&&opposite(side(t,e.start),side(t,e.end))))return!1;let n=cross(e.normal,t.normal);return dot(n,e.start)+dot(n,e.end)>0==dot(n,t.start)+dot(n,t.end)>0}function meet(e,t){return crosses(e,t)||onArc(e.start,t)||onArc(e.end,t)||onArc(t.start,e)||onArc(t.end,e)}function createLinks(e){return Array.from({length:e},()=>({previous:void 0,next:void 0}))}function below(e,t){let n=dot(t.north,e.west);return Math.abs(n)>v?n<0:dot(t.north,e.east)<0}function southOf(e,t,n){let r=e;for(let e=n;e>=0;--e){let n=r.links[e]?.next;for(;n?.stretch&&dot(n.stretch.north,t)>v;)r=n,n=r.links[e]?.next}return r}function enter(e,t,n){let r={stretch:t,links:createLinks(n)},i=e;for(let e=23;e>=0;--e){let n=i.links[e]?.next;for(;n?.stretch&&!below(t,n.stretch);)i=n,n=i.links[e]?.next;let a=r.links[e],o=i.links[e];if(a&&o){a.previous=i,a.next=o.next;let t=o.next?.links[e];t&&(t.previous=r),o.next=r}}return r}function leave(e){for(let[t,{previous:n,next:r}]of e.links.entries()){let e=n?.links[t];e&&(e.next=r);let i=r?.links[t];i&&(i.previous=n)}}const b=toVector(180,0);function atAntimeridian(e){let t=unit(cross(e.normal,[-b[1],b[0],0]));return dot(t,b)<0?antipode(t):t}function arcEvents(e){let{from:t,to:n,normal:r,pole:i}=e.arc,a=t.written===180?-180:t.written,o=n.written===180?-180:n.written;if(a===o){let[r,i]=t.latitude<n.latitude?[t,n]:[n,t];return[{longitude:a,rank:2,upright:{placed:e,south:r.vector,north:i.vector}}]}let s=t.longitude<n.longitude,[c,l]=s?[t,n]:[n,t],u=s?r:[-r[0],-r[1],-r[2]],[d,f]=s?[a,o]:[o,a];if(i)return polarEvents(e,i,u,s,d,f);let span=(t,n,r)=>{let i={stretch:{placed:e,west:r,east:l.vector,north:u,eastward:s},entry:void 0};return[{longitude:t,rank:1,slot:i},{longitude:n,rank:3,slot:i}]};return d<f?span(d,f,c.vector):[...span(d,180,c.vector),...span(-180,f,atAntimeridian(e.arc))]}function polarEvents(e,t,n,r,i,a){let o=[e.arc.from,e.arc.to].map(({written:n,vector:r})=>({longitude:n===180?-180:n,rank:2,upright:{placed:e,south:t[2]>0?r:t,north:t[2]>0?t:r}})),across=(i,a)=>{let o={stretch:{placed:e,west:t,east:t,north:n,eastward:r},entry:void 0};return[{longitude:i,rank:1,slot:o},{longitude:a,rank:0,slot:o}]};return i<a?[...o,...across(i,a)]:[...o,...across(i,180),...a>-180?across(-180,a):[]]}function latitude(e){return Math.atan2(e[2],Math.hypot(e[0],e[1]))}function sweep(e,t){let n=e.flatMap(arcEvents);n.sort((e,t)=>e.longitude-t.longitude||e.rank-t.rank);let r={stretch:void 0,links:createLinks(24)},meeting=(e,n)=>{if(e&&n&&!(t(e,n)||!meet(e.arc,n.arc)))return[e,n]},i=[],a=new Map,placeArrivals=()=>{let e=Array.from(a,([e,{entry:t,west:n}])=>{let r=t.links[0]?.next;for(;r?.stretch?.placed.ring===e;)r=r.links[0]?.next;return{ring:e,height:latitude(n),north:r?.stretch}});e.sort((e,t)=>t.height-e.height);for(let{ring:t,north:n}of e)i.push({ring:t,north:n});a.clear()},o=new Set;for(let[e,t]of n.entries())if(t.rank===1){let i=1+Math.floor(-Math.log2(1-Math.random())),s=enter(r,t.slot.stretch,Math.min(24,i));t.slot.entry=s;let[c]=s.links,l=meeting(c?.previous?.stretch?.placed,s.stretch?.placed)??meeting(s.stretch?.placed,c?.next?.stretch?.placed);if(l)return{meeting:l};let{placed:u,west:d}=t.slot.stretch,f=a.get(u.ring);(!o.has(u.ring)||f&&latitude(d)>latitude(f.west))&&(o.add(u.ring),a.set(u.ring,{entry:s,west:d}));let p=n[e+1];(p?.rank!==1||p.longitude!==t.longitude)&&placeArrivals()}else if(t.rank===2){let{upright:e}=t,n=southOf(r,e.south,23);for(n=n.stretch?n:n.links[0]?.next;n?.stretch;){let t=meeting(e.placed,n.stretch.placed);if(t)return{meeting:t};if(dot(n.stretch.north,e.north)<-v)break;n=n.links[0]?.next}}else if(t.slot.entry){let[e]=t.slot.entry.links;leave(t.slot.entry);let n=meeting(e?.previous?.stretch?.placed,e?.next?.stretch?.placed);if(n)return{meeting:n}}return{placements:i}}function signedArea(e){let t=0,n=0,r,i=0;for(let a of e){let e=cross(a.start,a.end)[2],o=1+dot(a.start,a.end),s=a.start[2]+a.end[2];s>=0?(t+=2*Math.atan2(e,o+s),r!==void 0&&(n+=a.from.longitude-r),r=void 0):(t+=2*Math.atan2(-e,o-s),r??=a.from.longitude),i=a.to.longitude}return r!==void 0&&(n+=i-r),t+2*n*_}function wound(e,t,n){return t===n?e:e.reverse()}function ringPath(e){return e===0?[`outer`]:[`holes`,e-1]}function ringNode(e,t,n){return{index:n,hole:n===0?1/0:n-1,points:e,arcs:t,counterClockwise:signedArea(t)>0,around:void 0,inside:!1,firstAround:1/0,firstWithin:1/0}}function validateGeoPolygon(e){let n=u(g,e);if(n.issues)return n;let i=ringArcs(n.value.outer,[`outer`]);if(i.issues)return i;let a=ringNode(n.value.outer,i.value,0),o=[];for(let[e,t]of(n.value.holes??[]).entries()){let n=ringArcs(t,[`holes`,e]);if(n.issues)return n;o.push(ringNode(t,n.value,e+1))}let s=sweep([a,...o].flatMap(e=>e.arcs.map((t,n)=>({arc:t,ring:e,index:n}))),(e,t)=>e.ring===t.ring&&[0,1,e.ring.arcs.length-1].includes(Math.abs(e.index-t.index)));if(s.meeting){let[e,t]=s.meeting,n=ringPath(Math.max(e.ring.index,t.ring.index));return e.ring===t.ring?r(`A GeoPolygon ring cannot self-intersect`,n):Math.min(e.ring.index,t.ring.index)===0?r(`A GeoPolygon hole must be strictly inside its outer ring`,n):r(`GeoPolygon holes cannot touch or overlap`,n)}for(let{ring:e,north:t}of s.placements){let n=t?.placed.ring,r=n===void 0||n.counterClockwise!==t?.eastward?n:n.around;e.around=r,e.inside=r!==void 0&&(r.index===0||r.inside),e.firstAround=r?Math.min(r.hole,r.firstAround):1/0}for(let{ring:e}of s.placements.reverse()){let{around:t}=e;t&&(t.firstWithin=Math.min(t.firstWithin,e.hole,e.firstWithin))}for(let{hole:e,inside:t,firstAround:n,firstWithin:i}of o){if(!t)return r(`A GeoPolygon hole must be strictly inside its outer ring`,[`holes`,e]);if(Math.min(n,i)<e)return r(`GeoPolygon holes cannot touch or overlap`,[`holes`,e])}let c=wound(a.points,a.counterClockwise,!0),l=o.map(({points:e,counterClockwise:t})=>wound(e,t,!1));return t(l.length>0?{outer:c,holes:l}:{outer:c})}const x=f({bounds:a(`object`,validateGeoBounds),polygon:a(`object`,validateGeoPolygon)});function validateGeoArea(e){let n=u(x,e);if(n.issues)return n;let{bounds:i,polygon:a}=n.value;return i&&!a?t({bounds:i}):a&&!i?t({polygon:a}):r(`Expected GeoArea with exactly one of bounds or polygon`)}function geoAreaSchema(){return a(`geo_area`,validateGeoArea)}export{geoAreaSchema as n,geoBoundsForDistance as r,m as t};
2
+ //# sourceMappingURL=geo-area-codec-CbkmFArQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"geo-area-codec-1SY9im7O.mjs","names":["latitude","last","north"],"sources":["../src/validation/primitives/geo-area-codec.ts"],"sourcesContent":["import type { ValidationResult, VibSchema } from \"../types\";\nimport { geoLatitude, geoLongitude, validateGeoPoint } from \"./geo-point-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n type GeoArea,\n type GeoBounds,\n type GeoPoint,\n type GeoPolygon,\n} from \"./geo-values\";\nimport {\n createSchema,\n fail,\n ok,\n validateArray,\n validateSchema,\n} from \"./helpers\";\nimport { object } from \"./object\";\nimport { optional } from \"./optional\";\n\nexport type { GeoArea, GeoBounds, GeoPolygon } from \"./geo-values\";\n\nconst OUTWARD_BOUND_DEGREES = 1e-10;\n\n/** The fixed spherical Earth model shared by portable GeoPoint distance SQL. */\nexport const GEO_POINT_EARTH_RADIUS_METERS = 6_371_008.8;\n\n/**\n * Construct the smallest conservative latitude/longitude rectangle around a\n * trusted spherical distance cap. The exact distance predicate remains the\n * membership owner; this rectangle is only an index-friendly superset.\n */\nexport function geoBoundsForDistance(\n point: GeoPoint,\n meters: number\n): GeoBounds {\n if (meters <= 0) {\n return {\n south: point.latitude,\n west: point.longitude,\n north: point.latitude,\n east: point.longitude,\n };\n }\n\n const angularRadius = meters / GEO_POINT_EARTH_RADIUS_METERS;\n if (angularRadius >= Math.PI) {\n return { south: -90, west: -180, north: 90, east: 180 };\n }\n\n const latitudeRadians = (point.latitude * Math.PI) / 180;\n const latitudeDelta = (angularRadius * 180) / Math.PI;\n const south = Math.max(\n -90,\n point.latitude - latitudeDelta - OUTWARD_BOUND_DEGREES\n );\n const north = Math.min(\n 90,\n point.latitude + latitudeDelta + OUTWARD_BOUND_DEGREES\n );\n if (south === -90 || north === 90) {\n return { south, west: -180, north, east: 180 };\n }\n\n const longitudeDelta =\n (Math.asin(\n Math.min(1, Math.sin(angularRadius) / Math.cos(latitudeRadians))\n ) *\n 180) /\n Math.PI +\n OUTWARD_BOUND_DEGREES;\n return {\n south,\n west: normalizeLongitude(point.longitude - longitudeDelta),\n north,\n east: normalizeLongitude(point.longitude + longitudeDelta),\n };\n}\n\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n\nconst boundsRecord = object(\n {\n [GEO_BOUNDS_KEYS[0]]: geoLatitude,\n [GEO_BOUNDS_KEYS[1]]: geoLongitude,\n [GEO_BOUNDS_KEYS[2]]: geoLatitude,\n [GEO_BOUNDS_KEYS[3]]: geoLongitude,\n },\n { partial: false }\n);\n\nexport function validateGeoBounds(value: unknown): ValidationResult<GeoBounds> {\n const bounds = validateSchema(boundsRecord, value);\n if (bounds.issues) return bounds;\n // An inverted rectangle is no database error: the latitude arm of\n // withinBounds (adapters/shared/geo-point.ts) would silently match nothing.\n if (bounds.value.south > bounds.value.north) {\n return fail(\"GeoBounds south must be less than or equal to north\", [\n \"south\",\n ]);\n }\n return bounds;\n}\n\n/**\n * A ring is its vertices in input order, at least GEO_POLYGON_MIN_RING_POINTS\n * of them: the JSON Schema states that minimum, and closedRing\n * (adapters/shared/geo-point.ts) reads the first vertex of every ring. The\n * count is judged before any vertex, so a short ring reports its length.\n */\nfunction validateRing(value: unknown): ValidationResult<GeoPoint[]> {\n const members = validateArray(value, ok);\n if (members.issues) return members;\n if (members.value.length < GEO_POLYGON_MIN_RING_POINTS) {\n return fail(\n `A GeoPolygon ring needs at least ${GEO_POLYGON_MIN_RING_POINTS} vertices`\n );\n }\n return validateArray(members.value, validateGeoPoint);\n}\n\nconst polygonRecord = object(\n {\n outer: createSchema(\"array\", validateRing),\n holes: optional(\n createSchema(\"array\", (value) => validateArray(value, validateRing))\n ),\n },\n { partial: false }\n);\n\n/*\n * Polygon geometry, judged after the record walker admitted the shape.\n * VibORM reads an edge as the great-circle arc between its vertices, so\n * crossings, touches and containment are judged on the unit sphere, never on\n * straight longitude/latitude lines, and the polygon is the side of its outer\n * ring away from both poles.\n *\n * Refused as having no single meaning on that reading: a ring crossing,\n * touching or retracing itself, a ring of zero area, a hole not strictly\n * inside its outer ring, holes touching or overlapping.\n *\n * DOMAIN CHOICES, each made for the reason given, not a property every valid\n * polygon lacks. A new refusal needs a reason of this kind; \"invalid\n * geometry\" is not one.\n * - Resolution, TOLERANCE (1e-9 degrees): exact tests on float64 vectors need\n * a margin for rounding, one for every ring size. Within it a point is on\n * what it touches: rings closer than it touch and are refused, and an edge\n * shorter than it is a repeated vertex.\n * - Near-antipodal edges, NEAREST_ANTIPODE (0.01 degrees): nearer to\n * antipodal, one float64 step of a written coordinate turns the edge's\n * great circle by more than a third of TOLERANCE, so the coordinates do not\n * fix the edge; it is refused.\n * - Poles: a vertex within TOLERANCE of a pole has no longitude, and a ring\n * winding around a pole or running over both has no side away from both;\n * both are refused. An edge whose longitudes differ by exactly 180 degrees\n * runs over the pole on its vertices' side, and is admitted.\n *\n * A valid polygon is not refused because a database reads it differently:\n * MySQL draws edges on the ellipsoid, PostGIS misreads some rings reaching\n * across all three coordinate planes (docs/content/docs/schema/scalars/\n * point.mdx, \"How each database reads a polygon\", gives the measured\n * differences).\n */\n\ntype Vector = readonly [x: number, y: number, z: number];\n\n/** One ring vertex, its longitude unwrapped past ±180 along the ring. */\ninterface UnwrappedPoint {\n /**\n * The longitude unwrapped: it records how the ring travels (the edges'\n * directions, the area's lunes), never where the vertex lies.\n */\n readonly longitude: number;\n readonly latitude: number;\n /** The longitude as written, where `sweep` places it. */\n readonly written: number;\n /** The vertex on the unit sphere, from its written coordinates. */\n readonly vector: Vector;\n}\n\n/** One ring edge: the great-circle arc from `from` to `to`. */\ninterface Arc {\n readonly from: UnwrappedPoint;\n readonly to: UnwrappedPoint;\n readonly start: Vector;\n readonly end: Vector;\n /** The unit normal of the arc's great circle, start × end. */\n readonly normal: Vector;\n /**\n * The pole the arc runs over, when its longitudes differ by exactly 180\n * degrees: it rises along one meridian and falls along the other.\n */\n readonly pole: Vector | undefined;\n}\n\n/** A ring's arcs; a ring is refused before it could have fewer than two. */\ntype Ring = readonly [Arc, ...Arc[]];\n\nconst RADIANS = Math.PI / 180;\n/**\n * An angle of 1e-9 degrees, about 0.1 mm: a point this near an arc is on it,\n * and an edge this short is a repeated vertex. It is VibORM's resolution, a\n * domain choice (above), at every ring size: a smaller feature reads as a\n * touch or a repeated vertex, so a ring needs no size bound of its own, and a\n * vertex needs no pole clearance. How exactly rings are judged above it is\n * measured in the guard-ownership ledger's D2 addendum.\n */\nconst TOLERANCE = 1e-9 * RADIANS;\n/**\n * The chord between an edge's end and the antipode of its start below which\n * the edge is refused: 0.01 degrees, a domain choice (above). Two antipodal\n * points lie on every great circle through them, and near the antipode the\n * circle an edge takes turns by up to about 3e-12 / d degrees when a written\n * coordinate moves by one float64 step, d degrees from antipodal (measured in\n * the ledger's D2 addendum, \"Near-antipodal edge\"). From 0.01 degrees out the\n * edge's path is fixed to a third of TOLERANCE; nearer, the written\n * coordinates do not decide on which side of it a point lies.\n */\nconst NEAREST_ANTIPODE = 2 * Math.sin(0.005 * RADIANS);\n\nfunction toVector(longitude: number, latitude: number): Vector {\n const cosine = Math.cos(latitude * RADIANS);\n return [\n cosine * Math.cos(longitude * RADIANS),\n cosine * Math.sin(longitude * RADIANS),\n Math.sin(latitude * RADIANS),\n ];\n}\n\nfunction dot(first: Vector, second: Vector): number {\n return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];\n}\n\n/**\n * first × second, taken as (first − second) × (first + second) / 2: the same\n * vector, but the difference of two nearby points is exact, so the normal of\n * a short arc keeps its direction; taken plainly it loses it at 1e-7 degrees\n * (the ledger's D2 addendum, \"Cross products from vertex differences\").\n */\nfunction cross(first: Vector, second: Vector): Vector {\n const dx = first[0] - second[0];\n const dy = first[1] - second[1];\n const dz = first[2] - second[2];\n const sx = first[0] + second[0];\n const sy = first[1] + second[1];\n const sz = first[2] + second[2];\n return [\n (dy * sz - dz * sy) / 2,\n (dz * sx - dx * sz) / 2,\n (dx * sy - dy * sx) / 2,\n ];\n}\n\nfunction unit(vector: Vector): Vector {\n const length = Math.hypot(...vector);\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nfunction chord(first: Vector, second: Vector): number {\n return Math.hypot(\n first[0] - second[0],\n first[1] - second[1],\n first[2] - second[2]\n );\n}\n\nfunction antipode(vector: Vector): Vector {\n return [-vector[0], -vector[1], -vector[2]];\n}\n\n/** What an edge adds to its end's longitude to take the short way round. */\nfunction shortWay(delta: number): number {\n if (delta > 180) return -360;\n if (delta < -180) return 360;\n return 0;\n}\n\n/** One distinct ring vertex, at its index in the ring. */\ninterface Distinct {\n readonly vertex: GeoPoint;\n readonly index: number;\n readonly vector: Vector;\n}\n\n/**\n * The ring's distinct vertices, closed on the first. A vertex within TOLERANCE\n * of a pole is refused: on the pole it has no longitude, and so no meridian\n * for its edges. A repeated consecutive vertex, the caller's closing vertex\n * included, is admitted as the zero-length edge both databases ignore, and\n * dropped here.\n */\nfunction distinctVertices(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Distinct[]> {\n const distinct: Distinct[] = [];\n for (const [index, vertex] of ring.entries()) {\n const vector = toVector(vertex.longitude, vertex.latitude);\n if (Math.hypot(vector[0], vector[1]) <= TOLERANCE) {\n return fail(\"A GeoPolygon ring cannot contain a pole\", [...path, index]);\n }\n const last = distinct.at(-1);\n if (!last || chord(last.vector, vector) > TOLERANCE) {\n distinct.push({ vertex, index, vector });\n }\n }\n const [first] = distinct;\n const last = distinct.at(-1);\n if (first && last && chord(last.vector, first.vector) > TOLERANCE) {\n distinct.push(first);\n }\n return ok(distinct);\n}\n\n/**\n * The ring's arcs, each taking the short way round in longitude. An edge\n * whose longitudes differ by exactly 180 degrees has no short way: it runs\n * over the pole on the side of its endpoints' mean latitude, along one great\n * circle, and goes round whichever way leaves the ring no turn.\n */\nfunction ringArcs(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Ring> {\n const distinct = distinctVertices(ring, path);\n if (distinct.issues) return distinct;\n // The ring's turn in longitude, an edge over a pole taken as written.\n let turn = 0;\n for (const [position, { vertex }] of distinct.value.entries()) {\n const previous = distinct.value[position - 1];\n if (previous) {\n turn += shortWay(vertex.longitude - previous.vertex.longitude);\n }\n }\n const arcs: Arc[] = [];\n let wrap = 0;\n let from: UnwrappedPoint | undefined;\n let overPole: Vector | undefined;\n for (const { vertex, index, vector } of distinct.value) {\n let pole: Vector | undefined;\n if (from) {\n const delta = vertex.longitude - from.written;\n if (Math.abs(delta) === 180) {\n pole = [0, 0, Math.sign(vertex.latitude + from.latitude)];\n if (Math.abs(delta - turn) === 180) wrap -= turn;\n }\n wrap += shortWay(delta);\n }\n const to = {\n longitude: vertex.longitude + wrap,\n latitude: vertex.latitude,\n written: vertex.longitude,\n vector,\n };\n if (from) {\n if (chord(antipode(from.vector), vector) < NEAREST_ANTIPODE) {\n return fail(\n \"A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal\",\n [...path, index]\n );\n }\n // Over both poles the ring has no side away from both, and no way\n // round that leaves it no turn. Over one pole twice it crosses itself\n // there, which the sweep finds.\n if (pole && overPole && pole[2] !== overPole[2]) {\n return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n }\n overPole ??= pole;\n arcs.push({\n from,\n to,\n start: from.vector,\n end: vector,\n normal: unit(cross(from.vector, vector)),\n pole,\n });\n }\n from = to;\n }\n // Longitudes that went once around the globe enclose a pole, and the ring\n // then has no side away from both poles.\n if (wrap !== 0) return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n const [first, ...rest] = arcs;\n // The self-intersection no pair of non-neighbor arcs shows: a ring of at\n // most three arcs on one great circle retraces itself, and a ring of one\n // distinct vertex has no arc at all.\n if (\n !first ||\n (rest.length < 3 &&\n rest.every(({ start }) => Math.abs(side(first, start)) <= TOLERANCE))\n ) {\n return fail(\"A GeoPolygon ring must have non-zero area\", [...path]);\n }\n // Neighbors meet at their shared vertex, which `sweep` excuses, unless\n // one doubles back along the other: such arcs overlap, and the sweep\n // cannot order arcs that overlap.\n let behind = first;\n for (const arc of [...rest, first]) {\n if (onArc(arc.end, behind) || onArc(behind.start, arc)) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", [...path]);\n }\n behind = arc;\n }\n return ok([first, ...rest]);\n}\n\n/** The sine of the point's signed angular distance from the arc's circle. */\nfunction side(arc: Arc, point: Vector): number {\n return dot(arc.normal, point);\n}\n\nfunction onArc(point: Vector, arc: Arc): boolean {\n return (\n Math.abs(side(arc, point)) <= TOLERANCE &&\n dot(cross(arc.start, point), arc.normal) >= -TOLERANCE &&\n dot(cross(point, arc.end), arc.normal) >= -TOLERANCE\n );\n}\n\nfunction opposite(first: number, second: number): boolean {\n return (\n (first > TOLERANCE && second < -TOLERANCE) ||\n (first < -TOLERANCE && second > TOLERANCE)\n );\n}\n\n/**\n * The two arcs cross at one point interior to both: each straddles the\n * other's great circle, and they hold the same one of the two antipodal\n * points where the circles meet. An arc shorter than half a circle holds a\n * point of it when the point lies on the side of the arc's middle, where\n * start + end points; arcs that straddle each other but hold opposite points\n * (a ring reaching across all three coordinate planes has such pairs) are\n * apart.\n */\nfunction crosses(first: Arc, second: Arc): boolean {\n if (\n !(\n opposite(side(first, second.start), side(first, second.end)) &&\n opposite(side(second, first.start), side(second, first.end))\n )\n ) {\n return false;\n }\n const meeting = cross(first.normal, second.normal);\n return (\n dot(meeting, first.start) + dot(meeting, first.end) > 0 ===\n dot(meeting, second.start) + dot(meeting, second.end) > 0\n );\n}\n\nfunction meet(first: Arc, second: Arc): boolean {\n return (\n crosses(first, second) ||\n onArc(first.start, second) ||\n onArc(first.end, second) ||\n onArc(second.start, first) ||\n onArc(second.end, first)\n );\n}\n\n/**\n * One ring of the polygon, and where `sweep` places it among the others:\n * `around` is the innermost ring around it, `inside` whether it lies inside\n * the outer ring, `firstAround` and `firstWithin` the first hole around it\n * and inside it.\n */\ninterface RingNode {\n /** 0 the outer ring, then the holes. */\n readonly index: number;\n /** The ring's index in `holes`, none for the outer ring. */\n readonly hole: number;\n readonly points: GeoPoint[];\n readonly arcs: Ring;\n readonly counterClockwise: boolean;\n around: RingNode | undefined;\n inside: boolean;\n firstAround: number;\n firstWithin: number;\n}\n\n/** An arc of `ring` at `index` along it. */\ninterface Placed {\n readonly arc: Arc;\n readonly ring: RingNode;\n readonly index: number;\n}\n\n/**\n * One stretch of an arc between two meridians, as the sweep orders it, from\n * its west end.\n */\ninterface Stretch {\n readonly placed: Placed;\n readonly west: Vector;\n readonly east: Vector;\n /** The arc's unit normal, turned north. */\n readonly north: Vector;\n /** Whether the arc runs east, so that its normal is `north`. */\n readonly eastward: boolean;\n}\n\n/** An arc along a meridian, which the sweep meets at one longitude. */\ninterface Upright {\n readonly placed: Placed;\n readonly south: Vector;\n readonly north: Vector;\n}\n\ninterface Link {\n previous: Entry | undefined;\n next: Entry | undefined;\n}\n\n/** A stretch in the sweep's south-to-north order, a skip list. */\ninterface Entry {\n readonly stretch: Stretch | undefined;\n readonly links: readonly Link[];\n}\n\nconst LEVELS = 24;\n\nfunction createLinks(height: number): Link[] {\n return Array.from({ length: height }, () => ({\n previous: undefined,\n next: undefined,\n }));\n}\n\n/**\n * Whether `entering` starts south of `resident` on the meridian where it\n * enters the sweep; one starting on the resident is ordered by where it\n * heads. Only neighbors in this order are compared, so the order must only\n * be right between arcs that do not meet.\n */\nfunction below(entering: Stretch, resident: Stretch): boolean {\n const height = dot(resident.north, entering.west);\n if (Math.abs(height) > TOLERANCE) return height < 0;\n return dot(resident.north, entering.east) < 0;\n}\n\n/** The last entry south of `point` on the sweep's meridian, or the head. */\nfunction southOf(head: Entry, point: Vector, level: number): Entry {\n let cursor = head;\n for (let at = level; at >= 0; at -= 1) {\n let next = cursor.links[at]?.next;\n while (next?.stretch && dot(next.stretch.north, point) > TOLERANCE) {\n cursor = next;\n next = cursor.links[at]?.next;\n }\n }\n return cursor;\n}\n\nfunction enter(head: Entry, stretch: Stretch, height: number): Entry {\n const entry: Entry = { stretch, links: createLinks(height) };\n let cursor = head;\n for (let level = LEVELS - 1; level >= 0; level -= 1) {\n let next = cursor.links[level]?.next;\n while (next?.stretch && !below(stretch, next.stretch)) {\n cursor = next;\n next = cursor.links[level]?.next;\n }\n const link = entry.links[level];\n const before = cursor.links[level];\n if (link && before) {\n link.previous = cursor;\n link.next = before.next;\n const after = before.next?.links[level];\n if (after) after.previous = entry;\n before.next = entry;\n }\n }\n return entry;\n}\n\nfunction leave(entry: Entry): void {\n for (const [level, { previous, next }] of entry.links.entries()) {\n const before = previous?.links[level];\n if (before) before.next = next;\n const after = next?.links[level];\n if (after) after.previous = previous;\n }\n}\n\n/** The antimeridian on the equator. */\nconst ANTIMERIDIAN = toVector(180, 0);\n\n/** The point where the arc crosses the antimeridian. */\nfunction atAntimeridian(arc: Arc): Vector {\n const meeting = unit(\n cross(arc.normal, [-ANTIMERIDIAN[1], ANTIMERIDIAN[0], 0])\n );\n return dot(meeting, ANTIMERIDIAN) < 0 ? antipode(meeting) : meeting;\n}\n\n/**\n * At one longitude the arcs over a pole leave first, then the stretches\n * starting there enter, then the arcs along the meridian are walked, then the\n * stretches ending there leave.\n */\ntype Event =\n | { readonly longitude: number; readonly rank: 0 | 3; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 1; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 2; readonly upright: Upright };\n\ninterface Slot {\n readonly stretch: Stretch;\n entry: Entry | undefined;\n}\n\n/**\n * The arc's sweep events at its written longitudes, west to east, ±180 read\n * as -180 so that arcs meeting on the antimeridian are in the sweep\n * together: one for an arc along a meridian, else an entry and an exit per\n * stretch, two stretches when the arc crosses the antimeridian, split there.\n */\nfunction arcEvents(placed: Placed): Event[] {\n const { from, to, normal, pole } = placed.arc;\n const first = from.written === 180 ? -180 : from.written;\n const second = to.written === 180 ? -180 : to.written;\n if (first === second) {\n const [south, north] =\n from.latitude < to.latitude ? [from, to] : [to, from];\n const upright = { placed, south: south.vector, north: north.vector };\n return [{ longitude: first, rank: 2, upright }];\n }\n const eastward = from.longitude < to.longitude;\n const [west, east] = eastward ? [from, to] : [to, from];\n const north: Vector = eastward\n ? normal\n : [-normal[0], -normal[1], -normal[2]];\n const [low, high] = eastward ? [first, second] : [second, first];\n if (pole) return polarEvents(placed, pole, north, eastward, low, high);\n const span = (start: number, end: number, point: Vector): Event[] => {\n const slot = {\n stretch: { placed, west: point, east: east.vector, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 3, slot },\n ];\n };\n return low < high\n ? span(low, high, west.vector)\n : [\n ...span(low, 180, west.vector),\n ...span(-180, high, atAntimeridian(placed.arc)),\n ];\n}\n\n/**\n * The sweep events of an arc over a pole: an arc along each of its meridians,\n * from its vertex to the pole, and between them a stretch at the pole, beyond\n * every other arc crossing those longitudes. The stretch keeps the arc's\n * circle, which has every point of the meridians between on its far side\n * from the pole. It leaves before the stretches starting on the arc's last\n * meridian enter, since the arc runs along that meridian there, which its\n * walk there covers.\n */\nfunction polarEvents(\n placed: Placed,\n pole: Vector,\n north: Vector,\n eastward: boolean,\n low: number,\n high: number\n): Event[] {\n const walks = [placed.arc.from, placed.arc.to].map(\n ({ written, vector }): Event => ({\n longitude: written === 180 ? -180 : written,\n rank: 2,\n upright: {\n placed,\n south: pole[2] > 0 ? vector : pole,\n north: pole[2] > 0 ? pole : vector,\n },\n })\n );\n const across = (start: number, end: number): Event[] => {\n const slot = {\n stretch: { placed, west: pole, east: pole, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 0, slot },\n ];\n };\n if (low < high) return [...walks, ...across(low, high)];\n return [\n ...walks,\n ...across(low, 180),\n ...(high > -180 ? across(-180, high) : []),\n ];\n}\n\n/**\n * The point's latitude, in radians, which orders points on one meridian. Its\n * z coordinate alone does not: z rounds to ±1 within about 6e-7 degrees of a\n * pole, where rings arriving together would tie.\n */\nfunction latitude(point: Vector): number {\n return Math.atan2(point[2], Math.hypot(point[0], point[1]));\n}\n\n/**\n * A ring on the meridian where the sweep first meets it, and the arc of\n * another ring first north of it there, if any.\n */\ninterface Placement {\n readonly ring: RingNode;\n readonly north: Stretch | undefined;\n}\n\ntype Swept =\n | { readonly meeting: readonly [Placed, Placed] }\n | { readonly meeting?: undefined; readonly placements: Placement[] };\n\n/**\n * The first two arcs found meeting that `apart` does not excuse, by a sweep\n * from the antimeridian eastward that keeps the arcs it crosses in\n * south-to-north order and compares each only with its neighbors in it\n * (Shamos and Hoey): two arcs that meet are neighbors just before the\n * westernmost meeting, so admission takes expected n log n time in the arc\n * count however the arcs lie. At each longitude the arcs starting there enter\n * first; then each arc along that meridian is compared with the arcs crossing\n * its span, found by position; then the arcs ending there leave. Two arcs\n * along one meridian need no comparison of their own: where they meet, one\n * ends on the other, and the arc continuing its ring from that end crosses\n * the meridian there (a ring's arcs along one meridian that continue each\n * other end where the last one does, and a ring doubling back along a\n * meridian is refused in `ringArcs`), so the walk along the other one meets\n * it. An arc over a pole is walked along both its meridians, with a stretch\n * at the pole between them (`polarEvents`): two arcs over one pole meet\n * there, where either their stretches are neighbors at the pole or, when\n * their longitudes only touch, one's walk finds the other's stretch.\n *\n * Failing a meeting, where each ring was first met: once the arcs starting\n * on that meridian have entered, the arc north of the ring's northernmost\n * point there, skipping the ring's own arcs through that point. The rings\n * met on one meridian are listed north to south, so every ring is listed\n * after the ring of the arc north of it.\n */\nfunction sweep(\n arcs: readonly Placed[],\n apart: (first: Placed, second: Placed) => boolean\n): Swept {\n const events = arcs.flatMap(arcEvents);\n events.sort(\n (left, right) => left.longitude - right.longitude || left.rank - right.rank\n );\n const head: Entry = { stretch: undefined, links: createLinks(LEVELS) };\n const meeting = (\n first: Placed | undefined,\n second: Placed | undefined\n ): readonly [Placed, Placed] | undefined => {\n if (!(first && second)) return;\n if (apart(first, second) || !meet(first.arc, second.arc)) return;\n return [first, second];\n };\n const placements: Placement[] = [];\n // Each ring met for the first time on the sweep's meridian, with its\n // northernmost entry there so far.\n const arrivals = new Map<RingNode, { entry: Entry; west: Vector }>();\n const placeArrivals = (): void => {\n const arrived = Array.from(arrivals, ([ring, { entry, west }]) => {\n let next = entry.links[0]?.next;\n while (next?.stretch?.placed.ring === ring) next = next.links[0]?.next;\n return { ring, height: latitude(west), north: next?.stretch };\n });\n arrived.sort((left, right) => right.height - left.height);\n // One push per ring: a spread would pass every ring arriving on this\n // meridian as a call argument, past the engine's argument limit.\n for (const { ring, north } of arrived) placements.push({ ring, north });\n arrivals.clear();\n };\n const met = new Set<RingNode>();\n for (const [index, event] of events.entries()) {\n if (event.rank === 1) {\n // A skip list's heights are coin flips the input cannot know: heights\n // a polygon could predict let it keep its long-lived arcs low and make\n // every search walk them one by one. The verdict does not depend on\n // them: arcs that meet are neighbors before they meet at any height.\n const height = 1 + Math.floor(-Math.log2(1 - Math.random()));\n const entry = enter(head, event.slot.stretch, Math.min(LEVELS, height));\n event.slot.entry = entry;\n const [link] = entry.links;\n const found =\n meeting(link?.previous?.stretch?.placed, entry.stretch?.placed) ??\n meeting(entry.stretch?.placed, link?.next?.stretch?.placed);\n if (found) return { meeting: found };\n const { placed, west } = event.slot.stretch;\n const top = arrivals.get(placed.ring);\n if (\n !met.has(placed.ring) ||\n (top && latitude(west) > latitude(top.west))\n ) {\n met.add(placed.ring);\n arrivals.set(placed.ring, { entry, west });\n }\n const next = events[index + 1];\n if (next?.rank !== 1 || next.longitude !== event.longitude) {\n placeArrivals();\n }\n } else if (event.rank === 2) {\n const { upright } = event;\n // Every arc crossing the meridian within the span meets this one, so\n // the walk stops at the first not excused, or past the north end.\n let entry: Entry | undefined = southOf(head, upright.south, LEVELS - 1);\n entry = entry.stretch ? entry : entry.links[0]?.next;\n while (entry?.stretch) {\n const found = meeting(upright.placed, entry.stretch.placed);\n if (found) return { meeting: found };\n if (dot(entry.stretch.north, upright.north) < -TOLERANCE) break;\n entry = entry.links[0]?.next;\n }\n } else if (event.slot.entry) {\n const [link] = event.slot.entry.links;\n leave(event.slot.entry);\n const found = meeting(\n link?.previous?.stretch?.placed,\n link?.next?.stretch?.placed\n );\n if (found) return { meeting: found };\n }\n }\n return { placements };\n}\n\n/**\n * The ring's signed area in steradians, positive when counterclockwise: the\n * sum of the triangles each arc makes with the north pole (Van Oosterom and\n * Strackee), taken through the south pole's triangle and the lune between the\n * arc's meridians when the arc lies nearer the south pole, where the north\n * pole's triangle loses its precision. The lunes' longitudes telescope, so\n * each run of such arcs adds the longitude from its start to its end: a ring\n * near the south pole is one run, and its lunes add exactly nothing, where\n * summed arc by arc their rounding would outweigh its area. No admitted ring\n * has a pole inside it (`wrap` in `ringArcs`), so this is the area on the\n * ring's pole-free side, and its sign says on which side of its arcs that\n * area lies.\n */\nfunction signedArea(ring: Ring): number {\n let sum = 0;\n let lune = 0;\n let run: number | undefined;\n let end = 0;\n for (const arc of ring) {\n const turn = cross(arc.start, arc.end)[2];\n const along = 1 + dot(arc.start, arc.end);\n const lift = arc.start[2] + arc.end[2];\n if (lift >= 0) {\n sum += 2 * Math.atan2(turn, along + lift);\n if (run !== undefined) lune += arc.from.longitude - run;\n run = undefined;\n } else {\n sum += 2 * Math.atan2(-turn, along - lift);\n run ??= arc.from.longitude;\n }\n end = arc.to.longitude;\n }\n if (run !== undefined) lune += end - run;\n return sum + 2 * lune * RADIANS;\n}\n\n/*\n * A hole must lie strictly inside its outer ring, and holes must neither touch\n * nor overlap: a hole reaching outside its outer ring, or a point in two\n * holes, has no single reading (the ledger's D2 addendum tabulates what each\n * database answered). A touch is refused with them: a hole written touching a\n * straight parallel edge crosses that edge's arc.\n */\n\n/**\n * Kept output normalization, not a refusal: the GeoJSON that withinPolygon\n * binds (adapters/databases/{postgres,mysql}) always carries a counterclockwise\n * outer ring and clockwise holes, because neither database's reading of ring\n * orientation is proven portable (v1-public-api-geopoint-plan.md).\n */\nfunction wound(\n ring: GeoPoint[],\n counterClockwise: boolean,\n wanted: boolean\n): GeoPoint[] {\n return counterClockwise === wanted ? ring : ring.reverse();\n}\n\nfunction ringPath(ring: number): PropertyKey[] {\n return ring === 0 ? [\"outer\"] : [\"holes\", ring - 1];\n}\n\nfunction ringNode(points: GeoPoint[], arcs: Ring, index: number): RingNode {\n return {\n index,\n hole: index === 0 ? Number.POSITIVE_INFINITY : index - 1,\n points,\n arcs,\n counterClockwise: signedArea(arcs) > 0,\n around: undefined,\n inside: false,\n firstAround: Number.POSITIVE_INFINITY,\n firstWithin: Number.POSITIVE_INFINITY,\n };\n}\n\n/**\n * The walker admits the polygon's shape (exact keys, finite in-range\n * vertices, at least three per ring); the geometry then refuses the polygons\n * with no single meaning or outside the domain choices (above): each ring\n * alone, then the rings together.\n */\nexport function validateGeoPolygon(\n value: unknown\n): ValidationResult<GeoPolygon> {\n const polygon = validateSchema(polygonRecord, value);\n if (polygon.issues) return polygon;\n const outer = ringArcs(polygon.value.outer, [\"outer\"]);\n if (outer.issues) return outer;\n const shell = ringNode(polygon.value.outer, outer.value, 0);\n const holes: RingNode[] = [];\n for (const [index, points] of (polygon.value.holes ?? []).entries()) {\n const hole = ringArcs(points, [\"holes\", index]);\n if (hole.issues) return hole;\n holes.push(ringNode(points, hole.value, index + 1));\n }\n const placed = [shell, ...holes].flatMap((ring) =>\n ring.arcs.map((arc, index) => ({ arc, ring, index }))\n );\n // Neighbors along a ring meet at their shared vertex; an arc over a pole\n // meets itself where its walks find its stretch.\n const swept = sweep(\n placed,\n (first, second) =>\n first.ring === second.ring &&\n [0, 1, first.ring.arcs.length - 1].includes(\n Math.abs(first.index - second.index)\n )\n );\n if (swept.meeting) {\n const [first, second] = swept.meeting;\n const later = ringPath(Math.max(first.ring.index, second.ring.index));\n // A ring meeting itself has no single reading (the ledger's D2 table:\n // the bowtie and the ring past a whole turn over itself).\n if (first.ring === second.ring) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", later);\n }\n return Math.min(first.ring.index, second.ring.index) === 0\n ? fail(\"A GeoPolygon hole must be strictly inside its outer ring\", later)\n : fail(\"GeoPolygon holes cannot touch or overlap\", later);\n }\n // No two rings meet, so where the sweep first met a ring places all of it:\n // inside the ring of the arc north of it when that arc has its ring's\n // interior to the south (a counterclockwise ring's interior is on the left\n // of its arcs), else beside that ring, in the ring around it, which the\n // sweep placed first.\n for (const { ring, north } of swept.placements) {\n const other = north?.placed.ring;\n const around =\n other === undefined || other.counterClockwise !== north?.eastward\n ? other\n : other.around;\n ring.around = around;\n ring.inside = around !== undefined && (around.index === 0 || around.inside);\n ring.firstAround = around\n ? Math.min(around.hole, around.firstAround)\n : Number.POSITIVE_INFINITY;\n }\n // Reversed in place, the list's last use: every ring now comes before the\n // ring around it, which collects the first hole within it.\n for (const { ring } of swept.placements.reverse()) {\n const { around } = ring;\n if (around) {\n around.firstWithin = Math.min(\n around.firstWithin,\n ring.hole,\n ring.firstWithin\n );\n }\n }\n for (const { hole, inside, firstAround, firstWithin } of holes) {\n if (!inside) {\n return fail(\"A GeoPolygon hole must be strictly inside its outer ring\", [\n \"holes\",\n hole,\n ]);\n }\n if (Math.min(firstAround, firstWithin) < hole) {\n return fail(\"GeoPolygon holes cannot touch or overlap\", [\"holes\", hole]);\n }\n }\n const wide = wound(shell.points, shell.counterClockwise, true);\n const cut = holes.map(({ points, counterClockwise }) =>\n wound(points, counterClockwise, false)\n );\n // An empty and an absent holes list emit the same GeoJSON; one spelling\n // keeps them one validated argument, and so one cache key.\n return ok(cut.length > 0 ? { outer: wide, holes: cut } : { outer: wide });\n}\n\nconst areaRecord = object({\n bounds: createSchema(\"object\", validateGeoBounds),\n polygon: createSchema(\"object\", validateGeoPolygon),\n});\n\nexport function validateGeoArea(value: unknown): ValidationResult<GeoArea> {\n const area = validateSchema(areaRecord, value);\n if (area.issues) return area;\n const { bounds, polygon } = area.value;\n // Exactly one variant: buildGeoPointWithin (query-engine/builders/\n // geo-point-builder.ts) branches on `\"bounds\" in area`, so a second variant\n // would be dropped silently and a missing one would reach geoPolygonJson as\n // undefined and throw a TypeError instead of a database error.\n if (bounds && !polygon) return ok({ bounds });\n if (polygon && !bounds) return ok({ polygon });\n return fail(\"Expected GeoArea with exactly one of bounds or polygon\");\n}\n\nexport function geoAreaSchema(): VibSchema<GeoArea, GeoArea> {\n return createSchema(\"geo_area\", validateGeoArea);\n}\n"],"mappings":"2KAsBA,MAAM,EAAwB,MAGjB,EAAgC,UAO7C,SAAgB,qBACd,EACA,EACW,CACX,GAAI,GAAU,EACZ,MAAO,CACL,MAAO,EAAM,SACb,KAAM,EAAM,UACZ,MAAO,EAAM,SACb,KAAM,EAAM,UACb,CAGH,IAAM,EAAgB,EAAS,EAC/B,GAAI,GAAiB,KAAK,GACxB,MAAO,CAAE,MAAO,IAAK,KAAM,KAAM,MAAO,GAAI,KAAM,IAAK,CAGzD,IAAM,EAAmB,EAAM,SAAW,KAAK,GAAM,IAC/C,EAAiB,EAAgB,IAAO,KAAK,GAC7C,EAAQ,KAAK,IACjB,IACA,EAAM,SAAW,EAAgB,EAClC,CACK,EAAQ,KAAK,IACjB,GACA,EAAM,SAAW,EAAgB,EAClC,CACD,GAAI,IAAU,KAAO,IAAU,GAC7B,MAAO,CAAE,QAAO,KAAM,KAAM,QAAO,KAAM,IAAK,CAGhD,IAAM,EACH,KAAK,KACJ,KAAK,IAAI,EAAG,KAAK,IAAI,EAAc,CAAG,KAAK,IAAI,EAAgB,CAAC,CACjE,CACC,IACA,KAAK,GACP,EACF,MAAO,CACL,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC1D,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC3D,CAGH,SAAS,mBAAmB,EAA2B,CACrD,QAAW,EAAY,KAAO,IAAO,KAAO,IAAO,IAGrD,MAAM,EAAe,EACnB,EACG,EAAgB,IAAK,GACrB,EAAgB,IAAK,GACrB,EAAgB,IAAK,GACrB,EAAgB,IAAK,EACvB,CACD,CAAE,QAAS,GAAO,CACnB,CAED,SAAgB,kBAAkB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,OAAQ,OAAO,EACxB,GAAM,CAAE,SAAQ,WAAY,EAAK,MAOjC,OAFI,GAAU,CAAC,EAAgB,EAAG,CAAE,SAAQ,CAAC,CACzC,GAAW,CAAC,EAAe,EAAG,CAAE,UAAS,CAAC,CACvC,EAAK,yDAAyD,CAGvE,SAAgB,eAA6C,CAC3D,OAAO,EAAa,WAAY,gBAAgB"}
1
+ {"version":3,"file":"geo-area-codec-CbkmFArQ.mjs","names":["latitude","last","north"],"sources":["../src/validation/primitives/geo-area-codec.ts"],"sourcesContent":["import type { ValidationResult, VibSchema } from \"../types\";\nimport { geoLatitude, geoLongitude, validateGeoPoint } from \"./geo-point-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n type GeoArea,\n type GeoBounds,\n type GeoPoint,\n type GeoPolygon,\n} from \"./geo-values\";\nimport {\n createSchema,\n fail,\n ok,\n validateArray,\n validateSchema,\n} from \"./helpers\";\nimport { object } from \"./object\";\nimport { optional } from \"./optional\";\n\nexport type { GeoArea, GeoBounds, GeoPolygon } from \"./geo-values\";\n\nconst OUTWARD_BOUND_DEGREES = 1e-10;\n\n/** The fixed spherical Earth model shared by portable GeoPoint distance SQL. */\nexport const GEO_POINT_EARTH_RADIUS_METERS = 6_371_008.8;\n\n/**\n * Construct the smallest conservative latitude/longitude rectangle around a\n * trusted spherical distance cap. The exact distance predicate remains the\n * membership owner; this rectangle is only an index-friendly superset.\n */\nexport function geoBoundsForDistance(\n point: GeoPoint,\n meters: number\n): GeoBounds {\n if (meters <= 0) {\n return {\n south: point.latitude,\n west: point.longitude,\n north: point.latitude,\n east: point.longitude,\n };\n }\n\n const angularRadius = meters / GEO_POINT_EARTH_RADIUS_METERS;\n if (angularRadius >= Math.PI) {\n return { south: -90, west: -180, north: 90, east: 180 };\n }\n\n const latitudeRadians = (point.latitude * Math.PI) / 180;\n const latitudeDelta = (angularRadius * 180) / Math.PI;\n const south = Math.max(\n -90,\n point.latitude - latitudeDelta - OUTWARD_BOUND_DEGREES\n );\n const north = Math.min(\n 90,\n point.latitude + latitudeDelta + OUTWARD_BOUND_DEGREES\n );\n if (south === -90 || north === 90) {\n return { south, west: -180, north, east: 180 };\n }\n\n const longitudeDelta =\n (Math.asin(\n Math.min(1, Math.sin(angularRadius) / Math.cos(latitudeRadians))\n ) *\n 180) /\n Math.PI +\n OUTWARD_BOUND_DEGREES;\n return {\n south,\n west: normalizeLongitude(point.longitude - longitudeDelta),\n north,\n east: normalizeLongitude(point.longitude + longitudeDelta),\n };\n}\n\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n\nconst boundsRecord = object(\n {\n [GEO_BOUNDS_KEYS[0]]: geoLatitude,\n [GEO_BOUNDS_KEYS[1]]: geoLongitude,\n [GEO_BOUNDS_KEYS[2]]: geoLatitude,\n [GEO_BOUNDS_KEYS[3]]: geoLongitude,\n },\n { partial: false }\n);\n\nexport function validateGeoBounds(value: unknown): ValidationResult<GeoBounds> {\n const bounds = validateSchema(boundsRecord, value);\n if (bounds.issues) return bounds;\n // An inverted rectangle is no database error: the latitude arm of\n // withinBounds (adapters/shared/geo-point.ts) would silently match nothing.\n if (bounds.value.south > bounds.value.north) {\n return fail(\"GeoBounds south must be less than or equal to north\", [\n \"south\",\n ]);\n }\n return bounds;\n}\n\n/**\n * A ring is its vertices in input order, at least GEO_POLYGON_MIN_RING_POINTS\n * of them: the JSON Schema states that minimum, and closedRing\n * (adapters/shared/geo-point.ts) reads the first vertex of every ring. The\n * count is judged before any vertex, so a short ring reports its length.\n */\nfunction validateRing(value: unknown): ValidationResult<GeoPoint[]> {\n const members = validateArray(value, ok);\n if (members.issues) return members;\n if (members.value.length < GEO_POLYGON_MIN_RING_POINTS) {\n return fail(\n `A GeoPolygon ring needs at least ${GEO_POLYGON_MIN_RING_POINTS} vertices`\n );\n }\n return validateArray(members.value, validateGeoPoint);\n}\n\nconst polygonRecord = object(\n {\n outer: createSchema(\"array\", validateRing),\n holes: optional(\n createSchema(\"array\", (value) => validateArray(value, validateRing))\n ),\n },\n { partial: false }\n);\n\n/*\n * Polygon geometry, judged after the record walker admitted the shape.\n * VibORM reads an edge as the great-circle arc between its vertices, so\n * crossings, touches and containment are judged on the unit sphere, never on\n * straight longitude/latitude lines, and the polygon is the side of its outer\n * ring away from both poles.\n *\n * Refused as having no single meaning on that reading: a ring crossing,\n * touching or retracing itself, a ring of zero area, a hole not strictly\n * inside its outer ring, holes touching or overlapping.\n *\n * DOMAIN CHOICES, each made for the reason given, not a property every valid\n * polygon lacks. A new refusal needs a reason of this kind; \"invalid\n * geometry\" is not one.\n * - Resolution, TOLERANCE (1e-9 degrees): exact tests on float64 vectors need\n * a margin for rounding, one for every ring size. Within it a point is on\n * what it touches: rings closer than it touch and are refused, and an edge\n * shorter than it is a repeated vertex.\n * - Near-antipodal edges, NEAREST_ANTIPODE (0.01 degrees): nearer to\n * antipodal, one float64 step of a written coordinate turns the edge's\n * great circle by more than a third of TOLERANCE, so the coordinates do not\n * fix the edge; it is refused.\n * - Poles: a vertex within TOLERANCE of a pole has no longitude, and a ring\n * winding around a pole or running over both has no side away from both;\n * both are refused. An edge whose longitudes differ by exactly 180 degrees\n * runs over the pole on its vertices' side, and is admitted.\n *\n * A valid polygon is not refused because a database reads it differently:\n * MySQL draws edges on the ellipsoid, PostGIS misreads some rings reaching\n * across all three coordinate planes (docs/content/docs/schema/scalars/\n * point.mdx, \"How each database reads a polygon\", gives the measured\n * differences).\n */\n\ntype Vector = readonly [x: number, y: number, z: number];\n\n/** One ring vertex, its longitude unwrapped past ±180 along the ring. */\ninterface UnwrappedPoint {\n /**\n * The longitude unwrapped: it records how the ring travels (the edges'\n * directions, the area's lunes), never where the vertex lies.\n */\n readonly longitude: number;\n readonly latitude: number;\n /** The longitude as written, where `sweep` places it. */\n readonly written: number;\n /** The vertex on the unit sphere, from its written coordinates. */\n readonly vector: Vector;\n}\n\n/** One ring edge: the great-circle arc from `from` to `to`. */\ninterface Arc {\n readonly from: UnwrappedPoint;\n readonly to: UnwrappedPoint;\n readonly start: Vector;\n readonly end: Vector;\n /** The unit normal of the arc's great circle, start × end. */\n readonly normal: Vector;\n /**\n * The pole the arc runs over, when its longitudes differ by exactly 180\n * degrees: it rises along one meridian and falls along the other.\n */\n readonly pole: Vector | undefined;\n}\n\n/** A ring's arcs; a ring is refused before it could have fewer than two. */\ntype Ring = readonly [Arc, ...Arc[]];\n\nconst RADIANS = Math.PI / 180;\n/**\n * An angle of 1e-9 degrees, about 0.1 mm: a point this near an arc is on it,\n * and an edge this short is a repeated vertex. It is VibORM's resolution, a\n * domain choice (above), at every ring size: a smaller feature reads as a\n * touch or a repeated vertex, so a ring needs no size bound of its own, and a\n * vertex needs no pole clearance. How exactly rings are judged above it is\n * measured in the guard-ownership ledger's D2 addendum.\n */\nconst TOLERANCE = 1e-9 * RADIANS;\n/**\n * The chord between an edge's end and the antipode of its start below which\n * the edge is refused: 0.01 degrees, a domain choice (above). Two antipodal\n * points lie on every great circle through them, and near the antipode the\n * circle an edge takes turns by up to about 3e-12 / d degrees when a written\n * coordinate moves by one float64 step, d degrees from antipodal (measured in\n * the ledger's D2 addendum, \"Near-antipodal edge\"). From 0.01 degrees out the\n * edge's path is fixed to a third of TOLERANCE; nearer, the written\n * coordinates do not decide on which side of it a point lies.\n */\nconst NEAREST_ANTIPODE = 2 * Math.sin(0.005 * RADIANS);\n\nfunction toVector(longitude: number, latitude: number): Vector {\n const cosine = Math.cos(latitude * RADIANS);\n return [\n cosine * Math.cos(longitude * RADIANS),\n cosine * Math.sin(longitude * RADIANS),\n Math.sin(latitude * RADIANS),\n ];\n}\n\nfunction dot(first: Vector, second: Vector): number {\n return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];\n}\n\n/**\n * first × second, taken as (first − second) × (first + second) / 2: the same\n * vector, but the difference of two nearby points is exact, so the normal of\n * a short arc keeps its direction; taken plainly it loses it at 1e-7 degrees\n * (the ledger's D2 addendum, \"Cross products from vertex differences\").\n */\nfunction cross(first: Vector, second: Vector): Vector {\n const dx = first[0] - second[0];\n const dy = first[1] - second[1];\n const dz = first[2] - second[2];\n const sx = first[0] + second[0];\n const sy = first[1] + second[1];\n const sz = first[2] + second[2];\n return [\n (dy * sz - dz * sy) / 2,\n (dz * sx - dx * sz) / 2,\n (dx * sy - dy * sx) / 2,\n ];\n}\n\nfunction unit(vector: Vector): Vector {\n const length = Math.hypot(...vector);\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nfunction chord(first: Vector, second: Vector): number {\n return Math.hypot(\n first[0] - second[0],\n first[1] - second[1],\n first[2] - second[2]\n );\n}\n\nfunction antipode(vector: Vector): Vector {\n return [-vector[0], -vector[1], -vector[2]];\n}\n\n/** What an edge adds to its end's longitude to take the short way round. */\nfunction shortWay(delta: number): number {\n if (delta > 180) return -360;\n if (delta < -180) return 360;\n return 0;\n}\n\n/** One distinct ring vertex, at its index in the ring. */\ninterface Distinct {\n readonly vertex: GeoPoint;\n readonly index: number;\n readonly vector: Vector;\n}\n\n/**\n * The ring's distinct vertices, closed on the first. A vertex within TOLERANCE\n * of a pole is refused: on the pole it has no longitude, and so no meridian\n * for its edges. A repeated consecutive vertex, the caller's closing vertex\n * included, is admitted as the zero-length edge both databases ignore, and\n * dropped here.\n */\nfunction distinctVertices(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Distinct[]> {\n const distinct: Distinct[] = [];\n for (const [index, vertex] of ring.entries()) {\n const vector = toVector(vertex.longitude, vertex.latitude);\n if (Math.hypot(vector[0], vector[1]) <= TOLERANCE) {\n return fail(\"A GeoPolygon ring cannot contain a pole\", [...path, index]);\n }\n const last = distinct.at(-1);\n if (!last || chord(last.vector, vector) > TOLERANCE) {\n distinct.push({ vertex, index, vector });\n }\n }\n const [first] = distinct;\n const last = distinct.at(-1);\n if (first && last && chord(last.vector, first.vector) > TOLERANCE) {\n distinct.push(first);\n }\n return ok(distinct);\n}\n\n/**\n * The ring's arcs, each taking the short way round in longitude. An edge\n * whose longitudes differ by exactly 180 degrees has no short way: it runs\n * over the pole on the side of its endpoints' mean latitude, along one great\n * circle, and goes round whichever way leaves the ring no turn.\n */\nfunction ringArcs(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Ring> {\n const distinct = distinctVertices(ring, path);\n if (distinct.issues) return distinct;\n // The ring's turn in longitude, an edge over a pole taken as written.\n let turn = 0;\n for (const [position, { vertex }] of distinct.value.entries()) {\n const previous = distinct.value[position - 1];\n if (previous) {\n turn += shortWay(vertex.longitude - previous.vertex.longitude);\n }\n }\n const arcs: Arc[] = [];\n let wrap = 0;\n let from: UnwrappedPoint | undefined;\n let overPole: Vector | undefined;\n for (const { vertex, index, vector } of distinct.value) {\n let pole: Vector | undefined;\n if (from) {\n const delta = vertex.longitude - from.written;\n if (Math.abs(delta) === 180) {\n pole = [0, 0, Math.sign(vertex.latitude + from.latitude)];\n if (Math.abs(delta - turn) === 180) wrap -= turn;\n }\n wrap += shortWay(delta);\n }\n const to = {\n longitude: vertex.longitude + wrap,\n latitude: vertex.latitude,\n written: vertex.longitude,\n vector,\n };\n if (from) {\n if (chord(antipode(from.vector), vector) < NEAREST_ANTIPODE) {\n return fail(\n \"A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal\",\n [...path, index]\n );\n }\n // Over both poles the ring has no side away from both, and no way\n // round that leaves it no turn. Over one pole twice it crosses itself\n // there, which the sweep finds.\n if (pole && overPole && pole[2] !== overPole[2]) {\n return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n }\n overPole ??= pole;\n arcs.push({\n from,\n to,\n start: from.vector,\n end: vector,\n normal: unit(cross(from.vector, vector)),\n pole,\n });\n }\n from = to;\n }\n // Longitudes that went once around the globe enclose a pole, and the ring\n // then has no side away from both poles.\n if (wrap !== 0) return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n const [first, ...rest] = arcs;\n // The self-intersection no pair of non-neighbor arcs shows: a ring of at\n // most three arcs on one great circle retraces itself, and a ring of one\n // distinct vertex has no arc at all.\n if (\n !first ||\n (rest.length < 3 &&\n rest.every(({ start }) => Math.abs(side(first, start)) <= TOLERANCE))\n ) {\n return fail(\"A GeoPolygon ring must have non-zero area\", [...path]);\n }\n // Neighbors meet at their shared vertex, which `sweep` excuses, unless\n // one doubles back along the other: such arcs overlap, and the sweep\n // cannot order arcs that overlap.\n let behind = first;\n for (const arc of [...rest, first]) {\n if (onArc(arc.end, behind) || onArc(behind.start, arc)) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", [...path]);\n }\n behind = arc;\n }\n return ok([first, ...rest]);\n}\n\n/** The sine of the point's signed angular distance from the arc's circle. */\nfunction side(arc: Arc, point: Vector): number {\n return dot(arc.normal, point);\n}\n\nfunction onArc(point: Vector, arc: Arc): boolean {\n return (\n Math.abs(side(arc, point)) <= TOLERANCE &&\n dot(cross(arc.start, point), arc.normal) >= -TOLERANCE &&\n dot(cross(point, arc.end), arc.normal) >= -TOLERANCE\n );\n}\n\nfunction opposite(first: number, second: number): boolean {\n return (\n (first > TOLERANCE && second < -TOLERANCE) ||\n (first < -TOLERANCE && second > TOLERANCE)\n );\n}\n\n/**\n * The two arcs cross at one point interior to both: each straddles the\n * other's great circle, and they hold the same one of the two antipodal\n * points where the circles meet. An arc shorter than half a circle holds a\n * point of it when the point lies on the side of the arc's middle, where\n * start + end points; arcs that straddle each other but hold opposite points\n * (a ring reaching across all three coordinate planes has such pairs) are\n * apart.\n */\nfunction crosses(first: Arc, second: Arc): boolean {\n if (\n !(\n opposite(side(first, second.start), side(first, second.end)) &&\n opposite(side(second, first.start), side(second, first.end))\n )\n ) {\n return false;\n }\n const meeting = cross(first.normal, second.normal);\n return (\n dot(meeting, first.start) + dot(meeting, first.end) > 0 ===\n dot(meeting, second.start) + dot(meeting, second.end) > 0\n );\n}\n\nfunction meet(first: Arc, second: Arc): boolean {\n return (\n crosses(first, second) ||\n onArc(first.start, second) ||\n onArc(first.end, second) ||\n onArc(second.start, first) ||\n onArc(second.end, first)\n );\n}\n\n/**\n * One ring of the polygon, and where `sweep` places it among the others:\n * `around` is the innermost ring around it, `inside` whether it lies inside\n * the outer ring, `firstAround` and `firstWithin` the first hole around it\n * and inside it.\n */\ninterface RingNode {\n /** 0 the outer ring, then the holes. */\n readonly index: number;\n /** The ring's index in `holes`, none for the outer ring. */\n readonly hole: number;\n readonly points: GeoPoint[];\n readonly arcs: Ring;\n readonly counterClockwise: boolean;\n around: RingNode | undefined;\n inside: boolean;\n firstAround: number;\n firstWithin: number;\n}\n\n/** An arc of `ring` at `index` along it. */\ninterface Placed {\n readonly arc: Arc;\n readonly ring: RingNode;\n readonly index: number;\n}\n\n/**\n * One stretch of an arc between two meridians, as the sweep orders it, from\n * its west end.\n */\ninterface Stretch {\n readonly placed: Placed;\n readonly west: Vector;\n readonly east: Vector;\n /** The arc's unit normal, turned north. */\n readonly north: Vector;\n /** Whether the arc runs east, so that its normal is `north`. */\n readonly eastward: boolean;\n}\n\n/** An arc along a meridian, which the sweep meets at one longitude. */\ninterface Upright {\n readonly placed: Placed;\n readonly south: Vector;\n readonly north: Vector;\n}\n\ninterface Link {\n previous: Entry | undefined;\n next: Entry | undefined;\n}\n\n/** A stretch in the sweep's south-to-north order, a skip list. */\ninterface Entry {\n readonly stretch: Stretch | undefined;\n readonly links: readonly Link[];\n}\n\nconst LEVELS = 24;\n\nfunction createLinks(height: number): Link[] {\n return Array.from({ length: height }, () => ({\n previous: undefined,\n next: undefined,\n }));\n}\n\n/**\n * Whether `entering` starts south of `resident` on the meridian where it\n * enters the sweep; one starting on the resident is ordered by where it\n * heads. Only neighbors in this order are compared, so the order must only\n * be right between arcs that do not meet.\n */\nfunction below(entering: Stretch, resident: Stretch): boolean {\n const height = dot(resident.north, entering.west);\n if (Math.abs(height) > TOLERANCE) return height < 0;\n return dot(resident.north, entering.east) < 0;\n}\n\n/** The last entry south of `point` on the sweep's meridian, or the head. */\nfunction southOf(head: Entry, point: Vector, level: number): Entry {\n let cursor = head;\n for (let at = level; at >= 0; at -= 1) {\n let next = cursor.links[at]?.next;\n while (next?.stretch && dot(next.stretch.north, point) > TOLERANCE) {\n cursor = next;\n next = cursor.links[at]?.next;\n }\n }\n return cursor;\n}\n\nfunction enter(head: Entry, stretch: Stretch, height: number): Entry {\n const entry: Entry = { stretch, links: createLinks(height) };\n let cursor = head;\n for (let level = LEVELS - 1; level >= 0; level -= 1) {\n let next = cursor.links[level]?.next;\n while (next?.stretch && !below(stretch, next.stretch)) {\n cursor = next;\n next = cursor.links[level]?.next;\n }\n const link = entry.links[level];\n const before = cursor.links[level];\n if (link && before) {\n link.previous = cursor;\n link.next = before.next;\n const after = before.next?.links[level];\n if (after) after.previous = entry;\n before.next = entry;\n }\n }\n return entry;\n}\n\nfunction leave(entry: Entry): void {\n for (const [level, { previous, next }] of entry.links.entries()) {\n const before = previous?.links[level];\n if (before) before.next = next;\n const after = next?.links[level];\n if (after) after.previous = previous;\n }\n}\n\n/** The antimeridian on the equator. */\nconst ANTIMERIDIAN = toVector(180, 0);\n\n/** The point where the arc crosses the antimeridian. */\nfunction atAntimeridian(arc: Arc): Vector {\n const meeting = unit(\n cross(arc.normal, [-ANTIMERIDIAN[1], ANTIMERIDIAN[0], 0])\n );\n return dot(meeting, ANTIMERIDIAN) < 0 ? antipode(meeting) : meeting;\n}\n\n/**\n * At one longitude the arcs over a pole leave first, then the stretches\n * starting there enter, then the arcs along the meridian are walked, then the\n * stretches ending there leave.\n */\ntype Event =\n | { readonly longitude: number; readonly rank: 0 | 3; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 1; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 2; readonly upright: Upright };\n\ninterface Slot {\n readonly stretch: Stretch;\n entry: Entry | undefined;\n}\n\n/**\n * The arc's sweep events at its written longitudes, west to east, ±180 read\n * as -180 so that arcs meeting on the antimeridian are in the sweep\n * together: one for an arc along a meridian, else an entry and an exit per\n * stretch, two stretches when the arc crosses the antimeridian, split there.\n */\nfunction arcEvents(placed: Placed): Event[] {\n const { from, to, normal, pole } = placed.arc;\n const first = from.written === 180 ? -180 : from.written;\n const second = to.written === 180 ? -180 : to.written;\n if (first === second) {\n const [south, north] =\n from.latitude < to.latitude ? [from, to] : [to, from];\n const upright = { placed, south: south.vector, north: north.vector };\n return [{ longitude: first, rank: 2, upright }];\n }\n const eastward = from.longitude < to.longitude;\n const [west, east] = eastward ? [from, to] : [to, from];\n const north: Vector = eastward\n ? normal\n : [-normal[0], -normal[1], -normal[2]];\n const [low, high] = eastward ? [first, second] : [second, first];\n if (pole) return polarEvents(placed, pole, north, eastward, low, high);\n const span = (start: number, end: number, point: Vector): Event[] => {\n const slot = {\n stretch: { placed, west: point, east: east.vector, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 3, slot },\n ];\n };\n return low < high\n ? span(low, high, west.vector)\n : [\n ...span(low, 180, west.vector),\n ...span(-180, high, atAntimeridian(placed.arc)),\n ];\n}\n\n/**\n * The sweep events of an arc over a pole: an arc along each of its meridians,\n * from its vertex to the pole, and between them a stretch at the pole, beyond\n * every other arc crossing those longitudes. The stretch keeps the arc's\n * circle, which has every point of the meridians between on its far side\n * from the pole. It leaves before the stretches starting on the arc's last\n * meridian enter, since the arc runs along that meridian there, which its\n * walk there covers.\n */\nfunction polarEvents(\n placed: Placed,\n pole: Vector,\n north: Vector,\n eastward: boolean,\n low: number,\n high: number\n): Event[] {\n const walks = [placed.arc.from, placed.arc.to].map(\n ({ written, vector }): Event => ({\n longitude: written === 180 ? -180 : written,\n rank: 2,\n upright: {\n placed,\n south: pole[2] > 0 ? vector : pole,\n north: pole[2] > 0 ? pole : vector,\n },\n })\n );\n const across = (start: number, end: number): Event[] => {\n const slot = {\n stretch: { placed, west: pole, east: pole, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 0, slot },\n ];\n };\n if (low < high) return [...walks, ...across(low, high)];\n return [\n ...walks,\n ...across(low, 180),\n ...(high > -180 ? across(-180, high) : []),\n ];\n}\n\n/**\n * The point's latitude, in radians, which orders points on one meridian. Its\n * z coordinate alone does not: z rounds to ±1 within about 6e-7 degrees of a\n * pole, where rings arriving together would tie.\n */\nfunction latitude(point: Vector): number {\n return Math.atan2(point[2], Math.hypot(point[0], point[1]));\n}\n\n/**\n * A ring on the meridian where the sweep first meets it, and the arc of\n * another ring first north of it there, if any.\n */\ninterface Placement {\n readonly ring: RingNode;\n readonly north: Stretch | undefined;\n}\n\ntype Swept =\n | { readonly meeting: readonly [Placed, Placed] }\n | { readonly meeting?: undefined; readonly placements: Placement[] };\n\n/**\n * The first two arcs found meeting that `apart` does not excuse, by a sweep\n * from the antimeridian eastward that keeps the arcs it crosses in\n * south-to-north order and compares each only with its neighbors in it\n * (Shamos and Hoey): two arcs that meet are neighbors just before the\n * westernmost meeting, so admission takes expected n log n time in the arc\n * count however the arcs lie. At each longitude the arcs starting there enter\n * first; then each arc along that meridian is compared with the arcs crossing\n * its span, found by position; then the arcs ending there leave. Two arcs\n * along one meridian need no comparison of their own: where they meet, one\n * ends on the other, and the arc continuing its ring from that end crosses\n * the meridian there (a ring's arcs along one meridian that continue each\n * other end where the last one does, and a ring doubling back along a\n * meridian is refused in `ringArcs`), so the walk along the other one meets\n * it. An arc over a pole is walked along both its meridians, with a stretch\n * at the pole between them (`polarEvents`): two arcs over one pole meet\n * there, where either their stretches are neighbors at the pole or, when\n * their longitudes only touch, one's walk finds the other's stretch.\n *\n * Failing a meeting, where each ring was first met: once the arcs starting\n * on that meridian have entered, the arc north of the ring's northernmost\n * point there, skipping the ring's own arcs through that point. The rings\n * met on one meridian are listed north to south, so every ring is listed\n * after the ring of the arc north of it.\n */\nfunction sweep(\n arcs: readonly Placed[],\n apart: (first: Placed, second: Placed) => boolean\n): Swept {\n const events = arcs.flatMap(arcEvents);\n events.sort(\n (left, right) => left.longitude - right.longitude || left.rank - right.rank\n );\n const head: Entry = { stretch: undefined, links: createLinks(LEVELS) };\n const meeting = (\n first: Placed | undefined,\n second: Placed | undefined\n ): readonly [Placed, Placed] | undefined => {\n if (!(first && second)) return;\n if (apart(first, second) || !meet(first.arc, second.arc)) return;\n return [first, second];\n };\n const placements: Placement[] = [];\n // Each ring met for the first time on the sweep's meridian, with its\n // northernmost entry there so far.\n const arrivals = new Map<RingNode, { entry: Entry; west: Vector }>();\n const placeArrivals = (): void => {\n const arrived = Array.from(arrivals, ([ring, { entry, west }]) => {\n let next = entry.links[0]?.next;\n while (next?.stretch?.placed.ring === ring) next = next.links[0]?.next;\n return { ring, height: latitude(west), north: next?.stretch };\n });\n arrived.sort((left, right) => right.height - left.height);\n // One push per ring: a spread would pass every ring arriving on this\n // meridian as a call argument, past the engine's argument limit.\n for (const { ring, north } of arrived) placements.push({ ring, north });\n arrivals.clear();\n };\n const met = new Set<RingNode>();\n for (const [index, event] of events.entries()) {\n if (event.rank === 1) {\n // A skip list's heights are coin flips the input cannot know: heights\n // a polygon could predict let it keep its long-lived arcs low and make\n // every search walk them one by one. The verdict does not depend on\n // them: arcs that meet are neighbors before they meet at any height.\n const height = 1 + Math.floor(-Math.log2(1 - Math.random()));\n const entry = enter(head, event.slot.stretch, Math.min(LEVELS, height));\n event.slot.entry = entry;\n const [link] = entry.links;\n const found =\n meeting(link?.previous?.stretch?.placed, entry.stretch?.placed) ??\n meeting(entry.stretch?.placed, link?.next?.stretch?.placed);\n if (found) return { meeting: found };\n const { placed, west } = event.slot.stretch;\n const top = arrivals.get(placed.ring);\n if (\n !met.has(placed.ring) ||\n (top && latitude(west) > latitude(top.west))\n ) {\n met.add(placed.ring);\n arrivals.set(placed.ring, { entry, west });\n }\n const next = events[index + 1];\n if (next?.rank !== 1 || next.longitude !== event.longitude) {\n placeArrivals();\n }\n } else if (event.rank === 2) {\n const { upright } = event;\n // Every arc crossing the meridian within the span meets this one, so\n // the walk stops at the first not excused, or past the north end.\n let entry: Entry | undefined = southOf(head, upright.south, LEVELS - 1);\n entry = entry.stretch ? entry : entry.links[0]?.next;\n while (entry?.stretch) {\n const found = meeting(upright.placed, entry.stretch.placed);\n if (found) return { meeting: found };\n if (dot(entry.stretch.north, upright.north) < -TOLERANCE) break;\n entry = entry.links[0]?.next;\n }\n } else if (event.slot.entry) {\n const [link] = event.slot.entry.links;\n leave(event.slot.entry);\n const found = meeting(\n link?.previous?.stretch?.placed,\n link?.next?.stretch?.placed\n );\n if (found) return { meeting: found };\n }\n }\n return { placements };\n}\n\n/**\n * The ring's signed area in steradians, positive when counterclockwise: the\n * sum of the triangles each arc makes with the north pole (Van Oosterom and\n * Strackee), taken through the south pole's triangle and the lune between the\n * arc's meridians when the arc lies nearer the south pole, where the north\n * pole's triangle loses its precision. The lunes' longitudes telescope, so\n * each run of such arcs adds the longitude from its start to its end: a ring\n * near the south pole is one run, and its lunes add exactly nothing, where\n * summed arc by arc their rounding would outweigh its area. No admitted ring\n * has a pole inside it (`wrap` in `ringArcs`), so this is the area on the\n * ring's pole-free side, and its sign says on which side of its arcs that\n * area lies.\n */\nfunction signedArea(ring: Ring): number {\n let sum = 0;\n let lune = 0;\n let run: number | undefined;\n let end = 0;\n for (const arc of ring) {\n const turn = cross(arc.start, arc.end)[2];\n const along = 1 + dot(arc.start, arc.end);\n const lift = arc.start[2] + arc.end[2];\n if (lift >= 0) {\n sum += 2 * Math.atan2(turn, along + lift);\n if (run !== undefined) lune += arc.from.longitude - run;\n run = undefined;\n } else {\n sum += 2 * Math.atan2(-turn, along - lift);\n run ??= arc.from.longitude;\n }\n end = arc.to.longitude;\n }\n if (run !== undefined) lune += end - run;\n return sum + 2 * lune * RADIANS;\n}\n\n/*\n * A hole must lie strictly inside its outer ring, and holes must neither touch\n * nor overlap: a hole reaching outside its outer ring, or a point in two\n * holes, has no single reading (the ledger's D2 addendum tabulates what each\n * database answered). A touch is refused with them: a hole written touching a\n * straight parallel edge crosses that edge's arc.\n */\n\n/**\n * Kept output normalization, not a refusal: the GeoJSON that withinPolygon\n * binds (adapters/databases/{postgres,mysql}) always carries a counterclockwise\n * outer ring and clockwise holes, because neither database's reading of ring\n * orientation is proven portable (v1-public-api-geopoint-plan.md).\n */\nfunction wound(\n ring: GeoPoint[],\n counterClockwise: boolean,\n wanted: boolean\n): GeoPoint[] {\n return counterClockwise === wanted ? ring : ring.reverse();\n}\n\nfunction ringPath(ring: number): PropertyKey[] {\n return ring === 0 ? [\"outer\"] : [\"holes\", ring - 1];\n}\n\nfunction ringNode(points: GeoPoint[], arcs: Ring, index: number): RingNode {\n return {\n index,\n hole: index === 0 ? Number.POSITIVE_INFINITY : index - 1,\n points,\n arcs,\n counterClockwise: signedArea(arcs) > 0,\n around: undefined,\n inside: false,\n firstAround: Number.POSITIVE_INFINITY,\n firstWithin: Number.POSITIVE_INFINITY,\n };\n}\n\n/**\n * The walker admits the polygon's shape (exact keys, finite in-range\n * vertices, at least three per ring); the geometry then refuses the polygons\n * with no single meaning or outside the domain choices (above): each ring\n * alone, then the rings together.\n */\nexport function validateGeoPolygon(\n value: unknown\n): ValidationResult<GeoPolygon> {\n const polygon = validateSchema(polygonRecord, value);\n if (polygon.issues) return polygon;\n const outer = ringArcs(polygon.value.outer, [\"outer\"]);\n if (outer.issues) return outer;\n const shell = ringNode(polygon.value.outer, outer.value, 0);\n const holes: RingNode[] = [];\n for (const [index, points] of (polygon.value.holes ?? []).entries()) {\n const hole = ringArcs(points, [\"holes\", index]);\n if (hole.issues) return hole;\n holes.push(ringNode(points, hole.value, index + 1));\n }\n const placed = [shell, ...holes].flatMap((ring) =>\n ring.arcs.map((arc, index) => ({ arc, ring, index }))\n );\n // Neighbors along a ring meet at their shared vertex; an arc over a pole\n // meets itself where its walks find its stretch.\n const swept = sweep(\n placed,\n (first, second) =>\n first.ring === second.ring &&\n [0, 1, first.ring.arcs.length - 1].includes(\n Math.abs(first.index - second.index)\n )\n );\n if (swept.meeting) {\n const [first, second] = swept.meeting;\n const later = ringPath(Math.max(first.ring.index, second.ring.index));\n // A ring meeting itself has no single reading (the ledger's D2 table:\n // the bowtie and the ring past a whole turn over itself).\n if (first.ring === second.ring) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", later);\n }\n return Math.min(first.ring.index, second.ring.index) === 0\n ? fail(\"A GeoPolygon hole must be strictly inside its outer ring\", later)\n : fail(\"GeoPolygon holes cannot touch or overlap\", later);\n }\n // No two rings meet, so where the sweep first met a ring places all of it:\n // inside the ring of the arc north of it when that arc has its ring's\n // interior to the south (a counterclockwise ring's interior is on the left\n // of its arcs), else beside that ring, in the ring around it, which the\n // sweep placed first.\n for (const { ring, north } of swept.placements) {\n const other = north?.placed.ring;\n const around =\n other === undefined || other.counterClockwise !== north?.eastward\n ? other\n : other.around;\n ring.around = around;\n ring.inside = around !== undefined && (around.index === 0 || around.inside);\n ring.firstAround = around\n ? Math.min(around.hole, around.firstAround)\n : Number.POSITIVE_INFINITY;\n }\n // Reversed in place, the list's last use: every ring now comes before the\n // ring around it, which collects the first hole within it.\n for (const { ring } of swept.placements.reverse()) {\n const { around } = ring;\n if (around) {\n around.firstWithin = Math.min(\n around.firstWithin,\n ring.hole,\n ring.firstWithin\n );\n }\n }\n for (const { hole, inside, firstAround, firstWithin } of holes) {\n if (!inside) {\n return fail(\"A GeoPolygon hole must be strictly inside its outer ring\", [\n \"holes\",\n hole,\n ]);\n }\n if (Math.min(firstAround, firstWithin) < hole) {\n return fail(\"GeoPolygon holes cannot touch or overlap\", [\"holes\", hole]);\n }\n }\n const wide = wound(shell.points, shell.counterClockwise, true);\n const cut = holes.map(({ points, counterClockwise }) =>\n wound(points, counterClockwise, false)\n );\n // An empty and an absent holes list emit the same GeoJSON; one spelling\n // keeps them one validated argument, and so one cache key.\n return ok(cut.length > 0 ? { outer: wide, holes: cut } : { outer: wide });\n}\n\nconst areaRecord = object({\n bounds: createSchema(\"object\", validateGeoBounds),\n polygon: createSchema(\"object\", validateGeoPolygon),\n});\n\nexport function validateGeoArea(value: unknown): ValidationResult<GeoArea> {\n const area = validateSchema(areaRecord, value);\n if (area.issues) return area;\n const { bounds, polygon } = area.value;\n // Exactly one variant: buildGeoPointWithin (query-engine/builders/\n // geo-point-builder.ts) branches on `\"bounds\" in area`, so a second variant\n // would be dropped silently and a missing one would reach geoPolygonJson as\n // undefined and throw a TypeError instead of a database error.\n if (bounds && !polygon) return ok({ bounds });\n if (polygon && !bounds) return ok({ polygon });\n return fail(\"Expected GeoArea with exactly one of bounds or polygon\");\n}\n\nexport function geoAreaSchema(): VibSchema<GeoArea, GeoArea> {\n return createSchema(\"geo_area\", validateGeoArea);\n}\n"],"mappings":"2KAsBA,MAAM,EAAwB,MAGjB,EAAgC,UAO7C,SAAgB,qBACd,EACA,EACW,CACX,GAAI,GAAU,EACZ,MAAO,CACL,MAAO,EAAM,SACb,KAAM,EAAM,UACZ,MAAO,EAAM,SACb,KAAM,EAAM,UACb,CAGH,IAAM,EAAgB,EAAS,EAC/B,GAAI,GAAiB,KAAK,GACxB,MAAO,CAAE,MAAO,IAAK,KAAM,KAAM,MAAO,GAAI,KAAM,IAAK,CAGzD,IAAM,EAAmB,EAAM,SAAW,KAAK,GAAM,IAC/C,EAAiB,EAAgB,IAAO,KAAK,GAC7C,EAAQ,KAAK,IACjB,IACA,EAAM,SAAW,EAAgB,EAClC,CACK,EAAQ,KAAK,IACjB,GACA,EAAM,SAAW,EAAgB,EAClC,CACD,GAAI,IAAU,KAAO,IAAU,GAC7B,MAAO,CAAE,QAAO,KAAM,KAAM,QAAO,KAAM,IAAK,CAGhD,IAAM,EACH,KAAK,KACJ,KAAK,IAAI,EAAG,KAAK,IAAI,EAAc,CAAG,KAAK,IAAI,EAAgB,CAAC,CACjE,CACC,IACA,KAAK,GACP,EACF,MAAO,CACL,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC1D,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC3D,CAGH,SAAS,mBAAmB,EAA2B,CACrD,QAAW,EAAY,KAAO,IAAO,KAAO,IAAO,IAGrD,MAAM,EAAe,EACnB,EACG,EA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,QAAS,EAAa,SAAU,mBAAmB,CACpD,CAAC,CAEF,SAAgB,gBAAgB,EAA2C,CACzE,IAAM,EAAO,EAAe,EAAY,EAAM,CAC9C,GAAI,EAAK,OAAQ,OAAO,EACxB,GAAM,CAAE,SAAQ,WAAY,EAAK,MAOjC,OAFI,GAAU,CAAC,EAAgB,EAAG,CAAE,SAAQ,CAAC,CACzC,GAAW,CAAC,EAAe,EAAG,CAAE,UAAS,CAAC,CACvC,EAAK,yDAAyD,CAGvE,SAAgB,eAA6C,CAC3D,OAAO,EAAa,WAAY,gBAAgB"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r,s as i,t as a}from"./value-guards-CK9guf2Z.mjs";import{S as o,b as s,h as c}from"./base-D3m1S7Uc.mjs";import{r as l,t as u}from"./validation-BamBwne9.mjs";const d=/^[a-zA-Z_][a-zA-Z0-9_]*$/,f=new Set(Object.getOwnPropertyNames(Object.prototype));function isValidSchemaIdentifier(e){return typeof e==`string`&&e.length<=63&&d.test(e)&&!f.has(e)}const p={postgresql:63,mysql:64},m={postgresql:`PostgreSQL`,mysql:`MySQL`},h=new Set([`information_schema`,`mysql`,`performance_schema`,`sys`,`ndbinfo`]);function refuseNamespace(e,t){throw new l(`The "namespace" option ${t} (${m[e]}).`)}function normalizeNamespace(e,t){typeof e!=`string`&&refuseNamespace(t,`must be a string; received type "${typeof e}"`);let n=p[t];return e.length>n&&refuseNamespace(t,`must be at most ${n} characters; received ${e.length}`),d.test(e)||refuseNamespace(t,`must match [A-Za-z_][A-Za-z0-9_]*; received ${JSON.stringify(e)}`),f.has(e)&&refuseNamespace(t,`must not be an Object.prototype property name; received ${JSON.stringify(e)}`),t===`postgresql`?((e===`information_schema`||e.startsWith(`pg_`))&&refuseNamespace(t,`must not be a system schema; "information_schema" and the "pg_" prefix are reserved`),e):(h.has(e.toLowerCase())&&refuseNamespace(t,`must not be a system database; received ${JSON.stringify(e)}`),e)}const g=Symbol(`viborm.validation.parseFailureCause`);function discardAsyncValidationResult(e){Promise.resolve(e).catch(()=>void 0)}function validationFailureFromThrown(e){let t=s(e),n={issues:[{message:`Schema validation failed unexpectedly`}]};return Object.defineProperty(n,g,{value:c(t)}),n}function readValidationFailureCause(e){let t=Reflect.get(e,g);return o(t)?t:void 0}const _=/^(?:[0-9a-fA-F]{2})*$/,v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,y=/^base64:type\d+:(.*)$/;function hexBytes(e){if(!_.test(e))return{unsupported:`hex string`};let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return{bytes:t}}function base64Bytes(e){if(!v.test(e))return{unsupported:`base64 string`};let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(e);return{bytes:n}}function normalizeBinaryValue(e){if(e instanceof ArrayBuffer)return{bytes:new Uint8Array(e.slice(0))};if(ArrayBuffer.isView(e)){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return{bytes:new Uint8Array(t)}}if(Array.isArray(e)){for(let t of e)if(!Number.isInteger(t)||t<0||t>255)return{unsupported:`byte array`};return{bytes:Uint8Array.from(e)}}if(typeof e==`string`){if(e.startsWith(`\\x`))return hexBytes(e.slice(2));if(e.startsWith(`base64:type`)){if(!y.exec(e))return{unsupported:`base64 string`};let t=e.indexOf(`:`,11)+1;return base64Bytes(e.slice(t))}return hexBytes(e)}return{unsupported:typeof e}}const b=16,x=10,S=10,C=16,w=0xffffffffffff,T=14e8,E=T+4294967295,D=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,O=D+`0123456789abcdefghjkmnpqrstvwxyz`,k=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,ee=21,A=/^[a-z][0-9a-z]{23}$/,j=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,M=2n**160n,N=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,P=62n;function refuseId(e,t,n){throw new u({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}])}const te=65536;function randomBytes(e,t){let n=globalThis.crypto;return typeof n?.getRandomValues!=`function`&&refuseId(`s.string().${t}`,`generate`,`Cannot generate a ${t} value: this runtime exposes no \`crypto.getRandomValues\`. VibORM never falls back to \`Math.random()\` for an identifier`),n.getRandomValues(new Uint8Array(e))}function hasIdPrefix(e){return e!==void 0&&e!==``}function applyIdPrefix(e,t){return hasIdPrefix(e)?`${e}-${t}`:t}function writeUintBE(e,t,n,r){let i=r;for(let r=n-1;r>=0;r--)e.setUint8(t+r,i%256),i=Math.floor(i/256)}function assertMillisecondTimestamp(e,t){(!Number.isInteger(t)||t<0||t>w)&&refuseId(`s.string().${e}`,`generate`,`A ${e} timestamp must be a whole number of milliseconds between 0 and ${w}; received ${t}`)}function uuidV4Bytes(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.setUint8(6,t.getUint8(6)&15|64),t.setUint8(8,t.getUint8(8)&63|128),e}function uuidV7Bytes(e,t){assertMillisecondTimestamp(`uuidv7`,e);let n=new Uint8Array(16);n.set(t,6);let r=new DataView(n.buffer);return writeUintBE(r,0,6,e),r.setUint8(6,r.getUint8(6)&15|112),r.setUint8(8,r.getUint8(8)&63|128),n}function bytesToUuid(e){e.length!==16&&refuseId(`s.string().uuid`,`generate`,`A UUID is exactly 16 bytes; received ${e.length}`);let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function uuidToBytes(e){if(!N.test(e))return;let t=e.replaceAll(`-`,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=Number.parseInt(t.slice(e*2,e*2+2),16);return n}function ulidBytes(e,t){assertMillisecondTimestamp(`ulid`,e);let n=new Uint8Array(16);return n.set(t,6),writeUintBE(new DataView(n.buffer),0,6,e),n}function bytesToUlid(e){e.length!==16&&refuseId(`s.string().ulid`,`generate`,`A ULID is exactly 16 bytes; received ${e.length}`);let t=``,n=0,r=2;for(let i of e){for(n=n<<8|i,r+=8;r>=5;)r-=5,t+=D.charAt(n>>>r&31);n&=(1<<r)-1}return t}function ulidToBytes(e){if(e.length!==26)return;let t=O.indexOf(e.charAt(0));if(t<0)return;let n=t%32;if(n>7)return;let r=new Uint8Array(16),i=n,a=3,o=0;for(let t of e.slice(1)){let e=O.indexOf(t);if(e<0)return;i=i<<5|e%32,a+=5,a>=8&&(a-=8,r[o]=i>>>a&255,o++,i&=(1<<a)-1)}return r}function ksuidBytes(e,t){(!Number.isInteger(e)||e<T||e>E)&&refuseId(`s.string().ksuid`,`generate`,`A KSUID timestamp must be a whole Unix second between ${T} and ${E}; received ${e}`);let n=new Uint8Array(20);return n.set(t,4),writeUintBE(new DataView(n.buffer),0,4,e-T),n}function bytesToKsuid(e){e.length!==20&&refuseId(`s.string().ksuid`,`generate`,`A KSUID is exactly 20 bytes; received ${e.length}`);let t=0n;for(let n of e)t=t*256n+BigInt(n);return ksuidText(t)}function ksuidText(e){let t=[],n=e;for(let e=0;e<27;e++)t.push(j.charAt(Number(n%P))),n/=P;return t.reverse().join(``)}const F=ksuidText(M-1n);function ksuidToBytes(e){if(e.length!==27)return;let t=0n;for(let n of e){let e=j.indexOf(n);if(e<0)return;t=t*P+BigInt(e)}if(t>=M)return;let n=new Uint8Array(20);for(let e=19;e>=0;e--)n[e]=Number(t&255n),t>>=8n;return n}const ne=new Set([`uuid`,`uuidv7`,`ulid`,`ksuid`,`nanoid`,`cuid`]);function isIdFormat(e){return e!==void 0&&ne.has(e)}function isCompactIdFormat(e){return e===`uuid`||e===`uuidv7`||e===`ulid`||e===`ksuid`}function sameIdDomain(e,t){return e===void 0||t===void 0?e===t:e.format===t.format&&idPrefixOf(e)===idPrefixOf(t)&&nanoidLengthOf(e)===nanoidLengthOf(t)}function idPrefixOf(e){return hasIdPrefix(e.prefix)?e.prefix:void 0}function nanoidLengthOf(e){if(e.format===`nanoid`)return e.length??21}function describeIdDomain(e){let t=idPrefixOf(e),n=e.format===`nanoid`?` of length ${nanoidLengthOf(e)}`:``;return t===void 0?`a ${e.format} value${n}`:`a ${e.format} value${n} prefixed '${t}-'`}const re=/[$()*+./?[\\\]^{|}]/g;function idDomainPattern(e){let t=idPrefixOf(e);return`^${t===void 0?``:`${t.replace(re,`\\$&`)}-`}${payloadPattern(e)}$`}function payloadPattern(e){switch(e.format){case`uuid`:case`uuidv7`:return N.source.slice(1,-1);case`ulid`:return`[0-7][${D}0123456789abcdefghjkmnpqrstvwxyz]{25}`;case`ksuid`:return base62NotAbove(F);case`nanoid`:return`[${k.replace(`-`,`\\-`)}]{${nanoidLengthOf(e)}}`;default:return A.source.slice(1,-1)}}function base62NotAbove(e){let t=[e];for(let n=0;n<e.length;n++){let r=base62Below(e[n]);r!==``&&t.push(`${e.slice(0,n)}[${r}][0-9A-Za-z]{${e.length-n-1}}`)}return`(?:${t.join(`|`)})`}const ie=/[0-9]{3,}|[A-Z]{3,}|[a-z]{3,}/g;function base62Below(e){return j.slice(0,j.indexOf(e)).replace(ie,e=>`${e[0]}-${e.at(-1)}`)}function payloadOf(e,t){let n=idPrefixOf(t);if(n===void 0)return e;let r=`${n}-`;return e.startsWith(r)?e.slice(r.length):void 0}function isNanoidPayload(e,t){if(e.length!==t)return!1;for(let t of e)if(!k.includes(t))return!1;return!0}function canonicalizePayload(e,t){switch(t.format){case`uuid`:case`uuidv7`:{let t=uuidToBytes(e);return t===void 0?void 0:bytesToUuid(t)}case`ulid`:{let t=ulidToBytes(e);return t===void 0?void 0:bytesToUlid(t)}case`ksuid`:return ksuidToBytes(e)===void 0?void 0:e;case`nanoid`:return isNanoidPayload(e,nanoidLengthOf(t))?e:void 0;default:return A.test(e)?e:void 0}}function canonicalizeId(e,t){if(typeof e!=`string`)return;let n=payloadOf(e,t);if(n===void 0)return;let r=canonicalizePayload(n,t);return r===void 0?void 0:applyIdPrefix(idPrefixOf(t),r)}function payloadBytes(e,t){switch(t){case`uuid`:case`uuidv7`:return uuidToBytes(e);case`ulid`:return ulidToBytes(e);case`ksuid`:return ksuidToBytes(e);default:return}}function idByteLength(e){switch(e){case`uuid`:case`uuidv7`:return 16;case`ulid`:return 16;case`ksuid`:return 20;default:return}}function textOfBytes(e,t){if(e.length===idByteLength(t))return t===`ulid`?bytesToUlid(e):t===`ksuid`?bytesToKsuid(e):bytesToUuid(e)}function encodePhysicalId(e,t,n){let r=canonicalizeId(e,t);if(r===void 0)return;if(n===`text`)return r;let i=payloadOf(r,t);return n===`uuid`?i:payloadBytes(i,t.format)}function decodePhysicalId(e,t,n){if(n===`text`)return canonicalizeId(e,t);if(n===`uuid`){if(typeof e!=`string`)return;let n=uuidToBytes(e);return n===void 0?void 0:applyIdPrefix(idPrefixOf(t),bytesToUuid(n))}let r=normalizeBinaryValue(e);if(r.bytes===void 0)return;let i=textOfBytes(r.bytes,t.format);return i===void 0?void 0:applyIdPrefix(idPrefixOf(t),i)}function fail(e,t){return{issues:[t&&t.length>0?{message:e,path:t}:{message:e}]}}let I=!1;const collectingAllIssues=()=>I;function reportingAllIssues(e,t){let n=I;I=e;try{return t()}finally{I=n}}function issuesUnder(e,t){return(I?t:t.slice(0,1)).map(t=>({message:t.message,path:t.path?[e,...t.path]:[e]}))}function ok(e){return{value:e}}function standardSchemaFailure(e){return{issues:e.map(e=>e.path===void 0?{message:e.message}:{message:e.message,path:e.path.map(e=>typeof e==`object`?e.key:e)})}}const L=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array`})])}),R=Object.freeze({value:null}),z=Object.freeze({value:void 0});function validateArray(e,t){try{if(!Array.isArray(e))return L}catch{return fail(`Could not inspect array`)}let n;try{n=e.length}catch{return fail(`Could not read array length`)}if(!Number.isInteger(n)||n<0)return L;if(n===0)return ok([]);let r=Array(n),i;for(let a=0;a<n;a++){let n;try{n=e[a]}catch{return fail(`Could not read array member`,[a])}let o=t(n);if(o.issues){let e=issuesUnder(a,o.issues);if(!I)return{issues:e};(i??=[]).push(...e);continue}r[a]=o.value}return i?{issues:i}:ok(r)}function createOptionalWithDefault(e,t){return n=>{if(n!==void 0)return e(n);let r;try{r=t()}catch(e){return fail(`Default failed: ${describeDefaultFailure(e)}`)}return e(r)}}function describeDefaultFailure(e){try{return String(e instanceof Error?e.message:e)}catch{return`unrenderable thrown value`}}function thenValidate(e,t){return n=>{let r=e(n);return r.issues?r:t(r.value)}}function idDomainAdmission(e){let t=`Expected ${describeIdDomain(e)}`;return n=>{let r=canonicalizeId(n,e);return r===void 0?fail(t):ok(r)}}function buildValidator(e,t,r){if(!t)return e;let{nullable:i,optional:a,array:o,default:s,transform:c,schema:l,disallowZero:u,idDomain:d}=t,f=s!==void 0,p=c!==void 0,validate=e;u&&(validate=refusingZero(validate));let m=d===void 0?void 0:idDomainAdmission(d);if(m&&(validate=thenValidate(validate,m)),l!==void 0&&(validate=withCustomSchema(validate,l,m)),p&&(validate=withTransform(validate,c)),r===`json`&&(p||l!==void 0)&&(validate=thenValidate(validate,e)),o){let e=validate;validate=t=>validateArray(t,e)}if(i){let e=validate;validate=t=>t===null?R:e(t)}if(f){let e=n(s)?s:()=>s;return createOptionalWithDefault(validate,e)}if(a){let e=validate;validate=t=>t===void 0?z:e(t)}return validate}function refusingZero(e){return t=>{let n=e(t);if(n.issues)return n;let r=n.value;return r===0||r===0n?fail(`Explicit zero is not portable for an auto-increment field`):n}}function withCustomSchema(e,t,n){let r=t[`~standard`].validate,validate=t=>{let n=e(t);if(n.issues)return n;let i=r(n.value);return`then`in i?(discardAsyncValidationResult(i),fail(`Async schemas are not supported`)):i.issues?standardSchemaFailure(i.issues):ok(i.value)};return n?thenValidate(validate,n):validate}function withTransform(e,t){return n=>{let r=e(n);if(r.issues)return r;try{return ok(t(r.value))}catch(e){return fail(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}}}function buildSchema(e,t,n,r){let i=n?.optional===!0||n?.default!==void 0;return Object.assign(createSchema(e,buildValidator(t,n,e)),{options:n,acceptsUndefined:i,...r})}function createSchema(e,t){let n={type:e,"~standard":{version:1,vendor:`viborm`,validate:t,get jsonSchema(){let e=createJsonSchemaConverter(n);return Object.defineProperty(this,`jsonSchema`,{value:e,writable:!1,enumerable:!0}),e}}};return Object.defineProperty(n,` vibInferred`,{value:void 0,enumerable:!1}),n}function validateSchema(e,t){let n=e[`~standard`].validate(t);return`then`in n?(discardAsyncValidationResult(n),fail(`Async schemas are not supported`)):n.issues?standardSchemaFailure(n.issues):ok(n.value)}const ae=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected bigint or an integer string`})])}),B=`^[+-]?\\d+$`,oe=new RegExp(B);function validateBigInt(e){return a(e)?ok(e):typeof e==`string`&&oe.test(e)?ok(BigInt(e)):ae}function bigint(e){return buildSchema(`bigint`,validateBigInt,e)}const V=[`longitude`,`latitude`],H=-180,se=180,ce=-90,le=90,U=[`south`,`west`,`north`,`east`],ue=3,de=[`draft-07`,`draft-2020-12`,`openapi-3.0`];function createContext(e,t,n=`input`){return{definitions:{},referenceMap:new Map,activeFrames:new Map,rootSchema:t,refCount:0,target:e,direction:n}}const fe=new Set([`array`,`nullable`,`optional`,`lazyRef`]);function decimalDomainPattern({precision:e,scale:t}){let n=e-t;return`^[+-]?(?:${n===0?`0+`:`(?:0+|0*[1-9]\\d{0,${n-1}})`}(?:\\.${`\\d{0,${t}}0*`})?|\\.${t===0?`0+`:`\\d{1,${t}}0*`})$`}function geoPointJsonSchema(){return{type:`object`,properties:{[V[0]]:{type:`number`,minimum:H,maximum:180},[V[1]]:{type:`number`,minimum:-90,maximum:90}},required:[...V],additionalProperties:!1}}function geoBoundsJsonSchema(){let e={type:`number`,minimum:-90,maximum:90},t={type:`number`,minimum:H,maximum:180};return{type:`object`,properties:{[U[0]]:e,[U[1]]:t,[U[2]]:e,[U[3]]:t},required:[...U],additionalProperties:!1}}function isDecimalSchema(e){return e.type===`decimal`}function isExactOneSchema(e){return e.type===`exact_one`}function getInnerSchema(e){let t=e;for(;t&&fe.has(t.type);)t=t.item??t.wrapped;return t}function framePointer(e,t){if(e.pointer!==null)return e.pointer;if(e.schema===t.rootSchema)return e.pointer=`#`,e.pointer;let n=e.schema.options?.name,r=n===``?void 0:n;for(;r===void 0||r in t.definitions;)t.refCount+=1,r=`Recursive${t.refCount}`;return e.name=r,e.pointer=`#/$defs/${r}`,t.definitions[r]={},e.pointer}function convertSchema(e,t,n=!1){if(!n){let n=t.referenceMap.get(e);if(n)return{$ref:`#/$defs/${n}`};let r=t.activeFrames.get(e);if(r)return{$ref:framePointer(r,t)}}let i=t.activeFrames.get(e),a={schema:e,pointer:null,name:null};t.activeFrames.set(e,a);let o;try{o=convertSchemaBody(e,t),`options`in e&&r(e.options)&&(e.options.array===!0&&(o={type:`array`,items:o}),e.options.nullable===!0&&(o=t.target===`openapi-3.0`?{...o,nullable:!0}:{anyOf:[o,{type:`null`}]}))}finally{i?t.activeFrames.set(e,i):t.activeFrames.delete(e)}return a.name===null?o:(t.definitions[a.name]=o,t.referenceMap.set(e,a.name),{$ref:a.pointer})}function convertSchemaBody(e,t){let a={};if(isDecimalSchema(e)){let n=e.options?.decimal;return n&&(a.description=`Exact decimal with at most ${n.precision} total digits and at most ${n.scale} fractional digits`),a.type=`string`,t.direction===`output`?a.pattern=`^(?:0|-?(?:[1-9]\\d*(?:\\.\\d*[1-9])?|0\\.\\d*[1-9]))$`:a.pattern=n?decimalDomainPattern(n):`^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$`,a}if(isExactOneSchema(e)){let r=[];for(let[i,a]of Object.entries(e.entries)){let e=n(a)?a():a;e.type!==`refused`&&r.push({type:`object`,properties:{[i]:convertSchema(e,t)},required:[i],additionalProperties:!1})}return a.oneOf=r,a}let o=e.type;switch(o){case`string`:{a.type=`string`;let t=e.options?.idDomain;t&&(a.pattern=idDomainPattern(t));break}case`number`:case`integer`:a.type=o===`integer`?`integer`:`number`,`minimum`in e&&typeof e.minimum==`number`&&(a.minimum=e.minimum),`maximum`in e&&typeof e.maximum==`number`&&(a.maximum=e.maximum);break;case`boolean`:a.type=`boolean`;break;case`bigint`:a.type=`string`,a.pattern=B;break;case`literal`:{let n=e.value;t.target===`openapi-3.0`?a.enum=[n]:a.const=n;break}case`enum`:a.enum=e.values;break;case`nullable`:{let n=e.wrapped,r=convertSchema(n,t);t.target===`openapi-3.0`?(Object.assign(a,r),a.nullable=!0):a.anyOf=[r,{type:`null`}];break}case`optional`:{let n=e.wrapped;return convertSchema(n,t)}case`array`:{let n=e.item;a.type=`array`,a.items=convertSchema(n,t);break}case`object`:{let o=e.entries,s=e.options,c=s?.partial??!0,l=s?.strict??!0;for(let e in a.type=`object`,a.properties={},a.required=[],o){let l=o[e],u=n(l)?l():l,d=getInnerSchema(u),f=d?.options?.name;f&&i(f)&&!t.referenceMap.has(d)&&(t.referenceMap.set(d,f),t.definitions[f]=convertSchema(d,t,!0)),a.properties[e]=convertSchema(u,t);let p=u.type,m=p===`optional`||p===`nullish`,h=`acceptsUndefined`in u&&u.acceptsUndefined===!0,g=t.direction===`output`&&`options`in u&&r(u.options)&&u.options.default!==void 0;(!c||s?.atLeast?.includes(e))&&(g||!(m||h))&&a.required.push(e)}l&&(a.additionalProperties=!1),a.required.length===0&&(a.required=void 0);break}case`record`:{let n=e.value;a.type=`object`,a.additionalProperties=convertSchema(n,t);break}case`union`:a.anyOf=e.options.map(e=>convertSchema(e,t));break;case`date`:a.type=`string`,a.format=`date-time`;break;case`iso_timestamp`:a.type=`string`,a.format=`date-time`;break;case`iso_date`:a.type=`string`,a.format=`date`;break;case`iso_time`:a.type=`string`,a.format=`time`;break;case`json`:break;case`refused`:a.not={};break;case`blob`:a.type=`string`,a.contentEncoding=`base64`;break;case`vector`:{let t=e.dimensions;a.type=`array`,a.items={type:`number`},t!==void 0&&(a.minItems=t,a.maxItems=t);break}case`point`:Object.assign(a,geoPointJsonSchema());break;case`geo_area`:{let e={type:`array`,items:geoPointJsonSchema(),minItems:3};a.oneOf=[{type:`object`,properties:{bounds:{...geoBoundsJsonSchema()}},required:[`bounds`],additionalProperties:!1},{type:`object`,properties:{polygon:{type:`object`,properties:{outer:e,holes:{type:`array`,items:e}},required:[`outer`],additionalProperties:!1}},required:[`polygon`],additionalProperties:!1}];break}case`transform`:{let n=e.wrapped;return convertSchema(n,t)}case`field_ref_or`:case`comparison_operand`:case`value_node_or`:{let n=e.wrapped;return convertSchema(n,t)}case`lazyRef`:{let n=e.wrapped;return convertSchema(n,t)}case`no_field_ref`:case`written_depth`:{let n=e.wrapped;return convertSchema(n,t)}case`json_null_or`:case`json_write`:{let n=e.wrapped;return convertSchema(n,t)}case`polymorphic_only`:{let{wrapped:n}=e;return{...convertSchema(n,t),uniqueItems:!0}}case`pipe`:{let n=e.schema;return convertSchema(n,t)}default:throw new u({kind:`json-schema`,schemaType:o},[{path:`type`,message:`Cannot convert "${o}" schema to JSON Schema: unsupported type`}])}return a}function toJsonSchema(e,t=`draft-07`){return toJsonSchemaForDirection(e,t,`input`)}function toJsonSchemaForDirection(e,t,n){if(!de.includes(t))throw new u({kind:`json-schema`,target:t},[{path:`target`,message:`Unsupported JSON Schema target: ${t}`}]);let r=createContext(t,e,n),i=convertSchema(e,r);return t===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:t===`draft-07`&&(i.$schema=`http://json-schema.org/draft-07/schema#`),Object.keys(r.definitions).length>0&&(i.$defs=r.definitions),i}function createJsonSchemaConverter(e){return{input(t){return toJsonSchemaForDirection(e,t.target,`input`)},output(t){return toJsonSchemaForDirection(e,t.target,`output`)}}}let W;const isProvided=(e,t)=>e!==void 0&&W?.(e,t)===!0;function parseProviding(e,t){let n=W;W=e;try{return t()}finally{W=n}}const G=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected object`})])}),K=Object.freeze([]),pe=Object.freeze(new Map),q=Symbol(`inputValueUnread`);function readObjectInputValue(e,t,n,r){if(n===void 0||r===void 0)return e[t];let i=r.get(t);if(i===void 0)return e[t];let a=n[i];if(a!==q)return a;let o=e[t];return n[i]=o,o}function createObjectValidator(e,t={}){let{partial:i=!0,strict:a=!0,atLeast:o,requiresOneOf:s,requiresOneOfKeySets:c,omit:l,nonEmpty:u,refuse:d,provides:f}=t,p=K,m=pe,h=K,g,_,v=K,y=K,b=null,x,S,resolve=()=>{resolve=void 0;let t=l?new Set(l):null,r=Object.keys(e).filter(e=>!t?.has(e)),a=o?new Set(o):null,u=new Map,d=Array(r.length),f=i&&!a,C=s?.filter(e=>!e.some(e=>t?.has(e))),w=c?.filter(e=>!e.some(e=>e.some(e=>t?.has(e)))),T,E;p=r,m=u,h=d,g=C,_=w,f?(T=[],v=T,y=K,b=null):(E=Array(r.length),v=K,y=E,b=i&&a?r.map(e=>a.has(e)):null);for(let t=0;t<r.length;t++){let i=r[t];u.set(i,t);let a=e[i],o=n(a)?a():a;d[t]=o[`~standard`].validate;let s=o.acceptsUndefined===!0;T?s&&T.push(t):E&&(E[t]=s)}let D=new Map,registerInputValueScratchIndex=e=>{D.has(e)||D.set(e,D.size)};for(let e of C??K)for(let t of e)registerInputValueScratchIndex(t);for(let e of w??K)for(let t of e)for(let e of t)registerInputValueScratchIndex(e);for(let e of v)registerInputValueScratchIndex(r[e]);D.size>0&&(x=Array.from({length:D.size},()=>q),S=D)},C=u===!0||s||c?(e,t)=>{if(u===!0){let t=!1;for(let n in e){t=!0;break}if(!t)return[{message:`Object cannot be empty`}]}if(g){for(let n of g)if(!n.some(n=>readObjectInputValue(e,n,t,S)!==void 0))return[{message:`Missing required field: one of ${n.join(`, `)}`}]}if(_){for(let n of _)if(!n.some(n=>n.every(n=>readObjectInputValue(e,n,t,S)!==void 0||isProvided(f,n))))return[{message:`Missing required fields: one of ${n.map(e=>e.join(`, `)).join(` or `)}`}]}}:void 0,precheck=(e,t)=>{let n=a?unknownKeyIssues(e,m):void 0;if(n&&!collectingAllIssues())return n;let r=C?.(e,t);return r?gathered(n,r):n},parsePartial=e=>{if(!r(e))return G;let t=e;resolve&&resolve();let n=x?.slice(),i=precheck(t,n);if(i&&!collectingAllIssues())return{issues:i};let a={};for(let e in t){let r=m.get(e);if(r===void 0)continue;let o=readObjectInputValue(t,e,n,S);if(o===void 0)continue;let s=h[r](o);if(s.issues){if(i=gathered(i,issuesUnder(e,s.issues)),!collectingAllIssues())return{issues:i};continue}s.value!==void 0&&(a[e]=s.value)}for(let e of v){let r=p[e];if(readObjectInputValue(t,r,n,S)!==void 0)continue;let o=h[e](void 0);if(o.issues){if(i=gathered(i,issuesUnder(r,o.issues)),!collectingAllIssues())return{issues:i};continue}o.value!==void 0&&(a[r]=o.value)}if(i)return{issues:i};let o=d?.(a);return o?{issues:[typeof o==`string`?{message:o}:o]}:{value:a}},parseDense=e=>{if(!r(e))return G;let t=e;resolve&&resolve();let n=x?.slice(),a=precheck(t,n);if(a&&!collectingAllIssues())return{issues:a};let o={};for(let e=0;e<p.length;e++){let r=p[e],s=readObjectInputValue(t,r,n,S);if(s===void 0){if((!i||b?.[e]===!0)&&!y[e]&&!isProvided(f,r)){if(a=gathered(a,[{message:`Missing required field: ${r}`,path:[r]}]),!collectingAllIssues())return{issues:a};continue}if(y[e]){let t=h[e](void 0);if(t.issues){if(a=gathered(a,issuesUnder(r,t.issues)),!collectingAllIssues())return{issues:a};continue}o[r]=t.value}else o[r]=void 0;continue}let c=h[e](s);if(c.issues){if(a=gathered(a,issuesUnder(r,c.issues)),!collectingAllIssues())return{issues:a};continue}o[r]=c.value}if(a)return{issues:a};let s=d?.(o);return s?{issues:[typeof s==`string`?{message:s}:s]}:{value:o}};return i&&!o?parsePartial:parseDense}function gathered(e,t){return e?(e.push(...t),e):t}function unknownKeyIssues(e,t){let n;for(let r in e)if(!t.has(r)&&((n??=[]).push({message:`Unknown key: ${r}`,path:[r]}),!collectingAllIssues()))break;return n}function object(e,t){let r=createObjectValidator(e,t),i=t?.optional===!0,a=t?.nullable===!0,o=t?.array===!0,s=t?.transform!==void 0,c=t?.default!==void 0,l=i||a||o||s||c,u;if(l){let e=c?n(t.default)?t.default:()=>t.default:null,l=s?e=>{let n=r(e);if(n.issues)return n;try{return ok(t.transform(n.value))}catch(e){return fail(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}}:r;if(o){let arrayValidate=e=>validateArray(e,l);u=i&&a?t=>t===void 0?e?ok(e()):z:t===null?R:arrayValidate(t):i?t=>t===void 0?e?ok(e()):z:arrayValidate(t):a?e=>e===null?R:arrayValidate(e):arrayValidate}else u=i&&a?t=>t===void 0?e?ok(e()):z:t===null?R:l(t):i?t=>t===void 0?e?ok(e()):z:l(t):a?e=>e===null?R:l(e):l}else u=r;let d={type:`object`,entries:e,options:t,acceptsUndefined:i||c,"~standard":{version:1,vendor:`viborm`,validate:u,get jsonSchema(){let e=createJsonSchemaConverter(d);return Object.defineProperty(this,`jsonSchema`,{value:e,writable:!1,enumerable:!0}),e}},extend:n=>object({...e,...n},t)};return d}const me=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/,he=/^0+/,ge=/0+$/,_e=/^[+-]/;function canonicalizeLiteral(e){let t=e.startsWith(`-`),[n=``,r=``]=e.replace(_e,``).split(`.`),i=n.replace(he,``),a=r.replace(ge,``),o=i===``?`0`:i;if(o===`0`&&a===``)return`0`;let s=t?`-`:``;return a===``?`${s}${o}`:`${s}${o}.${a}`}function admitDecimal(e){return typeof e==`string`?me.test(e)?canonicalizeLiteral(e):void 0:canonicalDecimalText(e)}const J=10n;function shift(e){return J**BigInt(e)}function roundQuotient(e,t,n){let r=e/t,i=e%t*2n;return i>t?r+1n:i<t?r:n===`half-up`||r%2n!=0n?r+1n:r}const Y=`a string like '-12.345' (sign, digits, at most one dot, no exponent); a JavaScript number is a double and is not accepted`,ve=`Expected an exact decimal: a Decimal or ${Y}`,ye=`Expected an exact decimal: a Decimal, a bigint, or ${Y}`;function renderParts(e,t){let n=e<0n;return placePoint(n,(n?-e:e).toString(),t)}function placePoint(e,t,n){let r=e?`-`:``;if(n===0)return`${r}${t}`;let i=t.padStart(n+1,`0`),a=i.length-n;return`${r}${i.slice(0,a)}.${i.slice(a)}`}function renderFixed(e,t,n){let r=e<0n;return placePoint(r,roundQuotient((r?-e:e)*shift(n),shift(t),`half-up`).toString(),n)}function partsOfCanonical(e){let t=e.indexOf(`.`);if(t===-1)return[BigInt(e),0];let n=e.length-t-1;return[BigInt(e.slice(0,t)+e.slice(t+1)),n]}let owns,textOf;var X=class ExactDecimal{#e;#t;value;constructor(e,t){if(typeof e==`bigint`){let n=e,r=t??0;for(;r>0&&n%J===0n;)n/=J,r--;this.#e=n,this.#t=n===0n?0:r}else if(owns(e))this.#e=e.#e,this.#t=e.#t;else{let t=admitDecimal(e);if(t===void 0)throw TypeError(ye);let[n,r]=partsOfCanonical(t);this.#e=n,this.#t=r}this.value=renderParts(this.#e,this.#t),Object.defineProperty(this,`value`,{writable:!1,configurable:!1})}static{owns=e=>typeof e==`object`&&!!e&&#e in e,textOf=e=>renderParts(e.#e,e.#t)}#n(e){return this.#e*shift(e-this.#t)}plus(e){let t=new ExactDecimal(e),n=Math.max(this.#t,t.#t);return new ExactDecimal(this.#n(n)+t.#n(n),n)}minus(e){let t=new ExactDecimal(e),n=Math.max(this.#t,t.#t);return new ExactDecimal(this.#n(n)-t.#n(n),n)}times(e){let t=new ExactDecimal(e);return new ExactDecimal(this.#e*t.#e,this.#t+t.#t)}div(e,t=20,n=`half-up`){let r=new ExactDecimal(e);if(r.#e===0n)throw RangeError(`Division by zero`);let i=this.#e*shift(r.#t+t),a=r.#e*shift(this.#t),o=i<0n!=a<0n,s=roundQuotient(i<0n?-i:i,a<0n?-a:a,n);return new ExactDecimal(o?-s:s,t)}cmp(e){let t=new ExactDecimal(e),n=Math.max(this.#t,t.#t),r=this.#n(n),i=t.#n(n);return r<i?-1:r>i?1:0}eq(e){return this.cmp(e)===0}lt(e){return this.cmp(e)===-1}lte(e){return this.cmp(e)!==1}gt(e){return this.cmp(e)===1}gte(e){return this.cmp(e)!==-1}abs(){return new ExactDecimal(this.#e<0n?-this.#e:this.#e,this.#t)}neg(){return new ExactDecimal(-this.#e,this.#t)}toString(){return renderParts(this.#e,this.#t)}toFixed(e){return e===void 0?this.toString():renderFixed(this.#e,this.#t,e)}toNumber(){return Number(this.toString())}valueOf(){return this.toString()}toJSON(){return this.toString()}[Symbol.for(`nodejs.util.inspect.custom`)](){return`Decimal("${this.value}")`}};const be=X;function fromCanonical(e){let[t,n]=partsOfCanonical(e);return new X(t,n)}function canonicalDecimalText(e){return owns(e)?textOf(e):void 0}function fromCoefficient(e,t){return new X(e,t)}function toCoefficient(e,t){let[n,r]=partsOfCanonical(e);return(n*shift(t-r)).toString()}function domainRefusal(e,t,n){let r=e.indexOf(`.`),i=r===-1?0:e.length-r-1;if(i>n)return`Expected at most ${n} fractional digit${n===1?``:`s`}, but '${e}' has ${i}`;let a=e.startsWith(`-`)?1:0,o;if(e[a]!==`0`)o=(r===-1?e.length:r)-a+n;else{let t=r+1;for(;e[t]===`0`;)t++;o=r===-1?0:n-(t-r-1)}if(o>t)return`Expected an unscaled coefficient of at most ${t} digits, but '${e}' needs ${o}`}function sameDecimalDescriptor(e,t){return e===void 0||t===void 0?e===t:e.precision===t.precision&&e.scale===t.scale}const xe=admitDecimal,Se=canonicalDecimalText,Ce=fromCanonical,we=toCoefficient,Te=/^(?:0|-?[1-9]\d*)$/;function decodeCoefficient(e,t,n){if(!(i(e)&&Te.test(e)))return;let r=e.startsWith(`-`)?e.length-1:e.length;if(!(n!==void 0&&r>n))return fromCoefficient(BigInt(e),t)}function decodeCoefficientText(e,t,n){let r=decodeCoefficient(e,t,n);return r===void 0?void 0:canonicalDecimalText(r)}function isDecimalDigit(e){return e>=48&&e<=57}function scanProviderText(e,t,n){let r=e.length;if(r===0)return;let i=e.charCodeAt(0)===45?1:0;if(i===r)return;let a=i,o=e.charCodeAt(a),s=o===48;if(s){if(a++,a<r&&isDecimalDigit(e.charCodeAt(a)))return}else{if(o<49||o>57)return;for(a++;a<r&&isDecimalDigit(e.charCodeAt(a));)a++}let c=a,l=r,u=-1,d=-1;if(a<r){if(e.charCodeAt(a)!==46||(l=++a,a===r))return;for(;a<r;a++){let t=e.charCodeAt(a);if(!isDecimalDigit(t))return;t!==48&&(u<0&&(u=a-l),d=a+1)}}let f=s&&u<0,p=d<0?0:d-l,m=s?u<0?0:t-u:c-i+t;if(!(p>t||n!==void 0&&m>n))return f?0:p===0?c:d}function renderProviderText(e,t){return t===0?`0`:t===e.length?e:e.slice(0,t)}function decodeFieldScalar(e,t){if(!i(e))return;let n=scanProviderText(e,t.scale,t.precision);return n===void 0?void 0:renderProviderText(e,n)}function decodeWidenedSum(e,t){if(!i(e))return;let n=scanProviderText(e,t);return n===void 0?void 0:renderProviderText(e,n)}function encodePhysicalDecimalAtScale(e,t,n){return n===`coefficient`?toCoefficient(e,t):e}function encodePhysicalDecimal(e,t,n){return encodePhysicalDecimalAtScale(e,t.scale,n)}function materializeProviderText(e,t,n){if(!i(e))return;let r=scanProviderText(e,t,n);if(r!==void 0)return fromCanonical(renderProviderText(e,r))}function decodePhysicalDecimal(e,t,n){return n===`text`?decodeFieldScalar(e,t):decodeCoefficientText(e,t.scale,t.precision)}function materializePhysicalDecimal(e,t,n){return n===`text`?materializeProviderText(e,t.scale,t.precision):decodeCoefficient(e,t.scale,t.precision)}function encodePhysicalDecimalListMembers(e,t,n){let r=Array(e.length);for(let[i,a]of e.entries()){let e=admitDecimal(a);if(e===void 0)return;r[i]=encodePhysicalDecimalAtScale(e,t.scale,n)}return r}function decodePhysicalDecimalList(e,t,n){let r;if(n===`coefficient`){let n=decodeDecimalListContainer(e,t.scale,t.precision);if(n===void 0)return;r=n}else{try{if(!Array.isArray(e))return;let n=e.length;if(!Number.isSafeInteger(n)||n<0)return;r=Array(n);for(let i=0;i<n;i++){if(!Object.hasOwn(e,i))return;let n=decodeFieldScalar(e[i],t);if(n===void 0)return;r[i]=n}}catch{return}return r}return r}function decodePhysicalWidenedSum(e,t,n){return n===`text`?decodeWidenedSum(e,t.scale):decodeCoefficientText(e,t.scale)}function materializePhysicalWidenedSum(e,t,n){return n===`text`?materializeProviderText(e,t.scale):decodeCoefficient(e,t.scale)}const Ee={pg:{precision:1e3,scale:1e3},mysql:{precision:65,scale:30,sum:65},sqlite:{precision:18,scale:18,sum:18}};function describeProviderLimitRefusal(e,t){let n=Ee[e],{precision:r,scale:i}=t,a=`precision ${r}, scale ${i}`;if(r>n.precision)return`${a} exceeds this provider's maximum precision of ${n.precision}`;if(i>n.scale)return`${a} exceeds this provider's maximum scale of ${n.scale}`;if(n.sum!==void 0&&r+i>n.sum)return`${a} needs precision + scale <= ${n.sum} on this provider, which is what makes its one-statement exact multiply and divide representable`}function decimalColumnType(e,t){let{precision:n,scale:r}=t;return e===`pg`?`NUMERIC(${n},${r})`:e===`mysql`?`DECIMAL(${n},${r})`:`INTEGER`}function decimalDefaultText(e,t,n){let{scale:r}=n;if(e===`sqlite`)return toCoefficient(t,r);let i=t.indexOf(`.`);return r===0?i===-1?t:t.slice(0,i):i===-1?`${t}.${`0`.repeat(r)}`:t.padEnd(i+1+r,`0`)}function decimalListDefaultText(e,t,n){if(e!==`pg`)return encodeDecimalListContainer(t,n.scale);let r=Array(t.length);for(let[e,i]of t.entries())r[e]=decimalDefaultText(`pg`,i,n);return`{${r.join(`,`)}}`}function encodeDecimalListContainer(e,t){let n=Array(e.length);for(let[r,i]of e.entries())n[r]=encodePhysicalDecimalAtScale(i,t,`coefficient`);return JSON.stringify(n)}function decodeDecimalListContainer(e,t,n){if(!i(e))return;let r;try{r=JSON.parse(e)}catch{return}if(!Array.isArray(r))return;let a=Array(r.length);for(let[e,i]of r.entries()){let r=decodeCoefficientText(i,t,n);if(r===void 0)return;a[e]=r}return a}function describeDecimalDomain(e){return`precision ${e.precision}, scale ${e.scale}`}const De=/^-?\d+$/;function readStoredDecimalDescriptor(e,t,n){let r=readStoredDecimalInteger(e),i=readStoredDecimalInteger(t);if(r===void 0||i===void 0||r<=0||i<0||i>r)return;let a={precision:r,scale:i};return describeProviderLimitRefusal(n,a)===void 0?a:void 0}function readStoredDecimalInteger(e){if(typeof e==`number`)return Number.isSafeInteger(e)?e:void 0;if(typeof e!=`string`||!De.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}const Z=-621672192e5,Q=0xe677d21fdbff;function isDateTimeInstant(e){return Number.isInteger(e)&&e>=Z&&e<=Q}function isGregorianCalendarDate(e,t,n){if(!(Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n))||t<1||t>12||n<1)return!1;let r=31;return t===2?r=isLeapYear(e)?29:28:(t===4||t===6||t===9||t===11)&&(r=30),n<=r}function isDateTimeClock(e,t,n){return Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(n)&&e>=0&&e<=23&&t>=0&&t<=59&&n>=0&&n<=59}function isLeapYear(e){return e%4==0&&(e%100!=0||e%400==0)}const Oe=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected finite number`})])});function validateNumber(e){return t(e)&&Number.isFinite(e)?ok(e):Oe}function number(e){return buildSchema(`number`,validateNumber,e)}const ke=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected integer`})])}),Ae=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected safe integer`})])});function validateInteger(e){return t(e)&&Number.isInteger(e)?Number.isSafeInteger(e)?ok(e):Ae:ke}function integer(e){return buildSchema(`integer`,validateInteger,e)}function optional(e,t){let r=n(e)&&!(`~standard`in e)?null:e[`~standard`].validate,getValidate=()=>r||(r=e()[`~standard`].validate,r),i=createSchema(`optional`,e=>e===void 0?ok(t===void 0?void 0:n(t)?t():t):getValidate()(e));return i.wrapped=e,i.default=t,i.acceptsUndefined=!0,i}function geoCoordinate(e,t,n){return createSchema(`number`,r=>{let i=validateNumber(r);return i.issues?i:i.value<t||i.value>n?fail(`${e} must be between ${t} and ${n}`):ok(Object.is(i.value,-0)?0:i.value)})}const $=geoCoordinate(`Longitude`,H,180),je=geoCoordinate(`Latitude`,-90,90),Me=object({[V[0]]:$,[V[1]]:je},{partial:!1});function validateGeoPoint(e){let t=validateSchema(Me,e);if(t.issues)return t;let{longitude:n,latitude:r}=t.value;return ok({longitude:n===H?180:n,latitude:r})}export{ok as $,materializePhysicalWidenedSum as A,normalizeBinaryValue as At,parseProviding as B,decodeWidenedSum as C,hasIdPrefix as Ct,encodePhysicalDecimalListMembers as D,ulidBytes as Dt,encodePhysicalDecimal as E,refuseId as Et,be as F,normalizeNamespace as Ft,ce as G,toJsonSchema as H,admitDecimal as I,ue as J,se as K,canonicalDecimalText as L,sameDecimalDescriptor as M,readValidationFailureCause as Mt,Ce as N,validationFailureFromThrown as Nt,we as O,uuidV4Bytes as Ot,ve as P,isValidSchemaIdentifier as Pt,fail as Q,domainRefusal as R,decodePhysicalWidenedSum as S,bytesToUuid as St,describeProviderLimitRefusal as T,randomBytes as Tt,U,createJsonSchemaConverter as V,le as W,buildSchema as X,bigint as Y,createSchema as Z,decimalDefaultText as _,S as _t,integer as a,describeIdDomain as at,decodePhysicalDecimal as b,bytesToKsuid as bt,validateNumber as c,isCompactIdFormat as ct,isDateTimeClock as d,F as dt,reportingAllIssues as et,isDateTimeInstant as f,C as ft,decimalColumnType as g,x as gt,Se as h,ee as ht,optional as i,decodePhysicalId as it,readStoredDecimalDescriptor as j,discardAsyncValidationResult as jt,materializePhysicalDecimal as k,uuidV7Bytes as kt,Q as l,isIdFormat as lt,xe as m,k as mt,$ as n,validateArray as nt,number as o,encodePhysicalId as ot,isGregorianCalendarDate as p,te as pt,H as q,validateGeoPoint as r,validateSchema as rt,validateInteger as s,idByteLength as st,je as t,standardSchemaFailure as tt,Z as u,sameIdDomain as ut,decimalListDefaultText as v,b as vt,describeDecimalDomain as w,ksuidBytes as wt,decodePhysicalDecimalList as x,bytesToUlid as xt,decodeFieldScalar as y,applyIdPrefix as yt,object as z};
2
+ //# sourceMappingURL=geo-point-codec-DyEHMdJg.mjs.map