schema.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { Option, Schema, SchemaGetter } from "effect"
  2. import { zod, ZodOverride } from "./effect-zod"
  3. /**
  4. * Integer greater than zero.
  5. */
  6. export const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0))
  7. /**
  8. * Integer greater than or equal to zero.
  9. */
  10. export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
  11. /**
  12. * Optional public JSON field that can hold explicit `undefined` on the type
  13. * side but encodes it as an omitted key, matching legacy `JSON.stringify`.
  14. */
  15. export const optionalOmitUndefined = <S extends Schema.Top>(schema: S) =>
  16. Schema.optionalKey(schema).pipe(
  17. Schema.decodeTo(Schema.optional(schema), {
  18. decode: SchemaGetter.passthrough({ strict: false }),
  19. encode: SchemaGetter.transformOptional(Option.filter((value) => value !== undefined)),
  20. }),
  21. Schema.annotate({ [ZodOverride]: zod(schema).optional() }),
  22. )
  23. /**
  24. * Strip `readonly` from a nested type. Stand-in for `effect`'s `Types.DeepMutable`
  25. * until `effect:core/x228my` ("Types.DeepMutable widens unknown to `{}`") lands.
  26. *
  27. * The upstream version falls through `unknown` into `{ -readonly [K in keyof T]: ... }`
  28. * where `keyof unknown = never`, so `unknown` collapses to `{}`. This local
  29. * version gates the object branch on `extends object` (which `unknown` does
  30. * not) so `unknown` passes through untouched.
  31. *
  32. * Primitive bailout matches upstream — without it, branded strings like
  33. * `string & Brand<"SessionID">` fall into the object branch and get their
  34. * prototype methods walked.
  35. *
  36. * Tuple branch preserves readonly tuples (e.g. `ConfigPlugin.Spec`'s
  37. * `readonly [string, Options]`); the general array branch would otherwise
  38. * widen them to unbounded arrays.
  39. */
  40. // eslint-disable-next-line @typescript-eslint/ban-types
  41. export type DeepMutable<T> = T extends string | number | boolean | bigint | symbol | Function
  42. ? T
  43. : T extends readonly [unknown, ...unknown[]]
  44. ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
  45. : T extends readonly (infer U)[]
  46. ? DeepMutable<U>[]
  47. : T extends object
  48. ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
  49. : T
  50. /**
  51. * Attach static methods to a schema object. Designed to be used with `.pipe()`:
  52. *
  53. * @example
  54. * export const Foo = fooSchema.pipe(
  55. * withStatics((schema) => ({
  56. * zero: schema.make(0),
  57. * from: Schema.decodeUnknownOption(schema),
  58. * }))
  59. * )
  60. */
  61. export const withStatics =
  62. <S extends object, M extends Record<string, unknown>>(methods: (schema: S) => M) =>
  63. (schema: S): S & M =>
  64. Object.assign(schema, methods(schema))
  65. /**
  66. * Nominal wrapper for scalar types. The class itself is a valid schema —
  67. * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc.
  68. *
  69. * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type`
  70. * of a field using this newtype resolves to `Self` rather than the underlying
  71. * branded phantom. Without that override, passing a class instance to code
  72. * typed against `Schema.Schema.Type<FieldSchema>` would require a cast even
  73. * though the values are structurally equivalent at runtime.
  74. *
  75. * @example
  76. * class QuestionID extends Newtype<QuestionID>()("QuestionID", Schema.String) {
  77. * static make(id: string): QuestionID {
  78. * return this.make(id)
  79. * }
  80. * }
  81. *
  82. * Schema.decodeEffect(QuestionID)(input)
  83. */
  84. export function Newtype<Self>() {
  85. return <const Tag extends string, S extends Schema.Top>(tag: Tag, schema: S) => {
  86. abstract class Base {
  87. declare readonly _newtype: Tag
  88. static make(value: Schema.Schema.Type<S>): Self {
  89. return value as unknown as Self
  90. }
  91. }
  92. Object.setPrototypeOf(Base, schema)
  93. return Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & {
  94. readonly make: (value: Schema.Schema.Type<S>) => Self
  95. } & Omit<Schema.Opaque<Self, S, {}>, "make" | "~type.make"> & {
  96. readonly "~type.make": Self
  97. }
  98. }
  99. }