effect-app 4.0.0-beta.13 → 4.0.0-beta.131

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 (139) hide show
  1. package/CHANGELOG.md +503 -0
  2. package/dist/Config/SecretURL.js +2 -2
  3. package/dist/Config.d.ts +7 -0
  4. package/dist/Config.d.ts.map +1 -0
  5. package/dist/Config.js +6 -0
  6. package/dist/ConfigProvider.d.ts +39 -0
  7. package/dist/ConfigProvider.d.ts.map +1 -0
  8. package/dist/ConfigProvider.js +42 -0
  9. package/dist/{ServiceMap.d.ts → Context.d.ts} +14 -18
  10. package/dist/Context.d.ts.map +1 -0
  11. package/dist/Context.js +66 -0
  12. package/dist/Effect.d.ts +8 -9
  13. package/dist/Effect.d.ts.map +1 -1
  14. package/dist/Effect.js +3 -6
  15. package/dist/Layer.d.ts +5 -4
  16. package/dist/Layer.d.ts.map +1 -1
  17. package/dist/Layer.js +1 -1
  18. package/dist/Operations.d.ts +198 -33
  19. package/dist/Operations.d.ts.map +1 -1
  20. package/dist/Pure.d.ts +2 -2
  21. package/dist/Pure.d.ts.map +1 -1
  22. package/dist/Pure.js +13 -13
  23. package/dist/Schema/Class.d.ts +48 -10
  24. package/dist/Schema/Class.d.ts.map +1 -1
  25. package/dist/Schema/Class.js +120 -16
  26. package/dist/Schema/SpecialJsonSchema.d.ts +33 -0
  27. package/dist/Schema/SpecialJsonSchema.d.ts.map +1 -0
  28. package/dist/Schema/SpecialJsonSchema.js +122 -0
  29. package/dist/Schema/SpecialOpenApi.d.ts +32 -0
  30. package/dist/Schema/SpecialOpenApi.d.ts.map +1 -0
  31. package/dist/Schema/SpecialOpenApi.js +123 -0
  32. package/dist/Schema/brand.d.ts +10 -1
  33. package/dist/Schema/brand.d.ts.map +1 -1
  34. package/dist/Schema/brand.js +1 -1
  35. package/dist/Schema/email.d.ts.map +1 -1
  36. package/dist/Schema/email.js +9 -4
  37. package/dist/Schema/ext.d.ts +112 -47
  38. package/dist/Schema/ext.d.ts.map +1 -1
  39. package/dist/Schema/ext.js +115 -53
  40. package/dist/Schema/moreStrings.d.ts +110 -10
  41. package/dist/Schema/moreStrings.d.ts.map +1 -1
  42. package/dist/Schema/moreStrings.js +19 -10
  43. package/dist/Schema/numbers.d.ts +126 -14
  44. package/dist/Schema/numbers.d.ts.map +1 -1
  45. package/dist/Schema/numbers.js +10 -9
  46. package/dist/Schema/phoneNumber.d.ts.map +1 -1
  47. package/dist/Schema/phoneNumber.js +8 -3
  48. package/dist/Schema/strings.d.ts +36 -4
  49. package/dist/Schema/strings.d.ts.map +1 -1
  50. package/dist/Schema/strings.js +1 -1
  51. package/dist/Schema.d.ts +74 -55
  52. package/dist/Schema.d.ts.map +1 -1
  53. package/dist/Schema.js +85 -64
  54. package/dist/client/apiClientFactory.d.ts +12 -28
  55. package/dist/client/apiClientFactory.d.ts.map +1 -1
  56. package/dist/client/apiClientFactory.js +16 -17
  57. package/dist/client/clientFor.d.ts +6 -5
  58. package/dist/client/clientFor.d.ts.map +1 -1
  59. package/dist/client/errors.d.ts +18 -9
  60. package/dist/client/errors.d.ts.map +1 -1
  61. package/dist/client/errors.js +35 -10
  62. package/dist/client/makeClient.d.ts +73 -28
  63. package/dist/client/makeClient.d.ts.map +1 -1
  64. package/dist/client/makeClient.js +49 -23
  65. package/dist/http/Request.d.ts.map +1 -1
  66. package/dist/http/Request.js +5 -5
  67. package/dist/ids.d.ts +2 -2
  68. package/dist/ids.d.ts.map +1 -1
  69. package/dist/ids.js +3 -2
  70. package/dist/index.d.ts +3 -7
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +4 -8
  73. package/dist/middleware.d.ts +2 -2
  74. package/dist/middleware.d.ts.map +1 -1
  75. package/dist/middleware.js +3 -3
  76. package/dist/rpc/MiddlewareMaker.d.ts +4 -3
  77. package/dist/rpc/MiddlewareMaker.d.ts.map +1 -1
  78. package/dist/rpc/MiddlewareMaker.js +23 -24
  79. package/dist/rpc/RpcContextMap.d.ts +2 -2
  80. package/dist/rpc/RpcContextMap.d.ts.map +1 -1
  81. package/dist/rpc/RpcContextMap.js +4 -4
  82. package/dist/rpc/RpcMiddleware.d.ts +4 -3
  83. package/dist/rpc/RpcMiddleware.d.ts.map +1 -1
  84. package/dist/rpc/RpcMiddleware.js +1 -1
  85. package/dist/utils/gen.d.ts +1 -1
  86. package/dist/utils/gen.d.ts.map +1 -1
  87. package/dist/utils/logger.d.ts +2 -2
  88. package/dist/utils/logger.d.ts.map +1 -1
  89. package/dist/utils/logger.js +3 -3
  90. package/dist/utils.d.ts +7 -1
  91. package/dist/utils.d.ts.map +1 -1
  92. package/dist/utils.js +8 -2
  93. package/package.json +30 -14
  94. package/src/Config/SecretURL.ts +1 -1
  95. package/src/Config.ts +14 -0
  96. package/src/ConfigProvider.ts +48 -0
  97. package/src/{ServiceMap.ts → Context.ts} +51 -59
  98. package/src/Effect.ts +11 -14
  99. package/src/Layer.ts +5 -4
  100. package/src/Pure.ts +17 -18
  101. package/src/Schema/Class.ts +157 -30
  102. package/src/Schema/SpecialJsonSchema.ts +137 -0
  103. package/src/Schema/SpecialOpenApi.ts +130 -0
  104. package/src/Schema/brand.ts +18 -3
  105. package/src/Schema/email.ts +10 -2
  106. package/src/Schema/ext.ts +196 -87
  107. package/src/Schema/moreStrings.ts +31 -17
  108. package/src/Schema/numbers.ts +14 -13
  109. package/src/Schema/phoneNumber.ts +8 -1
  110. package/src/Schema/strings.ts +4 -4
  111. package/src/Schema.ts +195 -104
  112. package/src/client/apiClientFactory.ts +104 -112
  113. package/src/client/clientFor.ts +6 -1
  114. package/src/client/errors.ts +42 -17
  115. package/src/client/makeClient.ts +150 -61
  116. package/src/http/Request.ts +7 -4
  117. package/src/ids.ts +2 -1
  118. package/src/index.ts +3 -10
  119. package/src/middleware.ts +2 -2
  120. package/src/rpc/MiddlewareMaker.ts +33 -44
  121. package/src/rpc/RpcContextMap.ts +6 -5
  122. package/src/rpc/RpcMiddleware.ts +5 -4
  123. package/src/utils/gen.ts +1 -1
  124. package/src/utils/logger.ts +2 -2
  125. package/src/utils.ts +8 -4
  126. package/test/dist/moreStrings.test.d.ts.map +1 -0
  127. package/test/dist/rpc.test.d.ts.map +1 -1
  128. package/test/dist/secretURL.test.d.ts.map +1 -0
  129. package/test/dist/special.test.d.ts.map +1 -0
  130. package/test/moreStrings.test.ts +17 -0
  131. package/test/rpc.test.ts +30 -6
  132. package/test/schema.test.ts +517 -4
  133. package/test/secretURL.test.ts +157 -0
  134. package/test/special.test.ts +862 -0
  135. package/test/utils.test.ts +2 -2
  136. package/tsconfig.base.json +0 -1
  137. package/tsconfig.json +0 -1
  138. package/dist/ServiceMap.d.ts.map +0 -1
  139. package/dist/ServiceMap.js +0 -91
