@prisma/orm-sqlite 8.0.0-rc.20-dev.8 → 8.0.0-rc.20-dev.10

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 (26) hide show
  1. package/dist/runtime.mjs +1 -1
  2. package/dist/runtime.mjs.map +1 -1
  3. package/dist/{sqlite-static-DORjKoZ5-ChzQDdU5.mjs → sqlite-static-mr8PBZYf-C8YT9m5s.mjs} +3 -3
  4. package/dist/sqlite-static-mr8PBZYf-C8YT9m5s.mjs.map +1 -0
  5. package/dist/static.mjs +1 -1
  6. package/package.json +8 -8
  7. package/skills/prisma-8/SKILL.md +1 -1
  8. package/skills/prisma-8/references/migrations.md +2 -1
  9. package/skills/prisma-8/references/upgrade-app.md +2 -2
  10. package/skills/prisma-8/references/upgrade-extension.md +2 -2
  11. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +130 -94
  12. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +245 -30
  13. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +8 -5
  14. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +77 -23
  15. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +1668 -19
  16. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +23 -12
  17. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +50 -15
  18. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +273 -87
  19. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +245 -30
  20. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +1120 -0
  21. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
  22. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +304 -0
  23. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +1668 -19
  24. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +8 -6
  25. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +50 -15
  26. package/dist/sqlite-static-DORjKoZ5-ChzQDdU5.mjs.map +0 -1
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Removes the `noCheck` key from every column of every SQL contract in a project. Where the key waived the element check of a list, the column and the field that maps it become lists whose elements may be null, in `contract.json` and `contract.d.ts`, because that is what the database enforces. The checks each contract declares are left as they are. The script then renames the snapshot directories and rewrites every migration, ref, `migration.ts` and `contract.d.ts` that names an old storage hash.
3
+ * Removes the `noCheck` key from every column of every SQL contract in a project. Where the key waived the element check of a list, the column and the field that maps it become lists whose elements may be null, in `contract.json` and `contract.d.ts`, because that is what the database enforces. The checks each contract declares are left as they are. In a PostgreSQL contract it also writes each literal default in the contract form this release stores, as its column's data type and parameters give it. The script then renames the snapshot directories and rewrites every migration, ref, `migration.ts` and `contract.d.ts` that names an old storage hash.
4
4
  *
5
- * Usage: node remove-nocheck.ts [project-root]
5
+ * Usage: node remove-nocheck.ts [project-root] [--default <namespace>.<table>.<column>=<JSON value>]...
6
6
  *
7
- * The project root defaults to the working directory. The script reads and writes files only. It needs no database, network or configured stack, and a project with no `noCheck` key is left unchanged. When it stops (a file it must read is not valid JSON, a contract whose stored hash does not match its content, or a snapshot directory that already exists with different content) it changes no file, prints one line per case and exits 1. When it finishes it prints how many files and snapshot directories it changed and each storage hash it replaced.
7
+ * The project root defaults to the working directory. The script reads and writes files only. It needs no database, network or configured stack, and a project already in this release's form is left unchanged. When it stops (a file it must read is not valid JSON, a contract whose stored hash does not match its content, a default that this release refuses, or a snapshot directory that already exists with different content) it changes no file, prints one line per case and exits 1. When it finishes it prints how many files and snapshot directories it changed and each storage hash it replaced.
8
8
  *
9
- * The storage hash and migration hash rules are copied from `@internal/contract` and `@internal/migration-tools` because a project's strict `node_modules` does not expose them.
9
+ * `--default` gives the value to store in place of a default this release refuses, in every stored contract where that column's default is refused. The script checks the value by the same rules, and stops when a `--default` names a column whose default it does not refuse.
10
+ *
11
+ * The storage hash and migration hash rules are copied from `@internal/contract` and `@internal/migration-tools`, and the default rules from the data types of 8.0.0-rc.19, PostgreSQL's built-in types, `postgis/geometry` and `pgvector/vector`, so the script gives the same result whatever is installed.
10
12
  */
11
13
  import { createHash } from 'node:crypto';
