@prisma/orm-sqlite 8.0.0-rc.2-dev.3 → 8.0.0-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +2 -7
  2. package/dist/config.d.mts +1 -1
  3. package/dist/config.d.mts.map +1 -1
  4. package/dist/config.mjs +3 -8
  5. package/dist/config.mjs.map +1 -1
  6. package/dist/contract-builder.d.mts +205 -15
  7. package/dist/contract-builder.d.mts.map +1 -1
  8. package/dist/contract-builder.mjs +24 -4
  9. package/dist/contract-builder.mjs.map +1 -1
  10. package/dist/contract__validate-once.d.mts +1 -0
  11. package/dist/contract__validate-once.mjs +2 -0
  12. package/dist/control.d.mts +1 -1
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +1 -1
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/family-contract__data-type-support.d.mts +1 -0
  17. package/dist/family-contract__data-type-support.mjs +2 -0
  18. package/dist/family-contract__data-type.d.mts +1 -0
  19. package/dist/family-contract__data-type.mjs +2 -0
  20. package/dist/family-contract__sql-expression.d.mts +1 -0
  21. package/dist/family-contract__sql-expression.mjs +2 -0
  22. package/dist/family__psl-build.d.mts +1 -0
  23. package/dist/family__psl-build.mjs +2 -0
  24. package/dist/relational-core__collection-methods.d.mts +1 -0
  25. package/dist/relational-core__collection-methods.mjs +2 -0
  26. package/dist/relational-core__functions.d.mts +1 -0
  27. package/dist/relational-core__functions.mjs +2 -0
  28. package/dist/relational-core__index-reference.d.mts +1 -0
  29. package/dist/relational-core__index-reference.mjs +2 -0
  30. package/dist/runtime.d.mts +3 -3
  31. package/dist/runtime.d.mts.map +1 -1
  32. package/dist/runtime.mjs +107 -62
  33. package/dist/runtime.mjs.map +1 -1
  34. package/dist/sqlite-Yizsft25-C2Eb0g8b.d.mts +94 -0
  35. package/dist/sqlite-Yizsft25-C2Eb0g8b.d.mts.map +1 -0
  36. package/dist/sqlite-static-DHwrAnt0-c2gsEamQ.mjs +83 -0
  37. package/dist/sqlite-static-DHwrAnt0-c2gsEamQ.mjs.map +1 -0
  38. package/dist/static.d.mts +25 -2
  39. package/dist/static.d.mts.map +1 -0
  40. package/dist/static.mjs +2 -2
  41. package/dist/target__data-types.d.mts +1 -0
  42. package/dist/target__data-types.mjs +2 -0
  43. package/dist/utils__suppress-idle-connection-errors.d.mts +1 -0
  44. package/dist/utils__suppress-idle-connection-errors.mjs +2 -0
  45. package/dist/utils__text.d.mts +1 -0
  46. package/dist/utils__text.mjs +2 -0
  47. package/package.json +26 -15
  48. package/skills/prisma-8/SKILL.md +96 -0
  49. package/skills/prisma-8/references/build.md +142 -0
  50. package/skills/prisma-8/references/contract.md +544 -0
  51. package/skills/prisma-8/references/debug.md +149 -0
  52. package/skills/prisma-8/references/feedback.md +251 -0
  53. package/skills/prisma-8/references/migration-model.md +179 -0
  54. package/skills/prisma-8/references/migration-review.md +211 -0
  55. package/skills/prisma-8/references/migrations.md +581 -0
  56. package/skills/prisma-8/references/queries-mongo.md +238 -0
  57. package/skills/prisma-8/references/queries-postgres.md +710 -0
  58. package/skills/prisma-8/references/queries.md +253 -0
  59. package/skills/prisma-8/references/quickstart.md +317 -0
  60. package/skills/prisma-8/references/runtime.md +463 -0
  61. package/skills/prisma-8/references/supabase.md +234 -0
  62. package/skills/prisma-8/references/upgrade-app.md +102 -0
  63. package/skills/prisma-8/references/upgrade-extension.md +106 -0
  64. package/skills/prisma-8/upgrading/app/upgrades/0.10-to-0.11/instructions.md +56 -0
  65. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/instructions.md +381 -0
  66. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-closed-mongo-contracts.ts +202 -0
  67. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-domain-namespaced-contracts.ts +201 -0
  68. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-postgres-public-default.ts +198 -0
  69. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
  70. package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/instructions.md +339 -0
  71. package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/re-emit-mti-variant-link-columns.ts +229 -0
  72. package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/instructions.md +543 -0
  73. package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
  74. package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
  75. package/skills/prisma-8/upgrading/app/upgrades/0.14-to-0.15/instructions.md +359 -0
  76. package/skills/prisma-8/upgrading/app/upgrades/0.15-to-0.16/instructions.md +173 -0
  77. package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/instructions.md +805 -0
  78. package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
  79. package/skills/prisma-8/upgrading/app/upgrades/0.17-to-8.0.0-rc.1/instructions.md +72 -0
  80. package/skills/prisma-8/upgrading/app/upgrades/0.7-to-0.8/instructions.md +8 -0
  81. package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/instructions.md +36 -0
  82. package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
  83. package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/instructions.md +86 -0
  84. package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
  85. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +588 -0
  86. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  87. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +639 -0
  88. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/multifile-psl/add-use-prisma-8-directive.mjs +60 -0
  89. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
  90. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +332 -0
  91. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
  92. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +489 -0
  93. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +1368 -0
  94. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
  95. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +108 -0
  96. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +755 -0
  97. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +973 -0
  98. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/scripts/sql-expression-literals-psl/rewrite-sql-strings.mjs +271 -0
  99. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +1826 -0
  100. 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 +382 -0
  101. 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 +1117 -0
  102. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
  103. 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 +250 -0
  104. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +813 -0
  105. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +502 -0
  106. 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 +1171 -0
  107. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
  108. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +158 -0
  109. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +42 -0
  110. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.5-to-8.0.0-rc.6/instructions.md +157 -0
  111. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.6-to-8.0.0-rc.7/instructions.md +33 -0
  112. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.7-to-8.0.0-rc.8/instructions.md +36 -0
  113. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.8-to-8.0.0-rc.9/instructions.md +63 -0
  114. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +84 -0
  115. package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +276 -0
  116. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +738 -0
  117. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/migrate-contract-testing-imports.ts +97 -0
  118. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/regenerate-extension-public-baseline.ts +223 -0
  119. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
  120. package/skills/prisma-8/upgrading/extension/upgrades/0.12-to-0.13/instructions.md +266 -0
  121. package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/instructions.md +522 -0
  122. package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
  123. package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
  124. package/skills/prisma-8/upgrading/extension/upgrades/0.14-to-0.15/instructions.md +803 -0
  125. package/skills/prisma-8/upgrading/extension/upgrades/0.15-to-0.16/instructions.md +219 -0
  126. package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/instructions.md +731 -0
  127. package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
  128. package/skills/prisma-8/upgrading/extension/upgrades/0.17-to-8.0.0-rc.1/instructions.md +194 -0
  129. package/skills/prisma-8/upgrading/extension/upgrades/0.7-to-0.8/instructions.md +8 -0
  130. package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/instructions.md +57 -0
  131. package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
  132. package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/instructions.md +150 -0
  133. package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
  134. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +746 -0
  135. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  136. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +857 -0
  137. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
  138. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +504 -0
  139. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
  140. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +143 -0
  141. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +2168 -0
  142. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
  143. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +223 -0
  144. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +583 -0
  145. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +1008 -0
  146. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +2000 -0
  147. 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 +382 -0
  148. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +813 -0
  149. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +379 -0
  150. 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 +1171 -0
  151. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
  152. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +137 -0
  153. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +129 -0
  154. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.5-to-8.0.0-rc.6/instructions.md +102 -0
  155. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.6-to-8.0.0-rc.7/instructions.md +33 -0
  156. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.7-to-8.0.0-rc.8/instructions.md +35 -0
  157. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.8-to-8.0.0-rc.9/instructions.md +86 -0
  158. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +63 -0
  159. package/dist/family-contract__pack-types.d.mts +0 -1
  160. package/dist/family-contract__pack-types.mjs +0 -2
  161. package/dist/sqlite-CjWZostj-Cprd7rkt.d.mts +0 -76
  162. package/dist/sqlite-CjWZostj-Cprd7rkt.d.mts.map +0 -1
  163. package/dist/sqlite-static-CBCbqogG-BtpT_pWA.mjs +0 -44
  164. package/dist/sqlite-static-CBCbqogG-BtpT_pWA.mjs.map +0 -1
  165. package/dist/target__native-type-normalizer.d.mts +0 -1
  166. package/dist/target__native-type-normalizer.mjs +0 -2
