@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
package/README.md CHANGED
@@ -1,45 +1,30 @@
1
- <!-- TODO: Update -->
2
-
3
1
  # @kikiutils/mongoose
4
2
 
5
3
  [![npm version][npm-version-src]][npm-version-href]
6
4
  [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![Node.js][node-src]][node-href]
7
6
  [![codecov][codecov-src]][codecov-href]
8
7
  [![License][license-src]][license-href]
9
8
 
10
- Provides Mongoose schema builders and utilities for connections, pagination, JSON normalization, and update checks.
9
+ Typed Mongoose schema builders and a `buildMongooseModel` that applies pagination, JSON normalization, lean Decimal128-to-string conversion and update assertions, plus connection, transaction and duplicate-key helpers. ESM only.
11
10
 
12
11
  - [✨ Release Notes](./CHANGELOG.md)
13
12
 
14
- ## Features
15
-
16
- - ✨ Supports custom connections and reuses an automatically created default connection with configurable creation options.
17
- - 🔌 Registers `mongoose-aggregate-paginate-v2`, `mongoose-paginate-v2`, and update-result assertion plugins, with optional recursive JSON normalization.
18
- - 🛠 Provides chainable schema builders for `bigint`, `boolean`, `date`, `decimal128`, `double`, `int32`, `mixed`, `number`, `objectId`, `ref`, `string`, and `uuid`, with field options tailored to each schema type.
19
- - 🧮 Provides `Decimal128` rounding, fixed-decimal formatting, string getters, and inclusive range validation.
20
- - 🔄 Normalizes JSON output by default: adds `id`, removes `_id`, `__v`, and private fields, and serializes `Decimal128` values as strings.
21
- - 🔗 Defines ObjectId reference fields using model names, model constructors, or callbacks.
22
- - 🔧 Checks update acknowledgment and a minimum modified-document count through function, model, and document APIs.
23
-
24
- ## Requirements
25
-
26
- - **Mongoose** `>=9`
27
- - **Node.js** `>=22.12.0`
28
-
29
13
  ## Installation
30
14
 