12
14
  import {
@@ -29,7 +31,7 @@ interface JsonRecord {
29
31
  [key: string]: Json;
30
32
  }
31
33
 
32
- const SKIPPED_DIRECTORIES = new Set(['node_modules', '.git', 'dist', 'build']);
34
+ const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
33
35
  const HASH = /^[0-9a-f]{64}$/;
34
36
  const TEMPORARY_SUFFIX = '.remove-nocheck-tmp';
35
37
 
@@ -322,7 +324,7 @@ function listFiles(root: string): ProjectFiles {
322
324
  continue;
323
325
  }
324
326
  if (entry.isDirectory() || (entry.isSymbolicLink() && isDirectory(path))) {
325
- if (!SKIPPED_DIRECTORIES.has(entry.name)) visit(path);
327
+ if (!SKIPPED_DIRECTORIES.has(entry.name) && !entry.name.startsWith('.')) visit(path);
326
328
  continue;
327
329
  }
328
330
  if (!isFileEntry(dir, entry)) continue;
@@ -421,6 +423,1481 @@ interface Rewrite {
421
423
  readonly changed: boolean;
422
424
  readonly columns: ReadonlySet<string>;
423
425
  readonly fields: ReadonlySet<string>;
426
+ readonly defaults: ReadonlyMap<string, readonly DefaultRewrite[]>;
427
+ readonly notValues: readonly string[];
428
+ }
429
+
430
+ interface DefaultRewrite {
431
+ readonly from: string | number;
432
+ readonly to: string | number;
433
+ }
434
+
435
+ type DefaultForm =
436
+ | { readonly kind: 'unchanged' }
437
+ | { readonly kind: 'rewritten'; readonly value: Json }
438
+ | { readonly kind: 'notAValue'; readonly reason: string };
439
+
440
+ type Params = Readonly<Record<string, Json>>;
441
+
442
+ class NotAValue extends Error {}
443
+
444
+ class CastRefused extends Error {}
445
+
446
+ function refuseJsonValue(typeId: string, expected: string): never {
447
+ throw new NotAValue(`${typeId} JSON value must be ${expected}`);
448
+ }
449
+
450
+ function withoutTrailing(text: string, character: string): string {
451
+ let end = text.length;
452
+ while (end > 0 && text[end - 1] === character) end -= 1;
453
+ return end === text.length ? text : text.slice(0, end);
454
+ }
455
+
456
+ function counted(amount: number, noun: string): string {
457
+ return `${amount} ${amount === 1 ? noun : `${noun}s`}`;
458
+ }
459
+
460
+ function integerParam(params: Params, name: string): number | undefined {
461
+ const value = params[name];
462
+ return typeof value === 'number' ? value : undefined;
463
+ }
464
+
465
+ function readJsonString(typeId: string, json: Json): string {
466
+ return typeof json === 'string' ? json : refuseJsonValue(typeId, 'a string');
467
+ }
468
+
469
+ function readJsonMatching(typeId: string, json: Json, pattern: RegExp, form: string): string {
470
+ return typeof json === 'string' && pattern.test(json) ? json : refuseJsonValue(typeId, form);
471
+ }
472
+
473
+ function readJsonInteger(typeId: string, json: Json, min: number, max: number): Json {
474
+ return typeof json === 'number' && Number.isInteger(json) && json >= min && json <= max
475
+ ? json
476
+ : refuseJsonValue(typeId, `an integer from ${min} to ${max}`);
477
+ }
478
+
479
+ const INT64_MIN = -(2n ** 63n);
480
+ const INT64_MAX = 2n ** 63n - 1n;
481
+
482
+ function readInt8(json: Json): Json {
483
+ const expected = `a decimal integer string from ${INT64_MIN} to ${INT64_MAX}`;
484
+ const value = BigInt(readJsonMatching('pg/int8', json, /^-?\d+$/, expected));
485
+ if (value < INT64_MIN || value > INT64_MAX) return refuseJsonValue('pg/int8', expected);
486
+ const written = value.toString();
487
+ if (json !== written)
488
+ return refuseJsonValue(
489
+ 'pg/int8',
490
+ `"${written}", the integer's decimal text without leading zeros or a minus sign on zero`,
491
+ );
492
+ return json;
493
+ }
494
+
495
+ const NON_FINITE_TEXT: ReadonlySet<string> = new Set(['NaN', 'Infinity', '-Infinity']);
496
+
497
+ function readJsonFloat(typeId: string, json: Json): number {
498
+ if (typeof json === 'number' && Number.isFinite(json)) return json;
499
+ if (typeof json === 'string' && NON_FINITE_TEXT.has(json)) return Number(json);
500
+ return refuseJsonValue(typeId, 'a finite number or the text NaN, Infinity or -Infinity');
501
+ }
502
+
503
+ const FLOAT4_MAX = 3.4028234663852886e38;
504
+
505
+ function fitsFloat4(value: number): boolean {
506
+ const single = Math.fround(value);
507
+ return Number.isFinite(single) && (value === 0 || single !== 0);
508
+ }
509
+
510
+ function readFloat4(json: Json): Json {
511
+ const value = readJsonFloat('pg/float4', json);
512
+ if (Number.isFinite(value) && !fitsFloat4(value))
513
+ return refuseJsonValue(
514
+ 'pg/float4',
515
+ `a number float4 holds, at most ${FLOAT4_MAX} in magnitude and not so small that it becomes 0, or the text NaN, Infinity or -Infinity`,
516
+ );
517
+ return json;
518
+ }
519
+
520
+ const DECIMAL_NUMERAL_TEXT = /^-?\d+(?:\.\d+)?$/;
521
+ const STORED_NUMERIC_TEXT = /^(?:(?!-0(?:\.0+)?$)-?(?:0|[1-9]\d*)(?:\.\d+)?|NaN|-?Infinity)$/;
522
+
523
+ function storedNumeralText(text: string): string {
524
+ const numeral = /^([+-]?)0*(\d+)(\.\d+)?$/.exec(text);
525
+ if (numeral === null) return text;
526
+ const [, sign = '', whole = '', fraction = ''] = numeral;
527
+ const digits = `${whole}${fraction}`;
528
+ return sign !== '-' || /^[0.]+$/.test(digits) ? digits : `-${digits}`;
529
+ }
530
+
531
+ function fitsNumeric(text: string, precision: number, scale: number): boolean {
532
+ if (text === 'NaN') return true;
533
+ if (text.endsWith('Infinity')) return false;
534
+ const [whole = '', fraction = ''] = text.replace(/^-/, '').split('.');
535
+ const significantFraction = withoutTrailing(fraction, '0');
536
+ const digits = `${whole}${significantFraction}`.replace(/^0+/, '');
537
+ if (digits === '') return true;
538
+ const shift = scale - significantFraction.length;
539
+ if (shift >= 0) return digits.length + shift <= precision;
540
+ const units = withoutTrailing(digits, '0');
541
+ const droppedZeros = digits.length - units.length;
542
+ if (droppedZeros < -shift) return false;
543
+ return digits.length + shift <= precision;
544
+ }
545
+
546
+ function readNumeric(json: Json, params: Params): Json {
547
+ if (typeof json !== 'string' || !STORED_NUMERIC_TEXT.test(json)) {
548
+ const printed =
549
+ typeof json === 'string' && DECIMAL_NUMERAL_TEXT.test(json)
550
+ ? storedNumeralText(json)
551
+ : undefined;
552
+ return refuseJsonValue(
553
+ 'pg/numeric',
554
+ printed === undefined ? 'a decimal string' : `"${printed}", as PostgreSQL writes this value`,
555
+ );
556
+ }
557
+ const precision = integerParam(params, 'precision');
558
+ if (precision === undefined) return json;
559
+ const scale = integerParam(params, 'scale') ?? 0;
560
+ if (!fitsNumeric(json, precision, scale))
561
+ return refuseJsonValue(
562
+ 'pg/numeric',
563
+ `a decimal string that numeric(${precision}, ${scale}) stores without rounding`,
564
+ );
565
+ return json;
566
+ }
567
+
568
+ function spellNumeric(json: Json, params: Params): Json {
569
+ const precision = integerParam(params, 'precision');
570
+ if (precision === undefined || typeof json !== 'string' || json === 'NaN') return json;
571
+ const scale = integerParam(params, 'scale') ?? 0;
572
+ const [whole = '', fraction = ''] = json.split('.');
573
+ return scale <= 0 ? whole : `${whole}.${fraction.slice(0, scale).padEnd(scale, '0')}`;
574
+ }
575
+
576
+ function fitsCharacterLength(text: string, length: number, blankPadded: boolean): boolean {
577
+ const significant = blankPadded ? withoutTrailing(text, ' ') : text;
578
+ return significant.length <= length || [...significant].length <= length;
579
+ }
580
+
581
+ function readCharacter(json: Json, params: Params): Json {
582
+ const length = integerParam(params, 'length') ?? 1;
583
+ if (!fitsCharacterLength(readJsonString('pg/char', json), length, true))
584
+ return refuseJsonValue(
585
+ 'pg/char',
586
+ `a string of at most ${counted(length, 'character')} before any trailing spaces`,
587
+ );
588
+ return json;
589
+ }
590
+
591
+ function spellCharacter(json: Json): Json {
592
+ return typeof json === 'string' ? withoutTrailing(json, ' ') : json;
593
+ }
594
+
595
+ function readCharacterVarying(json: Json, params: Params): Json {
596
+ const length = integerParam(params, 'length');
597
+ const text = readJsonString('pg/varchar', json);
598
+ if (length !== undefined && !fitsCharacterLength(text, length, false))
599
+ return refuseJsonValue('pg/varchar', `a string of at most ${counted(length, 'character')}`);
600
+ return json;
601
+ }
602
+
603
+ const BIT_STRING = /^[01]*$/;
604
+
605
+ function readBit(json: Json, params: Params): Json {
606
+ const length = integerParam(params, 'length') ?? 1;
607
+ const bits = readJsonMatching('pg/bit', json, BIT_STRING, 'a string of 0 and 1 digits');
608
+ if (bits.length !== length)
609
+ return refuseJsonValue('pg/bit', `a string of exactly ${counted(length, 'bit')}`);
610
+ return json;
611
+ }
612
+
613
+ function readBitVarying(json: Json, params: Params): Json {
614
+ const length = integerParam(params, 'length');
615
+ const bits = readJsonMatching('pg/varbit', json, BIT_STRING, 'a string of 0 and 1 digits');
616
+ if (length !== undefined && bits.length > length)
617
+ return refuseJsonValue('pg/varbit', `a string of at most ${counted(length, 'bit')}`);
618
+ return json;
619
+ }
620
+
621
+ function readTextArray(json: Json): Json {
622
+ const expected = 'an array of strings and nulls';
623
+ if (!Array.isArray(json)) return refuseJsonValue('pg/text-array', expected);
624
+ for (const entry of json)
625
+ if (entry !== null && typeof entry !== 'string')
626
+ return refuseJsonValue('pg/text-array', expected);
627
+ return json;
628
+ }
629
+
630
+ const UUID_INPUT = /^(?:\{[0-9a-f]{4}(?:-?[0-9a-f]{4}){7}\}|[0-9a-f]{4}(?:-?[0-9a-f]{4}){7})$/i;
631
+
632
+ function storedUuid(text: string): string | undefined {
633
+ if (!UUID_INPUT.test(text)) return undefined;
634
+ const hex = text.replace(/[{}-]/g, '').toLowerCase();
635
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
636
+ }
637
+
638
+ interface InetValue {
639
+ readonly bytes: readonly number[];
640
+ readonly bits: number;
641
+ }
642
+
643
+ const isDigit = (ch: string | undefined): ch is string => ch !== undefined && /^[0-9]$/.test(ch);
644
+
645
+ function storedInet(text: string): string | undefined {
646
+ if (text.includes(':')) {
647
+ const value = readIpv6(text);
648
+ return value === undefined ? undefined : printIpv6(value);
649
+ }
650
+ const value = readIpv4(text);
651
+ return value === undefined ? undefined : printIpv4(value);
652
+ }
653
+
654
+ function readIpv4(text: string): InetValue | undefined {
655
+ const octets: number[] = [];
656
+ let index = 0;
657
+ let ch = text[index++];
658
+ while (isDigit(ch)) {
659
+ let octet = 0;
660
+ do {
661
+ octet = octet * 10 + Number(ch);
662
+ if (octet > 255) return undefined;
663
+ ch = text[index++];
664
+ } while (isDigit(ch));
665
+ if (octets.length === 4) return undefined;
666
+ octets.push(octet);
667
+ if (ch === undefined || ch === '/') break;
668
+ if (ch !== '.') return undefined;
669
+ ch = text[index++];
670
+ }
671
+ let bits = -1;
672
+ if (ch === '/' && isDigit(text[index]) && octets.length > 0) {
673
+ ch = text[index++];
674
+ bits = 0;
675
+ do {
676
+ bits = bits * 10 + Number(ch);
677
+ ch = text[index++];
678
+ } while (isDigit(ch));
679
+ if (ch !== undefined || bits > 32) return undefined;
680
+ }
681
+ if (ch !== undefined) return undefined;
682
+ if (bits === -1) {
683
+ if (octets.length !== 4) return undefined;
684
+ bits = 32;
685
+ }
686
+ if (octets.length === 0 || Math.floor(bits / 8) > octets.length) return undefined;
687
+ return { bytes: [...octets, 0, 0, 0, 0].slice(0, 4), bits };
688
+ }
689
+
690
+ function readBits(text: string): number | undefined {
691
+ let bits = 0;
692
+ let digits = 0;
693
+ for (const ch of text) {
694
+ if (!isDigit(ch)) return undefined;
695
+ if (digits++ !== 0 && bits === 0) return undefined;
696
+ bits = bits * 10 + Number(ch);
697
+ if (bits > 128) return undefined;
698
+ }
699
+ return digits === 0 ? undefined : bits;
700
+ }
701
+
702
+ function readIpv4Tail(
703
+ text: string,
704
+ ): { readonly octets: readonly number[]; readonly bits: number | undefined } | undefined {
705
+ const octets: number[] = [];
706
+ let octet = 0;
707
+ let digits = 0;
708
+ for (const [index, ch] of [...text].entries()) {
709
+ if (isDigit(ch)) {
710
+ if (digits++ !== 0 && octet === 0) return undefined;
711
+ octet = octet * 10 + Number(ch);
712
+ if (octet > 255) return undefined;
713
+ continue;
714
+ }
715
+ if (ch !== '.' && ch !== '/') return undefined;
716
+ if (octets.length > 3) return undefined;
717
+ octets.push(octet);
718
+ if (ch === '/') {
719
+ const bits = readBits(text.slice(index + 1));
720
+ return bits === undefined ? undefined : { octets, bits };
721
+ }
722
+ octet = 0;
723
+ digits = 0;
724
+ }
725
+ if (digits === 0 || octets.length > 3) return undefined;
726
+ return { octets: [...octets, octet], bits: undefined };
727
+ }
728
+
729
+ function readIpv6(text: string): InetValue | undefined {
730
+ const bytes = new Array<number>(16).fill(0);
731
+ let filled = 0;
732
+ let compressedAt: number | undefined;
733
+ let index = 0;
734
+ if (text[0] === ':') {
735
+ if (text[1] !== ':') return undefined;
736
+ index = 1;
737
+ }
738
+ let tokenStart = index;
739
+ let sawHexDigit = false;
740
+ let group = 0;
741
+ let groupDigits = 0;
742
+ let bits = 128;
743
+ while (index < text.length) {
744
+ const ch = text[index++] ?? '';
745
+ if (/^[0-9a-fA-F]$/.test(ch)) {
746
+ group = (group << 4) | Number.parseInt(ch, 16);
747
+ if (++groupDigits > 4) return undefined;
748
+ sawHexDigit = true;
749
+ continue;
750
+ }
751
+ if (ch === ':') {
752
+ tokenStart = index;
753
+ if (!sawHexDigit) {
754
+ if (compressedAt !== undefined) return undefined;
755
+ compressedAt = filled;
756
+ continue;
757
+ }
758
+ if (index >= text.length || filled + 2 > 16) return undefined;
759
+ bytes[filled++] = group >> 8;
760
+ bytes[filled++] = group & 0xff;
761
+ sawHexDigit = false;
762
+ group = 0;
763
+ groupDigits = 0;
764
+ continue;
765
+ }
766
+ if (ch === '.' && filled + 4 <= 16) {
767
+ const tail = readIpv4Tail(text.slice(tokenStart));
768
+ if (tail !== undefined) {
769
+ tail.octets.forEach((octet, offset) => {
770
+ bytes[filled + offset] = octet;
771
+ });
772
+ filled += 4;
773
+ sawHexDigit = false;
774
+ bits = tail.bits ?? bits;
775
+ break;
776
+ }
777
+ }
778
+ if (ch === '/') {
779
+ const prefix = readBits(text.slice(index));
780
+ if (prefix !== undefined) {
781
+ bits = prefix;
782
+ break;
783
+ }
784
+ }
785
+ return undefined;
786
+ }
787
+ if (sawHexDigit) {
788
+ if (filled + 2 > 16) return undefined;
789
+ bytes[filled++] = group >> 8;
790
+ bytes[filled++] = group & 0xff;
791
+ }
792
+ if (compressedAt !== undefined) {
793
+ if (filled === 16) return undefined;
794
+ const shifted = bytes.slice(compressedAt, filled);
795
+ bytes.fill(0, compressedAt, filled);
796
+ bytes.splice(16 - shifted.length, shifted.length, ...shifted);
797
+ filled = 16;
798
+ }
799
+ return filled === 16 ? { bytes, bits } : undefined;
800
+ }
801
+
802
+ function printIpv4({ bytes, bits }: InetValue): string {
803
+ const address = bytes.join('.');
804
+ return bits === 32 ? address : `${address}/${bits}`;
805
+ }
806
+
807
+ function printIpv6({ bytes, bits }: InetValue): string {
808
+ const groups = Array.from(
809
+ { length: 8 },
810
+ (_, i) => ((bytes[2 * i] ?? 0) << 8) | (bytes[2 * i + 1] ?? 0),
811
+ );
812
+ const zeroRun = longestZeroRun(groups);
813
+ let text = '';
814
+ for (let i = 0; i < 8; i++) {
815
+ if (zeroRun !== undefined && i >= zeroRun.start && i < zeroRun.start + zeroRun.length) {
816
+ if (i === zeroRun.start) text += ':';
817
+ continue;
818
+ }
819
+ if (i !== 0) text += ':';
820
+ const ipv4Tail =
821
+ i === 6 &&
822
+ zeroRun?.start === 0 &&
823
+ (zeroRun.length === 6 || (zeroRun.length === 5 && groups[5] === 0xffff));
824
+ if (ipv4Tail) {
825
+ text += bytes.slice(12).join('.');
826
+ break;
827
+ }
828
+ text += (groups[i] ?? 0).toString(16);
829
+ }
830
+ if (zeroRun !== undefined && zeroRun.start + zeroRun.length === 8) text += ':';
831
+ return bits === 128 ? text : `${text}/${bits}`;
832
+ }
833
+
834
+ function longestZeroRun(
835
+ groups: readonly number[],
836
+ ): { readonly start: number; readonly length: number } | undefined {
837
+ let best: { start: number; length: number } | undefined;
838
+ let current: { start: number; length: number } | undefined;
839
+ for (const [i, group] of groups.entries()) {
840
+ if (group === 0) {
841
+ current =
842
+ current === undefined
843
+ ? { start: i, length: 1 }
844
+ : { ...current, length: current.length + 1 };
845
+ continue;
846
+ }
847
+ if (current !== undefined && (best === undefined || current.length > best.length))
848
+ best = current;
849
+ current = undefined;
850
+ }
851
+ if (current !== undefined && (best === undefined || current.length > best.length)) best = current;
852
+ return best !== undefined && best.length >= 2 ? best : undefined;
853
+ }
854
+
855
+ const BASE64_TEXT = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
856
+
857
+ function spellBytea(json: Json): Json {
858
+ return typeof json === 'string' ? Buffer.from(json, 'base64').toString('base64') : json;
859
+ }
860
+
861
+ const ISO_DURATION =
862
+ /^P(?!$)(-?\d+Y)?(-?\d+M)?(-?\d+D)?(?:T(?!$)(-?\d+H)?(-?\d+M)?(-?\d+(?:\.\d+)?S)?)?$/;
863
+ const MICROS_PER_SECOND = 1_000_000n;
864
+
865
+ interface IntervalFields {
866
+ readonly months: number;
867
+ readonly days: number;
868
+ readonly micros: bigint;
869
+ }
870
+
871
+ function microsFromFraction(fraction: string, negative: boolean): bigint {
872
+ if (fraction === '') return 0n;
873
+ const kept = BigInt(fraction.slice(0, 6).padEnd(6, '0'));
874
+ const rest = fraction.slice(6).replace(/0+$/, '');
875
+ if (rest === '') return kept;
876
+ const half = rest[0] === '5' && rest.length === 1;
877
+ const roundsUp = rest > '5' || (half && !negative);
878
+ return roundsUp ? kept + 1n : kept;
879
+ }
880
+
881
+ function intervalFieldsOf(match: RegExpExecArray): IntervalFields {
882
+ const [, years, months, days, hours, minutes, seconds] = match;
883
+ const wholeNumber = (part: string | undefined): number =>
884
+ part === undefined ? 0 : Number(part.slice(0, -1));
885
+ const secondsLiteral = seconds === undefined ? '0' : seconds.slice(0, -1);
886
+ const negative = secondsLiteral.startsWith('-');
887
+ const [whole = '0', fraction = ''] = secondsLiteral.replace('-', '').split('.');
888
+ const magnitude = BigInt(whole) * MICROS_PER_SECOND + microsFromFraction(fraction, negative);
889
+ return {
890
+ months: wholeNumber(years) * 12 + wholeNumber(months),
891
+ days: wholeNumber(days),
892
+ micros:
893
+ BigInt(wholeNumber(hours)) * 3_600n * MICROS_PER_SECOND +
894
+ BigInt(wholeNumber(minutes)) * 60n * MICROS_PER_SECOND +
895
+ (negative ? -magnitude : magnitude),
896
+ };
897
+ }
898
+
899
+ function secondsText(micros: bigint): string {
900
+ const sign = micros < 0n ? '-' : '';
901
+ const magnitude = micros < 0n ? -micros : micros;
902
+ const whole = (magnitude / MICROS_PER_SECOND) % 60n;
903
+ const fraction = magnitude % MICROS_PER_SECOND;
904
+ const fractionText =
905
+ fraction === 0n ? '' : `.${fraction.toString().padStart(6, '0').replace(/0+$/, '')}`;
906
+ return `${sign}${whole}${fractionText}`;
907
+ }
908
+
909
+ function formatIsoDuration({ months, days, micros }: IntervalFields): string {
910
+ const years = Math.trunc(months / 12);
911
+ const restMonths = months % 12;
912
+ const sign = micros < 0n ? '-' : '';
913
+ const magnitude = micros < 0n ? -micros : micros;
914
+ const hours = magnitude / (3_600n * MICROS_PER_SECOND);
915
+ const minutes = (magnitude / (60n * MICROS_PER_SECOND)) % 60n;
916
+ const hasSeconds = magnitude % (60n * MICROS_PER_SECOND) !== 0n;
917
+ const parts = [
918
+ years === 0 ? '' : `${years}Y`,
919
+ restMonths === 0 ? '' : `${restMonths}M`,
920
+ days === 0 ? '' : `${days}D`,
921
+ ];
922
+ const time = [
923
+ hours === 0n ? '' : `${sign}${hours}H`,
924
+ minutes === 0n ? '' : `${sign}${minutes}M`,
925
+ hasSeconds ? `${secondsText(micros)}S` : '',
926
+ ].join('');
927
+ const rendered = `P${parts.join('')}${time === '' ? '' : `T${time}`}`;
928
+ return rendered === 'P' ? 'PT0S' : rendered;
929
+ }
930
+
931
+ const POSTGRES_INTERVAL =
932
+ /^(?:([+-]?\d+) years? ?)?(?:([+-]?\d+) mons? ?)?(?:([+-]?\d+) days? ?)?(?:([+-])?(\d+):(\d{2}):(\d{2})(?:\.(\d+))?)?$/;
933
+
934
+ function postgresIntervalFields(text: string): IntervalFields | undefined {
935
+ const match = POSTGRES_INTERVAL.exec(text);
936
+ if (match === null || text === '' || text.endsWith(' ')) return undefined;
937
+ const [, years = '0', months = '0', days = '0', sign, hours = '0', minutes = '0', seconds = '0'] =
938
+ match;
939
+ const fraction = match[8] ?? '';
940
+ const magnitude =
941
+ (BigInt(hours) * 3_600n + BigInt(minutes) * 60n + BigInt(seconds)) * MICROS_PER_SECOND +
942
+ microsFromFraction(fraction, sign === '-');
943
+ return {
944
+ months: Number(years) * 12 + Number(months),
945
+ days: Number(days),
946
+ micros: sign === '-' ? -magnitude : magnitude,
947
+ };
948
+ }
949
+
950
+ function intervalStoredText(text: string): string {
951
+ const fractionDigits = /\.(\d+)/.exec(text)?.[1]?.length ?? 0;
952
+ if (fractionDigits > 6)
953
+ throw new CastRefused(
954
+ `"${text}" has ${fractionDigits} digits after the decimal point, but pg/interval holds microseconds, so at most 6. Round it, as in "PT1.123456S".`,
955
+ );
956
+ const iso = ISO_DURATION.exec(text);
957
+ if (iso !== null) return formatIsoDuration(intervalFieldsOf(iso));
958
+ const fields = postgresIntervalFields(text);
959
+ if (fields === undefined)
960
+ throw new CastRefused(
961
+ `pg/interval cannot read "${text}". Write an ISO 8601 duration, as in "P1Y2M3DT4H5M6S".`,
962
+ );
963
+ return formatIsoDuration(fields);
964
+ }
965
+
966
+ function isoYearText(text: string): string {
967
+ const match = /^(\d{4,6})(-.*?)( BC)?$/.exec(text);
968
+ if (match === null) return text;
969
+ const [, digits = '', rest = '', bc] = match;
970
+ const year = Number(digits);
971
+ if (bc !== undefined) {
972
+ if (year === 0) return text;
973
+ return `${yearText(1 - year)}${rest}`;
974
+ }
975
+ return digits.length > 4 ? `${yearText(year)}${rest}` : text;
976
+ }
977
+
978
+ type DateTimeShape = 'date' | 'time' | 'timeWithOffset' | 'dateTime' | 'instant';
979
+
980
+ interface DateTimeOptions {
981
+ readonly shape: DateTimeShape;
982
+ readonly typeId: string;
983
+ readonly maxOffsetHours?: number;
984
+ readonly range?: { readonly earliest: string; readonly latest: string };
985
+ }
986
+
987
+ interface DateFields {
988
+ readonly year: number;
989
+ readonly month: number;
990
+ readonly day: number;
991
+ }
992
+
993
+ interface TimeFields {
994
+ readonly hour: number;
995
+ readonly minute: number;
996
+ readonly second: number;
997
+ readonly fraction: string;
998
+ }
999
+
1000
+ interface WrittenDateTime {
1001
+ readonly date: DateFields | undefined;
1002
+ readonly time: TimeFields | undefined;
1003
+ readonly offsetSeconds: number | undefined;
1004
+ readonly fractionDigits: number;
1005
+ }
1006
+
1007
+ const SHAPES: Readonly<
1008
+ Record<
1009
+ DateTimeShape,
1010
+ {
1011
+ readonly description: string;
1012
+ readonly plural: string;
1013
+ readonly example: string;
1014
+ readonly date: boolean;
1015
+ readonly time: boolean;
1016
+ readonly offset: boolean;
1017
+ }
1018
+ >
1019
+ > = {
1020
+ date: {
1021
+ description: 'a date',
1022
+ plural: 'dates',
1023
+ example: '2024-01-01',
1024
+ date: true,
1025
+ time: false,
1026
+ offset: false,
1027
+ },
1028
+ time: {
1029
+ description: 'a time of day',
1030
+ plural: 'times of day',
1031
+ example: '12:34:56',
1032
+ date: false,
1033
+ time: true,
1034
+ offset: false,
1035
+ },
1036
+ timeWithOffset: {
1037
+ description: 'a time of day with a UTC offset',
1038
+ plural: 'times of day with a UTC offset',
1039
+ example: '12:34:56+02:00',
1040
+ date: false,
1041
+ time: true,
1042
+ offset: true,
1043
+ },
1044
+ dateTime: {
1045
+ description: 'a date and time',
1046
+ plural: 'dates and times',
1047
+ example: '2024-01-01T12:34:56',
1048
+ date: true,
1049
+ time: true,
1050
+ offset: false,
1051
+ },
1052
+ instant: {
1053
+ description: 'a date and time with a UTC offset',
1054
+ plural: 'instants',
1055
+ example: '2024-01-01T12:34:56Z',
1056
+ date: true,
1057
+ time: true,
1058
+ offset: true,
1059
+ },
1060
+ };
1061
+
1062
+ const DATE_PREFIX = /^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})/;
1063
+ const TIME_PREFIX = /^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?/;
1064
+ const OFFSET = /^([+-])(\d{2})(?::(\d{2})(?::(\d{2}))?)?$/;
1065
+ const MAX_FRACTION_DIGITS = 6;
1066
+ const SECONDS_PER_DAY = 86_400;
1067
+ const MIDNIGHT: TimeFields = { hour: 0, minute: 0, second: 0, fraction: '' };
1068
+
1069
+ function isLeapYear(year: number): boolean {
1070
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
1071
+ }
1072
+
1073
+ function daysInMonth(year: number, month: number): number {
1074
+ if (month === 2) return isLeapYear(year) ? 29 : 28;
1075
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
1076
+ }
1077
+
1078
+ function daysFromCivil({ year, month, day }: DateFields): number {
1079
+ const shifted = month <= 2 ? year - 1 : year;
1080
+ const era = Math.floor(shifted / 400);
1081
+ const yearOfEra = shifted - era * 400;
1082
+ const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
1083
+ const dayOfEra =
1084
+ yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
1085
+ return era * 146_097 + dayOfEra - 719_468;
1086
+ }
1087
+
1088
+ function civilFromDays(days: number): DateFields {
1089
+ const shifted = days + 719_468;
1090
+ const era = Math.floor(shifted / 146_097);
1091
+ const dayOfEra = shifted - era * 146_097;
1092
+ const yearOfEra = Math.floor(
1093
+ (dayOfEra -
1094
+ Math.floor(dayOfEra / 1460) +
1095
+ Math.floor(dayOfEra / 36_524) -
1096
+ Math.floor(dayOfEra / 146_096)) /
1097
+ 365,
1098
+ );
1099
+ const dayOfYear =
1100
+ dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
1101
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
1102
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
1103
+ const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9;
1104
+ return { year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day };
1105
+ }
1106
+
1107
+ function pad(value: number, width = 2): string {
1108
+ return String(value).padStart(width, '0');
1109
+ }
1110
+
1111
+ function yearText(year: number): string {
1112
+ if (year >= 0 && year <= 9999) return pad(year, 4);
1113
+ return `${year < 0 ? '-' : '+'}${pad(Math.abs(year), 6)}`;
1114
+ }
1115
+
1116
+ function dateText(date: DateFields): string {
1117
+ return `${yearText(date.year)}-${pad(date.month)}-${pad(date.day)}`;
1118
+ }
1119
+
1120
+ function timeText(time: TimeFields): string {
1121
+ const fraction = time.fraction.replace(/0+$/, '');
1122
+ return `${pad(time.hour)}:${pad(time.minute)}:${pad(time.second)}${fraction === '' ? '' : `.${fraction}`}`;
1123
+ }
1124
+
1125
+ function offsetText(seconds: number): string {
1126
+ if (seconds === 0) return 'Z';
1127
+ const magnitude = Math.abs(seconds);
1128
+ const rest = magnitude % 60;
1129
+ return `${seconds < 0 ? '-' : '+'}${pad(Math.floor(magnitude / 3600))}:${pad(Math.floor(magnitude / 60) % 60)}${rest === 0 ? '' : `:${pad(rest)}`}`;
1130
+ }
1131
+
1132
+ function readWritten(text: string): WrittenDateTime | undefined {
1133
+ let rest = text;
1134
+ let date: DateFields | undefined;
1135
+ let timeFollows = true;
1136
+ const dateMatch = DATE_PREFIX.exec(rest);
1137
+ if (dateMatch !== null) {
1138
+ const [whole, yearDigits = '', month = '', day = ''] = dateMatch;
1139
+ if (yearDigits === '-000000') return undefined;
1140
+ date = { year: Number(yearDigits), month: Number(month), day: Number(day) };
1141
+ rest = rest.slice(whole.length);
1142
+ timeFollows = /^[Tt ]/.test(rest);
1143
+ if (timeFollows) rest = rest.slice(1);
1144
+ }
1145
+ let time: TimeFields | undefined;
1146
+ let fractionDigits = 0;
1147
+ if (timeFollows) {
1148
+ const timeMatch = TIME_PREFIX.exec(rest);
1149
+ if (timeMatch === null) return undefined;
1150
+ const [whole, hour = '', minute = '', second = '00', fraction = ''] = timeMatch;
1151
+ time = { hour: Number(hour), minute: Number(minute), second: Number(second), fraction };
1152
+ fractionDigits = fraction.length;
1153
+ rest = rest.slice(whole.length);
1154
+ }
1155
+ let offsetSeconds: number | undefined;
1156
+ if (rest === 'Z' || rest === 'z') {
1157
+ offsetSeconds = 0;
1158
+ } else if (rest !== '') {
1159
+ const offset = OFFSET.exec(rest);
1160
+ if (offset === null) return undefined;
1161
+ const [, sign, hours = '', minutes = '00', seconds = '00'] = offset;
1162
+ if (Number(minutes) > 59 || Number(seconds) > 59) return undefined;
1163
+ const magnitude = Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);
1164
+ offsetSeconds = sign === '-' ? -magnitude : magnitude;
1165
+ }
1166
+ return { date, time, offsetSeconds, fractionDigits };
1167
+ }
1168
+
1169
+ type Position = readonly [days: number, seconds: number, fraction: string];
1170
+
1171
+ interface NormalizedDateTime {
1172
+ readonly date: DateFields | undefined;
1173
+ readonly time: TimeFields;
1174
+ readonly offsetSeconds: number;
1175
+ }
1176
+
1177
+ function normalized(written: WrittenDateTime, shape: DateTimeShape): NormalizedDateTime {
1178
+ const clock = written.time ?? MIDNIGHT;
1179
+ const offsetSeconds = written.offsetSeconds ?? 0;
1180
+ if (written.date === undefined || shape !== 'instant')
1181
+ return { date: written.date, time: clock, offsetSeconds };
1182
+ const utc =
1183
+ daysFromCivil(written.date) * SECONDS_PER_DAY +
1184
+ clock.hour * 3600 +
1185
+ clock.minute * 60 +
1186
+ clock.second -
1187
+ offsetSeconds;
1188
+ const days = Math.floor(utc / SECONDS_PER_DAY);
1189
+ const secondOfDay = utc - days * SECONDS_PER_DAY;
1190
+ return {
1191
+ date: civilFromDays(days),
1192
+ time: {
1193
+ hour: Math.floor(secondOfDay / 3600),
1194
+ minute: Math.floor(secondOfDay / 60) % 60,
1195
+ second: secondOfDay % 60,
1196
+ fraction: clock.fraction,
1197
+ },
1198
+ offsetSeconds: 0,
1199
+ };
1200
+ }
1201
+
1202
+ function position(value: NormalizedDateTime): Position {
1203
+ const { time } = value;
1204
+ return [
1205
+ value.date === undefined ? 0 : daysFromCivil(value.date),
1206
+ time.hour * 3600 + time.minute * 60 + time.second,
1207
+ time.fraction.padEnd(MAX_FRACTION_DIGITS, '0'),
1208
+ ];
1209
+ }
1210
+
1211
+ function isBefore(left: Position, right: Position): boolean {
1212
+ if (left[0] !== right[0]) return left[0] < right[0];
1213
+ if (left[1] !== right[1]) return left[1] < right[1];
1214
+ return left[2] < right[2];
1215
+ }
1216
+
1217
+ function printed(value: NormalizedDateTime, shape: DateTimeShape): string {
1218
+ const { date, time, offsetSeconds } = value;
1219
+ if (date === undefined)
1220
+ return shape === 'timeWithOffset'
1221
+ ? `${timeText(time)}${offsetText(offsetSeconds)}`
1222
+ : timeText(time);
1223
+ if (shape === 'date') return dateText(date);
1224
+ if (shape === 'dateTime') return `${dateText(date)}T${timeText(time)}`;
1225
+ return `${dateText(date)}T${timeText(time)}Z`;
1226
+ }
1227
+
1228
+ function boundPosition(text: string, shape: DateTimeShape): Position {
1229
+ const written = readWritten(text);
1230
+ if (written === undefined)
1231
+ throw new Error(`The range bound "${text}" is not in its stored form.`);
1232
+ return position(normalized(written, shape));
1233
+ }
1234
+
1235
+ function dateTimeStoredText(text: string, options: DateTimeOptions, written: string): string {
1236
+ const shape = SHAPES[options.shape];
1237
+ const id = options.typeId;
1238
+ const parts = readWritten(text);
1239
+ if (parts === undefined)
1240
+ throw new CastRefused(
1241
+ `${id} cannot read "${written}". Write ${shape.description}, as in "${shape.example}".`,
1242
+ );
1243
+ if (parts.date !== undefined && !shape.date)
1244
+ throw new CastRefused(
1245
+ `${id} holds a time of day without a date, but "${written}" has a date. Write the time alone, as in "${shape.example}".`,
1246
+ );
1247
+ if (parts.date === undefined && shape.date)
1248
+ throw new CastRefused(
1249
+ shape.time
1250
+ ? `${id} holds ${shape.description}, but "${written}" has no date. Write the date too, as in "${shape.example}".`
1251
+ : `${id} holds a date, and "${written}" is a time of day. Write a date, as in "${shape.example}".`,
1252
+ );
1253
+ if (parts.time !== undefined && !shape.time)
1254
+ throw new CastRefused(
1255
+ `${id} holds a date without a time of day, but "${written}" has a time. Write the date alone, as in "${shape.example}".`,
1256
+ );
1257
+ if (parts.time === undefined && shape.offset)
1258
+ throw new CastRefused(
1259
+ `${id} holds ${shape.description}, but "${written}" has no time of day. Write the time too, as in "${shape.example}".`,
1260
+ );
1261
+ if (parts.offsetSeconds !== undefined && !shape.offset)
1262
+ throw new CastRefused(
1263
+ `${id} holds no UTC offset, but "${written}" has one. Leave it out, as in "${shape.example}".`,
1264
+ );
1265
+ if (parts.offsetSeconds === undefined && shape.offset)
1266
+ throw new CastRefused(
1267
+ `${id} needs a UTC offset, but "${written}" has none. Add Z for UTC or an offset such as +02:00, as in "${shape.example}".`,
1268
+ );
1269
+ if (parts.fractionDigits > MAX_FRACTION_DIGITS)
1270
+ throw new CastRefused(
1271
+ `"${written}" has ${parts.fractionDigits} digits after the decimal point, but ${id} holds microseconds, so at most ${MAX_FRACTION_DIGITS}. Round it, as in "${shape.example.replace(/(\d{2}:\d{2}:\d{2})/, '$1.123456')}".`,
1272
+ );
1273
+ const { date, time } = parts;
1274
+ if (
1275
+ date !== undefined &&
1276
+ (date.month < 1 ||
1277
+ date.month > 12 ||
1278
+ date.day < 1 ||
1279
+ date.day > daysInMonth(date.year, date.month))
1280
+ )
1281
+ throw new CastRefused(
1282
+ `"${written}" is not a date that exists. Write a real date, as in "${shape.example}".`,
1283
+ );
1284
+ if (time !== undefined && (time.hour > 23 || time.minute > 59 || time.second > 59))
1285
+ throw new CastRefused(
1286
+ `"${written}" is not a time of day that exists: hours run from 00 to 23, and minutes and seconds from 00 to 59. Write one, as in "${shape.example}".`,
1287
+ );
1288
+ const offsetLimit = options.maxOffsetHours ?? 23;
1289
+ if (
1290
+ parts.offsetSeconds !== undefined &&
1291
+ Math.abs(parts.offsetSeconds) >= (offsetLimit + 1) * 3600
1292
+ )
1293
+ throw new CastRefused(
1294
+ `"${written}" has a UTC offset outside -${pad(offsetLimit)}:59 to +${pad(offsetLimit)}:59, which ${id} does not hold. Write a smaller offset, as in "${shape.example}".`,
1295
+ );
1296
+ const value = normalized(parts, options.shape);
1297
+ const { range } = options;
1298
+ if (range !== undefined) {
1299
+ const at = position(value);
1300
+ if (
1301
+ isBefore(at, boundPosition(range.earliest, options.shape)) ||
1302
+ isBefore(boundPosition(range.latest, options.shape), at)
1303
+ )
1304
+ throw new CastRefused(
1305
+ `${id} holds ${shape.plural} from ${range.earliest} to ${range.latest}, and "${written}" is outside them.`,
1306
+ );
1307
+ }
1308
+ return printed(value, options.shape);
1309
+ }
1310
+
1311
+ const INFINITIES: ReadonlySet<string> = new Set(['infinity', '-infinity']);
1312
+
1313
+ function postgresDateTime(
1314
+ options: DateTimeOptions,
1315
+ holdsInfinity: boolean,
1316
+ ): (text: string) => string {
1317
+ return (text) =>
1318
+ holdsInfinity && INFINITIES.has(text)
1319
+ ? text
1320
+ : dateTimeStoredText(isoYearText(text), options, text);
1321
+ }
1322
+
1323
+ function storedForm(
1324
+ storedText: (text: string) => string,
1325
+ text: string,
1326
+ ): { readonly stored: string } | { readonly reason: string } {
1327
+ try {
1328
+ return { stored: storedText(text) };
1329
+ } catch (error) {
1330
+ if (error instanceof CastRefused) return { reason: error.message };
1331
+ throw error;
1332
+ }
1333
+ }
1334
+
1335
+ const SECONDS_FRACTION = /:\d{2}\.(\d+)/;
1336
+ const INTERVAL_SECONDS_FRACTION = /\d\.(\d+)S$/;
1337
+
1338
+ function storedTextType(
1339
+ typeId: string,
1340
+ storedText: (text: string) => string,
1341
+ description: string,
1342
+ fraction: RegExp,
1343
+ ): Pick<PostgresDataType, 'read' | 'spell'> {
1344
+ return {
1345
+ read: (json, params) => {
1346
+ if (typeof json !== 'string') return refuseJsonValue(typeId, description);
1347
+ const form = storedForm(storedText, json);
1348
+ if ('reason' in form) return refuseJsonValue(typeId, `${description}: ${form.reason}`);
1349
+ const precision = integerParam(params, 'precision') ?? MAX_FRACTION_DIGITS;
1350
+ if (withoutTrailing(fraction.exec(form.stored)?.[1] ?? '', '0').length > precision)
1351
+ return refuseJsonValue(
1352
+ typeId,
1353
+ `a value with at most ${counted(precision, 'fraction digit')} of a second, which precision ${precision} holds without rounding`,
1354
+ );
1355
+ return json;
1356
+ },
1357
+ spell: (json) => {
1358
+ if (typeof json !== 'string') return json;
1359
+ const form = storedForm(storedText, json);
1360
+ return 'stored' in form ? form.stored : json;
1361
+ },
1362
+ };
1363
+ }
1364
+
1365
+ type ParamRule = (value: Json | undefined) => boolean;
1366
+
1367
+ const optionalInteger =
1368
+ (min: number, max: number): ParamRule =>
1369
+ (value) =>
1370
+ value === undefined ||
1371
+ (typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max);
1372
+
1373
+ interface PostgresDataType {
1374
+ readonly params?: Readonly<Record<string, ParamRule>>;
1375
+ readonly read: (json: Json, params: Params) => Json;
1376
+ readonly spell?: (json: Json, params: Params) => Json;
1377
+ }
1378
+
1379
+ const NUMERIC_PARAMS = {
1380
+ precision: optionalInteger(1, 1000),
1381
+ scale: optionalInteger(-1000, 1000),
1382
+ };
1383
+ const CHARACTER_LENGTH_PARAMS = { length: optionalInteger(1, 10485760) };
1384
+ const BIT_LENGTH_PARAMS = { length: optionalInteger(1, 83886080) };
1385
+ const PRECISION_PARAMS = { precision: optionalInteger(0, 6) };
1386
+ const readString =
1387
+ (typeId: string): PostgresDataType['read'] =>
1388
+ (json) =>
1389
+ readJsonString(typeId, json);
1390
+ const anyJson: PostgresDataType['read'] = (json) => json;
1391
+
1392
+ const requiredInteger =
1393
+ (min: number, max: number): ParamRule =>
1394
+ (value) =>
1395
+ typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
1396
+
1397
+ const HEX_TEXT = /^(?:[0-9A-Fa-f]{2})*$/;
1398
+ const EWKB_FLAG_Z = 0x80000000;
1399
+ const EWKB_FLAG_M = 0x40000000;
1400
+ const EWKB_FLAG_SRID = 0x20000000;
1401
+ const EWKB_TYPE_MASK = 0x1fffffff;
1402
+ const EWKB_POINT = 1;
1403
+ const EWKB_LINESTRING = 2;
1404
+ const EWKB_POLYGON = 3;
1405
+ const EWKB_MULTI_PARTS: ReadonlyMap<number, number> = new Map([
1406
+ [4, EWKB_POINT],
1407
+ [5, EWKB_LINESTRING],
1408
+ [6, EWKB_POLYGON],
1409
+ ]);
1410
+
1411
+ class NotEwkb extends Error {}
1412
+
1413
+ interface EwkbGeometry {
1414
+ readonly srid: number | undefined;
1415
+ /** The geometry as the upper-case little-endian HEXEWKB PostGIS prints, or undefined when a coordinate is not finite. */
1416
+ readonly printed: string | undefined;
1417
+ }
1418
+
1419
+ /** Reads HEXEWKB in either case and byte order, as `postgis/geometry` of 8.0.0-rc.19 does: points, line strings, polygons and their multi forms, without Z or M coordinates. */
1420
+ function readEwkb(hex: string): EwkbGeometry {
1421
+ const bytes = Buffer.from(hex, 'hex');
1422
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1423
+ const out: number[] = [];
1424
+ let offset = 0;
1425
+ let finite = true;
1426
+ const take = (size: number): number => {
1427
+ if (offset + size > view.byteLength) throw new NotEwkb();
1428
+ const at = offset;
1429
+ offset += size;
1430
+ return at;
1431
+ };
1432
+ const writeUint32 = (value: number): void => {
1433
+ const buffer = Buffer.alloc(4);
1434
+ buffer.writeUInt32LE(value >>> 0);
1435
+ out.push(...buffer);
1436
+ };
1437
+ const header = (top: boolean): { type: number; little: boolean; srid: number | undefined } => {
1438
+ const order = view.getUint8(take(1));
1439
+ if (order !== 0 && order !== 1) throw new NotEwkb();
1440
+ const little = order === 1;
1441
+ const code = view.getUint32(take(4), little) >>> 0;
1442
+ if ((code & EWKB_FLAG_Z) !== 0 || (code & EWKB_FLAG_M) !== 0) throw new NotEwkb();
1443
+ const type = code & EWKB_TYPE_MASK;
1444
+ const srid = (code & EWKB_FLAG_SRID) !== 0 ? view.getUint32(take(4), little) >>> 0 : undefined;
1445
+ out.push(1);
1446
+ writeUint32(top && srid !== undefined ? type | EWKB_FLAG_SRID : type);
1447
+ if (top && srid !== undefined) writeUint32(srid);
1448
+ return { type, little, srid };
1449
+ };
1450
+ const count = (little: boolean): number => {
1451
+ const value = view.getUint32(take(4), little) >>> 0;
1452
+ writeUint32(value);
1453
+ return value;
1454
+ };
1455
+ const positions = (amount: number, little: boolean): void => {
1456
+ for (let index = 0; index < amount * 2; index++) {
1457
+ const value = view.getFloat64(take(8), little);
1458
+ if (!Number.isFinite(value)) finite = false;
1459
+ const buffer = Buffer.alloc(8);
1460
+ buffer.writeDoubleLE(value);
1461
+ out.push(...buffer);
1462
+ }
1463
+ };
1464
+ const body = (type: number, little: boolean): void => {
1465
+ if (type === EWKB_POINT) positions(1, little);
1466
+ else if (type === EWKB_LINESTRING) positions(count(little), little);
1467
+ else if (type === EWKB_POLYGON)
1468
+ for (let ring = count(little); ring > 0; ring--) positions(count(little), little);
1469
+ else throw new NotEwkb();
1470
+ };
1471
+ const top = header(true);
1472
+ const part = EWKB_MULTI_PARTS.get(top.type);
1473
+ if (part === undefined) body(top.type, top.little);
1474
+ else
1475
+ for (let index = count(top.little); index > 0; index--) {
1476
+ const sub = header(false);
1477
+ if (sub.type !== part) throw new NotEwkb();
1478
+ body(sub.type, sub.little);
1479
+ }
1480
+ if (offset !== view.byteLength) throw new NotEwkb();
1481
+ return {
1482
+ srid: top.srid,
1483
+ printed: finite ? Buffer.from(out).toString('hex').toUpperCase() : undefined,
1484
+ };
1485
+ }
1486
+
1487
+ function ewkbOf(json: Json): EwkbGeometry | undefined {
1488
+ if (typeof json !== 'string') return undefined;
1489
+ try {
1490
+ return readEwkb(json);
1491
+ } catch (error) {
1492
+ if (error instanceof NotEwkb) return undefined;
1493
+ throw error;
1494
+ }
1495
+ }
1496
+
1497
+ function readGeometry(json: Json, params: Params): Json {
1498
+ readJsonMatching('postgis/geometry', json, HEX_TEXT, 'a HEXEWKB string');
1499
+ const srid = integerParam(params, 'srid');
1500
+ const geometry = ewkbOf(json);
1501
+ if (geometry === undefined || (srid !== undefined && geometry.srid !== srid))
1502
+ return refuseJsonValue(
1503
+ 'postgis/geometry',
1504
+ srid !== undefined ? `a HEXEWKB string of a geometry with SRID ${srid}` : 'a HEXEWKB string',
1505
+ );
1506
+ return json;
1507
+ }
1508
+
1509
+ function spellGeometry(json: Json): Json {
1510
+ const geometry = ewkbOf(json);
1511
+ if (geometry === undefined) return json;
1512
+ if (geometry.printed === undefined)
1513
+ throw new NotAValue('Geometry encode: coordinates must be finite numbers');
1514
+ return geometry.printed;
1515
+ }
1516
+
1517
+ /** The text PostgreSQL prints for `value` stored as a `real`: the shortest decimal that reads back as the same single-precision number. */
1518
+ function realText(value: number): string {
1519
+ const single = Math.fround(value);
1520
+ for (let digits = 1; digits <= 9; digits++) {
1521
+ const text = String(Number(single.toPrecision(digits)));
1522
+ if (Math.fround(Number(text)) === single) return text;
1523
+ }
1524
+ return String(single);
1525
+ }
1526
+
1527
+ function readVector(json: Json, params: Params): Json {
1528
+ const length = integerParam(params, 'length');
1529
+ const expected =
1530
+ length === undefined
1531
+ ? 'an array of finite numbers'
1532
+ : `an array of ${counted(length, 'finite number')}`;
1533
+ if (!Array.isArray(json) || (length !== undefined && json.length !== length))
1534
+ return refuseJsonValue('pgvector/vector', expected);
1535
+ for (const element of json)
1536
+ if (typeof element !== 'number' || !Number.isFinite(element))
1537
+ return refuseJsonValue('pgvector/vector', expected);
1538
+ for (const [index, element] of json.entries()) {
1539
+ if (typeof element !== 'number') continue;
1540
+ const refuse = (why: string) =>
1541
+ refuseJsonValue(
1542
+ 'pgvector/vector',
1543
+ `an array of numbers real holds exactly; element ${index + 1}, ${element}, ${why}`,
1544
+ );
1545
+ if (!Number.isFinite(Math.fround(element)))
1546
+ return refuse('is outside the range real holds, which PostgreSQL refuses');
1547
+ const stored = realText(element);
1548
+ if (Number(stored) !== element) return refuse(`would be stored as ${stored}`);
1549
+ }
1550
+ return json;
1551
+ }
1552
+
1553
+ const POSTGRES_DATA_TYPES: ReadonlyMap<string, PostgresDataType> = new Map<
1554
+ string,
1555
+ PostgresDataType
1556
+ >([
1557
+ ['pg/text', { read: readString('pg/text') }],
1558
+ ['pg/text-array', { read: readTextArray }],
1559
+ [
1560
+ 'pg/enum',
1561
+ {
1562
+ params: { typeName: (value) => typeof value === 'string' && value.length > 0 },
1563
+ read: readString('pg/enum'),
1564
+ },
1565
+ ],
1566
+ ['pg/int2', { read: (json) => readJsonInteger('pg/int2', json, -32768, 32767) }],
1567
+ [
1568
+ 'pg/bool',
1569
+ {
1570
+ read: (json) => (typeof json === 'boolean' ? json : refuseJsonValue('pg/bool', 'a boolean')),
1571
+ },
1572
+ ],
1573
+ ['pg/json', { read: anyJson }],
1574
+ ['pg/tsquery', { read: readString('pg/tsquery') }],
1575
+ ['pg/int4', { read: (json) => readJsonInteger('pg/int4', json, -(2 ** 31), 2 ** 31 - 1) }],
1576
+ ['pg/int8', { read: readInt8 }],
1577
+ ['pg/numeric', { params: NUMERIC_PARAMS, read: readNumeric, spell: spellNumeric }],
1578
+ ['pg/float4', { read: readFloat4 }],
1579
+ [
1580
+ 'pg/float8',
1581
+ {
1582
+ read: (json) => {
1583
+ readJsonFloat('pg/float8', json);
1584
+ return json;
1585
+ },
1586
+ },
1587
+ ],
1588
+ ['pg/jsonb', { read: anyJson }],
1589
+ ['pg/char', { params: CHARACTER_LENGTH_PARAMS, read: readCharacter, spell: spellCharacter }],
1590
+ ['pg/varchar', { params: CHARACTER_LENGTH_PARAMS, read: readCharacterVarying }],
1591
+ [
1592
+ 'pg/uuid',
1593
+ {
1594
+ read: (json) =>
1595
+ typeof json === 'string' && storedUuid(json) !== undefined
1596
+ ? json
1597
+ : refuseJsonValue(
1598
+ 'pg/uuid',
1599
+ 'a UUID in a spelling PostgreSQL reads: 32 hexadecimal digits in either case, with or without a hyphen after any group of four, optionally in braces',
1600
+ ),
1601
+ spell: (json) => (typeof json === 'string' ? (storedUuid(json) ?? json) : json),
1602
+ },
1603
+ ],
1604
+ [
1605
+ 'pg/inet',
1606
+ {
1607
+ read: (json) =>
1608
+ typeof json === 'string' && storedInet(json) !== undefined
1609
+ ? json
1610
+ : refuseJsonValue(
1611
+ 'pg/inet',
1612
+ 'an IP address or network in a spelling PostgreSQL reads, as in 10.0.0.1 or 2001:db8::/32',
1613
+ ),
1614
+ spell: (json) => (typeof json === 'string' ? (storedInet(json) ?? json) : json),
1615
+ },
1616
+ ],
1617
+ ['pg/bit', { params: BIT_LENGTH_PARAMS, read: readBit }],
1618
+ ['pg/varbit', { params: BIT_LENGTH_PARAMS, read: readBitVarying }],
1619
+ [
1620
+ 'pg/timetz',
1621
+ {
1622
+ params: PRECISION_PARAMS,
1623
+ ...storedTextType(
1624
+ 'pg/timetz',
1625
+ postgresDateTime(
1626
+ { shape: 'timeWithOffset', typeId: 'pg/timetz', maxOffsetHours: 15 },
1627
+ false,
1628
+ ),
1629
+ 'a time of day with its UTC offset, as in "12:34:56+02:00" or "12:34:56Z"',
1630
+ SECONDS_FRACTION,
1631
+ ),
1632
+ },
1633
+ ],
1634
+ [
1635
+ 'pg/interval',
1636
+ {
1637
+ params: PRECISION_PARAMS,
1638
+ ...storedTextType(
1639
+ 'pg/interval',
1640
+ intervalStoredText,
1641
+ 'an ISO 8601 duration, as in "P1Y2M3DT4H5M6.5S"',
1642
+ INTERVAL_SECONDS_FRACTION,
1643
+ ),
1644
+ },
1645
+ ],
1646
+ [
1647
+ 'pg/bytea',
1648
+ {
1649
+ read: (json) => readJsonMatching('pg/bytea', json, BASE64_TEXT, 'a base64 string'),
1650
+ spell: spellBytea,
1651
+ },
1652
+ ],
1653
+ [
1654
+ 'pg/date',
1655
+ storedTextType(
1656
+ 'pg/date',
1657
+ postgresDateTime(
1658
+ {
1659
+ shape: 'date',
1660
+ typeId: 'pg/date',
1661
+ range: { earliest: '-004713-11-24', latest: '+275760-09-13' },
1662
+ },
1663
+ true,
1664
+ ),
1665
+ 'a date, as in "2024-01-01", or infinity or -infinity',
1666
+ SECONDS_FRACTION,
1667
+ ),
1668
+ ],
1669
+ [
1670
+ 'pg/time',
1671
+ {
1672
+ params: PRECISION_PARAMS,
1673
+ ...storedTextType(
1674
+ 'pg/time',
1675
+ postgresDateTime({ shape: 'time', typeId: 'pg/time' }, false),
1676
+ 'a time of day, as in "12:34:56"',
1677
+ SECONDS_FRACTION,
1678
+ ),
1679
+ },
1680
+ ],
1681
+ [
1682
+ 'pg/timestamp',
1683
+ {
1684
+ params: PRECISION_PARAMS,
1685
+ ...storedTextType(
1686
+ 'pg/timestamp',
1687
+ postgresDateTime(
1688
+ {
1689
+ shape: 'dateTime',
1690
+ typeId: 'pg/timestamp',
1691
+ range: { earliest: '-004713-11-24T00:00:00', latest: '+275760-09-13T23:59:59.999999' },
1692
+ },
1693
+ true,
1694
+ ),
1695
+ 'a date and time of day, as in "2024-01-01T12:34:56", or infinity or -infinity',
1696
+ SECONDS_FRACTION,
1697
+ ),
1698
+ },
1699
+ ],
1700
+ [
1701
+ 'pg/timestamptz',
1702
+ {
1703
+ params: PRECISION_PARAMS,
1704
+ ...storedTextType(
1705
+ 'pg/timestamptz',
1706
+ postgresDateTime(
1707
+ {
1708
+ shape: 'instant',
1709
+ typeId: 'pg/timestamptz',
1710
+ range: { earliest: '-004713-11-24T00:00:00Z', latest: '+275760-09-13T00:00:00Z' },
1711
+ },
1712
+ true,
1713
+ ),
1714
+ 'an instant in UTC, as in "2024-01-01T00:00:00Z", or infinity or -infinity',
1715
+ SECONDS_FRACTION,
1716
+ ),
1717
+ },
1718
+ ],
1719
+ [
1720
+ 'postgis/geometry',
1721
+ {
1722
+ params: { srid: optionalInteger(1, Number.POSITIVE_INFINITY) },
1723
+ read: readGeometry,
1724
+ spell: spellGeometry,
1725
+ },
1726
+ ],
1727
+ ['pgvector/vector', { params: { length: requiredInteger(1, 16000) }, read: readVector }],
1728
+ ]);
1729
+
1730
+ function resolvedTypeParams(column: JsonRecord, namedTypes: Json | undefined): Json | undefined {
1731
+ const typeRef = column['typeRef'];
1732
+ const named =
1733
+ typeof typeRef === 'string' && isRecord(namedTypes) ? namedTypes[typeRef] : undefined;
1734
+ const typeParams = column['typeParams'] ?? (isRecord(named) ? named['typeParams'] : undefined);
1735
+ return isRecord(typeParams) && Object.keys(typeParams).length > 0 ? typeParams : undefined;
1736
+ }
1737
+
1738
+ /** The parameters of the column that its data type declares, or undefined when the type refuses them. */
1739
+ function declaredParams(type: PostgresDataType, typeParams: Json | undefined): Params | undefined {
1740
+ const params: Record<string, Json> = {};
1741
+ for (const [name, accepts] of Object.entries(type.params ?? {})) {
1742
+ const value = isRecord(typeParams) ? typeParams[name] : undefined;
1743
+ if (!accepts(value)) return undefined;
1744
+ if (value !== undefined) params[name] = value;
1745
+ }
1746
+ if (params['scale'] !== undefined && params['precision'] === undefined) return undefined;
1747
+ return params;
1748
+ }
1749
+
1750
+ interface ColumnType {
1751
+ readonly id: string;
1752
+ readonly type: PostgresDataType;
1753
+ readonly params: Params;
1754
+ readonly list: boolean;
1755
+ }
1756
+
1757
+ /** The column's data type and parameters, or undefined when this release does not register the type or refuses the parameters, and so does not read the default. */
1758
+ function columnType(column: JsonRecord, namedTypes: Json | undefined): ColumnType | undefined {
1759
+ const id = column['dataType'];
1760
+ const type = typeof id === 'string' ? POSTGRES_DATA_TYPES.get(id) : undefined;
1761
+ if (typeof id !== 'string' || type === undefined) return undefined;
1762
+ const params = declaredParams(type, resolvedTypeParams(column, namedTypes));
1763
+ if (params === undefined) return undefined;
1764
+ const many = column['many'];
1765
+ return { id, type, params, list: many !== undefined && many !== false };
1766
+ }
1767
+
1768
+ /** A literal default value in the contract form this release stores. */
1769
+ function contractFormOfDefault(value: Json, { type, params }: ColumnType): DefaultForm {
1770
+ let stored: Json;
1771
+ try {
1772
+ const read = type.read(value, params);
1773
+ stored = type.spell === undefined ? read : type.spell(read, params);
1774
+ } catch (error) {
1775
+ if (error instanceof NotAValue) return { kind: 'notAValue', reason: error.message };
1776
+ throw error;
1777
+ }
1778
+ return canonicalizeJson(stored) === canonicalizeJson(value)
1779
+ ? { kind: 'unchanged' }
1780
+ : { kind: 'rewritten', value: stored };
1781
+ }
1782
+
1783
+ type StoredDefault =
1784
+ | { readonly kind: 'stored'; readonly value: Json }
1785
+ | { readonly kind: 'refused'; readonly reason: string };
1786
+
1787
+ /** A column's default in the contract form this release stores, element by element on a list column, or why this release refuses it. */
1788
+ function storedDefault(value: Json, columnType: ColumnType): StoredDefault {
1789
+ if (value === null) return { kind: 'stored', value };
1790
+ if (columnType.list && !Array.isArray(value))
1791
+ return {
1792
+ kind: 'refused',
1793
+ reason: `the default ${JSON.stringify(value)} is not a list, and the column holds a list of ${columnType.id}`,
1794
+ };
1795
+ const values = columnType.list && Array.isArray(value) ? value : [value];
1796
+ const stored: Json[] = [];
1797
+ for (const element of values) {
1798
+ const form = element === null ? undefined : contractFormOfDefault(element, columnType);
1799
+ if (form?.kind === 'notAValue')
1800
+ return {
1801
+ kind: 'refused',
1802
+ reason: `the default ${JSON.stringify(element)} is not a value of ${columnType.id} (${form.reason})`,
1803
+ };
1804
+ stored.push(form?.kind === 'rewritten' ? form.value : element);
1805
+ }
1806
+ return { kind: 'stored', value: columnType.list ? stored : (stored[0] ?? null) };
1807
+ }
1808
+
1809
+ /** The scalar values that changed between two defaults, pairing list elements by position, for the literal types of `contract.d.ts`. */
1810
+ function defaultRewrites(from: Json, to: Json): DefaultRewrite[] {
1811
+ const pairs: [Json, Json][] =
1812
+ Array.isArray(from) && Array.isArray(to)
1813
+ ? from.length === to.length
1814
+ ? from.map((element, index) => [element, to[index] ?? null])
1815
+ : []
1816
+ : [[from, to]];
1817
+ return pairs.flatMap(([a, b]) =>
1818
+ (typeof a === 'string' && typeof b === 'string') ||
1819
+ (typeof a === 'number' && typeof b === 'number')
1820
+ ? a === b
1821
+ ? []
1822
+ : [{ from: a, to: b }]
1823
+ : [],
1824
+ );
1825
+ }
1826
+
1827
+ /** How `--default` names a column: `<namespace>.<table>.<column>`. */
1828
+ function defaultKey(namespaceId: string, tableName: string, columnName: string): string {
1829
+ return `${namespaceId}.${tableName}.${columnName}`;
1830
+ }
1831
+
1832
+ interface ColumnEntry {
1833
+ readonly namespaceId: string;
1834
+ readonly tableName: string;
1835
+ readonly columnName: string;
1836
+ readonly column: JsonRecord;
1837
+ }
1838
+
1839
+ function columnsOf(contract: JsonRecord): ColumnEntry[] {
1840
+ const storage = contract['storage'];
1841
+ const namespaces = isRecord(storage) ? storage['namespaces'] : undefined;
1842
+ return Object.entries(isRecord(namespaces) ? namespaces : {}).flatMap(
1843
+ ([namespaceId, namespace]) => {
1844
+ const entries = isRecord(namespace) ? namespace['entries'] : undefined;
1845
+ const tables = isRecord(entries) ? entries['table'] : undefined;
1846
+ return Object.entries(isRecord(tables) ? tables : {}).flatMap(([tableName, table]) => {
1847
+ const columns = isRecord(table) ? table['columns'] : undefined;
1848
+ return Object.entries(isRecord(columns) ? columns : {}).flatMap(([columnName, column]) =>
1849
+ isRecord(column) ? [{ namespaceId, tableName, columnName, column }] : [],
1850
+ );
1851
+ });
1852
+ },
1853
+ );
1854
+ }
1855
+
1856
+ /** Mutates `copy`: each literal default in the contract form this release stores, element by element on a list column. A default this release refuses takes the value given for its column with `--default`, and each column whose replacement was taken is added to `used`. */
1857
+ function rewriteDefaults(
1858
+ copy: JsonRecord,
1859
+ replacements: ReadonlyMap<string, Json>,
1860
+ used: Set<string>,
1861
+ ): {
1862
+ readonly defaults: Map<string, DefaultRewrite[]>;
1863
+ readonly notValues: string[];
1864
+ } {
1865
+ const defaults = new Map<string, DefaultRewrite[]>();
1866
+ const notValues: string[] = [];
1867
+ const storage = copy['storage'];
1868
+ const namedTypes = isRecord(storage) ? storage['types'] : undefined;
1869
+ for (const { namespaceId, tableName, columnName, column } of columnsOf(copy)) {
1870
+ const columnDefault = column['default'];
1871
+ if (!isRecord(columnDefault) || columnDefault['kind'] !== 'literal') continue;
1872
+ const original = columnDefault['value'];
1873
+ const type = columnType(column, namedTypes);
1874
+ if (original === undefined || type === undefined) continue;
1875
+ const place = `namespace ${namespaceId}, table ${tableName}, column ${columnName}`;
1876
+ const key = defaultKey(namespaceId, tableName, columnName);
1877
+ let stored = storedDefault(original, type);
1878
+ if (stored.kind === 'refused') {
1879
+ const replacement = replacements.get(key);
1880
+ if (replacement === undefined) {
1881
+ notValues.push(
1882
+ `${place}: ${stored.reason}; choose the value the database stores and run the script again with --default '${key}=<that value as JSON>'`,
1883
+ );
1884
+ continue;
1885
+ }
1886
+ used.add(key);
1887
+ stored = storedDefault(replacement, type);
1888
+ if (stored.kind === 'refused') {
1889
+ notValues.push(`${place}: --default ${key}: ${stored.reason}`);
1890
+ continue;
1891
+ }
1892
+ }
1893
+ if (canonicalizeJson(stored.value) === canonicalizeJson(original)) continue;
1894
+ columnDefault['value'] = stored.value;
1895
+ defaults.set(
1896
+ listKey(namespaceId, tableName, columnName),
1897
+ defaultRewrites(original, stored.value),
1898
+ );
1899
+ }
1900
+ return { defaults, notValues };
424
1901
  }