@@ -0,0 +1,1171 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Writes every type alias a column of a SQL contract is typed by into the column. Contracts emitted before this release store an alias as a `storage.types` entry and each column typed by it as a `typeRef` naming the entry; this release stores the alias's params on the column itself and refuses a stored `typeRef`. In each contract the script replaces every column's `typeRef` with the entry's `typeParams`, removes each entry a column named, and makes the same change in `contract.d.ts`. In a contract of the app's own contract space it also removes every entry no column names, an alias nothing uses, so the result is what a re-emit gives. In a contract of an extension's contract space, where registered database types live, it keeps such an entry and lists 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
+ *
5
+ * A contract belongs to an extension's contract space when a ref or migration of an extension space names its hash: one under `migrations/<space>/` other than `migrations/app/`, or one in a package's own single-space `migrations/` directory. It belongs to the app's when only refs and migrations under `migrations/app/` name it. A snapshot that nothing names keeps its unreferenced entries, as the script cannot tell whose it is. For an emitted contract that nothing names, the nearest migrations directory decides: one with an `app/` space directory, or none at all, is the app's; one with `refs/` directly in it is a package's own space.
6
+ *
7
+ * Usage: node expand-type-aliases.ts [project-root]
8
+ *
9
+ * 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 `typeRef` and no unused alias in the app's space 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 column whose alias is missing or has another codec or data type, a migration with no data operation between two snapshots that become the same snapshot, 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, each storage hash it replaced, and each entry it removed or kept.
10
+ *
11
+ * 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.
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ import {
15
+ chmodSync,
16
+ type Dirent,
17
+ existsSync,
18
+ mkdirSync,
19
+ readdirSync,
20
+ readFileSync,
21
+ realpathSync,
22
+ renameSync,
23
+ rmSync,
24
+ statSync,
25
+ writeFileSync,
26
+ } from 'node:fs';
27
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
28
+
29
+ type Json = null | boolean | number | string | Json[] | JsonRecord;
30
+ interface JsonRecord {
31
+ [key: string]: Json;
32
+ }
33
+
34
+ const SKIPPED_DIRECTORIES = new Set(['node_modules', '.git', 'dist', 'build']);
35
+ const APP_SPACE_ID = 'app';
36
+ const HASH = /^[0-9a-f]{64}$/;
37
+ const TEMPORARY_SUFFIX = '.expand-type-aliases-tmp';
38
+
39
+ function isRecord(value: unknown): value is JsonRecord {
40
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
41
+ const prototype: unknown = Object.getPrototypeOf(value);
42
+ return prototype === Object.prototype || prototype === null;
43
+ }
44
+
45
+ function parseJson(text: string): Json | undefined {
46
+ try {
47
+ const value: Json = JSON.parse(text);
48
+ return value;
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ function sha256(text: string): string {
55
+ return createHash('sha256').update(text).digest('hex');
56
+ }
57
+
58
+ function compareCodeUnits(a: string, b: string): number {
59
+ return a < b ? -1 : a > b ? 1 : 0;
60
+ }
61
+
62
+ function sortKeys(value: Json): Json {
63
+ if (Array.isArray(value)) return value.map(sortKeys);
64
+ if (!isRecord(value)) return value;
65
+ const sorted: JsonRecord = {};
66
+ for (const key of Object.keys(value).sort(compareCodeUnits)) {
67
+ const child = value[key];
68
+ if (child !== undefined) sorted[key] = sortKeys(child);
69
+ }
70
+ return sorted;
71
+ }
72
+
73
+ function canonicalizeJson(value: Json): string {
74
+ return JSON.stringify(sortKeys(value));
75
+ }
76
+
77
+ type PathSegment = string | readonly string[];
78
+
79
+ function matchesPath(path: readonly string[], pattern: readonly PathSegment[]): boolean {
80
+ if (path.length !== pattern.length) return false;
81
+ return pattern.every((segment, index) => {
82
+ const value = path[index];
83
+ if (value === undefined) return false;
84
+ if (segment === '*') return true;
85
+ return typeof segment === 'string' ? value === segment : segment.includes(value);
86
+ });
87
+ }
88
+
89
+ const SQL_PRESERVED_EMPTY: readonly (readonly PathSegment[])[] = [
90
+ ['storage', 'namespaces', '*', 'entries', 'table'],
91
+ ['storage', 'namespaces', '*', 'entries', 'table', '*'],
92
+ ['storage', 'namespaces', '*', 'entries', 'table', '*', ['uniques', 'indexes', 'foreignKeys']],
93
+ ['storage', 'namespaces', '*', 'entries', 'table', '*', 'indexes', 'unique'],
94
+ ['storage', 'namespaces', '*', 'entries', 'table', '*', 'columns', '*', 'default', 'value'],
95
+ ];
96
+ const COLUMN_DEFAULT_VALUE: readonly PathSegment[] = [
97
+ 'storage',
98
+ 'namespaces',
99
+ '*',
100
+ 'entries',
101
+ 'table',
102
+ '*',
103
+ 'columns',
104
+ '*',
105
+ 'default',
106
+ 'value',
107
+ ];
108
+ const FRAMEWORK_PRESERVED_EMPTY: readonly (readonly PathSegment[])[] = [
109
+ ['domain', 'namespaces'],
110
+ ['domain', 'namespaces', '*'],
111
+ ['domain', 'namespaces', '*', 'models'],
112
+ ['domain', 'namespaces', '*', 'models', '*', 'relations'],
113
+ ['domain', 'namespaces', '*', 'models', '*', 'storage'],
114
+ ['storage', 'namespaces'],
115
+ ['storage', 'namespaces', '*', 'entries'],
116
+ ['roots'],
117
+ ['extensions'],
118
+ ['extensions', '*'],
119
+ ['capabilities'],
120
+ ['meta'],
121
+ ['execution', 'mutations', 'defaults'],
122
+ ];
123
+ const TOP_LEVEL_ORDER = [
124
+ 'schemaVersion',
125
+ 'canonicalVersion',
126
+ 'targetFamily',
127
+ 'target',
128
+ 'profileHash',
129
+ 'roots',
130
+ 'domain',
131
+ 'storage',
132
+ 'execution',
133
+ 'capabilities',
134
+ 'extensions',
135
+ 'defaultControlPolicy',
136
+ 'meta',
137
+ ];
138
+
139
+ function isDefaultValue(value: Json): boolean {
140
+ if (value === false) return true;
141
+ if (Array.isArray(value)) return value.length === 0;
142
+ return isRecord(value) && Object.keys(value).length === 0;
143
+ }
144
+
145
+ function isPreservedEmpty(path: readonly string[], key: string): boolean {
146
+ if (key === 'nullable') return true;
147
+ if (key === 'elementNullable' && path.at(-2) === 'many') return true;
148
+ if (FRAMEWORK_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern))) return true;
149
+ if (
150
+ path.length >= COLUMN_DEFAULT_VALUE.length &&
151
+ matchesPath(path.slice(0, COLUMN_DEFAULT_VALUE.length), COLUMN_DEFAULT_VALUE)
152
+ )
153
+ return true;
154
+ return SQL_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern));
155
+ }
156
+
157
+ function omitDefaults(value: Json, path: readonly string[]): Json {
158
+ if (Array.isArray(value)) return value.map((item) => omitDefaults(item, path));
159
+ if (!isRecord(value)) return value;
160
+ const result: JsonRecord = {};
161
+ for (const [key, child] of Object.entries(value)) {
162
+ const childPath = [...path, key];
163
+ if (key === '_generated') continue;
164
+ if (key === 'generated' && child === false) continue;
165
+ if ((key === 'onDelete' || key === 'onUpdate') && child === 'noAction') continue;
166
+ if (isDefaultValue(child) && !isPreservedEmpty(childPath, key)) continue;
167
+ result[key] = omitDefaults(child, childPath);
168
+ }
169
+ return result;
170
+ }
171
+
172
+ function compareByName(a: Json, b: Json): number {
173
+ const nameA = isRecord(a) && typeof a['name'] === 'string' ? a['name'] : '';
174
+ const nameB = isRecord(b) && typeof b['name'] === 'string' ? b['name'] : '';
175
+ return compareCodeUnits(nameA, nameB);
176
+ }
177
+
178
+ function sortTableArrays(storage: Json): Json {
179
+ if (!isRecord(storage)) return storage;
180
+ const namespaces = storage['namespaces'];
181
+ if (!isRecord(namespaces)) return storage;
182
+ const sortedNamespaces: JsonRecord = {};
183
+ for (const [namespaceId, namespace] of Object.entries(namespaces)) {
184
+ const entries = isRecord(namespace) ? namespace['entries'] : undefined;
185
+ const tables = isRecord(entries) ? entries['table'] : undefined;
186
+ if (!isRecord(namespace) || !isRecord(entries) || !isRecord(tables)) {
187
+ sortedNamespaces[namespaceId] = namespace;
188
+ continue;
189
+ }
190
+ const sortedTables: JsonRecord = {};
191
+ for (const [tableName, table] of Object.entries(tables)) {
192
+ if (!isRecord(table)) {
193
+ sortedTables[tableName] = table;
194
+ continue;
195
+ }
196
+ const sortedTable: JsonRecord = { ...table };
197
+ for (const key of ['checks', 'indexes', 'uniques']) {
198
+ const list = table[key];
199
+ if (Array.isArray(list)) sortedTable[key] = [...list].sort(compareByName);
200
+ }
201
+ sortedTables[tableName] = sortedTable;
202
+ }
203
+ sortedNamespaces[namespaceId] = { ...namespace, entries: { ...entries, table: sortedTables } };
204
+ }
205
+ return { ...storage, namespaces: sortedNamespaces };
206
+ }
207
+
208
+ function orderTopLevel(value: JsonRecord): JsonRecord {
209
+ const ordered: JsonRecord = {};
210
+ const remaining = new Set(Object.keys(value));
211
+ for (const key of TOP_LEVEL_ORDER) {
212
+ const child = value[key];
213
+ if (child !== undefined) {
214
+ ordered[key] = child;
215
+ remaining.delete(key);
216
+ }
217
+ }
218
+ for (const key of [...remaining].sort(compareCodeUnits)) {
219
+ const child = value[key];
220
+ if (child !== undefined) ordered[key] = child;
221
+ }
222
+ return ordered;
223
+ }
224
+
225
+ function omitNamespaceKinds(storage: JsonRecord): JsonRecord {
226
+ const namespaces = storage['namespaces'];
227
+ if (!isRecord(namespaces)) return storage;
228
+ const stripped: JsonRecord = {};
229
+ for (const [namespaceId, namespace] of Object.entries(namespaces)) {
230
+ if (isRecord(namespace)) {
231
+ const { kind: _kind, ...rest } = namespace;
232
+ stripped[namespaceId] = rest;
233
+ } else {
234
+ stripped[namespaceId] = namespace;
235
+ }
236
+ }
237
+ return { ...storage, namespaces: stripped };
238
+ }
239
+
240
+ function computeStorageHash(contract: JsonRecord): string {
241
+ const storage = isRecord(contract['storage']) ? contract['storage'] : {};
242
+ const { storageHash: _published, ...withoutHash } = storage;
243
+ const hashed: JsonRecord = {
244
+ schemaVersion: '1',
245
+ targetFamily: typeof contract['targetFamily'] === 'string' ? contract['targetFamily'] : '',
246
+ target: typeof contract['target'] === 'string' ? contract['target'] : '',
247
+ profileHash: '',
248
+ roots: {},
249
+ domain: { namespaces: {} },
250
+ storage: omitNamespaceKinds(withoutHash),
251
+ extensions: {},
252
+ capabilities: {},
253
+ meta: {},
254
+ };
255
+ const withoutDefaults = omitDefaults(hashed, []);
256
+ if (!isRecord(withoutDefaults)) return '';
257
+ const withSortedStorage = {
258
+ ...withoutDefaults,
259
+ storage: sortTableArrays(withoutDefaults['storage'] ?? {}),
260
+ };
261
+ const sorted = sortKeys(withSortedStorage);
262
+ return isRecord(sorted) ? sha256(JSON.stringify(orderTopLevel(sorted), null, 2)) : '';
263
+ }
264
+
265
+ function computeMigrationHash(metadata: JsonRecord, ops: Json): string {
266
+ const { migrationHash: _migrationHash, ...withoutHash } = metadata;
267
+ const parts = [canonicalizeJson(withoutHash), canonicalizeJson(ops)].map(sha256);
268
+ return sha256(canonicalizeJson(parts));
269
+ }
270
+
271
+ interface ProjectFiles {
272
+ readonly json: readonly string[];
273
+ readonly migrationJson: readonly string[];
274
+ readonly refs: readonly string[];
275
+ readonly migrationTs: readonly string[];
276
+ readonly leftovers: readonly string[];
277
+ }
278
+
279
+ function isDirectory(path: string): boolean {
280
+ try {
281
+ return statSync(path).isDirectory();
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
286
+
287
+ function isFile(path: string): boolean {
288
+ try {
289
+ return statSync(path).isFile();
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
294
+
295
+ /** A file, or a link to one: the script reads and writes through links to files. */
296
+ function isFileEntry(dir: string, entry: Dirent): boolean {
297
+ return entry.isFile() || (entry.isSymbolicLink() && isFile(join(dir, entry.name)));
298
+ }
299
+
300
+ /** A file the script reads, by the path it was reached through: its own path rather than a link's. */
301
+ interface FoundFile {
302
+ readonly path: string;
303
+ readonly linked: boolean;
304
+ readonly inMigrationPackage: boolean;
305
+ }
306
+
307
+ function listFiles(root: string): ProjectFiles {
308
+ const leftovers: string[] = [];
309
+ const visited = new Set<string>();
310
+ const found = new Map<string, FoundFile>();
311
+ const visit = (dir: string): void => {
312
+ const realDir = realpathSync(dir);
313
+ if (visited.has(realDir)) return;
314
+ visited.add(realDir);
315
+ const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
316
+ compareCodeUnits(a.name, b.name),
317
+ );
318
+ const inMigrationPackage = entries.some(
319
+ (entry) => entry.name === 'migration.json' && isFileEntry(dir, entry),
320
+ );
321
+ for (const entry of entries) {
322
+ const path = join(dir, entry.name);
323
+ if (entry.name.endsWith(TEMPORARY_SUFFIX)) {
324
+ leftovers.push(path);
325
+ continue;
326
+ }
327
+ if (entry.isDirectory() || (entry.isSymbolicLink() && isDirectory(path))) {
328
+ if (!SKIPPED_DIRECTORIES.has(entry.name)) visit(path);
329
+ continue;
330
+ }
331
+ if (!isFileEntry(dir, entry)) continue;
332
+ const realFile = realpathSync(path);
333
+ const linked = entry.isSymbolicLink();
334
+ const known = found.get(realFile);
335
+ if (known === undefined || (known.linked && !linked))
336
+ found.set(realFile, { path, linked, inMigrationPackage });
337
+ }
338
+ };
339
+ visit(root);
340
+ const files = [...found.values()];
341
+ const named = (test: (file: FoundFile, name: string) => boolean): string[] =>
342
+ files.filter((file) => test(file, basename(file.path))).map((file) => file.path);
343
+ return {
344
+ json: named((_file, name) => name.endsWith('.json')),
345
+ migrationJson: named((_file, name) => name === 'migration.json'),
346
+ refs: named((file, name) => name.endsWith('.json') && basename(dirname(file.path)) === 'refs'),
347
+ migrationTs: named((file, name) => name === 'migration.ts' && file.inMigrationPackage),
348
+ leftovers,
349
+ };
350
+ }
351
+
352
+ function isSnapshotContract(path: string): boolean {
353
+ const snapshotDir = dirname(path);
354
+ return (
355
+ basename(path) === 'contract.json' &&
356
+ HASH.test(basename(snapshotDir)) &&
357
+ basename(dirname(snapshotDir)) === 'snapshots'
358
+ );
359
+ }
360
+
361
+ function replaceQuotedHashes(text: string, hashes: ReadonlyMap<string, string>): string {
362
+ return text.replace(/"([0-9a-f]{64})"/g, (match: string, hash: string) => {
363
+ const next = hashes.get(hash);
364
+ return next === undefined ? match : `"${next}"`;
365
+ });
366
+ }
367
+
368
+ function readDirectory(dir: string): Map<string, string> {
369
+ const files = new Map<string, string>();
370
+ if (!existsSync(dir)) return files;
371
+ for (const entry of readdirSync(dir, { withFileTypes: true }))
372
+ if (isFileEntry(dir, entry) && !entry.name.endsWith(TEMPORARY_SUFFIX))
373
+ files.set(entry.name, readFileSync(join(dir, entry.name), 'utf8'));
374
+ return files;
375
+ }
376
+
377
+ function sameFiles(a: ReadonlyMap<string, string>, b: ReadonlyMap<string, string>): boolean {
378
+ return a.size === b.size && [...a].every(([name, content]) => b.get(name) === content);
379
+ }
380
+
381
+ function temporaryPath(path: string): string {
382
+ return join(dirname(path), `.${basename(path)}${TEMPORARY_SUFFIX}`);
383
+ }
384
+
385
+ function writeWithModeOf(path: string, text: string, modeSource: string): void {
386
+ writeFileSync(path, text);
387
+ if (existsSync(modeSource)) chmodSync(path, statSync(modeSource).mode & 0o7777);
388
+ }
389
+
390
+ function writeFile(path: string, text: string): void {
391
+ const target = realpathSync(path);
392
+ const temporary = temporaryPath(target);
393
+ writeWithModeOf(temporary, text, target);
394
+ renameSync(temporary, target);
395
+ }
396
+
397
+ function writeDirectory(dir: string, files: ReadonlyMap<string, string>, sourceDir: string): void {
398
+ const temporary = temporaryPath(dir);
399
+ mkdirSync(temporary);
400
+ for (const [name, text] of files)
401
+ writeWithModeOf(join(temporary, name), text, join(sourceDir, name));
402
+ renameSync(temporary, dir);
403
+ }
404
+
405
+ function removeDirectory(dir: string): void {
406
+ const temporary = temporaryPath(dir);
407
+ renameSync(dir, temporary);
408
+ rmSync(temporary, { recursive: true, force: true });
409
+ }
410
+
411
+ function count(amount: number, singular: string, plural: string): string {
412
+ return `${amount} ${amount === 1 ? singular : plural}`;
413
+ }
414
+
415
+ const REMOVED_KEY = 'typeRef';
416
+ const DTS_LINE_WIDTH = 100;
417
+
418
+ interface Rewrite {
419
+ readonly contract: JsonRecord;
420
+ readonly changed: boolean;
421
+ /** The `storage.types` entries a column referenced, whose params the rewrite wrote into the columns. */
422
+ readonly expanded: ReadonlyMap<string, JsonRecord>;
423
+ /** Every `storage.types` entry the rewrite removed: the referenced ones, and in the app's space the unreferenced ones too. */
424
+ readonly removed: ReadonlySet<string>;
425
+ /** The `storage.types` entries no column referenced, which the rewrite kept. */
426
+ readonly kept: readonly string[];
427
+ readonly problems: readonly string[];
428
+ }
429
+
430
+ function nonEmptyParams(entry: JsonRecord): JsonRecord | undefined {
431
+ const params = entry['typeParams'];
432
+ return isRecord(params) && Object.keys(params).length > 0 ? params : undefined;
433
+ }
434
+
435
+ /** The column with its `typeRef` replaced, in place, by the referenced entry's params. */
436
+ function expandedColumn(column: JsonRecord, entry: JsonRecord): JsonRecord {
437
+ const params = nonEmptyParams(entry);
438
+ const result: JsonRecord = {};
439
+ for (const [key, value] of Object.entries(column)) {
440
+ if (key !== REMOVED_KEY) result[key] = value;
441
+ else if (params !== undefined) result['typeParams'] = params;
442
+ }
443
+ return result;
444
+ }
445
+
446
+ function describeType(record: JsonRecord): string {
447
+ return `codec ${String(record['codecId'])} and data type ${String(record['dataType'])}`;
448
+ }
449
+
450
+ /** The contract with every column's type alias written into the column, the aliases it named removed from `storage.types`, and in a contract of the app's space every other entry too. */
451
+ function rewriteContract(contract: JsonRecord, space: SpaceKind): Rewrite {
452
+ const copy = parseJson(JSON.stringify(contract));
453
+ const storage = isRecord(copy) ? copy['storage'] : undefined;
454
+ if (!isRecord(copy) || !isRecord(storage))
455
+ return {
456
+ contract,
457
+ changed: false,
458
+ expanded: new Map(),
459
+ removed: new Set(),
460
+ kept: [],
461
+ problems: [],
462
+ };
463
+ const types = isRecord(storage['types']) ? storage['types'] : {};
464
+ const expanded = new Map<string, JsonRecord>();
465
+ const problems: string[] = [];
466
+ let changed = false;
467
+ const namespaces = storage['namespaces'];
468
+ for (const namespace of isRecord(namespaces) ? Object.values(namespaces) : []) {
469
+ const entries = isRecord(namespace) ? namespace['entries'] : undefined;
470
+ const tables = isRecord(entries) ? entries['table'] : undefined;
471
+ for (const [tableName, table] of isRecord(tables) ? Object.entries(tables) : []) {
472
+ const columns = isRecord(table) ? table['columns'] : undefined;
473
+ if (!isRecord(columns)) continue;
474
+ for (const [columnName, column] of Object.entries(columns)) {
475
+ if (!isRecord(column) || !Object.hasOwn(column, REMOVED_KEY)) continue;
476
+ changed = true;
477
+ const alias = column[REMOVED_KEY];
478
+ const entry = typeof alias === 'string' ? types[alias] : undefined;
479
+ const where = `column ${tableName}.${columnName}`;
480
+ if (typeof alias !== 'string' || !isRecord(entry)) {
481
+ problems.push(
482
+ `${where} is typed by the type alias ${JSON.stringify(alias)}, which storage.types does not declare`,
483
+ );
484
+ continue;
485
+ }
486
+ if (Object.hasOwn(column, 'typeParams')) {
487
+ problems.push(`${where} stores both typeRef and typeParams`);
488
+ continue;
489
+ }
490
+ if (column['codecId'] !== entry['codecId'] || column['dataType'] !== entry['dataType']) {
491
+ problems.push(
492
+ `${where} has ${describeType(column)}, but its type alias ${alias} has ${describeType(entry)}`,
493
+ );
494
+ continue;
495
+ }
496
+ columns[columnName] = expandedColumn(column, entry);
497
+ expanded.set(alias, entry);
498
+ }
499
+ }
500
+ }
501
+ const removed = new Set(space === 'app' ? Object.keys(types) : expanded.keys());
502
+ for (const alias of removed) delete types[alias];
503
+ if (removed.size > 0 && Object.keys(types).length === 0) delete storage['types'];
504
+ const kept = Object.keys(types).sort(compareCodeUnits);
505
+ return {
506
+ contract: copy,
507
+ changed: changed || removed.size > 0,
508
+ expanded,
509
+ removed,
510
+ kept,
511
+ problems,
512
+ };
513
+ }
514
+
515
+ function withStorageHash(contract: JsonRecord, hash: string): JsonRecord {
516
+ const storage = contract['storage'];
517
+ if (!isRecord(storage) || typeof storage['storageHash'] !== 'string') return contract;
518
+ return { ...contract, storage: { ...storage, storageHash: hash } };
519
+ }
520
+
521
+ /** The contract written the way the file held it: a snapshot's canonical line, or indented JSON. */
522
+ function writtenForm(contract: JsonRecord, original: JsonRecord, text: string): string {
523
+ const newline = text.endsWith('\n') ? '\n' : '';
524
+ if (text === `${canonicalizeJson(original)}${newline}`)
525
+ return `${canonicalizeJson(contract)}${newline}`;
526
+ return `${JSON.stringify(contract, null, 2)}${newline}`;
527
+ }
528
+
529
+ interface Block {
530
+ readonly start: number;
531
+ end: number;
532
+ readonly label: string;
533
+ readonly parent: Block | undefined;
534
+ }
535
+
536
+ function scanBlocks(text: string): Block[] {
537
+ const blocks: Block[] = [];
538
+ const open: Block[] = [];
539
+ let quote: string | undefined;
540
+ for (let index = 0; index < text.length; index++) {
541
+ const char = text[index];
542
+ if (quote !== undefined) {
543
+ if (char === '\\') index++;
544
+ else if (char === quote) quote = undefined;
545
+ continue;
546
+ }
547
+ if (char === '/' && text[index + 1] === '/') {
548
+ const end = text.indexOf('\n', index);
549
+ index = end === -1 ? text.length : end;
550
+ continue;
551
+ }
552
+ if (char === '/' && text[index + 1] === '*') {
553
+ const end = text.indexOf('*/', index + 2);
554
+ index = end === -1 ? text.length : end + 1;
555
+ continue;
556
+ }
557
+ if (char === "'" || char === '"' || char === '`') {
558
+ quote = char;
559
+ continue;
560
+ }
561
+ if (char === '{') {
562
+ const key =
563
+ /(?:readonly\s+)?([\p{ID_Start}_$][\p{ID_Continue}$]*|'[^']*'|"[^"]*")\s*\??\s*:\s*$/u.exec(
564
+ text.slice(Math.max(0, index - 200), index),
565
+ );
566
+ const block: Block = {
567
+ start: index,
568
+ end: text.length,
569
+ label: key?.[1]?.replace(/^['"]|['"]$/g, '') ?? '',
570
+ parent: open.at(-1),
571
+ };
572
+ open.push(block);
573
+ blocks.push(block);
574
+ } else if (char === '}') {
575
+ const block = open.pop();
576
+ if (block !== undefined) block.end = index;
577
+ }
578
+ }
579
+ return blocks;
580
+ }
581
+
582
+ function innermostBlock(blocks: readonly Block[], position: number): Block | undefined {
583
+ let found: Block | undefined;
584
+ for (const block of blocks)
585
+ if (
586
+ block.start < position &&
587
+ position < block.end &&
588
+ (found === undefined || block.start > found.start)
589
+ )
590
+ found = block;
591
+ return found;
592
+ }
593
+
594
+ /** Whether the block is a storage column (`namespaces.<ns>.entries.table.<table>.columns.<column>`). */
595
+ function isColumnBlock(block: Block): boolean {
596
+ const table = block.parent?.parent;
597
+ return (
598
+ block.parent?.label === 'columns' &&
599
+ table?.parent?.label === 'table' &&
600
+ table.parent.parent?.label === 'entries'
601
+ );
602
+ }
603
+
604
+ function childBlocks(blocks: readonly Block[], parent: Block): Block[] {
605
+ return blocks.filter((block) => block.parent === parent);
606
+ }
607
+
608
+ /** The `readonly types` block of the storage type: the one whose parent also holds `namespaces`. */
609
+ function storageTypesBlock(blocks: readonly Block[]): Block | undefined {
610
+ return blocks.find(
611
+ (block) =>
612
+ block.label === 'types' &&
613
+ block.parent !== undefined &&
614
+ childBlocks(blocks, block.parent).some((sibling) => sibling.label === 'namespaces'),
615
+ );
616
+ }
617
+
618
+ function lineStart(text: string, position: number): number {
619
+ return text.lastIndexOf('\n', position - 1) + 1;
620
+ }
621
+
622
+ /** The end of the member a block closes: past its `;` and the line break after it. */
623
+ function memberEnd(text: string, block: Block): number {
624
+ const rest = /^\s*;?[ \t]*\n?/.exec(text.slice(block.end + 1));
625
+ return block.end + 1 + (rest?.[0].length ?? 0);
626
+ }
627
+
628
+ function indentOf(text: string, position: number): string {
629
+ return /^[ \t]*/.exec(text.slice(lineStart(text, position)))?.[0] ?? '';
630
+ }
631
+
632
+ /** Splits `{ a; b }` into its top-level members. */
633
+ function topLevelMembers(literal: string): string[] {
634
+ const inner = literal.trim().slice(1, -1);
635
+ const members: string[] = [];
636
+ let depth = 0;
637
+ let quote: string | undefined;
638
+ let current = '';
639
+ for (let index = 0; index < inner.length; index++) {
640
+ const char = inner[index] ?? '';
641
+ current += char;
642
+ if (quote !== undefined) {
643
+ if (char === '\\') current += inner[++index] ?? '';
644
+ else if (char === quote) quote = undefined;
645
+ continue;
646
+ }
647
+ if (char === "'" || char === '"' || char === '`') quote = char;
648
+ else if (char === '{' || char === '[' || char === '(') depth++;
649
+ else if (char === '}' || char === ']' || char === ')') depth--;
650
+ else if (char === ';' && depth === 0) {
651
+ members.push(current.slice(0, -1).trim());
652
+ current = '';
653
+ }
654
+ }
655
+ if (current.trim() !== '') members.push(current.trim());
656
+ return members;
657
+ }
658
+
659
+ /** The `readonly typeParams` member, laid out as the emitter's formatter lays it out at `indent`. */
660
+ function typeParamsMember(literal: string, indent: string): string {
661
+ const lines = literal.split('\n');
662
+ const head = `${indent}readonly typeParams: `;
663
+ if (lines.length > 1) {
664
+ const literalIndent = /^[ \t]*/.exec(lines.at(-1) ?? '')?.[0] ?? '';
665
+ const shifted = lines.map((line, index) =>
666
+ index === 0 ? line : `${indent}${line.slice(literalIndent.length)}`,
667
+ );
668
+ return `${head}${shifted.join('\n')};`;
669
+ }
670
+ const single = `${head}${literal};`;
671
+ if (single.length <= DTS_LINE_WIDTH) return single;
672
+ const members = topLevelMembers(literal).map((member) => `${indent} ${member};`);
673
+ return `${head}{\n${members.join('\n')}\n${indent}};`;
674
+ }
675
+
676
+ /** The text of `typeParams` in an entry block of `readonly types`, as the emitter wrote it. */
677
+ function entryParamsLiteral(
678
+ text: string,
679
+ blocks: readonly Block[],
680
+ entry: Block,
681
+ ): string | undefined {
682
+ const params = childBlocks(blocks, entry).find((block) => block.label === 'typeParams');
683
+ return params === undefined ? undefined : text.slice(params.start, params.end + 1);
684
+ }
685
+
686
+ function jsonParamsLiteral(params: JsonRecord): string {
687
+ const members = Object.entries(params).map(
688
+ ([key, value]) =>
689
+ `readonly ${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `'${key}'`}: ${JSON.stringify(value)}`,
690
+ );
691
+ return `{ ${members.join('; ')} }`;
692
+ }
693
+
694
+ interface Edit {
695
+ readonly start: number;
696
+ readonly end: number;
697
+ readonly text: string;
698
+ }
699
+
700
+ function rewriteDts(
701
+ text: string,
702
+ expanded: ReadonlyMap<string, JsonRecord>,
703
+ removedEntries: ReadonlySet<string>,
704
+ hashes: ReadonlyMap<string, string>,
705
+ ): string {
706
+ const blocks = scanBlocks(text);
707
+ const typesBlock = storageTypesBlock(blocks);
708
+ const entryBlocks = typesBlock === undefined ? [] : childBlocks(blocks, typesBlock);
709
+ const literals = new Map<string, string>();
710
+ for (const [alias, entry] of expanded) {
711
+ const params = nonEmptyParams(entry);
712
+ if (params === undefined) continue;
713
+ const block = entryBlocks.find((candidate) => candidate.label === alias);
714
+ literals.set(
715
+ alias,
716
+ (block === undefined ? undefined : entryParamsLiteral(text, blocks, block)) ??
717
+ jsonParamsLiteral(params),
718
+ );
719
+ }
720
+ const edits: Edit[] = [];
721
+ for (const match of text.matchAll(/readonly typeRef:\s*(?:'([^']*)'|"([^"]*)")\s*;?/g)) {
722
+ const alias = match[1] ?? match[2] ?? '';
723
+ const column = innermostBlock(blocks, match.index);
724
+ if (column === undefined || !isColumnBlock(column) || !expanded.has(alias)) continue;
725
+ const start = lineStart(text, match.index);
726
+ const literal = literals.get(alias);
727
+ if (literal === undefined) {
728
+ const end = match.index + match[0].length;
729
+ edits.push({ start, end: text[end] === '\n' ? end + 1 : end, text: '' });
730
+ } else {
731
+ edits.push({
732
+ start,
733
+ end: match.index + match[0].length,
734
+ text: typeParamsMember(literal, indentOf(text, match.index)),
735
+ });
736
+ }
737
+ }
738
+ if (typesBlock !== undefined) {
739
+ const removed = entryBlocks.filter((block) => removedEntries.has(block.label));
740
+ if (removed.length > 0 && removed.length === entryBlocks.length) {
741
+ edits.push({
742
+ start: lineStart(text, typesBlock.start),
743
+ end: memberEnd(text, typesBlock),
744
+ text: '',
745
+ });
746
+ } else {
747
+ for (const block of removed)
748
+ edits.push({ start: lineStart(text, block.start), end: memberEnd(text, block), text: '' });
749
+ }
750
+ }
751
+ let result = text;
752
+ for (const edit of edits.sort((a, b) => b.start - a.start))
753
+ result = `${result.slice(0, edit.start)}${edit.text}${result.slice(edit.end)}`;
754
+ return replaceHashTokens(result, hashes);
755
+ }
756
+
757
+ function replaceHashTokens(text: string, hashes: ReadonlyMap<string, string>): string {
758
+ return text.replace(
759
+ /(?<![0-9a-f])[0-9a-f]{64}(?![0-9a-f])/g,
760
+ (hash: string) => hashes.get(hash) ?? hash,
761
+ );
762
+ }
763
+
764
+ interface ContractPlan {
765
+ readonly path: string;
766
+ readonly snapshot: boolean;
767
+ readonly oldHash: string;
768
+ readonly newHash: string;
769
+ readonly content: string;
770
+ readonly expanded: ReadonlyMap<string, JsonRecord>;
771
+ readonly removed: ReadonlySet<string>;
772
+ readonly kept: readonly string[];
773
+ }
774
+
775
+ /** Whose contract space a contract is: the app's own; an extension's, which registers database types; or unknown, for a snapshot no migration or ref names. Only a contract of the app's space loses the entries no column references. */
776
+ type SpaceKind = 'app' | 'extension' | 'unknown';
777
+
778
+ /** A hash a migration or ref names, and the space whose directory holds it. */
779
+ interface HashReference {
780
+ readonly path: string;
781
+ readonly space: SpaceKind;
782
+ readonly hashes: readonly string[];
783
+ /** A migration's `from` and `to`; `undefined` for a ref. */
784
+ readonly edge: { readonly from: string; readonly to: string } | undefined;
785
+ }
786
+
787
+ /** The space of the directory that holds a migration package or a `refs` directory: `migrations/app` is the app's; any other space directory, or a package's own single-space `migrations`, an extension's. */
788
+ function spaceOfDirectory(spaceDir: string): SpaceKind {
789
+ return basename(spaceDir) === APP_SPACE_ID ? 'app' : 'extension';
790
+ }
791
+
792
+ function hashReferences(files: ProjectFiles): HashReference[] {
793
+ const references: HashReference[] = [];
794
+ for (const path of files.migrationJson) {
795
+ const metadata = parseJson(readFileSync(path, 'utf8'));
796
+ if (!isRecord(metadata)) continue;
797
+ const from = metadata['from'];
798
+ const to = metadata['to'];
799
+ const hashes = [from, to].filter((hash): hash is string => typeof hash === 'string');
800
+ references.push({
801
+ path: dirname(path),
802
+ space: spaceOfDirectory(dirname(dirname(path))),
803
+ hashes,
804
+ edge: typeof from === 'string' && typeof to === 'string' ? { from, to } : undefined,
805
+ });
806
+ }
807
+ for (const path of files.refs) {
808
+ const ref = parseJson(readFileSync(path, 'utf8'));
809
+ const hash = isRecord(ref) ? ref['hash'] : undefined;
810
+ if (typeof hash !== 'string') continue;
811
+ references.push({
812
+ path,
813
+ space: spaceOfDirectory(dirname(dirname(path))),
814
+ hashes: [hash],
815
+ edge: undefined,
816
+ });
817
+ }
818
+ return references;
819
+ }
820
+
821
+ /** The space of a migrations directory, by its layout: an `app` space directory, or no `refs` directly in it, is the app's. */
822
+ function spaceOfMigrationsDirectory(dir: string): SpaceKind {
823
+ if (isDirectory(join(dir, APP_SPACE_ID))) return 'app';
824
+ return isDirectory(join(dir, 'refs')) ? 'extension' : 'app';
825
+ }
826
+
827
+ /** The space of a contract that no ref or migration names: unknown for a snapshot, as every space shares the snapshot store; for an emitted contract, that of the nearest `migrations` directory above it, or the app's when there is none. */
828
+ function spaceByLayout(path: string, snapshot: boolean, root: string): SpaceKind {
829
+ if (snapshot) return 'unknown';
830
+ for (let dir = dirname(path); ; dir = dirname(dir)) {
831
+ const migrations = join(dir, 'migrations');
832
+ if (isDirectory(migrations)) return spaceOfMigrationsDirectory(migrations);
833
+ if (dir === root || dirname(dir) === dir) return 'app';
834
+ }
835
+ }
836
+
837
+ function summary(
838
+ root: string,
839
+ contractsFound: number,
840
+ files: number,
841
+ directories: number,
842
+ hashes: ReadonlyMap<string, string>,
843
+ removed: readonly (readonly [string, readonly string[]])[],
844
+ kept: readonly (readonly [string, readonly string[]])[],
845
+ ): readonly string[] {
846
+ if (contractsFound === 0) return [`No SQL contract was found under ${root}; nothing changed.`];
847
+ if (files === 0 && directories === 0)
848
+ return ['No contract stores a type alias; nothing changed.'];
849
+ const renamed = count(directories, 'snapshot directory', 'snapshot directories');
850
+ const changes = `Rewrote ${count(files, 'file', 'files')} and renamed ${renamed}.`;
851
+ const listed = (entries: readonly (readonly [string, readonly string[]])[]) =>
852
+ entries.map(([path, names]) => ` ${path}: ${names.join(', ')}`);
853
+ return [
854
+ ...(hashes.size === 0
855
+ ? [changes]
856
+ : [
857
+ `${changes} Storage hashes changed (old -> new):`,
858
+ ...[...hashes]
859
+ .sort(([a], [b]) => compareCodeUnits(a, b))
860
+ .map(([oldHash, newHash]) => ` ${oldHash} -> ${newHash}`),
861
+ ]),
862
+ ...(removed.length === 0 ? [] : ['Removed storage.types entries:', ...listed(removed)]),
863
+ ...(kept.length === 0
864
+ ? []
865
+ : [
866
+ "Kept storage.types entries that no column references, in contracts of an extension's contract space and in snapshots that no migration or ref names. Each is a database type a contract space registers, or a type alias nothing uses:",
867
+ ...listed(kept),
868
+ ]),
869
+ ];
870
+ }
871
+
872
+ /** Each path with the names listed for it, merged and sorted, in path order. */
873
+ function byPath(
874
+ entries: readonly (readonly [string, readonly string[]])[],
875
+ ): (readonly [string, readonly string[]])[] {
876
+ const merged = new Map<string, Set<string>>();
877
+ for (const [path, names] of entries)
878
+ merged.set(path, new Set([...(merged.get(path) ?? []), ...names]));
879
+ return [...merged]
880
+ .map(([path, names]): readonly [string, readonly string[]] => [
881
+ path,
882
+ [...names].sort(compareCodeUnits),
883
+ ])
884
+ .sort(([a], [b]) => compareCodeUnits(a, b));
885
+ }
886
+
887
+ interface MigrationOps {
888
+ readonly path: string;
889
+ /** `undefined` when the package has no `ops.json` or it is not valid JSON. */
890
+ readonly ops: Json | undefined;
891
+ readonly unreadable: boolean;
892
+ }
893
+
894
+ function readOps(migrationDir: string): MigrationOps {
895
+ const path = join(migrationDir, 'ops.json');
896
+ if (!existsSync(path)) return { path, ops: undefined, unreadable: false };
897
+ const ops = parseJson(readFileSync(path, 'utf8'));
898
+ return { path, ops, unreadable: ops === undefined };
899
+ }
900
+
901
+ /** Whether the operations hold one of class `data`, the one kind that lets a migration go from a snapshot to itself. The migration checker's rule (`checkIntegrity` in `@internal/migration-tools`). */
902
+ function hasDataOperation(ops: Json | undefined): boolean {
903
+ return Array.isArray(ops) && ops.some((op) => isRecord(op) && op['operationClass'] === 'data');
904
+ }
905
+
906
+ /**
907
+ * The snapshot directories that the rewrite turns two or more snapshots into, and a stop line for each migration between such snapshots that has no data operation, naming too each of its snapshots that nothing else names, or, when its `ops.json` is not valid JSON, for that file. Expanding the aliases can make two contracts equal: one that wrote a type inline and one that wrote it through an alias, or two that named one alias differently. A migration between them then goes from a snapshot to itself, which the migration checker allows only for a migration with a data operation. A snapshot nothing names, such as a copy an interrupted run left, is not counted.
908
+ */
909
+ function mergedSnapshots(
910
+ files: ProjectFiles,
911
+ plans: readonly ContractPlan[],
912
+ references: readonly HashReference[],
913
+ display: (path: string) => string,
914
+ ): { readonly lines: readonly string[]; readonly directories: ReadonlySet<string> } {
915
+ const planned = new Map(plans.map((plan) => [plan.path, plan.newHash]));
916
+ const referenced = new Set(references.flatMap((reference) => reference.hashes));
917
+ const stores = new Map<string, Map<string, Set<string>>>();
918
+ for (const path of files.json) {
919
+ if (!isSnapshotContract(path)) continue;
920
+ const hash = basename(dirname(path));
921
+ if (!referenced.has(hash)) continue;
922
+ const store = dirname(dirname(path));
923
+ const merged = stores.get(store) ?? new Map<string, Set<string>>();
924
+ stores.set(store, merged);
925
+ const newHash = planned.get(path) ?? hash;
926
+ merged.set(newHash, new Set([...(merged.get(newHash) ?? []), hash]));
927
+ }
928
+ const lines: string[] = [];
929
+ const directories = new Set<string>();
930
+ for (const [store, merged] of stores) {
931
+ for (const [newHash, oldHashes] of merged) {
932
+ if (oldHashes.size < 2) continue;
933
+ directories.add(join(store, newHash));
934
+ const names = [...oldHashes].sort(compareCodeUnits).join(' and ');
935
+ for (const { path, edge } of references) {
936
+ if (
937
+ edge === undefined ||
938
+ edge.from === edge.to ||
939
+ !oldHashes.has(edge.from) ||
940
+ !oldHashes.has(edge.to) ||
941
+ !path.startsWith(`${dirname(store)}${sep}`)
942
+ )
943
+ continue;
944
+ const ops = readOps(path);
945
+ if (ops.unreadable) {
946
+ lines.push(`${display(ops.path)}: not valid JSON`);
947
+ continue;
948
+ }
949
+ if (hasDataOperation(ops.ops)) continue;
950
+ const orphaned = [edge.from, edge.to].filter(
951
+ (hash) => !references.some((other) => other.path !== path && other.hashes.includes(hash)),
952
+ );
953
+ const snapshots = orphaned.map((hash) => display(join(store, hash)));
954
+ const toDelete =
955
+ snapshots.length === 0
956
+ ? `the migration directory ${display(path)}`
957
+ : `the migration directory ${display(path)} and the snapshot ${snapshots.length === 1 ? 'directory' : 'directories'} ${snapshots.join(' and ')}, which no other migration or ref names,`;
958
+ lines.push(
959
+ `${display(store)}: the snapshots ${names} become the same snapshot, ${newHash}, once their type aliases are written into their columns. Migration ${display(path)} goes from ${edge.from} to ${edge.to} and has no data operation, so it would go from ${newHash} to itself, which only a migration with a data operation may do. Delete ${toDelete} and run the script again.`,
960
+ );
961
+ }
962
+ }
963
+ }
964
+ return { lines, directories };
965
+ }
966
+
967
+ const JSON_FILES_THAT_MUST_PARSE = new Set(['contract.json', 'migration.json']);
968
+
969
+ function main(root: string): number {
970
+ const display = (path: string): string => relative(root, path).split(sep).join('/');
971
+ const files = listFiles(root);
972
+ const references = hashReferences(files);
973
+ const spacesByHash = new Map<string, Set<SpaceKind>>();
974
+ for (const reference of references)
975
+ for (const hash of reference.hashes)
976
+ spacesByHash.set(hash, new Set([...(spacesByHash.get(hash) ?? []), reference.space]));
977
+ const spaceOf = (path: string, snapshot: boolean, hash: string): SpaceKind => {
978
+ const spaces = spacesByHash.get(hash);
979
+ if (spaces?.has('extension')) return 'extension';
980
+ if (spaces?.has('app')) return 'app';
981
+ return spaceByLayout(path, snapshot, root);
982
+ };
983
+ const plans: ContractPlan[] = [];
984
+ const stops: string[] = [];
985
+ let contractsFound = 0;
986
+
987
+ for (const path of files.json) {
988
+ const text = readFileSync(path, 'utf8');
989
+ const contract = parseJson(text);
990
+ if (
991
+ contract === undefined &&
992
+ (JSON_FILES_THAT_MUST_PARSE.has(basename(path)) || files.refs.includes(path))
993
+ ) {
994
+ stops.push(`${display(path)}: not valid JSON`);
995
+ continue;
996
+ }
997
+ if (
998
+ !isRecord(contract) ||
999
+ contract['targetFamily'] !== 'sql' ||
1000
+ typeof contract['target'] !== 'string' ||
1001
+ !isRecord(contract['storage'])
1002
+ )
1003
+ continue;
1004
+ contractsFound++;
1005
+ const snapshot = isSnapshotContract(path);
1006
+ const stored = contract['storage']['storageHash'];
1007
+ const oldHash = snapshot ? basename(dirname(path)) : typeof stored === 'string' ? stored : '';
1008
+ const rewrite = rewriteContract(contract, spaceOf(path, snapshot, oldHash));
1009
+ if (!rewrite.changed) continue;
1010
+ const computed = computeStorageHash(contract);
1011
+ if (computed !== oldHash || (typeof stored === 'string' && stored !== oldHash)) {
1012
+ stops.push(
1013
+ `${display(path)}: the stored storage hash ${oldHash} does not match the contract's content, which hashes to ${computed}; restore the file from version control, or re-emit it, and run the script again`,
1014
+ );
1015
+ continue;
1016
+ }
1017
+ if (rewrite.problems.length > 0) {
1018
+ for (const problem of rewrite.problems)
1019
+ stops.push(
1020
+ `${display(path)}: ${problem}; restore the file from version control, or re-emit it, and run the script again`,
1021
+ );
1022
+ continue;
1023
+ }
1024
+ const newHash = computeStorageHash(rewrite.contract);
1025
+ plans.push({
1026
+ path,
1027
+ snapshot,
1028
+ oldHash,
1029
+ newHash,
1030
+ content: writtenForm(withStorageHash(rewrite.contract, newHash), contract, text),
1031
+ expanded: rewrite.expanded,
1032
+ removed: rewrite.removed,
1033
+ kept: rewrite.kept,
1034
+ });
1035
+ }
1036
+
1037
+ const hashes = new Map<string, string>();
1038
+ for (const plan of [...plans].sort((a, b) => Number(b.snapshot) - Number(a.snapshot)))
1039
+ if (plan.oldHash !== plan.newHash && !hashes.has(plan.oldHash))
1040
+ hashes.set(plan.oldHash, plan.newHash);
1041
+ const merged = mergedSnapshots(files, plans, references, display);
1042
+ stops.push(...merged.lines);
1043
+
1044
+ const newDirectories = new Map<string, Map<string, string>>();
1045
+ const directorySources = new Map<string, string>();
1046
+ const sourceDirectories = new Set<string>();
1047
+ const removals = new Set<string>();
1048
+ const snapshotRewrites: [string, string][] = [];
1049
+ const referenceWrites = new Map<string, string>();
1050
+ const contractWrites = new Map<string, string>();
1051
+ const kept: [string, readonly string[]][] = [];
1052
+ const removedEntries: [string, readonly string[]][] = [];
1053
+ for (const plan of plans) {
1054
+ const dtsPath = plan.snapshot
1055
+ ? join(dirname(plan.path), 'contract.d.ts')
1056
+ : `${plan.path.slice(0, -'.json'.length)}.d.ts`;
1057
+ const dtsHashes = new Map([...hashes, [plan.oldHash, plan.newHash]]);
1058
+ const dts = existsSync(dtsPath)
1059
+ ? rewriteDts(readFileSync(dtsPath, 'utf8'), plan.expanded, plan.removed, dtsHashes)
1060
+ : undefined;
1061
+ const writtenPath = plan.snapshot
1062
+ ? join(dirname(dirname(plan.path)), plan.newHash, 'contract.json')
1063
+ : plan.path;
1064
+ if (plan.kept.length > 0) kept.push([display(writtenPath), plan.kept]);
1065
+ if (plan.removed.size > 0) removedEntries.push([display(writtenPath), [...plan.removed]]);
1066
+ if (!plan.snapshot) {
1067
+ if (dts !== undefined) referenceWrites.set(dtsPath, dts);
1068
+ contractWrites.set(plan.path, plan.content);
1069
+ continue;
1070
+ }
1071
+ const oldDir = dirname(plan.path);
1072
+ const newDir = join(dirname(oldDir), plan.newHash);
1073
+ sourceDirectories.add(oldDir);
1074
+ if (newDir === oldDir) {
1075
+ if (dts !== undefined) snapshotRewrites.push([dtsPath, dts]);
1076
+ snapshotRewrites.push([plan.path, plan.content]);
1077
+ continue;
1078
+ }
1079
+ removals.add(oldDir);
1080
+ const content = readDirectory(oldDir);
1081
+ content.set('contract.json', plan.content);
1082
+ if (dts !== undefined) content.set('contract.d.ts', dts);
1083
+ const planned = newDirectories.get(newDir);
1084
+ if (planned !== undefined && !sameFiles(planned, content)) {
1085
+ if (!merged.directories.has(newDir))
1086
+ stops.push(`${display(newDir)}: snapshot directory already exists with different content`);
1087
+ continue;
1088
+ }
1089
+ newDirectories.set(newDir, content);
1090
+ directorySources.set(newDir, oldDir);
1091
+ }
1092
+ for (const [dir, content] of newDirectories) {
1093
+ if (sourceDirectories.has(dir) || !existsSync(dir)) continue;
1094
+ if (merged.directories.has(dir) || sameFiles(readDirectory(dir), content))
1095
+ newDirectories.delete(dir);
1096
+ else stops.push(`${display(dir)}: snapshot directory already exists with different content`);
1097
+ }
1098
+
1099
+ for (const path of files.migrationJson) {
1100
+ const text = readFileSync(path, 'utf8');
1101
+ const metadata = parseJson(text);
1102
+ if (!isRecord(metadata)) continue;
1103
+ const from = metadata['from'];
1104
+ const to = metadata['to'];
1105
+ const nextFrom = typeof from === 'string' ? (hashes.get(from) ?? from) : from;
1106
+ const nextTo = typeof to === 'string' ? (hashes.get(to) ?? to) : to;
1107
+ if (nextFrom === from && nextTo === to) continue;
1108
+ const { path: opsPath, ops, unreadable } = readOps(dirname(path));
1109
+ if (unreadable) {
1110
+ stops.push(`${display(opsPath)}: not valid JSON`);
1111
+ continue;
1112
+ }
1113
+ const oldMigrationHash = metadata['migrationHash'];
1114
+ let next = replaceQuotedHashes(text, hashes);
1115
+ if (
1116
+ ops !== undefined &&
1117
+ typeof oldMigrationHash === 'string' &&
1118
+ nextFrom !== undefined &&
1119
+ nextTo !== undefined
1120
+ ) {
1121
+ const migrationHash = computeMigrationHash({ ...metadata, from: nextFrom, to: nextTo }, ops);
1122
+ next = next.replace(`"${oldMigrationHash}"`, `"${migrationHash}"`);
1123
+ }
1124
+ referenceWrites.set(path, next);
1125
+ }
1126
+ for (const path of files.refs) {
1127
+ const text = readFileSync(path, 'utf8');
1128
+ const next = replaceQuotedHashes(text, hashes);
1129
+ if (next !== text) referenceWrites.set(path, next);
1130
+ }
1131
+ for (const path of files.migrationTs) {
1132
+ const text = readFileSync(path, 'utf8');
1133
+ const next = replaceHashTokens(text, hashes);
1134
+ if (next !== text) referenceWrites.set(path, next);
1135
+ }
1136
+
1137
+ if (stops.length > 0) {
1138
+ process.stderr.write(`${[...new Set(stops)].join('\n')}\n`);
1139
+ return 1;
1140
+ }
1141
+
1142
+ try {
1143
+ for (const path of files.leftovers) rmSync(path, { recursive: true, force: true });
1144
+ for (const [dir, content] of newDirectories)
1145
+ writeDirectory(dir, content, directorySources.get(dir) ?? dir);
1146
+ for (const [path, text] of snapshotRewrites) writeFile(path, text);
1147
+ for (const [path, text] of referenceWrites) writeFile(path, text);
1148
+ for (const [path, text] of contractWrites) writeFile(path, text);
1149
+ for (const dir of removals) removeDirectory(dir);
1150
+ } catch (error) {
1151
+ const message = error instanceof Error ? error.message : String(error);
1152
+ process.stderr.write(
1153
+ `${message}; the upgrade stopped partway, run the script again to finish it\n`,
1154
+ );
1155
+ return 1;
1156
+ }
1157
+ const rewrittenFiles = snapshotRewrites.length + referenceWrites.size + contractWrites.size;
1158
+ const lines = summary(
1159
+ root,
1160
+ contractsFound,
1161
+ rewrittenFiles,
1162
+ removals.size,
1163
+ hashes,
1164
+ byPath(removedEntries),
1165
+ byPath(kept),
1166
+ );
1167
+ process.stdout.write(`${lines.join('\n')}\n`);
1168
+ return 0;
1169
+ }
1170
+
1171
+ process.exitCode = main(resolve(process.argv[2] ?? '.'));