@kikiutils/mongoose 9.0.4 → 10.0.0

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 (211) hide show
  1. package/README.md +13 -25
  2. package/dist/_internals.d.ts +10 -1
  3. package/dist/_internals.d.ts.map +1 -1
  4. package/dist/_internals.js +20 -1
  5. package/dist/_internals.js.map +1 -1
  6. package/dist/assertions.d.ts +5 -2
  7. package/dist/assertions.d.ts.map +1 -1
  8. package/dist/assertions.js +10 -4
  9. package/dist/assertions.js.map +1 -1
  10. package/dist/builders.d.ts +9 -4
  11. package/dist/builders.d.ts.map +1 -1
  12. package/dist/builders.js +10 -10
  13. package/dist/builders.js.map +1 -1
  14. package/dist/connection.d.ts +3 -0
  15. package/dist/connection.d.ts.map +1 -1
  16. package/dist/connection.js +8 -2
  17. package/dist/connection.js.map +1 -1
  18. package/dist/documents.d.ts +8 -0
  19. package/dist/documents.d.ts.map +1 -0
  20. package/dist/documents.js +10 -0
  21. package/dist/documents.js.map +1 -0
  22. package/dist/errors/duplicate-key.d.ts +9 -0
  23. package/dist/errors/duplicate-key.d.ts.map +1 -0
  24. package/dist/errors/duplicate-key.js +15 -0
  25. package/dist/errors/duplicate-key.js.map +1 -0
  26. package/dist/errors/mongoose-update-conflict-error.d.ts +4 -0
  27. package/dist/errors/mongoose-update-conflict-error.d.ts.map +1 -0
  28. package/dist/errors/mongoose-update-conflict-error.js +7 -0
  29. package/dist/errors/mongoose-update-conflict-error.js.map +1 -0
  30. package/dist/options.d.ts +15 -1
  31. package/dist/options.d.ts.map +1 -1
  32. package/dist/options.js +19 -2
  33. package/dist/options.js.map +1 -1
  34. package/dist/plugins/assertions.d.ts +30 -9
  35. package/dist/plugins/assertions.d.ts.map +1 -1
  36. package/dist/plugins/assertions.js +32 -4
  37. package/dist/plugins/assertions.js.map +1 -1
  38. package/dist/plugins/lean-decimal128-to-string.d.ts +3 -15
  39. package/dist/plugins/lean-decimal128-to-string.d.ts.map +1 -1
  40. package/dist/plugins/lean-decimal128-to-string.js +30 -23
  41. package/dist/plugins/lean-decimal128-to-string.js.map +1 -1
  42. package/dist/plugins/normalize.d.ts +3 -40
  43. package/dist/plugins/normalize.d.ts.map +1 -1
  44. package/dist/plugins/normalize.js +98 -44
  45. package/dist/plugins/normalize.js.map +1 -1
  46. package/dist/schema-builders/_internals/array.d.ts +9 -0
  47. package/dist/schema-builders/_internals/array.d.ts.map +1 -0
  48. package/dist/schema-builders/_internals/array.js +12 -0
  49. package/dist/schema-builders/_internals/array.js.map +1 -0
  50. package/dist/schema-builders/_internals/boolean.d.ts +8 -0
  51. package/dist/schema-builders/_internals/boolean.d.ts.map +1 -0
  52. package/dist/schema-builders/_internals/boolean.js +9 -0
  53. package/dist/schema-builders/_internals/boolean.js.map +1 -0
  54. package/dist/schema-builders/_internals/date.d.ts +8 -0
  55. package/dist/schema-builders/_internals/date.d.ts.map +1 -0
  56. package/dist/schema-builders/_internals/date.js +9 -0
  57. package/dist/schema-builders/_internals/date.js.map +1 -0
  58. package/dist/schema-builders/_internals/decimal128.d.ts +36 -0
  59. package/dist/schema-builders/_internals/decimal128.d.ts.map +1 -0
  60. package/dist/schema-builders/_internals/decimal128.js +38 -0
  61. package/dist/schema-builders/_internals/decimal128.js.map +1 -0
  62. package/dist/schema-builders/_internals/int32.d.ts +21 -0
  63. package/dist/schema-builders/_internals/int32.d.ts.map +1 -0
  64. package/dist/schema-builders/_internals/int32.js +29 -0
  65. package/dist/schema-builders/_internals/int32.js.map +1 -0
  66. package/dist/schema-builders/_internals/mixed.d.ts +9 -0
  67. package/dist/schema-builders/_internals/mixed.d.ts.map +1 -0
  68. package/dist/schema-builders/_internals/mixed.js +10 -0
  69. package/dist/schema-builders/_internals/mixed.js.map +1 -0
  70. package/dist/schema-builders/_internals/number.d.ts +21 -0
  71. package/dist/schema-builders/_internals/number.d.ts.map +1 -0
  72. package/dist/schema-builders/_internals/number.js +20 -0
  73. package/dist/schema-builders/_internals/number.js.map +1 -0
  74. package/dist/schema-builders/_internals/object-id.d.ts +9 -0
  75. package/dist/schema-builders/_internals/object-id.d.ts.map +1 -0
  76. package/dist/schema-builders/_internals/object-id.js +10 -0
  77. package/dist/schema-builders/_internals/object-id.js.map +1 -0
  78. package/dist/schema-builders/_internals/ref.d.ts +8 -0
  79. package/dist/schema-builders/_internals/ref.d.ts.map +1 -0
  80. package/dist/schema-builders/_internals/ref.js +13 -0
  81. package/dist/schema-builders/_internals/ref.js.map +1 -0
  82. package/dist/schema-builders/_internals/shared.d.ts +104 -0
  83. package/dist/schema-builders/_internals/shared.d.ts.map +1 -0
  84. package/dist/schema-builders/_internals/shared.js +128 -0
  85. package/dist/schema-builders/_internals/shared.js.map +1 -0
  86. package/dist/schema-builders/_internals/string.d.ts +37 -0
  87. package/dist/schema-builders/_internals/string.d.ts.map +1 -0
  88. package/dist/schema-builders/_internals/string.js +39 -0
  89. package/dist/schema-builders/_internals/string.js.map +1 -0
  90. package/dist/schema-builders/index.d.ts +12 -13
  91. package/dist/schema-builders/index.js +11 -13
  92. package/dist/transaction.d.ts +10 -0
  93. package/dist/transaction.d.ts.map +1 -0
  94. package/dist/transaction.js +9 -0
  95. package/dist/transaction.js.map +1 -0
  96. package/dist/types/data.d.ts +3 -5
  97. package/dist/types/data.d.ts.map +1 -1
  98. package/dist/types/index.d.ts +16 -12
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/paginate.d.ts +4 -19
  101. package/dist/types/paginate.d.ts.map +1 -1
  102. package/package.json +19 -21
  103. package/src/_internals.ts +31 -1
  104. package/src/assertions.ts +20 -11
  105. package/src/builders.ts +26 -18
  106. package/src/connection.ts +8 -2
  107. package/src/documents.ts +12 -0
  108. package/src/errors/duplicate-key.ts +14 -0
  109. package/src/errors/mongoose-update-conflict-error.ts +3 -0
  110. package/src/options.ts +31 -1
  111. package/src/plugins/assertions.ts +117 -49
  112. package/src/plugins/lean-decimal128-to-string.ts +47 -41
  113. package/src/plugins/normalize.ts +169 -99
  114. package/src/schema-builders/_internals/array.ts +15 -0
  115. package/src/schema-builders/_internals/boolean.ts +10 -0
  116. package/src/schema-builders/_internals/date.ts +11 -0
  117. package/src/schema-builders/_internals/decimal128.ts +79 -0
  118. package/src/schema-builders/_internals/int32.ts +58 -0
  119. package/src/schema-builders/_internals/mixed.ts +12 -0
  120. package/src/schema-builders/_internals/number.ts +71 -0
  121. package/src/schema-builders/_internals/object-id.ts +13 -0
  122. package/src/schema-builders/_internals/ref.ts +18 -0
  123. package/src/schema-builders/_internals/shared.ts +302 -0
  124. package/src/schema-builders/_internals/string.ts +113 -0
  125. package/src/schema-builders/index.ts +26 -35
  126. package/src/transaction.ts +22 -0
  127. package/src/types/data.ts +5 -10
  128. package/src/types/index.ts +32 -22
  129. package/src/types/paginate.ts +9 -24
  130. package/dist/schema-builders/_internals.d.ts +0 -18
  131. package/dist/schema-builders/_internals.d.ts.map +0 -1
  132. package/dist/schema-builders/_internals.js +0 -36
  133. package/dist/schema-builders/_internals.js.map +0 -1
  134. package/dist/schema-builders/base.d.ts +0 -5
  135. package/dist/schema-builders/base.d.ts.map +0 -1
  136. package/dist/schema-builders/base.js +0 -33
  137. package/dist/schema-builders/base.js.map +0 -1
  138. package/dist/schema-builders/bigint.d.ts +0 -39
  139. package/dist/schema-builders/bigint.d.ts.map +0 -1
  140. package/dist/schema-builders/bigint.js +0 -47
  141. package/dist/schema-builders/bigint.js.map +0 -1
  142. package/dist/schema-builders/boolean.d.ts +0 -33
  143. package/dist/schema-builders/boolean.d.ts.map +0 -1
  144. package/dist/schema-builders/boolean.js +0 -6
  145. package/dist/schema-builders/boolean.js.map +0 -1
  146. package/dist/schema-builders/date.d.ts +0 -49
  147. package/dist/schema-builders/date.d.ts.map +0 -1
  148. package/dist/schema-builders/date.js +0 -6
  149. package/dist/schema-builders/date.js.map +0 -1
  150. package/dist/schema-builders/decimal128.d.ts +0 -79
  151. package/dist/schema-builders/decimal128.d.ts.map +0 -1
  152. package/dist/schema-builders/decimal128.js +0 -47
  153. package/dist/schema-builders/decimal128.js.map +0 -1
  154. package/dist/schema-builders/double.d.ts +0 -39
  155. package/dist/schema-builders/double.d.ts.map +0 -1
  156. package/dist/schema-builders/double.js +0 -51
  157. package/dist/schema-builders/double.js.map +0 -1
  158. package/dist/schema-builders/int32.d.ts +0 -39
  159. package/dist/schema-builders/int32.d.ts.map +0 -1
  160. package/dist/schema-builders/int32.js +0 -47
  161. package/dist/schema-builders/int32.js.map +0 -1
  162. package/dist/schema-builders/mixed.d.ts +0 -33
  163. package/dist/schema-builders/mixed.d.ts.map +0 -1
  164. package/dist/schema-builders/mixed.js +0 -7
  165. package/dist/schema-builders/mixed.js.map +0 -1
  166. package/dist/schema-builders/number.d.ts +0 -49
  167. package/dist/schema-builders/number.d.ts.map +0 -1
  168. package/dist/schema-builders/number.js +0 -6
  169. package/dist/schema-builders/number.js.map +0 -1
  170. package/dist/schema-builders/object-id.d.ts +0 -43
  171. package/dist/schema-builders/object-id.d.ts.map +0 -1
  172. package/dist/schema-builders/object-id.js +0 -7
  173. package/dist/schema-builders/object-id.js.map +0 -1
  174. package/dist/schema-builders/ref.d.ts +0 -44
  175. package/dist/schema-builders/ref.d.ts.map +0 -1
  176. package/dist/schema-builders/ref.js +0 -10
  177. package/dist/schema-builders/ref.js.map +0 -1
  178. package/dist/schema-builders/string.d.ts +0 -138
  179. package/dist/schema-builders/string.d.ts.map +0 -1
  180. package/dist/schema-builders/string.js +0 -48
  181. package/dist/schema-builders/string.js.map +0 -1
  182. package/dist/schema-builders/uuid.d.ts +0 -33
  183. package/dist/schema-builders/uuid.d.ts.map +0 -1
  184. package/dist/schema-builders/uuid.js +0 -7
  185. package/dist/schema-builders/uuid.js.map +0 -1
  186. package/dist/types/_internals.d.ts +0 -24
  187. package/dist/types/_internals.d.ts.map +0 -1
  188. package/dist/types/_internals.js +0 -1
  189. package/dist/types/aggregate-paginate.d.ts +0 -82
  190. package/dist/types/aggregate-paginate.d.ts.map +0 -1
  191. package/dist/types/aggregate-paginate.js +0 -1
  192. package/dist/types/options.d.ts +0 -23
  193. package/dist/types/options.d.ts.map +0 -1
  194. package/dist/types/options.js +0 -1
  195. package/src/schema-builders/_internals.ts +0 -64
  196. package/src/schema-builders/base.ts +0 -57
  197. package/src/schema-builders/bigint.ts +0 -156
  198. package/src/schema-builders/boolean.ts +0 -45
  199. package/src/schema-builders/date.ts +0 -80
  200. package/src/schema-builders/decimal128.ts +0 -196
  201. package/src/schema-builders/double.ts +0 -166
  202. package/src/schema-builders/int32.ts +0 -157
  203. package/src/schema-builders/mixed.ts +0 -37
  204. package/src/schema-builders/number.ts +0 -80
  205. package/src/schema-builders/object-id.ts +0 -60
  206. package/src/schema-builders/ref.ts +0 -67
  207. package/src/schema-builders/string.ts +0 -258
  208. package/src/schema-builders/uuid.ts +0 -48
  209. package/src/types/_internals.ts +0 -27
  210. package/src/types/aggregate-paginate.ts +0 -115
  211. package/src/types/options.ts +0 -46