425
1902
 
426
1903
  function allowNullElements(holder: JsonRecord): void {
@@ -457,10 +1934,22 @@ function fieldsMappingColumns(copy: JsonRecord, columns: ReadonlySet<string>): S
457
1934
  return fields;
458
1935
  }
459
1936
 
460
- /** The contract with the key removed from each column, and the lists whose element check it waived made element-nullable. */
461
- function rewriteContract(contract: JsonRecord): Rewrite {
1937
+ /** The contract with the key removed from each column, the lists whose element check it waived made element-nullable, and each default in the contract form this release stores. */
1938
+ function rewriteContract(
1939
+ contract: JsonRecord,
1940
+ replacements: ReadonlyMap<string, Json>,
1941
+ used: Set<string>,
1942
+ ): Rewrite {
462
1943
  const copy = parseJson(JSON.stringify(contract));
463
- if (!isRecord(copy)) return { contract, changed: false, columns: new Set(), fields: new Set() };
1944
+ if (!isRecord(copy))
1945
+ return {
1946
+ contract,
1947
+ changed: false,
1948
+ columns: new Set(),
1949
+ fields: new Set(),
1950
+ defaults: new Map(),
1951
+ notValues: [],
1952
+ };
464
1953
  let changed = false;
465
1954
  const columns = new Set<string>();
466
1955
  const storage = copy['storage'];
@@ -484,7 +1973,18 @@ function rewriteContract(contract: JsonRecord): Rewrite {
484
1973
  }
485
1974
  }
486
1975
  }
