@forestfuture/active-record 0.8.2 → 0.9.1

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.
@@ -19,6 +19,13 @@ var NoDatabase = class extends ActiveRecordError {
19
19
  var RecordNotFound = class extends ActiveRecordError {
20
20
  name = "RecordNotFound";
21
21
  };
22
+ /**
23
+ * A token a finder that must find a record was given isn't valid (#517): it was changed, signed
24
+ * with another secret, made for another purpose, or has expired.
25
+ */
26
+ var InvalidToken = class extends ActiveRecordError {
27
+ name = "InvalidToken";
28
+ };
22
29
  /** `sole()` or `findSoleBy()` matched more than one record. */
23
30
  var SoleRecordExceeded = class extends ActiveRecordError {
24
31
  name = "SoleRecordExceeded";
@@ -31,7 +38,7 @@ var MissingAttribute = class extends ActiveRecordError {
31
38
  var DeleteRestriction = class extends ActiveRecordError {
32
39
  name = "DeleteRestriction";
33
40
  };
34
- /** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
41
+ /** `last()` can't reverse an order given as an `sql` fragment. */
35
42
  var IrreversibleOrder = class extends ActiveRecordError {
36
43
  name = "IrreversibleOrder";
37
44
  };
@@ -116,6 +123,57 @@ var RecordNotSaved = class extends ActiveRecordError {
116
123
  name = "RecordNotSaved";
117
124
  };
118
125
  /**
126
+ * A save, destroy or `touch()` of a record whose row another write changed since it was loaded
127
+ * (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
128
+ */
129
+ var StaleRecord = class extends ActiveRecordError {
130
+ name = "StaleRecord";
131
+ record;
132
+ action;
133
+ constructor(record, action, options) {
134
+ super(`Attempted to ${action} a stale ${record.constructor.name} record`, options);
135
+ this.record = record;
136
+ this.action = action;
137
+ }
138
+ };
139
+ /**
140
+ * Assigning a persisted record's read-only attribute a value other than the one it holds (#358):
141
+ * it's written when the record is created, and never changed by it after.
142
+ */
143
+ var ReadonlyAttribute = class extends ActiveRecordError {
144
+ name = "ReadonlyAttribute";
145
+ attribute;
146
+ constructor(model, attribute) {
147
+ super(`${model}'s "${attribute}" is read-only once it's created; it can't be changed`);
148
+ this.attribute = attribute;
149
+ }
150
+ };
151
+ /**
152
+ * A write of a read-only record (#358): one marked by `markReadonly()`, or loaded through a
153
+ * `readonly()` Relation. Nothing ran and nothing was sent.
154
+ */
155
+ var ReadonlyRecord = class extends ActiveRecordError {
156
+ name = "ReadonlyRecord";
157
+ record;
158
+ action;
159
+ constructor(record, action) {
160
+ super(`${record.constructor.name} record is read-only; it can't ${verbs[action]}`);
161
+ this.record = record;
162
+ this.action = action;
163
+ }
164
+ };
165
+ /** How a refused action reads after "it can't". */
166
+ const verbs = {
167
+ save: "be saved",
168
+ destroy: "be destroyed",
169
+ touch: "be touched",
170
+ updateColumns: "be written by updateColumns",
171
+ updateColumn: "be written by updateColumn",
172
+ incrementColumn: "be written by incrementColumn",
173
+ decrementColumn: "be written by decrementColumn",
174
+ toggleColumn: "be written by toggleColumn"
175
+ };
176
+ /**
119
177
  * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
120
178
  * `afterDestroy`, `afterTouch`), or from an around callback once its `next()` resolved. That's a
121
179
  * mistake: the write already succeeded and nothing rolls back.
@@ -151,7 +209,7 @@ var ReadonlyAssociation = class extends ActiveRecordError {
151
209
  };
152
210
  /**
153
211
  * A polymorphic belongsTo's type that names none of the Models it lists (#60), read from the
154
- * database, as Rails raises when it can't find the class a type names.
212
+ * database.
155
213
  */
156
214
  var UnknownModelName = class extends ActiveRecordError {
157
215
  name = "UnknownModelName";
@@ -163,7 +221,7 @@ var AssociationNotLoaded = class extends ActiveRecordError {
163
221
  // src/naming.ts
164
222
  /**
165
223
  * Converts a camelCase attribute name to its snake_case column name, treating
166
- * a run of capitals as one word (Rails' `underscore`): `htmlURL` → `html_url`,
224
+ * a run of capitals as one word: `htmlURL` → `html_url`,
167
225
  * `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
168
226
  */
169
227
  function underscore(name) {
@@ -173,6 +231,10 @@ function underscore(name) {
173
231
  function camelize(name) {
174
232
  return name.replace(/_([a-z\d])/g, (_, letter) => letter.toUpperCase());
175
233
  }
234
+ /** A name with its first letter capitalized, as a method's name holds it: `authToken` → `AuthToken`. */
235
+ function capitalized(name) {
236
+ return name.charAt(0).toUpperCase() + name.slice(1);
237
+ }
176
238
  // src/inflections.ts
177
239
  /** Words whose plural no rule makes: singular, then plural. */
178
240
  const IRREGULARS = [
@@ -183,7 +245,7 @@ const IRREGULARS = [
183
245
  ["move", "moves"],
184
246
  ["zombie", "zombies"]
185
247
  ];
186
- /** Plural rules in Rails' order of definition. The last one that matches wins, as in Rails. */
248
+ /** Plural rules in order of definition. The last one that matches wins. */
187
249
  const PLURALS = [
188
250
  [/$/, "s"],
189
251
  [/s$/i, "s"],
@@ -208,7 +270,7 @@ const PLURALS = [
208
270
  [/(quiz)$/i, "$1zes"],
209
271
  ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, plural))
210
272
  ];
211
- /** Singular rules, likewise in Rails' order. */
273
+ /** Singular rules, likewise in order of definition. */
212
274
  const SINGULARS = [
213
275
  [/s$/i, ""],
214
276
  [/(ss)$/i, "$1"],
@@ -239,16 +301,16 @@ const SINGULARS = [
239
301
  [/(database)s$/i, "$1"],
240
302
  ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, singular))
241
303
  ];
242
- /** Words with no plural, matched as the last word (Rails' `\b<word>\z`). */
304
+ /** Words with no plural, matched as the last word. */
243
305
  const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/i;
244
306
  /**
245
- * Rails' `irregular`: rules turning either form into `into` (the plural for plural rules, the
307
+ * Irregular words: rules turning either form into `into` (the plural for plural rules, the
246
308
  * singular for singular ones), keeping the first letter's case.
247
309
  */
248
310
  function irregular(singular, plural, into) {
249
311
  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)}`]];
250
312
  }
251
- /** Applies the last rule that matches, as Rails does; uncountable words stay as they are. */
313
+ /** Applies the last rule that matches; uncountable words stay as they are. */
252
314
  function inflect(word, rules) {
253
315
  if (word === "" || UNCOUNTABLE.test(word)) return word;
254
316
  for (let index = rules.length - 1; index >= 0; index--) {
@@ -257,11 +319,11 @@ function inflect(word, rules) {
257
319
  }
258
320
  return word;
259
321
  }
260
- /** Rails' `pluralize`: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
322
+ /** A word's plural: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
261
323
  function pluralize(word) {
262
324
  return inflect(word, PLURALS);
263
325
  }
264
- /** Rails' `singularize`: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
326
+ /** A word's singular: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
265
327
  function singularize(word) {
266
328
  return inflect(word, SINGULARS);
267
329
  }
@@ -313,7 +375,7 @@ function repeatProblem(entries) {
313
375
  }
314
376
  /**
315
377
  * The validations an enum declared `validate: true` adds, before a Model's own: its value must be
316
- * one of its names, and not null unless `allowNull`, as Rails' `validate: true` adds them.
378
+ * one of its names, and not null unless `allowNull`.
317
379
  */
318
380
  function enumValidations(definitions) {
319
381
  return [...definitions].flatMap(([attribute, { enum: values, validate = false }]) => {
@@ -345,49 +407,6 @@ function enumValuesOf(model, attribute) {
345
407
  if (values === void 0) throw new UnknownAttribute(`${model.name} has no enum attribute "${attribute}"`);
346
408
  return mappingOf(values);
347
409
  }
348
- // src/identifiers.ts
349
- /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
350
- function isIdentifier(name) {
351
- return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
352
- }
353
- /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
354
- 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(" "));
355
- // src/binary-values.ts
356
- /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
357
- function castBinary(value) {
358
- if (value instanceof Uint8Array) return value;
359
- return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
360
- }
361
- /**
362
- * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
363
- * a `bytea` as a `Buffer`.
364
- */
365
- function readBinary(cell) {
366
- if (cell instanceof Uint8Array) return Uint8Array.from(cell);
367
- return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
368
- }
369
- /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
370
- function isSameCell(a, b) {
371
- if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
372
- return a.length === b.length && a.every((byte, index) => byte === b[index]);
373
- }
374
- /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
375
- const digitCodes = new TextEncoder().encode("0123456789abcdef");
376
- const decoder = new TextDecoder();
377
- /**
378
- * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
379
- * digits' character codes are written into one array and decoded once: mapping each byte to a
380
- * string of its own takes many times the memory and time, which a large file can't afford.
381
- */
382
- function hexOf(bytes) {
383
- const text = new Uint8Array(bytes.length * 2);
384
- for (let index = 0; index < bytes.length; index++) {
385
- const byte = bytes[index];
386
- text[index * 2] = digitCodes[byte >> 4];
387
- text[index * 2 + 1] = digitCodes[byte & 15];
388
- }
389
- return decoder.decode(text);
390
- }
391
410
  // src/calendar-values.ts
392
411
  /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
393
412
  const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
@@ -428,6 +447,179 @@ function withoutTrailingZeros(digits) {
428
447
  while (digits[end - 1] === "0") end--;
429
448
  return digits.slice(0, end);
430
449
  }
450
+ // src/decimal-values.ts
451
+ /**
452
+ * A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
453
+ * exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
454
+ * can match two ways (ReDoS).
455
+ */
456
+ const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
457
+ /** The most digits Postgres's `numeric` holds before its point, and after it. */
458
+ const maxWholeDigits = 131072;
459
+ const maxFractionDigits = 16383;
460
+ /**
461
+ * The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
462
+ * point, an exponent and spaces. Longer text is refused before it's read.
463
+ */
464
+ const maxTextLength = 147519;
465
+ /** The significant digits a number keeps when it's cast to a decimal. */
466
+ const numberPrecision = 16;
467
+ /**
468
+ * An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
469
+ * 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
470
+ * Postgres's `numeric` holds, is `uncastable`.
471
+ */
472
+ function castDecimal(value) {
473
+ if (typeof value === "bigint") return canonical(String(value));
474
+ if (typeof value === "number") return castNumber(value);
475
+ return typeof value === "string" ? canonical(value) : uncastable;
476
+ }
477
+ /**
478
+ * A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
479
+ * cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
480
+ * significant digits, a whole number past a safe integer too.
481
+ */
482
+ function readDecimal(cell) {
483
+ if (typeof cell === "number") return castNumber(cell);
484
+ return typeof cell === "string" ? canonical(cell) : uncastable;
485
+ }
486
+ function castNumber(value) {
487
+ if (!Number.isFinite(value)) return uncastable;
488
+ const decimal = canonical(value.toPrecision(numberPrecision));
489
+ return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
490
+ }
491
+ /**
492
+ * Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
493
+ * no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
494
+ */
495
+ function canonical(text) {
496
+ const parts = partsOf(text);
497
+ if (parts === void 0) return uncastable;
498
+ const { negative, digits, point } = parts;
499
+ const first = digits.search(/[1-9]/);
500
+ if (first === -1) return "0";
501
+ const last = lastNonZero(digits) + 1;
502
+ if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
503
+ const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
504
+ return isWithinDouble(decimal) ? decimal : uncastable;
505
+ }
506
+ /**
507
+ * Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
508
+ * underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
509
+ * which reads as NULL, or as 0, so every database refuses one alike (#391).
510
+ */
511
+ function isWithinDouble(decimal) {
512
+ const number = Number(decimal);
513
+ return Number.isFinite(number) && number !== 0;
514
+ }
515
+ /** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
516
+ function partsOf(text) {
517
+ if (text.length > maxTextLength) return void 0;
518
+ const match = decimalText.exec(text);
519
+ if (match === null) return void 0;
520
+ const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
521
+ return {
522
+ negative: sign === "-",
523
+ digits: whole + (pointed ?? unpointed ?? ""),
524
+ point: whole.length + Number(exponent)
525
+ };
526
+ }
527
+ /**
528
+ * Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
529
+ * on a long run of zeros it takes quadratic time.
530
+ */
531
+ function lastNonZero(digits) {
532
+ let index = digits.length - 1;
533
+ while (digits[index] === "0") index--;
534
+ return index;
535
+ }
536
+ /** Significant `digits` with the point `point` digits after the first, padded with zeros. */
537
+ function placePoint(digits, point) {
538
+ if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
539
+ if (point >= digits.length) return digits + "0".repeat(point - digits.length);
540
+ return `${digits.slice(0, point)}.${digits.slice(point)}`;
541
+ }
542
+ /**
543
+ * Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
544
+ * by the digits before the point (more is larger), then digit by digit, which is exact.
545
+ */
546
+ function compareDecimals(a, b) {
547
+ const [signA, signB] = [signOf(a), signOf(b)];
548
+ if (signA !== signB) return Math.sign(signA - signB);
549
+ const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
550
+ return signA < 0 ? -order : order;
551
+ }
552
+ function signOf(decimal) {
553
+ if (decimal === "0") return 0;
554
+ return decimal.startsWith("-") ? -1 : 1;
555
+ }
556
+ function compareMagnitudes(a, b) {
557
+ const [wholeA = "", fractionA = ""] = a.split(".");
558
+ const [wholeB = "", fractionB = ""] = b.split(".");
559
+ if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
560
+ const width = Math.max(fractionA.length, fractionB.length);
561
+ const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
562
+ if (left === right) return 0;
563
+ return left < right ? -1 : 1;
564
+ }
565
+ /**
566
+ * Where a decimal falls against a bound given as a number or decimal text: exactly, as
567
+ * `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
568
+ * every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
569
+ */
570
+ function orderDecimal(value, bound) {
571
+ if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
572
+ const decimal = castDecimal(bound);
573
+ return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
574
+ }
575
+ /** The most digits Postgres's `numeric` takes as a precision or a scale. */
576
+ const maxDigits = 1e3;
577
+ /** Whether `value` is a whole number of digits from `least` to 1000. */
578
+ function isDigitCount(value, least) {
579
+ return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
580
+ }
581
+ /**
582
+ * Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
583
+ * a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
584
+ * the generators all check it here (#398).
585
+ */
586
+ function digitsProblem({ precision, scale }) {
587
+ if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
588
+ if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
589
+ if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
590
+ return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
591
+ }
592
+ /**
593
+ * A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
594
+ * rounds; `uncastable` when its digits before the point are more than the precision
595
+ * leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
596
+ */
597
+ function limitDecimal(decimal, { precision, scale }) {
598
+ const places = scale ?? (precision === void 0 ? void 0 : 0);
599
+ const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
600
+ if (precision === void 0 || rounded === uncastable) return rounded;
601
+ const whole = rounded.replace("-", "").split(".")[0];
602
+ return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
603
+ }
604
+ /**
605
+ * A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
606
+ * `uncastable` when rounding carries it past a double's range.
607
+ */
608
+ function roundDecimal(decimal, places) {
609
+ const negative = decimal.startsWith("-");
610
+ const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
611
+ if (fraction.length <= places) return decimal;
612
+ const kept = whole + fraction.slice(0, places);
613
+ const digits = fraction[places] >= "5" ? incremented(kept) : kept;
614
+ const point = digits.length - places;
615
+ return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
616
+ }
617
+ /** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
618
+ function incremented(digits) {
619
+ let index = digits.length - 1;
620
+ while (index >= 0 && digits[index] === "9") index--;
621
+ return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
622
+ }
431
623
  // src/conversion.ts
432
624
  /** A value that can't be read as the attribute's type. */
433
625
  const uncastable = Symbol("uncastable");
@@ -577,8 +769,8 @@ function customConverter(type, stored) {
577
769
  }
578
770
  /**
579
771
  * An enum's values are its names (#340). A name is cast as itself, and so is the value it's
580
- * stored as (`1`, or `"1"` from a form), as Rails accepts; anything else is `uncastable`. A stored
581
- * cell of its type that's none of its values reads as null, as Rails reads it, so a row written
772
+ * stored as (`1`, or `"1"` from a form); anything else is `uncastable`. A stored
773
+ * cell of its type that's none of its values reads as null, so a row written
582
774
  * by code that lists a newer value doesn't fail every list it's in; one of another type is
583
775
  * `uncastable`, as for any attribute of that type (#159).
584
776
  */
@@ -602,7 +794,7 @@ function castValue(attribute, value) {
602
794
  /**
603
795
  * A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
604
796
  * finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
605
- * for a text key and as Rails does, so a foreign key of another type still finds its target.
797
+ * for a text key, so a foreign key of another type still finds its target.
606
798
  */
607
799
  function castCondition(attribute, value) {
608
800
  return castKey(withoutPrecision(attribute), value);
@@ -810,180 +1002,50 @@ function dayOf(day) {
810
1002
  function isInvalidDate(value) {
811
1003
  return value instanceof Date && Number.isNaN(value.getTime());
812
1004
  }
813
- // src/decimal-values.ts
814
- /**
815
- * A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
816
- * exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
817
- * can match two ways (ReDoS).
818
- */
819
- const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
820
- /** The most digits Postgres's `numeric` holds before its point, and after it. */
821
- const maxWholeDigits = 131072;
822
- const maxFractionDigits = 16383;
823
- /**
824
- * The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
825
- * point, an exponent and spaces. Longer text is refused before it's read.
826
- */
827
- const maxTextLength = 147519;
828
- /** A number's significant digits when it's cast, as Rails casts a float to a decimal. */
829
- const numberPrecision = 16;
830
- /**
831
- * An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
832
- * 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
833
- * Postgres's `numeric` holds, is `uncastable`.
834
- */
835
- function castDecimal(value) {
836
- if (typeof value === "bigint") return canonical(String(value));
837
- if (typeof value === "number") return castNumber(value);
838
- return typeof value === "string" ? canonical(value) : uncastable;
839
- }
840
- /**
841
- * A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
842
- * cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
843
- * significant digits, a whole number past a safe integer too, as Rails reads one on SQLite.
844
- */
845
- function readDecimal(cell) {
846
- if (typeof cell === "number") return castNumber(cell);
847
- return typeof cell === "string" ? canonical(cell) : uncastable;
848
- }
849
- function castNumber(value) {
850
- if (!Number.isFinite(value)) return uncastable;
851
- const decimal = canonical(value.toPrecision(numberPrecision));
852
- return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
853
- }
854
- /**
855
- * Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
856
- * no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
857
- */
858
- function canonical(text) {
859
- const parts = partsOf(text);
860
- if (parts === void 0) return uncastable;
861
- const { negative, digits, point } = parts;
862
- const first = digits.search(/[1-9]/);
863
- if (first === -1) return "0";
864
- const last = lastNonZero(digits) + 1;
865
- if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
866
- const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
867
- return isWithinDouble(decimal) ? decimal : uncastable;
868
- }
869
- /**
870
- * Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
871
- * underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
872
- * which reads as NULL, or as 0, so every database refuses one alike (#391).
873
- */
874
- function isWithinDouble(decimal) {
875
- const number = Number(decimal);
876
- return Number.isFinite(number) && number !== 0;
877
- }
878
- /** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
879
- function partsOf(text) {
880
- if (text.length > maxTextLength) return void 0;
881
- const match = decimalText.exec(text);
882
- if (match === null) return void 0;
883
- const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
884
- return {
885
- negative: sign === "-",
886
- digits: whole + (pointed ?? unpointed ?? ""),
887
- point: whole.length + Number(exponent)
888
- };
889
- }
890
- /**
891
- * Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
892
- * on a long run of zeros it takes quadratic time.
893
- */
894
- function lastNonZero(digits) {
895
- let index = digits.length - 1;
896
- while (digits[index] === "0") index--;
897
- return index;
898
- }
899
- /** Significant `digits` with the point `point` digits after the first, padded with zeros. */
900
- function placePoint(digits, point) {
901
- if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
902
- if (point >= digits.length) return digits + "0".repeat(point - digits.length);
903
- return `${digits.slice(0, point)}.${digits.slice(point)}`;
904
- }
905
- /**
906
- * Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
907
- * by the digits before the point (more is larger), then digit by digit, which is exact.
908
- */
909
- function compareDecimals(a, b) {
910
- const [signA, signB] = [signOf(a), signOf(b)];
911
- if (signA !== signB) return Math.sign(signA - signB);
912
- const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
913
- return signA < 0 ? -order : order;
914
- }
915
- function signOf(decimal) {
916
- if (decimal === "0") return 0;
917
- return decimal.startsWith("-") ? -1 : 1;
918
- }
919
- function compareMagnitudes(a, b) {
920
- const [wholeA = "", fractionA = ""] = a.split(".");
921
- const [wholeB = "", fractionB = ""] = b.split(".");
922
- if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
923
- const width = Math.max(fractionA.length, fractionB.length);
924
- const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
925
- if (left === right) return 0;
926
- return left < right ? -1 : 1;
927
- }
928
- /**
929
- * Where a decimal falls against a bound given as a number or decimal text: exactly, as
930
- * `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
931
- * every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
932
- */
933
- function orderDecimal(value, bound) {
934
- if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
935
- const decimal = castDecimal(bound);
936
- return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
937
- }
938
- /** The most digits Postgres's `numeric` takes as a precision or a scale. */
939
- const maxDigits = 1e3;
940
- /** Whether `value` is a whole number of digits from `least` to 1000. */
941
- function isDigitCount(value, least) {
942
- return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
1005
+ // src/binary-values.ts
1006
+ /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
1007
+ function castBinary(value) {
1008
+ if (value instanceof Uint8Array) return value;
1009
+ return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
943
1010
  }
944
1011
  /**
945
- * Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
946
- * a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
947
- * the generators all check it here (#398).
1012
+ * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
1013
+ * a `bytea` as a `Buffer`.
948
1014
  */
949
- function digitsProblem({ precision, scale }) {
950
- if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
951
- if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
952
- if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
953
- return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
1015
+ function readBinary(cell) {
1016
+ if (cell instanceof Uint8Array) return Uint8Array.from(cell);
1017
+ return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
954
1018
  }
955
- /**
956
- * A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
957
- * and Rails round; `uncastable` when its digits before the point are more than the precision
958
- * leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
959
- */
960
- function limitDecimal(decimal, { precision, scale }) {
961
- const places = scale ?? (precision === void 0 ? void 0 : 0);
962
- const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
963
- if (precision === void 0 || rounded === uncastable) return rounded;
964
- const whole = rounded.replace("-", "").split(".")[0];
965
- return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
1019
+ /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
1020
+ function isSameCell(a, b) {
1021
+ if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
1022
+ return a.length === b.length && a.every((byte, index) => byte === b[index]);
966
1023
  }
1024
+ /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
1025
+ const digitCodes = new TextEncoder().encode("0123456789abcdef");
1026
+ const decoder = new TextDecoder();
967
1027
  /**
968
- * A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
969
- * `uncastable` when rounding carries it past a double's range.
1028
+ * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
1029
+ * digits' character codes are written into one array and decoded once: mapping each byte to a
1030
+ * string of its own takes many times the memory and time, which a large file can't afford.
970
1031
  */
971
- function roundDecimal(decimal, places) {
972
- const negative = decimal.startsWith("-");
973
- const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
974
- if (fraction.length <= places) return decimal;
975
- const kept = whole + fraction.slice(0, places);
976
- const digits = fraction[places] >= "5" ? incremented(kept) : kept;
977
- const point = digits.length - places;
978
- return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
979
- }
980
- /** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
981
- function incremented(digits) {
982
- let index = digits.length - 1;
983
- while (index >= 0 && digits[index] === "9") index--;
984
- return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
1032
+ function hexOf(bytes) {
1033
+ const text = new Uint8Array(bytes.length * 2);
1034
+ for (let index = 0; index < bytes.length; index++) {
1035
+ const byte = bytes[index];
1036
+ text[index * 2] = digitCodes[byte >> 4];
1037
+ text[index * 2 + 1] = digitCodes[byte & 15];
1038
+ }
1039
+ return decoder.decode(text);
985
1040
  }
986
1041
  // src/epoch-storage.ts
987
1042
  /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
988
1043
  const epochStorages = ["unixSeconds", "unixMilliseconds"];
989
- 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 };
1044
+ // src/identifiers.ts
1045
+ /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
1046
+ function isIdentifier(name) {
1047
+ return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
1048
+ }
1049
+ /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
1050
+ 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(" "));
1051
+ export { StaleRecord as $, AssociationNotLoaded as A, MissingAttribute as B, pluralize as C, underscore as D, capitalized as E, IncompatibleRelation as F, ReadonlyRecord as G, NotNullViolation as H, InvalidForeignKey as I, RecordNotDestroyed as J, RecordDestroyed as K, InvalidModel as L, CheckViolation as M, ConstraintViolation as N, AbortAfterPersistence as O, DeleteRestriction as P, SoleRecordExceeded as Q, InvalidToken as R, listedNames as S, camelize as T, ReadonlyAssociation as U, NoDatabase as V, ReadonlyAttribute as W, RecordNotSaved as X, RecordNotFound as Y, RecordNotUnique as Z, enumEntries as _, isSameCell as a, enumValuesOf as b, castValue as c, uncastable as d, StrictValidationFailed as et, writeUntypedValue as f, orderDecimal as g, digitsProblem as h, hexOf as i, abort as it, CallbackAbort as j, ActiveRecordError as k, isInvalidDate as l, zonelessDateTime as m, reservedWords as n, UnknownAttribute as nt, castCondition as o, writeValue as p, RecordInvalid as q, epochStorages as r, UnknownModelName as rt, castKey as s, isIdentifier as t, UnknownAssociation as tt, readValue as u, enumProblem as v, singularize as w, isEnumValues as x, enumValidations as y, IrreversibleOrder as z };