effect 4.0.0-rc.111 → 4.0.0-rc.113

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 (1293) hide show
  1. package/AGENTS.md +24 -9
  2. package/CLAUDE.md +24 -9
  3. package/ai-docs/package.json +2 -2
  4. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +18 -5
  5. package/ai-docs/src/01_effect/01_basics/index.md +5 -3
  6. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +1 -1
  7. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +2 -2
  8. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +2 -2
  9. package/ai-docs/src/03_stream/30_encoding.ts +5 -7
  10. package/ai-docs/src/08_observability/10_logging.ts +1 -1
  11. package/ai-docs/src/70_cli/10_basics.ts +7 -7
  12. package/ai-docs/src/71_ai/10_language-model.ts +2 -2
  13. package/ai-docs/src/71_ai/20_tools.ts +1 -1
  14. package/ai-docs/src/71_ai/30_chat.ts +1 -1
  15. package/dist/Array.d.ts +109 -52
  16. package/dist/Array.d.ts.map +1 -1
  17. package/dist/Array.js +65 -32
  18. package/dist/Array.js.map +1 -1
  19. package/dist/BigDecimal.d.ts +5 -1
  20. package/dist/BigDecimal.d.ts.map +1 -1
  21. package/dist/BigDecimal.js +40 -23
  22. package/dist/BigDecimal.js.map +1 -1
  23. package/dist/ByteSize.d.ts +633 -0
  24. package/dist/ByteSize.d.ts.map +1 -0
  25. package/dist/ByteSize.js +524 -0
  26. package/dist/ByteSize.js.map +1 -0
  27. package/dist/Cache.d.ts.map +1 -1
  28. package/dist/Cache.js +17 -3
  29. package/dist/Cache.js.map +1 -1
  30. package/dist/Cause.d.ts +1 -1
  31. package/dist/Cause.d.ts.map +1 -1
  32. package/dist/Channel.d.ts +97 -24
  33. package/dist/Channel.d.ts.map +1 -1
  34. package/dist/Channel.js +68 -41
  35. package/dist/Channel.js.map +1 -1
  36. package/dist/Chunk.d.ts +49 -28
  37. package/dist/Chunk.d.ts.map +1 -1
  38. package/dist/Chunk.js +27 -18
  39. package/dist/Chunk.js.map +1 -1
  40. package/dist/Config.d.ts +162 -201
  41. package/dist/Config.d.ts.map +1 -1
  42. package/dist/Config.js +103 -212
  43. package/dist/Config.js.map +1 -1
  44. package/dist/ConfigProvider.d.ts +4 -4
  45. package/dist/ConfigProvider.d.ts.map +1 -1
  46. package/dist/ConfigProvider.js +7 -7
  47. package/dist/ConfigProvider.js.map +1 -1
  48. package/dist/Context.d.ts +31 -0
  49. package/dist/Context.d.ts.map +1 -1
  50. package/dist/Context.js.map +1 -1
  51. package/dist/Cron.d.ts +2 -2
  52. package/dist/Cron.d.ts.map +1 -1
  53. package/dist/Cron.js +2 -2
  54. package/dist/Cron.js.map +1 -1
  55. package/dist/Crypto.d.ts +1 -1
  56. package/dist/Crypto.d.ts.map +1 -1
  57. package/dist/Crypto.js +3 -2
  58. package/dist/Crypto.js.map +1 -1
  59. package/dist/DateTime.d.ts +2 -2
  60. package/dist/DateTime.d.ts.map +1 -1
  61. package/dist/Deferred.d.ts.map +1 -1
  62. package/dist/Deferred.js +6 -6
  63. package/dist/Deferred.js.map +1 -1
  64. package/dist/Duration.d.ts +1 -1
  65. package/dist/Duration.d.ts.map +1 -1
  66. package/dist/Duration.js +1 -1
  67. package/dist/Duration.js.map +1 -1
  68. package/dist/Effect.d.ts +220 -113
  69. package/dist/Effect.d.ts.map +1 -1
  70. package/dist/Effect.js +27 -26
  71. package/dist/Effect.js.map +1 -1
  72. package/dist/Effectable.d.ts +58 -2
  73. package/dist/Effectable.d.ts.map +1 -1
  74. package/dist/Effectable.js +58 -6
  75. package/dist/Effectable.js.map +1 -1
  76. package/dist/Encoding.d.ts +3 -1
  77. package/dist/Encoding.d.ts.map +1 -1
  78. package/dist/Encoding.js +40 -10
  79. package/dist/Encoding.js.map +1 -1
  80. package/dist/Equal.d.ts +1 -1
  81. package/dist/Equal.d.ts.map +1 -1
  82. package/dist/Equal.js +1 -1
  83. package/dist/Equal.js.map +1 -1
  84. package/dist/ExecutionPlan.d.ts.map +1 -1
  85. package/dist/ExecutionPlan.js +1 -0
  86. package/dist/ExecutionPlan.js.map +1 -1
  87. package/dist/Fiber.d.ts +32 -8
  88. package/dist/Fiber.d.ts.map +1 -1
  89. package/dist/Fiber.js.map +1 -1
  90. package/dist/FiberHandle.js +3 -3
  91. package/dist/FiberHandle.js.map +1 -1
  92. package/dist/FiberMap.d.ts +12 -6
  93. package/dist/FiberMap.d.ts.map +1 -1
  94. package/dist/FiberMap.js +11 -6
  95. package/dist/FiberMap.js.map +1 -1
  96. package/dist/FileSystem.d.ts +42 -210
  97. package/dist/FileSystem.d.ts.map +1 -1
  98. package/dist/FileSystem.js +16 -148
  99. package/dist/FileSystem.js.map +1 -1
  100. package/dist/Formatter.d.ts +1 -0
  101. package/dist/Formatter.d.ts.map +1 -1
  102. package/dist/Formatter.js +19 -3
  103. package/dist/Formatter.js.map +1 -1
  104. package/dist/Graph.d.ts +48 -20
  105. package/dist/Graph.d.ts.map +1 -1
  106. package/dist/Graph.js +20 -5
  107. package/dist/Graph.js.map +1 -1
  108. package/dist/Hash.d.ts +1 -1
  109. package/dist/Hash.d.ts.map +1 -1
  110. package/dist/Hash.js +5 -14
  111. package/dist/Hash.js.map +1 -1
  112. package/dist/HashMap.d.ts +1 -1
  113. package/dist/HashMap.d.ts.map +1 -1
  114. package/dist/HashRing.d.ts +6 -1
  115. package/dist/HashRing.d.ts.map +1 -1
  116. package/dist/HashRing.js +9 -2
  117. package/dist/HashRing.js.map +1 -1
  118. package/dist/HashSet.d.ts +1 -1
  119. package/dist/HashSet.d.ts.map +1 -1
  120. package/dist/HashSet.js.map +1 -1
  121. package/dist/Iterable.d.ts +56 -17
  122. package/dist/Iterable.d.ts.map +1 -1
  123. package/dist/Iterable.js +65 -45
  124. package/dist/Iterable.js.map +1 -1
  125. package/dist/JsonPatch.js +4 -4
  126. package/dist/JsonPatch.js.map +1 -1
  127. package/dist/JsonPointer.d.ts +68 -4
  128. package/dist/JsonPointer.d.ts.map +1 -1
  129. package/dist/JsonPointer.js +90 -4
  130. package/dist/JsonPointer.js.map +1 -1
  131. package/dist/JsonSchema.d.ts +67 -94
  132. package/dist/JsonSchema.d.ts.map +1 -1
  133. package/dist/JsonSchema.js +752 -397
  134. package/dist/JsonSchema.js.map +1 -1
  135. package/dist/Layer.d.ts +47 -4
  136. package/dist/Layer.d.ts.map +1 -1
  137. package/dist/Layer.js +4 -6
  138. package/dist/Layer.js.map +1 -1
  139. package/dist/LayerMap.d.ts +24 -3
  140. package/dist/LayerMap.d.ts.map +1 -1
  141. package/dist/LayerMap.js +9 -5
  142. package/dist/LayerMap.js.map +1 -1
  143. package/dist/LayerRef.d.ts.map +1 -1
  144. package/dist/LayerRef.js +7 -5
  145. package/dist/LayerRef.js.map +1 -1
  146. package/dist/Logger.d.ts +114 -9
  147. package/dist/Logger.d.ts.map +1 -1
  148. package/dist/Logger.js +109 -9
  149. package/dist/Logger.js.map +1 -1
  150. package/dist/ManagedRuntime.js +1 -1
  151. package/dist/ManagedRuntime.js.map +1 -1
  152. package/dist/Match.d.ts +43 -31
  153. package/dist/Match.d.ts.map +1 -1
  154. package/dist/Match.js +5 -2
  155. package/dist/Match.js.map +1 -1
  156. package/dist/Metric.d.ts +11 -4
  157. package/dist/Metric.d.ts.map +1 -1
  158. package/dist/Metric.js +14 -18
  159. package/dist/Metric.js.map +1 -1
  160. package/dist/MutableHashMap.d.ts +1 -1
  161. package/dist/MutableHashMap.d.ts.map +1 -1
  162. package/dist/MutableHashMap.js +1 -1
  163. package/dist/MutableHashMap.js.map +1 -1
  164. package/dist/MutableHashSet.d.ts +1 -1
  165. package/dist/MutableHashSet.d.ts.map +1 -1
  166. package/dist/MutableHashSet.js +1 -1
  167. package/dist/MutableHashSet.js.map +1 -1
  168. package/dist/MutableList.d.ts +13 -2
  169. package/dist/MutableList.d.ts.map +1 -1
  170. package/dist/MutableList.js +18 -2
  171. package/dist/MutableList.js.map +1 -1
  172. package/dist/Number.d.ts +6 -0
  173. package/dist/Number.d.ts.map +1 -1
  174. package/dist/Number.js +3 -1
  175. package/dist/Number.js.map +1 -1
  176. package/dist/Optic.d.ts.map +1 -1
  177. package/dist/Optic.js +5 -4
  178. package/dist/Optic.js.map +1 -1
  179. package/dist/Option.d.ts +1 -1
  180. package/dist/Option.d.ts.map +1 -1
  181. package/dist/Option.js +1 -1
  182. package/dist/Option.js.map +1 -1
  183. package/dist/Order.d.ts +1 -0
  184. package/dist/Order.d.ts.map +1 -1
  185. package/dist/Order.js +3 -1
  186. package/dist/Order.js.map +1 -1
  187. package/dist/PartitionedSemaphore.d.ts.map +1 -1
  188. package/dist/PartitionedSemaphore.js +1 -2
  189. package/dist/PartitionedSemaphore.js.map +1 -1
  190. package/dist/Path.d.ts +1 -1
  191. package/dist/Path.d.ts.map +1 -1
  192. package/dist/Path.js +1 -1
  193. package/dist/Path.js.map +1 -1
  194. package/dist/PlatformError.d.ts +1 -1
  195. package/dist/PlatformError.d.ts.map +1 -1
  196. package/dist/PlatformError.js +1 -1
  197. package/dist/PlatformError.js.map +1 -1
  198. package/dist/Pool.d.ts +137 -10
  199. package/dist/Pool.d.ts.map +1 -1
  200. package/dist/Pool.js +332 -75
  201. package/dist/Pool.js.map +1 -1
  202. package/dist/PrimaryKey.d.ts +1 -1
  203. package/dist/PrimaryKey.d.ts.map +1 -1
  204. package/dist/PrimaryKey.js +1 -1
  205. package/dist/PrimaryKey.js.map +1 -1
  206. package/dist/PubSub.d.ts +21 -9
  207. package/dist/PubSub.d.ts.map +1 -1
  208. package/dist/PubSub.js +18 -14
  209. package/dist/PubSub.js.map +1 -1
  210. package/dist/Queue.d.ts +82 -6
  211. package/dist/Queue.d.ts.map +1 -1
  212. package/dist/Queue.js +116 -27
  213. package/dist/Queue.js.map +1 -1
  214. package/dist/Random.d.ts +17 -4
  215. package/dist/Random.d.ts.map +1 -1
  216. package/dist/Random.js +1 -1
  217. package/dist/Random.js.map +1 -1
  218. package/dist/RcMap.d.ts +137 -0
  219. package/dist/RcMap.d.ts.map +1 -1
  220. package/dist/RcMap.js +72 -9
  221. package/dist/RcMap.js.map +1 -1
  222. package/dist/Record.d.ts +13 -0
  223. package/dist/Record.d.ts.map +1 -1
  224. package/dist/Record.js.map +1 -1
  225. package/dist/Redacted.d.ts +1 -1
  226. package/dist/Redacted.d.ts.map +1 -1
  227. package/dist/Redacted.js +1 -1
  228. package/dist/Redacted.js.map +1 -1
  229. package/dist/RequestResolver.d.ts +15 -9
  230. package/dist/RequestResolver.d.ts.map +1 -1
  231. package/dist/RequestResolver.js +33 -15
  232. package/dist/RequestResolver.js.map +1 -1
  233. package/dist/Result.d.ts +1 -1
  234. package/dist/Result.d.ts.map +1 -1
  235. package/dist/Result.js +1 -1
  236. package/dist/Result.js.map +1 -1
  237. package/dist/Scheduler.d.ts.map +1 -1
  238. package/dist/Scheduler.js +19 -10
  239. package/dist/Scheduler.js.map +1 -1
  240. package/dist/Schema.d.ts +2200 -2433
  241. package/dist/Schema.d.ts.map +1 -1
  242. package/dist/Schema.js +2797 -4184
  243. package/dist/Schema.js.map +1 -1
  244. package/dist/SchemaAST.d.ts +359 -176
  245. package/dist/SchemaAST.d.ts.map +1 -1
  246. package/dist/SchemaAST.js +373 -630
  247. package/dist/SchemaAST.js.map +1 -1
  248. package/dist/SchemaGetter.d.ts +46 -22
  249. package/dist/SchemaGetter.d.ts.map +1 -1
  250. package/dist/SchemaGetter.js +56 -53
  251. package/dist/SchemaGetter.js.map +1 -1
  252. package/dist/SchemaIssue.d.ts +123 -200
  253. package/dist/SchemaIssue.d.ts.map +1 -1
  254. package/dist/SchemaIssue.js +59 -263
  255. package/dist/SchemaIssue.js.map +1 -1
  256. package/dist/SchemaParser.js +2 -9
  257. package/dist/SchemaParser.js.map +1 -1
  258. package/dist/SchemaRepresentation.d.ts +1276 -172
  259. package/dist/SchemaRepresentation.d.ts.map +1 -1
  260. package/dist/SchemaRepresentation.js +1371 -29
  261. package/dist/SchemaRepresentation.js.map +1 -1
  262. package/dist/SchemaTransformation.d.ts +49 -16
  263. package/dist/SchemaTransformation.d.ts.map +1 -1
  264. package/dist/SchemaTransformation.js +75 -98
  265. package/dist/SchemaTransformation.js.map +1 -1
  266. package/dist/Scope.d.ts +9 -2
  267. package/dist/Scope.d.ts.map +1 -1
  268. package/dist/Scope.js.map +1 -1
  269. package/dist/ScopedCache.d.ts.map +1 -1
  270. package/dist/ScopedCache.js +10 -3
  271. package/dist/ScopedCache.js.map +1 -1
  272. package/dist/Sink.d.ts +9 -4
  273. package/dist/Sink.d.ts.map +1 -1
  274. package/dist/Sink.js +49 -31
  275. package/dist/Sink.js.map +1 -1
  276. package/dist/StandardSchema.d.ts +125 -0
  277. package/dist/StandardSchema.d.ts.map +1 -0
  278. package/dist/StandardSchema.js +9 -0
  279. package/dist/StandardSchema.js.map +1 -0
  280. package/dist/Stream.d.ts +221 -35
  281. package/dist/Stream.d.ts.map +1 -1
  282. package/dist/Stream.js +168 -84
  283. package/dist/Stream.js.map +1 -1
  284. package/dist/String.d.ts +16 -6
  285. package/dist/String.d.ts.map +1 -1
  286. package/dist/String.js +12 -5
  287. package/dist/String.js.map +1 -1
  288. package/dist/Struct.d.ts.map +1 -1
  289. package/dist/Struct.js +7 -4
  290. package/dist/Struct.js.map +1 -1
  291. package/dist/SynchronizedRef.d.ts +3 -2
  292. package/dist/SynchronizedRef.d.ts.map +1 -1
  293. package/dist/SynchronizedRef.js.map +1 -1
  294. package/dist/Terminal.d.ts +3 -3
  295. package/dist/Terminal.d.ts.map +1 -1
  296. package/dist/Terminal.js +3 -3
  297. package/dist/Terminal.js.map +1 -1
  298. package/dist/Tracer.d.ts +27 -7
  299. package/dist/Tracer.d.ts.map +1 -1
  300. package/dist/Tracer.js +38 -13
  301. package/dist/Tracer.js.map +1 -1
  302. package/dist/Trie.d.ts +1 -1
  303. package/dist/Trie.d.ts.map +1 -1
  304. package/dist/Tuple.d.ts +2 -1
  305. package/dist/Tuple.d.ts.map +1 -1
  306. package/dist/Tuple.js.map +1 -1
  307. package/dist/TxChunk.d.ts +1 -1
  308. package/dist/TxChunk.d.ts.map +1 -1
  309. package/dist/TxChunk.js +1 -1
  310. package/dist/TxChunk.js.map +1 -1
  311. package/dist/TxDeferred.d.ts +1 -1
  312. package/dist/TxDeferred.d.ts.map +1 -1
  313. package/dist/TxDeferred.js +1 -1
  314. package/dist/TxDeferred.js.map +1 -1
  315. package/dist/TxHashMap.d.ts +1 -1
  316. package/dist/TxHashMap.d.ts.map +1 -1
  317. package/dist/TxHashMap.js +1 -1
  318. package/dist/TxHashMap.js.map +1 -1
  319. package/dist/TxHashSet.d.ts +1 -1
  320. package/dist/TxHashSet.d.ts.map +1 -1
  321. package/dist/TxHashSet.js +1 -1
  322. package/dist/TxHashSet.js.map +1 -1
  323. package/dist/TxPriorityQueue.d.ts +1 -1
  324. package/dist/TxPriorityQueue.d.ts.map +1 -1
  325. package/dist/TxPriorityQueue.js +1 -1
  326. package/dist/TxPriorityQueue.js.map +1 -1
  327. package/dist/TxPubSub.d.ts +1 -1
  328. package/dist/TxPubSub.d.ts.map +1 -1
  329. package/dist/TxPubSub.js +1 -1
  330. package/dist/TxPubSub.js.map +1 -1
  331. package/dist/TxQueue.d.ts +9 -9
  332. package/dist/TxQueue.d.ts.map +1 -1
  333. package/dist/TxQueue.js +93 -86
  334. package/dist/TxQueue.js.map +1 -1
  335. package/dist/TxReentrantLock.d.ts +29 -1
  336. package/dist/TxReentrantLock.d.ts.map +1 -1
  337. package/dist/TxReentrantLock.js +29 -1
  338. package/dist/TxReentrantLock.js.map +1 -1
  339. package/dist/TxRef.d.ts +1 -1
  340. package/dist/TxRef.d.ts.map +1 -1
  341. package/dist/TxRef.js +1 -1
  342. package/dist/TxRef.js.map +1 -1
  343. package/dist/TxSemaphore.d.ts +1 -1
  344. package/dist/TxSemaphore.d.ts.map +1 -1
  345. package/dist/TxSemaphore.js +1 -1
  346. package/dist/TxSemaphore.js.map +1 -1
  347. package/dist/TxSubscriptionRef.d.ts +1 -1
  348. package/dist/TxSubscriptionRef.d.ts.map +1 -1
  349. package/dist/TxSubscriptionRef.js +1 -1
  350. package/dist/TxSubscriptionRef.js.map +1 -1
  351. package/dist/Types.d.ts +33 -19
  352. package/dist/Types.d.ts.map +1 -1
  353. package/dist/Utils.d.ts.map +1 -1
  354. package/dist/Utils.js +2 -1
  355. package/dist/Utils.js.map +1 -1
  356. package/dist/index.d.ts +8 -0
  357. package/dist/index.d.ts.map +1 -1
  358. package/dist/index.js +8 -0
  359. package/dist/index.js.map +1 -1
  360. package/dist/internal/arbitrary/model.d.ts +2 -0
  361. package/dist/internal/arbitrary/model.d.ts.map +1 -0
  362. package/dist/internal/arbitrary/model.js +495 -0
  363. package/dist/internal/arbitrary/model.js.map +1 -0
  364. package/dist/internal/arbitrary/regexp.d.ts +2 -0
  365. package/dist/internal/arbitrary/regexp.d.ts.map +1 -0
  366. package/dist/internal/arbitrary/regexp.js +789 -0
  367. package/dist/internal/arbitrary/regexp.js.map +1 -0
  368. package/dist/internal/arbitrary/runner.d.ts +2 -0
  369. package/dist/internal/arbitrary/runner.d.ts.map +1 -0
  370. package/dist/internal/arbitrary/runner.js +496 -0
  371. package/dist/internal/arbitrary/runner.js.map +1 -0
  372. package/dist/internal/arbitrary/schema.d.ts.map +1 -0
  373. package/dist/internal/arbitrary/schema.js +1340 -0
  374. package/dist/internal/arbitrary/schema.js.map +1 -0
  375. package/dist/internal/core.js +27 -13
  376. package/dist/internal/core.js.map +1 -1
  377. package/dist/internal/count.d.ts +2 -0
  378. package/dist/internal/count.d.ts.map +1 -0
  379. package/dist/internal/count.js +14 -0
  380. package/dist/internal/count.js.map +1 -0
  381. package/dist/internal/dateTime.js +4 -10
  382. package/dist/internal/dateTime.js.map +1 -1
  383. package/dist/internal/effect.js +416 -258
  384. package/dist/internal/effect.js.map +1 -1
  385. package/dist/internal/graph.js +3 -1
  386. package/dist/internal/graph.js.map +1 -1
  387. package/dist/internal/hashMap.js +5 -3
  388. package/dist/internal/hashMap.js.map +1 -1
  389. package/dist/internal/hashSet.js +1 -1
  390. package/dist/internal/hashSet.js.map +1 -1
  391. package/dist/internal/matcher.js +1 -1
  392. package/dist/internal/matcher.js.map +1 -1
  393. package/dist/internal/metric.js +1 -1
  394. package/dist/internal/metric.js.map +1 -1
  395. package/dist/internal/option.js +6 -5
  396. package/dist/internal/option.js.map +1 -1
  397. package/dist/internal/random.js +17 -0
  398. package/dist/internal/random.js.map +1 -1
  399. package/dist/internal/rcRef.js +10 -7
  400. package/dist/internal/rcRef.js.map +1 -1
  401. package/dist/internal/references.js +1 -0
  402. package/dist/internal/references.js.map +1 -1
  403. package/dist/internal/request.js +13 -6
  404. package/dist/internal/request.js.map +1 -1
  405. package/dist/internal/result.js +11 -9
  406. package/dist/internal/result.js.map +1 -1
  407. package/dist/internal/schema/annotations.js +1 -1
  408. package/dist/internal/schema/annotations.js.map +1 -1
  409. package/dist/internal/schema/fromJsonSchemaDocument.js +238 -132
  410. package/dist/internal/schema/fromJsonSchemaDocument.js.map +1 -1
  411. package/dist/internal/schema/fromRepresentation.js +5 -5
  412. package/dist/internal/schema/fromRepresentation.js.map +1 -1
  413. package/dist/internal/schema/make.d.ts +2 -0
  414. package/dist/internal/schema/make.d.ts.map +1 -0
  415. package/dist/internal/schema/{schema.js → make.js} +1 -25
  416. package/dist/internal/schema/make.js.map +1 -0
  417. package/dist/internal/schema/parser.d.ts +0 -12
  418. package/dist/internal/schema/parser.d.ts.map +1 -1
  419. package/dist/internal/schema/parser.js +7 -0
  420. package/dist/internal/schema/parser.js.map +1 -1
  421. package/dist/internal/schema/standardSchema.d.ts +2 -0
  422. package/dist/internal/schema/standardSchema.d.ts.map +1 -0
  423. package/dist/internal/schema/standardSchema.js +112 -0
  424. package/dist/internal/schema/standardSchema.js.map +1 -0
  425. package/dist/internal/schema/toCodeDocument.js +34 -22
  426. package/dist/internal/schema/toCodeDocument.js.map +1 -1
  427. package/dist/internal/schema/toCodec.d.ts +2 -0
  428. package/dist/internal/schema/toCodec.d.ts.map +1 -0
  429. package/dist/internal/schema/toCodec.js +242 -0
  430. package/dist/internal/schema/toCodec.js.map +1 -0
  431. package/dist/internal/schema/toDifferJsonPatch.d.ts +2 -0
  432. package/dist/internal/schema/toDifferJsonPatch.d.ts.map +1 -0
  433. package/dist/internal/schema/toDifferJsonPatch.js +20 -0
  434. package/dist/internal/schema/toDifferJsonPatch.js.map +1 -0
  435. package/dist/internal/schema/toEncoderXml.d.ts +2 -0
  436. package/dist/internal/schema/toEncoderXml.d.ts.map +1 -0
  437. package/dist/internal/schema/toEncoderXml.js +104 -0
  438. package/dist/internal/schema/toEncoderXml.js.map +1 -0
  439. package/dist/internal/schema/toEquivalence.js +66 -0
  440. package/dist/internal/schema/toEquivalence.js.map +1 -1
  441. package/dist/internal/schema/toFormatter.d.ts +2 -0
  442. package/dist/internal/schema/toFormatter.d.ts.map +1 -0
  443. package/dist/internal/schema/toFormatter.js +227 -0
  444. package/dist/internal/schema/toFormatter.js.map +1 -0
  445. package/dist/internal/schema/toIso.d.ts +2 -0
  446. package/dist/internal/schema/toIso.d.ts.map +1 -0
  447. package/dist/internal/schema/toIso.js +17 -0
  448. package/dist/internal/schema/toIso.js.map +1 -0
  449. package/dist/internal/schema/toJsonSchemaDocument.js +122 -71
  450. package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -1
  451. package/dist/internal/schema/toRepresentation.js +3 -1
  452. package/dist/internal/schema/toRepresentation.js.map +1 -1
  453. package/dist/internal/schemaError.d.ts +4 -0
  454. package/dist/internal/schemaError.d.ts.map +1 -0
  455. package/dist/internal/schemaError.js +6 -0
  456. package/dist/internal/schemaError.js.map +1 -0
  457. package/dist/internal/stream.js +5 -6
  458. package/dist/internal/stream.js.map +1 -1
  459. package/dist/internal/tracer.d.ts +1 -3
  460. package/dist/internal/tracer.d.ts.map +1 -1
  461. package/dist/internal/tracer.js +6 -0
  462. package/dist/internal/tracer.js.map +1 -1
  463. package/dist/internal/trie.js +2 -2
  464. package/dist/internal/trie.js.map +1 -1
  465. package/dist/internal/uuid.d.ts +1 -2
  466. package/dist/internal/uuid.d.ts.map +1 -1
  467. package/dist/internal/uuid.js +2 -0
  468. package/dist/internal/uuid.js.map +1 -1
  469. package/dist/testing/TestSchema.d.ts +9 -11
  470. package/dist/testing/TestSchema.d.ts.map +1 -1
  471. package/dist/testing/TestSchema.js +20 -18
  472. package/dist/testing/TestSchema.js.map +1 -1
  473. package/dist/testing/index.d.ts +0 -4
  474. package/dist/testing/index.d.ts.map +1 -1
  475. package/dist/testing/index.js +0 -4
  476. package/dist/testing/index.js.map +1 -1
  477. package/dist/unstable/ai/AiError.d.ts +98 -23
  478. package/dist/unstable/ai/AiError.d.ts.map +1 -1
  479. package/dist/unstable/ai/AiError.js +98 -6
  480. package/dist/unstable/ai/AiError.js.map +1 -1
  481. package/dist/unstable/ai/AnthropicStructuredOutput.d.ts +1 -1
  482. package/dist/unstable/ai/AnthropicStructuredOutput.d.ts.map +1 -1
  483. package/dist/unstable/ai/AnthropicStructuredOutput.js +5 -16
  484. package/dist/unstable/ai/AnthropicStructuredOutput.js.map +1 -1
  485. package/dist/unstable/ai/Chat.d.ts +27 -32
  486. package/dist/unstable/ai/Chat.d.ts.map +1 -1
  487. package/dist/unstable/ai/Chat.js +10 -13
  488. package/dist/unstable/ai/Chat.js.map +1 -1
  489. package/dist/unstable/ai/EmbeddingModel.d.ts +23 -16
  490. package/dist/unstable/ai/EmbeddingModel.d.ts.map +1 -1
  491. package/dist/unstable/ai/EmbeddingModel.js +13 -11
  492. package/dist/unstable/ai/EmbeddingModel.js.map +1 -1
  493. package/dist/unstable/ai/LanguageModel.d.ts +48 -37
  494. package/dist/unstable/ai/LanguageModel.d.ts.map +1 -1
  495. package/dist/unstable/ai/LanguageModel.js +150 -47
  496. package/dist/unstable/ai/LanguageModel.js.map +1 -1
  497. package/dist/unstable/ai/McpServer.d.ts +2 -2
  498. package/dist/unstable/ai/McpServer.d.ts.map +1 -1
  499. package/dist/unstable/ai/McpServer.js +87 -78
  500. package/dist/unstable/ai/McpServer.js.map +1 -1
  501. package/dist/unstable/ai/OpenAiStructuredOutput.d.ts +1 -1
  502. package/dist/unstable/ai/OpenAiStructuredOutput.d.ts.map +1 -1
  503. package/dist/unstable/ai/OpenAiStructuredOutput.js +3 -14
  504. package/dist/unstable/ai/OpenAiStructuredOutput.js.map +1 -1
  505. package/dist/unstable/ai/Prompt.d.ts +2 -2
  506. package/dist/unstable/ai/Prompt.d.ts.map +1 -1
  507. package/dist/unstable/ai/Prompt.js +15 -4
  508. package/dist/unstable/ai/Prompt.js.map +1 -1
  509. package/dist/unstable/ai/Response.d.ts +37 -94
  510. package/dist/unstable/ai/Response.d.ts.map +1 -1
  511. package/dist/unstable/ai/Response.js +46 -96
  512. package/dist/unstable/ai/Response.js.map +1 -1
  513. package/dist/unstable/ai/Tokenizer.js +4 -5
  514. package/dist/unstable/ai/Tokenizer.js.map +1 -1
  515. package/dist/unstable/ai/Tool.d.ts +38 -20
  516. package/dist/unstable/ai/Tool.d.ts.map +1 -1
  517. package/dist/unstable/ai/Tool.js +27 -1
  518. package/dist/unstable/ai/Tool.js.map +1 -1
  519. package/dist/unstable/ai/Toolkit.d.ts +1 -1
  520. package/dist/unstable/ai/Toolkit.d.ts.map +1 -1
  521. package/dist/unstable/ai/Toolkit.js +30 -18
  522. package/dist/unstable/ai/Toolkit.js.map +1 -1
  523. package/dist/unstable/ai/internal/codec-transformer.js +2 -2
  524. package/dist/unstable/ai/internal/codec-transformer.js.map +1 -1
  525. package/dist/unstable/ai/internal/structured-output.js +28 -5
  526. package/dist/unstable/ai/internal/structured-output.js.map +1 -1
  527. package/dist/unstable/arbitrary/Arbitrary.d.ts +626 -0
  528. package/dist/unstable/arbitrary/Arbitrary.d.ts.map +1 -0
  529. package/dist/unstable/arbitrary/Arbitrary.js +238 -0
  530. package/dist/unstable/arbitrary/Arbitrary.js.map +1 -0
  531. package/dist/unstable/arbitrary/index.d.ts +8 -0
  532. package/dist/unstable/arbitrary/index.d.ts.map +1 -0
  533. package/dist/unstable/arbitrary/index.js +9 -0
  534. package/dist/unstable/arbitrary/index.js.map +1 -0
  535. package/dist/unstable/cli/Argument.d.ts +104 -108
  536. package/dist/unstable/cli/Argument.d.ts.map +1 -1
  537. package/dist/unstable/cli/Argument.js +56 -57
  538. package/dist/unstable/cli/Argument.js.map +1 -1
  539. package/dist/unstable/cli/CliError.d.ts +2 -0
  540. package/dist/unstable/cli/CliError.d.ts.map +1 -1
  541. package/dist/unstable/cli/CliError.js +2 -0
  542. package/dist/unstable/cli/CliError.js.map +1 -1
  543. package/dist/unstable/cli/CliOutput.js +27 -4
  544. package/dist/unstable/cli/CliOutput.js.map +1 -1
  545. package/dist/unstable/cli/Command.d.ts +73 -73
  546. package/dist/unstable/cli/Command.d.ts.map +1 -1
  547. package/dist/unstable/cli/Command.js +22 -22
  548. package/dist/unstable/cli/Command.js.map +1 -1
  549. package/dist/unstable/cli/Completions.d.ts +4 -4
  550. package/dist/unstable/cli/Completions.d.ts.map +1 -1
  551. package/dist/unstable/cli/Flag.d.ts +150 -161
  552. package/dist/unstable/cli/Flag.d.ts.map +1 -1
  553. package/dist/unstable/cli/Flag.js +79 -90
  554. package/dist/unstable/cli/Flag.js.map +1 -1
  555. package/dist/unstable/cli/GlobalFlag.d.ts +3 -3
  556. package/dist/unstable/cli/GlobalFlag.js +13 -13
  557. package/dist/unstable/cli/GlobalFlag.js.map +1 -1
  558. package/dist/unstable/cli/Param.d.ts +118 -126
  559. package/dist/unstable/cli/Param.d.ts.map +1 -1
  560. package/dist/unstable/cli/Param.js +104 -113
  561. package/dist/unstable/cli/Param.js.map +1 -1
  562. package/dist/unstable/cli/Primitive.d.ts +69 -58
  563. package/dist/unstable/cli/Primitive.d.ts.map +1 -1
  564. package/dist/unstable/cli/Primitive.js +65 -66
  565. package/dist/unstable/cli/Primitive.js.map +1 -1
  566. package/dist/unstable/cli/Prompt.d.ts +113 -59
  567. package/dist/unstable/cli/Prompt.d.ts.map +1 -1
  568. package/dist/unstable/cli/Prompt.js +391 -327
  569. package/dist/unstable/cli/Prompt.js.map +1 -1
  570. package/dist/unstable/cli/internal/completions/bash.js +109 -38
  571. package/dist/unstable/cli/internal/completions/bash.js.map +1 -1
  572. package/dist/unstable/cli/internal/completions/descriptor.js +23 -11
  573. package/dist/unstable/cli/internal/completions/descriptor.js.map +1 -1
  574. package/dist/unstable/cli/internal/completions/fish.js +15 -7
  575. package/dist/unstable/cli/internal/completions/fish.js.map +1 -1
  576. package/dist/unstable/cli/internal/completions/zsh.js +6 -4
  577. package/dist/unstable/cli/internal/completions/zsh.js.map +1 -1
  578. package/dist/unstable/cli/internal/config.js +4 -4
  579. package/dist/unstable/cli/internal/parser.js +1 -1
  580. package/dist/unstable/cli/internal/parser.js.map +1 -1
  581. package/dist/unstable/cli/internal/wizard.d.ts +5 -1
  582. package/dist/unstable/cli/internal/wizard.d.ts.map +1 -1
  583. package/dist/unstable/cli/internal/wizard.js +34 -26
  584. package/dist/unstable/cli/internal/wizard.js.map +1 -1
  585. package/dist/unstable/cluster/ClusterSchema.d.ts +13 -0
  586. package/dist/unstable/cluster/ClusterSchema.d.ts.map +1 -1
  587. package/dist/unstable/cluster/ClusterSchema.js +16 -1
  588. package/dist/unstable/cluster/ClusterSchema.js.map +1 -1
  589. package/dist/unstable/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  590. package/dist/unstable/cluster/ClusterWorkflowEngine.js +57 -14
  591. package/dist/unstable/cluster/ClusterWorkflowEngine.js.map +1 -1
  592. package/dist/unstable/cluster/Entity.d.ts.map +1 -1
  593. package/dist/unstable/cluster/Entity.js +2 -0
  594. package/dist/unstable/cluster/Entity.js.map +1 -1
  595. package/dist/unstable/cluster/EntityProxyServer.d.ts +2 -2
  596. package/dist/unstable/cluster/EntityProxyServer.d.ts.map +1 -1
  597. package/dist/unstable/cluster/EntityProxyServer.js.map +1 -1
  598. package/dist/unstable/cluster/Envelope.d.ts +22 -5
  599. package/dist/unstable/cluster/Envelope.d.ts.map +1 -1
  600. package/dist/unstable/cluster/Envelope.js +23 -3
  601. package/dist/unstable/cluster/Envelope.js.map +1 -1
  602. package/dist/unstable/cluster/HttpRunner.d.ts.map +1 -1
  603. package/dist/unstable/cluster/HttpRunner.js +32 -13
  604. package/dist/unstable/cluster/HttpRunner.js.map +1 -1
  605. package/dist/unstable/cluster/Message.d.ts +17 -5
  606. package/dist/unstable/cluster/Message.d.ts.map +1 -1
  607. package/dist/unstable/cluster/Message.js +21 -8
  608. package/dist/unstable/cluster/Message.js.map +1 -1
  609. package/dist/unstable/cluster/MessageStorage.d.ts +34 -4
  610. package/dist/unstable/cluster/MessageStorage.d.ts.map +1 -1
  611. package/dist/unstable/cluster/MessageStorage.js +33 -12
  612. package/dist/unstable/cluster/MessageStorage.js.map +1 -1
  613. package/dist/unstable/cluster/Reply.d.ts +5 -4
  614. package/dist/unstable/cluster/Reply.d.ts.map +1 -1
  615. package/dist/unstable/cluster/Reply.js +21 -12
  616. package/dist/unstable/cluster/Reply.js.map +1 -1
  617. package/dist/unstable/cluster/RunnerServer.d.ts +1 -1
  618. package/dist/unstable/cluster/RunnerServer.d.ts.map +1 -1
  619. package/dist/unstable/cluster/RunnerServer.js +12 -6
  620. package/dist/unstable/cluster/RunnerServer.js.map +1 -1
  621. package/dist/unstable/cluster/Runners.d.ts +11 -5
  622. package/dist/unstable/cluster/Runners.d.ts.map +1 -1
  623. package/dist/unstable/cluster/Runners.js +56 -35
  624. package/dist/unstable/cluster/Runners.js.map +1 -1
  625. package/dist/unstable/cluster/Sharding.d.ts +1 -1
  626. package/dist/unstable/cluster/Sharding.d.ts.map +1 -1
  627. package/dist/unstable/cluster/Sharding.js +32 -17
  628. package/dist/unstable/cluster/Sharding.js.map +1 -1
  629. package/dist/unstable/cluster/ShardingConfig.js +23 -23
  630. package/dist/unstable/cluster/ShardingConfig.js.map +1 -1
  631. package/dist/unstable/cluster/SocketRunner.d.ts +2 -2
  632. package/dist/unstable/cluster/SocketRunner.d.ts.map +1 -1
  633. package/dist/unstable/cluster/SocketRunner.js +4 -3
  634. package/dist/unstable/cluster/SocketRunner.js.map +1 -1
  635. package/dist/unstable/cluster/SqlMessageStorage.js +11 -8
  636. package/dist/unstable/cluster/SqlMessageStorage.js.map +1 -1
  637. package/dist/unstable/cluster/SqlRunnerStorage.d.ts.map +1 -1
  638. package/dist/unstable/cluster/SqlRunnerStorage.js +11 -4
  639. package/dist/unstable/cluster/SqlRunnerStorage.js.map +1 -1
  640. package/dist/unstable/cluster/internal/clusterAbandon.d.ts +5 -0
  641. package/dist/unstable/cluster/internal/clusterAbandon.d.ts.map +1 -0
  642. package/dist/unstable/cluster/internal/clusterAbandon.js +9 -0
  643. package/dist/unstable/cluster/internal/clusterAbandon.js.map +1 -0
  644. package/dist/unstable/cluster/internal/entityManager.js +10 -6
  645. package/dist/unstable/cluster/internal/entityManager.js.map +1 -1
  646. package/dist/unstable/cluster/internal/interruptors.js +30 -1
  647. package/dist/unstable/cluster/internal/interruptors.js.map +1 -1
  648. package/dist/unstable/cluster/internal/resourceRef.js +12 -7
  649. package/dist/unstable/cluster/internal/resourceRef.js.map +1 -1
  650. package/dist/unstable/devtools/DevToolsClient.d.ts.map +1 -1
  651. package/dist/unstable/devtools/DevToolsClient.js +12 -7
  652. package/dist/unstable/devtools/DevToolsClient.js.map +1 -1
  653. package/dist/unstable/encoding/Ini.d.ts +2 -0
  654. package/dist/unstable/encoding/Ini.d.ts.map +1 -1
  655. package/dist/unstable/encoding/Ini.js +2 -0
  656. package/dist/unstable/encoding/Ini.js.map +1 -1
  657. package/dist/unstable/encoding/SchemaBinary.d.ts +273 -0
  658. package/dist/unstable/encoding/SchemaBinary.d.ts.map +1 -0
  659. package/dist/unstable/encoding/SchemaBinary.js +4573 -0
  660. package/dist/unstable/encoding/SchemaBinary.js.map +1 -0
  661. package/dist/unstable/encoding/Sse.js +1 -1
  662. package/dist/unstable/encoding/Sse.js.map +1 -1
  663. package/dist/unstable/encoding/Toml.d.ts +2 -0
  664. package/dist/unstable/encoding/Toml.d.ts.map +1 -1
  665. package/dist/unstable/encoding/Toml.js +6 -4
  666. package/dist/unstable/encoding/Toml.js.map +1 -1
  667. package/dist/unstable/encoding/Yaml.d.ts +2 -0
  668. package/dist/unstable/encoding/Yaml.d.ts.map +1 -1
  669. package/dist/unstable/encoding/Yaml.js +16 -5
  670. package/dist/unstable/encoding/Yaml.js.map +1 -1
  671. package/dist/unstable/encoding/index.d.ts +2 -2
  672. package/dist/unstable/encoding/index.d.ts.map +1 -1
  673. package/dist/unstable/encoding/index.js +2 -2
  674. package/dist/unstable/encoding/index.js.map +1 -1
  675. package/dist/unstable/eventlog/Event.d.ts +5 -5
  676. package/dist/unstable/eventlog/Event.d.ts.map +1 -1
  677. package/dist/unstable/eventlog/Event.js +3 -3
  678. package/dist/unstable/eventlog/Event.js.map +1 -1
  679. package/dist/unstable/eventlog/EventJournal.d.ts +15 -9
  680. package/dist/unstable/eventlog/EventJournal.d.ts.map +1 -1
  681. package/dist/unstable/eventlog/EventJournal.js +26 -12
  682. package/dist/unstable/eventlog/EventJournal.js.map +1 -1
  683. package/dist/unstable/eventlog/EventLog.d.ts +1 -1
  684. package/dist/unstable/eventlog/EventLog.d.ts.map +1 -1
  685. package/dist/unstable/eventlog/EventLog.js +13 -9
  686. package/dist/unstable/eventlog/EventLog.js.map +1 -1
  687. package/dist/unstable/eventlog/EventLogMessage.d.ts +11 -5
  688. package/dist/unstable/eventlog/EventLogMessage.d.ts.map +1 -1
  689. package/dist/unstable/eventlog/EventLogMessage.js +25 -15
  690. package/dist/unstable/eventlog/EventLogMessage.js.map +1 -1
  691. package/dist/unstable/eventlog/EventLogRemote.d.ts +7 -1
  692. package/dist/unstable/eventlog/EventLogRemote.d.ts.map +1 -1
  693. package/dist/unstable/eventlog/EventLogRemote.js +13 -3
  694. package/dist/unstable/eventlog/EventLogRemote.js.map +1 -1
  695. package/dist/unstable/eventlog/EventLogServerUnencrypted.js +2 -2
  696. package/dist/unstable/eventlog/EventLogServerUnencrypted.js.map +1 -1
  697. package/dist/unstable/eventlog/SqlEventJournal.d.ts +0 -10
  698. package/dist/unstable/eventlog/SqlEventJournal.d.ts.map +1 -1
  699. package/dist/unstable/eventlog/SqlEventJournal.js +29 -14
  700. package/dist/unstable/eventlog/SqlEventJournal.js.map +1 -1
  701. package/dist/unstable/eventlog/SqlEventLogServerUnencrypted.d.ts.map +1 -1
  702. package/dist/unstable/eventlog/SqlEventLogServerUnencrypted.js +5 -1
  703. package/dist/unstable/eventlog/SqlEventLogServerUnencrypted.js.map +1 -1
  704. package/dist/unstable/http/Cookies.d.ts +1 -45
  705. package/dist/unstable/http/Cookies.d.ts.map +1 -1
  706. package/dist/unstable/http/Cookies.js +2 -64
  707. package/dist/unstable/http/Cookies.js.map +1 -1
  708. package/dist/unstable/http/FetchHttpClient.js +1 -1
  709. package/dist/unstable/http/FetchHttpClient.js.map +1 -1
  710. package/dist/unstable/http/FindMyWay/internal/router.js +124 -33
  711. package/dist/unstable/http/FindMyWay/internal/router.js.map +1 -1
  712. package/dist/unstable/http/FindMyWay.d.ts +15 -5
  713. package/dist/unstable/http/FindMyWay.d.ts.map +1 -1
  714. package/dist/unstable/http/FindMyWay.js +3 -1
  715. package/dist/unstable/http/FindMyWay.js.map +1 -1
  716. package/dist/unstable/http/Headers.d.ts +0 -22
  717. package/dist/unstable/http/Headers.d.ts.map +1 -1
  718. package/dist/unstable/http/Headers.js +3 -34
  719. package/dist/unstable/http/Headers.js.map +1 -1
  720. package/dist/unstable/http/HttpBody.d.ts +41 -10
  721. package/dist/unstable/http/HttpBody.d.ts.map +1 -1
  722. package/dist/unstable/http/HttpBody.js +64 -10
  723. package/dist/unstable/http/HttpBody.js.map +1 -1
  724. package/dist/unstable/http/HttpClient.d.ts +1 -1
  725. package/dist/unstable/http/HttpClient.d.ts.map +1 -1
  726. package/dist/unstable/http/HttpClient.js +28 -18
  727. package/dist/unstable/http/HttpClient.js.map +1 -1
  728. package/dist/unstable/http/HttpClientRequest.d.ts +28 -6
  729. package/dist/unstable/http/HttpClientRequest.d.ts.map +1 -1
  730. package/dist/unstable/http/HttpClientRequest.js +8 -19
  731. package/dist/unstable/http/HttpClientRequest.js.map +1 -1
  732. package/dist/unstable/http/HttpClientResponse.d.ts +6 -1
  733. package/dist/unstable/http/HttpClientResponse.d.ts.map +1 -1
  734. package/dist/unstable/http/HttpClientResponse.js +10 -6
  735. package/dist/unstable/http/HttpClientResponse.js.map +1 -1
  736. package/dist/unstable/http/HttpEffect.d.ts +16 -0
  737. package/dist/unstable/http/HttpEffect.d.ts.map +1 -1
  738. package/dist/unstable/http/HttpEffect.js +121 -65
  739. package/dist/unstable/http/HttpEffect.js.map +1 -1
  740. package/dist/unstable/http/HttpIncomingMessage.d.ts +3 -3
  741. package/dist/unstable/http/HttpIncomingMessage.d.ts.map +1 -1
  742. package/dist/unstable/http/HttpIncomingMessage.js +1 -13
  743. package/dist/unstable/http/HttpIncomingMessage.js.map +1 -1
  744. package/dist/unstable/http/HttpMiddleware.d.ts +1 -1
  745. package/dist/unstable/http/HttpMiddleware.d.ts.map +1 -1
  746. package/dist/unstable/http/HttpMiddleware.js +29 -21
  747. package/dist/unstable/http/HttpMiddleware.js.map +1 -1
  748. package/dist/unstable/http/HttpPlatform.d.ts +12 -11
  749. package/dist/unstable/http/HttpPlatform.d.ts.map +1 -1
  750. package/dist/unstable/http/HttpPlatform.js +36 -10
  751. package/dist/unstable/http/HttpPlatform.js.map +1 -1
  752. package/dist/unstable/http/HttpRouter.d.ts +5 -1
  753. package/dist/unstable/http/HttpRouter.d.ts.map +1 -1
  754. package/dist/unstable/http/HttpRouter.js +22 -8
  755. package/dist/unstable/http/HttpRouter.js.map +1 -1
  756. package/dist/unstable/http/HttpServer.d.ts +11 -42
  757. package/dist/unstable/http/HttpServer.d.ts.map +1 -1
  758. package/dist/unstable/http/HttpServer.js +16 -20
  759. package/dist/unstable/http/HttpServer.js.map +1 -1
  760. package/dist/unstable/http/HttpServerRequest.d.ts.map +1 -1
  761. package/dist/unstable/http/HttpServerRequest.js +11 -11
  762. package/dist/unstable/http/HttpServerRequest.js.map +1 -1
  763. package/dist/unstable/http/HttpServerRespondable.js +1 -1
  764. package/dist/unstable/http/HttpServerRespondable.js.map +1 -1
  765. package/dist/unstable/http/HttpServerResponse.d.ts +9 -13
  766. package/dist/unstable/http/HttpServerResponse.d.ts.map +1 -1
  767. package/dist/unstable/http/HttpServerResponse.js +34 -44
  768. package/dist/unstable/http/HttpServerResponse.js.map +1 -1
  769. package/dist/unstable/http/HttpStaticServer.d.ts +2 -2
  770. package/dist/unstable/http/HttpStaticServer.d.ts.map +1 -1
  771. package/dist/unstable/http/HttpStaticServer.js +19 -19
  772. package/dist/unstable/http/HttpStaticServer.js.map +1 -1
  773. package/dist/unstable/http/Mime.d.ts +28 -0
  774. package/dist/unstable/http/Mime.d.ts.map +1 -0
  775. package/dist/unstable/http/Mime.js +72 -0
  776. package/dist/unstable/http/Mime.js.map +1 -0
  777. package/dist/unstable/http/Multipart.d.ts +22 -9
  778. package/dist/unstable/http/Multipart.d.ts.map +1 -1
  779. package/dist/unstable/http/Multipart.js +26 -10
  780. package/dist/unstable/http/Multipart.js.map +1 -1
  781. package/dist/unstable/http/MultipartParser/internal/multipart.d.ts +1 -1
  782. package/dist/unstable/http/MultipartParser/internal/multipart.d.ts.map +1 -1
  783. package/dist/unstable/http/MultipartParser/internal/multipart.js +8 -3
  784. package/dist/unstable/http/MultipartParser/internal/multipart.js.map +1 -1
  785. package/dist/unstable/http/MultipartParser.d.ts +4 -3
  786. package/dist/unstable/http/MultipartParser.d.ts.map +1 -1
  787. package/dist/unstable/http/MultipartParser.js.map +1 -1
  788. package/dist/unstable/http/UrlParams.d.ts +0 -97
  789. package/dist/unstable/http/UrlParams.d.ts.map +1 -1
  790. package/dist/unstable/http/UrlParams.js +3 -104
  791. package/dist/unstable/http/UrlParams.js.map +1 -1
  792. package/dist/unstable/http/index.d.ts +4 -0
  793. package/dist/unstable/http/index.d.ts.map +1 -1
  794. package/dist/unstable/http/index.js +4 -0
  795. package/dist/unstable/http/index.js.map +1 -1
  796. package/dist/unstable/http/internal/compression.js +8 -11
  797. package/dist/unstable/http/internal/compression.js.map +1 -1
  798. package/dist/unstable/http/internal/headers.d.ts +2 -0
  799. package/dist/unstable/http/internal/headers.d.ts.map +1 -0
  800. package/dist/unstable/http/internal/headers.js +5 -0
  801. package/dist/unstable/http/internal/headers.js.map +1 -0
  802. package/dist/unstable/http/internal/httpBody.js +8 -0
  803. package/dist/unstable/http/internal/httpBody.js.map +1 -1
  804. package/dist/unstable/http/internal/mimeTypes.d.ts +361 -0
  805. package/dist/unstable/http/internal/mimeTypes.d.ts.map +1 -0
  806. package/dist/unstable/http/internal/mimeTypes.js +363 -0
  807. package/dist/unstable/http/internal/mimeTypes.js.map +1 -0
  808. package/dist/unstable/httpapi/HttpApiBuilder.d.ts +13 -0
  809. package/dist/unstable/httpapi/HttpApiBuilder.d.ts.map +1 -1
  810. package/dist/unstable/httpapi/HttpApiBuilder.js +28 -11
  811. package/dist/unstable/httpapi/HttpApiBuilder.js.map +1 -1
  812. package/dist/unstable/httpapi/HttpApiClient.d.ts +4 -3
  813. package/dist/unstable/httpapi/HttpApiClient.d.ts.map +1 -1
  814. package/dist/unstable/httpapi/HttpApiClient.js +25 -13
  815. package/dist/unstable/httpapi/HttpApiClient.js.map +1 -1
  816. package/dist/unstable/httpapi/HttpApiEndpoint.d.ts +8 -3
  817. package/dist/unstable/httpapi/HttpApiEndpoint.d.ts.map +1 -1
  818. package/dist/unstable/httpapi/HttpApiEndpoint.js +9 -6
  819. package/dist/unstable/httpapi/HttpApiEndpoint.js.map +1 -1
  820. package/dist/unstable/httpapi/HttpApiError.d.ts.map +1 -1
  821. package/dist/unstable/httpapi/HttpApiError.js +3 -1
  822. package/dist/unstable/httpapi/HttpApiError.js.map +1 -1
  823. package/dist/unstable/httpapi/HttpApiMiddleware.d.ts.map +1 -1
  824. package/dist/unstable/httpapi/HttpApiMiddleware.js +7 -5
  825. package/dist/unstable/httpapi/HttpApiMiddleware.js.map +1 -1
  826. package/dist/unstable/httpapi/HttpApiScalar.d.ts.map +1 -1
  827. package/dist/unstable/httpapi/HttpApiScalar.js +15 -12
  828. package/dist/unstable/httpapi/HttpApiScalar.js.map +1 -1
  829. package/dist/unstable/httpapi/HttpApiSchema.d.ts +12 -0
  830. package/dist/unstable/httpapi/HttpApiSchema.d.ts.map +1 -1
  831. package/dist/unstable/httpapi/HttpApiSchema.js +8 -10
  832. package/dist/unstable/httpapi/HttpApiSchema.js.map +1 -1
  833. package/dist/unstable/httpapi/HttpApiSwagger.d.ts.map +1 -1
  834. package/dist/unstable/httpapi/HttpApiSwagger.js +6 -3
  835. package/dist/unstable/httpapi/HttpApiSwagger.js.map +1 -1
  836. package/dist/unstable/httpapi/HttpApiTest.d.ts.map +1 -1
  837. package/dist/unstable/httpapi/HttpApiTest.js +8 -2
  838. package/dist/unstable/httpapi/HttpApiTest.js.map +1 -1
  839. package/dist/unstable/httpapi/OpenApi.d.ts.map +1 -1
  840. package/dist/unstable/httpapi/OpenApi.js +31 -20
  841. package/dist/unstable/httpapi/OpenApi.js.map +1 -1
  842. package/dist/unstable/net/IpInterface.d.ts +140 -0
  843. package/dist/unstable/net/IpInterface.d.ts.map +1 -0
  844. package/dist/unstable/net/IpInterface.js +149 -0
  845. package/dist/unstable/net/IpInterface.js.map +1 -0
  846. package/dist/unstable/net/IpNetwork.d.ts +227 -0
  847. package/dist/unstable/net/IpNetwork.d.ts.map +1 -0
  848. package/dist/unstable/net/IpNetwork.js +239 -0
  849. package/dist/unstable/net/IpNetwork.js.map +1 -0
  850. package/dist/unstable/net/NetAddress.d.ts +705 -0
  851. package/dist/unstable/net/NetAddress.d.ts.map +1 -0
  852. package/dist/unstable/net/NetAddress.js +956 -0
  853. package/dist/unstable/net/NetAddress.js.map +1 -0
  854. package/dist/unstable/net/index.d.ts +16 -0
  855. package/dist/unstable/net/index.d.ts.map +1 -0
  856. package/dist/unstable/net/index.js +17 -0
  857. package/dist/unstable/net/index.js.map +1 -0
  858. package/dist/unstable/observability/OtlpExporter.d.ts +1 -0
  859. package/dist/unstable/observability/OtlpExporter.d.ts.map +1 -1
  860. package/dist/unstable/observability/OtlpExporter.js +4 -6
  861. package/dist/unstable/observability/OtlpExporter.js.map +1 -1
  862. package/dist/unstable/observability/OtlpLogger.js +9 -9
  863. package/dist/unstable/observability/OtlpLogger.js.map +1 -1
  864. package/dist/unstable/observability/OtlpMetrics.d.ts.map +1 -1
  865. package/dist/unstable/observability/OtlpMetrics.js +9 -8
  866. package/dist/unstable/observability/OtlpMetrics.js.map +1 -1
  867. package/dist/unstable/observability/OtlpResource.d.ts.map +1 -1
  868. package/dist/unstable/observability/OtlpResource.js +2 -2
  869. package/dist/unstable/observability/OtlpResource.js.map +1 -1
  870. package/dist/unstable/observability/OtlpTracer.d.ts.map +1 -1
  871. package/dist/unstable/observability/OtlpTracer.js +82 -55
  872. package/dist/unstable/observability/OtlpTracer.js.map +1 -1
  873. package/dist/unstable/observability/internal/otlpEnv.d.ts +1 -1
  874. package/dist/unstable/observability/internal/otlpEnv.d.ts.map +1 -1
  875. package/dist/unstable/observability/internal/otlpEnv.js +5 -9
  876. package/dist/unstable/observability/internal/otlpEnv.js.map +1 -1
  877. package/dist/unstable/persistence/PersistedCache.js +1 -1
  878. package/dist/unstable/persistence/PersistedCache.js.map +1 -1
  879. package/dist/unstable/persistence/PersistedQueue.d.ts +114 -14
  880. package/dist/unstable/persistence/PersistedQueue.d.ts.map +1 -1
  881. package/dist/unstable/persistence/PersistedQueue.js +799 -234
  882. package/dist/unstable/persistence/PersistedQueue.js.map +1 -1
  883. package/dist/unstable/persistence/RateLimiter.d.ts +28 -15
  884. package/dist/unstable/persistence/RateLimiter.d.ts.map +1 -1
  885. package/dist/unstable/persistence/RateLimiter.js +33 -41
  886. package/dist/unstable/persistence/RateLimiter.js.map +1 -1
  887. package/dist/unstable/process/ChildProcess.d.ts +8 -2
  888. package/dist/unstable/process/ChildProcess.d.ts.map +1 -1
  889. package/dist/unstable/process/ChildProcess.js +7 -2
  890. package/dist/unstable/process/ChildProcess.js.map +1 -1
  891. package/dist/unstable/process/ChildProcessSpawner.d.ts +1 -1
  892. package/dist/unstable/process/ChildProcessSpawner.d.ts.map +1 -1
  893. package/dist/unstable/process/ChildProcessSpawner.js +1 -1
  894. package/dist/unstable/process/ChildProcessSpawner.js.map +1 -1
  895. package/dist/unstable/reactivity/Atom.d.ts.map +1 -1
  896. package/dist/unstable/reactivity/Atom.js +6 -3
  897. package/dist/unstable/reactivity/Atom.js.map +1 -1
  898. package/dist/unstable/reactivity/AtomHttpApi.d.ts +3 -6
  899. package/dist/unstable/reactivity/AtomHttpApi.d.ts.map +1 -1
  900. package/dist/unstable/reactivity/AtomHttpApi.js +6 -3
  901. package/dist/unstable/reactivity/AtomHttpApi.js.map +1 -1
  902. package/dist/unstable/reactivity/AtomRegistry.js +2 -3
  903. package/dist/unstable/reactivity/AtomRegistry.js.map +1 -1
  904. package/dist/unstable/reactivity/AtomRpc.d.ts +2 -2
  905. package/dist/unstable/reactivity/AtomRpc.d.ts.map +1 -1
  906. package/dist/unstable/reactivity/AtomRpc.js +1 -1
  907. package/dist/unstable/reactivity/AtomRpc.js.map +1 -1
  908. package/dist/unstable/reactivity/Hydration.d.ts +6 -4
  909. package/dist/unstable/reactivity/Hydration.d.ts.map +1 -1
  910. package/dist/unstable/reactivity/Hydration.js +20 -6
  911. package/dist/unstable/reactivity/Hydration.js.map +1 -1
  912. package/dist/unstable/reactivity/Reactivity.d.ts +26 -26
  913. package/dist/unstable/reactivity/Reactivity.d.ts.map +1 -1
  914. package/dist/unstable/reactivity/Reactivity.js +10 -12
  915. package/dist/unstable/reactivity/Reactivity.js.map +1 -1
  916. package/dist/unstable/rpc/RpcClient.d.ts +5 -0
  917. package/dist/unstable/rpc/RpcClient.d.ts.map +1 -1
  918. package/dist/unstable/rpc/RpcClient.js +94 -81
  919. package/dist/unstable/rpc/RpcClient.js.map +1 -1
  920. package/dist/unstable/rpc/RpcClientError.d.ts +1 -1
  921. package/dist/unstable/rpc/RpcMessage.d.ts +66 -7
  922. package/dist/unstable/rpc/RpcMessage.d.ts.map +1 -1
  923. package/dist/unstable/rpc/RpcMessage.js +68 -9
  924. package/dist/unstable/rpc/RpcMessage.js.map +1 -1
  925. package/dist/unstable/rpc/RpcMiddleware.d.ts.map +1 -1
  926. package/dist/unstable/rpc/RpcMiddleware.js +7 -5
  927. package/dist/unstable/rpc/RpcMiddleware.js.map +1 -1
  928. package/dist/unstable/rpc/RpcSerialization.d.ts +28 -33
  929. package/dist/unstable/rpc/RpcSerialization.d.ts.map +1 -1
  930. package/dist/unstable/rpc/RpcSerialization.js +56 -92
  931. package/dist/unstable/rpc/RpcSerialization.js.map +1 -1
  932. package/dist/unstable/rpc/RpcServer.d.ts +25 -0
  933. package/dist/unstable/rpc/RpcServer.d.ts.map +1 -1
  934. package/dist/unstable/rpc/RpcServer.js +125 -68
  935. package/dist/unstable/rpc/RpcServer.js.map +1 -1
  936. package/dist/unstable/schema/Model.d.ts.map +1 -1
  937. package/dist/unstable/schema/Model.js +7 -6
  938. package/dist/unstable/schema/Model.js.map +1 -1
  939. package/dist/unstable/schema/VariantSchema.d.ts.map +1 -1
  940. package/dist/unstable/schema/VariantSchema.js +3 -0
  941. package/dist/unstable/schema/VariantSchema.js.map +1 -1
  942. package/dist/unstable/socket/Socket.d.ts +287 -102
  943. package/dist/unstable/socket/Socket.d.ts.map +1 -1
  944. package/dist/unstable/socket/Socket.js +408 -215
  945. package/dist/unstable/socket/Socket.js.map +1 -1
  946. package/dist/unstable/socket/SocketServer.d.ts +5 -32
  947. package/dist/unstable/socket/SocketServer.d.ts.map +1 -1
  948. package/dist/unstable/socket/SocketServer.js +3 -3
  949. package/dist/unstable/socket/SocketServer.js.map +1 -1
  950. package/dist/unstable/sql/SqlClient.d.ts +20 -0
  951. package/dist/unstable/sql/SqlClient.d.ts.map +1 -1
  952. package/dist/unstable/sql/SqlClient.js +14 -7
  953. package/dist/unstable/sql/SqlClient.js.map +1 -1
  954. package/dist/unstable/sql/SqlConnection.d.ts +15 -0
  955. package/dist/unstable/sql/SqlConnection.d.ts.map +1 -1
  956. package/dist/unstable/sql/SqlConnection.js.map +1 -1
  957. package/dist/unstable/sql/SqlModel.d.ts +1 -1
  958. package/dist/unstable/sql/SqlModel.d.ts.map +1 -1
  959. package/dist/unstable/sql/Statement.d.ts +13 -5
  960. package/dist/unstable/sql/Statement.d.ts.map +1 -1
  961. package/dist/unstable/sql/Statement.js +29 -15
  962. package/dist/unstable/sql/Statement.js.map +1 -1
  963. package/dist/unstable/workers/Transferable.js +1 -1
  964. package/dist/unstable/workers/Worker.d.ts.map +1 -1
  965. package/dist/unstable/workers/Worker.js +3 -1
  966. package/dist/unstable/workers/Worker.js.map +1 -1
  967. package/dist/unstable/workflow/Activity.d.ts +7 -0
  968. package/dist/unstable/workflow/Activity.d.ts.map +1 -1
  969. package/dist/unstable/workflow/Activity.js +14 -4
  970. package/dist/unstable/workflow/Activity.js.map +1 -1
  971. package/dist/unstable/workflow/DurableClock.js +1 -1
  972. package/dist/unstable/workflow/DurableClock.js.map +1 -1
  973. package/dist/unstable/workflow/DurableDeferred.d.ts +2 -2
  974. package/dist/unstable/workflow/DurableDeferred.d.ts.map +1 -1
  975. package/dist/unstable/workflow/DurableDeferred.js.map +1 -1
  976. package/dist/unstable/workflow/DurableQueue.d.ts +8 -0
  977. package/dist/unstable/workflow/DurableQueue.d.ts.map +1 -1
  978. package/dist/unstable/workflow/DurableQueue.js +8 -0
  979. package/dist/unstable/workflow/DurableQueue.js.map +1 -1
  980. package/dist/unstable/workflow/Workflow.d.ts +5 -0
  981. package/dist/unstable/workflow/Workflow.d.ts.map +1 -1
  982. package/dist/unstable/workflow/Workflow.js +70 -12
  983. package/dist/unstable/workflow/Workflow.js.map +1 -1
  984. package/dist/unstable/workflow/WorkflowEngine.d.ts +6 -0
  985. package/dist/unstable/workflow/WorkflowEngine.d.ts.map +1 -1
  986. package/dist/unstable/workflow/WorkflowEngine.js +11 -0
  987. package/dist/unstable/workflow/WorkflowEngine.js.map +1 -1
  988. package/dist/unstable/workflow/WorkflowProxy.d.ts +2 -2
  989. package/dist/unstable/workflow/WorkflowProxy.d.ts.map +1 -1
  990. package/dist/unstable/workflow/WorkflowProxy.js +4 -2
  991. package/dist/unstable/workflow/WorkflowProxy.js.map +1 -1
  992. package/package.json +8 -10
  993. package/src/Array.ts +142 -70
  994. package/src/BigDecimal.ts +50 -28
  995. package/src/ByteSize.ts +838 -0
  996. package/src/Cache.ts +17 -3
  997. package/src/Cause.ts +1 -1
  998. package/src/Channel.ts +185 -50
  999. package/src/Chunk.ts +65 -36
  1000. package/src/Config.ts +237 -248
  1001. package/src/ConfigProvider.ts +7 -8
  1002. package/src/Context.ts +31 -0
  1003. package/src/Cron.ts +2 -2
  1004. package/src/Crypto.ts +3 -2
  1005. package/src/Deferred.ts +7 -6
  1006. package/src/Duration.ts +1 -1
  1007. package/src/Effect.ts +226 -122
  1008. package/src/Effectable.ts +78 -9
  1009. package/src/Encoding.ts +101 -11
  1010. package/src/Equal.ts +1 -1
  1011. package/src/ExecutionPlan.ts +3 -0
  1012. package/src/Fiber.ts +33 -8
  1013. package/src/FiberHandle.ts +3 -3
  1014. package/src/FiberMap.ts +19 -10
  1015. package/src/FileSystem.ts +55 -230
  1016. package/src/Formatter.ts +21 -3
  1017. package/src/Graph.ts +55 -25
  1018. package/src/Hash.ts +5 -16
  1019. package/src/HashRing.ts +9 -2
  1020. package/src/HashSet.ts +56 -0
  1021. package/src/Iterable.ts +90 -44
  1022. package/src/JsonPatch.ts +4 -4
  1023. package/src/JsonPointer.ts +97 -4
  1024. package/src/JsonSchema.ts +998 -476
  1025. package/src/Layer.ts +59 -18
  1026. package/src/LayerMap.ts +38 -6
  1027. package/src/LayerRef.ts +7 -5
  1028. package/src/Logger.ts +125 -18
  1029. package/src/ManagedRuntime.ts +1 -1
  1030. package/src/Match.ts +33 -14
  1031. package/src/Metric.ts +24 -21
  1032. package/src/MutableHashMap.ts +1 -1
  1033. package/src/MutableHashSet.ts +1 -1
  1034. package/src/MutableList.ts +18 -2
  1035. package/src/Number.ts +7 -1
  1036. package/src/Optic.ts +8 -4
  1037. package/src/Option.ts +1 -1
  1038. package/src/Order.ts +3 -1
  1039. package/src/PartitionedSemaphore.ts +1 -2
  1040. package/src/Path.ts +1 -1
  1041. package/src/PlatformError.ts +1 -1
  1042. package/src/Pool.ts +535 -134
  1043. package/src/PrimaryKey.ts +1 -1
  1044. package/src/PubSub.ts +32 -20
  1045. package/src/Queue.ts +119 -28
  1046. package/src/Random.ts +20 -6
  1047. package/src/RcMap.ts +176 -13
  1048. package/src/Record.ts +15 -0
  1049. package/src/Redacted.ts +1 -1
  1050. package/src/RequestResolver.ts +49 -26
  1051. package/src/Result.ts +1 -1
  1052. package/src/Scheduler.ts +21 -11
  1053. package/src/Schema.ts +5032 -6518
  1054. package/src/SchemaAST.ts +1156 -316
  1055. package/src/SchemaGetter.ts +75 -21
  1056. package/src/SchemaIssue.ts +260 -16
  1057. package/src/SchemaParser.ts +2 -12
  1058. package/src/SchemaRepresentation.ts +1774 -189
  1059. package/src/SchemaTransformation.ts +145 -22
  1060. package/src/Scope.ts +9 -2
  1061. package/src/ScopedCache.ts +10 -3
  1062. package/src/Sink.ts +31 -15
  1063. package/src/StandardSchema.ts +207 -0
  1064. package/src/Stream.ts +294 -76
  1065. package/src/String.ts +20 -9
  1066. package/src/Struct.ts +8 -4
  1067. package/src/SynchronizedRef.ts +3 -5
  1068. package/src/Terminal.ts +3 -3
  1069. package/src/Tracer.ts +43 -14
  1070. package/src/Tuple.ts +3 -1
  1071. package/src/TxChunk.ts +1 -1
  1072. package/src/TxDeferred.ts +1 -1
  1073. package/src/TxHashMap.ts +1 -1
  1074. package/src/TxHashSet.ts +92 -11
  1075. package/src/TxPriorityQueue.ts +1 -1
  1076. package/src/TxPubSub.ts +1 -1
  1077. package/src/TxQueue.ts +22 -17
  1078. package/src/TxReentrantLock.ts +29 -1
  1079. package/src/TxRef.ts +1 -1
  1080. package/src/TxSemaphore.ts +1 -1
  1081. package/src/TxSubscriptionRef.ts +1 -1
  1082. package/src/Types.ts +40 -17
  1083. package/src/Utils.ts +3 -1
  1084. package/src/index.ts +10 -0
  1085. package/src/internal/arbitrary/model.ts +701 -0
  1086. package/src/internal/arbitrary/regexp.ts +855 -0
  1087. package/src/internal/arbitrary/runner.ts +608 -0
  1088. package/src/internal/arbitrary/schema.ts +1800 -0
  1089. package/src/internal/core.ts +48 -22
  1090. package/src/internal/count.ts +14 -0
  1091. package/src/internal/dateTime.ts +8 -10
  1092. package/src/internal/effect.ts +510 -301
  1093. package/src/internal/graph.ts +6 -1
  1094. package/src/internal/hashMap.ts +5 -3
  1095. package/src/internal/hashSet.ts +1 -1
  1096. package/src/internal/matcher.ts +34 -19
  1097. package/src/internal/metric.ts +1 -1
  1098. package/src/internal/option.ts +8 -6
  1099. package/src/internal/random.ts +20 -7
  1100. package/src/internal/rcRef.ts +10 -7
  1101. package/src/internal/references.ts +1 -0
  1102. package/src/internal/request.ts +12 -7
  1103. package/src/internal/result.ts +15 -11
  1104. package/src/internal/schema/annotations.ts +3 -3
  1105. package/src/internal/schema/fromJsonSchemaDocument.ts +326 -160
  1106. package/src/internal/schema/fromRepresentation.ts +5 -3
  1107. package/src/internal/schema/{schema.ts → make.ts} +0 -40
  1108. package/src/internal/schema/parser.ts +8 -0
  1109. package/src/internal/schema/standardSchema.ts +125 -0
  1110. package/src/internal/schema/toCodeDocument.ts +58 -44
  1111. package/src/internal/schema/toCodec.ts +312 -0
  1112. package/src/internal/schema/toDifferJsonPatch.ts +24 -0
  1113. package/src/internal/schema/toEncoderXml.ts +110 -0
  1114. package/src/internal/schema/toEquivalence.ts +76 -0
  1115. package/src/internal/schema/toFormatter.ts +230 -0
  1116. package/src/internal/schema/toIso.ts +20 -0
  1117. package/src/internal/schema/toJsonSchemaDocument.ts +125 -67
  1118. package/src/internal/schema/toRepresentation.ts +1 -1
  1119. package/src/internal/schemaError.ts +8 -0
  1120. package/src/internal/stream.ts +14 -6
  1121. package/src/internal/tracer.ts +4 -0
  1122. package/src/internal/trie.ts +5 -2
  1123. package/src/internal/uuid.ts +4 -0
  1124. package/src/testing/TestSchema.ts +36 -30
  1125. package/src/testing/index.ts +0 -5
  1126. package/src/unstable/ai/AiError.ts +126 -6
  1127. package/src/unstable/ai/AnthropicStructuredOutput.ts +8 -5
  1128. package/src/unstable/ai/Chat.ts +35 -36
  1129. package/src/unstable/ai/EmbeddingModel.ts +27 -15
  1130. package/src/unstable/ai/LanguageModel.ts +283 -100
  1131. package/src/unstable/ai/McpServer.ts +105 -92
  1132. package/src/unstable/ai/OpenAiStructuredOutput.ts +6 -3
  1133. package/src/unstable/ai/Prompt.ts +20 -5
  1134. package/src/unstable/ai/Response.ts +107 -189
  1135. package/src/unstable/ai/Tokenizer.ts +4 -5
  1136. package/src/unstable/ai/Tool.ts +58 -35
  1137. package/src/unstable/ai/Toolkit.ts +43 -37
  1138. package/src/unstable/ai/internal/codec-transformer.ts +3 -2
  1139. package/src/unstable/ai/internal/structured-output.ts +29 -6
  1140. package/src/unstable/arbitrary/Arbitrary.ts +715 -0
  1141. package/src/unstable/arbitrary/index.ts +10 -0
  1142. package/src/unstable/cli/Argument.ts +111 -115
  1143. package/src/unstable/cli/CliError.ts +2 -0
  1144. package/src/unstable/cli/CliOutput.ts +41 -4
  1145. package/src/unstable/cli/Command.ts +79 -78
  1146. package/src/unstable/cli/Completions.ts +4 -4
  1147. package/src/unstable/cli/Flag.ts +158 -169
  1148. package/src/unstable/cli/GlobalFlag.ts +13 -13
  1149. package/src/unstable/cli/Param.ts +150 -159
  1150. package/src/unstable/cli/Primitive.ts +75 -76
  1151. package/src/unstable/cli/Prompt.ts +543 -408
  1152. package/src/unstable/cli/internal/completions/bash.ts +113 -38
  1153. package/src/unstable/cli/internal/completions/descriptor.ts +23 -11
  1154. package/src/unstable/cli/internal/completions/fish.ts +17 -9
  1155. package/src/unstable/cli/internal/completions/zsh.ts +7 -4
  1156. package/src/unstable/cli/internal/config.ts +4 -4
  1157. package/src/unstable/cli/internal/parser.ts +1 -1
  1158. package/src/unstable/cli/internal/wizard.ts +60 -32
  1159. package/src/unstable/cluster/ClusterSchema.ts +19 -1
  1160. package/src/unstable/cluster/ClusterWorkflowEngine.ts +66 -16
  1161. package/src/unstable/cluster/Entity.ts +3 -0
  1162. package/src/unstable/cluster/EntityProxyServer.ts +6 -2
  1163. package/src/unstable/cluster/Envelope.ts +32 -3
  1164. package/src/unstable/cluster/HttpRunner.ts +52 -25
  1165. package/src/unstable/cluster/Message.ts +35 -13
  1166. package/src/unstable/cluster/MessageStorage.ts +69 -24
  1167. package/src/unstable/cluster/Reply.ts +36 -19
  1168. package/src/unstable/cluster/RunnerServer.ts +21 -11
  1169. package/src/unstable/cluster/Runners.ts +93 -80
  1170. package/src/unstable/cluster/Sharding.ts +44 -19
  1171. package/src/unstable/cluster/ShardingConfig.ts +23 -23
  1172. package/src/unstable/cluster/SocketRunner.ts +5 -4
  1173. package/src/unstable/cluster/SqlMessageStorage.ts +12 -8
  1174. package/src/unstable/cluster/SqlRunnerStorage.ts +18 -10
  1175. package/src/unstable/cluster/internal/clusterAbandon.ts +14 -0
  1176. package/src/unstable/cluster/internal/entityManager.ts +15 -6
  1177. package/src/unstable/cluster/internal/interruptors.ts +58 -1
  1178. package/src/unstable/cluster/internal/resourceRef.ts +15 -7
  1179. package/src/unstable/devtools/DevToolsClient.ts +13 -3
  1180. package/src/unstable/encoding/Ini.ts +2 -0
  1181. package/src/unstable/encoding/SchemaBinary.ts +5308 -0
  1182. package/src/unstable/encoding/Sse.ts +1 -1
  1183. package/src/unstable/encoding/Toml.ts +7 -5
  1184. package/src/unstable/encoding/Yaml.ts +18 -5
  1185. package/src/unstable/encoding/index.ts +2 -2
  1186. package/src/unstable/eventlog/Event.ts +7 -7
  1187. package/src/unstable/eventlog/EventJournal.ts +22 -15
  1188. package/src/unstable/eventlog/EventLog.ts +24 -14
  1189. package/src/unstable/eventlog/EventLogMessage.ts +25 -15
  1190. package/src/unstable/eventlog/EventLogRemote.ts +15 -4
  1191. package/src/unstable/eventlog/EventLogServerUnencrypted.ts +2 -2
  1192. package/src/unstable/eventlog/SqlEventJournal.ts +35 -10
  1193. package/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts +11 -1
  1194. package/src/unstable/http/Cookies.ts +2 -102
  1195. package/src/unstable/http/FetchHttpClient.ts +1 -1
  1196. package/src/unstable/http/FindMyWay/internal/router.ts +139 -33
  1197. package/src/unstable/http/FindMyWay.ts +15 -5
  1198. package/src/unstable/http/Headers.ts +3 -48
  1199. package/src/unstable/http/HttpBody.ts +107 -36
  1200. package/src/unstable/http/HttpClient.ts +41 -30
  1201. package/src/unstable/http/HttpClientRequest.ts +32 -18
  1202. package/src/unstable/http/HttpClientResponse.ts +16 -3
  1203. package/src/unstable/http/HttpEffect.ts +145 -73
  1204. package/src/unstable/http/HttpIncomingMessage.ts +4 -4
  1205. package/src/unstable/http/HttpMiddleware.ts +43 -24
  1206. package/src/unstable/http/HttpPlatform.ts +62 -20
  1207. package/src/unstable/http/HttpRouter.ts +27 -16
  1208. package/src/unstable/http/HttpServer.ts +18 -57
  1209. package/src/unstable/http/HttpServerRequest.ts +17 -15
  1210. package/src/unstable/http/HttpServerRespondable.ts +1 -1
  1211. package/src/unstable/http/HttpServerResponse.ts +49 -40
  1212. package/src/unstable/http/HttpStaticServer.ts +30 -28
  1213. package/src/unstable/http/Mime.ts +76 -0
  1214. package/src/unstable/http/Multipart.ts +35 -18
  1215. package/src/unstable/http/MultipartParser/internal/multipart.ts +10 -3
  1216. package/src/unstable/http/MultipartParser.ts +4 -3
  1217. package/src/unstable/http/UrlParams.ts +3 -161
  1218. package/src/unstable/http/index.ts +5 -0
  1219. package/src/unstable/http/internal/compression.ts +11 -12
  1220. package/src/unstable/http/internal/headers.ts +7 -0
  1221. package/src/unstable/http/internal/httpBody.ts +9 -0
  1222. package/src/unstable/http/internal/mimeTypes.ts +395 -0
  1223. package/src/unstable/httpapi/HttpApiBuilder.ts +63 -11
  1224. package/src/unstable/httpapi/HttpApiClient.ts +44 -24
  1225. package/src/unstable/httpapi/HttpApiEndpoint.ts +24 -11
  1226. package/src/unstable/httpapi/HttpApiError.ts +3 -1
  1227. package/src/unstable/httpapi/HttpApiMiddleware.ts +7 -5
  1228. package/src/unstable/httpapi/HttpApiScalar.ts +30 -27
  1229. package/src/unstable/httpapi/HttpApiSchema.ts +14 -7
  1230. package/src/unstable/httpapi/HttpApiSwagger.ts +6 -3
  1231. package/src/unstable/httpapi/HttpApiTest.ts +6 -1
  1232. package/src/unstable/httpapi/OpenApi.ts +32 -22
  1233. package/src/unstable/net/IpInterface.ts +242 -0
  1234. package/src/unstable/net/IpNetwork.ts +357 -0
  1235. package/src/unstable/net/NetAddress.ts +1271 -0
  1236. package/src/unstable/net/index.ts +20 -0
  1237. package/src/unstable/observability/OtlpExporter.ts +5 -6
  1238. package/src/unstable/observability/OtlpLogger.ts +9 -9
  1239. package/src/unstable/observability/OtlpMetrics.ts +9 -8
  1240. package/src/unstable/observability/OtlpResource.ts +5 -4
  1241. package/src/unstable/observability/OtlpTracer.ts +103 -81
  1242. package/src/unstable/observability/internal/otlpEnv.ts +10 -13
  1243. package/src/unstable/persistence/PersistedCache.ts +1 -1
  1244. package/src/unstable/persistence/PersistedQueue.ts +1100 -291
  1245. package/src/unstable/persistence/RateLimiter.ts +64 -58
  1246. package/src/unstable/process/ChildProcess.ts +15 -4
  1247. package/src/unstable/process/ChildProcessSpawner.ts +1 -1
  1248. package/src/unstable/reactivity/Atom.ts +6 -3
  1249. package/src/unstable/reactivity/AtomHttpApi.ts +21 -10
  1250. package/src/unstable/reactivity/AtomRegistry.ts +2 -4
  1251. package/src/unstable/reactivity/AtomRpc.ts +6 -5
  1252. package/src/unstable/reactivity/Hydration.ts +26 -7
  1253. package/src/unstable/reactivity/Reactivity.ts +49 -36
  1254. package/src/unstable/rpc/RpcClient.ts +100 -82
  1255. package/src/unstable/rpc/RpcMessage.ts +78 -11
  1256. package/src/unstable/rpc/RpcMiddleware.ts +7 -5
  1257. package/src/unstable/rpc/RpcSerialization.ts +82 -92
  1258. package/src/unstable/rpc/RpcServer.ts +171 -93
  1259. package/src/unstable/schema/Model.ts +8 -7
  1260. package/src/unstable/schema/VariantSchema.ts +3 -0
  1261. package/src/unstable/socket/Socket.ts +714 -383
  1262. package/src/unstable/socket/SocketServer.ts +5 -35
  1263. package/src/unstable/sql/SqlClient.ts +42 -7
  1264. package/src/unstable/sql/SqlConnection.ts +18 -0
  1265. package/src/unstable/sql/SqlModel.ts +1 -1
  1266. package/src/unstable/sql/Statement.ts +46 -20
  1267. package/src/unstable/workers/Transferable.ts +1 -1
  1268. package/src/unstable/workers/Worker.ts +3 -1
  1269. package/src/unstable/workflow/Activity.ts +20 -9
  1270. package/src/unstable/workflow/DurableClock.ts +1 -1
  1271. package/src/unstable/workflow/DurableDeferred.ts +6 -0
  1272. package/src/unstable/workflow/DurableQueue.ts +8 -0
  1273. package/src/unstable/workflow/Workflow.ts +105 -28
  1274. package/src/unstable/workflow/WorkflowEngine.ts +22 -0
  1275. package/src/unstable/workflow/WorkflowProxy.ts +8 -4
  1276. package/dist/internal/schema/schema.d.ts.map +0 -1
  1277. package/dist/internal/schema/schema.js.map +0 -1
  1278. package/dist/internal/schema/toArbitrary.d.ts +0 -2
  1279. package/dist/internal/schema/toArbitrary.d.ts.map +0 -1
  1280. package/dist/internal/schema/toArbitrary.js +0 -705
  1281. package/dist/internal/schema/toArbitrary.js.map +0 -1
  1282. package/dist/testing/FastCheck.d.ts +0 -90
  1283. package/dist/testing/FastCheck.d.ts.map +0 -1
  1284. package/dist/testing/FastCheck.js +0 -90
  1285. package/dist/testing/FastCheck.js.map +0 -1
  1286. package/dist/unstable/encoding/Msgpack.d.ts +0 -185
  1287. package/dist/unstable/encoding/Msgpack.d.ts.map +0 -1
  1288. package/dist/unstable/encoding/Msgpack.js +0 -227
  1289. package/dist/unstable/encoding/Msgpack.js.map +0 -1
  1290. package/src/internal/schema/toArbitrary.ts +0 -843
  1291. package/src/testing/FastCheck.ts +0 -90
  1292. package/src/unstable/encoding/Msgpack.ts +0 -432
  1293. /package/dist/internal/{schema → arbitrary}/schema.d.ts +0 -0
