effect 4.1.5 → 4.1.6

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 (309) hide show
  1. package/ai-docs/package.json +2 -2
  2. package/dist/Channel.d.ts +104 -7
  3. package/dist/Channel.d.ts.map +1 -1
  4. package/dist/Channel.js +73 -4
  5. package/dist/Channel.js.map +1 -1
  6. package/dist/Codegen.d.ts +7 -2
  7. package/dist/Codegen.d.ts.map +1 -1
  8. package/dist/Codegen.js +7 -2
  9. package/dist/Codegen.js.map +1 -1
  10. package/dist/Effect.d.ts +139 -18
  11. package/dist/Effect.d.ts.map +1 -1
  12. package/dist/Effect.js +10 -2
  13. package/dist/Effect.js.map +1 -1
  14. package/dist/Equal.d.ts +4 -4
  15. package/dist/Equal.d.ts.map +1 -1
  16. package/dist/Equal.js +78 -65
  17. package/dist/Equal.js.map +1 -1
  18. package/dist/Hash.d.ts.map +1 -1
  19. package/dist/Hash.js +24 -17
  20. package/dist/Hash.js.map +1 -1
  21. package/dist/LayerRef.d.ts +1 -1
  22. package/dist/LayerRef.d.ts.map +1 -1
  23. package/dist/LayerRef.js +3 -3
  24. package/dist/LayerRef.js.map +1 -1
  25. package/dist/Logger.d.ts +37 -13
  26. package/dist/Logger.d.ts.map +1 -1
  27. package/dist/Logger.js +39 -10
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/Match.d.ts +23 -23
  30. package/dist/Match.d.ts.map +1 -1
  31. package/dist/Match.js.map +1 -1
  32. package/dist/Order.js +1 -1
  33. package/dist/Order.js.map +1 -1
  34. package/dist/Schema.d.ts +41 -0
  35. package/dist/Schema.d.ts.map +1 -1
  36. package/dist/Schema.js +51 -390
  37. package/dist/Schema.js.map +1 -1
  38. package/dist/SchemaAST.d.ts.map +1 -1
  39. package/dist/SchemaAST.js +0 -3
  40. package/dist/SchemaAST.js.map +1 -1
  41. package/dist/ScopedCache.d.ts.map +1 -1
  42. package/dist/ScopedCache.js +6 -4
  43. package/dist/ScopedCache.js.map +1 -1
  44. package/dist/Stream.d.ts +128 -5
  45. package/dist/Stream.d.ts.map +1 -1
  46. package/dist/Stream.js +124 -29
  47. package/dist/Stream.js.map +1 -1
  48. package/dist/String.js +1 -1
  49. package/dist/String.js.map +1 -1
  50. package/dist/Tracer.d.ts +10 -0
  51. package/dist/Tracer.d.ts.map +1 -1
  52. package/dist/Tracer.js +2 -0
  53. package/dist/Tracer.js.map +1 -1
  54. package/dist/ai/McpSchema.d.ts +88 -88
  55. package/dist/ai/McpSchema.d.ts.map +1 -1
  56. package/dist/ai/McpServer.d.ts +152 -2
  57. package/dist/ai/McpServer.d.ts.map +1 -1
  58. package/dist/ai/McpServer.js +8 -2
  59. package/dist/ai/McpServer.js.map +1 -1
  60. package/dist/ai/Prompt.d.ts +3 -1
  61. package/dist/ai/Prompt.d.ts.map +1 -1
  62. package/dist/ai/Prompt.js +17 -3
  63. package/dist/ai/Prompt.js.map +1 -1
  64. package/dist/ai/Skill.d.ts +172 -0
  65. package/dist/ai/Skill.d.ts.map +1 -0
  66. package/dist/ai/Skill.js +209 -0
  67. package/dist/ai/Skill.js.map +1 -0
  68. package/dist/ai/index.d.ts +5 -0
  69. package/dist/ai/index.d.ts.map +1 -1
  70. package/dist/ai/index.js +5 -0
  71. package/dist/ai/index.js.map +1 -1
  72. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  73. package/dist/cluster/ClusterWorkflowEngine.js +155 -83
  74. package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
  75. package/dist/cluster/MessageStorage.d.ts +56 -0
  76. package/dist/cluster/MessageStorage.d.ts.map +1 -1
  77. package/dist/cluster/MessageStorage.js +18 -2
  78. package/dist/cluster/MessageStorage.js.map +1 -1
  79. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  80. package/dist/cluster/SqlMessageStorage.js +45 -22
  81. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  82. package/dist/cluster/internal/entityActivation.js +2 -0
  83. package/dist/cluster/internal/entityActivation.js.map +1 -1
  84. package/dist/cluster/internal/entityManager.js +8 -5
  85. package/dist/cluster/internal/entityManager.js.map +1 -1
  86. package/dist/encoding/Base64.js +5 -1
  87. package/dist/encoding/Base64.js.map +1 -1
  88. package/dist/encoding/Base64Url.d.ts.map +1 -1
  89. package/dist/encoding/Base64Url.js +6 -1
  90. package/dist/encoding/Base64Url.js.map +1 -1
  91. package/dist/encoding/Xml.d.ts +38 -9
  92. package/dist/encoding/Xml.d.ts.map +1 -1
  93. package/dist/encoding/Xml.js +63 -31
  94. package/dist/encoding/Xml.js.map +1 -1
  95. package/dist/http/FetchHttpClient.d.ts +2 -1
  96. package/dist/http/FetchHttpClient.d.ts.map +1 -1
  97. package/dist/http/FetchHttpClient.js +14 -10
  98. package/dist/http/FetchHttpClient.js.map +1 -1
  99. package/dist/http/Headers.d.ts +201 -3
  100. package/dist/http/Headers.d.ts.map +1 -1
  101. package/dist/http/Headers.js +205 -3
  102. package/dist/http/Headers.js.map +1 -1
  103. package/dist/http/HttpClient.d.ts.map +1 -1
  104. package/dist/http/HttpClient.js +11 -7
  105. package/dist/http/HttpClient.js.map +1 -1
  106. package/dist/http/HttpClientError.d.ts +1 -0
  107. package/dist/http/HttpClientError.d.ts.map +1 -1
  108. package/dist/http/HttpClientError.js +32 -9
  109. package/dist/http/HttpClientError.js.map +1 -1
  110. package/dist/http/HttpClientRequest.d.ts +46 -0
  111. package/dist/http/HttpClientRequest.d.ts.map +1 -1
  112. package/dist/http/HttpClientRequest.js +15 -0
  113. package/dist/http/HttpClientRequest.js.map +1 -1
  114. package/dist/http/HttpClientResponse.d.ts +132 -0
  115. package/dist/http/HttpClientResponse.d.ts.map +1 -1
  116. package/dist/http/HttpClientResponse.js +83 -0
  117. package/dist/http/HttpClientResponse.js.map +1 -1
  118. package/dist/http/HttpMiddleware.js +1 -1
  119. package/dist/http/HttpMiddleware.js.map +1 -1
  120. package/dist/http/HttpServerResponse.d.ts +118 -0
  121. package/dist/http/HttpServerResponse.d.ts.map +1 -1
  122. package/dist/http/HttpServerResponse.js +43 -0
  123. package/dist/http/HttpServerResponse.js.map +1 -1
  124. package/dist/http/Multipart.d.ts.map +1 -1
  125. package/dist/http/Multipart.js +0 -5
  126. package/dist/http/Multipart.js.map +1 -1
  127. package/dist/http/MultipartParser/internal/contentType.d.ts +6 -0
  128. package/dist/http/MultipartParser/internal/contentType.d.ts.map +1 -1
  129. package/dist/http/MultipartParser/internal/contentType.js +1 -1
  130. package/dist/http/MultipartParser/internal/contentType.js.map +1 -1
  131. package/dist/http/internal/clientPath.d.ts +2 -0
  132. package/dist/http/internal/clientPath.d.ts.map +1 -0
  133. package/dist/http/internal/clientPath.js +24 -0
  134. package/dist/http/internal/clientPath.js.map +1 -0
  135. package/dist/http/internal/redactedPath.js +2 -0
  136. package/dist/http/internal/redactedPath.js.map +1 -1
  137. package/dist/http/internal/tracing.js +5 -3
  138. package/dist/http/internal/tracing.js.map +1 -1
  139. package/dist/http-api/HttpApi.d.ts +2 -2
  140. package/dist/http-api/HttpApi.d.ts.map +1 -1
  141. package/dist/http-api/HttpApi.js +30 -7
  142. package/dist/http-api/HttpApi.js.map +1 -1
  143. package/dist/http-api/HttpApiBuilder.d.ts.map +1 -1
  144. package/dist/http-api/HttpApiBuilder.js +5 -2
  145. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  146. package/dist/http-api/HttpApiClient.d.ts.map +1 -1
  147. package/dist/http-api/HttpApiClient.js +23 -6
  148. package/dist/http-api/HttpApiClient.js.map +1 -1
  149. package/dist/http-api/internal/redactedKeys.d.ts +2 -0
  150. package/dist/http-api/internal/redactedKeys.d.ts.map +1 -0
  151. package/dist/http-api/internal/redactedKeys.js +37 -0
  152. package/dist/http-api/internal/redactedKeys.js.map +1 -0
  153. package/dist/internal/base64.js +34 -2
  154. package/dist/internal/base64.js.map +1 -1
  155. package/dist/internal/dateTime.js +35 -17
  156. package/dist/internal/dateTime.js.map +1 -1
  157. package/dist/internal/effect.js +9 -1
  158. package/dist/internal/effect.js.map +1 -1
  159. package/dist/internal/equal.js +14 -13
  160. package/dist/internal/equal.js.map +1 -1
  161. package/dist/internal/hash.js +4 -1
  162. package/dist/internal/hash.js.map +1 -1
  163. package/dist/internal/matcher.js +17 -17
  164. package/dist/internal/matcher.js.map +1 -1
  165. package/dist/internal/schema/schemaCodegen.js +3 -2
  166. package/dist/internal/schema/schemaCodegen.js.map +1 -1
  167. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts +2 -0
  168. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts.map +1 -0
  169. package/dist/internal/schema/schemaCodegenBuiltIns.js +425 -0
  170. package/dist/internal/schema/schemaCodegenBuiltIns.js.map +1 -0
  171. package/dist/internal/schema/toEquivalence.js +3 -4
  172. package/dist/internal/schema/toEquivalence.js.map +1 -1
  173. package/dist/internal/version.js +1 -1
  174. package/dist/jose/JoseError.d.ts +51 -1
  175. package/dist/jose/JoseError.d.ts.map +1 -1
  176. package/dist/jose/JoseError.js +25 -18
  177. package/dist/jose/JoseError.js.map +1 -1
  178. package/dist/jose/internal/compact.js +10 -5
  179. package/dist/jose/internal/compact.js.map +1 -1
  180. package/dist/observability/Otlp.d.ts +19 -0
  181. package/dist/observability/Otlp.d.ts.map +1 -1
  182. package/dist/observability/Otlp.js +10 -0
  183. package/dist/observability/Otlp.js.map +1 -1
  184. package/dist/observability/OtlpExporter.d.ts +49 -13
  185. package/dist/observability/OtlpExporter.d.ts.map +1 -1
  186. package/dist/observability/OtlpExporter.js +135 -54
  187. package/dist/observability/OtlpExporter.js.map +1 -1
  188. package/dist/observability/OtlpLogger.d.ts +14 -0
  189. package/dist/observability/OtlpLogger.d.ts.map +1 -1
  190. package/dist/observability/OtlpLogger.js +10 -2
  191. package/dist/observability/OtlpLogger.js.map +1 -1
  192. package/dist/observability/OtlpMetrics.d.ts.map +1 -1
  193. package/dist/observability/OtlpMetrics.js +2 -0
  194. package/dist/observability/OtlpMetrics.js.map +1 -1
  195. package/dist/observability/OtlpTracer.d.ts +14 -0
  196. package/dist/observability/OtlpTracer.d.ts.map +1 -1
  197. package/dist/observability/OtlpTracer.js +10 -2
  198. package/dist/observability/OtlpTracer.js.map +1 -1
  199. package/dist/persistence/KeyValueStore.d.ts.map +1 -1
  200. package/dist/persistence/KeyValueStore.js +6 -4
  201. package/dist/persistence/KeyValueStore.js.map +1 -1
  202. package/dist/reactivity/Atom.d.ts.map +1 -1
  203. package/dist/reactivity/Atom.js +10 -9
  204. package/dist/reactivity/Atom.js.map +1 -1
  205. package/dist/rpc/RpcClient.d.ts.map +1 -1
  206. package/dist/rpc/RpcClient.js +32 -1
  207. package/dist/rpc/RpcClient.js.map +1 -1
  208. package/dist/rpc/RpcGroup.d.ts +1 -1
  209. package/dist/rpc/RpcGroup.d.ts.map +1 -1
  210. package/dist/rpc/RpcGroup.js +4 -0
  211. package/dist/rpc/RpcGroup.js.map +1 -1
  212. package/dist/sql/Migrator.d.ts.map +1 -1
  213. package/dist/sql/Migrator.js +2 -5
  214. package/dist/sql/Migrator.js.map +1 -1
  215. package/dist/sql/SqlClient.d.ts.map +1 -1
  216. package/dist/sql/SqlClient.js +5 -1
  217. package/dist/sql/SqlClient.js.map +1 -1
  218. package/dist/workflow/Activity.d.ts +18 -0
  219. package/dist/workflow/Activity.d.ts.map +1 -1
  220. package/dist/workflow/Activity.js +13 -4
  221. package/dist/workflow/Activity.js.map +1 -1
  222. package/dist/workflow/Workflow.d.ts +10 -9
  223. package/dist/workflow/Workflow.d.ts.map +1 -1
  224. package/dist/workflow/Workflow.js +33 -22
  225. package/dist/workflow/Workflow.js.map +1 -1
  226. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  227. package/dist/workflow/WorkflowEngine.js +26 -12
  228. package/dist/workflow/WorkflowEngine.js.map +1 -1
  229. package/dist/workflow/internal/retry.d.ts +2 -0
  230. package/dist/workflow/internal/retry.d.ts.map +1 -0
  231. package/dist/workflow/internal/retry.js +11 -0
  232. package/dist/workflow/internal/retry.js.map +1 -0
  233. package/dist/workflow/internal/scope.d.ts +2 -0
  234. package/dist/workflow/internal/scope.d.ts.map +1 -0
  235. package/dist/workflow/internal/scope.js +26 -0
  236. package/dist/workflow/internal/scope.js.map +1 -0
  237. package/package.json +3 -3
  238. package/src/Channel.ts +105 -8
  239. package/src/Codegen.ts +7 -2
  240. package/src/Effect.ts +224 -48
  241. package/src/Equal.ts +85 -79
  242. package/src/Hash.ts +30 -22
  243. package/src/LayerRef.ts +6 -4
  244. package/src/Logger.ts +68 -25
  245. package/src/Match.ts +78 -50
  246. package/src/Order.ts +1 -1
  247. package/src/Schema.ts +79 -296
  248. package/src/SchemaAST.ts +0 -1
  249. package/src/ScopedCache.ts +6 -4
  250. package/src/Stream.ts +167 -33
  251. package/src/String.ts +1 -1
  252. package/src/Tracer.ts +10 -0
  253. package/src/ai/McpServer.ts +161 -4
  254. package/src/ai/Prompt.ts +20 -3
  255. package/src/ai/Skill.ts +236 -0
  256. package/src/ai/index.ts +6 -0
  257. package/src/cluster/ClusterWorkflowEngine.ts +172 -96
  258. package/src/cluster/MessageStorage.ts +51 -2
  259. package/src/cluster/SqlMessageStorage.ts +81 -34
  260. package/src/cluster/internal/entityActivation.ts +6 -0
  261. package/src/cluster/internal/entityManager.ts +8 -4
  262. package/src/encoding/Base64.ts +5 -1
  263. package/src/encoding/Base64Url.ts +6 -1
  264. package/src/encoding/Xml.ts +96 -26
  265. package/src/http/FetchHttpClient.ts +8 -5
  266. package/src/http/Headers.ts +309 -3
  267. package/src/http/HttpClient.ts +19 -7
  268. package/src/http/HttpClientError.ts +42 -9
  269. package/src/http/HttpClientRequest.ts +51 -0
  270. package/src/http/HttpClientResponse.ts +156 -0
  271. package/src/http/HttpMiddleware.ts +1 -1
  272. package/src/http/HttpServerResponse.ts +126 -0
  273. package/src/http/Multipart.ts +0 -5
  274. package/src/http/MultipartParser/internal/contentType.ts +1 -1
  275. package/src/http/internal/clientPath.ts +39 -0
  276. package/src/http/internal/redactedPath.ts +4 -0
  277. package/src/http/internal/tracing.ts +6 -3
  278. package/src/http-api/HttpApi.ts +29 -8
  279. package/src/http-api/HttpApiBuilder.ts +7 -2
  280. package/src/http-api/HttpApiClient.ts +30 -7
  281. package/src/http-api/internal/redactedKeys.ts +40 -0
  282. package/src/internal/base64.ts +57 -2
  283. package/src/internal/dateTime.ts +43 -24
  284. package/src/internal/effect.ts +31 -102
  285. package/src/internal/equal.ts +37 -17
  286. package/src/internal/hash.ts +5 -1
  287. package/src/internal/matcher.ts +34 -113
  288. package/src/internal/schema/schemaCodegen.ts +5 -4
  289. package/src/internal/schema/schemaCodegenBuiltIns.ts +343 -0
  290. package/src/internal/schema/toEquivalence.ts +3 -5
  291. package/src/internal/version.ts +1 -1
  292. package/src/jose/JoseError.ts +34 -0
  293. package/src/jose/internal/compact.ts +14 -5
  294. package/src/observability/Otlp.ts +29 -0
  295. package/src/observability/OtlpExporter.ts +206 -75
  296. package/src/observability/OtlpLogger.ts +24 -2
  297. package/src/observability/OtlpMetrics.ts +2 -0
  298. package/src/observability/OtlpTracer.ts +24 -3
  299. package/src/persistence/KeyValueStore.ts +17 -14
  300. package/src/reactivity/Atom.ts +12 -18
  301. package/src/rpc/RpcClient.ts +26 -1
  302. package/src/rpc/RpcGroup.ts +4 -1
  303. package/src/sql/Migrator.ts +2 -11
  304. package/src/sql/SqlClient.ts +14 -8
  305. package/src/workflow/Activity.ts +28 -4
  306. package/src/workflow/Workflow.ts +68 -44
  307. package/src/workflow/WorkflowEngine.ts +38 -15
  308. package/src/workflow/internal/retry.ts +12 -0
  309. package/src/workflow/internal/scope.ts +36 -0
