@prisma/orm-target-mongo 8.0.0-rc.2-dev.2 → 8.0.0-rc.20

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 (122) hide show
  1. package/README.md +1 -5
  2. package/dist/adapter.d.mts +2 -2
  3. package/dist/adapter.d.mts.map +1 -1
  4. package/dist/adapter.mjs +3 -3
  5. package/dist/adapter.mjs.map +1 -1
  6. package/dist/adapter__control.d.mts +204 -3
  7. package/dist/adapter__control.d.mts.map +1 -0
  8. package/dist/adapter__control.mjs +481 -3
  9. package/dist/adapter__control.mjs.map +1 -0
  10. package/dist/adapter__runtime.d.mts +3 -1
  11. package/dist/adapter__runtime.d.mts.map +1 -1
  12. package/dist/adapter__runtime.mjs +5 -3
  13. package/dist/adapter__runtime.mjs.map +1 -1
  14. package/dist/codec-ids-BKQbXhZt.d.mts +18 -0
  15. package/dist/codec-ids-BKQbXhZt.d.mts.map +1 -0
  16. package/dist/codec-ids-WdrumsYA-CZVjuKW8.mjs +18 -0
  17. package/dist/codec-ids-WdrumsYA-CZVjuKW8.mjs.map +1 -0
  18. package/dist/codec-types-oKxM85p-.d.mts +89 -0
  19. package/dist/codec-types-oKxM85p-.d.mts.map +1 -0
  20. package/dist/codecs-B1ab7vfj-QL33tkm2.mjs +392 -0
  21. package/dist/codecs-B1ab7vfj-QL33tkm2.mjs.map +1 -0
  22. package/dist/codecs-Y5GYsLPj.d.mts +36 -0
  23. package/dist/codecs-Y5GYsLPj.d.mts.map +1 -0
  24. package/dist/control-Cq6qWohQ.mjs +2421 -0
  25. package/dist/control-Cq6qWohQ.mjs.map +1 -0
  26. package/dist/{control-CxXmTy_h.d.mts → control-CrFS8bqh.d.mts} +133 -95
  27. package/dist/control-CrFS8bqh.d.mts.map +1 -0
  28. package/dist/data-types-LShlnAUM.d.mts +25 -0
  29. package/dist/data-types-LShlnAUM.d.mts.map +1 -0
  30. package/dist/data-types-hoKLBrYZ-h9cAgbOy.mjs +624 -0
  31. package/dist/data-types-hoKLBrYZ-h9cAgbOy.mjs.map +1 -0
  32. package/dist/descriptor-meta-DTj807jv-CjvK2XDD.mjs +146 -0
  33. package/dist/descriptor-meta-DTj807jv-CjvK2XDD.mjs.map +1 -0
  34. package/dist/descriptor-meta-runtime-BaRbjvD7-D0786_Lv.mjs +20 -0
  35. package/dist/descriptor-meta-runtime-BaRbjvD7-D0786_Lv.mjs.map +1 -0
  36. package/dist/driver.d.mts +1 -1
  37. package/dist/driver.mjs +1 -1
  38. package/dist/driver__control.d.mts +4 -3
  39. package/dist/driver__control.d.mts.map +1 -1
  40. package/dist/driver__control.mjs +5 -2
  41. package/dist/driver__control.mjs.map +1 -1
  42. package/dist/{migration-BkqcE2Uv.d.mts → migration-C4m4Uj8E.d.mts} +15 -7
  43. package/dist/migration-C4m4Uj8E.d.mts.map +1 -0
  44. package/dist/migration-factories-BqROEHRs-CfExMr9r.mjs +406 -0
  45. package/dist/migration-factories-BqROEHRs-CfExMr9r.mjs.map +1 -0
  46. package/dist/{mongo-adapter-B2HEyX0b-CQt2HH_o.mjs → mongo-adapter-Bo6ciURK-DIMJdC7y.mjs} +37 -18
  47. package/dist/mongo-adapter-Bo6ciURK-DIMJdC7y.mjs.map +1 -0
  48. package/dist/{mongo-adapter-CjJU3S9o-BIJruFYW.d.mts → mongo-adapter-wvK2fQOZ-FswLS-PJ.d.mts} +2 -2
  49. package/dist/mongo-adapter-wvK2fQOZ-FswLS-PJ.d.mts.map +1 -0
  50. package/dist/{mongo-driver-D1lEf5Kl-KPfGUVXK.d.mts → mongo-driver-CTyvKDUg-Bm9sBrfs.d.mts} +9 -4
  51. package/dist/mongo-driver-CTyvKDUg-Bm9sBrfs.d.mts.map +1 -0
  52. package/dist/{mongo-driver-CMzJAzeQ-B3Q4RoHN.mjs → mongo-driver-Cu6FP6OU-DhOzFM2D.mjs} +34 -8
  53. package/dist/mongo-driver-Cu6FP6OU-DhOzFM2D.mjs.map +1 -0
  54. package/dist/mongo-target-errors-Btf3ML1w-QOtEG7EX.mjs +9 -0
  55. package/dist/mongo-target-errors-Btf3ML1w-QOtEG7EX.mjs.map +1 -0
  56. package/dist/{op-factory-call-B7EKa4Ri-B2Lb6W68.d.mts → op-factory-call-BoYr7vvM-CjA8nx36.d.mts} +43 -9
  57. package/dist/op-factory-call-BoYr7vvM-CjA8nx36.d.mts.map +1 -0
  58. package/dist/pack-CIfujQmd.d.mts +266 -0
  59. package/dist/pack-CIfujQmd.d.mts.map +1 -0
  60. package/dist/prisma6-binding-DhnqslLT.d.mts +54 -0
  61. package/dist/prisma6-binding-DhnqslLT.d.mts.map +1 -0
  62. package/dist/prisma6-binding-vt4tbT-Z.mjs +45 -0
  63. package/dist/prisma6-binding-vt4tbT-Z.mjs.map +1 -0
  64. package/dist/{runtime-B9_-kjBX.d.mts → runtime-DbFgyDql.d.mts} +2 -2
  65. package/dist/runtime-DbFgyDql.d.mts.map +1 -0
  66. package/dist/target.d.mts +11 -8
  67. package/dist/target.mjs +7 -3
  68. package/dist/target__codec-ids.d.mts +2 -0
  69. package/dist/target__codec-ids.mjs +2 -0
  70. package/dist/target__codec-types.d.mts +2 -2
  71. package/dist/target__codecs.d.mts +2 -0
  72. package/dist/target__codecs.mjs +2 -0
  73. package/dist/target__control.d.mts +3 -4
  74. package/dist/target__control.mjs +2 -2
  75. package/dist/target__data-types.d.mts +2 -0
  76. package/dist/target__data-types.mjs +2 -0
  77. package/dist/target__migration.d.mts +2 -2
  78. package/dist/target__migration.mjs +2 -2
  79. package/dist/target__pack.d.mts +3 -2
  80. package/dist/target__pack.mjs +2 -2
  81. package/dist/target__pack.mjs.map +1 -1
  82. package/dist/target__prisma6-binding.d.mts +2 -0
  83. package/dist/target__prisma6-binding.mjs +2 -0
  84. package/dist/target__runtime.d.mts +1 -1
  85. package/dist/target__runtime.mjs +3 -3
  86. package/dist/target__runtime.mjs.map +1 -1
  87. package/package.json +16 -15
  88. package/dist/adapter__codec-ids.d.mts +0 -12
  89. package/dist/adapter__codec-ids.d.mts.map +0 -1
  90. package/dist/adapter__codec-ids.mjs +0 -2
  91. package/dist/adapter__codec-types.d.mts +0 -38
  92. package/dist/adapter__codec-types.d.mts.map +0 -1
  93. package/dist/adapter__codec-types.mjs +0 -1
  94. package/dist/adapter__codecs.d.mts +0 -14
  95. package/dist/adapter__codecs.d.mts.map +0 -1
  96. package/dist/adapter__codecs.mjs +0 -2
  97. package/dist/codec-ids-BennPcpQ-Btzz3ILV.mjs +0 -12
  98. package/dist/codec-ids-BennPcpQ-Btzz3ILV.mjs.map +0 -1
  99. package/dist/codec-types-Bx2fHyq_.d.mts +0 -35
  100. package/dist/codec-types-Bx2fHyq_.d.mts.map +0 -1
  101. package/dist/codecs-DLWO-Cjc-CWfQj0bY.mjs +0 -170
  102. package/dist/codecs-DLWO-Cjc-CWfQj0bY.mjs.map +0 -1
  103. package/dist/control-CxXmTy_h.d.mts.map +0 -1
  104. package/dist/control-DQD76x-1.mjs +0 -437
  105. package/dist/control-DQD76x-1.mjs.map +0 -1
  106. package/dist/control-Dfe3dqw9.mjs +0 -1563
  107. package/dist/control-Dfe3dqw9.mjs.map +0 -1
  108. package/dist/control-rPM2HNxW.d.mts +0 -170
  109. package/dist/control-rPM2HNxW.d.mts.map +0 -1
  110. package/dist/descriptor-meta-CBiaTwe5-HX742pZh.mjs +0 -17
  111. package/dist/descriptor-meta-CBiaTwe5-HX742pZh.mjs.map +0 -1
  112. package/dist/migration-BkqcE2Uv.d.mts.map +0 -1
  113. package/dist/migration-factories-CCJFG_3e-75oJ8xn2.mjs +0 -201
  114. package/dist/migration-factories-CCJFG_3e-75oJ8xn2.mjs.map +0 -1
  115. package/dist/mongo-adapter-B2HEyX0b-CQt2HH_o.mjs.map +0 -1
  116. package/dist/mongo-adapter-CjJU3S9o-BIJruFYW.d.mts.map +0 -1
  117. package/dist/mongo-driver-CMzJAzeQ-B3Q4RoHN.mjs.map +0 -1
  118. package/dist/mongo-driver-D1lEf5Kl-KPfGUVXK.d.mts.map +0 -1
  119. package/dist/op-factory-call-B7EKa4Ri-B2Lb6W68.d.mts.map +0 -1
  120. package/dist/pack-MK8ZQfrL.d.mts +0 -22
  121. package/dist/pack-MK8ZQfrL.d.mts.map +0 -1
  122. package/dist/runtime-B9_-kjBX.d.mts.map +0 -1
