import { pipe } from "@effect-ts/system/Function" import * as S from "../_schema.js" import * as Constructor from "../Constructor.js" import type { DefaultSchema } from "./withDefaults.js" import { withDefaults } from "./withDefaults.js" export type OptionalKey = & Omit< ConstructorInput, Key > & Partial> export const withDefaultConstructorFieldIdentifier = S.makeAnnotation<{ key: PropertyKey value: LazyArg self: S.SchemaAny }>() export function withDefaultConstructorField< ConstructorInput, Key extends keyof ConstructorInput >( key: Key, value: LazyArg ): ( self: S.Schema ) => DefaultSchema< ParserInput, ParsedShape, OptionalKey, Encoded, Api > { return self => { const constructSelf = Constructor.for(self) return pipe( self, S.constructor((u: any) => constructSelf(typeof u[key] !== "undefined" ? u : { ...u, [key]: value() })), withDefaults, S.annotate(withDefaultConstructorFieldIdentifier, { self, key, value }) ) } }