@@ -0,0 +1,4573 @@
1
+ /**
2
+ * A compact binary codec derived from the encoded side of a Schema.
3
+ *
4
+ * The default wire format supports compatible schema evolution. An array of
5
+ * structs is written as a row run: rows declare their shape once and
6
+ * back-reference repeated strings, so both stay off the wire on later rows.
7
+ * Fingerprint mode uses positional layouts and rejects mismatches for smaller
8
+ * frames; its row shapes are presence masks instead of field id lists. Encoded
9
+ * results are arena-backed views; see {@link toCodec} for ownership details.
10
+ *
11
+ * @since 4.0.0
12
+ */
13
+ import * as Arr from "../../Array.js";
14
+ import * as BigDecimal from "../../BigDecimal.js";
15
+ import * as Cause from "../../Cause.js";
16
+ import * as Channel from "../../Channel.js";
17
+ import * as Chunk from "../../Chunk.js";
18
+ import * as DateTime from "../../DateTime.js";
19
+ import * as Duration from "../../Duration.js";
20
+ import * as Effect from "../../Effect.js";
21
+ import * as Exit from "../../Exit.js";
22
+ import { dual, memoize } from "../../Function.js";
23
+ import * as HashMap from "../../HashMap.js";
24
+ import * as HashSet from "../../HashSet.js";
25
+ import { assignProperty } from "../../internal/record.js";
26
+ import * as InternalParserProtocol from "../../internal/schema/parser.js";
27
+ import * as Option from "../../Option.js";
28
+ import * as Predicate from "../../Predicate.js";
29
+ import * as Pull from "../../Pull.js";
30
+ import * as Redacted from "../../Redacted.js";
31
+ import * as Result from "../../Result.js";
32
+ import * as Schema from "../../Schema.js";
33
+ import * as SchemaAST from "../../SchemaAST.js";
34
+ import * as SchemaIssue from "../../SchemaIssue.js";
35
+ import * as SchemaParser from "../../SchemaParser.js";
36
+ import * as SchemaTransformation from "../../SchemaTransformation.js";
37
+ const codecCache = /*#__PURE__*/new WeakMap();
38
+ const fingerprintCodecCache = /*#__PURE__*/new WeakMap();
39
+ const directCodecCache = /*#__PURE__*/new WeakMap();
40
+ const directFingerprintCodecCache = /*#__PURE__*/new WeakMap();
41
+ /**
42
+ * Derives a compact binary codec from a schema.
43
+ *
44
+ * **Details**
45
+ *
46
+ * The wire layout is compiled from the encoded side of the schema. Each
47
+ * encode/decode handles exactly one frame; use {@link parser} for streams.
48
+ * Derived codecs are memoized by schema identity and wire mode.
49
+ *
50
+ * Encoded results are arena-backed views and may share a larger buffer. Use
51
+ * `bytes.slice()` when independent ownership is required.
52
+ *
53
+ * **Example** (Deriving a binary codec)
54
+ *
55
+ * ```ts
56
+ * import { Schema } from "effect"
57
+ * import { SchemaBinary } from "effect/unstable/encoding"
58
+ *
59
+ * const Person = Schema.Struct({ name: Schema.String, age: Schema.Number })
60
+ * const codec = SchemaBinary.toCodec(Person)
61
+ *
62
+ * const bytes = Schema.encodeUnknownSync(codec)({ name: "Ada", age: 36 })
63
+ * const person = Schema.decodeUnknownSync(codec)(bytes)
64
+ * ```
65
+ *
66
+ * @category constructors
67
+ * @since 4.0.0
68
+ */
69
+ export function toCodec(schema, options) {
70
+ const cache = options?.fingerprint === true ? fingerprintCodecCache : codecCache;
71
+ const cached = cache.get(schema);
72
+ if (cached !== undefined) return cached;
73
+ const {
74
+ exact,
75
+ layout,
76
+ recursive,
77
+ target
78
+ } = compileTarget(schema);
79
+ const mode = compileMode(layout, options?.fingerprint);
80
+ const trusted = exact ? {
81
+ value: undefined
82
+ } : undefined;
83
+ const codec = assembleCodec(trusted === undefined ? target : withTrustedDecode(target, trusted, !recursive), layout, mode, trusted);
84
+ cache.set(schema, codec);
85
+ return codec;
86
+ }
87
+ /**
88
+ * Derives the {@link toCodec} codec without the schema pass around the binary
89
+ * layer.
90
+ *
91
+ * Only schemas the binary layer already validates on its own take the direct
92
+ * path; anything else falls back to {@link toCodec}. A direct codec encodes and
93
+ * decodes the same values as {@link toCodec} but is not a sound `Schema.is`
94
+ * guard, so it is only for callers that never guard on it. Derived codecs are
95
+ * memoized by schema identity and wire mode.
96
+ *
97
+ * @internal
98
+ */
99
+ export function toCodecDirect(schema, options) {
100
+ const cache = options?.fingerprint === true ? directFingerprintCodecCache : directCodecCache;
101
+ const cached = cache.get(schema);
102
+ if (cached !== undefined) return cached;
103
+ const {
104
+ exact,
105
+ exitSuccess,
106
+ layout,
107
+ target
108
+ } = compileTarget(schema);
109
+ if (!exact) {
110
+ if (!exitSuccess) return toCodec(schema, options);
111
+ const trusted = {
112
+ value: undefined
113
+ };
114
+ const codec = assembleCodec(withExitSuccessDecode(target, trusted), layout, compileMode(layout, options?.fingerprint), trusted, true);
115
+ cache.set(schema, codec);
116
+ return codec;
117
+ }
118
+ const codec = assembleCodec(passThrough(target), layout, compileMode(layout, options?.fingerprint), undefined);
119
+ cache.set(schema, codec);
120
+ return codec;
121
+ }
122
+ function assembleCodec(target, layout, mode, trusted, successOnly = false) {
123
+ return Schema.Uint8Array.pipe(Schema.decodeTo(target, makeTransformation(layout, mode, trusted, successOnly)));
124
+ }
125
+ /**
126
+ * Encodes one frame without the schema pass {@link toCodec} wraps around it.
127
+ *
128
+ * Only schemas the binary layer already validates on its own take the direct
129
+ * path; anything else falls back to the codec, so checks and transformations
130
+ * still run.
131
+ *
132
+ * @internal
133
+ */
134
+ export function encodeUnknownSync(schema, options) {
135
+ const {
136
+ exact,
137
+ exitSuccess,
138
+ layout
139
+ } = compileTarget(schema);
140
+ const mode = compileMode(layout, options?.fingerprint);
141
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
142
+ if (!exact || parseOptions.onExcessProperty === "error") {
143
+ const fallback = Schema.encodeUnknownSync(toCodec(schema, options), options);
144
+ // The binary layer drops excess keys instead of reporting them.
145
+ if (!exitSuccess || parseOptions.onExcessProperty === "error") return fallback;
146
+ return value => {
147
+ if (!isSuccessExit(value)) return fallback(value);
148
+ try {
149
+ return encodeFrame(layout, value, parseOptions, mode);
150
+ } catch (e) {
151
+ throw e instanceof IssueError ? new Schema.SchemaError(e.issue) : e;
152
+ }
153
+ };
154
+ }
155
+ return value => {
156
+ try {
157
+ return encodeFrame(layout, value, parseOptions, mode);
158
+ } catch (e) {
159
+ throw e instanceof IssueError ? new Schema.SchemaError(e.issue) : e;
160
+ }
161
+ };
162
+ }
163
+ /**
164
+ * Encodes concatenated frames in one writer pass, so a batch costs no more
165
+ * allocations than a single frame.
166
+ *
167
+ * Shares {@link encodeUnknownSync}'s direct path and its fallback.
168
+ *
169
+ * @internal
170
+ */
171
+ export function encodeManyUnknownSync(schema, options) {
172
+ const {
173
+ exact,
174
+ layout
175
+ } = compileTarget(schema);
176
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
177
+ if (!exact || parseOptions.onExcessProperty === "error") {
178
+ const encode = encodeUnknownSync(schema, options);
179
+ return values => concatFrames(values.map(encode));
180
+ }
181
+ const mode = compileMode(layout, options?.fingerprint);
182
+ return values => {
183
+ try {
184
+ return encodeFrames(layout, values, parseOptions, mode);
185
+ } catch (e) {
186
+ throw e instanceof IssueError ? new Schema.SchemaError(e.issue) : e;
187
+ }
188
+ };
189
+ }
190
+ function concatFrames(frames) {
191
+ if (frames.length === 1) return frames[0];
192
+ let length = 0;
193
+ for (const frame of frames) length += frame.length;
194
+ const out = new Uint8Array(length);
195
+ let offset = 0;
196
+ for (const frame of frames) {
197
+ out.set(frame, offset);
198
+ offset += frame.length;
199
+ }
200
+ return out;
201
+ }
202
+ /**
203
+ * Creates a stateful parser for a stream of concatenated frames.
204
+ *
205
+ * **Details**
206
+ *
207
+ * Values completed before a failure remain observable. After a failure, the
208
+ * parser rejects further calls. Use `maxFrameSize` to limit buffered frames.
209
+ *
210
+ * @category constructors
211
+ * @since 4.0.0
212
+ */
213
+ export function parser(schema, options) {
214
+ const {
215
+ exact,
216
+ exitSuccess,
217
+ layout,
218
+ target
219
+ } = compileTarget(schema);
220
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
221
+ const decodeTarget = exact ? undefined : Schema.decodeUnknownSync(target, parseOptions);
222
+ const decodeEncoded = decodeTarget !== undefined && exitSuccess ? value => isSuccessExit(value) ? value : decodeTarget(value) : decodeTarget;
223
+ return makeParser(layout, compileMode(layout, options?.fingerprint), parseOptions, options?.maxFrameSize, decodeEncoded, requireDictionary(exact, options));
224
+ }
225
+ function requireDictionary(exact, options) {
226
+ if (options?.dictionary !== true) return false;
227
+ if (!exact) {
228
+ throw new Error("Binary layout: dictionary needs a schema the binary layer validates on its own");
229
+ }
230
+ return true;
231
+ }
232
+ /**
233
+ * A writer for one connection. Every frame it produces shares the string
234
+ * dictionary that the matching {@link parser} rebuilds as it reads them, so the
235
+ * two have to be created from the same schema and the same options.
236
+ *
237
+ * @category constructors
238
+ * @since 4.0.0
239
+ */
240
+ export function encoder(schema, options) {
241
+ const {
242
+ exact,
243
+ layout,
244
+ target
245
+ } = compileTarget(schema);
246
+ const dictionary = requireDictionary(exact, options);
247
+ const encode = encodeUnknownSync(schema, options);
248
+ const encodeMany = encodeManyUnknownSync(schema, options);
249
+ if (!dictionary) return {
250
+ encode,
251
+ encodeMany
252
+ };
253
+ const mode = compileMode(layout, options?.fingerprint);
254
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
255
+ const validate = parseOptions.onExcessProperty === "error" ? Schema.encodeUnknownSync(target, options) : undefined;
256
+ const dict = makeDictWrite();
257
+ const run = f => {
258
+ try {
259
+ return f();
260
+ } catch (e) {
261
+ throw e instanceof IssueError ? new Schema.SchemaError(e.issue) : e;
262
+ }
263
+ };
264
+ return {
265
+ encode: value => run(() => encodeFrame(layout, validate === undefined ? value : validate(value), parseOptions, mode, dict)),
266
+ encodeMany: values => run(() => encodeFrames(layout, validate === undefined ? values : values.map(validate), parseOptions, mode, dict))
267
+ };
268
+ }
269
+ // Frame parser over a compiled layout. `decodeEncoded` runs the target schema
270
+ // pass on each framed value; `undefined` yields the raw binary-decoded values.
271
+ function makeParser(layout, mode, parseOptions, maxFrameSize, decodeEncoded, dictionary) {
272
+ const dict = dictionary ? [] : undefined;
273
+ let buffer = new Uint8Array(0);
274
+ let bufferStart = 0;
275
+ let bufferEnd = 0;
276
+ let stashed;
277
+ let spent = false;
278
+ const body = new Reader();
279
+ const indexSignatures = new IndexSignatureCache(parseOptions, PARSER_INDEX_SIGNATURE_CACHE_SIZE);
280
+ const release = () => {
281
+ body.release();
282
+ indexSignatures.clear();
283
+ buffer = EMPTY_READER_BUFFER;
284
+ bufferStart = bufferEnd = 0;
285
+ };
286
+ const failSync = (expected, input) => {
287
+ throw new Schema.SchemaError(new SchemaIssue.InvalidValue({
288
+ expected
289
+ }, input, parseOptions));
290
+ };
291
+ const takeStashed = () => {
292
+ const error = stashed;
293
+ stashed = undefined;
294
+ throw error;
295
+ };
296
+ // Copy the unconsumed tail of a directly parsed chunk into the buffer.
297
+ const stashTail = (chunk, start) => {
298
+ const remaining = chunk.length - start;
299
+ if (remaining > buffer.length) {
300
+ buffer = new Uint8Array(Math.max(256, remaining));
301
+ }
302
+ buffer.set(start === 0 ? chunk : chunk.subarray(start), 0);
303
+ bufferStart = 0;
304
+ bufferEnd = remaining;
305
+ };
306
+ const self = {
307
+ feedSync(chunk) {
308
+ if (stashed !== undefined) return takeStashed();
309
+ if (spent) return failSync("parser is spent");
310
+ // Complete frames in a fresh chunk parse in place; only partial frames
311
+ // are ever copied into the buffer.
312
+ const direct = bufferEnd === bufferStart;
313
+ let buf;
314
+ let pos;
315
+ let end;
316
+ if (direct) {
317
+ buf = chunk;
318
+ pos = 0;
319
+ end = chunk.length;
320
+ } else {
321
+ if (chunk.length > 0) {
322
+ const remaining = bufferEnd - bufferStart;
323
+ const required = remaining + chunk.length;
324
+ if (required > buffer.length) {
325
+ const next = new Uint8Array(Math.max(256, buffer.length * 2, required));
326
+ next.set(buffer.subarray(bufferStart, bufferEnd));
327
+ buffer = next;
328
+ bufferStart = 0;
329
+ bufferEnd = remaining;
330
+ } else if (bufferStart > 0) {
331
+ buffer.copyWithin(0, bufferStart, bufferEnd);
332
+ bufferStart = 0;
333
+ bufferEnd = remaining;
334
+ }
335
+ buffer.set(chunk, bufferEnd);
336
+ bufferEnd += chunk.length;
337
+ }
338
+ buf = buffer;
339
+ pos = bufferStart;
340
+ end = bufferEnd;
341
+ }
342
+ const out = [];
343
+ const done = () => {
344
+ if (direct) {
345
+ if (pos < end) stashTail(chunk, pos);
346
+ } else {
347
+ bufferStart = pos;
348
+ if (bufferStart === bufferEnd) bufferStart = bufferEnd = 0;
349
+ }
350
+ return out;
351
+ };
352
+ const fail = (expected, input) => {
353
+ spent = true;
354
+ const error = new Schema.SchemaError(new SchemaIssue.InvalidValue({
355
+ expected
356
+ }, input, parseOptions));
357
+ release();
358
+ if (out.length === 0) throw error;
359
+ stashed = error;
360
+ return out;
361
+ };
362
+ while (true) {
363
+ // Use bigint only for frame lengths wider than six varint groups.
364
+ let frameLen = 0;
365
+ let headerLen = -1;
366
+ const buffered = end - pos;
367
+ let scale = 1;
368
+ for (let i = 0; i < Math.min(6, buffered); i++) {
369
+ const b = buf[pos + i];
370
+ frameLen += (b & 0x7F) * scale;
371
+ if ((b & 0x80) === 0) {
372
+ headerLen = i + 1;
373
+ break;
374
+ }
375
+ scale *= 128;
376
+ }
377
+ if (headerLen === -1) {
378
+ if (buffered < 6) return done();
379
+ let n = BigInt(frameLen);
380
+ for (let i = 6; i < Math.min(10, buffered); i++) {
381
+ const b = buf[pos + i];
382
+ n |= BigInt(b & 0x7F) << BigInt(i * 7);
383
+ if ((b & 0x80) === 0) {
384
+ headerLen = i + 1;
385
+ if (n > MAX_SAFE_BIGINT) return fail("safe integer length", n);
386
+ frameLen = Number(n);
387
+ break;
388
+ }
389
+ }
390
+ if (headerLen === -1) {
391
+ if (buffered >= 10) return fail("uvarint", buf.subarray(pos, pos + 10));
392
+ return done();
393
+ }
394
+ }
395
+ if (frameLen === 0) return fail("nonzero frame length", frameLen);
396
+ if (maxFrameSize !== undefined && frameLen > maxFrameSize) {
397
+ return fail("frame within maxFrameSize", frameLen);
398
+ }
399
+ if (headerLen + frameLen > buffered) return done();
400
+ const savedPathLen = issuePathLen;
401
+ try {
402
+ issuePathLen = 0;
403
+ const bodyStart = pos + headerLen;
404
+ indexSignatures.beginFrame();
405
+ body.reset(buf, bodyStart, bodyStart + frameLen, parseOptions, indexSignatures, mode.positional, dict);
406
+ const value = decodeFrameBody(layout, body, mode);
407
+ out.push(decodeEncoded === undefined ? value : decodeEncoded(value));
408
+ } catch (e) {
409
+ spent = true;
410
+ release();
411
+ const error = e instanceof IssueError ? new Schema.SchemaError(e.issue) : Schema.isSchemaError(e) ? e : (() => {
412
+ throw e;
413
+ })();
414
+ if (out.length === 0) throw error;
415
+ stashed = error;
416
+ return out;
417
+ } finally {
418
+ issuePathLen = savedPathLen;
419
+ }
420
+ pos += headerLen + frameLen;
421
+ }
422
+ },
423
+ endSync() {
424
+ if (stashed !== undefined) return takeStashed();
425
+ if (spent) return failSync("parser is spent");
426
+ spent = true;
427
+ const input = bufferStart < bufferEnd ? buffer.subarray(bufferStart, bufferEnd) : undefined;
428
+ release();
429
+ if (input !== undefined) return failSync("complete value", input);
430
+ },
431
+ feed: chunk => Effect.suspend(() => {
432
+ try {
433
+ return Effect.succeed(self.feedSync(chunk));
434
+ } catch (e) {
435
+ if (Schema.isSchemaError(e)) return Effect.fail(e);
436
+ throw e;
437
+ }
438
+ }),
439
+ end: Effect.suspend(() => {
440
+ try {
441
+ self.endSync();
442
+ return Effect.void;
443
+ } catch (e) {
444
+ if (Schema.isSchemaError(e)) return Effect.fail(e);
445
+ throw e;
446
+ }
447
+ })
448
+ };
449
+ return self;
450
+ }
451
+ /**
452
+ * Creates a channel that encodes chunks of schema values into binary frames.
453
+ *
454
+ * **Details**
455
+ *
456
+ * Each input chunk is emitted as one byte element holding concatenated frames
457
+ * written in one writer pass, so a batch costs no more allocations than a
458
+ * single frame. Schemas with transformations first run one schema pass per
459
+ * chunk to the binary-adjusted encoded side — supporting async transformations
460
+ * and encoding services — before that writer pass. Failures are
461
+ * `Schema.SchemaError`, matching {@link toCodec}. `maxFrameSize` only applies
462
+ * to {@link decode} and is ignored here.
463
+ *
464
+ * @category channels
465
+ * @since 4.0.0
466
+ */
467
+ export const encode = (schema, options) => () => {
468
+ // Everything here depends only on schema and options, so it is derived once
469
+ // per channel rather than once per run.
470
+ const {
471
+ exact,
472
+ layout,
473
+ target
474
+ } = compileTarget(schema);
475
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
476
+ const mode = compileMode(layout, options?.fingerprint);
477
+ const write = values => {
478
+ try {
479
+ return Effect.succeed(Arr.of(encodeFrames(layout, values, parseOptions, mode)));
480
+ } catch (e) {
481
+ if (e instanceof IssueError) return Effect.fail(new Schema.SchemaError(e.issue));
482
+ return Effect.die(e);
483
+ }
484
+ };
485
+ if (exact && parseOptions.onExcessProperty !== "error") {
486
+ return Channel.fromTransform((upstream, _scope) => Effect.sync(() => Effect.flatMap(upstream, write)));
487
+ }
488
+ // One schema pass per chunk brings the values to the binary-adjusted encoded
489
+ // side the writer expects, so the writer pass stays one sync batch.
490
+ const encodeValues = Schema.encodeUnknownEffect(Schema.NonEmptyArray(target), options);
491
+ return Channel.fromTransform((upstream, _scope) => Effect.sync(() => Effect.flatMap(upstream, chunk => Effect.flatMap(encodeValues(chunk), write))));
492
+ };
493
+ /**
494
+ * Creates a channel that decodes chunks of binary frames into schema values.
495
+ *
496
+ * **Details**
497
+ *
498
+ * The channel keeps one frame parser for its lifetime: frames may be
499
+ * fragmented across chunks or concatenated within one, values completed before
500
+ * a failure remain observable, and a leftover incomplete frame fails when the
501
+ * upstream is done. Schemas with transformations run the schema pass per
502
+ * framed value, which supports async transformations and decoding services.
503
+ * Failures are `Schema.SchemaError`, matching {@link toCodec}.
504
+ *
505
+ * @category channels
506
+ * @since 4.0.0
507
+ */
508
+ export const decode = (schema, options) => () => {
509
+ // Everything here depends only on schema and options, so it is derived once
510
+ // per channel; the frame parser and failure stash below stay per run.
511
+ const {
512
+ exact,
513
+ exitSuccess,
514
+ layout,
515
+ target
516
+ } = compileTarget(schema);
517
+ const parseOptions = options ?? SchemaAST.defaultParseOptions;
518
+ const mode = compileMode(layout, options?.fingerprint);
519
+ const decodeTarget = exact ? undefined : Schema.decodeUnknownEffect(target, parseOptions);
520
+ const decodeEncoded = decodeTarget !== undefined && exitSuccess ? value => isSuccessExit(value) ? Effect.succeed(value) : decodeTarget(value) : decodeTarget;
521
+ return Channel.fromTransform((upstream, _scope) => Effect.sync(() => {
522
+ const frames = makeParser(layout, mode, parseOptions, options?.maxFrameSize, undefined, false);
523
+ let stashed;
524
+ // Decodes framed values in order. On a failure, values decoded before it
525
+ // are emitted first and the error fails the next pull.
526
+ const decodeAll = raw => {
527
+ const out = [];
528
+ const loop = Effect.suspend(() => out.length === raw.length ? Effect.succeed(out) : Effect.flatMap(decodeEncoded(raw[out.length]), value => {
529
+ out.push(value);
530
+ return loop;
531
+ }));
532
+ return Effect.catch(loop, error => {
533
+ if (out.length === 0) {
534
+ stashed = undefined;
535
+ return Effect.fail(error);
536
+ }
537
+ stashed = error;
538
+ return Effect.succeed(out);
539
+ });
540
+ };
541
+ const feed = chunk => {
542
+ const raw = [];
543
+ try {
544
+ for (let i = 0; i < chunk.length; i++) {
545
+ const values = frames.feedSync(chunk[i]);
546
+ for (let j = 0; j < values.length; j++) raw.push(values[j]);
547
+ }
548
+ } catch (e) {
549
+ if (!Schema.isSchemaError(e)) return Effect.die(e);
550
+ if (raw.length === 0) return Effect.fail(e);
551
+ // Emit the values framed before the failure, then fail on the next
552
+ // pull.
553
+ stashed = e;
554
+ }
555
+ if (!Arr.isReadonlyArrayNonEmpty(raw)) return pull;
556
+ return decodeEncoded === undefined ? Effect.succeed(raw) : decodeAll(raw);
557
+ };
558
+ const pull = Effect.suspend(() => stashed !== undefined ? Effect.fail(stashed) : Pull.matchEffect(upstream, {
559
+ onSuccess: feed,
560
+ onFailure: Effect.failCause,
561
+ onDone: done => {
562
+ try {
563
+ frames.endSync();
564
+ return Cause.done(done);
565
+ } catch (e) {
566
+ if (Schema.isSchemaError(e)) return Effect.fail(e);
567
+ throw e;
568
+ }
569
+ }
570
+ }));
571
+ return pull;
572
+ }));
573
+ };
574
+ /**
575
+ * Wraps a bidirectional byte channel with schema-driven binary encoding and
576
+ * decoding.
577
+ *
578
+ * **Details**
579
+ *
580
+ * Values sent to the wrapped channel are encoded with `inputSchema` as binary
581
+ * frames; bytes received from it are decoded with `outputSchema`.
582
+ *
583
+ * @category channels
584
+ * @since 4.0.0
585
+ */
586
+ export const duplex = /*#__PURE__*/dual(2, (self, options) => encode(options.inputSchema, options)().pipe(Channel.pipeTo(self), Channel.pipeTo(decode(options.outputSchema, options)())));
587
+ /**
588
+ * Assigns an explicit wire field id to a struct property.
589
+ *
590
+ * **When to use**
591
+ *
592
+ * Use to preserve the wire id across a rename or resolve a hash collision.
593
+ *
594
+ * **Details**
595
+ *
596
+ * Valid ids are integers from 1 through 4294967295.
597
+ *
598
+ * **Example** (Assigning a wire field id)
599
+ *
600
+ * ```ts
601
+ * import { Schema } from "effect"
602
+ * import { SchemaBinary } from "effect/unstable/encoding"
603
+ *
604
+ * const Person = Schema.Struct({
605
+ * id: Schema.String.pipe(SchemaBinary.fieldId(1))
606
+ * })
607
+ * ```
608
+ *
609
+ * @category annotations
610
+ * @since 4.0.0
611
+ */
612
+ export function fieldId(id) {
613
+ if (!Number.isInteger(id) || id <= 0 || id > 0xFFFFFFFF) {
614
+ throw new Error(`Binary layout field id must be an integer in [1, 4294967295], got ${id}`);
615
+ }
616
+ const annotations = {
617
+ [FIELD_ID_ANNOTATION_KEY]: id
618
+ };
619
+ const annotateLastLink = SchemaAST.applyToLastLink(ast => SchemaAST.annotateKey(ast, annotations));
620
+ return self => self.rebuild(annotateLastLink(SchemaAST.annotateKey(self.ast, annotations)));
621
+ }
622
+ const FIELD_ID_ANNOTATION_KEY = "~effect/encoding/SchemaBinary/fieldId";
623
+ // Bit 0 selects fingerprint mode; all other flag bits are reserved.
624
+ const ENVELOPE = 0x20; // version nibble 2, flags 0
625
+ const ENVELOPE_FINGERPRINT = 0x21; // version nibble 2, flag bit 0
626
+ const MAX_SAFE_BIGINT = /*#__PURE__*/BigInt(Number.MAX_SAFE_INTEGER);
627
+ const BIGINT_ZERO = /*#__PURE__*/BigInt(0);
628
+ const BIGINT_ONE = /*#__PURE__*/BigInt(1);
629
+ const BIGINT_TWO = /*#__PURE__*/BigInt(2);
630
+ const BIGINT_SEVEN = /*#__PURE__*/BigInt(7);
631
+ const BIGINT_VARINT_MASK = /*#__PURE__*/BigInt(0x7F);
632
+ const BIGINT_NANOS_PER_MILLI = /*#__PURE__*/BigInt(1_000_000);
633
+ const BIGINT_BYTE_MASK = /*#__PURE__*/BigInt(0xFF);
634
+ const BIGINT_U32_MASK = /*#__PURE__*/BigInt(0xFFFFFFFF);
635
+ const BIGINT_THIRTY_TWO = /*#__PURE__*/BigInt(32);
636
+ const utf8Encode = /*#__PURE__*/new TextEncoder();
637
+ const utf8DecodeFatal = /*#__PURE__*/new TextDecoder("utf-8", {
638
+ fatal: true,
639
+ ignoreBOM: true
640
+ });
641
+ // General numbers use up to seven varint bytes, a varint mantissa with a
642
+ // decimal scale byte, or an eight-byte f64.
643
+ const NUMBER_VARINT_MAX_BYTES = 7;
644
+ const NUMBER_VARINT_MAX_MAGNITUDE = 281_474_976_710_655; // 2 ** 48 - 1
645
+ // Above this magnitude, build the sign-magnitude code with bigint.
646
+ const EXACT_MAGNITUDE_MAX = 4_503_599_627_370_495; // 2 ** 52 - 1
647
+ const NUMBER_RUN_F64 = 0;
648
+ const NUMBER_RUN_VARINT = 1;
649
+ const NUMBER_RUN_DECIMAL = 2;
650
+ // Recursive layouts must fail before the JavaScript stack does. This is high
651
+ // enough for practical payloads while keeping the decoder's stack bounded.
652
+ const MAX_NESTING_DEPTH = 512;
653
+ // Variable-width elements must be backed by frame bytes apart from a bounded
654
+ // allowance. Provably zero-width elements need their own absolute bound.
655
+ const ARRAY_ALLOCATION_SLACK = 1_048_576;
656
+ const ZERO_WIDTH_ARRAY_MAX = 4_194_304;
657
+ // Struct field tags pack the field id with enough information to skip the
658
+ // payload without consulting the schema. Decimal is a sign-magnitude mantissa
659
+ // varint followed by an unsigned scale varint.
660
+ const FIELD_WIRE_SIZED = 0;
661
+ const FIELD_WIRE_VARINT = 1;
662
+ const FIELD_WIRE_FIXED64 = 2;
663
+ const FIELD_WIRE_FALSE = 3;
664
+ const FIELD_WIRE_TRUE = 4;
665
+ const FIELD_WIRE_DECIMAL = 5;
666
+ const FIELD_WIRE_FIXED32 = 6;
667
+ const FIELD_WIRE_EMPTY = 7;
668
+ const FIELD_WIRE_FACTOR = 8;
669
+ function isVarintNumber(value) {
670
+ return typeof value === "number" && Number.isInteger(value) && value >= -NUMBER_VARINT_MAX_MAGNITUDE && value <= NUMBER_VARINT_MAX_MAGNITUDE;
671
+ }
672
+ // Short decimals ride the varint path as mantissa + one scale byte. The
673
+ // mantissa is capped at six varint bytes so the total stays under the
674
+ // eight-byte f64 discriminator.
675
+ const DECIMAL_SCALE_MAX = 8;
676
+ const DECIMAL_MANTISSA_MAX = 2_199_023_255_551; // 2 ** 41 - 1
677
+ const POW10 = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000];
678
+ // The scale that makes `value` an exact short-decimal mantissa, or 0.
679
+ function decimalScale(value) {
680
+ for (let scale = 1; scale <= DECIMAL_SCALE_MAX; scale++) {
681
+ const mantissa = Math.round(value * POW10[scale]);
682
+ // The mantissa only grows with the scale, so once it leaves the range no
683
+ // later scale can fit; this also rejects NaN and the infinities in one
684
+ // comparison.
685
+ if (!(mantissa >= -DECIMAL_MANTISSA_MAX && mantissa <= DECIMAL_MANTISSA_MAX)) return 0;
686
+ if (mantissa / POW10[scale] === value) return scale;
687
+ }
688
+ return 0;
689
+ }
690
+ // Sign-magnitude preserves `-0`, unlike zigzag.
691
+ function decodeSignMagnitude(code) {
692
+ const magnitude = Math.floor(code / 2);
693
+ return code % 2 === 1 ? -magnitude : magnitude;
694
+ }
695
+ const K = {
696
+ bool: 1,
697
+ null: 2,
698
+ undefined: 3,
699
+ number: 4,
700
+ string: 5,
701
+ bytes: 6,
702
+ bigint: 7,
703
+ int64: 8,
704
+ struct: 9,
705
+ variant: 10,
706
+ array: 11,
707
+ option: 12,
708
+ result: 13,
709
+ duration: 14,
710
+ bigDecimal: 15,
711
+ dateTimeZoned: 16,
712
+ json: 17,
713
+ exit: 18,
714
+ cause: 19,
715
+ causeReason: 20
716
+ };
717
+ function fnv32(bytes) {
718
+ let hash = 0x811C9DC5;
719
+ for (let i = 0; i < bytes.length; i++) {
720
+ hash = Math.imul(hash ^ bytes[i], 0x01000193);
721
+ }
722
+ return hash >>> 0;
723
+ }
724
+ const FNV64_OFFSET_BASIS = /*#__PURE__*/BigInt("14695981039346656037");
725
+ const FNV64_PRIME = /*#__PURE__*/BigInt("1099511628211");
726
+ const FNV64_MASK = /*#__PURE__*/BigInt("18446744073709551615");
727
+ function fnv64(bytes) {
728
+ let hash = FNV64_OFFSET_BASIS;
729
+ for (let i = 0; i < bytes.length; i++) {
730
+ hash = (hash ^ BigInt(bytes[i])) * FNV64_PRIME & FNV64_MASK;
731
+ }
732
+ return hash;
733
+ }
734
+ function pushBytes(out, bytes) {
735
+ for (let i = 0; i < bytes.length; i++) out.push(bytes[i]);
736
+ }
737
+ function pushUvarint(out, n) {
738
+ while (n > 0x7F) {
739
+ out.push(n & 0x7F | 0x80);
740
+ n = Math.floor(n / 128);
741
+ }
742
+ out.push(n);
743
+ }
744
+ function pushU32(out, n) {
745
+ out.push(n & 0xFF, n >>> 8 & 0xFF, n >>> 16 & 0xFF, n >>> 24 & 0xFF);
746
+ }
747
+ function pushU64(out, n) {
748
+ for (let i = 0; i < 8; i++) {
749
+ out.push(Number(n >> BigInt(i * 8) & BIGINT_BYTE_MASK));
750
+ }
751
+ }
752
+ function compareBytes(a, b) {
753
+ const len = Math.min(a.length, b.length);
754
+ for (let i = 0; i < len; i++) {
755
+ if (a[i] !== b[i]) return a[i] - b[i];
756
+ }
757
+ return a.length - b.length;
758
+ }
759
+ class IssueError extends Error {
760
+ issue;
761
+ constructor(issue) {
762
+ super("SchemaBinary failure");
763
+ this.issue = issue;
764
+ }
765
+ }
766
+ function invalid(expected, input, options) {
767
+ throw issueError(new SchemaIssue.InvalidValue({
768
+ expected
769
+ }, input, options));
770
+ }
771
+ // Materialize the ambient path only when raising an issue.
772
+ const issuePath = [];
773
+ let issuePathLen = 0;
774
+ function issueError(issue) {
775
+ return new IssueError(issuePathLen === 0 ? issue : new SchemaIssue.Pointer(issuePath.slice(0, issuePathLen), issue));
776
+ }
777
+ function uvarintBytes(n) {
778
+ const out = new Uint8Array(uvarintSize(n));
779
+ let p = 0;
780
+ while (n > 0x7F) {
781
+ out[p++] = n & 0x7F | 0x80;
782
+ n = Math.floor(n / 128);
783
+ }
784
+ out[p] = n;
785
+ return out;
786
+ }
787
+ function uvarintSize(n) {
788
+ let size = 1;
789
+ while (n > 0x7F) {
790
+ n = Math.floor(n / 128);
791
+ size++;
792
+ }
793
+ return size;
794
+ }
795
+ // Avoid TextDecoder's fixed cost for short strings.
796
+ const UTF8_INLINE_LIMIT = 32;
797
+ function decodeUtf8(buf, start, end, options) {
798
+ const len = end - start;
799
+ if (len === 0) return "";
800
+ if (len <= UTF8_INLINE_LIMIT) {
801
+ const ascii = decodeAscii(buf, start, end);
802
+ if (ascii !== undefined) return ascii;
803
+ }
804
+ try {
805
+ return utf8DecodeFatal.decode(buf.subarray(start, end));
806
+ } catch {
807
+ invalid("utf-8", undefined, options);
808
+ }
809
+ }
810
+ // Sixteen and eight code unit blocks, checking their high bits together and
811
+ // giving up on the first non-ASCII byte, then one call for the 0-7 tail.
812
+ function decodeAscii(buf, start, end) {
813
+ let out = "";
814
+ let i = start;
815
+ for (; i + 16 <= end; i += 16) {
816
+ const a = buf[i],
817
+ b = buf[i + 1],
818
+ c = buf[i + 2],
819
+ d = buf[i + 3];
820
+ const e = buf[i + 4],
821
+ f = buf[i + 5],
822
+ g = buf[i + 6],
823
+ h = buf[i + 7];
824
+ const a2 = buf[i + 8],
825
+ b2 = buf[i + 9],
826
+ c2 = buf[i + 10],
827
+ d2 = buf[i + 11];
828
+ const e2 = buf[i + 12],
829
+ f2 = buf[i + 13],
830
+ g2 = buf[i + 14],
831
+ h2 = buf[i + 15];
832
+ if ((a | b | c | d | e | f | g | h | a2 | b2 | c2 | d2 | e2 | f2 | g2 | h2) > 0x7F) return undefined;
833
+ out += String.fromCharCode(a, b, c, d, e, f, g, h, a2, b2, c2, d2, e2, f2, g2, h2);
834
+ }
835
+ if (i + 8 <= end) {
836
+ const a = buf[i],
837
+ b = buf[i + 1],
838
+ c = buf[i + 2],
839
+ d = buf[i + 3];
840
+ const e = buf[i + 4],
841
+ f = buf[i + 5],
842
+ g = buf[i + 6],
843
+ h = buf[i + 7];
844
+ if ((a | b | c | d | e | f | g | h) > 0x7F) return undefined;
845
+ out += String.fromCharCode(a, b, c, d, e, f, g, h);
846
+ i += 8;
847
+ }
848
+ switch (end - i) {
849
+ case 0:
850
+ return out;
851
+ case 1:
852
+ {
853
+ const a = buf[i];
854
+ if (a > 0x7F) return undefined;
855
+ return out + String.fromCharCode(a);
856
+ }
857
+ case 2:
858
+ {
859
+ const a = buf[i],
860
+ b = buf[i + 1];
861
+ if ((a | b) > 0x7F) return undefined;
862
+ return out + String.fromCharCode(a, b);
863
+ }
864
+ case 3:
865
+ {
866
+ const a = buf[i],
867
+ b = buf[i + 1],
868
+ c = buf[i + 2];
869
+ if ((a | b | c) > 0x7F) return undefined;
870
+ return out + String.fromCharCode(a, b, c);
871
+ }
872
+ case 4:
873
+ {
874
+ const a = buf[i],
875
+ b = buf[i + 1],
876
+ c = buf[i + 2],
877
+ d = buf[i + 3];
878
+ if ((a | b | c | d) > 0x7F) return undefined;
879
+ return out + String.fromCharCode(a, b, c, d);
880
+ }
881
+ case 5:
882
+ {
883
+ const a = buf[i],
884
+ b = buf[i + 1],
885
+ c = buf[i + 2],
886
+ d = buf[i + 3],
887
+ e = buf[i + 4];
888
+ if ((a | b | c | d | e) > 0x7F) return undefined;
889
+ return out + String.fromCharCode(a, b, c, d, e);
890
+ }
891
+ case 6:
892
+ {
893
+ const a = buf[i],
894
+ b = buf[i + 1],
895
+ c = buf[i + 2],
896
+ d = buf[i + 3];
897
+ const e = buf[i + 4],
898
+ f = buf[i + 5];
899
+ if ((a | b | c | d | e | f) > 0x7F) return undefined;
900
+ return out + String.fromCharCode(a, b, c, d, e, f);
901
+ }
902
+ default:
903
+ {
904
+ const a = buf[i],
905
+ b = buf[i + 1],
906
+ c = buf[i + 2],
907
+ d = buf[i + 3];
908
+ const e = buf[i + 4],
909
+ f = buf[i + 5],
910
+ g = buf[i + 6];
911
+ if ((a | b | c | d | e | f | g) > 0x7F) return undefined;
912
+ return out + String.fromCharCode(a, b, c, d, e, f, g);
913
+ }
914
+ }
915
+ }
916
+ const OUTPUT_ARENA_SIZE = 64 * 1024;
917
+ // Bound attacker-controlled keys retained between parser feeds.
918
+ const PARSER_INDEX_SIGNATURE_CACHE_SIZE = 256;
919
+ // Bound the last universal record shape retained by a compiled layout.
920
+ const ENCODE_INDEX_SIGNATURE_CACHE_KEYS = 512;
921
+ const ENCODE_INDEX_SIGNATURE_CACHE_CODE_UNITS = 16 * 1024;
922
+ function makeOutputArena(size) {
923
+ const buf = new Uint8Array(size);
924
+ return {
925
+ buf,
926
+ view: new DataView(buf.buffer),
927
+ offset: 0,
928
+ writing: false
929
+ };
930
+ }
931
+ let outputArena = /*#__PURE__*/makeOutputArena(OUTPUT_ARENA_SIZE);
932
+ class Writer {
933
+ buf = /*#__PURE__*/new Uint8Array(0);
934
+ view = /*#__PURE__*/new DataView(this.buf.buffer);
935
+ arena;
936
+ start = 0;
937
+ limit = 0;
938
+ len = 0;
939
+ reset() {
940
+ let arena = outputArena;
941
+ // Nested codecs cannot share the active arena tail.
942
+ if (arena.writing || arena.offset >= arena.buf.length) {
943
+ arena = outputArena = makeOutputArena(OUTPUT_ARENA_SIZE);
944
+ }
945
+ arena.writing = true;
946
+ this.arena = arena;
947
+ this.buf = arena.buf;
948
+ this.view = arena.view;
949
+ this.start = arena.offset;
950
+ this.limit = arena.buf.length - arena.offset;
951
+ this.len = 0;
952
+ }
953
+ ensure(n) {
954
+ if (this.len + n > this.limit) {
955
+ const previous = this.arena;
956
+ const required = this.len + n;
957
+ let size = OUTPUT_ARENA_SIZE;
958
+ while (size < required) size *= 2;
959
+ const next = makeOutputArena(size);
960
+ next.writing = true;
961
+ next.buf.set(this.buf.subarray(this.start, this.start + this.len));
962
+ previous.writing = false;
963
+ this.arena = outputArena = next;
964
+ this.buf = next.buf;
965
+ this.view = next.view;
966
+ this.start = 0;
967
+ this.limit = next.buf.length;
968
+ }
969
+ }
970
+ byte(b) {
971
+ this.ensure(1);
972
+ this.buf[this.start + this.len++] = b;
973
+ }
974
+ bytes(b) {
975
+ this.ensure(b.length);
976
+ this.buf.set(b, this.start + this.len);
977
+ this.len += b.length;
978
+ }
979
+ uvarint(n) {
980
+ this.ensure(10);
981
+ const buf = this.buf;
982
+ let p = this.start + this.len;
983
+ if (n < 0x80) {
984
+ buf[p++] = n;
985
+ } else {
986
+ buf[p++] = n & 0x7F | 0x80;
987
+ if (n < 0x4000) {
988
+ buf[p++] = n >>> 7;
989
+ } else {
990
+ buf[p++] = n >>> 7 & 0x7F | 0x80;
991
+ n = Math.floor(n / 0x4000);
992
+ while (n > 0x7F) {
993
+ buf[p++] = n & 0x7F | 0x80;
994
+ n = Math.floor(n / 128);
995
+ }
996
+ buf[p++] = n;
997
+ }
998
+ }
999
+ this.len = p - this.start;
1000
+ }
1001
+ uvarintBig(n) {
1002
+ while (n > BIGINT_VARINT_MASK) {
1003
+ this.byte(Number(n & BIGINT_VARINT_MASK) | 0x80);
1004
+ n >>= BIGINT_SEVEN;
1005
+ }
1006
+ this.byte(Number(n));
1007
+ }
1008
+ zigzag(n) {
1009
+ this.uvarintBig(n >= BIGINT_ZERO ? n << BIGINT_ONE : (-n << BIGINT_ONE) - BIGINT_ONE);
1010
+ }
1011
+ numberVarint(n) {
1012
+ const negative = n < 0 || n === 0 && 1 / n < 0;
1013
+ const magnitude = negative ? -n : n;
1014
+ if (magnitude <= EXACT_MAGNITUDE_MAX) {
1015
+ this.uvarint(magnitude * 2 + (negative ? 1 : 0));
1016
+ } else {
1017
+ this.uvarintBig(BigInt(magnitude) * BIGINT_TWO + (negative ? BIGINT_ONE : BIGINT_ZERO));
1018
+ }
1019
+ }
1020
+ f64(n) {
1021
+ this.ensure(8);
1022
+ this.view.setFloat64(this.start + this.len, n, true);
1023
+ this.len += 8;
1024
+ }
1025
+ i64(n) {
1026
+ this.ensure(8);
1027
+ this.view.setBigInt64(this.start + this.len, n, true);
1028
+ this.len += 8;
1029
+ }
1030
+ u32le(n) {
1031
+ this.ensure(4);
1032
+ this.view.setUint32(this.start + this.len, n >>> 0, true);
1033
+ this.len += 4;
1034
+ }
1035
+ i32le(n) {
1036
+ this.ensure(4);
1037
+ this.view.setInt32(this.start + this.len, n | 0, true);
1038
+ this.len += 4;
1039
+ }
1040
+ // Writes a field id and reserves its length byte under one bounds check.
1041
+ idAndMark(idBytes) {
1042
+ const n = idBytes.length;
1043
+ this.ensure(n + 1);
1044
+ const buf = this.buf;
1045
+ let p = this.start + this.len;
1046
+ for (let i = 0; i < n; i++) buf[p++] = idBytes[i];
1047
+ const mark = p - this.start;
1048
+ this.len = mark + 1;
1049
+ return mark;
1050
+ }
1051
+ // Reserve one byte, then expand and backfill the length prefix if needed.
1052
+ beginSized() {
1053
+ this.ensure(1);
1054
+ return this.len++;
1055
+ }
1056
+ endSized(mark) {
1057
+ const code = this.len - mark - 1;
1058
+ if (code < 0x80) this.buf[this.start + mark] = code;else this.growSized(mark, code);
1059
+ }
1060
+ // Row-run regions prefix `length * 2`; odd codes are back-references.
1061
+ endSizedRun(mark) {
1062
+ const code = (this.len - mark - 1) * 2;
1063
+ if (code < 0x80) this.buf[this.start + mark] = code;else this.growSized(mark, code);
1064
+ }
1065
+ growSized(mark, code) {
1066
+ const size = uvarintSize(code);
1067
+ const extra = size - 1;
1068
+ this.ensure(extra);
1069
+ const absoluteMark = this.start + mark;
1070
+ this.buf.copyWithin(absoluteMark + size, absoluteMark + 1, this.start + this.len);
1071
+ this.len += extra;
1072
+ let n = code;
1073
+ let p = absoluteMark;
1074
+ while (n > 0x7F) {
1075
+ this.buf[p++] = n & 0x7F | 0x80;
1076
+ n = Math.floor(n / 128);
1077
+ }
1078
+ this.buf[p] = n;
1079
+ }
1080
+ string(s) {
1081
+ const n = s.length;
1082
+ if (n === 0) return;
1083
+ this.ensure(n * 3);
1084
+ const buf = this.buf;
1085
+ let p = this.start + this.len;
1086
+ let i = 0;
1087
+ for (; i + 4 <= n; i += 4) {
1088
+ const a = s.charCodeAt(i);
1089
+ const b = s.charCodeAt(i + 1);
1090
+ const c = s.charCodeAt(i + 2);
1091
+ const d = s.charCodeAt(i + 3);
1092
+ if ((a | b | c | d) > 0x7F) {
1093
+ this.len += utf8Encode.encodeInto(s, buf.subarray(this.start + this.len)).written;
1094
+ return;
1095
+ }
1096
+ buf[p++] = a;
1097
+ buf[p++] = b;
1098
+ buf[p++] = c;
1099
+ buf[p++] = d;
1100
+ }
1101
+ for (; i < n; i++) {
1102
+ const c = s.charCodeAt(i);
1103
+ if (c > 0x7F) {
1104
+ this.len += utf8Encode.encodeInto(s, buf.subarray(this.start + this.len)).written;
1105
+ return;
1106
+ }
1107
+ buf[p++] = c;
1108
+ }
1109
+ this.len = p - this.start;
1110
+ }
1111
+ out() {
1112
+ const arena = this.arena;
1113
+ const out = new Uint8Array(arena.buf.buffer, this.start, this.len);
1114
+ if (arena === outputArena) arena.offset = this.start + this.len;
1115
+ arena.writing = false;
1116
+ this.arena = undefined;
1117
+ return out;
1118
+ }
1119
+ abort() {
1120
+ const arena = this.arena;
1121
+ if (arena === undefined) return;
1122
+ if (arena === outputArena) arena.offset = this.start;
1123
+ arena.writing = false;
1124
+ this.arena = undefined;
1125
+ }
1126
+ }
1127
+ // Index-signature predicates are not part of the fingerprint, so unmatched
1128
+ // keys are dropped in both modes.
1129
+ // A plain string parameter accepts every key without running the matcher.
1130
+ function matchesEveryKey(parameter) {
1131
+ const ast = SchemaAST.toEncoded(parameter);
1132
+ return ast._tag === "String" && ast.checks === undefined;
1133
+ }
1134
+ function matchIndexSignature(layout, key, options) {
1135
+ return layout.extra.find(s => SchemaAST.getIndexSignatureKeys({
1136
+ [key]: null
1137
+ }, s.parameter, options).length > 0);
1138
+ }
1139
+ class IndexSignatureCache {
1140
+ entries = /*#__PURE__*/new WeakMap();
1141
+ orderLayouts;
1142
+ orderKeys;
1143
+ options;
1144
+ size = 0;
1145
+ next = 0;
1146
+ replace = false;
1147
+ // Only the parser cache outlives one operation, and it is always bounded.
1148
+ constructor(options, capacity) {
1149
+ this.options = options;
1150
+ this.orderLayouts = capacity === undefined ? undefined : new Array(capacity);
1151
+ this.orderKeys = capacity === undefined ? undefined : new Array(capacity);
1152
+ }
1153
+ beginFrame() {
1154
+ this.replace = true;
1155
+ }
1156
+ find(layout, key) {
1157
+ let entries = this.entries.get(layout);
1158
+ if (entries === undefined) {
1159
+ entries = new Map();
1160
+ this.entries.set(layout, entries);
1161
+ }
1162
+ if (entries.has(key)) return entries.get(key);
1163
+ const signature = matchIndexSignature(layout, key, this.options);
1164
+ const orderLayouts = this.orderLayouts;
1165
+ if (orderLayouts === undefined) {
1166
+ entries.set(key, signature);
1167
+ return signature;
1168
+ }
1169
+ const orderKeys = this.orderKeys;
1170
+ if (this.size < orderLayouts.length) {
1171
+ orderLayouts[this.size] = layout;
1172
+ orderKeys[this.size] = key;
1173
+ this.size++;
1174
+ entries.set(key, signature);
1175
+ } else if (this.replace) {
1176
+ this.replace = false;
1177
+ const evictedLayout = orderLayouts[this.next];
1178
+ const evictedEntries = evictedLayout === layout ? entries : this.entries.get(evictedLayout);
1179
+ evictedEntries?.delete(orderKeys[this.next]);
1180
+ orderLayouts[this.next] = layout;
1181
+ orderKeys[this.next] = key;
1182
+ this.next = (this.next + 1) % orderLayouts.length;
1183
+ entries.set(key, signature);
1184
+ }
1185
+ return signature;
1186
+ }
1187
+ clear() {
1188
+ this.entries = new WeakMap();
1189
+ this.orderLayouts?.fill(undefined);
1190
+ this.orderKeys?.fill(undefined);
1191
+ this.size = this.next = 0;
1192
+ this.replace = false;
1193
+ }
1194
+ }
1195
+ // A named buffer preserves the build's pure annotation for these placeholders.
1196
+ const EMPTY_READER_ARRAY_BUFFER = /*#__PURE__*/new ArrayBuffer(0);
1197
+ const EMPTY_READER_BUFFER = /*#__PURE__*/new Uint8Array(EMPTY_READER_ARRAY_BUFFER);
1198
+ const EMPTY_READER_VIEW = /*#__PURE__*/new DataView(EMPTY_READER_ARRAY_BUFFER);
1199
+ class Reader {
1200
+ pos = 0;
1201
+ nesting = 0;
1202
+ buf = EMPTY_READER_BUFFER;
1203
+ // Frames of varints and strings never need a view, so it is built on demand
1204
+ // and reused while the reader stays on one buffer.
1205
+ view;
1206
+ viewCache = EMPTY_READER_VIEW;
1207
+ viewBuffer = EMPTY_READER_ARRAY_BUFFER;
1208
+ viewOffset = 0;
1209
+ viewLength = 0;
1210
+ end = 0;
1211
+ options = SchemaAST.defaultParseOptions;
1212
+ indexSignatures;
1213
+ positional = false;
1214
+ // Handed to the row-run field's immediate consumer, then cleared.
1215
+ intern;
1216
+ // String tables shared by every frame on one connection; `undefined` for a
1217
+ // one-shot decode, where each frame stands alone.
1218
+ dict;
1219
+ reset(buf, start, end, options, indexSignatures, positional, dict) {
1220
+ this.nesting = 0;
1221
+ this.view = undefined;
1222
+ this.buf = buf;
1223
+ this.pos = start;
1224
+ this.end = end;
1225
+ this.options = options;
1226
+ this.indexSignatures = indexSignatures;
1227
+ this.positional = positional;
1228
+ this.intern = undefined;
1229
+ this.dict = dict;
1230
+ }
1231
+ release() {
1232
+ this.pos = this.end = this.nesting = 0;
1233
+ this.buf = EMPTY_READER_BUFFER;
1234
+ this.view = undefined;
1235
+ this.viewCache = EMPTY_READER_VIEW;
1236
+ this.viewBuffer = EMPTY_READER_ARRAY_BUFFER;
1237
+ this.viewOffset = this.viewLength = 0;
1238
+ this.options = SchemaAST.defaultParseOptions;
1239
+ this.indexSignatures = undefined;
1240
+ this.positional = false;
1241
+ this.intern = undefined;
1242
+ this.dict = undefined;
1243
+ }
1244
+ get remaining() {
1245
+ return this.end - this.pos;
1246
+ }
1247
+ dataView() {
1248
+ const buf = this.buf;
1249
+ if (buf.buffer !== this.viewBuffer || buf.byteOffset !== this.viewOffset || buf.byteLength !== this.viewLength) {
1250
+ this.viewBuffer = buf.buffer;
1251
+ this.viewOffset = buf.byteOffset;
1252
+ this.viewLength = buf.byteLength;
1253
+ this.viewCache = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1254
+ }
1255
+ return this.view = this.viewCache;
1256
+ }
1257
+ byte() {
1258
+ if (this.pos >= this.end) invalid("complete value", undefined, this.options);
1259
+ return this.buf[this.pos++];
1260
+ }
1261
+ take(n) {
1262
+ if (this.pos + n > this.end) invalid("complete value", undefined, this.options);
1263
+ const out = this.buf.subarray(this.pos, this.pos + n);
1264
+ this.pos += n;
1265
+ return out;
1266
+ }
1267
+ // Decoded bytes outlive the parser's buffer, so they are copied, not viewed.
1268
+ takeCopy(n) {
1269
+ if (this.pos + n > this.end) invalid("complete value", undefined, this.options);
1270
+ const out = this.buf.slice(this.pos, this.pos + n);
1271
+ this.pos += n;
1272
+ return out;
1273
+ }
1274
+ // Decode a bounded child value without allocating another reader.
1275
+ enter(len) {
1276
+ if (this.pos + len > this.end) invalid("complete value", undefined, this.options);
1277
+ const saved = this.end;
1278
+ this.end = this.pos + len;
1279
+ return saved;
1280
+ }
1281
+ exit(saved) {
1282
+ this.pos = this.end;
1283
+ this.end = saved;
1284
+ }
1285
+ readUtf8(n) {
1286
+ if (this.pos + n > this.end) invalid("complete value", undefined, this.options);
1287
+ const start = this.pos;
1288
+ this.pos += n;
1289
+ return decodeUtf8(this.buf, start, start + n, this.options);
1290
+ }
1291
+ // Use bitwise arithmetic for the first four varint groups.
1292
+ uvarint() {
1293
+ const buf = this.buf;
1294
+ const end = this.end;
1295
+ let pos = this.pos;
1296
+ if (pos >= end) invalid("complete value", undefined, this.options);
1297
+ let b = buf[pos++];
1298
+ if (b < 0x80) {
1299
+ this.pos = pos;
1300
+ return b;
1301
+ }
1302
+ let value = b & 0x7F;
1303
+ if (pos >= end) invalid("complete value", undefined, this.options);
1304
+ b = buf[pos++];
1305
+ value |= (b & 0x7F) << 7;
1306
+ if (b < 0x80) {
1307
+ this.pos = pos;
1308
+ return value;
1309
+ }
1310
+ if (pos >= end) invalid("complete value", undefined, this.options);
1311
+ b = buf[pos++];
1312
+ value |= (b & 0x7F) << 14;
1313
+ if (b < 0x80) {
1314
+ this.pos = pos;
1315
+ return value;
1316
+ }
1317
+ if (pos >= end) invalid("complete value", undefined, this.options);
1318
+ b = buf[pos++];
1319
+ value |= (b & 0x7F) << 21;
1320
+ if (b < 0x80) {
1321
+ this.pos = pos;
1322
+ return value;
1323
+ }
1324
+ let scale = 268435456; // 2 ** 28
1325
+ for (let i = 4; i < 10; i++) {
1326
+ if (pos >= end) {
1327
+ this.pos = pos;
1328
+ invalid("complete value", undefined, this.options);
1329
+ }
1330
+ b = buf[pos++];
1331
+ const chunk = (b & 0x7F) * scale;
1332
+ if (chunk > Number.MAX_SAFE_INTEGER - value) {
1333
+ this.pos = pos;
1334
+ invalid("safe integer length", undefined, this.options);
1335
+ }
1336
+ value += chunk;
1337
+ if (b < 0x80) {
1338
+ this.pos = pos;
1339
+ return value;
1340
+ }
1341
+ scale *= 128;
1342
+ }
1343
+ this.pos = pos;
1344
+ invalid("uvarint", undefined, this.options);
1345
+ }
1346
+ // Field tags are capped at 35 bits, so their common five-byte form can skip
1347
+ // the general safe-integer loop in uvarint.
1348
+ fieldTag() {
1349
+ const buf = this.buf;
1350
+ const end = this.end;
1351
+ let pos = this.pos;
1352
+ if (pos >= end) invalid("complete value", undefined, this.options);
1353
+ let b = buf[pos++];
1354
+ if (b < 0x80) {
1355
+ this.pos = pos;
1356
+ return b;
1357
+ }
1358
+ let value = b & 0x7F;
1359
+ if (pos >= end) invalid("complete value", undefined, this.options);
1360
+ b = buf[pos++];
1361
+ value |= (b & 0x7F) << 7;
1362
+ if (b < 0x80) {
1363
+ this.pos = pos;
1364
+ return value;
1365
+ }
1366
+ if (pos >= end) invalid("complete value", undefined, this.options);
1367
+ b = buf[pos++];
1368
+ value |= (b & 0x7F) << 14;
1369
+ if (b < 0x80) {
1370
+ this.pos = pos;
1371
+ return value;
1372
+ }
1373
+ if (pos >= end) invalid("complete value", undefined, this.options);
1374
+ b = buf[pos++];
1375
+ value |= (b & 0x7F) << 21;
1376
+ if (b < 0x80) {
1377
+ this.pos = pos;
1378
+ return value;
1379
+ }
1380
+ if (pos >= end) invalid("complete value", undefined, this.options);
1381
+ b = buf[pos++];
1382
+ this.pos = pos;
1383
+ if (b >= 0x80) invalid("uvarint", undefined, this.options);
1384
+ return value + b * 268435456;
1385
+ }
1386
+ uvarintBig() {
1387
+ let value = BIGINT_ZERO;
1388
+ let shift = BIGINT_ZERO;
1389
+ while (true) {
1390
+ const b = this.byte();
1391
+ value |= BigInt(b & 0x7F) << shift;
1392
+ if ((b & 0x80) === 0) return value;
1393
+ shift += BIGINT_SEVEN;
1394
+ }
1395
+ }
1396
+ // Wider schema-proven integers switch to bigint arithmetic.
1397
+ numberVarint() {
1398
+ const buf = this.buf;
1399
+ const end = this.end;
1400
+ let pos = this.pos;
1401
+ let value = 0;
1402
+ let scale = 1;
1403
+ for (let i = 0; i < NUMBER_VARINT_MAX_BYTES; i++) {
1404
+ if (pos >= end) {
1405
+ this.pos = pos;
1406
+ invalid("complete value", undefined, this.options);
1407
+ }
1408
+ const b = buf[pos++];
1409
+ value += (b & 0x7F) * scale;
1410
+ if (b < 0x80) {
1411
+ this.pos = pos;
1412
+ return decodeSignMagnitude(value);
1413
+ }
1414
+ scale *= 128;
1415
+ }
1416
+ const code = this.uvarintBig();
1417
+ const magnitude = Number(code >> BIGINT_ONE);
1418
+ if (!Number.isFinite(magnitude)) invalid("safe integer length", undefined, this.options);
1419
+ return (code & BIGINT_ONE) === BIGINT_ONE ? -magnitude : magnitude;
1420
+ }
1421
+ zigzag() {
1422
+ const u = this.uvarintBig();
1423
+ return (u & BIGINT_ONE) === BIGINT_ONE ? -(u + BIGINT_ONE >> BIGINT_ONE) : u >> BIGINT_ONE;
1424
+ }
1425
+ f64() {
1426
+ if (this.pos + 8 > this.end) invalid("complete value", undefined, this.options);
1427
+ const value = (this.view ?? this.dataView()).getFloat64(this.pos, true);
1428
+ this.pos += 8;
1429
+ return value;
1430
+ }
1431
+ i64() {
1432
+ if (this.pos + 8 > this.end) invalid("complete value", undefined, this.options);
1433
+ const value = (this.view ?? this.dataView()).getBigInt64(this.pos, true);
1434
+ this.pos += 8;
1435
+ return value;
1436
+ }
1437
+ u32le() {
1438
+ if (this.pos + 4 > this.end) invalid("complete value", undefined, this.options);
1439
+ const value = (this.view ?? this.dataView()).getUint32(this.pos, true);
1440
+ this.pos += 4;
1441
+ return value;
1442
+ }
1443
+ i32le() {
1444
+ if (this.pos + 4 > this.end) invalid("complete value", undefined, this.options);
1445
+ const value = (this.view ?? this.dataView()).getInt32(this.pos, true);
1446
+ this.pos += 4;
1447
+ return value;
1448
+ }
1449
+ }
1450
+ function literalLayout(leaf, values) {
1451
+ return {
1452
+ _: "literal",
1453
+ leaf,
1454
+ values,
1455
+ valueSet: values.length > 4 ? new Set(values) : undefined
1456
+ };
1457
+ }
1458
+ function hasLiteral(layout, value) {
1459
+ const values = layout.values;
1460
+ return layout.valueSet !== undefined ? layout.valueSet.has(value) : values.length === 1 ? value === values[0] : values.includes(value);
1461
+ }
1462
+ function literalExpected(layout) {
1463
+ return layout.values.map(value => typeof value === "string" ? JSON.stringify(value) : String(value)).join(" | ");
1464
+ }
1465
+ const INTERN_NONE = 0;
1466
+ const INTERN_SELF = 1;
1467
+ const INTERN_ELEMENTS = 2;
1468
+ const INTERN_KEYS = 3;
1469
+ // Rows carry a presence mask over fields plus one bit for the extra block.
1470
+ const RUN_MAX_FIELDS = 30;
1471
+ const RUN_EXTRA_BIT = 1 << RUN_MAX_FIELDS;
1472
+ function isSelfDelimiting(layout) {
1473
+ return layout._ === "literal" ? isSelfDelimiting(layout.leaf) : layout._ === "int";
1474
+ }
1475
+ function packedSize(layout) {
1476
+ switch (layout._) {
1477
+ case "literal":
1478
+ return packedSize(layout.leaf);
1479
+ case "bool":
1480
+ return 1;
1481
+ case "int64":
1482
+ return 8;
1483
+ default:
1484
+ return undefined;
1485
+ }
1486
+ }
1487
+ function isInlineSlot(layout) {
1488
+ return packedSize(layout) !== undefined || isSelfDelimiting(layout) || layout._ === "null" || layout._ === "undefined";
1489
+ }
1490
+ function isZeroWidthSlot(layout) {
1491
+ return layout._ === "literal" ? isZeroWidthSlot(layout.leaf) : layout._ === "null" || layout._ === "undefined";
1492
+ }
1493
+ // One registry row per natively supported declaration: its wire kind and
1494
+ // whether the binary layer validates it exactly on its own (`true`) or exactly
1495
+ // when its type parameters are ("parameters"). `compileDeclaration` holds the
1496
+ // matching layout constructors; its fallback asserts the two stay in sync.
1497
+ const natives = {
1498
+ "effect/schema/Date": {
1499
+ kind: K.int64,
1500
+ exact: true
1501
+ },
1502
+ "effect/schema/DateTimeUtc": {
1503
+ kind: K.int64,
1504
+ exact: true
1505
+ },
1506
+ "effect/schema/DateTimeZoned": {
1507
+ kind: K.dateTimeZoned,
1508
+ exact: true
1509
+ },
1510
+ "effect/schema/Duration": {
1511
+ kind: K.duration,
1512
+ exact: true
1513
+ },
1514
+ "effect/schema/BigDecimal": {
1515
+ kind: K.bigDecimal,
1516
+ exact: true
1517
+ },
1518
+ "effect/schema/Uint8Array": {
1519
+ kind: K.bytes,
1520
+ exact: true
1521
+ },
1522
+ "effect/schema/Option": {
1523
+ kind: K.option,
1524
+ exact: "parameters"
1525
+ },
1526
+ "effect/schema/Result": {
1527
+ kind: K.result,
1528
+ exact: "parameters"
1529
+ },
1530
+ "effect/schema/Exit": {
1531
+ kind: K.exit,
1532
+ exact: "parameters"
1533
+ },
1534
+ "effect/schema/Cause": {
1535
+ kind: K.cause,
1536
+ exact: "parameters"
1537
+ },
1538
+ "effect/schema/CauseReason": {
1539
+ kind: K.causeReason,
1540
+ exact: "parameters"
1541
+ }
1542
+ };
1543
+ function representationId(ast) {
1544
+ const representation = ast.annotations?.representation;
1545
+ return Predicate.isObject(representation) && typeof representation.id === "string" ? representation.id : undefined;
1546
+ }
1547
+ const toBinaryAST = /*#__PURE__*/SchemaAST.applyToSelfOrLastLinkEncodingIdempotent(ast => {
1548
+ const out = toBinaryASTStep(ast);
1549
+ const context = ast.context;
1550
+ if (out === ast || context === undefined) return out;
1551
+ return SchemaAST.replaceContextLastLink(out, new SchemaAST.Context(context.isOptional, context.isMutable, undefined, context.annotations));
1552
+ });
1553
+ function toBinaryASTStep(ast) {
1554
+ switch (ast._tag) {
1555
+ case "Declaration":
1556
+ {
1557
+ const id = representationId(ast);
1558
+ if (id !== undefined && (id in natives || id === "effect/schema/Json" || id === "effect/schema/MutableJson")) {
1559
+ return ast.recur(toBinaryAST);
1560
+ }
1561
+ const getJson = ast.annotations?.toCodecJson;
1562
+ const getCodec = ast.annotations?.toCodec;
1563
+ if (!Predicate.isFunction(getJson) && !Predicate.isFunction(getCodec)) {
1564
+ return ast;
1565
+ }
1566
+ const typeParameters = ast.typeParameters.map(tp => Schema.make(SchemaAST.toEncoded(tp)));
1567
+ const link = (Predicate.isFunction(getJson) ? getJson(typeParameters) : undefined) ?? (Predicate.isFunction(getCodec) ? getCodec(typeParameters) : undefined);
1568
+ return link === undefined ? ast : SchemaAST.replaceEncoding(ast, [SchemaAST.mapLink(link, toBinaryAST)]);
1569
+ }
1570
+ case "Arrays":
1571
+ case "Objects":
1572
+ case "Union":
1573
+ case "Suspend":
1574
+ return ast.recur(toBinaryAST);
1575
+ default:
1576
+ return ast;
1577
+ }
1578
+ }
1579
+ function sentinelSetHash(sentinels) {
1580
+ const sorted = [...sentinels].sort((a, b) => {
1581
+ const an = typeof a.key === "number";
1582
+ const bn = typeof b.key === "number";
1583
+ if (an !== bn) return an ? -1 : 1;
1584
+ if (an) return a.key - b.key;
1585
+ return compareBytes(utf8Encode.encode(a.key), utf8Encode.encode(b.key));
1586
+ });
1587
+ const out = [];
1588
+ for (const sentinel of sorted) {
1589
+ const keyBytes = utf8Encode.encode(String(sentinel.key));
1590
+ out.push(typeof sentinel.key === "number" ? 0 : 1);
1591
+ pushU32(out, keyBytes.length);
1592
+ pushBytes(out, keyBytes);
1593
+ const literal = sentinel.literal;
1594
+ const valueBytes = utf8Encode.encode(sentinelLiteralString(literal));
1595
+ out.push(sentinelLiteralKind(literal));
1596
+ pushU32(out, valueBytes.length);
1597
+ pushBytes(out, valueBytes);
1598
+ }
1599
+ return fnv32(out);
1600
+ }
1601
+ function sentinelLiteralKind(literal) {
1602
+ switch (typeof literal) {
1603
+ case "string":
1604
+ return 1;
1605
+ case "number":
1606
+ return 2;
1607
+ case "boolean":
1608
+ return 3;
1609
+ case "bigint":
1610
+ return 4;
1611
+ default:
1612
+ return 5;
1613
+ }
1614
+ }
1615
+ function sentinelLiteralString(literal) {
1616
+ if (typeof literal === "symbol") {
1617
+ const key = globalThis.Symbol.keyFor(literal);
1618
+ if (key === undefined) {
1619
+ throw new Error("Binary layout: unregistered unique symbol (Symbol.keyFor)");
1620
+ }
1621
+ return key;
1622
+ }
1623
+ return String(literal);
1624
+ }
1625
+ function parameterHasSymbol(parameter) {
1626
+ switch (parameter._tag) {
1627
+ case "Symbol":
1628
+ return true;
1629
+ case "Union":
1630
+ return parameter.types.some(parameterHasSymbol);
1631
+ default:
1632
+ return false;
1633
+ }
1634
+ }
1635
+ function isJsonDeclaration(ast) {
1636
+ const id = representationId(ast);
1637
+ if (id === "effect/schema/Json" || id === "effect/schema/MutableJson") return true;
1638
+ return Predicate.isFunction(ast.annotations?.toCodecJson);
1639
+ }
1640
+ // Detect integer checks nested inside filter groups.
1641
+ function provesInteger(ast) {
1642
+ const checks = ast.checks;
1643
+ if (checks === undefined) return false;
1644
+ const go = check => {
1645
+ const id = check.annotations?.representation?.id;
1646
+ if (id === "effect/schema/isInt") return true;
1647
+ return check._tag === "FilterGroup" && check.checks.some(go);
1648
+ };
1649
+ return checks.some(go);
1650
+ }
1651
+ function resolveSuspend(ast) {
1652
+ while (ast._tag === "Suspend") {
1653
+ ast = ast.thunk();
1654
+ }
1655
+ return ast;
1656
+ }
1657
+ function enumsToLiterals(ast) {
1658
+ return new SchemaAST.Union(ast.enums.map(e => new SchemaAST.Literal(e[1], {
1659
+ title: e[0]
1660
+ })));
1661
+ }
1662
+ function flattenMembers(union) {
1663
+ const out = [];
1664
+ const seen = new Set();
1665
+ const go = ast => {
1666
+ const resolved = resolveSuspend(ast);
1667
+ if (seen.has(resolved)) return;
1668
+ seen.add(resolved);
1669
+ switch (resolved._tag) {
1670
+ case "Never":
1671
+ return;
1672
+ case "Union":
1673
+ resolved.types.forEach(go);
1674
+ return;
1675
+ case "Enum":
1676
+ enumsToLiterals(resolved).types.forEach(go);
1677
+ return;
1678
+ default:
1679
+ out.push(resolved);
1680
+ }
1681
+ };
1682
+ union.types.forEach(go);
1683
+ return out;
1684
+ }
1685
+ function literalKind(literal) {
1686
+ switch (typeof literal) {
1687
+ case "string":
1688
+ return "string";
1689
+ case "number":
1690
+ return "number";
1691
+ case "boolean":
1692
+ return "bool";
1693
+ default:
1694
+ return "bigint";
1695
+ }
1696
+ }
1697
+ // Classify union members without eagerly compiling recursive members.
1698
+ function astKind(ast) {
1699
+ switch (ast._tag) {
1700
+ case "String":
1701
+ case "TemplateLiteral":
1702
+ case "Symbol":
1703
+ return K.string;
1704
+ case "UniqueSymbol":
1705
+ if (globalThis.Symbol.keyFor(ast.symbol) === undefined) {
1706
+ throw new Error("Binary layout: unregistered unique symbol (Symbol.keyFor)");
1707
+ }
1708
+ return K.string;
1709
+ case "Boolean":
1710
+ return K.bool;
1711
+ case "Null":
1712
+ return K.null;
1713
+ case "Undefined":
1714
+ case "Void":
1715
+ return K.undefined;
1716
+ case "Number":
1717
+ return K.number;
1718
+ case "BigInt":
1719
+ return K.bigint;
1720
+ case "Literal":
1721
+ switch (typeof ast.literal) {
1722
+ case "string":
1723
+ return K.string;
1724
+ case "number":
1725
+ return K.number;
1726
+ case "boolean":
1727
+ return K.bool;
1728
+ default:
1729
+ return K.bigint;
1730
+ }
1731
+ case "Unknown":
1732
+ case "Any":
1733
+ case "ObjectKeyword":
1734
+ return K.json;
1735
+ case "Objects":
1736
+ return K.struct;
1737
+ case "Arrays":
1738
+ return K.array;
1739
+ case "Declaration":
1740
+ {
1741
+ const id = representationId(ast);
1742
+ if (id !== undefined && id in natives) return natives[id].kind;
1743
+ if (isJsonDeclaration(ast)) return K.json;
1744
+ throw new Error(`Binary layout: declaration ${id ?? "<anonymous>"} has no toCodecJson or toCodec`);
1745
+ }
1746
+ case "Suspend":
1747
+ return astKind(resolveSuspend(ast));
1748
+ default:
1749
+ throw new Error("Binary layout: union members are not uniquely identifiable");
1750
+ }
1751
+ }
1752
+ function computeRequired(layout) {
1753
+ for (const field of layout.fields) {
1754
+ if (field.optional) continue;
1755
+ if (field.index < 32) layout.requiredMask |= 1 << field.index;else layout.requiredWide = true;
1756
+ }
1757
+ }
1758
+ function compileLayout(root) {
1759
+ const exact = isExact(root);
1760
+ const exitSuccess = !exact && isExitWithExactSuccess(root);
1761
+ root = SchemaAST.toEncoded(root);
1762
+ const memo = new Map();
1763
+ let recursive = false;
1764
+ let stringSlots = 0;
1765
+ const leaf = kind => ({
1766
+ _: kind,
1767
+ slot: kind === "string" ? stringSlots++ : 0
1768
+ });
1769
+ function compile(ast) {
1770
+ const hit = memo.get(ast);
1771
+ if (hit !== undefined) return hit;
1772
+ const layout = go(ast);
1773
+ memo.set(ast, layout);
1774
+ return layout;
1775
+ }
1776
+ function go(ast) {
1777
+ switch (ast._tag) {
1778
+ case "String":
1779
+ case "TemplateLiteral":
1780
+ return leaf("string");
1781
+ case "Symbol":
1782
+ case "UniqueSymbol":
1783
+ return leaf("symbol");
1784
+ case "Boolean":
1785
+ return leaf("bool");
1786
+ case "Null":
1787
+ return leaf("null");
1788
+ case "Undefined":
1789
+ case "Void":
1790
+ return leaf("undefined");
1791
+ case "Number":
1792
+ return leaf(provesInteger(ast) ? "int" : "number");
1793
+ case "BigInt":
1794
+ return leaf("bigint");
1795
+ case "Literal":
1796
+ return literalLayout(leaf(literalKind(ast.literal)), [ast.literal]);
1797
+ case "Unknown":
1798
+ case "Any":
1799
+ case "ObjectKeyword":
1800
+ return leaf("json");
1801
+ case "Never":
1802
+ return {
1803
+ _: "never",
1804
+ ast
1805
+ };
1806
+ case "Enum":
1807
+ return compileUnion(ast, flattenMembers(enumsToLiterals(ast)));
1808
+ case "Suspend":
1809
+ {
1810
+ recursive = true;
1811
+ const layout = compile(ast.thunk());
1812
+ memo.set(ast, layout);
1813
+ return layout;
1814
+ }
1815
+ case "Objects":
1816
+ return compileStruct(ast);
1817
+ case "Arrays":
1818
+ return compileArray(ast);
1819
+ case "Union":
1820
+ return compileUnion(ast, flattenMembers(ast));
1821
+ case "Declaration":
1822
+ return compileDeclaration(ast);
1823
+ }
1824
+ }
1825
+ function compileStruct(ast) {
1826
+ const fields = [];
1827
+ const types = [];
1828
+ const idNames = new Map();
1829
+ for (const ps of ast.propertySignatures) {
1830
+ if (typeof ps.name === "symbol") {
1831
+ throw new Error("Binary layout: symbol property names are illegal");
1832
+ }
1833
+ const name = String(ps.name);
1834
+ const annotations = ps.type.context?.annotations;
1835
+ const explicit = annotations?.[FIELD_ID_ANNOTATION_KEY];
1836
+ const id = typeof explicit === "number" ? explicit : fnv32(utf8Encode.encode(name));
1837
+ if (!Number.isInteger(id) || id < 0 || id > 0xFFFFFFFF) {
1838
+ throw new Error(`Binary layout: illegal field id for ${name}`);
1839
+ }
1840
+ const names = idNames.get(id);
1841
+ if (names === undefined) idNames.set(id, [name]);else names.push(name);
1842
+ fields.push({
1843
+ name,
1844
+ id,
1845
+ tagBytes: uvarintBytes(id * FIELD_WIRE_FACTOR + FIELD_WIRE_SIZED),
1846
+ index: 0,
1847
+ optional: ps.type.context?.isOptional === true,
1848
+ annotations,
1849
+ layout: undefined,
1850
+ wireMask: 0,
1851
+ inline: false
1852
+ });
1853
+ types.push(ps.type);
1854
+ }
1855
+ for (const [id, names] of idNames) {
1856
+ if (id === 0 || names.length > 1) {
1857
+ throw new Error(`Binary layout field id collision: ${id} (${names.join(", ")})`);
1858
+ }
1859
+ }
1860
+ const extra = [];
1861
+ for (const is of ast.indexSignatures) {
1862
+ if (parameterHasSymbol(is.parameter)) {
1863
+ throw new Error("Binary layout: symbol property names are illegal");
1864
+ }
1865
+ extra.push({
1866
+ parameter: is.parameter,
1867
+ layout: undefined,
1868
+ wireMask: 0
1869
+ });
1870
+ }
1871
+ const layout = {
1872
+ _: "struct",
1873
+ ast,
1874
+ fields,
1875
+ byId: new Map(),
1876
+ extra,
1877
+ extraAll: extra.length === 1 && matchesEveryKey(extra[0].parameter) ? extra[0] : undefined,
1878
+ names: new Set(fields.map(f => f.name)),
1879
+ extraShape: undefined,
1880
+ optionalCount: 0,
1881
+ requiredMask: 0,
1882
+ requiredWide: false
1883
+ };
1884
+ memo.set(ast, layout);
1885
+ for (let i = 0; i < fields.length; i++) {
1886
+ const field = fields[i];
1887
+ field.layout = compile(types[i]);
1888
+ field.wireMask = fieldWireMask(field.layout);
1889
+ // Recursive placeholders already have the discriminant used here.
1890
+ field.inline = isInlineSlot(field.layout);
1891
+ if (field.optional) layout.optionalCount++;
1892
+ layout.byId.set(field.id, field);
1893
+ }
1894
+ fields.sort((a, b) => a.id - b.id);
1895
+ for (let i = 0; i < fields.length; i++) fields[i].index = i;
1896
+ computeRequired(layout);
1897
+ for (let i = 0; i < extra.length; i++) {
1898
+ extra[i].layout = compile(ast.indexSignatures[i].type);
1899
+ extra[i].wireMask = fieldWireMask(extra[i].layout);
1900
+ }
1901
+ return layout;
1902
+ }
1903
+ function compileArray(ast) {
1904
+ const hasCount = ast.rest.length > 0 || ast.elements.some(e => e.context?.isOptional === true);
1905
+ const requiredElements = ast.elements.filter(e => e.context?.isOptional !== true).length;
1906
+ const tailLen = Math.max(0, ast.rest.length - 1);
1907
+ const layout = {
1908
+ _: "array",
1909
+ ast,
1910
+ elements: [],
1911
+ rest: [],
1912
+ hasCount,
1913
+ minCount: requiredElements + tailLen,
1914
+ uniform: undefined,
1915
+ uniformInline: false,
1916
+ uniformPacked: undefined,
1917
+ uniformNumbers: false,
1918
+ run: undefined
1919
+ };
1920
+ memo.set(ast, layout);
1921
+ for (const element of ast.elements) {
1922
+ layout.elements.push({
1923
+ optional: element.context?.isOptional === true,
1924
+ layout: compile(element)
1925
+ });
1926
+ }
1927
+ for (const rest of ast.rest) {
1928
+ layout.rest.push(compile(rest));
1929
+ }
1930
+ if (layout.elements.length === 0 && layout.rest.length === 1) {
1931
+ const slot = layout.rest[0];
1932
+ layout.uniform = slot;
1933
+ layout.uniformPacked = packedSize(slot);
1934
+ layout.uniformNumbers = slot._ === "number";
1935
+ layout.uniformInline = isInlineSlot(slot);
1936
+ }
1937
+ return layout;
1938
+ }
1939
+ function compileDeclaration(ast) {
1940
+ const id = representationId(ast);
1941
+ switch (id) {
1942
+ case "effect/schema/Date":
1943
+ return {
1944
+ _: "int64",
1945
+ flavor: "date"
1946
+ };
1947
+ case "effect/schema/DateTimeUtc":
1948
+ return {
1949
+ _: "int64",
1950
+ flavor: "utc"
1951
+ };
1952
+ case "effect/schema/DateTimeZoned":
1953
+ return leaf("dateTimeZoned");
1954
+ case "effect/schema/Duration":
1955
+ return leaf("duration");
1956
+ case "effect/schema/BigDecimal":
1957
+ return leaf("bigDecimal");
1958
+ case "effect/schema/Uint8Array":
1959
+ return leaf("bytes");
1960
+ }
1961
+ const tps = ast.typeParameters;
1962
+ switch (id) {
1963
+ case "effect/schema/Option":
1964
+ {
1965
+ const layout = {
1966
+ _: "option",
1967
+ value: undefined
1968
+ };
1969
+ memo.set(ast, layout);
1970
+ layout.value = compile(tps[0]);
1971
+ return layout;
1972
+ }
1973
+ case "effect/schema/Result":
1974
+ {
1975
+ const layout = {
1976
+ _: "result",
1977
+ success: undefined,
1978
+ failure: undefined
1979
+ };
1980
+ memo.set(ast, layout);
1981
+ layout.success = compile(tps[0]);
1982
+ layout.failure = compile(tps[1]);
1983
+ return layout;
1984
+ }
1985
+ case "effect/schema/Exit":
1986
+ {
1987
+ const cause = {
1988
+ _: "cause",
1989
+ error: undefined,
1990
+ defect: undefined
1991
+ };
1992
+ const layout = {
1993
+ _: "exit",
1994
+ value: undefined,
1995
+ cause
1996
+ };
1997
+ memo.set(ast, layout);
1998
+ layout.value = compile(tps[0]);
1999
+ cause.error = compile(tps[1]);
2000
+ cause.defect = compile(tps[2]);
2001
+ return layout;
2002
+ }
2003
+ case "effect/schema/Cause":
2004
+ case "effect/schema/CauseReason":
2005
+ {
2006
+ const layout = {
2007
+ _: id === "effect/schema/Cause" ? "cause" : "causeReason",
2008
+ error: undefined,
2009
+ defect: undefined
2010
+ };
2011
+ memo.set(ast, layout);
2012
+ layout.error = compile(tps[0]);
2013
+ layout.defect = compile(tps[1]);
2014
+ return layout;
2015
+ }
2016
+ }
2017
+ if (id !== undefined && id in natives) {
2018
+ throw new Error(`Binary layout: native declaration ${id} has no layout constructor`);
2019
+ }
2020
+ if (isJsonDeclaration(ast)) return leaf("json");
2021
+ throw new Error(`Binary layout: declaration ${id ?? "<anonymous>"} has no toCodecJson or toCodec`);
2022
+ }
2023
+ function compileUnion(ast, members) {
2024
+ if (members.length === 0) return {
2025
+ _: "never",
2026
+ ast
2027
+ };
2028
+ const variantMembers = [];
2029
+ const rowMembers = [];
2030
+ const literalRows = new Map();
2031
+ const literalValues = new Map();
2032
+ const addLiteralRow = (kind, row) => {
2033
+ const existing = literalRows.get(kind);
2034
+ if (existing !== undefined && existing._ !== row._) {
2035
+ throw new Error("Binary layout: union members are not uniquely identifiable");
2036
+ }
2037
+ literalRows.set(kind, row);
2038
+ };
2039
+ for (const member of members) {
2040
+ if (member._tag === "Literal") {
2041
+ const kind = astKind(member);
2042
+ const values = literalValues.get(kind);
2043
+ if (values === undefined) {
2044
+ literalValues.set(kind, [member.literal]);
2045
+ } else if (!values.includes(member.literal)) {
2046
+ values.push(member.literal);
2047
+ }
2048
+ continue;
2049
+ }
2050
+ if (member._tag === "UniqueSymbol") {
2051
+ astKind(member); // validates the symbol is registered
2052
+ addLiteralRow(K.string, leaf("symbol"));
2053
+ continue;
2054
+ }
2055
+ if (member._tag === "Objects" || member._tag === "Arrays") {
2056
+ const sentinels = SchemaAST.collectSentinels(member);
2057
+ if (sentinels !== undefined && sentinels.length > 0) {
2058
+ for (const sentinel of sentinels) {
2059
+ if (typeof sentinel.key === "symbol") {
2060
+ throw new Error("Binary layout: symbol property names are illegal");
2061
+ }
2062
+ }
2063
+ variantMembers.push({
2064
+ member,
2065
+ sentinels
2066
+ });
2067
+ continue;
2068
+ }
2069
+ }
2070
+ rowMembers.push({
2071
+ member,
2072
+ kind: astKind(member)
2073
+ });
2074
+ }
2075
+ for (const [kind, values] of literalValues) {
2076
+ addLiteralRow(kind, literalLayout(leaf(literalKind(values[0])), values));
2077
+ }
2078
+ if (variantMembers.length === 0 && rowMembers.length === 0 && literalRows.size === 1) {
2079
+ return literalRows.values().next().value;
2080
+ }
2081
+ const kinds = new Set(literalRows.keys());
2082
+ for (const {
2083
+ kind
2084
+ } of rowMembers) {
2085
+ if (kinds.has(kind)) {
2086
+ throw new Error("Binary layout: union members are not uniquely identifiable");
2087
+ }
2088
+ kinds.add(kind);
2089
+ }
2090
+ if (variantMembers.length === 0 && literalRows.size === 0 && rowMembers.length === 1) {
2091
+ const layout = compile(rowMembers[0].member);
2092
+ memo.set(ast, layout);
2093
+ return layout;
2094
+ }
2095
+ const tags = new Map();
2096
+ const variantTags = [];
2097
+ for (const {
2098
+ sentinels
2099
+ } of variantMembers) {
2100
+ const tag = sentinelSetHash(sentinels);
2101
+ if (tags.has(tag)) {
2102
+ throw new Error(`Binary layout sentinel collision: ${tag}`);
2103
+ }
2104
+ tags.set(tag, sentinels);
2105
+ variantTags.push(tag);
2106
+ }
2107
+ const layout = {
2108
+ _: "union",
2109
+ ast,
2110
+ variants: [],
2111
+ byTag: new Map(),
2112
+ discriminator: undefined,
2113
+ others: [],
2114
+ byKind: new Map(),
2115
+ byPos: []
2116
+ };
2117
+ memo.set(ast, layout);
2118
+ for (let v = 0; v < variantMembers.length; v++) {
2119
+ const {
2120
+ member,
2121
+ sentinels
2122
+ } = variantMembers[v];
2123
+ const tag = variantTags[v];
2124
+ const full = compile(member);
2125
+ let payload;
2126
+ let tuple;
2127
+ if (member._tag === "Objects") {
2128
+ const struct = full;
2129
+ const sentinelNames = new Set(sentinels.map(s => String(s.key)));
2130
+ const fields = struct.fields.filter(f => !sentinelNames.has(f.name));
2131
+ const payloadStruct = {
2132
+ _: "struct",
2133
+ ast: struct.ast,
2134
+ fields,
2135
+ byId: new Map(fields.map(f => [f.id, f])),
2136
+ extra: struct.extra,
2137
+ extraAll: struct.extraAll,
2138
+ names: struct.names,
2139
+ extraShape: undefined,
2140
+ optionalCount: fields.reduce((count, f) => f.optional ? count + 1 : count, 0),
2141
+ requiredMask: 0,
2142
+ requiredWide: false
2143
+ };
2144
+ computeRequired(payloadStruct);
2145
+ payload = payloadStruct;
2146
+ tuple = false;
2147
+ } else {
2148
+ payload = full;
2149
+ tuple = true;
2150
+ }
2151
+ const row = {
2152
+ tag,
2153
+ sentinels,
2154
+ tuple,
2155
+ payload,
2156
+ position: 0
2157
+ };
2158
+ layout.variants.push(row);
2159
+ layout.byTag.set(tag, row);
2160
+ }
2161
+ for (const [kind, row] of literalRows) {
2162
+ layout.others.push({
2163
+ kind,
2164
+ layout: row,
2165
+ position: 0
2166
+ });
2167
+ layout.byKind.set(kind, row);
2168
+ }
2169
+ for (const {
2170
+ kind,
2171
+ member
2172
+ } of rowMembers) {
2173
+ const row = compile(member);
2174
+ layout.others.push({
2175
+ kind,
2176
+ layout: row,
2177
+ position: 0
2178
+ });
2179
+ layout.byKind.set(kind, row);
2180
+ }
2181
+ // Fingerprint positions are independent of declaration order.
2182
+ for (const row of [...layout.variants].sort((a, b) => a.tag - b.tag)) {
2183
+ row.position = layout.byPos.length;
2184
+ layout.byPos.push({
2185
+ variant: row,
2186
+ layout: row.payload
2187
+ });
2188
+ }
2189
+ for (const member of [...layout.others].sort((a, b) => a.kind - b.kind)) {
2190
+ member.position = layout.byPos.length;
2191
+ layout.byPos.push({
2192
+ variant: undefined,
2193
+ layout: member.layout
2194
+ });
2195
+ }
2196
+ // Probe specific runtime guards before `json`, which matches anything.
2197
+ layout.others.sort((a, b) => matchRank(a.layout) - matchRank(b.layout));
2198
+ layout.discriminator = findDiscriminator(layout.variants);
2199
+ return layout;
2200
+ }
2201
+ const layout = compile(root);
2202
+ return {
2203
+ layout,
2204
+ recursive,
2205
+ exact,
2206
+ exitSuccess
2207
+ };
2208
+ }
2209
+ // The parser may return the binary decoder's value directly only when that
2210
+ // decoder proves every predicate and no Schema parser behavior can change it.
2211
+ // Schemas whose decoded values the binary layer already produces and validates
2212
+ // on its own, so the schema pass around it would only repeat work. Constructor
2213
+ // defaults are ignored because they only run during construction.
2214
+ function isExact(root) {
2215
+ // A suspend that is still being walked counts as exact: if nothing else in
2216
+ // the cycle disqualifies it, the whole cycle is exact.
2217
+ const walked = new Map();
2218
+ const exact = ast => {
2219
+ if (ast.encoding !== undefined || ast.checks !== undefined || ast.encodingChecks !== undefined) {
2220
+ return false;
2221
+ }
2222
+ switch (ast._tag) {
2223
+ case "String":
2224
+ case "Symbol":
2225
+ case "Boolean":
2226
+ case "Null":
2227
+ case "Undefined":
2228
+ case "Void":
2229
+ case "Number":
2230
+ case "BigInt":
2231
+ case "Literal":
2232
+ return true;
2233
+ // The binary layer rejects every value for a never layout, in both
2234
+ // directions, so the schema pass has nothing left to say about it.
2235
+ // Inferred schemas hit this through the element type of an empty array.
2236
+ case "Never":
2237
+ return true;
2238
+ // Every decoded JSON value is a valid `unknown`, and the encoder already
2239
+ // reports the values it cannot represent, so the pass adds nothing.
2240
+ // `ObjectKeyword` is not here: the JSON layout can hand it a string.
2241
+ case "Unknown":
2242
+ case "Any":
2243
+ return true;
2244
+ case "Arrays":
2245
+ return ast.elements.every(exact) && ast.rest.every(exact);
2246
+ case "Objects":
2247
+ return ast.propertySignatures.every(property => exact(property.type)) && ast.indexSignatures.every(signature => signature.parameter._tag === "String" && exact(signature.parameter) && exact(signature.type));
2248
+ case "Union":
2249
+ return (ast.options?.mode ?? "anyOf") === "anyOf" && ast.types.every(exact);
2250
+ // The layout compiles straight through a suspend, so the binary layer
2251
+ // validates whatever the thunk returns. Only decoding gets to act on
2252
+ // this: encoding a recursive schema still needs the cycle walk, which is
2253
+ // why {@link toCodec} keeps the schema pass on that side.
2254
+ case "Suspend":
2255
+ {
2256
+ const seen = walked.get(ast);
2257
+ if (seen !== undefined) return seen;
2258
+ walked.set(ast, true);
2259
+ const result = exact(ast.thunk());
2260
+ walked.set(ast, result);
2261
+ return result;
2262
+ }
2263
+ case "Declaration":
2264
+ {
2265
+ const id = representationId(ast);
2266
+ const native = id !== undefined ? natives[id] : undefined;
2267
+ if (native === undefined) return false;
2268
+ return native.exact === true || ast.typeParameters.every(exact);
2269
+ }
2270
+ default:
2271
+ return false;
2272
+ }
2273
+ };
2274
+ return exact(root);
2275
+ }
2276
+ // A clean Exit whose success schema is exact: the binary layer fully produces
2277
+ // and validates success exits, so only failure exits need the schema pass for
2278
+ // their cause's error and defect encodings.
2279
+ function isExitWithExactSuccess(root) {
2280
+ return root._tag === "Declaration" && root.encoding === undefined && root.checks === undefined && root.encodingChecks === undefined && representationId(root) === "effect/schema/Exit" && isExact(root.typeParameters[0]);
2281
+ }
2282
+ // Layouts sharing a wire kind can still require different fingerprints.
2283
+ const F = {
2284
+ backEdge: 0,
2285
+ bool: 1,
2286
+ null: 2,
2287
+ undefined: 3,
2288
+ number: 4,
2289
+ int: 5,
2290
+ string: 6,
2291
+ symbol: 7,
2292
+ bytes: 8,
2293
+ bigint: 9,
2294
+ json: 10,
2295
+ duration: 11,
2296
+ bigDecimal: 12,
2297
+ dateTimeZoned: 13,
2298
+ date: 14,
2299
+ dateTimeUtc: 15,
2300
+ never: 16,
2301
+ struct: 17,
2302
+ array: 18,
2303
+ union: 19,
2304
+ option: 20,
2305
+ result: 21,
2306
+ exit: 22,
2307
+ cause: 23,
2308
+ causeReason: 24,
2309
+ literal: 25
2310
+ };
2311
+ // Hash the compiled layout graph, including cycle back-edge distances.
2312
+ function layoutFingerprint(root) {
2313
+ const cache = new Map();
2314
+ const stack = [];
2315
+ // Cache only subtrees that do not escape above their own root.
2316
+ let escape = Number.MAX_SAFE_INTEGER;
2317
+ function go(layout) {
2318
+ const at = stack.lastIndexOf(layout);
2319
+ if (at >= 0) {
2320
+ if (at < escape) escape = at;
2321
+ const out = [F.backEdge];
2322
+ pushUvarint(out, stack.length - at);
2323
+ return fnv64(out);
2324
+ }
2325
+ const cached = cache.get(layout);
2326
+ if (cached !== undefined) return cached;
2327
+ const self = stack.length;
2328
+ const outerEscape = escape;
2329
+ escape = Number.MAX_SAFE_INTEGER;
2330
+ stack.push(layout);
2331
+ const hash = fnv64(structure(layout));
2332
+ stack.pop();
2333
+ const closed = escape >= self;
2334
+ if (closed) cache.set(layout, hash);
2335
+ escape = closed ? outerEscape : Math.min(outerEscape, escape);
2336
+ return hash;
2337
+ }
2338
+ function structure(layout) {
2339
+ const out = [];
2340
+ switch (layout._) {
2341
+ case "bool":
2342
+ case "null":
2343
+ case "undefined":
2344
+ case "number":
2345
+ case "int":
2346
+ case "string":
2347
+ case "symbol":
2348
+ case "bytes":
2349
+ case "bigint":
2350
+ case "json":
2351
+ case "duration":
2352
+ case "bigDecimal":
2353
+ case "dateTimeZoned":
2354
+ out.push(F[layout._]);
2355
+ return out;
2356
+ case "literal":
2357
+ {
2358
+ out.push(F.literal);
2359
+ pushBytes(out, structure(layout.leaf));
2360
+ pushUvarint(out, layout.values.length);
2361
+ // Sorted, so a union hashes the same whatever order it declares.
2362
+ const sorted = layout.values.map(value => [sentinelLiteralKind(value), sentinelLiteralString(value)]).sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[0] - b[0]);
2363
+ for (const [kind, text] of sorted) {
2364
+ out.push(kind);
2365
+ const bytes = utf8Encode.encode(text);
2366
+ pushUvarint(out, bytes.length);
2367
+ pushBytes(out, bytes);
2368
+ }
2369
+ return out;
2370
+ }
2371
+ case "int64":
2372
+ out.push(layout.flavor === "date" ? F.date : F.dateTimeUtc);
2373
+ return out;
2374
+ case "never":
2375
+ out.push(F.never);
2376
+ return out;
2377
+ case "struct":
2378
+ {
2379
+ out.push(F.struct);
2380
+ pushUvarint(out, layout.fields.length);
2381
+ for (const field of layout.fields) {
2382
+ pushU32(out, field.id);
2383
+ out.push(field.optional ? 1 : 0);
2384
+ pushU64(out, go(field.layout));
2385
+ }
2386
+ pushUvarint(out, layout.extra.length);
2387
+ for (const signature of layout.extra) pushU64(out, go(signature.layout));
2388
+ return out;
2389
+ }
2390
+ case "array":
2391
+ {
2392
+ out.push(F.array);
2393
+ pushUvarint(out, layout.elements.length);
2394
+ for (const slot of layout.elements) {
2395
+ out.push(slot.optional ? 1 : 0);
2396
+ pushU64(out, go(slot.layout));
2397
+ }
2398
+ pushUvarint(out, layout.rest.length);
2399
+ for (const rest of layout.rest) pushU64(out, go(rest));
2400
+ return out;
2401
+ }
2402
+ case "union":
2403
+ {
2404
+ out.push(F.union);
2405
+ pushUvarint(out, layout.byPos.length);
2406
+ for (const position of layout.byPos) {
2407
+ const variant = position.variant;
2408
+ if (variant === undefined) out.push(0);else {
2409
+ out.push(1, variant.tuple ? 1 : 0);
2410
+ pushU32(out, variant.tag);
2411
+ }
2412
+ pushU64(out, go(position.layout));
2413
+ }
2414
+ return out;
2415
+ }
2416
+ case "option":
2417
+ out.push(F.option);
2418
+ pushU64(out, go(layout.value));
2419
+ return out;
2420
+ case "result":
2421
+ out.push(F.result);
2422
+ pushU64(out, go(layout.success));
2423
+ pushU64(out, go(layout.failure));
2424
+ return out;
2425
+ case "exit":
2426
+ out.push(F.exit);
2427
+ pushU64(out, go(layout.value));
2428
+ pushU64(out, go(layout.cause.error));
2429
+ pushU64(out, go(layout.cause.defect));
2430
+ return out;
2431
+ case "cause":
2432
+ case "causeReason":
2433
+ out.push(layout._ === "cause" ? F.cause : F.causeReason);
2434
+ pushU64(out, go(layout.error));
2435
+ pushU64(out, go(layout.defect));
2436
+ return out;
2437
+ }
2438
+ }
2439
+ return go(root);
2440
+ }
2441
+ // A frame header the decoder can compare byte by byte, so frames that hold no
2442
+ // wide numbers never build a DataView.
2443
+ function fingerprintBytes(lo, hi) {
2444
+ const out = new Uint8Array(8);
2445
+ for (let i = 0; i < 4; i++) {
2446
+ out[i] = lo >>> i * 8 & 0xFF;
2447
+ out[i + 4] = hi >>> i * 8 & 0xFF;
2448
+ }
2449
+ return out;
2450
+ }
2451
+ const defaultMode = {
2452
+ positional: false,
2453
+ envelope: ENVELOPE,
2454
+ expectedEnvelope: "version 2 envelope, flags 0",
2455
+ fingerprint: /*#__PURE__*/new Uint8Array(8)
2456
+ };
2457
+ function fingerprintMode(layout) {
2458
+ const fingerprint = layoutFingerprint(layout);
2459
+ return {
2460
+ positional: true,
2461
+ envelope: ENVELOPE_FINGERPRINT,
2462
+ expectedEnvelope: "version 2 envelope, flags 1",
2463
+ fingerprint: fingerprintBytes(Number(fingerprint & BIGINT_U32_MASK), Number(fingerprint >> BIGINT_THIRTY_TWO & BIGINT_U32_MASK))
2464
+ };
2465
+ }
2466
+ function matchRank(layout) {
2467
+ switch (layout._) {
2468
+ case "json":
2469
+ return 2;
2470
+ case "struct":
2471
+ return 1;
2472
+ default:
2473
+ return 0;
2474
+ }
2475
+ }
2476
+ function matchesLayout(layout, value) {
2477
+ switch (layout._) {
2478
+ case "literal":
2479
+ return hasLiteral(layout, value);
2480
+ case "bool":
2481
+ return typeof value === "boolean";
2482
+ case "null":
2483
+ return value === null;
2484
+ case "undefined":
2485
+ return value === undefined;
2486
+ case "number":
2487
+ case "int":
2488
+ return typeof value === "number";
2489
+ case "string":
2490
+ return typeof value === "string";
2491
+ case "symbol":
2492
+ return typeof value === "symbol";
2493
+ case "bigint":
2494
+ return typeof value === "bigint";
2495
+ case "bytes":
2496
+ return value instanceof Uint8Array;
2497
+ case "int64":
2498
+ return layout.flavor === "date" ? value instanceof Date : DateTime.isDateTime(value) && value._tag === "Utc";
2499
+ case "dateTimeZoned":
2500
+ return DateTime.isDateTime(value) && value._tag === "Zoned";
2501
+ case "duration":
2502
+ return Duration.isDuration(value);
2503
+ case "bigDecimal":
2504
+ return BigDecimal.isBigDecimal(value);
2505
+ case "option":
2506
+ return Option.isOption(value);
2507
+ case "result":
2508
+ return Result.isResult(value);
2509
+ case "exit":
2510
+ return Exit.isExit(value);
2511
+ case "cause":
2512
+ return Cause.isCause(value);
2513
+ case "causeReason":
2514
+ return Cause.isReason(value);
2515
+ case "array":
2516
+ return Array.isArray(value);
2517
+ case "struct":
2518
+ return Predicate.isObject(value) && !Array.isArray(value);
2519
+ case "json":
2520
+ return true;
2521
+ case "union":
2522
+ case "never":
2523
+ return false;
2524
+ }
2525
+ }
2526
+ function encodeFail(expected, input, options) {
2527
+ throw issueError(new SchemaIssue.InvalidValue({
2528
+ expected
2529
+ }, input, options));
2530
+ }
2531
+ function isCyclic(value, stack = new Set()) {
2532
+ if (!Predicate.isObjectOrArray(value)) return false;
2533
+ const isArray = Array.isArray(value);
2534
+ const prototype = Object.getPrototypeOf(value);
2535
+ if (isArray || prototype === Object.prototype || prototype === null) {
2536
+ if (stack.has(value)) return true;
2537
+ stack.add(value);
2538
+ try {
2539
+ if (isArray) {
2540
+ for (let i = 0; i < value.length; i++) {
2541
+ if (isCyclic(value[i], stack)) return true;
2542
+ }
2543
+ } else {
2544
+ for (const key of Object.keys(value)) {
2545
+ if (isCyclic(value[key], stack)) return true;
2546
+ }
2547
+ }
2548
+ } finally {
2549
+ stack.delete(value);
2550
+ }
2551
+ return false;
2552
+ }
2553
+ if (value instanceof Date || value instanceof Uint8Array || DateTime.isDateTime(value) || Duration.isDuration(value) || BigDecimal.isBigDecimal(value)) return false;
2554
+ if (stack.has(value)) return true;
2555
+ stack.add(value);
2556
+ try {
2557
+ if (Option.isOption(value)) {
2558
+ return Option.isSome(value) && isCyclic(value.value, stack);
2559
+ }
2560
+ if (Result.isResult(value)) {
2561
+ return isCyclic(Result.isSuccess(value) ? value.success : value.failure, stack);
2562
+ }
2563
+ if (Exit.isExit(value)) {
2564
+ return isCyclic(Exit.isSuccess(value) ? value.value : value.cause, stack);
2565
+ }
2566
+ if (Cause.isCause(value)) {
2567
+ return value.reasons.some(reason => isCyclic(reason, stack));
2568
+ }
2569
+ if (Cause.isReason(value)) {
2570
+ switch (value._tag) {
2571
+ case "Fail":
2572
+ return isCyclic(value.error, stack);
2573
+ case "Die":
2574
+ return isCyclic(value.defect, stack);
2575
+ case "Interrupt":
2576
+ return false;
2577
+ }
2578
+ }
2579
+ if (Chunk.isChunk(value)) {
2580
+ for (const item of value) {
2581
+ if (isCyclic(item, stack)) return true;
2582
+ }
2583
+ return false;
2584
+ }
2585
+ if (HashMap.isHashMap(value)) {
2586
+ for (const [key, item] of value) {
2587
+ if (isCyclic(key, stack) || isCyclic(item, stack)) return true;
2588
+ }
2589
+ return false;
2590
+ }
2591
+ if (HashSet.isHashSet(value)) {
2592
+ for (const item of value) {
2593
+ if (isCyclic(item, stack)) return true;
2594
+ }
2595
+ return false;
2596
+ }
2597
+ if (Redacted.isRedacted(value)) {
2598
+ return isCyclic(Redacted.value(value), stack);
2599
+ }
2600
+ for (const key of Object.keys(value)) {
2601
+ if (isCyclic(value[key], stack)) return true;
2602
+ }
2603
+ } finally {
2604
+ stack.delete(value);
2605
+ }
2606
+ return false;
2607
+ }
2608
+ function encodeSized(ctx, layout, value, w) {
2609
+ const mark = w.beginSized();
2610
+ encodeValue(ctx, layout, value, w);
2611
+ w.endSized(mark);
2612
+ }
2613
+ function encodeSymbol(ctx, value, w) {
2614
+ const key = globalThis.Symbol.keyFor(value);
2615
+ if (key === undefined) encodeFail("registered symbol", value, ctx.options);
2616
+ w.string(key);
2617
+ }
2618
+ function encodeReason(ctx, layout, value, w) {
2619
+ const reason = value;
2620
+ switch (reason._tag) {
2621
+ case "Fail":
2622
+ w.byte(0);
2623
+ encodeValue(ctx, layout.error, reason.error, w);
2624
+ return;
2625
+ case "Die":
2626
+ w.byte(1);
2627
+ encodeValue(ctx, layout.defect, reason.defect, w);
2628
+ return;
2629
+ case "Interrupt":
2630
+ if (reason.fiberId === undefined) {
2631
+ w.byte(2);
2632
+ } else {
2633
+ w.byte(3);
2634
+ w.f64(reason.fiberId);
2635
+ }
2636
+ }
2637
+ }
2638
+ function isAscii(key) {
2639
+ for (let i = 0; i < key.length; i++) {
2640
+ if (key.charCodeAt(i) > 0x7F) return false;
2641
+ }
2642
+ return true;
2643
+ }
2644
+ function sameShape(shape, layout, keys) {
2645
+ if (shape.layout !== layout || shape.keys.length !== keys.length) return false;
2646
+ for (let i = 0; i < keys.length; i++) {
2647
+ if (shape.keys[i] !== keys[i]) return false;
2648
+ }
2649
+ return true;
2650
+ }
2651
+ function canCacheExtraShape(layout, keys) {
2652
+ if (layout.extraAll === undefined || keys.length > ENCODE_INDEX_SIGNATURE_CACHE_KEYS) return false;
2653
+ let codeUnits = 0;
2654
+ for (let i = 0; i < keys.length; i++) {
2655
+ codeUnits += keys[i].length;
2656
+ if (codeUnits > ENCODE_INDEX_SIGNATURE_CACHE_CODE_UNITS) return false;
2657
+ }
2658
+ return true;
2659
+ }
2660
+ // Sort extra keys by raw UTF-8 for deterministic output.
2661
+ function extraPairs(ctx, layout, obj) {
2662
+ const keys = Object.keys(obj);
2663
+ const cached = layout.extraShape;
2664
+ if (cached !== undefined && sameShape(cached, layout, keys)) return cached.pairs;
2665
+ const persistent = canCacheExtraShape(layout, keys);
2666
+ const shape = persistent ? undefined : ctx.extraShape;
2667
+ if (shape !== undefined && sameShape(shape, layout, keys)) return shape.pairs;
2668
+ const named = layout.names;
2669
+ const every = layout.extraAll;
2670
+ const pairs = [];
2671
+ let ascii = true;
2672
+ for (const key of keys) {
2673
+ if (named.has(key)) continue;
2674
+ const signature = every ?? (ctx.indexSignatures ??= new IndexSignatureCache(ctx.options)).find(layout, key);
2675
+ if (signature === undefined) continue;
2676
+ if (ascii && !isAscii(key)) ascii = false;
2677
+ pairs.push([key, signature, undefined]);
2678
+ }
2679
+ if (ascii) {
2680
+ pairs.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
2681
+ } else {
2682
+ for (const pair of pairs) pair[2] = utf8Encode.encode(pair[0]);
2683
+ pairs.sort((a, b) => compareBytes(a[2], b[2]));
2684
+ }
2685
+ if (persistent) {
2686
+ for (const pair of pairs) pair[2] ??= utf8Encode.encode(pair[0]);
2687
+ }
2688
+ const next = {
2689
+ layout,
2690
+ keys,
2691
+ pairs
2692
+ };
2693
+ if (persistent) layout.extraShape = next;else ctx.extraShape = next;
2694
+ return pairs;
2695
+ }
2696
+ function encodeExtraPairs(ctx, pairs, obj, w, keys) {
2697
+ for (const [key, signature, keyBytes] of pairs) {
2698
+ const keyLength = keyBytes === undefined ? key.length : keyBytes.length;
2699
+ const value = obj[key];
2700
+ const wire = valueWireCode(signature.layout, value, ctx.options);
2701
+ const kind = wire % FIELD_WIRE_FACTOR;
2702
+ if (keys === undefined) {
2703
+ w.uvarint(keyLength * FIELD_WIRE_FACTOR + kind);
2704
+ } else {
2705
+ if (!keys.disabled) {
2706
+ const ref = internRef(keys, key);
2707
+ if (ref !== undefined) {
2708
+ w.uvarint(ref * 16 + kind * 2 + 1);
2709
+ issuePath[issuePathLen++] = key;
2710
+ encodeWirePayload(ctx, signature.layout, value, wire, w);
2711
+ issuePathLen--;
2712
+ continue;
2713
+ }
2714
+ internAdd(keys, key);
2715
+ }
2716
+ w.uvarint(keyLength * 16 + kind * 2);
2717
+ }
2718
+ if (keyBytes === undefined) w.string(key);else w.bytes(keyBytes);
2719
+ issuePath[issuePathLen++] = key;
2720
+ encodeWirePayload(ctx, signature.layout, value, wire, w);
2721
+ issuePathLen--;
2722
+ }
2723
+ }
2724
+ // Decimal scale rides above the low three kind bits internally, avoiding a
2725
+ // second decimalScale scan when the payload is written.
2726
+ function valueWireCode(layout, value, options) {
2727
+ if (layout._ === "literal") {
2728
+ if (!hasLiteral(layout, value)) encodeFail(literalExpected(layout), value, options);
2729
+ return valueWireCode(layout.leaf, value, options);
2730
+ }
2731
+ switch (layout._) {
2732
+ case "bool":
2733
+ if (typeof value !== "boolean") encodeFail("a boolean", value, options);
2734
+ return value ? FIELD_WIRE_TRUE : FIELD_WIRE_FALSE;
2735
+ case "number":
2736
+ if (typeof value !== "number") encodeFail("a number", value, options);
2737
+ if (isVarintNumber(value)) return FIELD_WIRE_VARINT;
2738
+ {
2739
+ const scale = decimalScale(value);
2740
+ return scale === 0 ? FIELD_WIRE_FIXED64 : scale * FIELD_WIRE_FACTOR + FIELD_WIRE_DECIMAL;
2741
+ }
2742
+ case "int":
2743
+ if (!Number.isSafeInteger(value)) encodeFail("an integer", value, options);
2744
+ return FIELD_WIRE_VARINT;
2745
+ default:
2746
+ return FIELD_WIRE_SIZED;
2747
+ }
2748
+ }
2749
+ function encodeWirePayload(ctx, layout, value, wire, w) {
2750
+ const kind = wire % FIELD_WIRE_FACTOR;
2751
+ switch (kind) {
2752
+ // EMPTY and FIXED32 are decoder-side skip support only; `valueWireCode`
2753
+ // never produces them.
2754
+ case FIELD_WIRE_FALSE:
2755
+ case FIELD_WIRE_TRUE:
2756
+ return;
2757
+ case FIELD_WIRE_VARINT:
2758
+ w.numberVarint(value);
2759
+ return;
2760
+ case FIELD_WIRE_FIXED64:
2761
+ w.f64(value);
2762
+ return;
2763
+ case FIELD_WIRE_DECIMAL:
2764
+ {
2765
+ const scale = Math.floor(wire / FIELD_WIRE_FACTOR);
2766
+ w.numberVarint(Math.round(value * POW10[scale]));
2767
+ w.uvarint(scale);
2768
+ return;
2769
+ }
2770
+ default:
2771
+ encodeSized(ctx, layout, value, w);
2772
+ }
2773
+ }
2774
+ function encodeStructField(ctx, field, value, w) {
2775
+ const wire = valueWireCode(field.layout, value, ctx.options);
2776
+ const kind = wire % FIELD_WIRE_FACTOR;
2777
+ if (kind === FIELD_WIRE_SIZED) {
2778
+ const mark = w.idAndMark(field.tagBytes);
2779
+ encodeValue(ctx, field.layout, value, w);
2780
+ w.endSized(mark);
2781
+ return;
2782
+ }
2783
+ w.uvarint(field.id * FIELD_WIRE_FACTOR + kind);
2784
+ encodeWirePayload(ctx, field.layout, value, wire, w);
2785
+ }
2786
+ function runPresenceMask(plan, obj) {
2787
+ const byName = plan.byName;
2788
+ if (byName === undefined) return undefined;
2789
+ const keys = Object.getOwnPropertyNames(obj);
2790
+ let mask = 0;
2791
+ for (let i = 0; i < keys.length; i++) {
2792
+ const index = byName.get(keys[i]);
2793
+ if (index !== undefined) mask |= 1 << index;
2794
+ }
2795
+ const struct = plan.struct;
2796
+ if ((mask & struct.requiredMask) !== struct.requiredMask) {
2797
+ const fields = struct.fields;
2798
+ for (let i = 0; i < fields.length; i++) {
2799
+ const field = fields[i];
2800
+ if (!field.optional && (mask & 1 << i) === 0) {
2801
+ issuePath[issuePathLen++] = field.name;
2802
+ throw issueError(new SchemaIssue.MissingKey(field.annotations));
2803
+ }
2804
+ }
2805
+ }
2806
+ return mask;
2807
+ }
2808
+ function encodeStructFields(ctx, layout, value, w) {
2809
+ const obj = value;
2810
+ if (layout.extra.length > 0) {
2811
+ // Only a run field with index signatures hands over an intern table.
2812
+ const keys = ctx.intern;
2813
+ ctx.intern = undefined;
2814
+ const pairs = extraPairs(ctx, layout, obj);
2815
+ if (pairs.length > 0) {
2816
+ w.uvarint(0);
2817
+ const mark = w.beginSized();
2818
+ encodeExtraPairs(ctx, pairs, obj, w, keys);
2819
+ w.endSized(mark);
2820
+ }
2821
+ }
2822
+ const fields = layout.fields;
2823
+ for (let i = 0; i < fields.length; i++) {
2824
+ const field = fields[i];
2825
+ const name = field.name;
2826
+ if (!Object.hasOwn(obj, name)) {
2827
+ if (field.optional) continue;
2828
+ issuePath[issuePathLen++] = name;
2829
+ throw issueError(new SchemaIssue.MissingKey(field.annotations));
2830
+ }
2831
+ issuePath[issuePathLen++] = name;
2832
+ encodeStructField(ctx, field, obj[name], w);
2833
+ issuePathLen--;
2834
+ }
2835
+ }
2836
+ // Fingerprint structs use a presence bitmap followed by positional fields.
2837
+ function encodeStructPositional(ctx, layout, value, w) {
2838
+ const obj = value;
2839
+ // Only a run field with index signatures hands over an intern table. Extras
2840
+ // encode after the fields here, so claim it before a nested field can.
2841
+ const keys = ctx.intern;
2842
+ ctx.intern = undefined;
2843
+ const bitmapBytes = layout.optionalCount + 7 >> 3;
2844
+ let bitmap = 0;
2845
+ if (bitmapBytes > 0) {
2846
+ bitmap = w.len;
2847
+ for (let i = 0; i < bitmapBytes; i++) w.byte(0);
2848
+ }
2849
+ const fields = layout.fields;
2850
+ let optionalIndex = 0;
2851
+ for (let i = 0; i < fields.length; i++) {
2852
+ const field = fields[i];
2853
+ const name = field.name;
2854
+ const present = Object.hasOwn(obj, name);
2855
+ if (field.optional) {
2856
+ // Resolve the bitmap address again after any arena growth.
2857
+ if (present) w.buf[w.start + bitmap + (optionalIndex >> 3)] |= 1 << (optionalIndex & 7);
2858
+ optionalIndex++;
2859
+ if (!present) continue;
2860
+ } else if (!present) {
2861
+ issuePath[issuePathLen++] = name;
2862
+ throw issueError(new SchemaIssue.MissingKey(field.annotations));
2863
+ }
2864
+ issuePath[issuePathLen++] = name;
2865
+ if (field.inline) encodeValue(ctx, field.layout, obj[name], w);else encodeSized(ctx, field.layout, obj[name], w);
2866
+ issuePathLen--;
2867
+ }
2868
+ if (layout.extra.length > 0) {
2869
+ const pairs = extraPairs(ctx, layout, obj);
2870
+ w.uvarint(pairs.length);
2871
+ encodeExtraPairs(ctx, pairs, obj, w, keys);
2872
+ }
2873
+ }
2874
+ function internKind(layout) {
2875
+ switch (layout._) {
2876
+ case "string":
2877
+ return INTERN_SELF;
2878
+ case "array":
2879
+ return layout.uniform?._ === "string" ? INTERN_ELEMENTS : INTERN_NONE;
2880
+ case "struct":
2881
+ return layout.extra.length > 0 ? INTERN_KEYS : INTERN_NONE;
2882
+ default:
2883
+ return INTERN_NONE;
2884
+ }
2885
+ }
2886
+ // `Schema.Array(S)` and `Schema.NonEmptyArray(S)` both give every slot one layout.
2887
+ function runStruct(layout) {
2888
+ let uniform = layout.uniform;
2889
+ if (uniform === undefined) {
2890
+ if (layout.rest.length !== 1) return undefined;
2891
+ uniform = layout.rest[0];
2892
+ for (const slot of layout.elements) {
2893
+ if (slot.optional || slot.layout !== uniform) return undefined;
2894
+ }
2895
+ }
2896
+ return uniform._ === "struct" ? uniform : undefined;
2897
+ }
2898
+ function runPlan(layout) {
2899
+ let plan = layout.run;
2900
+ if (plan !== undefined) return plan;
2901
+ const struct = runStruct(layout);
2902
+ if (struct === undefined) {
2903
+ layout.run = plan = null;
2904
+ return plan;
2905
+ }
2906
+ const intern = struct.fields.map(field => internKind(field.layout));
2907
+ const shapes = struct.fields.length <= RUN_MAX_FIELDS;
2908
+ plan = {
2909
+ struct,
2910
+ intern,
2911
+ shapes,
2912
+ byName: shapes && struct.extra.length === 0 ? new Map(struct.fields.map((field, index) => [field.name, index])) : undefined
2913
+ };
2914
+ layout.run = plan;
2915
+ return plan;
2916
+ }
2917
+ const INTERN_MAP_AT = 16;
2918
+ const INTERN_DISABLE_AT = 64;
2919
+ function internWrite(tables, index) {
2920
+ return tables[index] ??= {
2921
+ values: [],
2922
+ refs: undefined,
2923
+ hits: 0,
2924
+ disabled: false
2925
+ };
2926
+ }
2927
+ function internRef(table, value) {
2928
+ const refs = table.refs;
2929
+ if (refs !== undefined) {
2930
+ const ref = refs.get(value);
2931
+ if (ref !== undefined) table.hits++;
2932
+ return ref;
2933
+ }
2934
+ const values = table.values;
2935
+ for (let i = 0; i < values.length; i++) {
2936
+ if (values[i] === value) {
2937
+ table.hits++;
2938
+ return i;
2939
+ }
2940
+ }
2941
+ return undefined;
2942
+ }
2943
+ function internAdd(table, value) {
2944
+ const values = table.values;
2945
+ if (table.refs !== undefined) {
2946
+ if (table.hits === 0 && values.length >= INTERN_DISABLE_AT) {
2947
+ table.disabled = true;
2948
+ table.refs = undefined;
2949
+ return;
2950
+ }
2951
+ table.refs.set(value, values.length);
2952
+ } else if (values.length >= INTERN_MAP_AT) {
2953
+ const refs = table.refs = new Map();
2954
+ for (let i = 0; i < values.length; i++) refs.set(values[i], i);
2955
+ refs.set(value, values.length);
2956
+ }
2957
+ values.push(value);
2958
+ }
2959
+ // A connection dictionary: string tables that outlive a single frame. The
2960
+ // writer and the reader build the same tables from the same frames, so a
2961
+ // reference means the same string on both ends. Fields that share a schema
2962
+ // object share a table, which is why `Schema.String` fields all land in one:
2963
+ // splitting them costs every layout a few percent and buys the RPC envelope,
2964
+ // where every string repeats, nothing.
2965
+ //
2966
+ // A leaf starts out only watching. It writes plain strings and remembers them
2967
+ // until one comes back, and only then starts writing references. A leaf whose
2968
+ // strings never repeat gives up and goes back to writing plain strings for
2969
+ // good, so it never costs a byte more than no dictionary at all.
2970
+ const DICT_WATCHING = 0;
2971
+ const DICT_REFERENCING = 1;
2972
+ const DICT_GAVE_UP = 2;
2973
+ // How many distinct strings a leaf watches before giving up on it.
2974
+ const DICT_WATCH_LIMIT = 64;
2975
+ // How many strings one leaf keeps once it is referencing.
2976
+ const DICT_MAX_ENTRIES = 512;
2977
+ function makeDictWrite() {
2978
+ return {
2979
+ slots: [],
2980
+ marks: [],
2981
+ frame: 0
2982
+ };
2983
+ }
2984
+ function dictSlot(slots, index) {
2985
+ return slots[index] ??= {
2986
+ values: [],
2987
+ refs: new Map(),
2988
+ state: DICT_WATCHING,
2989
+ stamp: -1
2990
+ };
2991
+ }
2992
+ function dictWatch(slot, value) {
2993
+ if (slot.refs.has(value)) {
2994
+ slot.state = DICT_REFERENCING;
2995
+ return;
2996
+ }
2997
+ slot.refs.set(value, slot.values.length);
2998
+ slot.values.push(value);
2999
+ if (slot.values.length >= DICT_WATCH_LIMIT) slot.state = DICT_GAVE_UP;
3000
+ }
3001
+ function dictAdd(slot, value) {
3002
+ const values = slot.values;
3003
+ if (values.length >= DICT_MAX_ENTRIES) return;
3004
+ slot.refs.set(value, values.length);
3005
+ values.push(value);
3006
+ }
3007
+ function dictMark(dict, slot) {
3008
+ if (slot.stamp === dict.frame) return;
3009
+ slot.stamp = dict.frame;
3010
+ dict.marks.push({
3011
+ slot,
3012
+ length: slot.values.length,
3013
+ state: slot.state
3014
+ });
3015
+ }
3016
+ function dictCommit(dict) {
3017
+ dict.marks.length = 0;
3018
+ dict.frame++;
3019
+ }
3020
+ function dictRollback(dict) {
3021
+ const marks = dict.marks;
3022
+ for (let i = marks.length - 1; i >= 0; i--) {
3023
+ const {
3024
+ length,
3025
+ slot,
3026
+ state
3027
+ } = marks[i];
3028
+ const values = slot.values;
3029
+ for (let j = length; j < values.length; j++) slot.refs.delete(values[j]);
3030
+ values.length = length;
3031
+ slot.state = state;
3032
+ }
3033
+ marks.length = 0;
3034
+ dict.frame++;
3035
+ }
3036
+ // A referencing leaf writes either a reference or a zero marker and the string.
3037
+ // A watching leaf writes the string alone, so watching costs nothing on the
3038
+ // wire.
3039
+ function encodeString(dict, layout, value, w) {
3040
+ const slot = dictSlot(dict.slots, layout.slot);
3041
+ const state = slot.state;
3042
+ if (state === DICT_GAVE_UP) {
3043
+ w.string(value);
3044
+ return;
3045
+ }
3046
+ dictMark(dict, slot);
3047
+ if (state === DICT_WATCHING) {
3048
+ w.string(value);
3049
+ dictWatch(slot, value);
3050
+ return;
3051
+ }
3052
+ const ref = slot.refs.get(value);
3053
+ if (ref !== undefined) {
3054
+ w.uvarint(ref * 2 + 1);
3055
+ return;
3056
+ }
3057
+ w.byte(0);
3058
+ dictAdd(slot, value);
3059
+ w.string(value);
3060
+ }
3061
+ function decodeString(dict, layout, r) {
3062
+ const slot = dictSlot(dict, layout.slot);
3063
+ const state = slot.state;
3064
+ if (state === DICT_GAVE_UP) return r.readUtf8(r.end - r.pos);
3065
+ if (state === DICT_WATCHING) {
3066
+ const value = r.readUtf8(r.end - r.pos);
3067
+ dictWatch(slot, value);
3068
+ return value;
3069
+ }
3070
+ const marker = r.uvarint();
3071
+ if ((marker & 1) === 1) {
3072
+ const ref = (marker - 1) / 2;
3073
+ const values = slot.values;
3074
+ if (ref >= values.length) invalid("a dictionary reference", marker, r.options);
3075
+ return values[ref];
3076
+ }
3077
+ if (marker !== 0) invalid("a dictionary marker", marker, r.options);
3078
+ const value = r.readUtf8(r.end - r.pos);
3079
+ dictAdd(slot, value);
3080
+ return value;
3081
+ }
3082
+ function encodeInterned(table, ctx, layout, value, w) {
3083
+ if (!table.disabled) {
3084
+ const ref = internRef(table, value);
3085
+ if (ref !== undefined) {
3086
+ w.uvarint(ref * 2 + 1);
3087
+ return;
3088
+ }
3089
+ internAdd(table, value);
3090
+ }
3091
+ const mark = w.beginSized();
3092
+ encodeValue(ctx, layout, value, w);
3093
+ w.endSizedRun(mark);
3094
+ }
3095
+ function encodeStructRun(ctx, plan, arr, count, w) {
3096
+ const shapes = [];
3097
+ const tables = [];
3098
+ for (let i = 0; i < count; i++) {
3099
+ issuePath[issuePathLen++] = i;
3100
+ const mark = w.beginSized();
3101
+ encodeRunRow(ctx, plan, shapes, tables, arr[i], w);
3102
+ w.endSized(mark);
3103
+ issuePathLen--;
3104
+ }
3105
+ }
3106
+ function encodeRunRow(ctx, plan, shapes, tables, value, w) {
3107
+ const struct = plan.struct;
3108
+ const obj = value;
3109
+ const fields = struct.fields;
3110
+ let pairs;
3111
+ if (struct.extra.length > 0) {
3112
+ const found = extraPairs(ctx, struct, obj);
3113
+ if (found.length > 0) pairs = found;
3114
+ }
3115
+ const wide = !plan.shapes;
3116
+ let mask = pairs === undefined ? 0 : RUN_EXTRA_BIT;
3117
+ const presenceMask = runPresenceMask(plan, obj);
3118
+ if (presenceMask !== undefined) {
3119
+ mask = presenceMask;
3120
+ } else {
3121
+ for (let i = 0; i < fields.length; i++) {
3122
+ const field = fields[i];
3123
+ if (Object.hasOwn(obj, field.name)) {
3124
+ if (!wide) mask |= 1 << i;
3125
+ } else if (!field.optional) {
3126
+ issuePath[issuePathLen++] = field.name;
3127
+ throw issueError(new SchemaIssue.MissingKey(field.annotations));
3128
+ }
3129
+ }
3130
+ }
3131
+ let shape = -1;
3132
+ for (let i = 0; i < shapes.length; i++) {
3133
+ if (shapes[i] === mask) {
3134
+ shape = i;
3135
+ break;
3136
+ }
3137
+ }
3138
+ if (shape >= 0) {
3139
+ w.uvarint(shape + 1);
3140
+ } else {
3141
+ w.uvarint(0);
3142
+ if (!wide) shapes.push(mask);
3143
+ }
3144
+ const declare = shape < 0;
3145
+ // Fingerprint mode proves both layouts match, so a declared shape is the
3146
+ // presence mask instead of a field id list.
3147
+ const positionalShape = ctx.positional && !wide;
3148
+ if (declare && positionalShape) w.uvarint(mask);
3149
+ if (pairs !== undefined) {
3150
+ if (declare && !positionalShape) w.uvarint(0);
3151
+ const mark = w.beginSized();
3152
+ encodeExtraPairs(ctx, pairs, obj, w);
3153
+ w.endSizedRun(mark);
3154
+ }
3155
+ for (let i = 0; i < fields.length; i++) {
3156
+ const field = fields[i];
3157
+ if (wide ? !Object.hasOwn(obj, field.name) : (mask & 1 << i) === 0) continue;
3158
+ if (declare && !positionalShape) w.uvarint(field.id);
3159
+ issuePath[issuePathLen++] = field.name;
3160
+ const kind = plan.intern[i];
3161
+ if (kind === INTERN_SELF) {
3162
+ encodeInterned(internWrite(tables, i), ctx, field.layout, obj[field.name], w);
3163
+ } else {
3164
+ if (kind !== INTERN_NONE) ctx.intern = internWrite(tables, i);
3165
+ const mark = w.beginSized();
3166
+ encodeValue(ctx, field.layout, obj[field.name], w);
3167
+ w.endSizedRun(mark);
3168
+ ctx.intern = undefined;
3169
+ }
3170
+ issuePathLen--;
3171
+ }
3172
+ }
3173
+ function arraySlot(layout, index, count) {
3174
+ const elementLen = layout.elements.length;
3175
+ if (index < elementLen) return layout.elements[index].layout;
3176
+ const tailLen = Math.max(0, layout.rest.length - 1);
3177
+ const tailThreshold = Math.max(elementLen, count - tailLen);
3178
+ return index >= tailThreshold ? layout.rest[index - tailThreshold + 1] : layout.rest[0];
3179
+ }
3180
+ function encodeArray(ctx, layout, arr, w) {
3181
+ const count = arr.length;
3182
+ if (layout.rest.length === 0 && count > layout.elements.length) {
3183
+ issuePath[issuePathLen++] = layout.elements.length;
3184
+ throw issueError(new SchemaIssue.UnexpectedKey(layout.ast, arr[layout.elements.length], ctx.options));
3185
+ }
3186
+ if (count < layout.minCount) {
3187
+ issuePath[issuePathLen++] = count;
3188
+ throw issueError(new SchemaIssue.MissingKey(undefined));
3189
+ }
3190
+ if (layout.hasCount) w.uvarint(count);
3191
+ if (count > 0) {
3192
+ const plan = runPlan(layout);
3193
+ if (plan !== null) {
3194
+ encodeStructRun(ctx, plan, arr, count, w);
3195
+ return;
3196
+ }
3197
+ }
3198
+ const uniform = layout.uniform;
3199
+ if (uniform !== undefined) {
3200
+ if (layout.uniformNumbers) {
3201
+ encodeNumberRun(ctx, arr, count, w);
3202
+ return;
3203
+ }
3204
+ // Only a run field holding an array of strings hands over an intern table.
3205
+ const table = ctx.intern;
3206
+ ctx.intern = undefined;
3207
+ if (table !== undefined) {
3208
+ for (let i = 0; i < count; i++) {
3209
+ issuePath[issuePathLen++] = i;
3210
+ encodeInterned(table, ctx, uniform, arr[i], w);
3211
+ issuePathLen--;
3212
+ }
3213
+ return;
3214
+ }
3215
+ const inline = layout.uniformInline;
3216
+ for (let i = 0; i < count; i++) {
3217
+ issuePath[issuePathLen++] = i;
3218
+ if (inline) encodeValue(ctx, uniform, arr[i], w);else encodeSized(ctx, uniform, arr[i], w);
3219
+ issuePathLen--;
3220
+ }
3221
+ return;
3222
+ }
3223
+ for (let i = 0; i < count; i++) {
3224
+ const slot = arraySlot(layout, i, count);
3225
+ issuePath[issuePathLen++] = i;
3226
+ if (isInlineSlot(slot)) {
3227
+ encodeValue(ctx, slot, arr[i], w);
3228
+ } else {
3229
+ encodeSized(ctx, slot, arr[i], w);
3230
+ }
3231
+ issuePathLen--;
3232
+ }
3233
+ }
3234
+ // Uniform number arrays share one mode byte: varint, packed decimal, or f64.
3235
+ // Scales found by the classification pass, reused by the decimal write pass so
3236
+ // each non-integer scans `decimalScale` once. Only written and read within one
3237
+ // synchronous `encodeNumberRun` call.
3238
+ const numberRunScales = [];
3239
+ function encodeNumberRun(ctx, arr, count, w) {
3240
+ let varint = true;
3241
+ let decimal = true;
3242
+ for (let i = 0; i < count; i++) {
3243
+ const value = arr[i];
3244
+ if (typeof value !== "number") {
3245
+ issuePath[issuePathLen++] = i;
3246
+ encodeFail("a number", value, ctx.options);
3247
+ }
3248
+ if (isVarintNumber(value)) {
3249
+ const magnitude = value < 0 ? -value : value;
3250
+ if (magnitude > DECIMAL_MANTISSA_MAX) decimal = false;
3251
+ } else {
3252
+ varint = false;
3253
+ const scale = decimalScale(value);
3254
+ if (scale === 0) decimal = false;else numberRunScales[i] = scale;
3255
+ }
3256
+ if (!varint && !decimal) break;
3257
+ }
3258
+ if (varint) {
3259
+ w.byte(NUMBER_RUN_VARINT);
3260
+ for (let i = 0; i < count; i++) w.numberVarint(arr[i]);
3261
+ } else if (decimal) {
3262
+ w.byte(NUMBER_RUN_DECIMAL);
3263
+ for (let i = 0; i < count; i++) {
3264
+ const value = arr[i];
3265
+ // Integers take scale 0 even when a scale would fit, matching the
3266
+ // classification pass writing scales only for non-integers.
3267
+ const scale = Number.isInteger(value) ? 0 : numberRunScales[i];
3268
+ const mantissa = scale === 0 ? value : Math.round(value * POW10[scale]);
3269
+ const negative = mantissa < 0 || mantissa === 0 && 1 / mantissa < 0;
3270
+ const magnitude = negative ? -mantissa : mantissa;
3271
+ w.uvarint((magnitude * 2 + (negative ? 1 : 0)) * 16 + scale);
3272
+ }
3273
+ } else {
3274
+ w.byte(NUMBER_RUN_F64);
3275
+ for (let i = 0; i < count; i++) w.f64(arr[i]);
3276
+ }
3277
+ }
3278
+ function findDiscriminator(variants) {
3279
+ if (variants.length < 2 || variants.some(variant => variant.tuple)) return undefined;
3280
+ for (const candidate of variants[0].sentinels) {
3281
+ const rows = new Map();
3282
+ for (const variant of variants) {
3283
+ const sentinel = variant.sentinels.find(s => s.key === candidate.key);
3284
+ // `NaN` matches under `Map`'s key equality but not under `===`.
3285
+ if (sentinel === undefined || rows.has(sentinel.literal) || Number.isNaN(sentinel.literal)) break;
3286
+ rows.set(sentinel.literal, variant);
3287
+ }
3288
+ if (rows.size === variants.length) return {
3289
+ key: candidate.key,
3290
+ rows
3291
+ };
3292
+ }
3293
+ return undefined;
3294
+ }
3295
+ // An inherited sentinel does not select a variant, matching the schema pass.
3296
+ function hasSentinels(variant, value) {
3297
+ const sentinels = variant.sentinels;
3298
+ for (let i = 0; i < sentinels.length; i++) {
3299
+ const {
3300
+ key,
3301
+ literal
3302
+ } = sentinels[i];
3303
+ if (value[key] !== literal || !Object.hasOwn(value, key)) return false;
3304
+ }
3305
+ return true;
3306
+ }
3307
+ function matchesVariant(variant, value) {
3308
+ return variant.tuple ? Array.isArray(value) && hasSentinels(variant, value) : Predicate.isObject(value) && !Array.isArray(value) && hasSentinels(variant, value);
3309
+ }
3310
+ function encodeVariant(ctx, variant, value, w) {
3311
+ if (ctx.positional) {
3312
+ w.uvarint(variant.position);
3313
+ } else {
3314
+ w.byte(K.variant);
3315
+ w.u32le(variant.tag);
3316
+ }
3317
+ encodeValue(ctx, variant.payload, value, w);
3318
+ }
3319
+ function encodeUnion(ctx, layout, value, w) {
3320
+ const discriminator = layout.discriminator;
3321
+ if (discriminator !== undefined) {
3322
+ // A miss rules out every variant, because each one pins this key to a
3323
+ // literal no other variant uses.
3324
+ if (Predicate.isObject(value) && !Array.isArray(value)) {
3325
+ const record = value;
3326
+ const variant = discriminator.rows.get(record[discriminator.key]);
3327
+ if (variant !== undefined && hasSentinels(variant, record)) {
3328
+ encodeVariant(ctx, variant, value, w);
3329
+ return;
3330
+ }
3331
+ }
3332
+ } else {
3333
+ for (const variant of layout.variants) {
3334
+ if (matchesVariant(variant, value)) {
3335
+ encodeVariant(ctx, variant, value, w);
3336
+ return;
3337
+ }
3338
+ }
3339
+ }
3340
+ for (const member of layout.others) {
3341
+ if (matchesLayout(member.layout, value)) {
3342
+ if (ctx.positional) w.uvarint(member.position);else w.byte(member.kind);
3343
+ encodeValue(ctx, member.layout, value, w);
3344
+ return;
3345
+ }
3346
+ }
3347
+ throw issueError(new SchemaIssue.InvalidType(layout.ast, value, ctx.options));
3348
+ }
3349
+ function encodeValue(ctx, layout, value, w) {
3350
+ switch (layout._) {
3351
+ case "literal":
3352
+ if (!hasLiteral(layout, value)) encodeFail(literalExpected(layout), value, ctx.options);
3353
+ encodeValue(ctx, layout.leaf, value, w);
3354
+ return;
3355
+ case "bool":
3356
+ if (typeof value !== "boolean") encodeFail("a boolean", value, ctx.options);
3357
+ w.byte(value === true ? 1 : 0);
3358
+ return;
3359
+ case "null":
3360
+ if (value !== null) encodeFail("null", value, ctx.options);
3361
+ return;
3362
+ case "undefined":
3363
+ if (value !== undefined) encodeFail("undefined", value, ctx.options);
3364
+ return;
3365
+ case "number":
3366
+ {
3367
+ if (typeof value !== "number") encodeFail("a number", value, ctx.options);
3368
+ if (isVarintNumber(value)) {
3369
+ w.numberVarint(value);
3370
+ return;
3371
+ }
3372
+ const scale = decimalScale(value);
3373
+ if (scale > 0) {
3374
+ w.numberVarint(Math.round(value * POW10[scale]));
3375
+ w.byte(scale);
3376
+ } else {
3377
+ w.f64(value);
3378
+ }
3379
+ return;
3380
+ }
3381
+ case "int":
3382
+ {
3383
+ // `disableChecks` can bypass the integer check used to select this layout.
3384
+ if (!Number.isSafeInteger(value)) encodeFail("an integer", value, ctx.options);
3385
+ w.numberVarint(value);
3386
+ return;
3387
+ }
3388
+ case "string":
3389
+ {
3390
+ if (typeof value !== "string") encodeFail("a string", value, ctx.options);
3391
+ const dict = ctx.dict;
3392
+ if (dict === undefined) w.string(value);else encodeString(dict, layout, value, w);
3393
+ return;
3394
+ }
3395
+ case "symbol":
3396
+ if (typeof value !== "symbol") encodeFail("a symbol", value, ctx.options);
3397
+ encodeSymbol(ctx, value, w);
3398
+ return;
3399
+ case "bytes":
3400
+ if (!(value instanceof Uint8Array)) encodeFail("a Uint8Array", value, ctx.options);
3401
+ w.bytes(value);
3402
+ return;
3403
+ case "bigint":
3404
+ if (typeof value !== "bigint") encodeFail("a bigint", value, ctx.options);
3405
+ w.zigzag(value);
3406
+ return;
3407
+ case "int64":
3408
+ {
3409
+ if (!matchesLayout(layout, value)) {
3410
+ encodeFail(layout.flavor === "date" ? "a Date" : "a DateTime.Utc", value, ctx.options);
3411
+ }
3412
+ const millis = layout.flavor === "date" ? value.getTime() : value.epochMilliseconds;
3413
+ if (Number.isNaN(millis)) encodeFail("a valid Date", value, ctx.options);
3414
+ w.i64(BigInt(millis));
3415
+ return;
3416
+ }
3417
+ case "dateTimeZoned":
3418
+ {
3419
+ if (!matchesLayout(layout, value)) encodeFail("a DateTime.Zoned", value, ctx.options);
3420
+ const zoned = value;
3421
+ w.i64(BigInt(zoned.epochMilliseconds));
3422
+ if (zoned.zone._tag === "Offset") {
3423
+ w.byte(0);
3424
+ w.i32le(zoned.zone.offset);
3425
+ } else {
3426
+ w.byte(1);
3427
+ w.string(zoned.zone.id);
3428
+ }
3429
+ return;
3430
+ }
3431
+ case "duration":
3432
+ {
3433
+ if (!Duration.isDuration(value)) encodeFail("a Duration", value, ctx.options);
3434
+ const duration = value.value;
3435
+ switch (duration._tag) {
3436
+ case "Infinity":
3437
+ w.byte(1);
3438
+ return;
3439
+ case "NegativeInfinity":
3440
+ w.byte(2);
3441
+ return;
3442
+ case "Nanos":
3443
+ w.byte(0);
3444
+ w.zigzag(duration.nanos);
3445
+ return;
3446
+ case "Millis":
3447
+ w.byte(0);
3448
+ w.zigzag(BigInt(duration.millis) * BIGINT_NANOS_PER_MILLI);
3449
+ return;
3450
+ }
3451
+ }
3452
+ case "bigDecimal":
3453
+ {
3454
+ if (!BigDecimal.isBigDecimal(value)) encodeFail("a BigDecimal", value, ctx.options);
3455
+ const normalized = BigDecimal.normalize(value);
3456
+ w.zigzag(normalized.value);
3457
+ w.zigzag(BigInt(normalized.scale));
3458
+ return;
3459
+ }
3460
+ case "json":
3461
+ {
3462
+ let text;
3463
+ try {
3464
+ text = JSON.stringify(value);
3465
+ } catch {
3466
+ text = undefined;
3467
+ }
3468
+ if (text === undefined) {
3469
+ if (isCyclic(value)) encodeFail("acyclic value", value, ctx.options);
3470
+ encodeFail("a JSON-serializable value", value, ctx.options);
3471
+ }
3472
+ w.string(text);
3473
+ return;
3474
+ }
3475
+ case "option":
3476
+ {
3477
+ if (!Option.isOption(value)) encodeFail("an Option", value, ctx.options);
3478
+ const option = value;
3479
+ if (option._tag === "None") {
3480
+ w.byte(0);
3481
+ } else {
3482
+ w.byte(1);
3483
+ encodeValue(ctx, layout.value, option.value, w);
3484
+ }
3485
+ return;
3486
+ }
3487
+ case "result":
3488
+ {
3489
+ if (!Result.isResult(value)) encodeFail("a Result", value, ctx.options);
3490
+ const result = value;
3491
+ if (result._tag === "Success") {
3492
+ w.byte(0);
3493
+ encodeValue(ctx, layout.success, result.success, w);
3494
+ } else {
3495
+ w.byte(1);
3496
+ encodeValue(ctx, layout.failure, result.failure, w);
3497
+ }
3498
+ return;
3499
+ }
3500
+ case "exit":
3501
+ {
3502
+ if (!Exit.isExit(value)) encodeFail("an Exit", value, ctx.options);
3503
+ const exit = value;
3504
+ if (exit._tag === "Success") {
3505
+ w.byte(0);
3506
+ encodeValue(ctx, layout.value, exit.value, w);
3507
+ } else {
3508
+ w.byte(1);
3509
+ encodeValue(ctx, layout.cause, exit.cause, w);
3510
+ }
3511
+ return;
3512
+ }
3513
+ case "cause":
3514
+ {
3515
+ if (!Cause.isCause(value)) encodeFail("a Cause", value, ctx.options);
3516
+ const reasons = value.reasons;
3517
+ w.uvarint(reasons.length);
3518
+ for (const reason of reasons) {
3519
+ const mark = w.beginSized();
3520
+ encodeReason(ctx, layout, reason, w);
3521
+ w.endSized(mark);
3522
+ }
3523
+ return;
3524
+ }
3525
+ case "causeReason":
3526
+ {
3527
+ if (!Cause.isReason(value)) encodeFail("a Cause.Reason", value, ctx.options);
3528
+ encodeReason(ctx, layout, value, w);
3529
+ return;
3530
+ }
3531
+ case "struct":
3532
+ {
3533
+ if (!Predicate.isObject(value) || Array.isArray(value)) encodeFail("an object", value, ctx.options);
3534
+ if (ctx.positional) encodeStructPositional(ctx, layout, value, w);else encodeStructFields(ctx, layout, value, w);
3535
+ return;
3536
+ }
3537
+ case "array":
3538
+ {
3539
+ if (!Array.isArray(value)) encodeFail("an array", value, ctx.options);
3540
+ encodeArray(ctx, layout, value, w);
3541
+ return;
3542
+ }
3543
+ case "union":
3544
+ encodeUnion(ctx, layout, value, w);
3545
+ return;
3546
+ case "never":
3547
+ throw issueError(new SchemaIssue.InvalidType(layout.ast, value, ctx.options));
3548
+ }
3549
+ }
3550
+ // Reuse one top-level writer while allowing nested codecs to allocate their own.
3551
+ let pooledWriter = /*#__PURE__*/new Writer();
3552
+ function writeFrame(ctx, layout, value, mode, w) {
3553
+ const mark = w.beginSized();
3554
+ w.byte(mode.envelope);
3555
+ if (mode.positional) w.bytes(mode.fingerprint);
3556
+ encodeValue(ctx, layout, value, w);
3557
+ w.endSized(mark);
3558
+ }
3559
+ // One context and one writer across a batch, so the caches built for the
3560
+ // first frame serve the rest and the frames need no second pass to join. The
3561
+ // single-value and batch entry points share this wrapper: the pooled-writer
3562
+ // protocol (checkout, reset, abort, restore) must not drift between them.
3563
+ function runFrames(layout, value, values, options, mode, dict) {
3564
+ const ctx = {
3565
+ options,
3566
+ positional: mode.positional,
3567
+ indexSignatures: undefined,
3568
+ extraShape: undefined,
3569
+ intern: undefined,
3570
+ dict
3571
+ };
3572
+ const w = pooledWriter ?? new Writer();
3573
+ const pooled = w === pooledWriter;
3574
+ if (pooled) pooledWriter = undefined;
3575
+ w.reset();
3576
+ const savedPathLen = issuePathLen;
3577
+ // A batch is one output: a failure anywhere discards every frame in it, so
3578
+ // the dictionary commits or rolls back once for the whole call.
3579
+ let sent = false;
3580
+ try {
3581
+ if (values === undefined) {
3582
+ issuePathLen = 0;
3583
+ writeFrame(ctx, layout, value, mode, w);
3584
+ } else {
3585
+ for (let i = 0; i < values.length; i++) {
3586
+ issuePathLen = 0;
3587
+ writeFrame(ctx, layout, values[i], mode, w);
3588
+ }
3589
+ }
3590
+ const out = w.out();
3591
+ sent = true;
3592
+ return out;
3593
+ } finally {
3594
+ if (dict !== undefined) {
3595
+ if (sent) dictCommit(dict);else dictRollback(dict);
3596
+ }
3597
+ w.abort();
3598
+ issuePathLen = savedPathLen;
3599
+ if (pooled) pooledWriter = w;
3600
+ }
3601
+ }
3602
+ function encodeFrames(layout, values, options, mode, dict) {
3603
+ return runFrames(layout, undefined, values, options, mode, dict);
3604
+ }
3605
+ function encodeFrame(layout, value, options, mode, dict) {
3606
+ return runFrames(layout, value, undefined, options, mode, dict);
3607
+ }
3608
+ // The direct paths bypass the schema pass for values the binary layer fully
3609
+ // validates on its own; success exits are that case for `exitSuccess` targets.
3610
+ function isSuccessExit(value) {
3611
+ return Exit.isExit(value) && Exit.isSuccess(value);
3612
+ }
3613
+ // Unknown union members resolve to this sentinel.
3614
+ const ABSENT = /*#__PURE__*/globalThis.Symbol.for("~effect/encoding/SchemaBinary/absent");
3615
+ function decodeChecked(layout, r) {
3616
+ const value = decodeValue(layout, r);
3617
+ if (value !== ABSENT && r.pos !== r.end) invalid("no leftover bytes", undefined, r.options);
3618
+ return value;
3619
+ }
3620
+ function decodeSized(layout, r) {
3621
+ const saved = r.enter(r.uvarint());
3622
+ const value = decodeChecked(layout, r);
3623
+ r.exit(saved);
3624
+ return value;
3625
+ }
3626
+ function decodeSlot(layout, r) {
3627
+ if (isSelfDelimiting(layout)) return decodeValue(layout, r);
3628
+ const size = packedSize(layout);
3629
+ const saved = r.enter(size !== undefined ? size : layout._ === "null" || layout._ === "undefined" ? 0 : r.uvarint());
3630
+ const value = decodeChecked(layout, r);
3631
+ r.exit(saved);
3632
+ return value;
3633
+ }
3634
+ // Records are usually small, so duplicate keys scan a list and only wide
3635
+ // records spill into a set.
3636
+ const SEEN_LIST_MAX = 8;
3637
+ function seenKey(seen, key) {
3638
+ const set = seen.set;
3639
+ if (set !== undefined) {
3640
+ if (set.has(key)) return true;
3641
+ set.add(key);
3642
+ return false;
3643
+ }
3644
+ const list = seen.list;
3645
+ if (list.includes(key)) return true;
3646
+ if (list.length >= SEEN_LIST_MAX) {
3647
+ const set = seen.set = new Set();
3648
+ for (let i = 0; i < list.length; i++) set.add(list[i]);
3649
+ set.add(key);
3650
+ } else {
3651
+ list.push(key);
3652
+ }
3653
+ return false;
3654
+ }
3655
+ function decodeExtraPair(layout, r, out, seen, keys) {
3656
+ const code = r.uvarint();
3657
+ const keyCode = keys === undefined ? Math.floor(code / FIELD_WIRE_FACTOR) : Math.floor(code / 16);
3658
+ const kind = keys === undefined ? code - keyCode * FIELD_WIRE_FACTOR : Math.floor((code - keyCode * 16) / 2);
3659
+ const key = keys === undefined ? r.readUtf8(keyCode) : decodeExtraKey(keys, code, keyCode, r);
3660
+ if (layout.names.has(key)) invalid("an extra key distinct from declared fields", key, r.options);
3661
+ if (seenKey(seen, key)) invalid("unique extra keys", undefined, r.options);
3662
+ const signature = layout.extraAll ?? (r.indexSignatures ??= new IndexSignatureCache(r.options)).find(layout, key);
3663
+ if (signature === undefined) {
3664
+ skipFieldPayload(kind, r);
3665
+ return;
3666
+ }
3667
+ issuePath[issuePathLen++] = key;
3668
+ const value = decodeFieldPayload(signature.layout, signature.wireMask, kind, r);
3669
+ issuePathLen--;
3670
+ if (value !== ABSENT) assignProperty(out, key, value);
3671
+ }
3672
+ function decodeExtraKey(keys, code, keyCode, r) {
3673
+ if ((code & 1) === 1) {
3674
+ if (keyCode >= keys.length) invalid("a known back-reference", undefined, r.options);
3675
+ return keys[keyCode];
3676
+ }
3677
+ const key = r.readUtf8(keyCode);
3678
+ keys.push(key);
3679
+ return key;
3680
+ }
3681
+ function missingKeyIssue(field) {
3682
+ return new SchemaIssue.Pointer([field.name], new SchemaIssue.MissingKey(field.annotations));
3683
+ }
3684
+ function throwMissingKeys(layout, issues) {
3685
+ throw issueError(new SchemaIssue.Composite(layout.ast, issues));
3686
+ }
3687
+ function skipFieldVarint(r) {
3688
+ while ((r.byte() & 0x80) !== 0) {
3689
+ // Scan without accumulating an attacker-controlled bigint.
3690
+ }
3691
+ }
3692
+ function skipFieldPayload(kind, r) {
3693
+ switch (kind) {
3694
+ case FIELD_WIRE_SIZED:
3695
+ r.take(r.uvarint());
3696
+ return;
3697
+ case FIELD_WIRE_VARINT:
3698
+ skipFieldVarint(r);
3699
+ return;
3700
+ case FIELD_WIRE_FIXED64:
3701
+ r.take(8);
3702
+ return;
3703
+ case FIELD_WIRE_FALSE:
3704
+ case FIELD_WIRE_TRUE:
3705
+ case FIELD_WIRE_EMPTY:
3706
+ return;
3707
+ case FIELD_WIRE_DECIMAL:
3708
+ skipFieldVarint(r);
3709
+ skipFieldVarint(r);
3710
+ return;
3711
+ case FIELD_WIRE_FIXED32:
3712
+ r.take(4);
3713
+ return;
3714
+ }
3715
+ }
3716
+ function fieldWireMask(layout) {
3717
+ if (layout._ === "literal") return fieldWireMask(layout.leaf);
3718
+ switch (layout._) {
3719
+ case "bool":
3720
+ return 1 << FIELD_WIRE_FALSE | 1 << FIELD_WIRE_TRUE;
3721
+ case "number":
3722
+ return 1 << FIELD_WIRE_VARINT | 1 << FIELD_WIRE_FIXED64 | 1 << FIELD_WIRE_DECIMAL;
3723
+ case "int":
3724
+ return 1 << FIELD_WIRE_VARINT;
3725
+ default:
3726
+ return 1 << FIELD_WIRE_SIZED;
3727
+ }
3728
+ }
3729
+ function decodeScalarField(kind, r) {
3730
+ switch (kind) {
3731
+ case FIELD_WIRE_FALSE:
3732
+ return false;
3733
+ case FIELD_WIRE_TRUE:
3734
+ return true;
3735
+ case FIELD_WIRE_VARINT:
3736
+ return r.numberVarint();
3737
+ case FIELD_WIRE_FIXED64:
3738
+ return r.f64();
3739
+ case FIELD_WIRE_DECIMAL:
3740
+ {
3741
+ const mantissa = r.numberVarint();
3742
+ const scale = r.uvarint();
3743
+ if (scale === 0 || scale > DECIMAL_SCALE_MAX) invalid("a decimal scale in [1, 8]", scale, r.options);
3744
+ return mantissa / POW10[scale];
3745
+ }
3746
+ }
3747
+ return invalid("matching field wire kind", undefined, r.options);
3748
+ }
3749
+ function decodeFieldPayload(layout, wireMask, kind, r) {
3750
+ if ((wireMask & 1 << kind) === 0) {
3751
+ skipFieldPayload(kind, r);
3752
+ return ABSENT;
3753
+ }
3754
+ if (kind !== FIELD_WIRE_SIZED) {
3755
+ const value = decodeScalarField(kind, r);
3756
+ if (layout._ === "literal" && !hasLiteral(layout, value)) {
3757
+ invalid(literalExpected(layout), value, r.options);
3758
+ }
3759
+ return value;
3760
+ }
3761
+ const saved = r.enter(r.uvarint());
3762
+ const value = decodeChecked(layout, r);
3763
+ r.exit(saved);
3764
+ return value;
3765
+ }
3766
+ function decodeStruct(layout, r) {
3767
+ // Only a run field with index signatures hands over an intern table.
3768
+ let keys;
3769
+ if (layout.extra.length > 0) {
3770
+ keys = r.intern;
3771
+ r.intern = undefined;
3772
+ }
3773
+ const out = {};
3774
+ // Use bitmasks for common structs and allocate sets only when needed.
3775
+ let seenMask = 0;
3776
+ let presentMask = 0;
3777
+ let seenWide;
3778
+ let presentWide;
3779
+ let seenUnknown;
3780
+ let seenExtra = false;
3781
+ // Fast-path fields in encoder order and fall back to the id map.
3782
+ const fields = layout.fields;
3783
+ let cursor = 0;
3784
+ while (r.pos < r.end) {
3785
+ const tag = r.fieldTag();
3786
+ const id = Math.floor(tag / FIELD_WIRE_FACTOR);
3787
+ const kind = tag - id * FIELD_WIRE_FACTOR;
3788
+ if (id === 0) {
3789
+ if (seenExtra) invalid("unique field ids", undefined, r.options);
3790
+ seenExtra = true;
3791
+ if (kind !== FIELD_WIRE_SIZED) invalid("extra field map", undefined, r.options);
3792
+ const saved = r.enter(r.uvarint());
3793
+ decodeExtraPairs(layout, r, out, keys);
3794
+ r.exit(saved);
3795
+ continue;
3796
+ }
3797
+ let field;
3798
+ if (cursor < fields.length && fields[cursor].id === id) {
3799
+ field = fields[cursor];
3800
+ cursor++;
3801
+ } else {
3802
+ field = layout.byId.get(id);
3803
+ if (field !== undefined) cursor = field.index + 1;
3804
+ }
3805
+ if (field === undefined) {
3806
+ if (seenUnknown === undefined) seenUnknown = new Set();else if (seenUnknown.has(id)) invalid("unique field ids", undefined, r.options);
3807
+ seenUnknown.add(id);
3808
+ skipFieldPayload(kind, r);
3809
+ continue;
3810
+ }
3811
+ const index = field.index;
3812
+ if (index < 32) {
3813
+ const bit = 1 << index;
3814
+ if ((seenMask & bit) !== 0) invalid("unique field ids", undefined, r.options);
3815
+ seenMask |= bit;
3816
+ } else if (seenWide === undefined) {
3817
+ seenWide = new Set([index]);
3818
+ } else {
3819
+ if (seenWide.has(index)) invalid("unique field ids", undefined, r.options);
3820
+ seenWide.add(index);
3821
+ }
3822
+ issuePath[issuePathLen++] = field.name;
3823
+ const value = decodeFieldPayload(field.layout, field.wireMask, kind, r);
3824
+ issuePathLen--;
3825
+ if (value !== ABSENT) {
3826
+ assignProperty(out, field.name, value);
3827
+ if (index < 32) presentMask |= 1 << index;else (presentWide ??= new Set()).add(index);
3828
+ }
3829
+ }
3830
+ checkRequiredFields(layout, presentMask, presentWide, r);
3831
+ return out;
3832
+ }
3833
+ // Fails when a required field is absent, honoring `errors: "all"`.
3834
+ function checkRequiredFields(struct, presentMask, presentWide, r) {
3835
+ if ((presentMask & struct.requiredMask) === struct.requiredMask && !struct.requiredWide) return;
3836
+ const fields = struct.fields;
3837
+ let issues;
3838
+ for (let i = 0; i < fields.length; i++) {
3839
+ const field = fields[i];
3840
+ const index = field.index;
3841
+ const present = index < 32 ? (presentMask & 1 << index) !== 0 : presentWide?.has(index) === true;
3842
+ if (!field.optional && !present) {
3843
+ ;
3844
+ (issues ??= []).push(missingKeyIssue(field));
3845
+ if (r.options.errors !== "all") break;
3846
+ }
3847
+ }
3848
+ if (issues !== undefined) throwMissingKeys(struct, issues);
3849
+ }
3850
+ function decodeStructPositional(layout, r) {
3851
+ // Only a run field with index signatures hands over an intern table. Extras
3852
+ // decode after the fields here, so claim it before a nested field can.
3853
+ let keys;
3854
+ if (layout.extra.length > 0) {
3855
+ keys = r.intern;
3856
+ r.intern = undefined;
3857
+ }
3858
+ const out = {};
3859
+ const bitmapBytes = layout.optionalCount + 7 >> 3;
3860
+ let bitmap = 0;
3861
+ if (bitmapBytes > 0) {
3862
+ if (r.pos + bitmapBytes > r.end) invalid("complete value", undefined, r.options);
3863
+ bitmap = r.pos;
3864
+ r.pos += bitmapBytes;
3865
+ }
3866
+ const buf = r.buf;
3867
+ const fields = layout.fields;
3868
+ let optionalIndex = 0;
3869
+ let issues;
3870
+ for (let i = 0; i < fields.length; i++) {
3871
+ const field = fields[i];
3872
+ if (field.optional) {
3873
+ const present = (buf[bitmap + (optionalIndex >> 3)] & 1 << (optionalIndex & 7)) !== 0;
3874
+ optionalIndex++;
3875
+ if (!present) continue;
3876
+ }
3877
+ issuePath[issuePathLen++] = field.name;
3878
+ const value = field.inline ? decodeSlot(field.layout, r) : decodeSized(field.layout, r);
3879
+ issuePathLen--;
3880
+ if (value !== ABSENT) assignProperty(out, field.name, value);else if (!field.optional) {
3881
+ ;
3882
+ (issues ??= []).push(missingKeyIssue(field));
3883
+ if (r.options.errors !== "all") break;
3884
+ }
3885
+ }
3886
+ if (issues !== undefined) throwMissingKeys(layout, issues);
3887
+ if (layout.extra.length > 0) {
3888
+ const count = r.uvarint();
3889
+ if (count > r.remaining) invalid("complete value", undefined, r.options);
3890
+ if (count > 0) {
3891
+ const seen = {
3892
+ list: [],
3893
+ set: undefined
3894
+ };
3895
+ for (let i = 0; i < count; i++) decodeExtraPair(layout, r, out, seen, keys);
3896
+ }
3897
+ }
3898
+ return out;
3899
+ }
3900
+ function decodeExtraPairs(layout, r, out, keys) {
3901
+ const seen = {
3902
+ list: [],
3903
+ set: undefined
3904
+ };
3905
+ while (r.pos < r.end) decodeExtraPair(layout, r, out, seen, keys);
3906
+ }
3907
+ function decodeInterned(table, layout, r) {
3908
+ const code = r.uvarint();
3909
+ if ((code & 1) === 1) {
3910
+ const ref = (code - 1) / 2;
3911
+ if (ref >= table.length) invalid("a known back-reference", undefined, r.options);
3912
+ return table[ref];
3913
+ }
3914
+ // Plain strings consume their whole region, so they skip the reader window.
3915
+ if (layout._ === "string") {
3916
+ if (r.dict !== undefined) {
3917
+ const saved = r.enter(code / 2);
3918
+ const value = decodeChecked(layout, r);
3919
+ r.exit(saved);
3920
+ table.push(value);
3921
+ return value;
3922
+ }
3923
+ const value = r.readUtf8(code / 2);
3924
+ table.push(value);
3925
+ return value;
3926
+ }
3927
+ const saved = r.enter(code / 2);
3928
+ const value = decodeChecked(layout, r);
3929
+ r.exit(saved);
3930
+ table.push(value);
3931
+ return value;
3932
+ }
3933
+ function decodeStructRun(plan, count, r) {
3934
+ const out = new Array(count);
3935
+ const shapes = [];
3936
+ const tables = [];
3937
+ for (let i = 0; i < count; i++) {
3938
+ issuePath[issuePathLen++] = i;
3939
+ const saved = r.enter(r.uvarint());
3940
+ out[i] = decodeRunRow(plan, shapes, tables, r);
3941
+ r.exit(saved);
3942
+ issuePathLen--;
3943
+ }
3944
+ return out;
3945
+ }
3946
+ // A positional shape is the presence mask over layout field order.
3947
+ function positionalRunShape(struct, r) {
3948
+ const mask = r.uvarint();
3949
+ const fields = struct.fields;
3950
+ const fieldBits = mask & ~RUN_EXTRA_BIT;
3951
+ if (mask > RUN_EXTRA_BIT * 2 - 1 || fieldBits >>> fields.length !== 0) {
3952
+ invalid("a known row shape", undefined, r.options);
3953
+ }
3954
+ const shape = [];
3955
+ if ((mask & RUN_EXTRA_BIT) !== 0) shape.push(null);
3956
+ for (let i = 0; i < fields.length; i++) {
3957
+ if ((fieldBits & 1 << i) !== 0) shape.push(fields[i]);
3958
+ }
3959
+ return shape;
3960
+ }
3961
+ function decodeRunRow(plan, shapes, tables, r) {
3962
+ const struct = plan.struct;
3963
+ const out = {};
3964
+ let presentMask = 0;
3965
+ let presentWide;
3966
+ const code = r.uvarint();
3967
+ let shape;
3968
+ if (code === 0) {
3969
+ if (r.positional && plan.shapes) {
3970
+ shape = positionalRunShape(struct, r);
3971
+ shapes.push(shape);
3972
+ }
3973
+ } else {
3974
+ shape = shapes[code - 1];
3975
+ if (shape === undefined) invalid("a known row shape", undefined, r.options);
3976
+ }
3977
+ if (shape !== undefined) {
3978
+ for (let i = 0; i < shape.length; i++) {
3979
+ const filled = decodeRunSlot(plan, tables, shape[i], out, r);
3980
+ if (filled >= 0) {
3981
+ if (filled < 32) presentMask |= 1 << filled;else (presentWide ??= new Set()).add(filled);
3982
+ }
3983
+ }
3984
+ if (r.pos !== r.end) invalid("no leftover bytes", undefined, r.options);
3985
+ } else {
3986
+ const declared = plan.shapes ? [] : undefined;
3987
+ let seenMask = 0;
3988
+ let seenWide;
3989
+ let seenIds;
3990
+ let seenExtra = false;
3991
+ while (r.pos < r.end) {
3992
+ const id = r.uvarint();
3993
+ let slot;
3994
+ if (id === 0) {
3995
+ if (seenExtra) invalid("unique field ids", undefined, r.options);
3996
+ seenExtra = true;
3997
+ slot = null;
3998
+ } else {
3999
+ slot = struct.byId.get(id);
4000
+ if (slot === undefined) {
4001
+ if (seenIds === undefined) seenIds = new Set([id]);else if (seenIds.has(id)) invalid("unique field ids", undefined, r.options);else seenIds.add(id);
4002
+ } else if (slot.index < 32) {
4003
+ if ((seenMask & 1 << slot.index) !== 0) invalid("unique field ids", undefined, r.options);
4004
+ seenMask |= 1 << slot.index;
4005
+ } else if (seenWide === undefined) {
4006
+ seenWide = new Set([slot.index]);
4007
+ } else {
4008
+ if (seenWide.has(slot.index)) invalid("unique field ids", undefined, r.options);
4009
+ seenWide.add(slot.index);
4010
+ }
4011
+ }
4012
+ declared?.push(slot);
4013
+ const filled = decodeRunSlot(plan, tables, slot, out, r);
4014
+ if (filled >= 0) {
4015
+ if (filled < 32) presentMask |= 1 << filled;else (presentWide ??= new Set()).add(filled);
4016
+ }
4017
+ }
4018
+ if (declared !== undefined) shapes.push(declared);
4019
+ }
4020
+ checkRequiredFields(struct, presentMask, presentWide, r);
4021
+ return out;
4022
+ }
4023
+ // Returns the field index this slot filled, or -1.
4024
+ function decodeRunSlot(plan, tables, slot, out, r) {
4025
+ const code = r.uvarint();
4026
+ if ((code & 1) === 1) {
4027
+ if (slot === null || slot === undefined) return -1;
4028
+ const table = tables[slot.index];
4029
+ const ref = (code - 1) / 2;
4030
+ if (table === undefined || ref >= table.length) {
4031
+ invalid("a known back-reference", undefined, r.options);
4032
+ }
4033
+ const value = table[ref];
4034
+ if (value === ABSENT) return -1;
4035
+ assignProperty(out, slot.name, value);
4036
+ return slot.index;
4037
+ }
4038
+ const saved = r.enter(code / 2);
4039
+ if (slot === null) {
4040
+ decodeExtraPairs(plan.struct, r, out);
4041
+ r.exit(saved);
4042
+ return -1;
4043
+ }
4044
+ if (slot === undefined) {
4045
+ r.exit(saved);
4046
+ return -1;
4047
+ }
4048
+ const kind = plan.intern[slot.index];
4049
+ if (kind === INTERN_ELEMENTS || kind === INTERN_KEYS) {
4050
+ r.intern = tables[slot.index] ??= [];
4051
+ }
4052
+ issuePath[issuePathLen++] = slot.name;
4053
+ const value = decodeChecked(slot.layout, r);
4054
+ issuePathLen--;
4055
+ r.intern = undefined;
4056
+ r.exit(saved);
4057
+ if (kind === INTERN_SELF) (tables[slot.index] ??= []).push(value);
4058
+ if (value === ABSENT) return -1;
4059
+ assignProperty(out, slot.name, value);
4060
+ return slot.index;
4061
+ }
4062
+ function decodeArray(layout, r) {
4063
+ const elementLen = layout.elements.length;
4064
+ const count = layout.hasCount ? r.uvarint() : elementLen;
4065
+ if (layout.rest.length === 0 && count > elementLen) {
4066
+ issuePath[issuePathLen++] = elementLen;
4067
+ throw issueError(new SchemaIssue.UnexpectedKey(layout.ast, undefined, r.options));
4068
+ }
4069
+ if (count < layout.minCount) {
4070
+ issuePath[issuePathLen++] = count;
4071
+ throw issueError(new SchemaIssue.MissingKey(undefined));
4072
+ }
4073
+ if (layout.hasCount) {
4074
+ const allocationLimit = layout.rest.length > 0 && isZeroWidthSlot(layout.rest[0]) ? ZERO_WIDTH_ARRAY_MAX : r.remaining + ARRAY_ALLOCATION_SLACK;
4075
+ if (count > allocationLimit) invalid("array count within allocation limit", count, r.options);
4076
+ }
4077
+ if (count > 0) {
4078
+ const plan = runPlan(layout);
4079
+ if (plan !== null) return decodeStructRun(plan, count, r);
4080
+ }
4081
+ const out = new Array(count);
4082
+ const uniform = layout.uniform;
4083
+ if (uniform !== undefined) {
4084
+ if (layout.uniformNumbers) return decodeNumberRun(out, count, r);
4085
+ // Only a run field holding an array of strings hands over an intern table.
4086
+ const table = r.intern;
4087
+ r.intern = undefined;
4088
+ if (table !== undefined) {
4089
+ for (let i = 0; i < count; i++) {
4090
+ issuePath[issuePathLen++] = i;
4091
+ const value = decodeInterned(table, uniform, r);
4092
+ if (value === ABSENT) throw issueError(new SchemaIssue.MissingKey(undefined));
4093
+ issuePathLen--;
4094
+ out[i] = value;
4095
+ }
4096
+ return out;
4097
+ }
4098
+ if (isSelfDelimiting(uniform)) {
4099
+ for (let i = 0; i < count; i++) {
4100
+ issuePath[issuePathLen++] = i;
4101
+ out[i] = decodeValue(uniform, r);
4102
+ issuePathLen--;
4103
+ }
4104
+ return out;
4105
+ }
4106
+ // Strings consume their whole region, so they skip the reader window.
4107
+ if (uniform._ === "string") {
4108
+ for (let i = 0; i < count; i++) {
4109
+ issuePath[issuePathLen++] = i;
4110
+ out[i] = r.dict === undefined ? r.readUtf8(r.uvarint()) : decodeSized(uniform, r);
4111
+ issuePathLen--;
4112
+ }
4113
+ return out;
4114
+ }
4115
+ const packed = layout.uniformPacked;
4116
+ const inline = layout.uniformInline;
4117
+ for (let i = 0; i < count; i++) {
4118
+ issuePath[issuePathLen++] = i;
4119
+ const saved = r.enter(inline ? packed ?? 0 : r.uvarint());
4120
+ const value = decodeChecked(uniform, r);
4121
+ r.exit(saved);
4122
+ if (value === ABSENT) throw issueError(new SchemaIssue.MissingKey(undefined));
4123
+ issuePathLen--;
4124
+ out[i] = value;
4125
+ }
4126
+ return out;
4127
+ }
4128
+ for (let i = 0; i < count; i++) {
4129
+ const slot = arraySlot(layout, i, count);
4130
+ const optional = i < elementLen && layout.elements[i].optional;
4131
+ if (!layout.hasCount && r.remaining === 0 && !optional && slot._ !== "null" && slot._ !== "undefined") {
4132
+ issuePath[issuePathLen++] = i;
4133
+ throw issueError(new SchemaIssue.MissingKey(undefined));
4134
+ }
4135
+ issuePath[issuePathLen++] = i;
4136
+ const value = decodeSlot(slot, r);
4137
+ if (value === ABSENT) {
4138
+ if (optional) invalid("known union member", undefined, r.options);
4139
+ throw issueError(new SchemaIssue.MissingKey(undefined));
4140
+ }
4141
+ issuePathLen--;
4142
+ out[i] = value;
4143
+ }
4144
+ if (!layout.hasCount && r.pos < r.end) {
4145
+ issuePath[issuePathLen++] = elementLen;
4146
+ throw issueError(new SchemaIssue.UnexpectedKey(layout.ast, undefined, r.options));
4147
+ }
4148
+ return out;
4149
+ }
4150
+ function decodeNumberRun(out, count, r) {
4151
+ const mode = r.byte();
4152
+ if (mode === NUMBER_RUN_F64) {
4153
+ if (r.remaining !== count * 8) invalid("f64", undefined, r.options);
4154
+ for (let i = 0; i < count; i++) out[i] = r.f64();
4155
+ return out;
4156
+ }
4157
+ if (mode === NUMBER_RUN_DECIMAL) {
4158
+ for (let i = 0; i < count; i++) {
4159
+ issuePath[issuePathLen++] = i;
4160
+ const code = r.uvarint();
4161
+ const scale = code % 16;
4162
+ if (scale > DECIMAL_SCALE_MAX) invalid("decimal", undefined, r.options);
4163
+ const value = decodeSignMagnitude((code - scale) / 16);
4164
+ out[i] = scale === 0 ? value : value / POW10[scale];
4165
+ issuePathLen--;
4166
+ }
4167
+ return out;
4168
+ }
4169
+ if (mode !== NUMBER_RUN_VARINT) invalid("f64", undefined, r.options);
4170
+ for (let i = 0; i < count; i++) {
4171
+ issuePath[issuePathLen++] = i;
4172
+ out[i] = r.numberVarint();
4173
+ issuePathLen--;
4174
+ }
4175
+ return out;
4176
+ }
4177
+ function decodeUnion(layout, r) {
4178
+ const kind = r.byte();
4179
+ if (kind === K.variant) {
4180
+ const tag = r.u32le();
4181
+ const variant = layout.byTag.get(tag);
4182
+ if (variant === undefined) {
4183
+ r.take(r.remaining);
4184
+ return ABSENT;
4185
+ }
4186
+ const payload = decodeChecked(variant.payload, r);
4187
+ if (payload === ABSENT) return ABSENT;
4188
+ if (!variant.tuple) {
4189
+ for (const sentinel of variant.sentinels) {
4190
+ assignProperty(payload, sentinel.key, sentinel.literal);
4191
+ }
4192
+ }
4193
+ return payload;
4194
+ }
4195
+ const member = layout.byKind.get(kind);
4196
+ if (member === undefined) {
4197
+ r.take(r.remaining);
4198
+ return ABSENT;
4199
+ }
4200
+ return decodeChecked(member, r);
4201
+ }
4202
+ // Fingerprint mode rejects selectors outside its canonical member table.
4203
+ function decodeUnionPositional(layout, r) {
4204
+ const position = layout.byPos[r.uvarint()];
4205
+ if (position === undefined) invalid("known union member", undefined, r.options);
4206
+ const payload = decodeChecked(position.layout, r);
4207
+ const variant = position.variant;
4208
+ if (variant !== undefined && !variant.tuple && payload !== ABSENT) {
4209
+ for (const sentinel of variant.sentinels) {
4210
+ assignProperty(payload, sentinel.key, sentinel.literal);
4211
+ }
4212
+ }
4213
+ return payload;
4214
+ }
4215
+ function decodeReason(layout, r) {
4216
+ const tag = r.byte();
4217
+ switch (tag) {
4218
+ case 0:
4219
+ return Cause.makeFailReason(requirePresent(decodeChecked(layout.error, r)));
4220
+ case 1:
4221
+ return Cause.makeDieReason(requirePresent(decodeChecked(layout.defect, r)));
4222
+ case 2:
4223
+ if (r.remaining !== 0) invalid("empty", undefined, r.options);
4224
+ return Cause.makeInterruptReason();
4225
+ case 3:
4226
+ {
4227
+ if (r.remaining !== 8) invalid("f64", undefined, r.options);
4228
+ return Cause.makeInterruptReason(r.f64());
4229
+ }
4230
+ default:
4231
+ r.take(r.remaining);
4232
+ return ABSENT;
4233
+ }
4234
+ }
4235
+ function requirePresent(value) {
4236
+ if (value === ABSENT) throw issueError(new SchemaIssue.MissingKey(undefined));
4237
+ return value;
4238
+ }
4239
+ function decodeValue(layout, r) {
4240
+ if (r.nesting >= MAX_NESTING_DEPTH) {
4241
+ invalid(`nesting depth at most ${MAX_NESTING_DEPTH}`, r.nesting + 1, r.options);
4242
+ }
4243
+ r.nesting++;
4244
+ try {
4245
+ return decodeValueUnchecked(layout, r);
4246
+ } finally {
4247
+ r.nesting--;
4248
+ }
4249
+ }
4250
+ function decodeValueUnchecked(layout, r) {
4251
+ switch (layout._) {
4252
+ case "literal":
4253
+ {
4254
+ const value = decodeValue(layout.leaf, r);
4255
+ if (!hasLiteral(layout, value)) invalid(literalExpected(layout), value, r.options);
4256
+ return value;
4257
+ }
4258
+ case "bool":
4259
+ {
4260
+ if (r.remaining !== 1) invalid("bool", undefined, r.options);
4261
+ const b = r.byte();
4262
+ if (b > 1) invalid("bool", undefined, r.options);
4263
+ return b === 1;
4264
+ }
4265
+ case "null":
4266
+ if (r.remaining !== 0) invalid("empty", undefined, r.options);
4267
+ return null;
4268
+ case "undefined":
4269
+ if (r.remaining !== 0) invalid("empty", undefined, r.options);
4270
+ return undefined;
4271
+ case "number":
4272
+ {
4273
+ const len = r.remaining;
4274
+ if (len === 8) return r.f64();
4275
+ if (len === 0 || len > NUMBER_VARINT_MAX_BYTES) invalid("f64", undefined, r.options);
4276
+ const value = r.numberVarint();
4277
+ if (r.remaining === 0) return value;
4278
+ const scale = r.byte();
4279
+ if (r.remaining !== 0 || scale === 0 || scale > DECIMAL_SCALE_MAX) {
4280
+ invalid("decimal", undefined, r.options);
4281
+ }
4282
+ return value / POW10[scale];
4283
+ }
4284
+ case "int":
4285
+ return r.numberVarint();
4286
+ case "string":
4287
+ {
4288
+ const dict = r.dict;
4289
+ return dict === undefined ? r.readUtf8(r.end - r.pos) : decodeString(dict, layout, r);
4290
+ }
4291
+ case "symbol":
4292
+ return globalThis.Symbol.for(r.readUtf8(r.end - r.pos));
4293
+ case "bytes":
4294
+ return r.takeCopy(r.end - r.pos);
4295
+ case "bigint":
4296
+ return r.zigzag();
4297
+ case "int64":
4298
+ {
4299
+ if (r.remaining !== 8) invalid("int64", undefined, r.options);
4300
+ const millis = Number(r.i64());
4301
+ const date = new Date(millis);
4302
+ if (Number.isNaN(date.getTime())) {
4303
+ invalid(layout.flavor === "date" ? "a valid Date" : "a valid DateTime", millis, r.options);
4304
+ }
4305
+ return layout.flavor === "date" ? date : DateTime.makeUnsafe(millis);
4306
+ }
4307
+ case "dateTimeZoned":
4308
+ {
4309
+ const millis = Number(r.i64());
4310
+ const tag = r.byte();
4311
+ let timeZone;
4312
+ if (tag === 0) {
4313
+ if (r.remaining !== 4) invalid("time zone", undefined, r.options);
4314
+ timeZone = r.i32le();
4315
+ } else if (tag === 1) {
4316
+ timeZone = r.readUtf8(r.end - r.pos);
4317
+ } else {
4318
+ return invalid("time zone", undefined, r.options);
4319
+ }
4320
+ try {
4321
+ return DateTime.makeZonedUnsafe(millis, {
4322
+ timeZone
4323
+ });
4324
+ } catch {
4325
+ return invalid("time zone", undefined, r.options);
4326
+ }
4327
+ }
4328
+ case "duration":
4329
+ {
4330
+ const tag = r.byte();
4331
+ switch (tag) {
4332
+ case 0:
4333
+ return Duration.nanos(r.zigzag());
4334
+ case 1:
4335
+ return Duration.infinity;
4336
+ case 2:
4337
+ return Duration.negativeInfinity;
4338
+ default:
4339
+ return invalid("duration", undefined, r.options);
4340
+ }
4341
+ }
4342
+ case "bigDecimal":
4343
+ {
4344
+ const value = r.zigzag();
4345
+ const scale = r.zigzag();
4346
+ if (scale > MAX_SAFE_BIGINT || -scale > MAX_SAFE_BIGINT) invalid("safe integer length", undefined, r.options);
4347
+ return BigDecimal.make(value, Number(scale));
4348
+ }
4349
+ case "json":
4350
+ {
4351
+ const text = r.readUtf8(r.end - r.pos);
4352
+ try {
4353
+ return JSON.parse(text);
4354
+ } catch {
4355
+ return invalid("json", undefined, r.options);
4356
+ }
4357
+ }
4358
+ case "option":
4359
+ {
4360
+ const tag = r.byte();
4361
+ if (tag === 0) {
4362
+ if (r.remaining !== 0) invalid("empty", undefined, r.options);
4363
+ return Option.none();
4364
+ }
4365
+ if (tag !== 1) invalid("bool", undefined, r.options);
4366
+ return Option.some(requirePresent(decodeChecked(layout.value, r)));
4367
+ }
4368
+ case "result":
4369
+ {
4370
+ const tag = r.byte();
4371
+ if (tag === 0) return Result.succeed(requirePresent(decodeChecked(layout.success, r)));
4372
+ if (tag !== 1) invalid("bool", undefined, r.options);
4373
+ return Result.fail(requirePresent(decodeChecked(layout.failure, r)));
4374
+ }
4375
+ case "exit":
4376
+ {
4377
+ const tag = r.byte();
4378
+ if (tag === 0) return Exit.succeed(requirePresent(decodeChecked(layout.value, r)));
4379
+ if (tag !== 1) invalid("bool", undefined, r.options);
4380
+ const cause = decodeValue(layout.cause, r);
4381
+ return Exit.failCause(cause);
4382
+ }
4383
+ case "cause":
4384
+ {
4385
+ const count = r.uvarint();
4386
+ const reasons = [];
4387
+ for (let i = 0; i < count; i++) {
4388
+ issuePath[issuePathLen++] = i;
4389
+ const saved = r.enter(r.uvarint());
4390
+ const reason = decodeReason(layout, r);
4391
+ r.exit(saved);
4392
+ issuePathLen--;
4393
+ if (reason !== ABSENT) reasons.push(reason);
4394
+ }
4395
+ if (r.pos !== r.end) invalid("no leftover bytes", undefined, r.options);
4396
+ return Cause.fromReasons(reasons);
4397
+ }
4398
+ case "causeReason":
4399
+ return decodeReason(layout, r);
4400
+ case "struct":
4401
+ return r.positional ? decodeStructPositional(layout, r) : decodeStruct(layout, r);
4402
+ case "array":
4403
+ return decodeArray(layout, r);
4404
+ case "union":
4405
+ return r.positional ? decodeUnionPositional(layout, r) : decodeUnion(layout, r);
4406
+ case "never":
4407
+ throw issueError(new SchemaIssue.InvalidType(layout.ast, undefined, r.options));
4408
+ }
4409
+ }
4410
+ function decodeFrameBody(layout, r, mode) {
4411
+ const envelope = r.byte();
4412
+ if (envelope !== mode.envelope) invalid(mode.expectedEnvelope, envelope, r.options);
4413
+ if (mode.positional) {
4414
+ if (r.remaining < 8) invalid("complete value", undefined, r.options);
4415
+ const buf = r.buf;
4416
+ const expected = mode.fingerprint;
4417
+ const pos = r.pos;
4418
+ for (let i = 0; i < 8; i++) {
4419
+ if (buf[pos + i] !== expected[i]) invalid("matching layout fingerprint", undefined, r.options);
4420
+ }
4421
+ r.pos = pos + 8;
4422
+ }
4423
+ const value = decodeChecked(layout, r);
4424
+ if (value === ABSENT) throw issueError(new SchemaIssue.MissingKey(undefined));
4425
+ return value;
4426
+ }
4427
+ // Reuse one top-level reader while allowing nested codecs to allocate their own.
4428
+ let pooledReader = /*#__PURE__*/new Reader();
4429
+ function decodeOneShot(layout, bytes, options, mode) {
4430
+ const r = pooledReader ?? new Reader();
4431
+ const pooled = r === pooledReader;
4432
+ if (pooled) pooledReader = undefined;
4433
+ r.reset(bytes, 0, bytes.length, options, undefined, mode.positional, undefined);
4434
+ const savedPathLen = issuePathLen;
4435
+ issuePathLen = 0;
4436
+ try {
4437
+ const n = r.uvarint();
4438
+ if (n === 0) invalid("nonzero frame length", undefined, options);
4439
+ const saved = r.enter(n);
4440
+ const value = decodeFrameBody(layout, r, mode);
4441
+ r.exit(saved);
4442
+ if (r.pos !== bytes.length) invalid("no leftover bytes", undefined, options);
4443
+ return value;
4444
+ } finally {
4445
+ issuePathLen = savedPathLen;
4446
+ r.release();
4447
+ if (pooled) pooledReader = r;
4448
+ }
4449
+ }
4450
+ function makeTransformation(layout, mode, trusted, successOnly = false) {
4451
+ return SchemaTransformation.transformEffect({
4452
+ decode: (bytes, options) => {
4453
+ try {
4454
+ const value = decodeOneShot(layout, bytes, options, mode);
4455
+ if (trusted !== undefined && Predicate.isObjectOrArray(value) && (!successOnly || isSuccessExit(value))) trusted.value = value;
4456
+ return Effect.succeed(value);
4457
+ } catch (e) {
4458
+ return e instanceof IssueError ? Effect.fail(e.issue) : Effect.die(e);
4459
+ }
4460
+ },
4461
+ encode: (value, options) => {
4462
+ try {
4463
+ return Effect.succeed(encodeFrame(layout, value, options, mode));
4464
+ } catch (e) {
4465
+ return e instanceof IssueError ? Effect.fail(e.issue) : Effect.die(e);
4466
+ }
4467
+ }
4468
+ });
4469
+ }
4470
+ const fingerprintModeMemo = /*#__PURE__*/memoize(fingerprintMode);
4471
+ function compileMode(layout, fingerprint) {
4472
+ return fingerprint === true ? fingerprintModeMemo(layout) : defaultMode;
4473
+ }
4474
+ const compileTargetFromAst = /*#__PURE__*/memoize(ast => {
4475
+ const raw = Schema.make(toBinaryAST(ast));
4476
+ const {
4477
+ exact,
4478
+ exitSuccess,
4479
+ layout,
4480
+ recursive
4481
+ } = compileLayout(raw.ast);
4482
+ // Only recursive schemas need the cycle walk.
4483
+ return {
4484
+ target: recursive ? withCycleGuard(raw) : raw,
4485
+ layout,
4486
+ exact,
4487
+ exitSuccess,
4488
+ recursive
4489
+ };
4490
+ });
4491
+ function compileTarget(schema) {
4492
+ return compileTargetFromAst(schema.ast);
4493
+ }
4494
+ function takeTrusted(trusted, input) {
4495
+ if (trusted.value === undefined || input !== trusted.value) return false;
4496
+ trusted.value = undefined;
4497
+ return true;
4498
+ }
4499
+ // A target that bypasses the schema pass when `accept` takes the input, and
4500
+ // otherwise runs the target's type schema. The two directions get their own
4501
+ // predicate: `flip` swaps the declaration's encoding run in when encoding, the
4502
+ // way it already swaps `encodingChecks`.
4503
+ function bypassPass(target, decodeAccept, encodeAccept) {
4504
+ const type = Schema.make(SchemaAST.toType(target.ast));
4505
+ const parse = SchemaParser.decodeUnknownEffect(type);
4506
+ // A bypassed input comes back unchanged, which the shared "same value" exit
4507
+ // says without allocating one per call.
4508
+ const run = accept => () => (input, _ast, options) => accept(input, options) ? InternalParserProtocol.sameExit : parse(input, options);
4509
+ return Schema.make(new SchemaAST.Declaration([type.ast], run(decodeAccept), {
4510
+ identifier: "binary value"
4511
+ }, undefined, undefined, undefined, undefined, run(encodeAccept)));
4512
+ }
4513
+ // The binary layer drops unknown keys instead of reporting them, so only
4514
+ // `onExcessProperty: "error"` needs the schema pass to see the input.
4515
+ function reportsExcess(_input, options) {
4516
+ return options.onExcessProperty !== "error";
4517
+ }
4518
+ // The binary layer already validates an exact schema in both directions, so the
4519
+ // schema pass around it repeats that work. Encoding skips it outright. Decoding
4520
+ // only lets values the binary layer just produced through, so every other
4521
+ // input, `Schema.is` included, still runs the real check.
4522
+ function withTrustedDecode(target, trusted, bypassEncode) {
4523
+ return bypassPass(target, input => takeTrusted(trusted, input),
4524
+ // A recursive schema keeps the pass on encode: decoding cannot build a
4525
+ // cycle, but a caller can hand one in, and the cycle walk lives there.
4526
+ bypassEncode ? reportsExcess : constFalse);
4527
+ }
4528
+ function constFalse() {
4529
+ return false;
4530
+ }
4531
+ // Success exits with an exact success schema are fully validated by the binary
4532
+ // layer, so only failure exits pay the schema pass for their cause's error and
4533
+ // defect encodings. The type parameter flips with the direction, so the same
4534
+ // fallback decodes binary failure exits and encodes failure exits back to the
4535
+ // wire representation. Under `onExcessProperty: "error"` only decoder-produced
4536
+ // values bypass the pass: the binary layer drops unknown keys instead of
4537
+ // reporting them, so other success exits keep the schema pass. It is not a
4538
+ // sound `Schema.is` guard, which is why only {@link toCodecDirect} uses it.
4539
+ function withExitSuccessDecode(target, trusted) {
4540
+ return Schema.declareConstructor()([target], ([codec]) => {
4541
+ const parse = SchemaParser.decodeUnknownEffect(codec);
4542
+ return (input, _ast, options) => takeTrusted(trusted, input) || isSuccessExit(input) && options.onExcessProperty !== "error" ? Effect.succeed(input) : parse(input, options);
4543
+ }, {
4544
+ identifier: "binary exit value"
4545
+ });
4546
+ }
4547
+ // An exact schema is fully validated by the binary layer in both directions, so
4548
+ // this target adds nothing, except under `onExcessProperty: "error"`. It is not
4549
+ // a sound `Schema.is` guard, which is why only {@link toCodecDirect} uses it.
4550
+ function passThrough(target) {
4551
+ return bypassPass(target, reportsExcess, reportsExcess);
4552
+ }
4553
+ // Skip the cycle walk once for structurally decoded values.
4554
+ function withCycleGuard(target) {
4555
+ const type = Schema.make(SchemaAST.toType(target.ast));
4556
+ const decoded = new WeakSet();
4557
+ const guard = Schema.declareConstructor()([type], ([type]) => (input, ast, options) => {
4558
+ if (Predicate.isObjectOrArray(input) && decoded.delete(input)) {
4559
+ return Effect.succeed(input);
4560
+ }
4561
+ return isCyclic(input) ? Effect.fail(new SchemaIssue.InvalidType(ast, input, options)) : SchemaParser.decodeUnknownEffect(type)(input, options);
4562
+ }, {
4563
+ identifier: "acyclic value"
4564
+ });
4565
+ return Schema.decodeTo(guard, SchemaTransformation.transform({
4566
+ decode: value => {
4567
+ if (Predicate.isObjectOrArray(value)) decoded.add(value);
4568
+ return value;
4569
+ },
4570
+ encode: value => value
4571
+ }))(target);
4572
+ }
4573
+ //# sourceMappingURL=SchemaBinary.js.map