@forestfuture/active-record 0.7.0 → 0.8.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 (33) hide show
  1. package/config-schema.json +6 -2
  2. package/dist/adapter.d.mts +3 -3
  3. package/dist/adapter.mjs +5 -4
  4. package/dist/batch-ReqVoCfa.mjs +9559 -0
  5. package/dist/cli.d.mts +55 -33
  6. package/dist/cli.mjs +4 -4
  7. package/dist/command.mjs +530 -271
  8. package/dist/d1.d.mts +2 -10
  9. package/dist/d1.mjs +0 -0
  10. package/dist/epoch-storage-CDlQZcBB.mjs +988 -0
  11. package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-B0xMP6Dq.d.mts} +8 -6
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-CfXMGeOu.mjs} +3 -5
  13. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-DhNV1mWf.mjs} +46 -10
  14. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-g5oWsDKE.mjs} +728 -540
  15. package/dist/index-BATasvJa.d.mts +241 -0
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.mjs +5 -4
  18. package/dist/metadata-CzntpYzC.d.mts +182 -0
  19. package/dist/{plugin-Cyoej7qV.mjs → plugin-wOSILvSB.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-x5-d3TSN.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-D56_3odT.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-n4w1cS_M.mjs} +61 -28
  25. package/dist/validations-DHDVV8hB.d.mts +1996 -0
  26. package/llms-full.txt +2354 -363
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +22 -14
  29. package/dist/adapter-AGKp6wfO.d.mts +0 -1326
  30. package/dist/batch-BS_WseLf.mjs +0 -4255
  31. package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
  32. package/dist/index-CyCJuM96.d.mts +0 -149
  33. package/dist/src-la_KkjCS.mjs +0 -1