@@ -1,31 +1,88 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { pipe, Struct as Struct2 } from "effect"
3
- import type { Struct } from "effect/Schema"
2
+ import { Effect, Option, Schema, SchemaAST, SchemaIssue } from "effect"
4
3
  import * as S from "effect/Schema"
4
+ import { copyOrigin } from "../utils.js"
5
+ import { concurrencyUnbounded } from "./ext.js"
5
6
 
6
7
  type ClassAnnotations<Self> = S.Annotations.Declaration<Self, readonly [any]>
7
8
 
8
- export interface EnhancedClass<Self, SchemaS extends S.Top & { readonly fields: Struct.Fields }, Inherited>
9
- extends S.Class<Self, SchemaS, Inherited>, /* Reason for enhancement */ PropsExtensions<SchemaS["fields"]>
9
+ export interface EnhancedClass<Self, SchemaS extends S.Top & { readonly fields: S.Struct.Fields }, Inherited>
10
+ extends S.Class<Self, SchemaS, Inherited>
10
11
  {
12
+ /**
13
+ * See `copyOrigin` docs in `utils.ts` for return-type design details.
14
+ */
15
+ readonly copy: ReturnType<typeof copyOrigin<new(_: any) => Self>>
11
16
  }
12
17
  type MissingSelfGeneric<Usage extends string, Params extends string = ""> =