@@ -0,0 +1,15 @@
1
+ import { SchemaBuilder } from './shared';
2
+
3
+ export class ArraySchemaBuilder<Props, Used extends string = never> extends SchemaBuilder<
4
+ 'array',
5
+ Props,
6
+ Used,
7
+ unknown[]
8
+ > {}
9
+
10
+ /**
11
+ * Mongoose initializes array paths to `[]`, so no default is needed for an empty array.
12
+ */
13
+ export function array<const T>(item: T) {
14
+ return new ArraySchemaBuilder<{ type: T[] }>({ type: [item] });
15
+ }
@@ -0,0 +1,10 @@
1
+ import { SchemaBuilder } from './shared';
2
+
3
+ export class BooleanSchemaBuilder<
4
+ Props = { type: BooleanConstructor },
5
+ Used extends string = never,
6
+ > extends SchemaBuilder<'boolean', Props, Used, boolean> {}
7
+
8
+ export function boolean() {
9
+ return new BooleanSchemaBuilder({ type: Boolean });
10
+ }
@@ -0,0 +1,11 @@
1
+ import { SchemaBuilder } from './shared';
2
+
3
+ export class DateSchemaBuilder<
4
+ Props = { type: DateConstructor },
5
+ Used extends string = never,
6
+ // A number default such as `Date.now` is cast to a date by Mongoose.
7
+ > extends SchemaBuilder<'date', Props, Used, NativeDate | number, NativeDate> {}
8
+
9
+ export function date() {
10
+ return new DateSchemaBuilder({ type: Date });
11
+ }
@@ -0,0 +1,79 @@
1
+ import { Decimal } from 'decimal.js';
2
+ import { Schema } from 'mongoose';
3
+ import type { Types } from 'mongoose';
4
+
5
+ import { decimal128ToPlainString } from '../../_internals';
6
+
7
+ import type {
8
+ NextSchemaBuilder,
9
+ OptionGuard,
10
+ } from './shared';
11
+ import { SchemaBuilder } from './shared';
12
+
13
+ type This<Props, Used extends string, Option extends string> =
14
+ & Decimal128SchemaBuilder<Props, Used>
15
+ & OptionGuard<Used, Option>;
16
+
17
+ export class Decimal128SchemaBuilder<
18
+ Props = { type: typeof Schema.Types.Decimal128 },
19
+ Used extends string = never,
20
+ > extends SchemaBuilder<'decimal128', Props, Used, number | string | Types.Decimal128, Types.Decimal128> {
21
+ /**
22
+ * Reads the value as a plain-notation string and marks the path for the lean Decimal128 plugin, which converts
23
+ * lean results without invoking this getter.
24
+ *
25
+ * @remarks
26
+ * The definition's `type` is typed as `String` so inferred and declared document types use `string`, while the
27
+ * stored type stays Decimal128. Reads that skip both the getter and the plugins still return Decimal128, such as
28
+ * `get(path, null, { getters: false })`, `toObject()` without getters, and `toJSON()` without getters or the
29
+ * normalize transform.
30
+ */
31
+ setToStringGetter(this: This<Props, Used, 'setToStringGetter'>): Decimal128SchemaBuilder<
32
+ & Omit<Props, 'type'>
33
+ & {
34
+ get: (value?: null | Types.Decimal128) => string | undefined;
35
+ leanDecimal128ToString: true;
36
+ type: StringConstructor;
37
+ },
38
+ 'setToStringGetter' | Used
39
+ > {
40
+ return this.with(
41
+ 'setToStringGetter',
42
+ {
43
+ get: (value?: null | Types.Decimal128) => value === null || value === undefined
44
+ ? undefined
45
+ : decimal128ToPlainString(value),
46
+ leanDecimal128ToString: true,
47
+ },
48
+ );
49
+ }
50
+
51
+ /**
52
+ * Decimal.js validates `places` and `rounding` when a value is set, not here.
53
+ */
54
+ toFixedOnSet(
55
+ this: This<Props, Used, 'toFixedOnSet'>,
56
+ places = 2,
57
+ rounding: Decimal.Rounding = Decimal.ROUND_DOWN,
58
+ ): NextSchemaBuilder<
59
+ 'decimal128',
60
+ Props,
61
+ Used,
62
+ 'toFixedOnSet',
63
+ { set: (value?: null | { toString: () => string }) => string | undefined }
64
+ > {
65
+ return this.with(
66
+ 'toFixedOnSet',
67
+ {
68
+ set: (value?: null | { toString: () => string }) => {
69
+ if (value === null || value === undefined) return undefined;
70
+ return (Decimal.isDecimal(value) ? value : new Decimal(value.toString())).toFixed(places, rounding);
71
+ },
72
+ },
73
+ );
74
+ }
75
+ }
76
+
77
+ export function decimal128() {
78
+ return new Decimal128SchemaBuilder({ type: Schema.Types.Decimal128 });
79
+ }
@@ -0,0 +1,58 @@
1
+ import { Schema } from 'mongoose';
2
+
3
+ import type {
4
+ EnumInput,
5
+ NextSchemaBuilder,
6
+ OptionGuard,
7
+ Validator,
8
+ } from './shared';
9
+ import {
10
+ createEnumValidator,
11
+ createLimitValidator,
12
+ getEnumValues,
13
+ SchemaBuilder,
14
+ } from './shared';
15
+
16
+ type Next<Props, Used extends string, Option extends string> = NextSchemaBuilder<
17
+ 'int32',
18
+ Props,
19
+ Used,
20
+ Option,
21
+ { validate: Array<Validator<number>> }
22
+ >;
23
+
24
+ type This<Props, Used extends string, Option extends string> =
25
+ & Int32SchemaBuilder<Props, Used>
26
+ & OptionGuard<Used, Option>;
27
+
28
+ const compare = (value: number, limit: number) => value - limit;
29
+
30
+ /**
31
+ * Mongoose has no `enum`, `min` or `max` for Int32, so these are added as validators.
32
+ */
33
+ export class Int32SchemaBuilder<
34
+ Props = { type: typeof Schema.Types.Int32 },
35
+ Used extends string = never,
36
+ > extends SchemaBuilder<'int32', Props, Used, number> {
37
+ enum(this: This<Props, Used, 'enum'>, values: EnumInput<number>, message?: string): Next<Props, Used, 'enum'> {
38
+ return this.withValidator('enum', createEnumValidator(getEnumValues(values, 'number'), message));
39
+ }
40
+
41
+ max(this: This<Props, Used, 'max'>, value: number, message?: string): Next<Props, Used, 'max'> {
42
+ assertFiniteLimit('max', value);
43
+ return this.withValidator('max', createLimitValidator('max', value, compare, message));
44
+ }
45
+
46
+ min(this: This<Props, Used, 'min'>, value: number, message?: string): Next<Props, Used, 'min'> {
47
+ assertFiniteLimit('min', value);
48
+ return this.withValidator('min', createLimitValidator('min', value, compare, message));
49
+ }
50
+ }
51
+
52
+ function assertFiniteLimit(type: 'max' | 'min', limit: number) {
53
+ if (!Number.isFinite(limit)) throw new RangeError(`Int32 ${type} limit must be finite`);
54
+ }
55
+
56
+ export function int32() {
57
+ return new Int32SchemaBuilder({ type: Schema.Types.Int32 });
58
+ }
@@ -0,0 +1,12 @@
1
+ import { Schema } from 'mongoose';
2
+
3
+ import { SchemaBuilder } from './shared';
4
+
5
+ export class MixedSchemaBuilder<
6
+ Props = { type: typeof Schema.Types.Mixed },
7
+ Used extends string = never,
8
+ > extends SchemaBuilder<'mixed', Props, Used, unknown> {}
9
+
10
+ export function mixed() {
11
+ return new MixedSchemaBuilder({ type: Schema.Types.Mixed });
12
+ }
@@ -0,0 +1,71 @@
1
+ import type {
2
+ EnumInput,
3
+ EnumValue,
4
+ NextSchemaBuilder,
5
+ OptionGuard,
6
+ } from './shared';
7
+ import {
8
+ getEnumValues,
9
+ SchemaBuilder,
10
+ withMessage,
11
+ } from './shared';
12
+
13
+ type Next<Props, Used extends string, Option extends string, Added> = NextSchemaBuilder<
14
+ 'number',
15
+ Props,
16
+ Used,
17
+ Option,
18
+ Added
19
+ >;
20
+
21
+ type This<Props, Used extends string, Option extends string> =
22
+ & NumberSchemaBuilder<Props, Used>
23
+ & OptionGuard<Used, Option>;
24
+
25
+ export class NumberSchemaBuilder<
26
+ Props = { type: NumberConstructor },
27
+ Used extends string = never,
28
+ > extends SchemaBuilder<'number', Props, Used, number> {
29
+ enum<const T extends EnumInput<number>, Message extends string | undefined = undefined>(
30
+ this: This<Props, Used, 'enum'>,
31
+ values: T,
32
+ message?: Message,
33
+ ): Next<
34
+ Props,
35
+ Used,
36
+ 'enum',
37
+ {
38
+ enum: Message extends string
39
+ ? {
40
+ message: Message;
41
+ values: Array<EnumValue<T, number>>;
42
+ }
43
+ : Array<EnumValue<T, number>>;
44
+ }
45
+ > {
46
+ const enumValues = getEnumValues(values, 'number');
47
+ return this.with(
48
+ 'enum',
49
+ {
50
+ enum: message === undefined
51
+ ? enumValues
52
+ : {
53
+ message,
54
+ values: enumValues,
55
+ },
56
+ },
57
+ );
58
+ }
59
+
60
+ min<T extends number, Message extends string | undefined = undefined>(
61
+ this: This<Props, Used, 'min'>,
62
+ value: T,
63
+ message?: Message,
64
+ ): Next<Props, Used, 'min', { min: Message extends string ? [T, Message] : T }> {
65
+ return this.with('min', { min: withMessage(value, message) });
66
+ }
67
+ }
68
+
69
+ export function number() {
70
+ return new NumberSchemaBuilder({ type: Number });
71
+ }
@@ -0,0 +1,13 @@
1
+ import { Schema } from 'mongoose';
2
+ import type { Types } from 'mongoose';
3
+
4
+ import { SchemaBuilder } from './shared';
5
+
6
+ export class ObjectIdSchemaBuilder<
7
+ Props = { type: typeof Schema.Types.ObjectId },
8
+ Used extends string = never,
9
+ > extends SchemaBuilder<'objectId', Props, Used, Types.ObjectId> {}
10
+
11
+ export function objectId() {
12
+ return new ObjectIdSchemaBuilder({ type: Schema.Types.ObjectId });
13
+ }
@@ -0,0 +1,18 @@
1
+ import { Schema } from 'mongoose';
2
+ import type { Types } from 'mongoose';
3
+
4
+ import { SchemaBuilder } from './shared';
5
+
6
+ export class RefSchemaBuilder<Props, Used extends string = never> extends SchemaBuilder<
7
+ 'ref',
8
+ Props,
9
+ Used,
10
+ Types.ObjectId
11
+ > {}
12
+
13
+ export function ref<const T extends string>(modelName: T) {
14
+ return new RefSchemaBuilder<{ ref: T; type: typeof Schema.Types.ObjectId }>({
15
+ ref: modelName,
16
+ type: Schema.Types.ObjectId,
17
+ });
18
+ }
@@ -0,0 +1,302 @@
1
+ import type {
2
+ IndexDirection,
3
+ IndexOptions,
4
+ } from 'mongoose';
5
+ import {
6
+ objectEntries,
7
+ objectKeys,
8
+ } from 'ts-extras';
9
+ import type {
10
+ Simplify,
11
+ UnknownRecord,
12
+ ValueOf,
13
+ } from 'type-fest';
14
+
15
+ import type { ArraySchemaBuilder } from './array';
16
+ import type { BooleanSchemaBuilder } from './boolean';
17
+ import type { DateSchemaBuilder } from './date';
18
+ import type { Decimal128SchemaBuilder } from './decimal128';
19
+ import type { Int32SchemaBuilder } from './int32';
20
+ import type { MixedSchemaBuilder } from './mixed';
21
+ import type { NumberSchemaBuilder } from './number';
22
+ import type { ObjectIdSchemaBuilder } from './object-id';
23
+ import type { RefSchemaBuilder } from './ref';
24
+ import type { StringSchemaBuilder } from './string';
25
+
26
+ /**
27
+ * A TypeScript enum object contributes only its values of the builder's type. `null` is not an enum value because
28
+ * the native String and Number enums and the emulated ones all accept it.
29
+ */
30
+ export type EnumInput<Value> = EnumObject | readonly Value[];
31
+ export type EnumObject = Readonly<Record<string, number | string>>;
32
+ export type EnumValue<T, Value> = T extends readonly unknown[] ? T[number] : Extract<ValueOf<T>, Value>;
33
+
34
+ /**
35
+ * Using an option also marks the listed ones as used, at runtime and in the types.
36
+ */
37
+ const conflictingOptions = {
38
+ // A `unique` index takes its direction from `index` only in some option orders.
39
+ index: ['unique'],
40
+ length: [
41
+ 'maxlength',
42
+ 'minlength',
43
+ ],
44
+ maxlength: ['length'],
45
+ minlength: ['length'],
46
+ unique: ['index'],
47
+ } as const satisfies Readonly<Record<string, readonly string[]>>;
48
+
49
+ type ConflictingOptions = typeof conflictingOptions;
50
+
51
+ export type NextSchemaBuilder<
52
+ Kind extends SchemaBuilderKind,
53
+ Props,
54
+ Used extends string,
55
+ Option extends string,
56
+ Added,
57
+ > = SchemaBuilderMap<Added & Props, UseOption<Used, Option>>[Kind];
58
+
59
+ export type OptionGuard<Used extends string, Option extends string> = Option extends Used
60
+ ? { [_ in `Error: '${Option}' is already set or conflicts with another option`]: never }
61
+ : unknown;
62
+
63
+ export type SchemaBuilderKind = keyof SchemaBuilderMap<any, any>;
64
+
65
+ export type UseOption<Used extends string, Option extends string> =
66
+ | Option
67
+ | (Option extends keyof ConflictingOptions ? ConflictingOptions[Option][number] : never)
68
+ | Used;
69
+
70
+ export interface SchemaBuilderMap<Props, Used extends string> {
71
+ array: ArraySchemaBuilder<Props, Used>;
72
+ boolean: BooleanSchemaBuilder<Props, Used>;
73
+ date: DateSchemaBuilder<Props, Used>;
74
+ decimal128: Decimal128SchemaBuilder<Props, Used>;
75
+ int32: Int32SchemaBuilder<Props, Used>;
76
+ mixed: MixedSchemaBuilder<Props, Used>;
77
+ number: NumberSchemaBuilder<Props, Used>;
78
+ objectId: ObjectIdSchemaBuilder<Props, Used>;
79
+ ref: RefSchemaBuilder<Props, Used>;
80
+ string: StringSchemaBuilder<Props, Used>;
81
+ }
82
+
83
+ export interface Validator<Value> {
84
+ message?: string;
85
+ type: string;
86
+ validator: (value: null | undefined | Value) => boolean | Promise<boolean>;
87
+ }
88
+
89
+ export const defaultEnumMessage = 'Path `{PATH}` (`{VALUE}`) is not a valid enum value.';
90
+ export const defaultLimitMessages = {
91
+ max: 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).',
92
+ min: 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).',
93
+ };
94
+
95
+ /**
96
+ * Every call returns a new builder, so a partially configured builder can be reused. `Value` is what `default`
97
+ * accepts; `CastValue` is what Mongoose stores and passes to validators.
98
+ */
99
+ export abstract class SchemaBuilder<
100
+ Kind extends SchemaBuilderKind,
101
+ Props,
102
+ Used extends string,
103
+ Value,
104
+ CastValue = Value,
105
+ > {
106
+ // Keeps the type parameters structurally significant so the `this` guards can tell builders apart.
107
+ declare private readonly '~types': {
108
+ castValue: CastValue;
109
+ kind: Kind;
110
+ props: Props;
111
+ used: Used;
112
+ value: Value;
113
+ };
114
+
115
+ readonly #definition: Readonly<UnknownRecord>;
116
+ readonly #used: ReadonlySet<string>;
117
+
118
+ constructor(definition: UnknownRecord, used: ReadonlySet<string> = new Set()) {
119
+ this.#definition = definition;
120
+ this.#used = used;
121
+ }
122
+
123
+ default<T extends ((this: any, doc: any) => null | undefined | Value) | null | Value>(
124
+ this: OptionGuard<Used, 'default'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
125
+ value: T,
126
+ ): NextSchemaBuilder<Kind, Props, Used, 'default', { default: T }> {
127
+ return this.with('default', { default: value });
128
+ }
129
+
130
+ immutable(
131
+ this: OptionGuard<Used, 'immutable'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
132
+ ): NextSchemaBuilder<Kind, Props, Used, 'immutable', { immutable: true }> {
133
+ return this.with('immutable', { immutable: true });
134
+ }
135
+
136
+ index<T extends boolean | IndexDirection | IndexOptions = true>(
137
+ this: OptionGuard<Used, 'index'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
138
+ value?: T,
139
+ ): NextSchemaBuilder<Kind, Props, Used, 'index', { index: T }> {
140
+ return this.with('index', { index: value ?? true });
141
+ }
142
+
143
+ optional(): Simplify<Props> {
144
+ return this.#build() as Simplify<Props>;
145
+ }
146
+
147
+ /**
148
+ * Marks the path for removal from `toJSON` output by the normalize plugin.
149
+ */
150
+ private(
151
+ this: OptionGuard<Used, 'private'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
152
+ ): NextSchemaBuilder<Kind, Props, Used, 'private', { private: true }> {
153
+ return this.with('private', { private: true });
154
+ }
155
+
156
+ required(): Simplify<Props & { required: true }> {
157
+ return {
158
+ ...this.#build(),
159
+ required: true,
160
+ } as Simplify<Props & { required: true }>;
161
+ }
162
+
163
+ unique(
164
+ this: OptionGuard<Used, 'unique'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
165
+ ): NextSchemaBuilder<Kind, Props, Used, 'unique', { unique: true }> {
166
+ return this.with('unique', { unique: true });
167
+ }
168
+
169
+ /**
170
+ * Adds a custom validator alongside any the builder already adds. Mongoose skips validators for `undefined`
171
+ * values, but passes `null`.
172
+ */
173
+ validate(
174
+ this: OptionGuard<Used, 'validate'> & SchemaBuilder<Kind, Props, Used, Value, CastValue>,
175
+ validator: (value: CastValue | null) => boolean | Promise<boolean>,
176
+ message?: string,
177
+ ): NextSchemaBuilder<Kind, Props, Used, 'validate', { validate: Array<Validator<unknown>> }> {
178
+ return this.withValidator(
179
+ 'validate',
180
+ {
181
+ ...message === undefined ? {} : { message },
182
+ type: 'user defined',
183
+ validator,
184
+ },
185
+ );
186
+ }
187
+
188
+ protected with(option: string, patch: UnknownRecord): any {
189
+ if (this.#used.has(option)) {
190
+ throw new Error(`Schema option '${option}' is already set or conflicts with another option`);
191
+ }
192
+
193
+ const used = new Set(this.#used).add(option);
194
+ (conflictingOptions as Readonly<Record<string, readonly string[] | undefined>>)[option]
195
+ ?.forEach((conflictingOption) => used.add(conflictingOption));
196
+
197
+ return Reflect.construct(
198
+ this.constructor,
199
+ [
200
+ {
201
+ ...this.#definition,
202
+ ...patch,
203
+ },
204
+ used,
205
+ ],
206
+ );
207
+ }
208
+
209
+ protected withValidator(option: string, validator: Validator<any>): any {
210
+ const validate = this.#definition.validate as Array<Validator<unknown>> | undefined;
211
+ return this.with(
212
+ option,
213
+ {
214
+ validate: [
215
+ ...validate ?? [],
216
+ validator,
217
+ ],
218
+ },
219
+ );
220
+ }
221
+
222
+ #build(): UnknownRecord {
223
+ // Builders are reused, so a definition must not share arrays or plain objects that callers or Mongoose
224
+ // may modify, such as enum values, validators and index options.
225
+ return copyContainers(this.#definition) as UnknownRecord;
226
+ }
227
+ }
228
+
229
+ function copyContainers(value: unknown): unknown {
230
+ if (Array.isArray(value)) return value.map(copyContainers);
231
+ if (value === null || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) return value;
232
+ return Object.fromEntries(objectEntries(value).map(([key, item]) => [
233
+ key,
234
+ copyContainers(item),
235
+ ]));
236
+ }
237
+
238
+ export function createEnumValidator<Value>(
239
+ values: readonly Value[],
240
+ message = defaultEnumMessage,
241
+ ): Validator<Value> & { enumValues: Value[] } {
242
+ const allowedValues = new Set(values);
243
+ return {
244
+ enumValues: [...values],
245
+ message,
246
+ type: 'enum',
247
+ validator: (value) => value === null || value === undefined || allowedValues.has(value),
248
+ };
249
+ }
250
+
251
+ export function createLimitValidator<Value>(
252
+ type: 'max' | 'min',
253
+ limit: Value,
254
+ compare: (value: Value, limit: Value) => number,
255
+ message = defaultLimitMessages[type],
256
+ ): Partial<Record<'max' | 'min', Value>> & Validator<Value> {
257
+ return {
258
+ message,
259
+ [type]: limit,
260
+ type,
261
+ validator: (value) => {
262
+ if (value === null || value === undefined) return true;
263
+ const result = compare(value, limit);
264
+ return type === 'min' ? result >= 0 : result <= 0;
265
+ },
266
+ };
267
+ }
268
+
269
+ export function getEnumValues<Value extends number | string>(
270
+ input: EnumInput<Value>,
271
+ valueType: 'number' | 'string',
272
+ ): Value[] {
273
+ let values: Value[];
274
+ if (Array.isArray(input)) values = [...input as readonly Value[]];
275
+ else {
276
+ const enumObject = input as EnumObject;
277
+ // Numeric TypeScript enums also map each value back to its name; only such entries are skipped.
278
+ values = objectKeys(enumObject)
279
+ .filter((key) => {
280
+ const value = enumObject[key];
281
+ return typeof value !== 'string' || enumObject[value] !== Number(key);
282
+ })
283
+ .map((key) => enumObject[key])
284
+ .filter((value): value is Value => valueType === 'number' ? typeof value === 'number' : typeof value === 'string');
285
+ }
286
+
287
+ // Mongoose treats an empty enum as "no enum" and drops the validator.
288
+ if (!values.length) throw new RangeError(`An enum needs at least one ${valueType} value`);
289
+ return values;
290
+ }
291
+
292
+ export function withMessage<T, Message extends string | undefined>(
293
+ value: T,
294
+ message: Message,
295
+ ): Message extends string ? [T, Message] : T {
296
+ return (message === undefined
297
+ ? value
298
+ : [
299
+ value,
300
+ message,
301
+ ]) as Message extends string ? [T, Message] : T;
302
+ }