487
- return { contract: copy, changed, columns, fields: fieldsMappingColumns(copy, columns) };
1976
+ const { defaults, notValues } =
1977
+ contract['target'] === 'postgres'
1978
+ ? rewriteDefaults(copy, replacements, used)
1979
+ : { defaults: new Map<string, DefaultRewrite[]>(), notValues: [] };
1980
+ return {
1981
+ contract: copy,
1982
+ changed: changed || defaults.size > 0,
1983
+ columns,
1984
+ fields: fieldsMappingColumns(copy, columns),
1985
+ defaults,
1986
+ notValues,
1987
+ };
488
1988
  }
489
1989
 
490
1990
  function withStorageHash(contract: JsonRecord, hash: string): JsonRecord {
@@ -524,10 +2024,11 @@ function scanBlocks(text: string): Block[] {
524
2024
  continue;
525
2025
  }
526
2026
  if (char === '{') {
2027
+ const before = text.slice(Math.max(0, index - 200), index);
527
2028
  const key =
528
2029
  /(?:readonly\s+)?([\p{ID_Start}_$][\p{ID_Continue}$]*|'[^']*'|"[^"]*")\s*\??\s*:\s*$/u.exec(
529
- text.slice(Math.max(0, index - 200), index),
530
- );
2030
+ before,
2031
+ ) ?? /\b(?:type|namespace)\s+([\p{ID_Start}_$][\p{ID_Continue}$]*)\s*=?\s*$/u.exec(before);
531
2032
  const block: Block = {
532
2033
  start: index,
533
2034
  end: text.length,
@@ -574,14 +2075,101 @@ function fieldBlockKey(block: Block): string | undefined {
574
2075
  return listKey(namespace.label, model.label, block.label);
575
2076
  }
576
2077
 
2078
+ const FIELD_TYPE_MAPS = new Set(['FieldOutputTypes', 'FieldInputTypes']);
2079
+ const COLUMN_TYPE_MAPS = new Set(['StorageColumnTypes', 'StorageColumnInputTypes']);
2080
+
2081
+ /** Whether a row type member names a waived list: in the field and column type maps, keyed namespace, model or table, member; or in a `Models` type alias, `<namespace>_<Model>` or `<Model>`. */
2082
+ function isWaivedRowMember(
2083
+ block: Block,
2084
+ member: string,
2085
+ columns: ReadonlySet<string>,
2086
+ fields: ReadonlySet<string>,
2087
+ ): boolean {
2088
+ const namespace = block.parent;
2089
+ const map = namespace?.parent;
2090
+ if (map !== undefined && map.parent === undefined) {
2091
+ const key = listKey(namespace?.label ?? '', block.label, member);
2092
+ if (FIELD_TYPE_MAPS.has(map.label)) return fields.has(key);
2093
+ if (COLUMN_TYPE_MAPS.has(map.label)) return columns.has(key);
2094
+ }
2095
+ if (namespace?.label !== 'Models' || namespace.parent !== undefined) return false;
2096
+ return [...fields].some((key) => {
2097
+ const [fieldNamespace, model, field] = key.split('\u0000');
2098
+ return (
2099
+ field === member && (block.label === model || block.label === `${fieldNamespace}_${model}`)
2100
+ );
2101
+ });
2102
+ }
2103
+
2104
+ /** The end of the type argument that starts at `start`: the index of its closing `>`. */
2105
+ function typeArgumentEnd(text: string, start: number): number {
2106
+ let depth = 1;
2107
+ let quote: string | undefined;
2108
+ for (let index = start; index < text.length; index++) {
2109
+ const char = text[index];
2110
+ if (quote !== undefined) {
2111
+ if (char === '\\') index++;
2112
+ else if (char === quote) quote = undefined;
2113
+ } else if (char === "'" || char === '"' || char === '`') quote = char;
2114
+ else if (char === '<') depth++;
2115
+ else if (char === '>' && text[index - 1] !== '=' && --depth === 0) return index;
2116
+ }
2117
+ return -1;
2118
+ }
2119
+
2120
+ function quoted(text: string, quote: string): string {
2121
+ return `${quote}${text.replaceAll('\\', '\\\\').replaceAll(quote, `\\${quote}`)}${quote}`;
2122
+ }
2123
+
2124
+ const NUMBER_TOKEN = /(?<![\w.$'"])-?\d+(?:\.\d+)?(?:e[+-]?\d+)?(?![\w.$'"])/gi;
2125
+
2126
+ /** A default's literal type with each rewritten value replaced: a string in either quote, a number as its own token. */
2127
+ function withRewrittenLiterals(literal: string, rewrites: readonly DefaultRewrite[]): string {
2128
+ let result = literal;
2129
+ const numbers = new Map<number, number>();
2130
+ for (const { from, to } of rewrites) {
2131
+ if (typeof from === 'number' && typeof to === 'number') numbers.set(from, to);
2132
+ if (typeof from === 'string' && typeof to === 'string')
2133
+ for (const quote of ["'", '"'])
2134
+ result = result.replaceAll(quoted(from, quote), quoted(to, quote));
2135
+ }
2136
+ if (numbers.size === 0) return result;
2137
+ return result.replace(NUMBER_TOKEN, (token) => String(numbers.get(Number(token)) ?? token));
2138
+ }
2139
+
577
2140
  function rewriteDts(
578
2141
  text: string,
579
2142
  columns: ReadonlySet<string>,
580
2143
  fields: ReadonlySet<string>,
2144
+ defaults: ReadonlyMap<string, readonly DefaultRewrite[]>,
581
2145
  hashes: ReadonlyMap<string, string>,
582
2146
  ): string {
583
2147
  const blocks = scanBlocks(text);
584
2148
  const edits: { start: number; end: number; text: string }[] = [];
2149
+ for (const match of text.matchAll(/DefaultLiteralValue</g)) {
2150
+ const holder = innermostBlock(blocks, match.index);
2151
+ const column = holder?.label === 'default' ? holder.parent : undefined;
2152
+ const key = column === undefined ? undefined : columnBlockKey(column);
2153
+ const rewrites = key === undefined ? undefined : defaults.get(key);
2154
+ const end = typeArgumentEnd(text, match.index + match[0].length);
2155
+ if (rewrites === undefined || end === -1) continue;
2156
+ const codecEnd = /^\s*(['"])(?:\\.|(?!\1).)*\1/.exec(
2157
+ text.slice(match.index + match[0].length, end),
2158
+ );
2159
+ const start = match.index + match[0].length + (codecEnd?.[0].length ?? 0);
2160
+ edits.push({ start, end, text: withRewrittenLiterals(text.slice(start, end), rewrites) });
2161
+ }
2162
+ const rowMember =
2163
+ /(?:readonly\s+)?([\p{ID_Start}_$][\p{ID_Continue}$]*|'[^']*'|"[^"]*")\s*\??\s*:\s*ReadonlyArray</gu;
2164
+ for (const match of text.matchAll(rowMember)) {
2165
+ const block = innermostBlock(blocks, match.index);
2166
+ const member = match[1]?.replace(/^['"]|['"]$/g, '') ?? '';
2167
+ if (block === undefined || !isWaivedRowMember(block, member, columns, fields)) continue;
2168
+ const elementStart = match.index + match[0].length;
2169
+ const elementEnd = typeArgumentEnd(text, elementStart);
2170
+ if (elementEnd === -1 || /\|\s*null\s*$/.test(text.slice(elementStart, elementEnd))) continue;
2171
+ edits.push({ start: elementEnd, end: elementEnd, text: ' | null' });
2172
+ }
585
2173
  for (const match of text.matchAll(/readonly elementNullable:\s*false/g)) {
586
2174
  const many = innermostBlock(blocks, match.index);
587
2175
  const holder = many?.label === 'many' ? many.parent : undefined;
@@ -620,6 +2208,7 @@ interface ContractPlan {
620
2208
  readonly content: string;
621
2209
  readonly columns: ReadonlySet<string>;
622
2210
  readonly fields: ReadonlySet<string>;
2211
+ readonly defaults: ReadonlyMap<string, readonly DefaultRewrite[]>;
623
2212
  }
624
2213
 
625
2214
  function summary(
@@ -631,7 +2220,7 @@ function summary(
631
2220
  ): readonly string[] {
632
2221
  if (contractsFound === 0) return [`No SQL contract was found under ${root}; nothing changed.`];
633
2222
  if (files === 0 && directories === 0)
634
- return ['No contract stores a noCheck key; nothing changed.'];
2223
+ return ['No contract stores a noCheck key or a default in another form; nothing changed.'];
635
2224
  const renamed = count(directories, 'snapshot directory', 'snapshot directories');
636
2225
  const changes = `Rewrote ${count(files, 'file', 'files')} and renamed ${renamed}.`;
637
2226
  if (hashes.size === 0) return [changes];
@@ -645,12 +2234,58 @@ function summary(
645
2234
 
646
2235
  const JSON_FILES_THAT_MUST_PARSE = new Set(['contract.json', 'migration.json']);
647
2236
 
648
- function main(root: string): number {
2237
+ const USAGE =
2238
+ 'Usage: node remove-nocheck.ts [project-root] [--default <namespace>.<table>.<column>=<JSON value>]...';
2239
+
2240
+ interface Args {
2241
+ readonly root: string;
2242
+ readonly replacements: ReadonlyMap<string, Json>;
2243
+ readonly errors: readonly string[];
2244
+ }
2245
+
2246
+ function parseArgs(args: readonly string[]): Args {
2247
+ const errors: string[] = [];
2248
+ const positional: string[] = [];
2249
+ const replacements = new Map<string, Json>();
2250
+ for (let index = 0; index < args.length; index++) {
2251
+ const arg = args[index] ?? '';
2252
+ const given = arg === '--default' ? args[++index] : undefined;
2253
+ const option = arg.startsWith('--default=') ? arg.slice('--default='.length) : given;
2254
+ if (option === undefined && !arg.startsWith('-')) {
2255
+ positional.push(arg);
2256
+ continue;
2257
+ }
2258
+ if (option === undefined && arg !== '--default') {
2259
+ errors.push(`${arg}: unknown option`);
2260
+ continue;
2261
+ }
2262
+ const separator = option?.indexOf('=') ?? -1;
2263
+ const value = option === undefined ? undefined : parseJson(option.slice(separator + 1));
2264
+ if (option === undefined || separator < 1 || value === undefined) {
2265
+ const shown = option === undefined ? '--default' : `--default ${option}`;
2266
+ errors.push(`${shown}: expected <namespace>.<table>.<column>=<JSON value>`);
2267
+ continue;
2268
+ }
2269
+ replacements.set(option.slice(0, separator), value);
2270
+ }
2271
+ if (positional.length > 1) errors.push(`expected one project root, got ${positional.length}`);
2272
+ const root = resolve(positional[0] ?? process.cwd());
2273
+ if (errors.length === 0 && !isDirectory(root)) errors.push(`${root}: not a directory`);
2274
+ if (errors.length > 0) errors.push(USAGE);
2275
+ return { root, replacements, errors };
2276
+ }
2277
+
2278
+ function main({ root, replacements, errors }: Args): number {
2279
+ if (errors.length > 0) {
2280
+ process.stderr.write(`${errors.join('\n')}\n`);
2281
+ return 1;
2282
+ }
649
2283
  const display = (path: string): string => relative(root, path).split(sep).join('/');
650
2284
  const files = listFiles(root);
651
2285
  const plans: ContractPlan[] = [];
652
2286
  const stops: string[] = [];
653
2287
  let contractsFound = 0;
2288
+ const used = new Set<string>();
654
2289
 
655
2290
  for (const path of files.json) {
656
2291
  const text = readFileSync(path, 'utf8');
@@ -670,8 +2305,9 @@ function main(root: string): number {
670
2305
  )
671
2306
  continue;
672
2307
  contractsFound++;
673
- const rewrite = rewriteContract(contract);
674
- if (!rewrite.changed) continue;
2308
+ const rewrite = rewriteContract(contract, replacements, used);
2309
+ for (const problem of rewrite.notValues) stops.push(`${display(path)}: ${problem}`);
2310
+ if (!rewrite.changed || rewrite.notValues.length > 0) continue;
675
2311
  const snapshot = isSnapshotContract(path);
676
2312
  const stored = contract['storage']['storageHash'];
677
2313
  const oldHash = snapshot ? basename(dirname(path)) : typeof stored === 'string' ? stored : '';
@@ -691,9 +2327,16 @@ function main(root: string): number {
691
2327
  content: writtenForm(withStorageHash(rewrite.contract, newHash), contract, text),
692
2328
  columns: rewrite.columns,
693
2329
  fields: rewrite.fields,
2330
+ defaults: rewrite.defaults,
694
2331
  });
695
2332
  }
696
2333
 
2334
+ for (const key of replacements.keys())
2335
+ if (!used.has(key))
2336
+ stops.push(
2337
+ `--default ${key}: no stored contract has a default of this column that this release refuses, so the script replaces nothing`,
2338
+ );
2339
+
697
2340
  const hashes = new Map<string, string>();
698
2341
  for (const plan of [...plans].sort((a, b) => Number(b.snapshot) - Number(a.snapshot)))
699
2342
  if (plan.oldHash !== plan.newHash && !hashes.has(plan.oldHash))
@@ -712,7 +2355,13 @@ function main(root: string): number {
712
2355
  : `${plan.path.slice(0, -'.json'.length)}.d.ts`;
713
2356
  const dtsHashes = new Map([...hashes, [plan.oldHash, plan.newHash]]);
714
2357
  const dts = existsSync(dtsPath)
715
- ? rewriteDts(readFileSync(dtsPath, 'utf8'), plan.columns, plan.fields, dtsHashes)
2358
+ ? rewriteDts(
2359
+ readFileSync(dtsPath, 'utf8'),
2360
+ plan.columns,
2361
+ plan.fields,
2362
+ plan.defaults,
2363
+ dtsHashes,
2364
+ )
716
2365
  : undefined;
717
2366
  if (!plan.snapshot) {
718
2367
  if (dts !== undefined) referenceWrites.set(dtsPath, dts);
@@ -805,9 +2454,9 @@ function main(root: string): number {
805
2454
  return 1;
806
2455
  }
807
2456
  const rewrittenFiles = snapshotRewrites.length + referenceWrites.size + contractWrites.size;
808
- const lines = summary(root, contractsFound, rewrittenFiles, removals.size, hashes);
2457
+ const lines = [...summary(root, contractsFound, rewrittenFiles, removals.size, hashes)];
809
2458
  process.stdout.write(`${lines.join('\n')}\n`);
810
2459
  return 0;
811
2460
  }
812
2461
 
813
- process.exitCode = main(resolve(process.argv[2] ?? '.'));
2462
+ process.exitCode = main(parseArgs(process.argv.slice(2)));