13
18
  `Missing \`Self\` generic - use \`class Self extends ${Usage}<Self>()(${Params}{ ... })\``
14
19
 
15
- export interface PropsExtensions<Fields> {
16
- // include: <NewProps extends S.Struct.Fields>(
17
- // fnc: (fields: Fields) => NewProps
18
- // ) => NewProps
19
- pick: <P extends keyof Fields>(...keys: readonly P[]) => Pick<Fields, P>
20
- omit: <P extends keyof Fields>(...keys: readonly P[]) => Omit<Fields, P>
21
- }
22
-
23
- type HasFields<Fields extends Struct.Fields> = {
20
+ type HasFields<Fields extends S.Struct.Fields> = {
24
21
  readonly fields: Fields
25
22
  } | {
26
23
  readonly from: HasFields<Fields>
27
24
  }
28
25
 
26
+ export type Class<Self, S extends S.Top & { readonly fields: S.Struct.Fields }, Inherited> = EnhancedClass<
27
+ Self,
28
+ S,
29
+ Inherited
30
+ >
31
+
32
+ /**
33
+ * Build a modified Declaration that accepts struct-matching values during
34
+ * encoding, given the original Declaration and the class's fields.
35
+ */
36
+ function makeRelaxedDeclaration(
37
+ ast: SchemaAST.Declaration,
38
+ fields: Schema.Struct.Fields,
39
+ cls: any
40
+ ): SchemaAST.Declaration {
41
+ const structSchema = Schema.Struct(fields)
42
+ const isStructValue = Schema.is(structSchema)
43
+ const existingParseOptions = ast.annotations?.["parseOptions"] as SchemaAST.ParseOptions | undefined
44
+ const annotations = {
45
+ ...ast.annotations,
46
+ parseOptions: { ...existingParseOptions, concurrency: "unbounded" as const }
47
+ }
48
+ return new SchemaAST.Declaration(
49
+ ast.typeParameters,
50
+ () => (input: unknown, self: SchemaAST.Declaration) => {
51
+ if (input instanceof cls || isStructValue(input)) {
52
+ return Effect.succeed(input)
53
+ }
54
+ return Effect.fail(new SchemaIssue.InvalidType(self, Option.some(input)))
55
+ },
56
+ annotations,
57
+ ast.checks,
58
+ ast.encoding,
59
+ ast.context
60
+ )
61
+ }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Class — like Schema.Class but with relaxed encoding
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Like `Schema.Class`, but the resulting class accepts plain objects matching
69
+ * the struct schema during encoding — not only `instanceof` or type-id
70
+ * checks.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * import { Schema } from "effect"
75
+ * import { Class } from "./Class.js"
76
+ *
77
+ * class A extends Class<A>("A")({ a: Schema.String }) {}
78
+ *
79
+ * // Construction works as normal:
80
+ * new A({ a: "hello" })
81
+ *
82
+ * // Encoding accepts plain objects:
83
+ * Schema.encodeUnknownSync(A)({ a: "hello" }) // { a: "hello" }
84
+ * ```
85
+ */
29
86
  export const Class: <Self = never>(identifier: string) => <Fields extends S.Struct.Fields>(
30
87
  fieldsOr: Fields | HasFields<Fields>,
31
88
  annotations?: ClassAnnotations<Self>
@@ -35,38 +92,104 @@ export const Class: <Self = never>(identifier: string) => <Fields extends S.Stru
35
92
  S.Struct<Fields>,
36
93
  {}
37
94
  > = (identifier) => (fields, annotations) => {
38
- const cls = S.Class as any
39
- return class extends cls(identifier)(fields, annotations) {
40
- constructor(a: any, b = true) {
41
- super(a, b)
95
+ // Build the original Schema.Class
96
+ const Base = (S.Class as any)(identifier)(fields, annotations)
97
+ // Get the original ast getter from the base class
98
+ const originalAstDescriptor = Object.getOwnPropertyDescriptor(Base, "ast")!
99
+
100
+ // Cache per-class to avoid recomputing
101
+ const astCache = new WeakMap<any, SchemaAST.Declaration>()
102
+ const copyCache = new WeakMap<any, ReturnType<typeof copyOrigin>>()
103
+
104
+ return class extends Base {
105
+ static get copy() {
106
+ let cached = copyCache.get(this)
107
+ if (cached === undefined) {
108
+ cached = copyOrigin(this)
109
+ copyCache.set(this, cached)
110
+ }
111
+ return cached
112
+ }
113
+ static get ast(): SchemaAST.Declaration {
114
+ let cached = astCache.get(this)
115
+ if (cached !== undefined) return cached
116
+ // Call the original getter with `this` bound to the actual user class,
117
+ // so getClassSchema(this) creates a schema that uses `new this(...)`.
118
+ const originalAst = originalAstDescriptor.get!.call(this) as SchemaAST.Declaration
119
+ cached = makeRelaxedDeclaration(originalAst, Base.fields, this)
120
+ astCache.set(this, cached)
121
+ return cached
122
+ }
123
+ static mapFields(f: any, options?: any) {
124
+ return Base.mapFields(f, options).annotate(concurrencyUnbounded)
42
125
  }
43
- // static readonly include = include(fields)
44
- static readonly pick = (...selection: any[]) => pipe(this["fields"], Struct2.pick(selection))
45
- static readonly omit = (...selection: any[]) => pipe(this["fields"], Struct2.omit(selection))
46
126
  } as any
47
127
  }
48
128
 
49
- export const TaggedClass: <Self = never>(identifier?: string) => <Tag extends string, Fields extends S.Struct.Fields>(
129
+ // ---------------------------------------------------------------------------
130
+ // TaggedClass — like Schema.TaggedClass but with relaxed encoding
131
+ // ---------------------------------------------------------------------------
132
+
133
+ /**
134
+ * Like `Schema.TaggedClass`, but the resulting class accepts plain objects
135
+ * matching the struct schema during encoding.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * import { Schema } from "effect"
140
+ * import { TaggedClass } from "./Class.js"
141
+ *
142
+ * class Circle extends TaggedClass<Circle>()("Circle", {
143
+ * radius: Schema.Number
144
+ * }) {}
145
+ *
146
+ * Schema.encodeUnknownSync(Circle)({ _tag: "Circle", radius: 5 })
147
+ * ```
148
+ */
149
+ export const TaggedClass: <Self = never>(
150
+ identifier?: string
151
+ ) => <Tag extends string, Fields extends S.Struct.Fields>(
50
152
  tag: Tag,
51
153
  fieldsOr: Fields | HasFields<Fields>,
52
154
  annotations?: ClassAnnotations<Self>
53
- ) => [Self] extends [never] ? MissingSelfGeneric<"Class">
155
+ ) => [Self] extends [never] ? MissingSelfGeneric<"TaggedClass">
54
156
  : EnhancedClass<