31
- Using [pnpm](https://pnpm.io):
32
-
33
15
  ```bash
34
- pnpm add @kikiutils/mongoose mongoose
16
+ pnpm add @kikiutils/mongoose
35
17
  ```
36
18
 
37
- You can also use `yarn`, `npm`, or `bun`.
19
+ ## Configuration
20
+
21
+ Models built without an explicit `connection` share a default connection, created on first use from the `MONGODB_URI` environment variable. Its options must be set before that:
38
22
 
39
- ## Usage
23
+ ```typescript
24
+ import { setCustomMongooseOptions } from '@kikiutils/mongoose/options';
40
25
 
41
- <!-- TODO: Full doc. -->
42
- To be completed.
26
+ setCustomMongooseOptions('defaultConnectionOptions', { maxPoolSize: 10 });
27
+ ```
43
28
 
44
29
  ## License
45
30
 
@@ -52,6 +37,9 @@ To be completed.
52
37
  [npm-downloads-href]: https://npmjs.com/package/@kikiutils/mongoose
53
38
  [npm-downloads-src]: https://img.shields.io/npm/dm/@kikiutils/mongoose.svg?colorA=18181b&colorB=28cf8d&style=flat
54
39
 
40
+ [node-href]: ./package.json
41
+ [node-src]: https://img.shields.io/node/v/@kikiutils/mongoose?colorA=18181b&colorB=28cf8d&style=flat
42
+
55
43
  [codecov-href]: https://codecov.io/gh/kikiutils/node-mongoose
56
44
  [codecov-src]: https://codecov.io/gh/kikiutils/node-mongoose/graph/badge.svg?token=DM89MM6FPK
57
45
 
@@ -1,7 +1,16 @@
1
- import { CustomMongooseOptions } from "./types/options.js";
2
1
  import { Connection } from "mongoose";
2
+ import { BeforeMongooseModelBuildHook, CustomMongooseOptions } from "./options.js";
3
+ export declare const beforeModelBuildHooks: BeforeMongooseModelBuildHook[];
3
4
  export declare const customMongooseOptions: CustomMongooseOptions;
4
5
  export declare const mongooseConnectionState: {
5
6
  defaultConnection?: Connection;
6
7
  };
8
+ /**
9
+ * `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the
10
+ * BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal
11
+ * places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.
12
+ */
13
+ export declare function decimal128ToPlainString(value: {
14
+ toString: () => string;
15
+ }): string;
7
16
  //# sourceMappingURL=_internals.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"_internals.d.ts","names":[],"sources":["../src/_internals.ts"],"mappings":";;qBAIa,uBAAuB;qBACvB;EAA2B,oBAAoB"}
1
+ {"version":3,"file":"_internals.d.ts","names":[],"sources":["../src/_internals.ts"],"mappings":";;qBAOa,uBAAuB;qBACvB,uBAAuB;qBACvB;EAA2B,oBAAoB;;;;;;;wBAS5C,wBAAwB;EAAS"}
@@ -1,6 +1,25 @@
1
1
  // src/_internals.ts
2
+ const beforeModelBuildHooks = [];
2
3
  const customMongooseOptions = {};
3
4
  const mongooseConnectionState = {};
4
- export { customMongooseOptions, mongooseConnectionState };
5
+ const exponentNotationPattern = /^([-+]?)(\d+)(?:\.(\d+))?e([-+]\d+)$/i;
6
+ /**
7
+ * `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the
8
+ * BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal
9
+ * places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.
10
+ */
11
+ function decimal128ToPlainString(value) {
12
+ const text = value.toString();
13
+ const match = exponentNotationPattern.exec(text);
14
+ if (!match) return text;
15
+ const [, sign = "", integerDigits = "", fractionDigits = "", exponent = "0"] = match;
16
+ const digits = integerDigits + fractionDigits;
17
+ const pointIndex = integerDigits.length + Number(exponent);
18
+ if (pointIndex <= 0) return `${sign}0.${"0".repeat(-pointIndex)}${digits}`;
19
+ const integerPart = digits.padEnd(pointIndex, "0").slice(0, pointIndex).replace(/^0+(?=\d)/, "");
20
+ const fractionPart = digits.slice(pointIndex);
21
+ return `${sign}${integerPart}${fractionPart ? `.${fractionPart}` : ""}`;
22
+ }
23
+ export { beforeModelBuildHooks, customMongooseOptions, decimal128ToPlainString, mongooseConnectionState };
5
24
 
6
25
  //# sourceMappingURL=_internals.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { Connection } from 'mongoose';\n\nimport type { CustomMongooseOptions } from './types/options';\n\nexport const customMongooseOptions: CustomMongooseOptions = {};\nexport const mongooseConnectionState: { defaultConnection?: Connection } = {};\n"],"mappings":";AAIA,MAAa,wBAA+C,CAAC;AAC7D,MAAa,0BAA8D,CAAC"}
1
+ {"version":3,"file":"_internals.js","names":[],"sources":["../src/_internals.ts"],"sourcesContent":["import type { Connection } from 'mongoose';\n\nimport type {\n BeforeMongooseModelBuildHook,\n CustomMongooseOptions,\n} from './options';\n\nexport const beforeModelBuildHooks: BeforeMongooseModelBuildHook[] = [];\nexport const customMongooseOptions: CustomMongooseOptions = {};\nexport const mongooseConnectionState: { defaultConnection?: Connection } = {};\n\nconst exponentNotationPattern = /^([-+]?)(\\d+)(?:\\.(\\d+))?e([-+]\\d+)$/i;\n\n/**\n * `Decimal128#toString()` switches to exponent notation (`1E-8`, `0E-8`) when the adjusted exponent is below -6, as the\n * BSON Decimal128 spec requires. This moves the decimal point instead, keeping the sign and the number of decimal\n * places, and returns every other value unchanged so trailing zeros such as `12.30` are kept.\n */\nexport function decimal128ToPlainString(value: { toString: () => string }) {\n const text = value.toString();\n const match = exponentNotationPattern.exec(text);\n if (!match) return text;\n const [\n , sign = '',\n integerDigits = '',\n fractionDigits = '',\n exponent = '0',\n ] = match;\n\n const digits = integerDigits + fractionDigits;\n const pointIndex = integerDigits.length + Number(exponent);\n if (pointIndex <= 0) return `${sign}0.${'0'.repeat(-pointIndex)}${digits}`;\n const integerPart = digits.padEnd(pointIndex, '0').slice(0, pointIndex).replace(/^0+(?=\\d)/, '');\n const fractionPart = digits.slice(pointIndex);\n return `${sign}${integerPart}${fractionPart ? `.${fractionPart}` : ''}`;\n}\n"],"mappings":";AAOA,MAAa,wBAAwD,CAAC;AACtE,MAAa,wBAA+C,CAAC;AAC7D,MAAa,0BAA8D,CAAC;AAE5E,MAAM,0BAA0B;;;;;;AAOhC,SAAgB,wBAAwB,OAAmC;CACvE,MAAM,OAAO,MAAM,SAAS;CAC5B,MAAM,QAAQ,wBAAwB,KAAK,IAAI;CAC/C,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,GACA,OAAO,IACT,gBAAgB,IAChB,iBAAiB,IACjB,WAAW,OACX;CAEJ,MAAM,SAAS,gBAAgB;CAC/B,MAAM,aAAa,cAAc,SAAS,OAAO,QAAQ;CACzD,IAAI,cAAc,GAAG,OAAO,GAAG,KAAK,IAAI,IAAI,OAAO,CAAC,UAAU,IAAI;CAClE,MAAM,cAAc,OAAO,OAAO,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,QAAQ,aAAa,EAAE;CAC/F,MAAM,eAAe,OAAO,MAAM,UAAU;CAC5C,OAAO,GAAG,OAAO,cAAc,eAAe,IAAI,iBAAiB;AACvE"}
@@ -1,3 +1,6 @@
1
- import { Document, mongo } from "mongoose";
2
- export declare function assertMongooseUpdateSuccess<T extends Document>(updatePromise: Promise<mongo.UpdateResult<T>>, expectedModifiedCount?: number): Promise<void>;
1
+ import { mongo } from "mongoose";
2
+ /**
3
+ * Matched documents whose values were already equal to the update do not count as modified.
4
+ */
5
+ export declare function assertMongooseUpdateSuccess(update: PromiseLike<mongo.UpdateResult<any>>, minModifiedCount?: number): Promise<void>;
3
6
  //# sourceMappingURL=assertions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.d.ts","names":[],"sources":["../src/assertions.ts"],"mappings":";wBAKsB,4BAA4B,UAAU,UACxD,eAAe,QAAQ,MAAM,aAAa,KAC1C,iCAAyB"}
1
+ {"version":3,"file":"assertions.d.ts","names":[],"sources":["../src/assertions.ts"],"mappings":";;;;wBAKsB,4BAClB,QAAQ,YAAY,MAAM,oBAC1B,4BAAoB"}
@@ -1,8 +1,14 @@
1
1
  // src/assertions.ts
2
- async function assertMongooseUpdateSuccess(updatePromise, expectedModifiedCount = 1) {
3
- const updateResult = await updatePromise;
4
- if (!updateResult.acknowledged) throw new Error("Update was not acknowledged");
5
- if (updateResult.modifiedCount < expectedModifiedCount) throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);
2
+ /**
3
+ * Matched documents whose values were already equal to the update do not count as modified.
4
+ */
5
+ async function assertMongooseUpdateSuccess(update, minModifiedCount = 1) {
6
+ if (typeof minModifiedCount !== "number") throw new TypeError("minModifiedCount must be a number");
7
+ if (!Number.isSafeInteger(minModifiedCount) || minModifiedCount < 1) throw new RangeError("minModifiedCount must be a positive safe integer");
8
+ const updateResult = await update;
9
+ if (!updateResult.acknowledged) throw new Error("Update was not acknowledged (Mongoose also reports this when the cast update is empty)");
10
+ const modifiedCount = updateResult.modifiedCount + updateResult.upsertedCount;
11
+ if (modifiedCount < minModifiedCount) throw new Error(`Expected to modify at least ${minModifiedCount} document(s), but modified ${modifiedCount}`);
6
12
  }
7
13
  export { assertMongooseUpdateSuccess };
8
14
 
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type {\n Document,\n mongo,\n} from 'mongoose';\n\nexport async function assertMongooseUpdateSuccess<T extends Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}`);\n }\n}\n"],"mappings":";AAKA,eAAsB,4BAClB,eACA,wBAAwB,GAC1B;CACE,MAAM,eAAe,MAAM;CAC3B,IAAI,CAAC,aAAa,cAAc,MAAM,IAAI,MAAM,6BAA6B;CAC7E,IAAI,aAAa,gBAAgB,uBAC7B,MAAM,IAAI,MAAM,+BAA+B,sBAAsB,6BAA6B,aAAa,eAAe;AAEtI"}
1
+ {"version":3,"file":"assertions.js","names":[],"sources":["../src/assertions.ts"],"sourcesContent":["import type { mongo } from 'mongoose';\n\n/**\n * Matched documents whose values were already equal to the update do not count as modified.\n */\nexport async function assertMongooseUpdateSuccess(\n update: PromiseLike<mongo.UpdateResult<any>>,\n minModifiedCount = 1,\n) {\n if (typeof minModifiedCount !== 'number') throw new TypeError('minModifiedCount must be a number');\n if (!Number.isSafeInteger(minModifiedCount) || minModifiedCount < 1) {\n throw new RangeError('minModifiedCount must be a positive safe integer');\n }\n\n const updateResult = await update;\n if (!updateResult.acknowledged) {\n throw new Error('Update was not acknowledged (Mongoose also reports this when the cast update is empty)');\n }\n\n const modifiedCount = updateResult.modifiedCount + updateResult.upsertedCount;\n if (modifiedCount < minModifiedCount) {\n throw new Error(`Expected to modify at least ${minModifiedCount} document(s), but modified ${modifiedCount}`);\n }\n}\n"],"mappings":";;;;AAKA,eAAsB,4BAClB,QACA,mBAAmB,GACrB;CACE,IAAI,OAAO,qBAAqB,UAAU,MAAM,IAAI,UAAU,mCAAmC;CACjG,IAAI,CAAC,OAAO,cAAc,gBAAgB,KAAK,mBAAmB,GAC9D,MAAM,IAAI,WAAW,kDAAkD;CAG3E,MAAM,eAAe,MAAM;CAC3B,IAAI,CAAC,aAAa,cACd,MAAM,IAAI,MAAM,wFAAwF;CAG5G,MAAM,gBAAgB,aAAa,gBAAgB,aAAa;CAChE,IAAI,gBAAgB,kBAChB,MAAM,IAAI,MAAM,+BAA+B,iBAAiB,6BAA6B,eAAe;AAEpH"}
@@ -1,7 +1,12 @@
1
- import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
1
+ import { Connection, Schema } from "mongoose";
2
+ import { MongooseLeanDecimal128ToStringPluginOptions } from "./plugins/lean-decimal128-to-string.js";
2
3
  import { BaseMongoosePaginateModel } from "./types/index.js";
3
- import { BuildMongooseModelOptions } from "./types/options.js";
4
- import { Schema } from "mongoose";
5
- export type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;
4
+ export interface BuildMongooseModelOptions {
5
+ connection?: Connection;
6
+ plugins?: {
7
+ leanDecimal128ToString?: boolean | MongooseLeanDecimal128ToStringPluginOptions;
8
+ normalize?: boolean;
9
+ };
10
+ }
6
11
  export declare function buildMongooseModel<DocType, Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>, InstanceMethodsAndOverrides = object, QueryHelpers = object>(collection: string, name: string, schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>, options?: BuildMongooseModelOptions): Model;
7
12
  //# sourceMappingURL=builders.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":";;;;YAYY,kCAAkC;wBAE9B,mBACZ,SACA,cAAc,0BAA0B,SAAS,6BAA6B,eAC9E,sCACA,uBAEA,oBACA,cACA,QAAQ,OAAO,SAAS,OAAO,6BAA6B,eAC5D,UAAU,4BACX"}
1
+ {"version":3,"file":"builders.d.ts","names":[],"sources":["../src/builders.ts"],"mappings":";;;iBAgBiB;EACb,aAAa;EACb;IACI,mCAAmC;IACnC;;;wBAIQ,mBACZ,SACA,cAAc,0BAA0B,SAAS,6BAA6B,eAC9E,sCACA,uBAEA,oBACA,cACA,QAAQ,OAAO,SAAS,OAAO,6BAA6B,eAC5D,UAAU,4BACX"}
package/dist/builders.js CHANGED
@@ -1,22 +1,22 @@
1
- import { customMongooseOptions } from "./_internals.js";
1
+ import mongoosePaginate from "mongoose-paginate-v2";
2
+ import { beforeModelBuildHooks } from "./_internals.js";
2
3
  import { getDefaultMongooseConnection } from "./connection.js";
3
4
  import { mongooseAssertionsPlugin } from "./plugins/assertions.js";
4
5
  import { mongooseLeanDecimal128ToStringPlugin } from "./plugins/lean-decimal128-to-string.js";
5
6
  import { mongooseNormalizePlugin } from "./plugins/normalize.js";
6
- import mongooseAggregatePaginate from "mongoose-aggregate-paginate-v2";
7
- import mongoosePaginate from "mongoose-paginate-v2";
8
7
  // src/builders.ts
8
+ const builtSchemas = /* @__PURE__ */ new WeakSet();
9
9
  function buildMongooseModel(collection, name, schema, options) {
10
+ const connection = options?.connection ?? getDefaultMongooseConnection();
11
+ if (!builtSchemas.has(schema)) [...beforeModelBuildHooks].forEach((hook) => hook(schema));
12
+ builtSchemas.add(schema);
10
13
  const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;
11
- if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin, typeof leanDecimal128ToStringPluginOptions === "object" ? leanDecimal128ToStringPluginOptions : void 0);
12
- const normalizePluginOptions = options?.plugins?.normalize;
13
- if (normalizePluginOptions !== false) schema.plugin(mongooseNormalizePlugin, typeof normalizePluginOptions === "object" ? normalizePluginOptions : void 0);
14
- schema.plugin(mongooseAggregatePaginate);
14
+ if (leanDecimal128ToStringPluginOptions !== false) schema.plugin(mongooseLeanDecimal128ToStringPlugin, leanDecimal128ToStringPluginOptions === true ? void 0 : leanDecimal128ToStringPluginOptions);
15
15
  schema.plugin(mongooseAssertionsPlugin);
16
16
  schema.plugin(mongoosePaginate);
17
- schema.set("timestamps", options?.timestamps ?? schema.get("timestamps") ?? true);
18
- customMongooseOptions.beforeModelBuild?.(schema);
19
- return (options?.connection ?? getDefaultMongooseConnection()).model(name, schema, collection);
17
+ if (schema.get("timestamps") === void 0) schema.set("timestamps", true);
18
+ if (options?.plugins?.normalize !== false) schema.plugin(mongooseNormalizePlugin);
19
+ return connection.model(name, schema, collection);
20
20
  }
21
21
  export { buildMongooseModel };
22
22
 
@@ -1 +1 @@
1
- {"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type { Schema } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof mongooseAssertionsPlugin;\n\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n): Model {\n const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;\n if (leanDecimal128ToStringPluginOptions !== false) {\n schema.plugin(\n mongooseLeanDecimal128ToStringPlugin,\n typeof leanDecimal128ToStringPluginOptions === 'object' ? leanDecimal128ToStringPluginOptions : undefined,\n );\n }\n\n const normalizePluginOptions = options?.plugins?.normalize;\n if (normalizePluginOptions !== false) {\n schema.plugin(\n mongooseNormalizePlugin,\n typeof normalizePluginOptions === 'object' ? normalizePluginOptions : undefined,\n );\n }\n\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n const connection = options?.connection ?? getDefaultMongooseConnection();\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CACL,MAAM,sCAAsC,SAAS,SAAS;CAC9D,IAAI,wCAAwC,OACxC,OAAO,OACH,sCACA,OAAO,wCAAwC,WAAW,sCAAsC,KAAA,CACpG;CAGJ,MAAM,yBAAyB,SAAS,SAAS;CACjD,IAAI,2BAA2B,OAC3B,OAAO,OACH,yBACA,OAAO,2BAA2B,WAAW,yBAAyB,KAAA,CAC1E;CAGJ,OAAO,OAAO,yBAAyB;CACvC,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAC9B,OAAO,IAAI,cAAc,SAAS,cAAc,OAAO,IAAI,YAAY,KAAK,IAAI;CAChF,sBAAsB,mBAAmB,MAAM;CAE/C,QADmB,SAAS,cAAc,6BAA6B,EAAA,CACrD,MAAoC,MAAM,QAAQ,UAAU;AAClF"}
1
+ {"version":3,"file":"builders.js","names":[],"sources":["../src/builders.ts"],"sourcesContent":["import type {\n Connection,\n Schema,\n} from 'mongoose';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { beforeModelBuildHooks } from './_internals';\nimport { getDefaultMongooseConnection } from './connection';\nimport { mongooseAssertionsPlugin } from './plugins/assertions';\nimport { mongooseLeanDecimal128ToStringPlugin } from './plugins/lean-decimal128-to-string';\nimport type { MongooseLeanDecimal128ToStringPluginOptions } from './plugins/lean-decimal128-to-string';\nimport { mongooseNormalizePlugin } from './plugins/normalize';\nimport type { BaseMongoosePaginateModel } from './types';\n\nconst builtSchemas = new WeakSet<object>();\n\nexport interface BuildMongooseModelOptions {\n connection?: Connection;\n plugins?: {\n leanDecimal128ToString?: boolean | MongooseLeanDecimal128ToStringPluginOptions;\n normalize?: boolean;\n };\n}\n\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n): Model {\n // Resolve first so a missing default connection fails before the schema is mutated.\n const connection = options?.connection ?? getDefaultMongooseConnection();\n // Hook settings such as `toJSON` and `timestamps` must be in place before the plugins and defaults below read them,\n // and a rebuilt schema has its `toJSON` options locked. Copied because a hook may remove itself while running.\n if (!builtSchemas.has(schema)) [...beforeModelBuildHooks].forEach((hook) => hook(schema));\n builtSchemas.add(schema);\n const leanDecimal128ToStringPluginOptions = options?.plugins?.leanDecimal128ToString;\n if (leanDecimal128ToStringPluginOptions !== false) {\n schema.plugin(\n mongooseLeanDecimal128ToStringPlugin,\n leanDecimal128ToStringPluginOptions === true ? undefined : leanDecimal128ToStringPluginOptions,\n );\n }\n\n schema.plugin(mongooseAssertionsPlugin);\n schema.plugin(mongoosePaginate);\n // Schema#set('timestamps') registers the timestamp hooks again, so only fill in the default.\n if (schema.get('timestamps') === undefined) schema.set('timestamps', true);\n // Registered last because it locks the schema's `toJSON` options.\n if (options?.plugins?.normalize !== false) schema.plugin(mongooseNormalizePlugin);\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n"],"mappings":";;;;;;;AAcA,MAAM,+BAAe,IAAI,QAAgB;AAUzC,SAAgB,mBAMZ,YACA,MACA,QACA,SACK;CAEL,MAAM,aAAa,SAAS,cAAc,6BAA6B;CAGvE,IAAI,CAAC,aAAa,IAAI,MAAM,GAAG,CAAC,GAAG,qBAAqB,CAAC,CAAC,SAAS,SAAS,KAAK,MAAM,CAAC;CACxF,aAAa,IAAI,MAAM;CACvB,MAAM,sCAAsC,SAAS,SAAS;CAC9D,IAAI,wCAAwC,OACxC,OAAO,OACH,sCACA,wCAAwC,OAAO,KAAA,IAAY,mCAC/D;CAGJ,OAAO,OAAO,wBAAwB;CACtC,OAAO,OAAO,gBAAgB;CAE9B,IAAI,OAAO,IAAI,YAAY,MAAM,KAAA,GAAW,OAAO,IAAI,cAAc,IAAI;CAEzE,IAAI,SAAS,SAAS,cAAc,OAAO,OAAO,OAAO,uBAAuB;CAChF,OAAO,WAAW,MAAoC,MAAM,QAAQ,UAAU;AAClF"}
@@ -1,3 +1,6 @@
1
1
  import { Connection } from "mongoose";
2
+ /**
3
+ * @throws {Error} If `MONGODB_URI` is unset or empty while the default connection has not been created.
4
+ */
2
5
  export declare function getDefaultMongooseConnection(): Connection;
3
6
  //# sourceMappingURL=connection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","names":[],"sources":["../src/connection.ts"],"mappings":";wBAQgB,gCAAgC"}
1
+ {"version":3,"file":"connection.d.ts","names":[],"sources":["../src/connection.ts"],"mappings":";;;;wBAWgB,gCAAgC"}
@@ -1,8 +1,14 @@
1
- import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
2
1
  import mongoose from "mongoose";
2
+ import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
3
3
  // src/connection.ts
4
+ /**
5
+ * @throws {Error} If `MONGODB_URI` is unset or empty while the default connection has not been created.
6
+ */
4
7
  function getDefaultMongooseConnection() {
5
- return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(process.env.MONGODB_URI || "mongodb://127.0.0.1:27017", customMongooseOptions.defaultConnectionOptions);
8
+ if (mongooseConnectionState.defaultConnection) return mongooseConnectionState.defaultConnection;
9
+ const uri = process.env.MONGODB_URI;
10
+ if (!uri) throw new Error("MONGODB_URI must be set before the default connection is created.");
11
+ return mongooseConnectionState.defaultConnection = mongoose.createConnection(uri, customMongooseOptions.defaultConnectionOptions);
6
12
  }
7
13
  export { getDefaultMongooseConnection };
8
14
 
@@ -1 +1 @@
1
- {"version":3,"file":"connection.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import mongoose from 'mongoose';\nimport type { Connection } from 'mongoose';\n\nimport {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\n\nexport function getDefaultMongooseConnection(): Connection {\n return mongooseConnectionState.defaultConnection ||= mongoose.createConnection(\n process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017',\n customMongooseOptions.defaultConnectionOptions,\n );\n}\n"],"mappings":";;;AAQA,SAAgB,+BAA2C;CACvD,OAAO,wBAAwB,sBAAsB,SAAS,iBAC1D,QAAQ,IAAI,eAAe,6BAC3B,sBAAsB,wBAC1B;AACJ"}
1
+ {"version":3,"file":"connection.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import mongoose from 'mongoose';\nimport type { Connection } from 'mongoose';\n\nimport {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\n\n/**\n * @throws {Error} If `MONGODB_URI` is unset or empty while the default connection has not been created.\n */\nexport function getDefaultMongooseConnection(): Connection {\n if (mongooseConnectionState.defaultConnection) return mongooseConnectionState.defaultConnection;\n const uri = process.env.MONGODB_URI;\n if (!uri) throw new Error('MONGODB_URI must be set before the default connection is created.');\n return mongooseConnectionState.defaultConnection = mongoose.createConnection(\n uri,\n customMongooseOptions.defaultConnectionOptions,\n );\n}\n"],"mappings":";;;;;;AAWA,SAAgB,+BAA2C;CACvD,IAAI,wBAAwB,mBAAmB,OAAO,wBAAwB;CAC9E,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,mEAAmE;CAC7F,OAAO,wBAAwB,oBAAoB,SAAS,iBACxD,KACA,sBAAsB,wBAC1B;AACJ"}
@@ -0,0 +1,8 @@
1
+ import { Types } from "mongoose";
2
+ export type MongooseDocumentId<T> = T extends string | Types.ObjectId ? T : T extends {
3
+ _id: infer Id;
4
+ } ? Id : never;
5
+ export declare function getMongooseDocumentId<T extends string | Types.ObjectId | {
6
+ _id: unknown;
7
+ }>(value: T): MongooseDocumentId<T>;
8
+ //# sourceMappingURL=documents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documents.d.ts","names":[],"sources":["../src/documents.ts"],"mappings":";YAEY,mBAAmB,KAAK,mBAAmB,MAAM,WAAW,IAAI;EAAY,WAAW;IAAO;wBAE1F,sBAAsB,mBAAmB,MAAM;EAAa;GACxE,OAAO,IACR,mBAAmB"}
@@ -0,0 +1,10 @@
1
+ import { Types } from "mongoose";
2
+ // src/documents.ts
3
+ function getMongooseDocumentId(value) {
4
+ const input = value;
5
+ if (typeof input === "string" || input instanceof Types.ObjectId || "_bsontype" in input && input._bsontype === "ObjectId") return input;
6
+ return input._id;
7
+ }
8
+ export { getMongooseDocumentId };
9
+
10
+ //# sourceMappingURL=documents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documents.js","names":[],"sources":["../src/documents.ts"],"sourcesContent":["import { Types } from 'mongoose';\n\nexport type MongooseDocumentId<T> = T extends string | Types.ObjectId ? T : T extends { _id: infer Id } ? Id : never;\n\nexport function getMongooseDocumentId<T extends string | Types.ObjectId | { _id: unknown }>(\n value: T,\n): MongooseDocumentId<T> {\n const input: string | Types.ObjectId | { _id: unknown } = value;\n // `_bsontype` also recognizes ObjectIds created by another copy of the bson package.\n if (typeof input === 'string' || input instanceof Types.ObjectId || ('_bsontype' in input && input._bsontype === 'ObjectId')) return input as never;\n return input._id as never;\n}\n"],"mappings":";;AAIA,SAAgB,sBACZ,OACqB;CACrB,MAAM,QAAoD;CAE1D,IAAI,OAAO,UAAU,YAAY,iBAAiB,MAAM,YAAa,eAAe,SAAS,MAAM,cAAc,YAAa,OAAO;CACrI,OAAO,MAAM;AACjB"}
@@ -0,0 +1,9 @@
1
+ import { mongo } from "mongoose";
2
+ /**
3
+ * Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate
4
+ * key; the driver sets only the first write error's code on the error itself.
5
+ */
6
+ export declare function isMongooseDuplicateKeyError(error: unknown): error is mongo.MongoServerError & {
7
+ code: 11000;
8
+ };
9
+ //# sourceMappingURL=duplicate-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duplicate-key.d.ts","names":[],"sources":["../../src/errors/duplicate-key.ts"],"mappings":";;;;;wBAMgB,4BAA4B,iBAAiB,SAAS,MAAM;EAAqB"}
@@ -0,0 +1,15 @@
1
+ import { mongo } from "mongoose";
2
+ // src/errors/duplicate-key.ts
3
+ /**
4
+ * Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate
5
+ * key; the driver sets only the first write error's code on the error itself.
6
+ */
7
+ function isMongooseDuplicateKeyError(error) {
8
+ if (error instanceof mongo.MongoBulkWriteError) {
9
+ if ((Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors]).some((writeError) => writeError?.code === 11e3)) return true;
10
+ }
11
+ return error instanceof mongo.MongoServerError && error.code === 11e3;
12
+ }
13
+ export { isMongooseDuplicateKeyError };
14
+
15
+ //# sourceMappingURL=duplicate-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duplicate-key.js","names":[],"sources":["../../src/errors/duplicate-key.ts"],"sourcesContent":["import { mongo } from 'mongoose';\n\n/**\n * Also matches a bulk write error, e.g. from an unordered `insertMany`, when any of its write errors is a duplicate\n * key; the driver sets only the first write error's code on the error itself.\n */\nexport function isMongooseDuplicateKeyError(error: unknown): error is mongo.MongoServerError & { code: 11000 } {\n if (error instanceof mongo.MongoBulkWriteError) {\n const writeErrors = Array.isArray(error.writeErrors) ? error.writeErrors : [error.writeErrors];\n if (writeErrors.some((writeError) => writeError?.code === 11000)) return true;\n }\n\n return error instanceof mongo.MongoServerError && error.code === 11000;\n}\n"],"mappings":";;;;;;AAMA,SAAgB,4BAA4B,OAAmE;CAC3G,IAAI,iBAAiB,MAAM,qBACH;OAAA,MAAM,QAAQ,MAAM,WAAW,IAAI,MAAM,cAAc,CAAC,MAAM,WAAW,EAAA,CAC7E,MAAM,eAAe,YAAY,SAAS,IAAK,GAAG,OAAO;CAAA;CAG7E,OAAO,iBAAiB,MAAM,oBAAoB,MAAM,SAAS;AACrE"}
@@ -0,0 +1,4 @@
1
+ export declare class MongooseUpdateConflictError extends Error {
2
+ name: string;
3
+ }
4
+ //# sourceMappingURL=mongoose-update-conflict-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mongoose-update-conflict-error.d.ts","names":[],"sources":["../../src/errors/mongoose-update-conflict-error.ts"],"mappings":"A,qBAAa,oCAAoC;EACpC"}
@@ -0,0 +1,7 @@
1
+ // src/errors/mongoose-update-conflict-error.ts
2
+ var MongooseUpdateConflictError = class extends Error {
3
+ name = "MongooseUpdateConflictError";
4
+ };
5
+ export { MongooseUpdateConflictError };
6
+
7
+ //# sourceMappingURL=mongoose-update-conflict-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mongoose-update-conflict-error.js","names":[],"sources":["../../src/errors/mongoose-update-conflict-error.ts"],"sourcesContent":["export class MongooseUpdateConflictError extends Error {\n override name = 'MongooseUpdateConflictError';\n}\n"],"mappings":";AAAA,IAAa,8BAAb,cAAiD,MAAM;CAC1C,OAAO;AACpB"}
package/dist/options.d.ts CHANGED
@@ -1,3 +1,17 @@
1
- import { CustomMongooseOptions } from "./types/options.js";
1
+ import { ConnectOptions, Schema } from "mongoose";
2
+ export type BeforeMongooseModelBuildHook = (schema: Schema<any, any, any, any>) => void;
3
+ export interface CustomMongooseOptions {
4
+ defaultConnectionOptions?: ConnectOptions;
5
+ }
6
+ /**
7
+ * Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the
8
+ * package plugins and the `timestamps` default are applied.
9
+ *
10
+ * @returns A function that removes the hook.
11
+ */
12
+ export declare function addBeforeMongooseModelBuildHook(hook: BeforeMongooseModelBuildHook): () => void;
13
+ /**
14
+ * @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.
15
+ */
2
16
  export declare function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(key: K, value: CustomMongooseOptions[K]): void;
3
17
  //# sourceMappingURL=options.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.ts","names":[],"sources":["../src/options.ts"],"mappings":";wBAMgB,yBAAyB,gBAAgB,uBACrD,KAAK,GACL,OAAO,sBAAsB"}
1
+ {"version":3,"file":"options.d.ts","names":[],"sources":["../src/options.ts"],"mappings":";YAWY,gCAAgC,QAAQ;iBAEnC;EACb,2BAA2B;;;;;;;;wBASf,gCAAgC,MAAM;;;;wBAatC,yBAAyB,gBAAgB,uBACrD,KAAK,GACL,OAAO,sBAAsB"}
package/dist/options.js CHANGED
@@ -1,9 +1,26 @@
1
- import { customMongooseOptions, mongooseConnectionState } from "./_internals.js";
1
+ import { beforeModelBuildHooks, customMongooseOptions, mongooseConnectionState } from "./_internals.js";
2
2
  // src/options.ts
3
+ /**
4
+ * Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the
5
+ * package plugins and the `timestamps` default are applied.
6
+ *
7
+ * @returns A function that removes the hook.
8
+ */
9
+ function addBeforeMongooseModelBuildHook(hook) {
10
+ const registration = (schema) => hook(schema);
11
+ beforeModelBuildHooks.push(registration);
12
+ return () => {
13
+ const index = beforeModelBuildHooks.indexOf(registration);
14
+ if (index !== -1) beforeModelBuildHooks.splice(index, 1);
15
+ };
16
+ }
17
+ /**
18
+ * @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.
19
+ */
3
20
  function setCustomMongooseOptions(key, value) {
4
21
  if (key === "defaultConnectionOptions" && mongooseConnectionState.defaultConnection) throw new Error("Default connection options must be set before the default connection is created.");
5
22
  customMongooseOptions[key] = value;
6
23
  }
7
- export { setCustomMongooseOptions };
24
+ export { addBeforeMongooseModelBuildHook, setCustomMongooseOptions };
8
25
 
9
26
  //# sourceMappingURL=options.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import {\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\nimport type { CustomMongooseOptions } from './types/options';\n\nexport function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(\n key: K,\n value: CustomMongooseOptions[K],\n) {\n if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {\n throw new Error('Default connection options must be set before the default connection is created.');\n }\n\n customMongooseOptions[key] = value;\n}\n"],"mappings":";;AAMA,SAAgB,yBACZ,KACA,OACF;CACE,IAAI,QAAQ,8BAA8B,wBAAwB,mBAC9D,MAAM,IAAI,MAAM,kFAAkF;CAGtG,sBAAsB,OAAO;AACjC"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import type {\n ConnectOptions,\n Schema,\n} from 'mongoose';\n\nimport {\n beforeModelBuildHooks,\n customMongooseOptions,\n mongooseConnectionState,\n} from './_internals';\n\nexport type BeforeMongooseModelBuildHook = (schema: Schema<any, any, any, any>) => void;\n\nexport interface CustomMongooseOptions {\n defaultConnectionOptions?: ConnectOptions;\n}\n\n/**\n * Hooks run in registration order on every schema passed to `buildMongooseModel`, once per schema, before the\n * package plugins and the `timestamps` default are applied.\n *\n * @returns A function that removes the hook.\n */\nexport function addBeforeMongooseModelBuildHook(hook: BeforeMongooseModelBuildHook) {\n // Wrapping keeps each registration distinct, so removing one never removes another of the same function.\n const registration: BeforeMongooseModelBuildHook = (schema) => hook(schema);\n beforeModelBuildHooks.push(registration);\n return () => {\n const index = beforeModelBuildHooks.indexOf(registration);\n if (index !== -1) beforeModelBuildHooks.splice(index, 1);\n };\n}\n\n/**\n * @throws {Error} If `defaultConnectionOptions` is set after the default connection has been created.\n */\nexport function setCustomMongooseOptions<K extends keyof CustomMongooseOptions>(\n key: K,\n value: CustomMongooseOptions[K],\n) {\n if (key === 'defaultConnectionOptions' && mongooseConnectionState.defaultConnection) {\n throw new Error('Default connection options must be set before the default connection is created.');\n }\n\n customMongooseOptions[key] = value;\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,gCAAgC,MAAoC;CAEhF,MAAM,gBAA8C,WAAW,KAAK,MAAM;CAC1E,sBAAsB,KAAK,YAAY;CACvC,aAAa;EACT,MAAM,QAAQ,sBAAsB,QAAQ,YAAY;EACxD,IAAI,UAAU,IAAI,sBAAsB,OAAO,OAAO,CAAC;CAC3D;AACJ;;;;AAKA,SAAgB,yBACZ,KACA,OACF;CACE,IAAI,QAAQ,8BAA8B,wBAAwB,mBAC9D,MAAM,IAAI,MAAM,kFAAkF;CAGtG,sBAAsB,OAAO;AACjC"}
@@ -1,11 +1,32 @@
1
- import { Schema, mongo } from "mongoose";
2
- declare module 'mongoose' {
3
- interface Document<T = Types.ObjectId, TQueryHelpers = any, DocType = any, TVirtuals = Record<string, any>, TSchemaOptions = {}> {
4
- assertUpdateSuccess: (update?: UpdateQuery<Document<T, TQueryHelpers, DocType, TVirtuals, TSchemaOptions>> | UpdateWithAggregationPipeline, options?: null | QueryOptions, expectedModifiedCount?: number) => Promise<void>;
5
- }
6
- interface Model<TRawDocType, TQueryHelpers = {}, TInstanceMethods = {}, TVirtuals = {}, THydratedDocumentType = HydratedDocument<TRawDocType, TInstanceMethods & TVirtuals, TQueryHelpers, TVirtuals>, TSchema = any> {
7
- assertUpdateSuccess: (filter: QueryFilter<TRawDocType>, update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline, options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null, expectedModifiedCount?: number) => Promise<void>;
8
- }
1
+ import { ClientSession, MongooseUpdateQueryOptions, QueryFilter, QueryOptions, Schema, UpdateQuery, UpdateWithAggregationPipeline, mongo } from "mongoose";
2
+ type UpdateIfUnmodified<RawDocType, Result> = (updatedAt: Date | number | string, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: UpdateIfUnmodifiedOptions) => Promise<Result>;
3
+ export interface MongooseAssertionsDocumentMethods<RawDocType> {
4
+ /**
5
+ * @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.
6
+ */
7
+ assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;
8
+ assertUpdateSuccess: (update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: null | QueryOptions) => Promise<void>;
9
+ /**
10
+ * Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and
11
+ * returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a
12
+ * deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same
13
+ * millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.
14
+ *
15
+ * @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.
16
+ */
17
+ updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;
9
18
  }
10
- export declare function mongooseAssertionsPlugin<S extends Schema>(schema: S): void;
19
+ export interface MongooseAssertionsModelStatics<RawDocType> {
20
+ assertUpdateManySuccess: (filter: QueryFilter<RawDocType>, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null, minModifiedCount?: number) => Promise<void>;
21
+ assertUpdateOneSuccess: (filter: QueryFilter<RawDocType>, update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null) => Promise<void>;
22
+ }
23
+ /**
24
+ * Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee
25
+ * that a successful update writes a new `updatedAt`.
26
+ */
27
+ export interface UpdateIfUnmodifiedOptions {
28
+ session?: ClientSession | null;
29
+ }
30
+ export declare function mongooseAssertionsPlugin(schema: Schema): void;
31
+ export {};
11
32
  //# sourceMappingURL=assertions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.d.ts","names":[],"sources":["../../src/plugins/assertions.ts"],"mappings":";;YAac,SACN,IAAI,MAAM,UACV,qBACA,eACA,YAAY,qBAEZ;IAEA,sBACI,SACI,YAAY,SAAS,GAAG,eAAe,SAAS,WAAW,mBAC3D,+BACJ,iBAAiB,cACjB,mCACC;;YAGC,MACN,aAEA,oBAEA,uBAEA,gBAEA,wBAAwB,iBAAiB,aAAa,mBAAmB,WAAW,eAAe,YAEnG;IAEA,sBACI,QAAQ,YAAY,cACpB,QAAQ,YAAY,eAAe,+BACnC,WAAW,MAAM,gBAAgB,2BAA2B,sBAC5D,mCACC;;;wBAIG,yBAAyB,UAAU,QAAQ,QAAQ"}
1
+ {"version":3,"file":"assertions.d.ts","names":[],"sources":["../../src/plugins/assertions.ts"],"mappings":";KAeK,mBAAmB,YAAY,WAChC,WAAW,wBACX,QAAQ,YAAY,cAAc,+BAClC,UAAU,8BACT,QAAQ;iBAEI,kCAAkC;;;;EAI/C,0BAA0B,mBAAmB;EAC7C,sBACI,SAAS,YAAY,cAAc,+BACnC,iBAAiB,iBAChB;;;;;;;;;EAUL,oBAAoB,mBAAmB;;iBAG1B,+BAA+B;EAC5C,0BACI,QAAQ,YAAY,aACpB,QAAQ,YAAY,cAAc,+BAClC,WAAW,MAAM,gBAAgB,2BAA2B,qBAC5D,8BACC;EAEL,yBACI,QAAQ,YAAY,aACpB,QAAQ,YAAY,cAAc,+BAClC,WAAW,MAAM,gBAAgB,2BAA2B,wBAC3D;;;;;;iBAOQ;EACb,UAAU;;wBAsBE,yBAAyB,QAAQ"}
@@ -1,12 +1,40 @@
1
1
  import { assertMongooseUpdateSuccess } from "../assertions.js";
2
+ import { MongooseUpdateConflictError } from "../errors/mongoose-update-conflict-error.js";
2
3
  // src/plugins/assertions.ts
4
+ function getUpdatedAtPath(schema) {
5
+ const timestamps = schema.get("timestamps");
6
+ let path;
7
+ if (timestamps === true) path = "updatedAt";
8
+ else if (timestamps && typeof timestamps === "object") path = timestamps.updatedAt === true || !("updatedAt" in timestamps) ? "updatedAt" : timestamps.updatedAt;
9
+ if (typeof path === "string" && schema.path(path)) return path;
10
+ throw new Error("updateIfUnmodified requires the schema to have an updatedAt timestamp");
11
+ }
3
12
  function mongooseAssertionsPlugin(schema) {
4
- schema.method("assertUpdateSuccess", async function(update, options, expectedModifiedCount) {
5
- return await assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);
13
+ schema.method("updateIfUnmodified", updateIfUnmodified);
14
+ schema.method("assertUpdateIfUnmodified", async function(...args) {
15
+ if (await updateIfUnmodified.apply(this, args)) return;
16
+ throw new MongooseUpdateConflictError("Document was modified or deleted");
17
+ });
18
+ schema.method("assertUpdateSuccess", async function(update, options) {
19
+ return await assertMongooseUpdateSuccess(this.updateOne(update, options));
6
20
  });
7
- schema.static("assertUpdateSuccess", async function(filter, update, options, expectedModifiedCount = 1) {
8
- return await assertMongooseUpdateSuccess(expectedModifiedCount === 1 ? this.updateOne(filter, update, options) : this.updateMany(filter, update, options), expectedModifiedCount);
21
+ schema.static("assertUpdateManySuccess", async function(filter, update, options, minModifiedCount) {
22
+ return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);
9
23
  });
24
+ schema.static("assertUpdateOneSuccess", async function(filter, update, options) {
25
+ return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));
26
+ });
27
+ }
28
+ async function updateIfUnmodified(updatedAt, update, options) {
29
+ if (this._id === null || this._id === void 0) throw new Error("updateIfUnmodified requires the document _id");
30
+ const session = options && "session" in options ? options.session : this.$session() ?? void 0;
31
+ const model = this.constructor;
32
+ const result = await model.updateOne({
33
+ _id: this._id,
34
+ [getUpdatedAtPath(model.schema)]: updatedAt
35
+ }, update, session === void 0 ? void 0 : { session });
36
+ if (!result.acknowledged) throw new Error("Update was not acknowledged");
37
+ return result.matchedCount === 1;
10
38
  }
11
39
  export { mongooseAssertionsPlugin };
12
40
 
@@ -1 +1 @@
1
- {"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\n\ndeclare module 'mongoose' {\n interface Document<\n T = Types.ObjectId,\n TQueryHelpers = any,\n DocType = any,\n TVirtuals = Record<string, any>,\n // eslint-disable-next-line ts/no-empty-object-type\n TSchemaOptions = {},\n > {\n assertUpdateSuccess: (\n update?:\n | UpdateQuery<Document<T, TQueryHelpers, DocType, TVirtuals, TSchemaOptions>>\n | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n\n interface Model<\n TRawDocType,\n // eslint-disable-next-line ts/no-empty-object-type\n TQueryHelpers = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TInstanceMethods = {},\n // eslint-disable-next-line ts/no-empty-object-type\n TVirtuals = {},\n // eslint-disable-next-line unused-imports/no-unused-vars\n THydratedDocumentType = HydratedDocument<TRawDocType, TInstanceMethods & TVirtuals, TQueryHelpers, TVirtuals>,\n // eslint-disable-next-line unused-imports/no-unused-vars\n TSchema = any,\n > {\n assertUpdateSuccess: (\n filter: QueryFilter<TRawDocType>,\n update: UpdateQuery<TRawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<TRawDocType>) | null,\n expectedModifiedCount?: number,\n ) => Promise<void>;\n }\n}\n\nexport function mongooseAssertionsPlugin<S extends Schema>(schema: S) {\n schema.method(\n 'assertUpdateSuccess',\n async function (\n update?: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n expectedModifiedCount?: number,\n ) {\n return await assertMongooseUpdateSuccess(this.updateOne(update, options), expectedModifiedCount);\n },\n );\n\n schema.static(\n 'assertUpdateSuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n expectedModifiedCount: number = 1,\n ) {\n return await assertMongooseUpdateSuccess(\n expectedModifiedCount === 1\n ? this.updateOne(filter, update, options)\n : this.updateMany(filter, update, options),\n expectedModifiedCount,\n );\n },\n );\n}\n"],"mappings":";;AAoDA,SAAgB,yBAA2C,QAAW;CAClE,OAAO,OACH,uBACA,eACI,QACA,SACA,uBACF;EACE,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,OAAO,GAAG,qBAAqB;CACnG,CACJ;CAEA,OAAO,OACH,uBACA,eACI,QACA,QACA,SACA,wBAAgC,GAClC;EACE,OAAO,MAAM,4BACT,0BAA0B,IACpB,KAAK,UAAU,QAAQ,QAAQ,OAAO,IACtC,KAAK,WAAW,QAAQ,QAAQ,OAAO,GAC7C,qBACJ;CACJ,CACJ;AACJ"}
1
+ {"version":3,"file":"assertions.js","names":[],"sources":["../../src/plugins/assertions.ts"],"sourcesContent":["import type {\n ClientSession,\n Model,\n mongo,\n MongooseUpdateQueryOptions,\n QueryFilter,\n QueryOptions,\n Schema,\n UpdateQuery,\n UpdateWithAggregationPipeline,\n} from 'mongoose';\n\nimport { assertMongooseUpdateSuccess } from '../assertions';\nimport { MongooseUpdateConflictError } from '../errors/mongoose-update-conflict-error';\n\ntype UpdateIfUnmodified<RawDocType, Result> = (\n updatedAt: Date | number | string,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: UpdateIfUnmodifiedOptions,\n) => Promise<Result>;\n\nexport interface MongooseAssertionsDocumentMethods<RawDocType> {\n /**\n * @throws {MongooseUpdateConflictError} If the document was changed or deleted after `updatedAt`.\n */\n assertUpdateIfUnmodified: UpdateIfUnmodified<RawDocType, void>;\n assertUpdateSuccess: (\n update?: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: null | QueryOptions,\n ) => Promise<void>;\n\n /**\n * Updates the document only if its `updatedAt` timestamp still equals `updatedAt`, in one atomic `updateOne`, and\n * returns whether it did. Every update through Mongoose sets a new `updatedAt`, so any change in between, or a\n * deletion, makes it return `false`; timestamps have millisecond precision, so two writes within the same\n * millisecond are not told apart. Uses `options.session` if given, otherwise the document's session.\n *\n * @throws {Error} If the schema has no `updatedAt` timestamp or the document has no `_id`.\n */\n updateIfUnmodified: UpdateIfUnmodified<RawDocType, boolean>;\n}\n\nexport interface MongooseAssertionsModelStatics<RawDocType> {\n assertUpdateManySuccess: (\n filter: QueryFilter<RawDocType>,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,\n minModifiedCount?: number,\n ) => Promise<void>;\n\n assertUpdateOneSuccess: (\n filter: QueryFilter<RawDocType>,\n update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<RawDocType>) | null,\n ) => Promise<void>;\n}\n\n/**\n * Only the session is configurable: other update options such as `upsert` or `timestamps` would break the guarantee\n * that a successful update writes a new `updatedAt`.\n */\nexport interface UpdateIfUnmodifiedOptions {\n session?: ClientSession | null;\n}\n\ninterface UpdateIfUnmodifiedThis {\n $session: () => ClientSession | null;\n _id: unknown;\n constructor: Model<any>;\n}\n\nfunction getUpdatedAtPath(schema: Schema) {\n const timestamps = schema.get('timestamps');\n let path: unknown;\n if (timestamps === true) path = 'updatedAt';\n else if (timestamps && typeof timestamps === 'object') {\n path = timestamps.updatedAt === true || !('updatedAt' in timestamps) ? 'updatedAt' : timestamps.updatedAt;\n }\n\n // Mongoose skips timestamp paths it cannot name, e.g. `{ updatedAt: '' }`, so require the path to exist.\n if (typeof path === 'string' && schema.path(path)) return path;\n throw new Error('updateIfUnmodified requires the schema to have an updatedAt timestamp');\n}\n\nexport function mongooseAssertionsPlugin(schema: Schema) {\n schema.method('updateIfUnmodified', updateIfUnmodified);\n schema.method(\n 'assertUpdateIfUnmodified',\n async function (this: UpdateIfUnmodifiedThis, ...args: Parameters<UpdateIfUnmodified<any, void>>) {\n if (await updateIfUnmodified.apply(this, args)) return;\n throw new MongooseUpdateConflictError('Document was modified or deleted');\n },\n );\n\n schema.method(\n 'assertUpdateSuccess',\n async function (update?: UpdateQuery<any> | UpdateWithAggregationPipeline, options?: null | QueryOptions) {\n return await assertMongooseUpdateSuccess(this.updateOne(update, options));\n },\n );\n\n schema.static(\n 'assertUpdateManySuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n minModifiedCount?: number,\n ) {\n return await assertMongooseUpdateSuccess(this.updateMany(filter, update, options), minModifiedCount);\n },\n );\n\n schema.static(\n 'assertUpdateOneSuccess',\n async function (\n filter: QueryFilter<any>,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: (mongo.UpdateOptions & MongooseUpdateQueryOptions<any>) | null,\n ) {\n return await assertMongooseUpdateSuccess(this.updateOne(filter, update, options));\n },\n );\n}\n\nasync function updateIfUnmodified(\n this: UpdateIfUnmodifiedThis,\n updatedAt: Date | number | string,\n update: UpdateQuery<any> | UpdateWithAggregationPipeline,\n options?: UpdateIfUnmodifiedOptions,\n) {\n // With `ignoreUndefined`, an undefined `_id` would be dropped from the filter and match another document.\n if (this._id === null || this._id === undefined) throw new Error('updateIfUnmodified requires the document _id');\n const session = options && 'session' in options ? options.session : this.$session() ?? undefined;\n const model = this.constructor;\n const result = await model.updateOne(\n {\n _id: this._id,\n [getUpdatedAtPath(model.schema)]: updatedAt,\n },\n update,\n // Without a session the key is omitted, so `transactionAsyncLocalStorage` can still supply one. An explicit\n // `null` opts out of any session, as Mongoose's own options do, although its types only allow `undefined`.\n session === undefined ? undefined : { session: session as ClientSession },\n );\n\n if (!result.acknowledged) throw new Error('Update was not acknowledged');\n return result.matchedCount === 1;\n}\n"],"mappings":";;;AAuEA,SAAS,iBAAiB,QAAgB;CACtC,MAAM,aAAa,OAAO,IAAI,YAAY;CAC1C,IAAI;CACJ,IAAI,eAAe,MAAM,OAAO;MAC3B,IAAI,cAAc,OAAO,eAAe,UACzC,OAAO,WAAW,cAAc,QAAQ,EAAE,eAAe,cAAc,cAAc,WAAW;CAIpG,IAAI,OAAO,SAAS,YAAY,OAAO,KAAK,IAAI,GAAG,OAAO;CAC1D,MAAM,IAAI,MAAM,uEAAuE;AAC3F;AAEA,SAAgB,yBAAyB,QAAgB;CACrD,OAAO,OAAO,sBAAsB,kBAAkB;CACtD,OAAO,OACH,4BACA,eAA8C,GAAG,MAAiD;EAC9F,IAAI,MAAM,mBAAmB,MAAM,MAAM,IAAI,GAAG;EAChD,MAAM,IAAI,4BAA4B,kCAAkC;CAC5E,CACJ;CAEA,OAAO,OACH,uBACA,eAAgB,QAA2D,SAA+B;EACtG,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,OAAO,CAAC;CAC5E,CACJ;CAEA,OAAO,OACH,2BACA,eACI,QACA,QACA,SACA,kBACF;EACE,OAAO,MAAM,4BAA4B,KAAK,WAAW,QAAQ,QAAQ,OAAO,GAAG,gBAAgB;CACvG,CACJ;CAEA,OAAO,OACH,0BACA,eACI,QACA,QACA,SACF;EACE,OAAO,MAAM,4BAA4B,KAAK,UAAU,QAAQ,QAAQ,OAAO,CAAC;CACpF,CACJ;AACJ;AAEA,eAAe,mBAEX,WACA,QACA,SACF;CAEE,IAAI,KAAK,QAAQ,QAAQ,KAAK,QAAQ,KAAA,GAAW,MAAM,IAAI,MAAM,8CAA8C;CAC/G,MAAM,UAAU,WAAW,aAAa,UAAU,QAAQ,UAAU,KAAK,SAAS,KAAK,KAAA;CACvF,MAAM,QAAQ,KAAK;CACnB,MAAM,SAAS,MAAM,MAAM,UACvB;EACI,KAAK,KAAK;GACT,iBAAiB,MAAM,MAAM,IAAI;CACtC,GACA,QAGA,YAAY,KAAA,IAAY,KAAA,IAAY,EAAW,QAAyB,CAC5E;CAEA,IAAI,CAAC,OAAO,cAAc,MAAM,IAAI,MAAM,6BAA6B;CACvE,OAAO,OAAO,iBAAiB;AACnC"}