@@ -23,21 +23,13 @@ export const TypeId = "~effect/Match/Matcher"
23
23
  /** @internal */
24
24
  export type Contextual<P, Fallback> = [P] extends [never] ? Fallback : P
25
25
 
26
- type TagHandlers<D extends string, R, Ret> = {
27
- readonly [Tag in Types.Tags<D, R> & string]: (_: Extract<R, Record<D, Tag>>) => Ret
28
- }
29
-
30
- type PartialTagHandlers<D extends string, R, Ret> = {
31
- readonly [Tag in Types.Tags<D, R> & string]?: ((_: Extract<R, Record<D, Tag>>) => Ret) | undefined
32
- }
33
-
34
26
  type ValueTagHandlers<I> = {
35
27
  readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any
36
28
  }
37
29
 
38
- type HandledKeys<P, Keys extends keyof P = keyof P> = {
39
- readonly [K in Keys]-?: undefined extends P[K] ? never : K
40
- }[Keys]
30
+ type InternalTypeMatcher = TypeMatcher<any, any, any, any, any, any> & {
31
+ readonly forwardArgs: boolean
32
+ }
41
33
 
42
34
  const TypeMatcherProto: Omit<TypeMatcher<any, any, any, any, any, any>, "cases" | "select"> = {
43
35
  [TypeId]: {
@@ -50,10 +42,10 @@ const TypeMatcherProto: Omit<TypeMatcher<any, any, any, any, any, any>, "cases"
50
42
  },
51
43
  _tag: "TypeMatcher",
52
44
  add<I, R, RA, A>(
53
- this: TypeMatcher<any, any, any, any, any, any>,
45
+ this: InternalTypeMatcher,
54
46
  _case: Case
55
47
  ): TypeMatcher<I, R, RA, A, any, any> {
56
- return makeTypeMatcher(this.select, [...this.cases, _case])
48
+ return makeTypeMatcher(this.select, [...this.cases, _case], this.forwardArgs)
57
49
  },
58
50
  pipe() {
59
51
  return pipeArguments(this, arguments)
@@ -62,11 +54,13 @@ const TypeMatcherProto: Omit<TypeMatcher<any, any, any, any, any, any>, "cases"
62
54
 
63
55
  function makeTypeMatcher<I, R, RA, A, Ret, Args extends Array<any>>(
64
56
  select: (...args: any) => I,
65
- cases: ReadonlyArray<Case>
57
+ cases: ReadonlyArray<Case>,
58
+ forwardArgs: boolean
66
59
  ): TypeMatcher<I, R, RA, A, Ret, Args> {
67
60
  const matcher = Object.create(TypeMatcherProto)
68
61
  matcher.select = select
69
62
  matcher.cases = cases
63
+ matcher.forwardArgs = forwardArgs
70
64
  return matcher
71
65
  }
72
66
 
@@ -137,6 +131,8 @@ const makeNot = (
137
131
  evaluate
138
132
  })
139
133
 
134
+ const matches = (_case: Case, input: unknown): boolean => _case.guard(input) === (_case._tag === "When")
135
+
140
136
  const makePredicate = (pattern: unknown): Predicate.Predicate<unknown> => {
141
137
  if (typeof pattern === "function") {
142
138
  return pattern as Predicate.Predicate<unknown>
@@ -223,12 +219,12 @@ export const type = <I>(): Matcher<
223
219
  I,
224
220
  never,
225
221
  never
226
- > => makeTypeMatcher(identity, [])
222
+ > => makeTypeMatcher(identity, [], false)
227
223
 
228
224
  /** @internal */
229
225
  export const fn = <Args extends Array<any>, I>(
230
226
  select: (...args: Args) => I
231
- ): Matcher<I, Types.Without<never>, I, never, never, any, Args> => makeTypeMatcher(select, [])
227
+ ): Matcher<I, Types.Without<never>, I, never, never, any, Args> => makeTypeMatcher(select, [], true)
232
228
 
233
229
  /** @internal */
234
230
  export const value = <const I>(
@@ -265,7 +261,7 @@ export const valueTags: {
265
261
  input: I,
266
262
  fields: Contextual<P, ValueTagHandlers<I>>
267
263
  ): Unify<ReturnType<P[keyof P]>> => {
268
- const match: any = tagsExhaustive(fields as any)(makeTypeMatcher(identity, []))
264
+ const match: any = tagsExhaustive(fields as any)(type())
269
265
  return match(input)
270
266
  }
271
267
  )
@@ -281,7 +277,7 @@ export const typeTags = <I>() =>
281
277
  >(
282
278
  fields: P
283
279
  ) => {
284
- const match: any = tagsExhaustive(fields as any)(makeTypeMatcher(identity, []))
280
+ const match: any = tagsExhaustive(fields as any)(type())
285
281
  return (input: I): Unify<ReturnType<P[keyof P]>> => match(input)
286
282
  }
287
283
 
@@ -376,111 +372,38 @@ export const whenAnd = <
376
372
  }
377
373
 
378
374
  /** @internal */
379
- export const discriminator = <D extends string>(field: D) =>
380
- <
381
- R,
382
- P extends Types.Tags<D, R> & string,
383
- Ret,
384
- Fn extends (_: Extract<R, Record<D, P>>) => Ret
385
- >(
386
- ...pattern: [
387
- first: P,
388
- ...values: Array<P>,
389
- f: Fn
390
- ]
391
- ) => {
375
+ export const discriminator = (field: string) => (...pattern: Array<any>) => {
392
376
  const f = pattern[pattern.length - 1]
393
- const values: Array<P> = pattern.slice(0, -1) as any
377
+ const values = pattern.slice(0, -1)
394
378
  const pred = values.length === 1
395
379
  ? (_: any) => _ != null && _[field] === values[0]
396
380
  : (_: any) => _ != null && values.includes(_[field])
397
381
 
398
- return <I, F, A, Pr>(
399
- self: Matcher<I, F, R, A, Pr, Ret>
400
- ): Matcher<
401
- I,
402
- Types.AddWithout<F, Extract<R, Record<D, P>>>,
403
- Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, P>>>>,
404
- A | ReturnType<Fn>,
405
- Pr,
406
- Ret
407
- > => (self as any).add(makeWhen(pred, f as any)) as any
382
+ return (self: any): any => self.add(makeWhen(pred, f))
408
383
  }
409
384
 
410
385
  /** @internal */
411
- export const discriminatorStartsWith = <D extends string>(field: D) =>
412
- <
413
- R,
414
- P extends string,
415
- Ret,
416
- Fn extends (_: Extract<R, Record<D, `${P}${string}`>>) => Ret
417
- >(
418
- pattern: P,
419
- f: Fn
420
- ) => {
386
+ export const discriminatorStartsWith = (field: string) => (pattern: string, f: (...args: Array<any>) => any) => {
421
387
  const pred = (_: any) => _ != null && typeof _[field] === "string" && _[field].startsWith(pattern)
422
388
 
423
- return <I, F, A, Pr>(
424
- self: Matcher<I, F, R, A, Pr, Ret>
425
- ): Matcher<
426
- I,
427
- Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>,
428
- Types.ApplyFilters<
429
- I,
430
- Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>
431
- >,
432
- A | ReturnType<Fn>,
433
- Pr,
434
- Ret
435
- > => (self as any).add(makeWhen(pred, f as any)) as any
389
+ return (self: any): any => self.add(makeWhen(pred, f))
436
390
  }
437
391
 
438
392
  /** @internal */
439
- export const discriminators = <D extends string>(field: D) =>
440
- <
441
- R,
442
- Ret,
443
- P extends
444
- & PartialTagHandlers<D, R, Ret>
445
- & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }
446
- >(
447
- fields: Contextual<P, PartialTagHandlers<D, R, Ret>>
448
- ) => {
393
+ export const discriminators = (field: string) => (fields: object) => {
449
394
  const predicate = makeWhen(
450
395
  (arg: any) => arg != null && Object.hasOwn(fields, arg[field]) && (fields as any)[arg[field]] !== undefined,
451
- (data: any) => (fields as any)[data[field]](data)
396
+ (data: any, ...args: Array<any>) => (fields as any)[data[field]](data, ...args)
452
397
  )
453
398
 
454
- return <I, F, A, Pr>(
455
- self: Matcher<I, F, R, A, Pr, Ret>
456
- ): Matcher<
457
- I,
458
- Types.AddWithout<F, Extract<R, Record<D, HandledKeys<P>>>>,
459
- Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, HandledKeys<P>>>>>,
460
- A | ReturnType<P[keyof P] & {}>,
461
- Pr,
462
- Ret
463
- > => (self as any).add(predicate)
399
+ return (self: any): any => self.add(predicate)
464
400
  }
465
401
 
466
402
  /** @internal */
467
- export const discriminatorsExhaustive: <D extends string>(
468
- field: D
469
- ) => <
470
- R,
471
- Ret,
472
- P extends
473
- & TagHandlers<D, R, Ret>
474
- & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }
475
- >(
476
- fields: Contextual<P, TagHandlers<D, R, Ret>>
477
- ) => <I, F, A, Pr>(
478
- self: Matcher<I, F, R, A, Pr, Ret>
479
- ) => [Pr] extends [never] ? (u: I) => Unify<A | ReturnType<P[keyof P]>>
480
- : Unify<A | ReturnType<P[keyof P]>> = (field: string) => (fields: object) => {
481
- const addCases = discriminators(field)(fields)
482
- return (matcher: any) => exhaustive(addCases(matcher))
483
- }
403
+ export const discriminatorsExhaustive = (field: string) => (fields: object) => {
404
+ const addCases = discriminators(field)(fields)
405
+ return (matcher: any): any => exhaustive(addCases(matcher))
406
+ }
484
407
 
485
408
  /** @internal */
486
409
  export const tag: <
@@ -522,7 +445,7 @@ export const literals = (fields: object) => {
522
445
  (arg: any) =>
523
446
  (typeof arg === "string" || typeof arg === "number") && Object.hasOwn(fields, arg) &&
524
447
  (fields as any)[arg] !== undefined,
525
- (data: any) => (fields as any)[data](data)
448
+ (data: any, ...args: Array<any>) => (fields as any)[data](data, ...args)
526
449
  )
527
450
  return (self: any): any => self.add(predicate)
528
451
  }
@@ -603,10 +526,11 @@ export const orElse =
603
526
  return toResult._tag === "Success" ? toResult.success as any : (f as any)(toResult.failure)
604
527
  }