@@ -0,0 +1,988 @@
1
+ // src/errors.ts
2
+ /** Base class for every error the library throws on purpose. */
3
+ var ActiveRecordError = class extends Error {
4
+ name = "ActiveRecordError";
5
+ };
6
+ /** A Model's declaration is invalid, e.g. an association's foreign key isn't an attribute. */
7
+ var InvalidModel = class extends ActiveRecordError {
8
+ name = "InvalidModel";
9
+ };
10
+ /** A key that isn't a declared attribute of the Model. */
11
+ var UnknownAttribute = class extends ActiveRecordError {
12
+ name = "UnknownAttribute";
13
+ };
14
+ /** A record constructed directly (`new User()`) was used for something that needs D1. */
15
+ var NoDatabase = class extends ActiveRecordError {
16
+ name = "NoDatabase";
17
+ };
18
+ /** No record matched a lookup that requires one (`find`, `findByOrThrow`, `sole`). */
19
+ var RecordNotFound = class extends ActiveRecordError {
20
+ name = "RecordNotFound";
21
+ };
22
+ /** `sole()` or `findSoleBy()` matched more than one record. */
23
+ var SoleRecordExceeded = class extends ActiveRecordError {
24
+ name = "SoleRecordExceeded";
25
+ };
26
+ /** Reading an attribute that wasn't loaded, e.g. one left out of `select(...)`. */
27
+ var MissingAttribute = class extends ActiveRecordError {
28
+ name = "MissingAttribute";
29
+ };
30
+ /** Destroying a record whose `dependent: "restrictWithException"` association still has records. */
31
+ var DeleteRestriction = class extends ActiveRecordError {
32
+ name = "DeleteRestriction";
33
+ };
34
+ /** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
35
+ var IrreversibleOrder = class extends ActiveRecordError {
36
+ name = "IrreversibleOrder";
37
+ };
38
+ /**
39
+ * Things that can't be combined: relations in `or`/`merge` (e.g. of different Models),
40
+ * `includes` or a write statement with `distinct()`, or statements of two Databases in a batch.
41
+ */
42
+ var IncompatibleRelation = class extends ActiveRecordError {
43
+ name = "IncompatibleRelation";
44
+ };
45
+ /** Using a destroyed record as a live one: `save`, `update`, `destroy` or `reload` after `destroy()`. */
46
+ var RecordDestroyed = class extends ActiveRecordError {
47
+ name = "RecordDestroyed";
48
+ };
49
+ /**
50
+ * D1 rejected a write because of a database constraint. `table`, `columns` and `attributes`
51
+ * are filled in when D1's message names them. `table` is null only for a batch writing to
52
+ * several tables, when D1 doesn't say which one failed. The original D1 error is the `cause`.
53
+ */
54
+ var ConstraintViolation = class extends ActiveRecordError {
55
+ name = "ConstraintViolation";
56
+ table;
57
+ columns;
58
+ attributes;
59
+ constructor(message, details) {
60
+ super(message, { cause: details.cause });
61
+ this.table = details.table;
62
+ this.columns = details.columns;
63
+ this.attributes = details.attributes;
64
+ }
65
+ };
66
+ /** A UNIQUE constraint failed, e.g. another request won the race after validation passed. */
67
+ var RecordNotUnique = class extends ConstraintViolation {
68
+ name = "RecordNotUnique";
69
+ };
70
+ /** A FOREIGN KEY constraint failed. SQLite's message doesn't name the column. */
71
+ var InvalidForeignKey = class extends ConstraintViolation {
72
+ name = "InvalidForeignKey";
73
+ };
74
+ /** A NOT NULL constraint failed. */
75
+ var NotNullViolation = class extends ConstraintViolation {
76
+ name = "NotNullViolation";
77
+ };
78
+ /** A CHECK constraint failed. */
79
+ var CheckViolation = class extends ConstraintViolation {
80
+ name = "CheckViolation";
81
+ };
82
+ /** A `…OrThrow` save was refused because the record is invalid; `record.errors` says why. */
83
+ var RecordInvalid = class extends ActiveRecordError {
84
+ name = "RecordInvalid";
85
+ record;
86
+ constructor(record) {
87
+ super(`Validation failed: ${record.errors.fullMessages().join(", ")}`);
88
+ this.record = record;
89
+ }
90
+ };
91
+ /**
92
+ * A rule declared with `strict: true` failed: thrown at once, with the failure's full message
93
+ * ("Email can't be blank"), instead of adding it to `record.errors`.
94
+ */
95
+ var StrictValidationFailed = class extends ActiveRecordError {
96
+ name = "StrictValidationFailed";
97
+ };
98
+ /**
99
+ * Thrown by a callback to refuse a save or destroy: `throw abort("Account is suspended")`.
100
+ * Only this exact class halts a lifecycle; returning `false` never does.
101
+ */
102
+ var CallbackAbort = class extends ActiveRecordError {
103
+ name = "CallbackAbort";
104
+ reason;
105
+ constructor(reason) {
106
+ super(reason);
107
+ this.reason = reason;
108
+ }
109
+ };
110
+ /** Makes the sentinel a pre-write callback throws to refuse: `throw abort("reason")`. */
111
+ function abort(reason = "Aborted by a callback") {
112
+ return new CallbackAbort(reason);
113
+ }
114
+ /** A `…OrThrow` save was refused by a callback's `abort(reason)`. */
115
+ var RecordNotSaved = class extends ActiveRecordError {
116
+ name = "RecordNotSaved";
117
+ };
118
+ /**
119
+ * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
120
+ * `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
121
+ */
122
+ var AbortAfterPersistence = class extends ActiveRecordError {
123
+ name = "AbortAfterPersistence";
124
+ callback;
125
+ reason;
126
+ constructor(callback, lifecycle, abortion) {
127
+ super(`abort() in ${callback}: the ${lifecycle} has already succeeded`, { cause: abortion });
128
+ this.callback = callback;
129
+ this.reason = abortion.reason;
130
+ }
131
+ };
132
+ /**
133
+ * A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)` or a
134
+ * `restrictWithError` association; or a `saveOrThrow()`, by a record it destroys (#37).
135
+ */
136
+ var RecordNotDestroyed = class extends ActiveRecordError {
137
+ name = "RecordNotDestroyed";
138
+ };
139
+ /** A name passed to `includes()` or `loaded()` that isn't one of the Model's associations. */
140
+ var UnknownAssociation = class extends ActiveRecordError {
141
+ name = "UnknownAssociation";
142
+ };
143
+ /**
144
+ * A write through an association that goes through another that it can't make (#434):
145
+ * inserting or upserting through it, or any write through one that doesn't go through a join
146
+ * Model (a source that isn't a belongsTo, a hop through a belongsTo, or a nested hop).
147
+ */
148
+ var ReadonlyAssociation = class extends ActiveRecordError {
149
+ name = "ReadonlyAssociation";
150
+ };
151
+ /**
152
+ * A polymorphic belongsTo's type that names none of the Models it lists (#60), read from the
153
+ * database, as Rails raises when it can't find the class a type names.
154
+ */
155
+ var UnknownModelName = class extends ActiveRecordError {
156
+ name = "UnknownModelName";
157
+ };
158
+ /** `record.loaded(name)` for an association that wasn't preloaded or read yet. */
159
+ var AssociationNotLoaded = class extends ActiveRecordError {
160
+ name = "AssociationNotLoaded";
161
+ };
162
+ // src/naming.ts
163
+ /**
164
+ * Converts a camelCase attribute name to its snake_case column name, treating
165
+ * a run of capitals as one word (Rails' `underscore`): `htmlURL` → `html_url`,
166
+ * `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
167
+ */
168
+ function underscore(name) {
169
+ return name.replace(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z\d])(?=[A-Z][a-z])/g, "_").toLowerCase();
170
+ }
171
+ /** A snake_case name as a camelCase attribute: `api_key` → `apiKey`. */
172
+ function camelize(name) {
173
+ return name.replace(/_([a-z\d])/g, (_, letter) => letter.toUpperCase());
174
+ }
175
+ // src/inflections.ts
176
+ /** Words whose plural no rule makes: singular, then plural. */
177
+ const IRREGULARS = [
178
+ ["person", "people"],
179
+ ["man", "men"],
180
+ ["child", "children"],
181
+ ["sex", "sexes"],
182
+ ["move", "moves"],
183
+ ["zombie", "zombies"]
184
+ ];
185
+ /** Plural rules in Rails' order of definition. The last one that matches wins, as in Rails. */
186
+ const PLURALS = [
187
+ [/$/, "s"],
188
+ [/s$/i, "s"],
189
+ [/^(ax|test)is$/i, "$1es"],
190
+ [/(octop|vir)us$/i, "$1i"],
191
+ [/(octop|vir)i$/i, "$1i"],
192
+ [/(alias|status)$/i, "$1es"],
193
+ [/(bu)s$/i, "$1ses"],
194
+ [/(buffal|tomat)o$/i, "$1oes"],
195
+ [/([ti])um$/i, "$1a"],
196
+ [/([ti])a$/i, "$1a"],
197
+ [/sis$/i, "ses"],
198
+ [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
199
+ [/(hive)$/i, "$1s"],
200
+ [/([^aeiouy]|qu)y$/i, "$1ies"],
201
+ [/(x|ch|ss|sh)$/i, "$1es"],
202
+ [/(matr|vert|ind)(?:ix|ex)$/i, "$1ices"],
203
+ [/^(m|l)ouse$/i, "$1ice"],
204
+ [/^(m|l)ice$/i, "$1ice"],
205
+ [/^(ox)$/i, "$1en"],
206
+ [/^(oxen)$/i, "$1"],
207
+ [/(quiz)$/i, "$1zes"],
208
+ ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, plural))
209
+ ];
210
+ /** Singular rules, likewise in Rails' order. */
211
+ const SINGULARS = [
212
+ [/s$/i, ""],
213
+ [/(ss)$/i, "$1"],
214
+ [/(n)ews$/i, "$1ews"],
215
+ [/([ti])a$/i, "$1um"],
216
+ [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, "$1sis"],
217
+ [/(^analy)(sis|ses)$/i, "$1sis"],
218
+ [/([^f])ves$/i, "$1fe"],
219
+ [/(hive)s$/i, "$1"],
220
+ [/(tive)s$/i, "$1"],
221
+ [/([lr])ves$/i, "$1f"],
222
+ [/([^aeiouy]|qu)ies$/i, "$1y"],
223
+ [/(s)eries$/i, "$1eries"],
224
+ [/(m)ovies$/i, "$1ovie"],
225
+ [/(x|ch|ss|sh)es$/i, "$1"],
226
+ [/^(m|l)ice$/i, "$1ouse"],
227
+ [/(bus)(es)?$/i, "$1"],
228
+ [/(o)es$/i, "$1"],
229
+ [/(shoe)s$/i, "$1"],
230
+ [/(cris|test)(is|es)$/i, "$1is"],
231
+ [/^(a)x[ie]s$/i, "$1xis"],
232
+ [/(octop|vir)(us|i)$/i, "$1us"],
233
+ [/(alias|status)(es)?$/i, "$1"],
234
+ [/^(ox)en/i, "$1"],
235
+ [/(vert|ind)ices$/i, "$1ex"],
236
+ [/(matr)ices$/i, "$1ix"],
237
+ [/(quiz)zes$/i, "$1"],
238
+ [/(database)s$/i, "$1"],
239
+ ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, singular))
240
+ ];
241
+ /** Words with no plural, matched as the last word (Rails' `\b<word>\z`). */
242
+ const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/i;
243
+ /**
244
+ * Rails' `irregular`: rules turning either form into `into` (the plural for plural rules, the
245
+ * singular for singular ones), keeping the first letter's case.
246
+ */
247
+ function irregular(singular, plural, into) {
248
+ return [[new RegExp(`(${singular[0]})${singular.slice(1)}$`, "i"), `$1${into.slice(1)}`], [new RegExp(`(${plural[0]})${plural.slice(1)}$`, "i"), `$1${into.slice(1)}`]];
249
+ }
250
+ /** Applies the last rule that matches, as Rails does; uncountable words stay as they are. */
251
+ function inflect(word, rules) {
252
+ if (word === "" || UNCOUNTABLE.test(word)) return word;
253
+ for (let index = rules.length - 1; index >= 0; index--) {
254
+ const [pattern, replacement] = rules[index];
255
+ if (pattern.test(word)) return word.replace(pattern, replacement);
256
+ }
257
+ return word;
258
+ }
259
+ /** Rails' `pluralize`: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
260
+ function pluralize(word) {
261
+ return inflect(word, PLURALS);
262
+ }
263
+ /** Rails' `singularize`: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
264
+ function singularize(word) {
265
+ return inflect(word, SINGULARS);
266
+ }
267
+ // src/enum-values.ts
268
+ /** Whether `value` is an enum's values: a list of names, or an object of names and stored values. */
269
+ function isEnumValues(value) {
270
+ if (Array.isArray(value)) return value.every((name) => typeof name === "string");
271
+ if (typeof value !== "object" || value === null) return false;
272
+ return Object.values(value).every((each) => typeof each === "string" || typeof each === "number");
273
+ }
274
+ /** Each name with the value it's stored as, in declaration order. */
275
+ function enumEntries(values) {
276
+ return Array.isArray(values) ? values.map((name) => [name, name]) : Object.entries(values);
277
+ }
278
+ /** The names as a message lists them: `"draft", "published"`. */
279
+ function listedNames(values) {
280
+ return enumEntries(values).map(([name]) => JSON.stringify(name)).join(", ");
281
+ }
282
+ /**
283
+ * What's wrong with `values` as the enum of an attribute of `type`, as the words that follow the
284
+ * attribute's name (`is "integer", so …`), or undefined. Past the types, so it checks the shape too.
285
+ */
286
+ function enumProblem(values, type) {
287
+ if (!isEnumValues(values)) return ` has ${typeof values === "boolean" ? `enum: ${values}, which only a generated Model's override gives, for the names its database lists` : `an enum ${JSON.stringify(values)}`}; give it a list of names, or an object of names and the values they're stored as`;
288
+ if (Array.isArray(values) && type !== "string") return ` is "${type}", so its enum gives each name the integer it's stored as, not a list of names`;
289
+ const entries = enumEntries(values);
290
+ if (entries.length === 0) return " has an enum with no names; give it at least one";
291
+ return storedTypeProblem(entries, type) ?? repeatProblem(entries);
292
+ }
293
+ /** A stored value that isn't of the attribute's type: text for a string, a safe integer for an integer. */
294
+ function storedTypeProblem(entries, type) {
295
+ const fits = type === "string" ? isText : Number.isSafeInteger;
296
+ const wrong = entries.find(([, stored]) => !fits(stored));
297
+ if (wrong === void 0) return void 0;
298
+ return ` is "${type}", so its enum stores ${type === "string" ? "text" : "integers"}, not ${JSON.stringify(wrong[1])} for "${wrong[0]}"`;
299
+ }
300
+ const isText = (value) => typeof value === "string";
301
+ /** A name given twice, or a value two names are stored as: a stored cell would read as either. */
302
+ function repeatProblem(entries) {
303
+ const names = /* @__PURE__ */ new Set();
304
+ const stored = /* @__PURE__ */ new Map();
305
+ for (const [name, value] of entries) {
306
+ if (names.has(name)) return `'s enum names "${name}" twice`;
307
+ const other = stored.get(value);
308
+ if (other !== void 0) return `'s enum stores ${JSON.stringify(value)} for both "${other}" and "${name}"`;
309
+ names.add(name);
310
+ stored.set(value, name);
311
+ }
312
+ }
313
+ /**
314
+ * The validations an enum declared `validate: true` adds, before a Model's own: its value must be
315
+ * one of its names, and not null unless `allowNull`, as Rails' `validate: true` adds them.
316
+ */
317
+ function enumValidations(definitions) {
318
+ return [...definitions].flatMap(([attribute, { enum: values, validate = false }]) => {
319
+ if (values === void 0 || validate === false) return [];
320
+ const allowNull = validate !== true && validate.allowNull === true;
321
+ return [{
322
+ attribute,
323
+ options: {
324
+ inclusion: enumEntries(values).map(([name]) => name),
325
+ allowNull
326
+ }
327
+ }];
328
+ });
329
+ }
330
+ /** Each enum's mapping, made once: `enumValues` gives the same frozen object each time. */
331
+ const mappings = /* @__PURE__ */ new WeakMap();
332
+ /** An enum's names and the value each is stored as, frozen: `{ draft: "draft" }`, `{ low: 0 }`. */
333
+ function mappingOf(values) {
334
+ let mapping = mappings.get(values);
335
+ if (mapping === void 0) {
336
+ mapping = Object.freeze(Object.fromEntries(enumEntries(values)));
337
+ mappings.set(values, mapping);
338
+ }
339
+ return mapping;
340
+ }
341
+ /** `model`'s enum `attribute`'s mapping, or `UnknownAttribute` for a name that isn't an enum's. */
342
+ function enumValuesOf(model, attribute) {
343
+ const values = model.attributeDefinitions.get(attribute)?.enum;
344
+ if (values === void 0) throw new UnknownAttribute(`${model.name} has no enum attribute "${attribute}"`);
345
+ return mappingOf(values);
346
+ }
347
+ // src/identifiers.ts
348
+ /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
349
+ function isIdentifier(name) {
350
+ return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
351
+ }
352
+ /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
353
+ const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
354
+ // src/binary-values.ts
355
+ /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
356
+ function castBinary(value) {
357
+ if (value instanceof Uint8Array) return value;
358
+ return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
359
+ }
360
+ /**
361
+ * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
362
+ * a `bytea` as a `Buffer`.
363
+ */
364
+ function readBinary(cell) {
365
+ if (cell instanceof Uint8Array) return Uint8Array.from(cell);
366
+ return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
367
+ }
368
+ /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
369
+ function isSameCell(a, b) {
370
+ if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
371
+ return a.length === b.length && a.every((byte, index) => byte === b[index]);
372
+ }
373
+ /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
374
+ const digitCodes = new TextEncoder().encode("0123456789abcdef");
375
+ const decoder = new TextDecoder();
376
+ /**
377
+ * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
378
+ * digits' character codes are written into one array and decoded once: mapping each byte to a
379
+ * string of its own takes many times the memory and time, which a large file can't afford.
380
+ */
381
+ function hexOf(bytes) {
382
+ const text = new Uint8Array(bytes.length * 2);
383
+ for (let index = 0; index < bytes.length; index++) {
384
+ const byte = bytes[index];
385
+ text[index * 2] = digitCodes[byte >> 4];
386
+ text[index * 2 + 1] = digitCodes[byte & 15];
387
+ }
388
+ return decoder.decode(text);
389
+ }
390
+ // src/calendar-values.ts
391
+ /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
392
+ const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
393
+ /**
394
+ * Text naming a day that exists (`"2026-01-02"`), as it is; anything else, a `Date` included
395
+ * (its day depends on the time zone), is `uncastable`. Each database returns a day as this text.
396
+ */
397
+ function castDay(value) {
398
+ if (typeof value !== "string") return uncastable;
399
+ const match = dayText.exec(value);
400
+ if (match === null) return uncastable;
401
+ const [, year, month, day] = match.map(Number);
402
+ const date = /* @__PURE__ */ new Date(0);
403
+ date.setUTCFullYear(year, month - 1, day);
404
+ return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? value : uncastable;
405
+ }
406
+ /** A time of day: hours and minutes, then optionally seconds and up to six digits of a fraction. */
407
+ const timeText = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?$/;
408
+ /** The end of a day, which Postgres's `time` holds as `24:00:00`, with no time past it. */
409
+ const endOfDay = /^24:00(?::00(?:\.0{1,6})?)?$/;
410
+ /**
411
+ * Text naming a time of day (`"09:30"`, `"09:30:15.5"`) in its one form, as Postgres writes a
412
+ * `time`: seconds always, a fraction without trailing zeros (`"09:30:00"`, `"09:30:15.5"`). The
413
+ * end of the day is `"24:00:00"`. Anything else, a `Date` included, is `uncastable`.
414
+ */
415
+ function castTime(value) {
416
+ if (typeof value !== "string") return uncastable;
417
+ if (endOfDay.test(value)) return "24:00:00";
418
+ const match = timeText.exec(value);
419
+ if (match === null) return uncastable;
420
+ const [, hours, minutes, seconds = "00", fraction = ""] = match;
421
+ const digits = withoutTrailingZeros(fraction);
422
+ return `${hours}:${minutes}:${seconds}${digits === "" ? "" : `.${digits}`}`;
423
+ }
424
+ /** `digits` without the zeros it ends with, found by a loop rather than an unanchored `0+$`. */
425
+ function withoutTrailingZeros(digits) {
426
+ let end = digits.length;
427
+ while (digits[end - 1] === "0") end--;
428
+ return digits.slice(0, end);
429
+ }
430
+ // src/conversion.ts
431
+ /** A value that can't be read as the attribute's type. */
432
+ const uncastable = Symbol("uncastable");
433
+ const identity = (value) => value;
434
+ const keyOf = ({ type, storage }) => storage ?? type;
435
+ const converters = {
436
+ string: {
437
+ cast: text,
438
+ read: text,
439
+ write: identity
440
+ },
441
+ integer: {
442
+ cast: castInteger,
443
+ read: safeInteger,
444
+ write: identity
445
+ },
446
+ real: {
447
+ cast: castReal,
448
+ read: finiteNumber,
449
+ write: identity
450
+ },
451
+ boolean: {
452
+ cast: castBoolean,
453
+ read: readBoolean,
454
+ write: (value) => value ? 1 : 0
455
+ },
456
+ datetime: {
457
+ cast: castDatetime,
458
+ read: readDatetime,
459
+ write: (value) => value.toISOString()
460
+ },
461
+ unixSeconds: {
462
+ cast: castDatetime,
463
+ read: unixTime(1e3),
464
+ write: (value) => Math.floor(value.getTime() / 1e3)
465
+ },
466
+ unixMilliseconds: {
467
+ cast: castDatetime,
468
+ read: unixTime(1),
469
+ write: (value) => value.getTime()
470
+ },
471
+ json: {
472
+ cast: castJson,
473
+ read: readJson,
474
+ write: (value) => JSON.stringify(value)
475
+ },
476
+ binary: {
477
+ cast: castBinary,
478
+ read: readBinary,
479
+ write: (value) => Uint8Array.from(value)
480
+ },
481
+ date: {
482
+ cast: castDay,
483
+ read: castDay,
484
+ write: identity
485
+ },
486
+ time: {
487
+ cast: castTime,
488
+ read: castTime,
489
+ write: identity
490
+ },
491
+ decimal: {
492
+ cast: castDecimal,
493
+ read: readDecimal,
494
+ write: identity
495
+ }
496
+ };
497
+ /** Each enum's converter, over the converter of the type its values are stored as. */
498
+ const enumConverters = /* @__PURE__ */ new WeakMap();
499
+ /** Each custom type's converter, over the converter of the type it's stored as (#20). */
500
+ const customConverters = /* @__PURE__ */ new WeakMap();
501
+ /**
502
+ * The converter for an attribute: its type's (or storage's), or for an enum or a custom type, one
503
+ * over it.
504
+ */
505
+ function converterOf(attribute) {
506
+ const stored = converters[keyOf(attribute)];
507
+ if (attribute.customType !== void 0) return customConverterOf(attribute.customType, stored);
508
+ if (attribute.type === "decimal" && hasDigits(attribute)) return limitedDecimalConverter(attribute);
509
+ if (attribute.enum === void 0) return stored;
510
+ let byType = enumConverters.get(attribute.enum);
511
+ if (byType === void 0) {
512
+ byType = /* @__PURE__ */ new Map();
513
+ enumConverters.set(attribute.enum, byType);
514
+ }
515
+ let converter = byType.get(stored);
516
+ if (converter === void 0) {
517
+ converter = enumConverter(attribute.enum, stored);
518
+ byType.set(stored, converter);
519
+ }
520
+ return converter;
521
+ }
522
+ /** Whether a decimal has a precision or a scale to round and limit it by (#398). */
523
+ function hasDigits({ precision, scale }) {
524
+ return precision !== void 0 || scale !== void 0;
525
+ }
526
+ /** Each precision and scale's decimal converter, by `"precision/scale"` (#398). */
527
+ const limitedDecimalConverters = /* @__PURE__ */ new Map();
528
+ /** A decimal's converter that rounds a cast value to its scale and refuses one past its precision. */
529
+ function limitedDecimalConverter({ precision, scale }) {
530
+ const key = `${precision}/${scale}`;
531
+ let converter = limitedDecimalConverters.get(key);
532
+ if (converter === void 0) {
533
+ const cast = (value) => {
534
+ const decimal = castDecimal(value);
535
+ return decimal === uncastable ? decimal : limitDecimal(decimal, {
536
+ precision,
537
+ scale
538
+ });
539
+ };
540
+ converter = {
541
+ ...converters.decimal,
542
+ cast
543
+ };
544
+ limitedDecimalConverters.set(key, converter);
545
+ }
546
+ return converter;
547
+ }
548
+ function customConverterOf(type, stored) {
549
+ let converter = customConverters.get(type);
550
+ if (converter === void 0) {
551
+ converter = customConverter(type, stored);
552
+ customConverters.set(type, converter);
553
+ }
554
+ return converter;
555
+ }
556
+ /**
557
+ * A custom type's values (#20): cast by the type, and kept as the stored type's. What the type's
558
+ * `serialize` gives is cast as the stored type's value, so it can't store what that type
559
+ * couldn't hold; a cell is read strictly as the stored type's, then by `deserialize`. The type's
560
+ * own errors are thrown as they are, for `Attribute` to name its attribute and keep them as the
561
+ * cause.
562
+ */
563
+ function customConverter(type, stored) {
564
+ return {
565
+ cast: (value) => type.cast(value),
566
+ read: (cell) => {
567
+ const value = stored.read(cell);
568
+ return value === uncastable ? uncastable : type.deserialize(value);
569
+ },
570
+ write: (value) => {
571
+ const serialized = stored.cast(type.serialize(value));
572
+ if (serialized === uncastable) throw new TypeError("serialize gave a value its stored type can't hold");
573
+ return stored.write(serialized);
574
+ }
575
+ };
576
+ }
577
+ /**
578
+ * An enum's values are its names (#340). A name is cast as itself, and so is the value it's
579
+ * stored as (`1`, or `"1"` from a form), as Rails accepts; anything else is `uncastable`. A stored
580
+ * cell of its type that's none of its values reads as null, as Rails reads it, so a row written
581
+ * by code that lists a newer value doesn't fail every list it's in; one of another type is
582
+ * `uncastable`, as for any attribute of that type (#159).
583
+ */
584
+ function enumConverter(values, stored) {
585
+ const entries = enumEntries(values);
586
+ const storedValues = new Map(entries);
587
+ const names = new Map(entries.map(([name, value]) => [value, name]));
588
+ return {
589
+ cast: (value) => typeof value === "string" && storedValues.has(value) ? value : names.get(stored.cast(value)) ?? uncastable,
590
+ read: (cell) => {
591
+ const value = stored.read(cell);
592
+ return value === uncastable ? uncastable : names.get(value) ?? null;
593
+ },
594
+ write: (name) => storedValues.get(name)
595
+ };
596
+ }
597
+ /** `value` as the attribute's type (null stays null), or `uncastable`. */
598
+ function castValue(attribute, value) {
599
+ return value === null ? null : converterOf(attribute).cast(value);
600
+ }
601
+ /**
602
+ * A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
603
+ * finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
604
+ * for a text key and as Rails does, so a foreign key of another type still finds its target.
605
+ */
606
+ function castCondition(attribute, value) {
607
+ return castKey(withoutPrecision(attribute), value);
608
+ }
609
+ /**
610
+ * A key's value (copied from another record, or inherited from a Relation's conditions) as the
611
+ * attribute's type, or `uncastable`: as a condition's, but past a decimal's precision it's
612
+ * refused, as it will be held as an assigned value is (#398).
613
+ */
614
+ function castKey(attribute, value) {
615
+ if (attribute.customType !== void 0) return castOrUncastable(attribute, value);
616
+ if (attribute.type === "string" && typeof value === "number" && Number.isFinite(value)) return attribute.enum === void 0 ? String(value) : castValue(attribute, String(value));
617
+ return castValue(attribute, value);
618
+ }
619
+ /**
620
+ * A decimal as a condition reads it: rounded to its scale (0 for a precision alone), but not
621
+ * refused past its precision, so `lt("1e9")` still compares (#398). No stored value is past it,
622
+ * so an equal one matches nothing anyway.
623
+ */
624
+ function withoutPrecision(attribute) {
625
+ if (attribute.precision === void 0) return attribute;
626
+ return {
627
+ ...attribute,
628
+ precision: void 0,
629
+ scale: attribute.scale ?? 0
630
+ };
631
+ }
632
+ /** `value` cast by a custom type, or `uncastable` where the type throws. */
633
+ function castOrUncastable(attribute, value) {
634
+ try {
635
+ return castValue(attribute, value);
636
+ } catch {
637
+ return uncastable;
638
+ }
639
+ }
640
+ /**
641
+ * A stored value as the attribute's, or `uncastable` for one that isn't. `Attribute#read`, in
642
+ * attribute.ts, is how a cell D1 returned is read, so it fails naming its attribute.
643
+ */
644
+ function readValue(attribute, value) {
645
+ return value === null || value === void 0 ? null : converterOf(attribute).read(value);
646
+ }
647
+ function writeValue(attribute, value) {
648
+ return value === null || value === void 0 ? null : converterOf(attribute).write(value);
649
+ }
650
+ /**
651
+ * Converts a value with no declared attribute type (e.g. one interpolated into
652
+ * an `sql` fragment) using the converter its runtime type implies, so it's
653
+ * stored the same way as an attribute of that type.
654
+ */
655
+ function writeUntypedValue(value) {
656
+ if (value instanceof Date) return writeValue({ type: "datetime" }, value);
657
+ if (typeof value === "boolean") return writeValue({ type: "boolean" }, value);
658
+ return value;
659
+ }
660
+ const booleans = /* @__PURE__ */ new Map([
661
+ [true, true],
662
+ [false, false],
663
+ [1, true],
664
+ [0, false],
665
+ ["1", true],
666
+ ["0", false],
667
+ ["true", true],
668
+ ["false", false],
669
+ ["on", true],
670
+ ["off", false]
671
+ ]);
672
+ /** `true`/`false`, `1`/`0`, `"1"`/`"0"`, and `"true"`/`"false"` or `"on"`/`"off"` in any case. */
673
+ function castBoolean(value) {
674
+ const key = typeof value === "string" ? value.toLowerCase() : value;
675
+ return booleans.has(key) ? booleans.get(key) : uncastable;
676
+ }
677
+ /**
678
+ * Any value JSON can write, as it is. What `stringify` writes lossily (a `Map` as `{}`, `NaN` as
679
+ * `null`) is kept; what it throws on (a BigInt, a cycle) or gives nothing for (a function, a
680
+ * symbol) is refused (#146). It's checked here, and written again at save, so a value is
681
+ * refused where it's assigned rather than where it's stored, and the cost is one more
682
+ * `stringify` per assignment.
683
+ */
684
+ function castJson(value) {
685
+ try {
686
+ return JSON.stringify(value) === void 0 ? uncastable : value;
687
+ } catch {
688
+ return uncastable;
689
+ }
690
+ }
691
+ /**
692
+ * Text is parsed; one that isn't JSON is `uncastable`. Under a column declared JSON, SQLite
693
+ * stores a number-like value (123) as a number, and D1 returns it as one, which is already the
694
+ * value.
695
+ */
696
+ function readJson(value) {
697
+ if (typeof value !== "string") return value;
698
+ try {
699
+ return JSON.parse(value);
700
+ } catch {
701
+ return uncastable;
702
+ }
703
+ }
704
+ /** A whole number, signed, with nothing else but spaces around it. */
705
+ const integerText = /^\s*[+-]?\d+\s*$/;
706
+ /**
707
+ * A decimal number, with an optional exponent (`1.5`, `-2e3`, `.5`), and spaces around it.
708
+ * Digits after the point only follow a point, so no run of digits can match two ways: an
709
+ * optional point between two runs of digits backtracks quadratically on a long string (ReDoS).
710
+ */
711
+ const realText = /^\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?\s*$/i;
712
+ /** `value` as a number: a number as it is, or a string matching `pattern`; else `uncastable`. */
713
+ function numberFrom(value, pattern) {
714
+ if (typeof value === "number") return value;
715
+ return typeof value === "string" && pattern.test(value) ? Number(value) : uncastable;
716
+ }
717
+ /** `value` if it's text, else `uncastable`. */
718
+ function text(value) {
719
+ return typeof value === "string" ? value : uncastable;
720
+ }
721
+ /** `value` if it's a safe integer, else `uncastable`. */
722
+ function safeInteger(value) {
723
+ return Number.isSafeInteger(value) ? value : uncastable;
724
+ }
725
+ /** `value` if it's a finite number, else `uncastable`. */
726
+ function finiteNumber(value) {
727
+ return Number.isFinite(value) ? value : uncastable;
728
+ }
729
+ /** A safe integer, or a string that's wholly one: `1.7`, `"12abc"` and `"1e3"` aren't. */
730
+ function castInteger(value) {
731
+ return safeInteger(numberFrom(value, integerText));
732
+ }
733
+ /** A finite number, or a string that's wholly a decimal number. */
734
+ function castReal(value) {
735
+ return finiteNumber(numberFrom(value, realText));
736
+ }
737
+ /** A Unix time of this many milliseconds per unit as a `Date`; anything but a number is `uncastable`. */
738
+ function unixTime(millisecondsPer) {
739
+ return (value) => typeof value === "number" ? validDate(new Date(value * millisecondsPer)) : uncastable;
740
+ }
741
+ /** An ISO-8601 date: `2026-01-02`, read as midnight UTC. */
742
+ const isoDate = /^(\d{4})-(\d{2})-(\d{2})$/;
743
+ /** An ISO-8601 date and time, with `Z` or an offset: a time without one is ambiguous. */
744
+ const isoDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
745
+ /** A stored date and time with no zone, as SQLite's `CURRENT_TIMESTAMP` writes it: UTC (#73). */
746
+ const zonelessDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
747
+ /** What `toISOString` writes, the form datetimes are stored in: `2026-01-02T03:04:05.678Z`. */
748
+ const isoStringForm = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
749
+ /** What `toISOString` writes for a year outside 0000-9999: a sign and six digits (`+010000-…`). */
750
+ const expandedYearDateTime = /^[+-]\d{6}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
751
+ /**
752
+ * A stored datetime as a `Date`: text in a form an assignment accepts (an ISO date, or a date and
753
+ * time with its offset), what `toISOString` writes for a far year, or SQLite's own, with no
754
+ * zone, which is UTC, where `new Date` would read it in the process's time zone. A number isn't
755
+ * one: it's a Unix time (#73), and read as a time in ISO text it would be a moment in January
756
+ * 1970 (#159).
757
+ */
758
+ function readDatetime(value) {
759
+ if (typeof value !== "string") return uncastable;
760
+ const stored = isoStringForm.test(value) ? dateIfOnCalendar(value) : void 0;
761
+ if (stored !== void 0) return stored;
762
+ if (expandedYearDateTime.test(value)) return dateIfCanonical(value) ?? uncastable;
763
+ return castDatetime(zonelessDateTime.test(value) ? `${value}Z` : value);
764
+ }
765
+ /**
766
+ * Text in the stored form as a `Date`, if it names a moment on the calendar. `value` must match
767
+ * `isoStringForm`, which fixes where the month and day are. Every character is then a digit or a
768
+ * fixed separator, so only the calendar can be wrong, and `Date` rolls a day that
769
+ * doesn't exist over (`2026-02-30` to 2 March, `T24:00` to the next day): a date whose day or
770
+ * month isn't the text's is refused. Cheaper than writing the text back to compare (#216).
771
+ */
772
+ function dateIfOnCalendar(value) {
773
+ const date = new Date(value);
774
+ const month = Number(value.slice(5, 7));
775
+ const day = Number(value.slice(8, 10));
776
+ return date.getUTCDate() === day && date.getUTCMonth() + 1 === month ? date : void 0;
777
+ }
778
+ /**
779
+ * `value` as a `Date`, if `toISOString` writes exactly this text for it. That also refuses a day
780
+ * that doesn't exist, and a year written with more digits than it needs (`+002026`).
781
+ */
782
+ function dateIfCanonical(value) {
783
+ const date = new Date(value);
784
+ return !isInvalidDate(date) && date.toISOString() === value ? date : void 0;
785
+ }
786
+ /** `1` and `0` are the stored form of a boolean; any other cell isn't one. */
787
+ function readBoolean(value) {
788
+ if (value === 1) return true;
789
+ return value === 0 ? false : uncastable;
790
+ }
791
+ /** A valid `Date`, or an ISO-8601 string (a date, or a date and time with its offset). */
792
+ function castDatetime(value) {
793
+ if (value instanceof Date) return isInvalidDate(value) ? uncastable : value;
794
+ if (typeof value !== "string") return uncastable;
795
+ if (isoDate.test(value)) return dayOf(value) ?? uncastable;
796
+ if (!isoDateTime.test(value) || dayOf(value.slice(0, 10)) === void 0) return uncastable;
797
+ const date = new Date(value.replace(" ", "T"));
798
+ return isInvalidDate(date) ? uncastable : date;
799
+ }
800
+ /** `date`, or `uncastable` for an invalid one (a stored number past the range of a `Date`). */
801
+ function validDate(date) {
802
+ return isInvalidDate(date) ? uncastable : date;
803
+ }
804
+ /** Midnight UTC on `day` (`2026-01-02`), if that day exists. */
805
+ function dayOf(day) {
806
+ const date = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
807
+ return !isInvalidDate(date) && date.toISOString().startsWith(day) ? date : void 0;
808
+ }
809
+ function isInvalidDate(value) {
810
+ return value instanceof Date && Number.isNaN(value.getTime());
811
+ }
812
+ // src/decimal-values.ts
813
+ /**
814
+ * A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
815
+ * exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
816
+ * can match two ways (ReDoS).
817
+ */
818
+ const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
819
+ /** The most digits Postgres's `numeric` holds before its point, and after it. */
820
+ const maxWholeDigits = 131072;
821
+ const maxFractionDigits = 16383;
822
+ /**
823
+ * The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
824
+ * point, an exponent and spaces. Longer text is refused before it's read.
825
+ */
826
+ const maxTextLength = 147519;
827
+ /** A number's significant digits when it's cast, as Rails casts a float to a decimal. */
828
+ const numberPrecision = 16;
829
+ /**
830
+ * An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
831
+ * 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
832
+ * Postgres's `numeric` holds, is `uncastable`.
833
+ */
834
+ function castDecimal(value) {
835
+ if (typeof value === "bigint") return canonical(String(value));
836
+ if (typeof value === "number") return castNumber(value);
837
+ return typeof value === "string" ? canonical(value) : uncastable;
838
+ }
839
+ /**
840
+ * A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
841
+ * cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
842
+ * significant digits, a whole number past a safe integer too, as Rails reads one on SQLite.
843
+ */
844
+ function readDecimal(cell) {
845
+ if (typeof cell === "number") return castNumber(cell);
846
+ return typeof cell === "string" ? canonical(cell) : uncastable;
847
+ }
848
+ function castNumber(value) {
849
+ if (!Number.isFinite(value)) return uncastable;
850
+ const decimal = canonical(value.toPrecision(numberPrecision));
851
+ return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
852
+ }
853
+ /**
854
+ * Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
855
+ * no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
856
+ */
857
+ function canonical(text) {
858
+ const parts = partsOf(text);
859
+ if (parts === void 0) return uncastable;
860
+ const { negative, digits, point } = parts;
861
+ const first = digits.search(/[1-9]/);
862
+ if (first === -1) return "0";
863
+ const last = lastNonZero(digits) + 1;
864
+ if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
865
+ const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
866
+ return isWithinDouble(decimal) ? decimal : uncastable;
867
+ }
868
+ /**
869
+ * Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
870
+ * underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
871
+ * which reads as NULL, or as 0, so every database refuses one alike (#391).
872
+ */
873
+ function isWithinDouble(decimal) {
874
+ const number = Number(decimal);
875
+ return Number.isFinite(number) && number !== 0;
876
+ }
877
+ /** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
878
+ function partsOf(text) {
879
+ if (text.length > maxTextLength) return void 0;
880
+ const match = decimalText.exec(text);
881
+ if (match === null) return void 0;
882
+ const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
883
+ return {
884
+ negative: sign === "-",
885
+ digits: whole + (pointed ?? unpointed ?? ""),
886
+ point: whole.length + Number(exponent)
887
+ };
888
+ }
889
+ /**
890
+ * Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
891
+ * on a long run of zeros it takes quadratic time.
892
+ */
893
+ function lastNonZero(digits) {
894
+ let index = digits.length - 1;
895
+ while (digits[index] === "0") index--;
896
+ return index;
897
+ }
898
+ /** Significant `digits` with the point `point` digits after the first, padded with zeros. */
899
+ function placePoint(digits, point) {
900
+ if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
901
+ if (point >= digits.length) return digits + "0".repeat(point - digits.length);
902
+ return `${digits.slice(0, point)}.${digits.slice(point)}`;
903
+ }
904
+ /**
905
+ * Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
906
+ * by the digits before the point (more is larger), then digit by digit, which is exact.
907
+ */
908
+ function compareDecimals(a, b) {
909
+ const [signA, signB] = [signOf(a), signOf(b)];
910
+ if (signA !== signB) return Math.sign(signA - signB);
911
+ const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
912
+ return signA < 0 ? -order : order;
913
+ }
914
+ function signOf(decimal) {
915
+ if (decimal === "0") return 0;
916
+ return decimal.startsWith("-") ? -1 : 1;
917
+ }
918
+ function compareMagnitudes(a, b) {
919
+ const [wholeA = "", fractionA = ""] = a.split(".");
920
+ const [wholeB = "", fractionB = ""] = b.split(".");
921
+ if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
922
+ const width = Math.max(fractionA.length, fractionB.length);
923
+ const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
924
+ if (left === right) return 0;
925
+ return left < right ? -1 : 1;
926
+ }
927
+ /**
928
+ * Where a decimal falls against a bound given as a number or decimal text: exactly, as
929
+ * `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
930
+ * every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
931
+ */
932
+ function orderDecimal(value, bound) {
933
+ if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
934
+ const decimal = castDecimal(bound);
935
+ return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
936
+ }
937
+ /** The most digits Postgres's `numeric` takes as a precision or a scale. */
938
+ const maxDigits = 1e3;
939
+ /** Whether `value` is a whole number of digits from `least` to 1000. */
940
+ function isDigitCount(value, least) {
941
+ return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
942
+ }
943
+ /**
944
+ * Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
945
+ * a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
946
+ * the generators all check it here (#398).
947
+ */
948
+ function digitsProblem({ precision, scale }) {
949
+ if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
950
+ if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
951
+ if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
952
+ return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
953
+ }
954
+ /**
955
+ * A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
956
+ * and Rails round; `uncastable` when its digits before the point are more than the precision
957
+ * leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
958
+ */
959
+ function limitDecimal(decimal, { precision, scale }) {
960
+ const places = scale ?? (precision === void 0 ? void 0 : 0);
961
+ const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
962
+ if (precision === void 0 || rounded === uncastable) return rounded;
963
+ const whole = rounded.replace("-", "").split(".")[0];
964
+ return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
965
+ }
966
+ /**
967
+ * A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
968
+ * `uncastable` when rounding carries it past a double's range.
969
+ */
970
+ function roundDecimal(decimal, places) {
971
+ const negative = decimal.startsWith("-");
972
+ const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
973
+ if (fraction.length <= places) return decimal;
974
+ const kept = whole + fraction.slice(0, places);
975
+ const digits = fraction[places] >= "5" ? incremented(kept) : kept;
976
+ const point = digits.length - places;
977
+ return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
978
+ }
979
+ /** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
980
+ function incremented(digits) {
981
+ let index = digits.length - 1;
982
+ while (index >= 0 && digits[index] === "9") index--;
983
+ return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
984
+ }
985
+ // src/epoch-storage.ts
986
+ /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
987
+ const epochStorages = ["unixSeconds", "unixMilliseconds"];
988
+ export { abort as $, CallbackAbort as A, NotNullViolation as B, pluralize as C, AbortAfterPersistence as D, underscore as E, InvalidForeignKey as F, RecordNotFound as G, RecordDestroyed as H, InvalidModel as I, SoleRecordExceeded as J, RecordNotSaved as K, IrreversibleOrder as L, ConstraintViolation as M, DeleteRestriction as N, ActiveRecordError as O, IncompatibleRelation as P, UnknownModelName as Q, MissingAttribute as R, listedNames as S, camelize as T, RecordInvalid as U, ReadonlyAssociation as V, RecordNotDestroyed as W, UnknownAssociation as X, StrictValidationFailed as Y, UnknownAttribute as Z, enumEntries as _, castKey as a, enumValuesOf as b, readValue as c, writeValue as d, zonelessDateTime as f, reservedWords as g, isIdentifier as h, castCondition as i, CheckViolation as j, AssociationNotLoaded as k, uncastable as l, isSameCell as m, digitsProblem as n, castValue as o, hexOf as p, RecordNotUnique as q, orderDecimal as r, isInvalidDate as s, epochStorages as t, writeUntypedValue as u, enumProblem as v, singularize as w, isEnumValues as x, enumValidations as y, NoDatabase as z };