55
157
  Self,
56
158
  S.Struct<{ readonly _tag: S.tag<Tag> } & Fields>,
57
159
  {}
58
160
  > = (identifier) => (tag, fields, annotations) => {
59
- const cls = S.TaggedClass as any
60
- return class extends cls(identifier)(tag, fields, annotations) {
61
- constructor(a: any, b = true) {
62
- super(a, b)
161
+ const Base = (S.TaggedClass as any)(identifier)(tag, fields, annotations)
162
+ const originalAstDescriptor = Object.getOwnPropertyDescriptor(Base, "ast")!
163
+ const astCache = new WeakMap<any, SchemaAST.Declaration>()
164
+ const copyCache = new WeakMap<any, ReturnType<typeof copyOrigin>>()
165
+
166
+ return class extends Base {
167
+ static get copy() {
168
+ let cached = copyCache.get(this)
169
+ if (cached === undefined) {
170
+ cached = copyOrigin(this)
171
+ copyCache.set(this, cached)
172
+ }
173
+ return cached
174
+ }
175
+ static get ast(): SchemaAST.Declaration {
176
+ let cached = astCache.get(this)
177
+ if (cached !== undefined) return cached
178
+ const originalAst = originalAstDescriptor.get!.call(this) as SchemaAST.Declaration
179
+ cached = makeRelaxedDeclaration(originalAst, Base.fields, this)
180
+ astCache.set(this, cached)
181
+ return cached
182
+ }
183
+ static mapFields(f: any, options?: any) {
184
+ return Base.mapFields(f, options).annotate(concurrencyUnbounded)
63
185
  }
64
- // static readonly include = include(fields)
65
- static readonly pick = (...selection: any[]) => pipe(this["fields"], Struct2.pick(selection))
66
- static readonly omit = (...selection: any[]) => pipe(this["fields"], Struct2.omit(selection))
67
186
  } as any
68
187
  }
69
188
 
189
+ // ---------------------------------------------------------------------------
190
+ // ExtendedClass — like Class but with extra type parameter for hierarchies
191
+ // ---------------------------------------------------------------------------
192
+
70
193
  export const ExtendedClass: <Self, _SelfFrom>(identifier: string) => <Fields extends S.Struct.Fields>(
71
194
  fieldsOr: Fields | HasFields<Fields>,
72
195
  annotations?: ClassAnnotations<Self>
@@ -76,7 +199,11 @@ export const ExtendedClass: <Self, _SelfFrom>(identifier: string) => <Fields ext
76
199
  {}
77
200
  > = Class as any
78
201
 
79
- export interface EnhancedTaggedClass<Self, Tag extends string, Fields extends Struct.Fields, SelfFrom>
202
+ // ---------------------------------------------------------------------------
203
+ // ExtendedTaggedClass — like TaggedClass but with extra type parameter for hierarchies
204
+ // ---------------------------------------------------------------------------
205
+
206
+ export interface EnhancedTaggedClass<Self, Tag extends string, Fields extends S.Struct.Fields, SelfFrom>
80
207
  extends
81
208
  EnhancedClass<
82
209
  Self,
@@ -0,0 +1,137 @@
1
+ /**
2
+ * SpecialJsonSchema — A variant of Schema.toJsonSchemaDocument that
3
+ * post-processes the output (e.g. flattens simple allOf).
4
+ */
5
+ import { type JsonSchema, type Schema, SchemaRepresentation } from "effect"
6
+
7
+ /**
8
+ * Converts a schema to a JSON Schema Document (draft-2020-12), with
9
+ * post-processing that flattens simple allOf entries.
10
+ */
11
+ export function specialJsonSchemaDocument(
12
+ schema: Schema.Top,
13
+ options?: Schema.ToJsonSchemaOptions
14
+ ): JsonSchema.Document<"draft-2020-12"> {
15
+ const doc = SchemaRepresentation.fromAST(schema.ast)
16
+ const jd = SchemaRepresentation.toJsonSchemaDocument(doc, options)
17
+ const processedDefs: JsonSchema.Definitions = {}
18
+ for (const [key, def] of Object.entries(jd.definitions)) {
19
+ processedDefs[key] = postProcessJsonSchema(def)
20
+ }
21
+ return {
22
+ dialect: "draft-2020-12",
23
+ schema: postProcessJsonSchema(jd.schema),
24
+ definitions: processedDefs
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Flattens `allOf` entries into the parent when the parent already has a
30
+ * `type` and every `allOf` entry is a plain constraint object (no `$ref`,
31
+ * no `type`). Merged properties from `allOf` entries win on conflict.
32
+ */
33
+ export function flattenSimpleAllOf(obj: unknown): unknown {
34
+ if (obj === null || typeof obj !== "object") return obj
35
+
36
+ if (globalThis.Array.isArray(obj)) {
37
+ return obj.map(flattenSimpleAllOf)
38
+ }
39
+
40
+ const record = obj as Record<string, unknown>
41
+ const result: Record<string, unknown> = {}
42
+ for (const [key, value] of Object.entries(record)) {
43
+ result[key] = flattenSimpleAllOf(value)
44
+ }
45
+
46
+ if (result["type"] && globalThis.Array.isArray(result["allOf"])) {
47
+ const allOf = result["allOf"] as Array<Record<string, unknown>>
48
+ const canFlatten = allOf.every((entry) =>
49
+ typeof entry === "object" && entry !== null && !("$ref" in entry) && !("type" in entry)
50
+ )
51
+ if (canFlatten) {
52
+ const { allOf: _, ...rest } = result
53
+ let merged: Record<string, unknown> = { ...rest }
54
+ for (const entry of allOf) {
55
+ merged = { ...merged, ...entry }
56
+ }
57
+ return merged
58
+ }
59
+ }
60
+
61
+ return result
62
+ }
63
+
64
+ /**
65
+ * Recursively removes `additionalProperties: false` from JSON Schema objects.
66
+ * Only removes when the value is exactly `false` -- other values are left intact.
67
+ */
68
+ export function removeAdditionalPropertiesFalse(obj: unknown): unknown {
69
+ if (obj === null || typeof obj !== "object") return obj
70
+
71
+ if (globalThis.Array.isArray(obj)) {
72
+ return obj.map(removeAdditionalPropertiesFalse)
73
+ }
74
+
75
+ const record = obj as Record<string, unknown>
76
+ const result: Record<string, unknown> = {}
77
+ for (const [key, value] of Object.entries(record)) {
78
+ if (key === "additionalProperties" && value === false) continue
79
+ result[key] = removeAdditionalPropertiesFalse(value)
80
+ }
81
+
82
+ return result
83
+ }
84
+
85
+ /**
86
+ * Flattens nested `anyOf` entries: if an anyOf entry is itself just `{ anyOf: [...] }`
87
+ * with no other keys, its children are inlined. If only one item remains, the anyOf
88
+ * wrapper is removed entirely.
89
+ */
90
+ export function flattenNestedAnyOf(obj: unknown): unknown {
91
+ if (obj === null || typeof obj !== "object") return obj
92
+ if (globalThis.Array.isArray(obj)) return obj.map(flattenNestedAnyOf)
93
+
94
+ const record = obj as Record<string, unknown>
95
+ const result: Record<string, unknown> = {}
96
+ for (const [key, value] of Object.entries(record)) {
97
+ result[key] = flattenNestedAnyOf(value)
98
+ }
99
+
100
+ if (globalThis.Array.isArray(result["anyOf"])) {
101
+ const anyOf = result["anyOf"] as Array<unknown>
102
+ const flattened: Array<unknown> = []
103
+ for (const entry of anyOf) {
104
+ if (
105
+ typeof entry === "object"
106
+ && entry !== null
107
+ && !globalThis.Array.isArray(entry)
108
+ && "anyOf" in entry
109
+ && Object.keys(entry).length === 1
110
+ && globalThis.Array.isArray((entry as Record<string, unknown>)["anyOf"])
111
+ ) {
112
+ flattened.push(...(entry as Record<string, unknown>)["anyOf"] as Array<unknown>)
113
+ } else {
114
+ flattened.push(entry)
115
+ }
116
+ }
117
+ if (flattened.length === 1) {
118
+ const { anyOf: _, ...rest } = result
119
+ const single = flattened[0]
120
+ if (typeof single === "object" && single !== null && !globalThis.Array.isArray(single)) {
121
+ return { ...rest, ...single }
122
+ }
123
+ return single
124
+ }
125
+ result["anyOf"] = flattened
126
+ }
127
+
128
+ return result
129
+ }
130
+
131
+ /**
132
+ * Applies JSON Schema post-processing: flattens simple allOf,
133
+ * flattens nested anyOf, then strips additionalProperties: false.
134
+ */
135
+ export function postProcessJsonSchema(obj: JsonSchema.JsonSchema): JsonSchema.JsonSchema {
136
+ return removeAdditionalPropertiesFalse(flattenNestedAnyOf(flattenSimpleAllOf(obj))) as JsonSchema.JsonSchema
137
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * SpecialOpenApi — Deduplicates `components/schemas` entries in an OpenAPI spec
3
+ * and applies JSON Schema post-processing (null removal, allOf flattening).
4
+ *
5
+ * When `OpenApi.fromApi` generates the spec, different AST nodes sharing the
6
+ * same identifier can produce duplicate entries (e.g. "X" and "X1") in
7
+ * `components.schemas`. This module provides a transform function that
8
+ * collapses those duplicates, rewrites all `$ref` pointers accordingly,
9
+ * and post-processes schemas for better codegen compatibility.
10
+ *
11
+ * Usage with the OpenApi `Transform` annotation:
12
+ *
13
+ * ```ts
14
+ * import { OpenApi } from "effect/unstable"
15
+ * import { deduplicateOpenApiSchemas } from "./SpecialOpenApi.js"
16
+ *
17
+ * const api = HttpApi.make("myApi")
18
+ * .pipe(HttpApi.annotateContext(OpenApi.annotations({ transform: deduplicateOpenApiSchemas })))
19
+ * ```
20
+ */
21
+
22
+ import { postProcessJsonSchema } from "./SpecialJsonSchema.js"
23
+
24
+ /**
25
+ * Deduplicates `components.schemas` entries in an OpenAPI spec.
26
+ *
27
+ * Entries sharing the same base identifier (e.g. "X" and "X1") whose JSON
28
+ * representations are identical are collapsed into a single canonical entry,
29
+ * and all `$ref` pointers throughout the spec are rewritten to point to
30
+ * the canonical key.
31
+ *
32
+ * Designed to be used as the `transform` option in `OpenApi.annotations`.
33
+ */
34
+ export function deduplicateOpenApiSchemas(
35
+ spec: Record<string, any>
36
+ ): Record<string, any> {
37
+ const components = spec["components"] as Record<string, any> | undefined
38
+ if (!components) return spec
39
+ const schemas = components["schemas"] as Record<string, any> | undefined
40
+ if (!schemas) return spec
41
+
42
+ const keys = Object.keys(schemas)
43
+ if (keys.length === 0) return spec
44
+
45
+ // Group keys by base identifier (strip trailing digits)
46
+ const groups = new Map<string, Array<{ key: string; fingerprint: string }>>()
47
+ for (const key of keys) {
48
+ const base = getBaseIdentifier(key)
49
+ const fingerprint = JSON.stringify(schemas[key])
50
+ const group = groups.get(base)
51
+ if (group === undefined) {
52
+ groups.set(base, [{ key, fingerprint }])
53
+ } else {
54
+ group.push({ key, fingerprint })
55
+ }
56
+ }
57
+
58
+ // Build remapping from duplicate keys to canonical keys
59
+ const remapping = new Map<string, string>()
60
+ for (const [, group] of groups) {
61
+ if (group.length <= 1) continue
62
+ const seen = new Map<string, string>() // fingerprint -> canonical key
63
+ for (const entry of group) {
64
+ const canonical = seen.get(entry.fingerprint)
65
+ if (canonical !== undefined) {
66
+ remapping.set(entry.key, canonical)
67
+ } else {
68
+ seen.set(entry.fingerprint, entry.key)
69
+ }
70
+ }
71
+ }
72
+
73
+ if (remapping.size === 0) return postProcessJsonSchema(spec)
74
+
75
+ // Build new schemas object without duplicates
76
+ const newSchemas: Record<string, any> = {}
77
+ for (const key of keys) {
78
+ if (!remapping.has(key)) {
79
+ newSchemas[key] = schemas[key]
80
+ }
81
+ }
82
+
83
+ // Deep clone the spec, replace schemas, and rewrite all $ref pointers
84
+ const newSpec = structuredClone(spec)
85
+ newSpec["components"]["schemas"] = newSchemas
86
+ rewriteRefs(newSpec, remapping)
87
+
88
+ return postProcessJsonSchema(newSpec)
89
+ }
90
+
91
+ /**
92
+ * Extracts the base identifier from a schema key by stripping trailing
93
+ * digits appended by the gen() function.
94
+ * E.g. "X1" -> "X", "X" -> "X", "MyType2" -> "MyType"
95
+ */
96
+ function getBaseIdentifier(key: string): string {
97
+ const match = key.match(/^(.+?)(\d+)$/)
98
+ return match ? match[1]! : key
99
+ }
100
+
101
+ /**
102
+ * Recursively rewrites `$ref` values in a JSON object tree.
103
+ * Mutates the object in-place (caller should pass a deep clone).
104
+ */
105
+ function rewriteRefs(obj: any, remapping: Map<string, string>): void {
106
+ if (obj === null || typeof obj !== "object") return
107
+
108
+ if (Array.isArray(obj)) {
109
+ for (const item of obj) {
110
+ rewriteRefs(item, remapping)
111
+ }
112
+ return
113
+ }
114
+
115
+ if (typeof obj.$ref === "string") {
116
+ // OpenAPI refs look like "#/components/schemas/X1"
117
+ const prefix = "#/components/schemas/"
118
+ if (obj.$ref.startsWith(prefix)) {
119
+ const refKey = obj.$ref.slice(prefix.length)
120
+ const canonical = remapping.get(refKey)
121
+ if (canonical !== undefined) {
122
+ obj.$ref = prefix + canonical
123
+ }
124
+ }
125
+ }
126
+
127
+ for (const value of Object.values(obj)) {
128
+ rewriteRefs(value, remapping)
129
+ }
130
+ }
@@ -28,11 +28,26 @@ export interface Constructor<in out A extends B.Brand<any>> {
28
28
  is(a: Unbranded<A>): a is Unbranded<A> & A
29
29
  }
30
30
 
31
- export const fromBrand = <C extends B.Brand<string>>(
31
+ type BrandAnnotations<C extends B.Brand<any>> =
32
+ & S.Annotations.Filter
33
+ & (
34
+ C extends string ? { readonly toArbitrary?: S.Annotations.ToArbitrary.Declaration<C, readonly []> }
35
+ : {}
36
+ )
37
+
38
+ type BrandedSchema<Self extends S.Top, C extends B.Brand<any>> =
39
+ & Omit<S.brand<Self["Rebuild"], B.Brand.Keys<C>>, "Type" | "Iso" | "~type.make">
40
+ & {
41
+ readonly Type: C
42
+ readonly Iso: C
43
+ readonly "~type.make": C
44
+ }
45
+
46
+ export const fromBrand = <C extends B.Brand<any>>(
32
47
  constructor: Constructor<C>,
33
- options?: S.Annotations.Filter
48
+ options?: BrandAnnotations<C>
34
49
  ) =>
35
- <Self extends S.Top>(self: Self): S.brand<Self["~rebuild.out"], B.Brand.Keys<C>> => {
50
+ <Self extends S.Top>(self: Self): BrandedSchema<Self, C> => {
36
51
  const branded = S.fromBrand(options?.identifier ?? "Brand", constructor as any)(self as any)
37
52
  return options ? (branded as any).pipe(S.annotate(options)) : branded as any
38
53
  }
@@ -12,11 +12,19 @@ export type Email = string & EmailBrand
12
12
  export const Email = S
13
13
  .String
14
14
  .pipe(
15
+ S.annotate({
16
+ title: "Email",
17
+ description: "an email according to RFC 5322",
18
+ format: "email"
19
+ }),
20
+ S.check(S.isMinLength(3), /* a@b */ S.isMaxLength(998)),
15
21
  S.refine(isValidEmail as Refinement<string, Email>, {
16
22
  identifier: "Email",
17
23
  title: "Email",
18
24
  description: "an email according to RFC 5322",
19
- jsonSchema: { format: "email", minLength: 3, /* a@b */ maxLength: 998 },
20
- arbitrary: () => (fc: any) => fc.emailAddress().map((_: any) => _ as Email)
25
+ jsonSchema: { format: "email", minLength: 3, maxLength: 998 }
26
+ }),
27
+ S.annotate({
28
+ toArbitrary: () => (fc) => fc.emailAddress().map((_) => _ as Email)
21
29
  })
22
30
  )