605
528
 
529
+ const forwardArgs = (self as InternalTypeMatcher).forwardArgs
606
530
  // @ts-expect-error
607
531
  return (...args: Array<any>) => {
608
532
  const a = (toResult as any)(...args)
609
- return Result.isSuccess(a) ? a.success : (f as any)(a.failure, ...args)
533
+ return Result.isSuccess(a) ? a.success : forwardArgs ? (f as any)(a.failure, ...args) : (f as any)(a.failure)
610
534
  }
611
535
  }
612
536
 
@@ -633,15 +557,14 @@ export const result: <I, F, R, A, Pr, Ret, Args extends Array<any>>(
633
557
  return self.value
634
558
  }
635
559
 
560
+ const forwardArgs = (self as InternalTypeMatcher).forwardArgs
636
561
  const len = self.cases.length
637
562
  if (len === 1) {
638
563
  const _case = self.cases[0]
639
564
  return (...args: Array<any>): Result.Result<A, RA> => {
640
565
  const input = self.select(...args)
641
- if (_case._tag === "When" && _case.guard(input) === true) {
642
- return Result.succeed(_case.evaluate(input, ...args))
643
- } else if (_case._tag === "Not" && _case.guard(input) === false) {
644
- return Result.succeed(_case.evaluate(input, ...args))
566
+ if (matches(_case, input)) {
567
+ return Result.succeed(forwardArgs ? _case.evaluate(input, ...args) : _case.evaluate(input))
645
568
  }
646
569
  return Result.fail(input as any)
647
570
  }
@@ -650,10 +573,8 @@ export const result: <I, F, R, A, Pr, Ret, Args extends Array<any>>(
650
573
  const input = self.select(...args)
651
574
  for (let i = 0; i < len; i++) {
652
575
  const _case = self.cases[i]
653
- if (_case._tag === "When" && _case.guard(input) === true) {
654
- return Result.succeed(_case.evaluate(input, ...args))
655
- } else if (_case._tag === "Not" && _case.guard(input) === false) {
656
- return Result.succeed(_case.evaluate(input, ...args))
576
+ if (matches(_case, input)) {
577
+ return Result.succeed(forwardArgs ? _case.evaluate(input, ...args) : _case.evaluate(input))
657
578
  }
658
579
  }
659
580
 
@@ -8,6 +8,7 @@ import { errorWithPath } from "../errors.ts"
8
8
  import * as InternalAnnotations from "./annotations.ts"
9
9
  import * as CodeExpression from "./codeExpression.ts"
10
10
  import * as CodeImports from "./codeImports.ts"
11
+ import * as BuiltIns from "./schemaCodegenBuiltIns.ts"
11
12
 
12
13
  type Path = ReadonlyArray<string | number>
13
14
  type CheckRepresentationAnnotation = SchemaRepresentation.CheckRepresentationAnnotation<
@@ -296,13 +297,13 @@ export function addSchemas(
296
297
  check: SchemaRepresentation.Check,
297
298
  path: Path
298
299
  ): Fragment {
299
- const callback = check.annotations?.toCode
300
+ const callback = BuiltIns.resolveCheck(check, path)
300
301
  let runtime: Fragment
301
302
  if (callback !== undefined) {
302
303
  const schemas = annotationSchemas(check.representation, [...path, "representation"])
303
304
  runtime = compileCallback(
304
305
  schemas,
305
- (schemas) => (callback as SchemaRepresentation.Generation.Check)({ schemas }),
306
+ (schemas) => callback({ schemas }),
306
307
  [...path, "annotations", "toCode"]
307
308
  ).runtime
308
309
  } else if (check._tag === "Filter") {
@@ -361,7 +362,7 @@ export function addSchemas(
361
362
  ): Code {
362
363
  switch (representation._tag) {
363
364
  case "Declaration": {
364
- const callback = representation.annotations?.toCode
365
+ const callback = BuiltIns.resolveDeclaration(representation, path)
365
366
  if (callback === undefined) {
366
367
  throw errorWithPath("Missing toCode callback", [...path, "annotations", "toCode"])
367
368
  }
@@ -370,7 +371,7 @@ export function addSchemas(
370
371
  )
371
372
  return compileCallback(
372
373
  typeParameters,
373
- (typeParameters) => (callback as SchemaRepresentation.Generation.Declaration)({ typeParameters }),
374
+ (typeParameters) => callback({ typeParameters }),
374
375
  [...path, "annotations", "toCode"]
375
376
  )
376
377
  }
@@ -0,0 +1,343 @@
1
+ import { format } from "../../Formatter.ts"
2
+ import { isObject } from "../../Predicate.ts"
3
+ import type { Json } from "../../Schema.ts"
4
+ import type * as Representation from "../../SchemaRepresentation.ts"
5
+ import { literal } from "../codegen.ts"
6
+ import { errorWithPath } from "../errors.ts"
7
+
8
+ type Path = ReadonlyArray<string | number>
9
+ type PrintArgument = (value: unknown) => string | undefined
10
+
11
+ const noArguments: PrintArgument = (payload) => payload === null ? "" : undefined
12
+ const string: PrintArgument = (value) => typeof value === "string" ? literal(value) : undefined
13
+ const number: PrintArgument = (value) =>
14
+ typeof value === "number" && Number.isFinite(value) ? literal(value) : undefined
15
+ const natural: PrintArgument = (value) =>
16
+ typeof value === "number" && Number.isInteger(value) && value >= 0 ? literal(value) : undefined
17
+ const bigint: PrintArgument = (value) =>
18
+ typeof value === "string" && /^-?(?:0|[1-9][0-9]*)$/.test(value) ? literal(BigInt(value)) : undefined
19
+ const date: PrintArgument = (value) => {
20
+ if (typeof value !== "string") return undefined
21
+ const ms = Date.parse(value)
22
+ return Number.isFinite(ms) && new Date(ms).toISOString() === value ? `new globalThis.Date(${ms})` : undefined
23
+ }
24
+
25
+ function fields(render: PrintArgument, ...keys: ReadonlyArray<string>): PrintArgument {
26
+ return (payload) => {
27
+ if (!isObject(payload)) return undefined
28
+ const args: Array<string> = []
29
+ for (const key of keys) {
30
+ const arg = render(payload[key])
31
+ if (arg === undefined) return undefined
32
+ args.push(arg)
33
+ }
34
+ return args.join(", ")
35
+ }
36
+ }
37
+
38
+ function between(render: PrintArgument): PrintArgument {
39
+ return (payload) => {
40
+ if (!isObject(payload)) return undefined
41
+ const minimum = render(payload.minimum)
42
+ const maximum = render(payload.maximum)
43
+ const { exclusiveMaximum, exclusiveMinimum } = payload
44
+ if (
45
+ minimum === undefined || maximum === undefined ||
46
+ exclusiveMinimum !== undefined && exclusiveMinimum !== true ||
47
+ exclusiveMaximum !== undefined && exclusiveMaximum !== true
48
+ ) return undefined
49
+ return `{ minimum: ${minimum}, maximum: ${maximum}, exclusiveMinimum: ${exclusiveMinimum}, exclusiveMaximum: ${exclusiveMaximum} }`
50
+ }
51
+ }
52
+
53
+ const checkArguments: Record<string, PrintArgument> = {
54
+ isTrimmed: noArguments,
55
+ isPattern: (payload) => {
56
+ if (!isObject(payload) || typeof payload.source !== "string" || typeof payload.flags !== "string") return undefined
57
+ const { source, flags } = payload
58
+ try {
59
+ const pattern = new RegExp(source, flags)
60
+ if (pattern.source !== source || pattern.flags !== flags) return undefined
61
+ } catch {
62
+ return undefined
63
+ }
64
+ return `new globalThis.RegExp(${literal(source)}${flags === "" ? "" : ", " + literal(flags)})`
65
+ },
66
+ isStringFinite: noArguments,
67
+ isStringBigInt: noArguments,
68
+ isStringSymbol: noArguments,
69
+ isUUID: (payload) => {
70
+ if (!isObject(payload)) return undefined
71
+ const { version } = payload
72
+ if (version === null) return ""
73
+ return typeof version === "number" && Number.isInteger(version) && version >= 1 && version <= 8
74
+ ? literal(version)
75
+ : undefined
76
+ },
77
+ isGUID: noArguments,
78
+ isULID: noArguments,
79
+ isAscii: noArguments,
80
+ isBase64: noArguments,
81
+ isBase64Url: noArguments,
82
+ isStartingWith: fields(string, "startsWith"),
83
+ isEndingWith: fields(string, "endsWith"),
84
+ isIncluding: fields(string, "includes"),
85
+ isUppercased: noArguments,
86
+ isLowercased: noArguments,
87
+ isCapitalized: noArguments,
88
+ isUncapitalized: noArguments,
89
+ isFinite: noArguments,
90
+ isInt: noArguments,
91
+ isGreaterThan: fields(number, "exclusiveMinimum"),
92
+ isGreaterThanOrEqualTo: fields(number, "minimum"),
93
+ isLessThan: fields(number, "exclusiveMaximum"),
94
+ isLessThanOrEqualTo: fields(number, "maximum"),
95
+ isBetween: between(number),
96
+ isMultipleOf: fields((value) => typeof value === "number" && value > 0 ? number(value) : undefined, "divisor"),
97
+ isGreaterThanDate: fields(date, "exclusiveMinimum"),
98
+ isGreaterThanOrEqualToDate: fields(date, "minimum"),
99
+ isLessThanDate: fields(date, "exclusiveMaximum"),
100
+ isLessThanOrEqualToDate: fields(date, "maximum"),
101
+ isBetweenDate: between(date),
102
+ isGreaterThanBigInt: fields(bigint, "exclusiveMinimum"),
103
+ isGreaterThanOrEqualToBigInt: fields(bigint, "minimum"),
104
+ isLessThanBigInt: fields(bigint, "exclusiveMaximum"),
105
+ isLessThanOrEqualToBigInt: fields(bigint, "maximum"),
106
+ isBetweenBigInt: between(bigint),
107
+ isMinLength: fields(natural, "minLength"),
108
+ isMaxLength: fields(natural, "maxLength"),
109
+ isBetweenLength: fields(natural, "minimum", "maximum"),
110
+ isMinCodePoints: fields(natural, "minCodePoints"),
111
+ isMaxCodePoints: fields(natural, "maxCodePoints"),
112
+ isBetweenCodePoints: fields(natural, "minimum", "maximum"),
113
+ isMinSize: fields(natural, "minSize"),
114
+ isMaxSize: fields(natural, "maxSize"),
115
+ isBetweenSize: fields(natural, "minimum", "maximum"),
116
+ isMinProperties: fields(natural, "minProperties"),
117
+ isMaxProperties: fields(natural, "maxProperties"),
118
+ isBetweenProperties: fields(natural, "minimum", "maximum"),
119
+ isPropertyNames: noArguments,
120
+ isUnique: noArguments,
121
+ isUniqueKey: noArguments
122
+ }
123
+
124
+ function invalidPayload(id: string, path: Path): never {
125
+ throw errorWithPath(`Invalid representation payload for ${id}`, [...path, "representation", "payload"])
126
+ }
127
+
128
+ function checkArity(id: string, actual: number, expected: number, path: Path): void {
129
+ if (actual !== expected) {
130
+ throw errorWithPath(`Invalid number of schema arguments for ${id}: expected ${expected}, got ${actual}`, path)
131
+ }
132
+ }
133
+
134
+ /** @internal */
135
+ export function resolveCheck(check: Representation.Check, path: Path): Representation.Generation.Check | undefined {
136
+ const { annotations, representation: repr } = check
137
+ if (annotations && "toCode" in annotations) return annotations.toCode as Representation.Generation.Check | undefined
138
+ if (check._tag !== "Filter" || !repr?.id.startsWith("effect/schema/")) return undefined
139
+ const name = repr.id.slice("effect/schema/".length)
140
+ if (!Object.hasOwn(checkArguments, name)) return undefined
141
+ const args = checkArguments[name](repr.payload) ?? invalidPayload(repr.id, path)
142
+ checkArity(repr.id, repr.schemas?.length ?? 0, name === "isPropertyNames" ? 1 : 0, [
143
+ ...path,
144
+ "representation",
145
+ "schemas"
146
+ ])
147
+ return ({ schemas }) => ({ runtime: `Schema.${name}(${schemas[0]?.runtime ?? args})` })
148
+ }
149
+
150
+ interface DeclarationRule {
151
+ readonly type: string
152
+ // An explicit zero distinguishes a call like ErrorInstance() from a constant like Date.
153
+ readonly arity?: number
154
+ readonly typeArity?: number
155
+ readonly module?: string
156
+ readonly runtime?: string
157
+ readonly argument?: PrintArgument
158
+ readonly crypto?: KeyAlgorithms
159
+ }
160
+
161
+ function options(accepts: (key: string, value: unknown) => boolean): PrintArgument {
162
+ return (payload) => {
163
+ if (payload === null) return ""
164
+ if (!isObject(payload)) return undefined
165
+ const entries = Object.entries(payload)
166
+ return entries.length > 0 && entries.every(([key, value]) => accepts(key, value)) ? format(payload) : undefined
167
+ }
168
+ }
169
+
170
+ interface KeyAlgorithms {
171
+ readonly withoutHash?: ReadonlyArray<string>
172
+ readonly withHash?: ReadonlyArray<string>
173
+ readonly rsa?: string
174
+ readonly rsaWithSalt?: string
175
+ }
176
+
177
+ const signature: KeyAlgorithms = {
178
+ withoutHash: ["ed25519"],
179
+ withHash: ["ecdsaP256", "ecdsaP384", "ecdsaP521"],
180
+ rsa: "rsaPkcs1v15",
181
+ rsaWithSalt: "rsaPss"
182
+ }
183
+ const keyAgreement: KeyAlgorithms = { withoutHash: ["x25519", "ecdhP256", "ecdhP384", "ecdhP521"] }
184
+
185
+ const declarations: Record<string, DeclarationRule> = {
186
+ "effect/schema/Json": { type: "Schema.Json" },
187
+ "effect/schema/MutableJson": { type: "Schema.MutableJson" },
188
+ "effect/schema/Error": {
189
+ type: "globalThis.Error",
190
+ runtime: "Schema.ErrorInstance",
191
+ arity: 0,
192
+ argument: options((key, value) => (key === "includeStack" || key === "excludeCause") && value === true)
193
+ },
194
+ "effect/schema/RegExp": { type: "globalThis.RegExp" },
195
+ "effect/schema/URL": { type: "globalThis.URL" },
196
+ "effect/schema/Date": { type: "globalThis.Date" },
197
+ "effect/schema/File": { type: "globalThis.File" },
198
+ "effect/schema/FormData": { type: "globalThis.FormData" },
199
+ "effect/schema/URLSearchParams": { type: "globalThis.URLSearchParams" },
200
+ "effect/schema/Uint8Array": { type: "globalThis.Uint8Array" },
201
+ "effect/schema/ReadonlyMap": { type: "globalThis.ReadonlyMap", arity: 2 },
202
+ "effect/schema/ReadonlySet": { type: "globalThis.ReadonlySet", arity: 1 },
203
+ "effect/schema/BigDecimal": { type: "BigDecimal.BigDecimal" },
204
+ "effect/schema/Rational": { type: "Rational.Rational" },
205
+ "effect/schema/ByteSize": { type: "ByteSize.ByteSize" },
206
+ "effect/schema/CauseReason": { type: "Cause.Reason", arity: 2, typeArity: 1 },
207
+ "effect/schema/Cause": { type: "Cause.Cause", arity: 2, typeArity: 1 },
208
+ "effect/schema/Chunk": { type: "Chunk.Chunk", arity: 1 },
209
+ "effect/schema/DateTimeUtc": { type: "DateTime.Utc" },
210
+ "effect/schema/TimeZoneOffset": { type: "DateTime.TimeZone.Offset" },
211
+ "effect/schema/TimeZoneNamed": { type: "DateTime.TimeZone.Named" },
212
+ "effect/schema/TimeZone": { type: "DateTime.TimeZone" },
213
+ "effect/schema/DateTimeZoned": { type: "DateTime.Zoned" },
214
+ "effect/schema/Duration": { type: "Duration.Duration" },
215
+ "effect/schema/Exit": { type: "Exit.Exit", arity: 3, typeArity: 2 },
216
+ "effect/schema/Graph": {
217
+ type: "Graph.Graph",
218
+ arity: 2,
219
+ argument: (kind) => kind === "directed" || kind === "undirected" ? literal(kind) : undefined
220
+ },
221
+ "effect/schema/HashMap": { type: "HashMap.HashMap", arity: 2 },
222
+ "effect/schema/HashSet": { type: "HashSet.HashSet", arity: 1 },
223
+ "effect/schema/Option": { type: "Option.Option", arity: 1 },
224
+ "effect/schema/Redacted": {
225
+ type: "Redacted.Redacted",
226
+ arity: 1,
227
+ argument: options((key, value) =>
228
+ key === "label" ? typeof value === "string" : key === "disallowJsonEncode" && value === true
229
+ )
230
+ },
231
+ "effect/schema/Result": { type: "Result.Result", arity: 2 },
232
+ "effect/schema/SemVer": { type: "SemVer.SemVer" },
233
+ "effect/schema/SemVerRange": { type: "SemVerRange.SemVerRange" },
234
+ "effect/http/Cookie": { type: "Cookies.Cookie", module: "effect/http/Cookies" },
235
+ "effect/http/Cookies": { type: "Cookies.Cookies", module: "effect/http/Cookies" },
236
+ "effect/http/Headers": { type: "Headers.Headers", module: "effect/http/Headers" },
237
+ "effect/http/UrlParams": { type: "UrlParams.UrlParams", module: "effect/http/UrlParams" },
238
+ "effect/http/PersistedFile": {
239
+ type: "Multipart.PersistedFile",
240
+ module: "effect/http/Multipart",
241
+ runtime: "Multipart.PersistedFileSchema"
242
+ },
243
+ "effect/crypto/MacKey": {
244
+ type: "Mac.Key",
245
+ crypto: { withHash: ["hmacSha1", "hmacSha256", "hmacSha384", "hmacSha512"] }
246
+ },
247
+ "effect/crypto/AeadKey": {
248
+ type: "Aead.Key",
249
+ crypto: { withoutHash: ["aes128Gcm", "aes256Gcm", "chacha20Poly1305", "xchacha20Poly1305"] }
250
+ },
251
+ "effect/crypto/CipherKey": {
252
+ type: "Cipher.Key",
253
+ crypto: { withoutHash: ["aes128Ctr", "aes256Ctr", "aes128Cbc", "aes256Cbc"] }
254
+ },
255
+ "effect/crypto/SignaturePublicKey": { type: "Signature.PublicKey", crypto: signature },
256
+ "effect/crypto/SignaturePrivateKey": { type: "Signature.PrivateKey", crypto: signature },
257
+ "effect/crypto/KeyAgreementPublicKey": { type: "KeyAgreement.PublicKey", crypto: keyAgreement },
258
+ "effect/crypto/KeyAgreementPrivateKey": { type: "KeyAgreement.PrivateKey", crypto: keyAgreement },
259
+ "effect/crypto/KeyWrapKey": { type: "KeyWrap.Key", crypto: { withoutHash: ["aes128Kw", "aes256Kw"] } },
260
+ "effect/crypto/KeyWrapPublicKey": { type: "KeyWrap.PublicKey", crypto: { rsa: "rsaOaep" } },
261
+ "effect/crypto/KeyWrapPrivateKey": { type: "KeyWrap.PrivateKey", crypto: { rsa: "rsaOaep" } }
262
+ }
263
+
264
+ const digestSuffixes = new Map([
265
+ ["MD5", "Md5"],
266
+ ["SHA-1", "Sha1"],
267
+ ["SHA-256", "Sha256"],
268
+ ["SHA-384", "Sha384"],
269
+ ["SHA-512", "Sha512"]
270
+ ])
271
+
272
+ function cryptoKey(
273
+ name: string,
274
+ type: string,
275
+ algorithms: KeyAlgorithms,
276
+ payload: Json
277
+ ): Representation.Generation.DeclarationOutput | undefined {
278
+ if (!isObject(payload) || typeof payload.name !== "string") return undefined
279
+ const { hash, modulusLength, saltLength } = payload
280
+ const suffix = typeof hash === "string" ? digestSuffixes.get(hash) : undefined
281
+ if (hash !== undefined && suffix === undefined) return undefined
282
+ const digest = suffix === undefined ? undefined : `Digest.${suffix.toLowerCase()}`
283
+ const family = type.split(".")[0]
284
+ const imports = [`import * as ${family} from "effect/crypto/${family}"`]
285
+ if (digest !== undefined) imports.push("import * as Digest from \"effect/crypto/Digest\"")
286
+ let algorithm: string
287
+ if (modulusLength === undefined) {
288
+ const names = digest === undefined ? algorithms.withoutHash : algorithms.withHash
289
+ if (!names?.includes(payload.name) || saltLength !== undefined) return undefined
290
+ algorithm = `${family}.${payload.name}`
291
+ if (digest !== undefined) algorithm = `{ ...${algorithm}, hash: ${digest} }`
292
+ } else {
293
+ const factory = saltLength === undefined ? algorithms.rsa : algorithms.rsaWithSalt
294
+ if (
295
+ factory === undefined || digest === undefined || !Number.isFinite(modulusLength) ||
296
+ saltLength !== undefined && !Number.isFinite(saltLength)
297
+ ) return undefined
298
+ const salt = saltLength === undefined ? "" : `, saltLength: ${saltLength}`
299
+ algorithm = `${family}.${factory}({ hash: ${digest}, modulusLength: ${modulusLength}${salt} })`
300
+ if (payload.name !== factory + suffix) algorithm = `{ ...${algorithm}, name: ${literal(payload.name)} }`
301
+ }
302
+ return { runtime: `Schema.${name}(${algorithm})`, Type: type, importDeclarations: imports }
303
+ }
304
+
305
+ /** @internal */
306
+ export function resolveDeclaration(
307
+ node: Representation.Declaration,
308
+ path: Path
309
+ ): Representation.Generation.Declaration | undefined {
310
+ const { annotations, representation: repr } = node
311
+ if (annotations && "toCode" in annotations) {
312
+ return annotations.toCode as Representation.Generation.Declaration | undefined
313
+ }
314
+ if (!repr || !Object.hasOwn(declarations, repr.id)) return undefined
315
+ const { id, payload } = repr
316
+ const name = id.slice(id.lastIndexOf("/") + 1)
317
+ const rule = declarations[id]
318
+ checkArity(id, node.typeParameters.length, rule.arity ?? 0, [...path, "typeParameters"])
319
+ if (rule.crypto) {
320
+ const output = cryptoKey(name, rule.type, rule.crypto, payload) ?? invalidPayload(id, path)
321
+ return () => output
322
+ }
323
+ return ({ typeParameters }) => {
324
+ const args = typeParameters.map((p) => p.runtime)
325
+ const types = typeParameters.slice(0, rule.typeArity).map((p) => p.Type)
326
+ const argument = (rule.argument ?? noArguments)(payload) ?? invalidPayload(id, path)
327
+ if (id === "effect/schema/Graph") {
328
+ args.unshift(argument)
329
+ types.push(argument)
330
+ } else if (argument !== "") {
331
+ args.push(argument)
332
+ }
333
+ const runtime = rule.runtime ?? `Schema.${name}`
334
+ const namespace = rule.type.split(".")[0]
335
+ return {
336
+ runtime: rule.arity === undefined ? runtime : `${runtime}(${args.join(", ")})`,
337
+ Type: types.length > 0 ? `${rule.type}<${types.join(", ")}>` : rule.type,
338
+ importDeclarations: namespace === "globalThis" || namespace === "Schema" ? [] : [
339
+ `import * as ${namespace} from "${rule.module ?? "effect/" + namespace}"`
340
+ ]
341
+ }
342
+ }
343
+ }
@@ -8,14 +8,12 @@ import * as SchemaAST from "../../SchemaAST.ts"
8
8
  import * as SchemaParser from "../../SchemaParser.ts"
9
9
  import * as InternalAnnotations from "./annotations.ts"
10
10
 
11
- const recurMemo = memoize(recur)
12
-
13
11
  /** @internal */
14
12
  export const toEquivalence = (ast: SchemaAST.AST): Equivalence.Equivalence<any> => {
15
- return recurMemo(SchemaAST.toType(ast))
13
+ return recur(SchemaAST.toType(ast))
16
14
  }
17
15
 
18
- function recur(ast: SchemaAST.AST): Equivalence.Equivalence<any> {
16
+ const recur = memoize((ast: SchemaAST.AST): Equivalence.Equivalence<any> => {
19
17
  // ---------------------------------------------
20
18
  // handle annotations
21
19
  // ---------------------------------------------
@@ -156,7 +154,7 @@ function recur(ast: SchemaAST.AST): Equivalence.Equivalence<any> {
156
154
  return Equivalence.make((a, b) => (equivalence ??= toEquivalence(ast.thunk()))(a, b))
157
155
  }
158
156
  }
159
- }
157
+ })
160
158
 
161
159
  function declarationEquivalence(ast: SchemaAST.Declaration): Equivalence.Equivalence<any> {
162
160
  const representation = (ast.annotations as Schema.Annotations.Declaration<any> | undefined)?.representation