@@ -0,0 +1,624 @@
1
+ import { r as MONGO_BSON_CODEC_ID } from "./codec-ids-WdrumsYA-CZVjuKW8.mjs";
2
+ import { t as mongoTargetError } from "./mongo-target-errors-Btf3ML1w-QOtEG7EX.mjs";
3
+ import { structuredError } from "@prisma/orm-framework/utils/structured-error";
4
+ import { INT32_RANGE, INT64_RANGE, SAFE_INTEGER_BIGINT_RANGE, SAFE_INTEGER_RANGE, asFloat, asNumeralText, castUnchanged, decimalTextEqualityKey, isIntegerIn, readJsonBoolean, readJsonFloat, readJsonInteger, readJsonIntegerText, readJsonMatching, readJsonString, refuseJsonValue, refuseWrongShape } from "@prisma/orm-framework/components/codec";
5
+ import { counted } from "@prisma/orm-framework/utils/text";
6
+ import { Binary, Code, Decimal128, Double, EJSON, Long, MinKey, ObjectId } from "bson";
7
+ import { mongoDataType } from "@prisma/orm-family-mongo/contract/data-type";
8
+ import { type } from "arktype";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
11
+ //#region ../../../3-targets/mongo/1-target/dist/data-types-hoKLBrYZ.mjs
12
+ const STORED_DECIMAL_TEXT = /^(?:-?\d+(?:\.\d+)?|NaN|-?Infinity)$/;
13
+ const DECIMAL128_TEXT = /^(-?)(\d+)(?:\.(\d+))?(?:E([+-]\d+))?$/;
14
+ const BASE64_TEXT = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
15
+ /**
16
+ * Checks the BSON type tag rather than `instanceof`: the driver deserialises with its own load of `bson` (CommonJS, where this module may be loaded as ESM), so a value read from the database need not be an instance of the class imported here.
17
+ */
18
+ function hasBsonTypeTag(value, tag) {
19
+ return typeof value === "object" && value !== null && "_bsontype" in value && value._bsontype === tag;
20
+ }
21
+ function isLong(value) {
22
+ return hasBsonTypeTag(value, "Long");
23
+ }
24
+ function isDecimal128(value) {
25
+ return hasBsonTypeTag(value, "Decimal128");
26
+ }
27
+ function isBinary(value) {
28
+ return hasBsonTypeTag(value, "Binary");
29
+ }
30
+ function decodeFailed(codecId, message, received) {
31
+ throw mongoTargetError("RUNTIME.DECODE_FAILED", `${codecId} ${message}`, { meta: {
32
+ codecId,
33
+ received: typeof received
34
+ } });
35
+ }
36
+ const RECEIVED_PREVIEW_LIMIT = 100;
37
+ function encodeFailed(codecId, message, received) {
38
+ throw mongoTargetError("RUNTIME.ENCODE_FAILED", `${codecId} ${message}`, { meta: {
39
+ codecId,
40
+ received: String(received).slice(0, RECEIVED_PREVIEW_LIMIT)
41
+ } });
42
+ }
43
+ function describeReceived(value) {
44
+ if (typeof value === "number") return String(value);
45
+ if (typeof value === "bigint") return `${value}n`;
46
+ if (typeof value === "string") return `string ${JSON.stringify(value.slice(0, RECEIVED_PREVIEW_LIMIT))}`;
47
+ if (value === null) return "null";
48
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "an invalid Date" : "a Date";
49
+ if (Array.isArray(value)) return "an array";
50
+ return typeof value;
51
+ }
52
+ function refuseType(codecId, expected, value, received = describeReceived(value)) {
53
+ return encodeFailed(codecId, `value must be ${expected}; received ${received}`, value);
54
+ }
55
+ function stringEncode(codecId, value) {
56
+ if (typeof value !== "string") refuseType(codecId, "a string", value);
57
+ return value;
58
+ }
59
+ function booleanEncode(codecId, value) {
60
+ if (typeof value !== "boolean") refuseType(codecId, "a boolean", value);
61
+ return value;
62
+ }
63
+ /**
64
+ * The driver writes an invalid `Date` as the epoch, so one is refused with any other non-`Date` value.
65
+ */
66
+ function dateEncode(codecId, value) {
67
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) refuseType(codecId, "a valid Date", value);
68
+ return value;
69
+ }
70
+ const OBJECT_ID_TEXT = /^[0-9a-fA-F]{24}$/;
71
+ function hexStringOf(value) {
72
+ const toHexString = Reflect.get(value, "toHexString");
73
+ if (typeof toHexString !== "function") return void 0;
74
+ const hex = Reflect.apply(toHexString, value, []);
75
+ return typeof hex === "string" && OBJECT_ID_TEXT.test(hex) ? hex : void 0;
76
+ }
77
+ /**
78
+ * `new ObjectId(...)` makes a fresh id from `null` or `undefined` and reads a number as a timestamp, so only a string, which the constructor accepts only as 24 hex digits, or an `ObjectId` is passed to it. An `ObjectId` is rebuilt from its hex string, so one from any major version of `bson` works.
79
+ */
80
+ function objectIdEncode(codecId, value) {
81
+ const expected = "a 24-digit hex string or an ObjectId";
82
+ if (typeof value === "string") try {
83
+ return new ObjectId(value);
84
+ } catch {
85
+ return refuseType(codecId, expected, value);
86
+ }
87
+ if (typeof value !== "object" || value === null || !hasBsonTypeTag(value, "ObjectId")) return refuseType(codecId, expected, value);
88
+ const hex = hexStringOf(value);
89
+ if (hex === void 0) return refuseType(codecId, expected, value, "an object tagged ObjectId whose toHexString() does not return 24 hex digits");
90
+ return new ObjectId(hex);
91
+ }
92
+ function vectorEncode(codecId, value) {
93
+ if (!Array.isArray(value) || !value.every((element) => typeof element === "number")) refuseType(codecId, "an array of numbers", value);
94
+ return value;
95
+ }
96
+ /**
97
+ * Wraps the number in the driver's `Double`, because the driver writes a whole JavaScript number in the int32 range as a BSON `int`, which a `double` validator refuses.
98
+ */
99
+ function doubleEncode(codecId, value) {
100
+ if (typeof value !== "number") encodeFailed(codecId, `value must be a number; received ${describeReceived(value)}`, value);
101
+ return new Double(value);
102
+ }
103
+ function int32Encode(codecId, value) {
104
+ if (!isIntegerIn(value, INT32_RANGE)) encodeFailed(codecId, `value must be an integer from ${INT32_RANGE.min} to ${INT32_RANGE.max}; received ${describeReceived(value)}`, value);
105
+ return value;
106
+ }
107
+ function objectIdToJson(codecId, value) {
108
+ if (typeof value !== "string" || !OBJECT_ID_TEXT.test(value)) encodeFailed(codecId, "value must be 24 hexadecimal digits", value);
109
+ return value;
110
+ }
111
+ /** Whether `text` is an ObjectId's 24 hexadecimal digits, in either case. */
112
+ function isObjectIdText(text) {
113
+ return OBJECT_ID_TEXT.test(text);
114
+ }
115
+ /** Reads ObjectId hex in either case; {@link spellObjectIdJson} writes the lower case the type stores. */
116
+ function readObjectIdJson(owner, json) {
117
+ return readJsonMatching(owner, json, OBJECT_ID_TEXT, "24 hexadecimal digits");
118
+ }
119
+ /** The ObjectId hex in lower case, as the driver's `toHexString` writes it. */
120
+ function spellObjectIdJson(json) {
121
+ return typeof json === "string" ? json.toLowerCase() : json;
122
+ }
123
+ function int32ToJson(codecId, value) {
124
+ if (!isIntegerIn(value, INT32_RANGE)) encodeFailed(codecId, `value must be an integer from ${INT32_RANGE.min} to ${INT32_RANGE.max}`, value);
125
+ return value;
126
+ }
127
+ function readInt32Json(owner, json) {
128
+ return readJsonInteger(owner, json, INT32_RANGE);
129
+ }
130
+ function dateToJson(codecId, value) {
131
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) encodeFailed(codecId, "value must be a valid Date", value);
132
+ return value.toISOString();
133
+ }
134
+ /**
135
+ * The JSON form is the text `Date.toISOString()` writes, so a string that does not read back to that same text is refused.
136
+ */
137
+ function readDateJson(owner, json) {
138
+ const date = typeof json === "string" ? new Date(json) : void 0;
139
+ if (date === void 0 || Number.isNaN(date.getTime()) || date.toISOString() !== json) return refuseJsonValue(owner, "a date and time in UTC as Date.toISOString writes it", json);
140
+ return json;
141
+ }
142
+ /** Reads an array of numbers, of exactly `length` numbers when the column sets one. */
143
+ function readVectorJson(owner, json, length) {
144
+ const expected = length === void 0 ? "an array of numbers" : `an array of ${counted(length, "number")}`;
145
+ if (!Array.isArray(json) || length !== void 0 && json.length !== length) return refuseJsonValue(owner, expected, json);
146
+ const numbers = [];
147
+ for (const element of json) {
148
+ if (typeof element !== "number") return refuseJsonValue(owner, expected, element);
149
+ if (!Number.isFinite(element)) return refuseJsonValue(owner, "an array of finite numbers", json);
150
+ numbers.push(element);
151
+ }
152
+ return numbers;
153
+ }
154
+ /**
155
+ * `Long.fromBigInt` keeps the low 64 bits of any bigint, so an out-of-range value would be stored as a different number without error.
156
+ */
157
+ function isInt64(value) {
158
+ return value >= INT64_RANGE.min && value <= INT64_RANGE.max;
159
+ }
160
+ function requireInt64(codecId, value) {
161
+ if (!isInt64(value)) encodeFailed(codecId, "value is outside the signed 64-bit range", value);
162
+ return value;
163
+ }
164
+ function int64Encode(codecId, value) {
165
+ if (typeof value !== "bigint") encodeFailed(codecId, "value must be a bigint", value);
166
+ return Long.fromBigInt(requireInt64(codecId, value));
167
+ }
168
+ /**
169
+ * A stored double with a fraction, which a 64-bit integer codec cannot read. Such values were written through a Prisma 6 `Int` while its contract used the 32-bit codec, which took any number.
170
+ */
171
+ function refuseFractionalDouble(codecId, wire) {
172
+ return decodeFailed(codecId, `wire value is the fractional double ${wire}, and a 64-bit integer holds whole numbers only. Rewrite each such stored value as a long, rounded or cut off ({ $toLong: { $round: [<value>, 0] } }, or $trunc in place of $round), mapping over the list when the value sits in one. The upgrade guide step prisma6-int-written-as-long has the queries for a plain field, a list and a list of composite values.`, wire);
173
+ }
174
+ /**
175
+ * The driver promotes a stored `long` that fits in 53 bits to a `number`, and hands larger ones over as `Long`, so both arrive here.
176
+ */
177
+ function int64Decode(codecId, wire) {
178
+ if (typeof wire === "bigint") return wire;
179
+ if (isLong(wire)) return wire.toBigInt();
180
+ if (typeof wire === "number" && Number.isSafeInteger(wire)) return BigInt(wire);
181
+ if (typeof wire === "number" && Number.isFinite(wire) && !Number.isInteger(wire)) return refuseFractionalDouble(codecId, wire);
182
+ return decodeFailed(codecId, "wire value must be a Long or a safe integer", wire);
183
+ }
184
+ /**
185
+ * A schema-written default arrives as a `number`; one that is a safe integer names its value exactly, so it is accepted like `pg/int8@1` accepts it.
186
+ */
187
+ function int64ToJson(codecId, value) {
188
+ if (typeof value === "bigint") return requireInt64(codecId, value).toString();
189
+ if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value).toString();
190
+ return encodeFailed(codecId, "value must be a bigint or a safe integer", value);
191
+ }
192
+ function readInt64Json(owner, json) {
193
+ readJsonIntegerText(owner, json, INT64_RANGE);
194
+ return json;
195
+ }
196
+ const SAFE_INTEGERS = `from ${SAFE_INTEGER_RANGE.min} to ${SAFE_INTEGER_RANGE.max}`;
197
+ function int64NumberEncode(codecId, value) {
198
+ if (!isIntegerIn(value, SAFE_INTEGER_RANGE)) encodeFailed(codecId, `value must be an integer ${SAFE_INTEGERS}; received ${describeReceived(value)}`, value);
199
+ return Long.fromNumber(value);
200
+ }
201
+ function safeIntegerOf(codecId, value) {
202
+ if (value < SAFE_INTEGER_BIGINT_RANGE.min || value > SAFE_INTEGER_BIGINT_RANGE.max) decodeFailed(codecId, `wire value must be a whole number ${SAFE_INTEGERS}; received ${value}`, value);
203
+ return Number(value);
204
+ }
205
+ /**
206
+ * The driver hands a stored `long` over as a `number` when it fits in 53 bits (the default `promoteLongs`), as a `Long` otherwise or with `promoteLongs: false`, and as a `bigint` with `useBigInt64`.
207
+ */
208
+ function int64NumberDecode(codecId, wire) {
209
+ if (typeof wire === "bigint") return safeIntegerOf(codecId, wire);
210
+ if (isLong(wire)) return safeIntegerOf(codecId, wire.toBigInt());
211
+ if (isIntegerIn(wire, SAFE_INTEGER_RANGE)) return wire;
212
+ if (typeof wire === "number" && Number.isFinite(wire) && !Number.isInteger(wire)) return refuseFractionalDouble(codecId, wire);
213
+ return decodeFailed(codecId, `wire value must be a whole number ${SAFE_INTEGERS}; received ${describeReceived(wire)}`, wire);
214
+ }
215
+ function int64NumberToJson(codecId, value) {
216
+ return int64NumberEncode(codecId, value).toString();
217
+ }
218
+ /** A `number` holds an integer exactly only within the safe integer range, so digit text past it is refused. */
219
+ function int64NumberFromDigits(codecId, digits) {
220
+ return Number(readJsonIntegerText(codecId, digits, SAFE_INTEGER_BIGINT_RANGE));
221
+ }
222
+ /**
223
+ * `Decimal128.toString()` writes some values with an exponent (`1E+3`, `1.23E+40`). The application value is decimal text without one, as for Postgres `numeric`: the point moves to where the exponent puts it, trailing zeros stay, and the sign of zero goes.
224
+ */
225
+ function decimalTextWithoutExponent(text) {
226
+ if (text === "NaN" || text === "Infinity" || text === "-Infinity") return text;
227
+ const match = DECIMAL128_TEXT.exec(text);
228
+ if (match === null) return void 0;
229
+ const [, sign = "", whole = "", fraction = "", exponent = "0"] = match;
230
+ const digits = `${whole}${fraction}`;
231
+ const point = whole.length + Number(exponent);
232
+ let integerPart;
233
+ let fractionPart;
234
+ if (point <= 0) {
235
+ integerPart = "0";
236
+ fractionPart = `${"0".repeat(-point)}${digits}`;
237
+ } else if (point >= digits.length) {
238
+ integerPart = `${digits}${"0".repeat(point - digits.length)}`;
239
+ fractionPart = "";
240
+ } else {
241
+ integerPart = digits.slice(0, point);
242
+ fractionPart = digits.slice(point);
243
+ }
244
+ const trimmedInteger = integerPart.replace(/^0+(?=\d)/, "");
245
+ const unsigned = fractionPart === "" ? trimmedInteger : `${trimmedInteger}.${fractionPart}`;
246
+ return /^[0.]+$/.test(unsigned) ? unsigned : `${sign}${unsigned}`;
247
+ }
248
+ function requireStoredDecimalText(codecId, value) {
249
+ if (typeof value !== "string" || !STORED_DECIMAL_TEXT.test(value)) encodeFailed(codecId, "value must be decimal text without an exponent, or NaN, Infinity or -Infinity", value);
250
+ return value;
251
+ }
252
+ function decimal128Encode(codecId, value) {
253
+ requireStoredDecimalText(codecId, value);
254
+ try {
255
+ return Decimal128.fromString(value);
256
+ } catch (error) {
257
+ return encodeFailed(codecId, `value cannot be stored as a Decimal128 exactly: ${error instanceof Error ? error.message : String(error)}`, value);
258
+ }
259
+ }
260
+ function decimal128Decode(codecId, wire) {
261
+ if (!isDecimal128(wire)) return decodeFailed(codecId, "wire value must be a Decimal128", wire);
262
+ const text = decimalTextWithoutExponent(wire.toString());
263
+ if (text === void 0) return decodeFailed(codecId, "wire value is not decimal text", wire);
264
+ return text;
265
+ }
266
+ function decimal128ToJson(codecId, value) {
267
+ return requireStoredDecimalText(codecId, value);
268
+ }
269
+ /** Decimal text without its leading zeros, as MongoDB writes it; the sign of zero and trailing zeros stay. */
270
+ function decimalTextWithoutLeadingZeros(text) {
271
+ return text.replace(/^(-?)0+(?=\d)/, "$1");
272
+ }
273
+ function withoutSignOfZero(text) {
274
+ return /^-[0.]+$/.test(text) ? text.slice(1) : text;
275
+ }
276
+ /** Whether a Decimal128 holds the decimal text exactly: the text it writes back is the same number, digit for digit. */
277
+ function decimal128HoldsExactly(text) {
278
+ let written;
279
+ try {
280
+ written = Decimal128.fromString(text).toString();
281
+ } catch {
282
+ return false;
283
+ }
284
+ return decimalTextWithoutExponent(written) === withoutSignOfZero(decimalTextWithoutLeadingZeros(text));
285
+ }
286
+ /**
287
+ * The stored form is what the codec writes, so it follows the encode rule: decimal text without an exponent, or `NaN`, `Infinity` or `-Infinity`, that a Decimal128 holds exactly. A value a Decimal128 would round is refused.
288
+ */
289
+ function readDecimal128Json(owner, json) {
290
+ const expected = "decimal text without an exponent that a Decimal128 holds exactly, or NaN, Infinity or -Infinity";
291
+ const text = readJsonMatching(owner, json, STORED_DECIMAL_TEXT, expected);
292
+ return decimal128HoldsExactly(text) ? text : refuseJsonValue(owner, expected, json);
293
+ }
294
+ /** The decimal text without leading zeros, as MongoDB writes it, keeping negative zero. */
295
+ function spellDecimal128Json(json) {
296
+ return typeof json === "string" ? decimalTextWithoutLeadingZeros(json) : json;
297
+ }
298
+ function binaryEncode(codecId, value) {
299
+ if (!(value instanceof Uint8Array)) encodeFailed(codecId, "value must be a Uint8Array", value);
300
+ return new Binary(value);
301
+ }
302
+ /**
303
+ * The driver reads binData as a `Binary`, or as a `Buffer` with `promoteBuffers: true`; either becomes a plain `Uint8Array` copy of the bytes.
304
+ */
305
+ function binaryDecode(codecId, wire) {
306
+ if (wire instanceof Uint8Array) return new Uint8Array(wire);
307
+ if (!isBinary(wire)) return decodeFailed(codecId, "wire value must be a Binary or a Uint8Array", wire);
308
+ return new Uint8Array(wire.value());
309
+ }
310
+ function binaryToBase64(value) {
311
+ return Buffer.from(value).toString("base64");
312
+ }
313
+ /** Whether `text` is base64, with or without padding bits set. */
314
+ function isBase64Text(text) {
315
+ return BASE64_TEXT.test(text);
316
+ }
317
+ /** Reads base64 with or without padding bits set; {@link spellBase64Json} writes the base64 the type stores. */
318
+ function readBinaryJson(owner, json) {
319
+ return readJsonMatching(owner, json, BASE64_TEXT, "base64 text");
320
+ }
321
+ /** The base64 of the same bytes with padding bits zero, as `Buffer` writes it. */
322
+ function spellBase64Json(json) {
323
+ return typeof json === "string" ? Buffer.from(json, "base64").toString("base64") : json;
324
+ }
325
+ function binaryFromBase64(base64) {
326
+ return new Uint8Array(Buffer.from(base64, "base64"));
327
+ }
328
+ function where(path) {
329
+ return path === "" ? "the root" : path;
330
+ }
331
+ function child(path, key) {
332
+ return path === "" ? String(key) : `${path}.${key}`;
333
+ }
334
+ function isPlainObject(value) {
335
+ const prototype = Object.getPrototypeOf(value);
336
+ return prototype === Object.prototype || prototype === null;
337
+ }
338
+ function isPlainArray(value) {
339
+ return Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype;
340
+ }
341
+ const BSON_VERSION = Symbol.for("@@mdb.bson.version");
342
+ /** The major version of the `bson` this package loads, which every `bson` class instance it can serialise carries. */
343
+ const BSON_MAJOR = Reflect.get(new MinKey(), BSON_VERSION);
344
+ /** Whether a `bson` class instance comes from the same major version of `bson`, rather than being a look-alike or from another version. */
345
+ function createdByBsonMajor(value) {
346
+ return Reflect.get(value, BSON_VERSION) === BSON_MAJOR;
347
+ }
348
+ function bsonTypeTag(value) {
349
+ const tag = Reflect.get(value, "_bsontype");
350
+ return typeof tag === "string" ? tag : void 0;
351
+ }
352
+ /**
353
+ * The `_bsontype` tag of a `bson` class instance. A stored subdocument is read as a plain object even when it has a `_bsontype` key, so a plain object has no tag.
354
+ */
355
+ function bsonClassTag(value) {
356
+ return isPlainObject(value) ? void 0 : bsonTypeTag(value);
357
+ }
358
+ function constructorName(value) {
359
+ const name = Reflect.get(value, "constructor")?.name;
360
+ return typeof name === "string" && name !== "" ? name : "object";
361
+ }
362
+ /**
363
+ * The `bson` library reads any subdocument with a string `$ref` and an `$id` as a `DBRef`. It was stored as a plain object; these are its entries in stored order, `$ref`, `$id`, `$db` when present, then the other fields.
364
+ */
365
+ function dbRefEntries(value) {
366
+ const ref = blindCast(value);
367
+ const entries = [["$ref", ref.collection], ["$id", ref.oid]];
368
+ if (ref.db !== void 0) entries.push(["$db", ref.db]);
369
+ entries.push(...Object.entries(ref.fields));
370
+ return entries;
371
+ }
372
+ const BSON_VALUE_TAGS = /* @__PURE__ */ new Set([
373
+ "ObjectId",
374
+ "Long",
375
+ "Decimal128",
376
+ "Binary",
377
+ "BSONRegExp",
378
+ "Timestamp",
379
+ "Int32",
380
+ "Double",
381
+ "Code",
382
+ "MinKey",
383
+ "MaxKey",
384
+ "BSONSymbol"
385
+ ]);
386
+ const ENCODE_FIX_BY_RECEIVED = { DBRef: "Write it as a { $ref, $id } document instead." };
387
+ function encodeRefused(received, path) {
388
+ const fix = ENCODE_FIX_BY_RECEIVED[received];
389
+ throw mongoTargetError("RUNTIME.ENCODE_FAILED", `${MONGO_BSON_CODEC_ID} value must be a BSON value; received ${received} at ${where(path)}${fix === void 0 ? "" : `. ${fix}`}`, { meta: {
390
+ codecId: MONGO_BSON_CODEC_ID,
391
+ received,
392
+ valuePath: path
393
+ } });
394
+ }
395
+ function assertBsonValue(value, path, ancestors) {
396
+ if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number") return;
397
+ if (typeof value !== "object") {
398
+ encodeRefused(typeof value, path);
399
+ return;
400
+ }
401
+ const tag = bsonTypeTag(value);
402
+ if (tag !== void 0) {
403
+ if (!BSON_VALUE_TAGS.has(tag)) encodeRefused(tag, path);
404
+ if (!createdByBsonMajor(value)) encodeRefused(`${tag} not created by bson ${String(BSON_MAJOR)}`, path);
405
+ return;
406
+ }
407
+ if (value instanceof Date || value instanceof RegExp || value instanceof Uint8Array) return;
408
+ if (!isPlainArray(value) && !isPlainObject(value)) {
409
+ encodeRefused(constructorName(value), path);
410
+ return;
411
+ }
412
+ if (ancestors.has(value)) encodeRefused("circular reference", path);
413
+ ancestors.add(value);
414
+ if (Array.isArray(value)) for (let index = 0; index < value.length; index++) {
415
+ if (!(index in value)) encodeRefused("sparse array hole", child(path, index));
416
+ assertBsonValue(value[index], child(path, index), ancestors);
417
+ }
418
+ else for (const [key, entry] of Object.entries(value)) assertBsonValue(entry, child(path, key), ancestors);
419
+ ancestors.delete(value);
420
+ }
421
+ /**
422
+ * Returns `value` unchanged when it is a BSON value at every depth, and throws `RUNTIME.ENCODE_FAILED` naming the first value that is not, with its path.
423
+ */
424
+ function encodeBsonValue(value) {
425
+ assertBsonValue(value, "", /* @__PURE__ */ new Set());
426
+ return value;
427
+ }
428
+ /**
429
+ * A `Code` value with a scope, recognised by its tag: the driver reads with its own load of `bson`, so its `Code` is not an instance of the class imported here.
430
+ */
431
+ function codeWithScope(value) {
432
+ if (bsonClassTag(value) !== "Code") return void 0;
433
+ const code = Reflect.get(value, "code");
434
+ const scope = Reflect.get(value, "scope");
435
+ return typeof code === "string" && typeof scope === "object" && scope !== null ? {
436
+ code,
437
+ scope
438
+ } : void 0;
439
+ }
440
+ function decodeEntries(entries) {
441
+ return Object.fromEntries(entries.map(([key, entry]) => [key, decodeValue(entry)]));
442
+ }
443
+ function decodeValue(value) {
444
+ if (typeof value !== "object" || value === null) return value;
445
+ if (bsonClassTag(value) === "DBRef") return decodeEntries(dbRefEntries(value));
446
+ if (Array.isArray(value)) {
447
+ const decoded = value.map(decodeValue);
448
+ return decoded.some((entry, index) => entry !== value[index]) ? decoded : value;
449
+ }
450
+ const code = codeWithScope(value);
451
+ if (code !== void 0) {
452
+ const scope = decodeValue(code.scope);
453
+ return scope === code.scope ? value : new Code(code.code, blindCast(scope));
454
+ }
455
+ if (!isPlainObject(value)) return value;
456
+ const entries = Object.entries(value);
457
+ const decoded = decodeEntries(entries);
458
+ return entries.some(([key, entry]) => decoded[key] !== entry) ? decoded : value;
459
+ }
460
+ /**
461
+ * Returns the wire value as the driver produced it, except that a `DBRef` the `bson` library read from a `{ $ref, $id }` subdocument becomes that document again, `{ $ref, $id[, $db], ...fields }`, with its members' BSON types kept, at any depth and inside a `Code` scope. A value holding no `DBRef` is returned as the same object.
462
+ */
463
+ function decodeBsonValue(wire) {
464
+ return blindCast(decodeValue(wire));
465
+ }
466
+ function asDriverWrites(value) {
467
+ if (typeof value === "number") return Number.isInteger(value) && (value < INT32_RANGE.min || value > INT32_RANGE.max) ? new Double(value) : value;
468
+ if (typeof value !== "object" || value === null) return value;
469
+ if (value instanceof Uint8Array) return new Binary(value);
470
+ if (Array.isArray(value)) return value.map(asDriverWrites);
471
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, asDriverWrites(entry)]));
472
+ const code = codeWithScope(value);
473
+ if (code !== void 0) return new Code(code.code, blindCast(asDriverWrites(code.scope)));
474
+ return value;
475
+ }
476
+ /**
477
+ * Canonical Extended JSON for a BSON value, recording each JavaScript number and `Uint8Array` as the BSON type the driver writes for it: an integer outside the int32 range as a `double`, and bytes as `binData`.
478
+ */
479
+ function bsonToJson(value) {
480
+ return blindCast(EJSON.serialize(asDriverWrites(value), { relaxed: false }));
481
+ }
482
+ /**
483
+ * Reads the canonical Extended JSON `bsonToJson` writes. The `bson` reader also takes forms that are not canonical, some of them silently wrong (`{ "$numberInt": "abc" }` reads as 0), so a value that does not write back to the same JSON is refused, naming `owner`.
484
+ */
485
+ function readBsonJson(owner, json) {
486
+ let value;
487
+ try {
488
+ value = EJSON.deserialize(blindCast(json), { relaxed: false });
489
+ } catch {
490
+ return refuseJsonValue(owner, "canonical Extended JSON", json);
491
+ }
492
+ if (!isDeepStrictEqual(EJSON.serialize(value, { relaxed: false }), json)) return refuseJsonValue(owner, "canonical Extended JSON", json);
493
+ return value;
494
+ }
495
+ /** The vector's dimension: the TypeScript type `Vector<n>` and the type's reader read it. */
496
+ const mongoVectorParams = type({ "length?": "number.integer >= 1" });
497
+ /** Text as the ObjectId it names; {@link spellObjectIdJson} gives it the lower case the type stores. */
498
+ const asObjectId = (value) => {
499
+ if (typeof value !== "string") return refuseWrongShape(value, "text");
500
+ if (isObjectIdText(value)) return value;
501
+ throw structuredError("CONTRACT.CAST_REFUSED", `"${value}" is not an ObjectId: write 24 hexadecimal digits.`, {
502
+ why: "An ObjectId is 12 bytes, written as 24 hexadecimal digits.",
503
+ fix: "Write the ObjectId as 24 hexadecimal digits, as in \"507f1f77bcf86cd799439011\"."
504
+ });
505
+ };
506
+ /** The numbers of a written list as a vector stores them, each finite. */
507
+ function vectorElements(elements) {
508
+ return elements.map((element, index) => {
509
+ const number = Number(element);
510
+ if (Number.isFinite(number)) return number;
511
+ throw structuredError("CONTRACT.CAST_REFUSED", `a vector element is a finite number, and element ${index + 1} is ${String(element)}.`, {
512
+ why: "A vector holds finite numbers, as a vector search index reads them.",
513
+ fix: "Write each element as a finite number."
514
+ });
515
+ });
516
+ }
517
+ const mongoString = mongoDataType("mongo/string", {
518
+ read: (json) => readJsonString("mongo/string", json),
519
+ bsonTypes: ["string"]
520
+ });
521
+ const mongoInt32 = mongoDataType("mongo/int32", {
522
+ read: (json) => readInt32Json("mongo/int32", json),
523
+ bsonTypes: ["int"]
524
+ });
525
+ const mongoInt64 = mongoDataType("mongo/int64", {
526
+ read: (json) => readInt64Json("mongo/int64", json),
527
+ bsonTypes: ["long"],
528
+ casts: { [mongoInt32.id]: asNumeralText }
529
+ });
530
+ const mongoDecimal128 = mongoDataType("mongo/decimal128", {
531
+ read: (json) => readDecimal128Json("mongo/decimal128", json),
532
+ spell: spellDecimal128Json,
533
+ equalityKey: decimalTextEqualityKey,
534
+ bsonTypes: ["decimal"],
535
+ casts: {
536
+ [mongoInt32.id]: asNumeralText,
537
+ [mongoInt64.id]: castUnchanged
538
+ }
539
+ });
540
+ const mongoDouble = mongoDataType("mongo/double", {
541
+ read: (json) => {
542
+ readJsonFloat("mongo/double", json);
543
+ return json;
544
+ },
545
+ bsonTypes: ["double"],
546
+ casts: {
547
+ [mongoInt32.id]: asFloat,
548
+ [mongoInt64.id]: asFloat,
549
+ [mongoDecimal128.id]: asFloat
550
+ }
551
+ });
552
+ const mongoObjectId = mongoDataType("mongo/objectid", {
553
+ read: (json) => readObjectIdJson("mongo/objectid", json),
554
+ spell: spellObjectIdJson,
555
+ bsonTypes: ["objectId"],
556
+ casts: { [mongoString.id]: asObjectId }
557
+ });
558
+ const mongoBool = mongoDataType("mongo/bool", {
559
+ read: (json) => readJsonBoolean("mongo/bool", json),
560
+ bsonTypes: ["bool"]
561
+ });
562
+ const mongoDate = mongoDataType("mongo/date", {
563
+ read: (json) => readDateJson("mongo/date", json),
564
+ bsonTypes: ["date"]
565
+ });
566
+ const mongoVector = mongoDataType("mongo/vector", {
567
+ read: (json, params) => readVectorJson("mongo/vector", json, typeof params["length"] === "number" ? params["length"] : void 0),
568
+ bsonTypes: ["array"],
569
+ params: mongoVectorParams,
570
+ listCast: {
571
+ of: [
572
+ mongoInt32.id,
573
+ mongoInt64.id,
574
+ mongoDecimal128.id,
575
+ mongoDouble.id
576
+ ],
577
+ cast: vectorElements
578
+ }
579
+ });
580
+ const mongoBinary = mongoDataType("mongo/binary", {
581
+ read: (json) => readBinaryJson("mongo/binary", json),
582
+ spell: spellBase64Json,
583
+ bsonTypes: ["binData"]
584
+ });
585
+ const mongoJson = mongoDataType("mongo/json", {
586
+ read: (json) => json,
587
+ bsonTypes: [
588
+ "object",
589
+ "array",
590
+ "string",
591
+ "double",
592
+ "int",
593
+ "long",
594
+ "bool",
595
+ "null"
596
+ ]
597
+ });
598
+ const mongoBson = mongoDataType("mongo/bson", {
599
+ read: (json) => {
600
+ readBsonJson("mongo/bson", json);
601
+ return json;
602
+ },
603
+ bsonTypes: []
604
+ });
605
+ const mongoDataTypes = [
606
+ mongoObjectId,
607
+ mongoString,
608
+ mongoDouble,
609
+ mongoInt32,
610
+ mongoBool,
611
+ mongoDate,
612
+ mongoVector,
613
+ mongoInt64,
614
+ mongoDecimal128,
615
+ mongoBinary,
616
+ mongoJson,
617
+ mongoBson
618
+ ];
619
+ /** MongoDB's text data type: `string`. */
620
+ const mongoTextDataTypes = [mongoString.id];
621
+ //#endregion
622
+ export { where as $, isBase64Text as A, mongoInt32 as B, int64Decode as C, int64NumberFromDigits as D, int64NumberEncode as E, mongoBson as F, mongoTextDataTypes as G, mongoJson as H, mongoDataTypes as I, objectIdEncode as J, mongoVector as K, mongoDate as L, isPlainObject as M, mongoBinary as N, int64NumberToJson as O, mongoBool as P, vectorEncode as Q, mongoDecimal128 as R, int32ToJson as S, int64NumberDecode as T, mongoObjectId as U, mongoInt64 as V, mongoString as W, readBsonJson as X, objectIdToJson as Y, stringEncode as Z, decimal128ToJson as _, booleanEncode as a, encodeBsonValue as b, bsonTypeTag as c, dateEncode as d, dateToJson as f, decimal128HoldsExactly as g, decimal128Encode as h, binaryToBase64 as i, isPlainArray as j, int64ToJson as k, child as l, decimal128Decode as m, binaryEncode as n, bsonClassTag as o, dbRefEntries as p, mongoVectorParams as q, binaryFromBase64 as r, bsonToJson as s, binaryDecode as t, constructorName as u, decodeBsonValue as v, int64Encode as w, int32Encode as x, doubleEncode as y, mongoDouble as z };
623
+
624
+ //# sourceMappingURL=data-types-hoKLBrYZ-h9cAgbOy.mjs.map