@prisma/orm-mongo 8.0.1-dev.41 → 8.0.1-dev.42
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.
- package/dist/{mongo-static-D3ow-Rl0-BeXA3Gno.mjs → mongo-static-DXv-zWOu-FTCkjjZe.mjs} +3 -3
- package/dist/{mongo-static-D3ow-Rl0-BeXA3Gno.mjs.map → mongo-static-DXv-zWOu-FTCkjjZe.mjs.map} +1 -1
- package/dist/runtime.mjs +1 -1
- package/dist/runtime.mjs.map +1 -1
- package/dist/static.mjs +1 -1
- package/package.json +12 -12
- package/skills/prisma-8/SKILL.md +1 -1
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2385 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +2048 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +667 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +667 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +1996 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +586 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2043 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +2048 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +667 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +667 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +1996 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +586 -0
|
@@ -0,0 +1,2048 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Gives every stored contract hash in a project the value this release computes. A contract's storage, profile and execution hashes used to cover a stand-in contract: the section, plus `schemaVersion: "1"` and blank `profileHash`, `roots`, `domain`, `extensions`, `meta` and `capabilities`. They now cover only their own section: `{ storage }`, `{ requiredCapabilities }` (the sorted list of keys) and `{ execution }`, without the target or the family. The canonicalization also used to leave out every `false`, empty list and empty object outside a list of kept paths; it now leaves out no value except the defaults each family names in its storage, so a value such as a restrictive policy's `permissive: false`, which the file kept and the hash left out, is now in the hash. Each family also orders the storage lists whose order has no meaning, by name and then by content: a SQL table's checks, foreign keys, indexes and uniques, and a MongoDB collection's indexes. So two contracts that list them in another order now have one storage hash.
|
|
4
|
+
*
|
|
5
|
+
* It also gives every contract the name and the keys this release reads for the capabilities it requires. A contract stored them as `capabilities`, each key in the namespace of its vocabulary: `sql.` for a key the SQL targets share and `postgres.` for PostgreSQL's own. It now stores them as `requiredCapabilities`, each key in the namespace of who provides it: `conn.interactiveTransactions` for the connection, and `db.` for every other key, which the database provides. A PostgreSQL contract also loses the nine keys the release candidates wrote that nothing reads: `postgres.jsonAgg`, `postgres.lateral`, `postgres.limit`, `postgres.orderBy`, `postgres.returning`, `postgres.paradedb/bm25`, `postgres.pgvector.cosine`, `postgres.postgis.geometry` and `sql.enums`; and any contract loses the keys in a namespace other than `sql` and `postgres`, such as one an extension declared, which nothing reads either. The list is stored as the sorted keys, such as `["conn.interactiveTransactions", "db.returning"]`, and the profile hash covers that list. A contract a development build wrote, with `requiredCapabilities` grouped by provider (`{ "db": { "returning": true } }`), gets the list too; a contract already in the list form keeps it. In `contract.d.ts` the script writes the type of the list too, when it finds it just before `extensions`. A snapshot cannot be emitted again, so this script is the only thing that rewrites one; this release refuses a contract that stores `capabilities` or groups `requiredCapabilities`.
|
|
6
|
+
*
|
|
7
|
+
* Usage: node contract-hash-inputs.ts [project-root]
|
|
8
|
+
*
|
|
9
|
+
* The project root defaults to the working directory. The script reads and writes files only; it needs no database. It walks the root, skipping `node_modules`, `dist`, `build` and directories whose name starts with a dot, and finds stored files the way the `stored-files-format-version` script does: a contract by its content (`targetFamily` and `storage`) in any `*.json` file, a `migration.json` by the `ops.json` next to it, and a ref file by where Prisma writes refs or by its content.
|
|
10
|
+
*
|
|
11
|
+
* First it checks every contract: each stored `storageHash`, `profileHash` and `executionHash`, and each snapshot directory's name, must be the hash the old rules or the new rules give the contract's content. Two exceptions: a snapshot's profile and execution hash may come from an earlier release's rules, and a MongoDB snapshot may keep the storage hash it had before an earlier upgrade step rewrote its content; both get the hashes their content gives. Then it checks each `migration.json` against its `migrationHash`, and that each `from`, `to` and ref `hash` names a contract of the project. If any check fails, it changes no file, prints one line per problem and exits 1. A hash that does not match the content means the file was edited by hand or comes from another release; fix that first.
|
|
12
|
+
*
|
|
13
|
+
* It reads a stored file whether or not it has a `formatVersion`, and leaves its format version as it is: a file a release candidate wrote keeps `"schemaVersion": "1"`, or no version field, and this release reads it as format version 0.
|
|
14
|
+
*
|
|
15
|
+
* A contract that is not a snapshot and whose storage hash no migration, ref or snapshot names, such as a hand-made test fixture, does not stop the upgrade when its hashes are wrong: it is reported, left unchanged, and makes the script exit 1.
|
|
16
|
+
*
|
|
17
|
+
* Otherwise it rewrites: the three hashes in every contract; the same hashes in the `contract.d.ts` beside it; each snapshot directory's name; `from`, `to` and `migrationHash` in every `migration.json`, and the storage hashes in the `ops.json` beside it; `hash` in every ref file; and every old storage hash in every `migration.ts` (snapshot import paths and hash literals). It edits each file's text, so every other byte stays, including a leading byte order mark, and replaces each file in one rename, so a run that stops partway can be run again to finish. It prints what it changed and each hash it replaced. A `contract.d.ts` whose hashes it cannot match with its contract, or a migration or ref naming a hash it cannot tell the new value of, is reported, left unchanged, and makes it exit 1. A second run changes nothing.
|
|
18
|
+
*
|
|
19
|
+
* The hash rules, old and new, the families' normal forms of storage and the migration hash rule are copied from Prisma's packages, because a project's strict `node_modules` does not expose them.
|
|
20
|
+
*/
|
|
21
|
+
import { createHash } from 'node:crypto';
|
|
22
|
+
import {
|
|
23
|
+
chmodSync,
|
|
24
|
+
type Dirent,
|
|
25
|
+
existsSync,
|
|
26
|
+
readdirSync,
|
|
27
|
+
readFileSync,
|
|
28
|
+
realpathSync,
|
|
29
|
+
renameSync,
|
|
30
|
+
rmSync,
|
|
31
|
+
statSync,
|
|
32
|
+
writeFileSync,
|
|
33
|
+
} from 'node:fs';
|
|
34
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
35
|
+
|
|
36
|
+
type Json = null | boolean | number | string | Json[] | JsonRecord;
|
|
37
|
+
interface JsonRecord {
|
|
38
|
+
[key: string]: Json;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type Family = 'sql' | 'mongo';
|
|
42
|
+
type HashKind = 'storage' | 'profile' | 'execution';
|
|
43
|
+
|
|
44
|
+
const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
|
|
45
|
+
const SPACE_ID = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
46
|
+
const HASH = /^[0-9a-f]{64}$/;
|
|
47
|
+
const REF_HASH = /^(empty|[0-9a-f]{64})$/;
|
|
48
|
+
const BYTE_ORDER_MARK = '';
|
|
49
|
+
const UNKNOWN_HASH =
|
|
50
|
+
'is a storage hash no contract or snapshot in the project has, so the script cannot tell its new value.';
|
|
51
|
+
const TEMPORARY_SUFFIX = '.contract-hash-inputs-tmp';
|
|
52
|
+
const REMOVED_SUFFIX = '.contract-hash-inputs-removed';
|
|
53
|
+
|
|
54
|
+
function isRecord(value: unknown): value is JsonRecord {
|
|
55
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
56
|
+
const prototype: unknown = Object.getPrototypeOf(value);
|
|
57
|
+
return prototype === Object.prototype || prototype === null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function compareCodeUnits(a: string, b: string): number {
|
|
61
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sha256(text: string): string {
|
|
65
|
+
return createHash('sha256').update(text).digest('hex');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Stores `value` as an own key of `target`, so a key named `__proto__` is a key rather than the prototype. */
|
|
69
|
+
function defineOwn(target: JsonRecord, key: string, value: Json): void {
|
|
70
|
+
Object.defineProperty(target, key, {
|
|
71
|
+
value,
|
|
72
|
+
enumerable: true,
|
|
73
|
+
writable: true,
|
|
74
|
+
configurable: true,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sortKeys(value: Json): Json {
|
|
79
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
80
|
+
if (!isRecord(value)) return value;
|
|
81
|
+
const sorted: JsonRecord = {};
|
|
82
|
+
for (const key of Object.keys(value).sort(compareCodeUnits)) {
|
|
83
|
+
const child = value[key];
|
|
84
|
+
if (child !== undefined) defineOwn(sorted, key, sortKeys(child));
|
|
85
|
+
}
|
|
86
|
+
return sorted;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function canonicalizeJson(value: Json): string {
|
|
90
|
+
return JSON.stringify(sortKeys(value));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// Canonicalization, shared by the old and the new hash rules.
|
|
95
|
+
|
|
96
|
+
type PathSegment = string | readonly string[];
|
|
97
|
+
type PathPattern = readonly PathSegment[];
|
|
98
|
+
|
|
99
|
+
function matchesPath(path: readonly string[], pattern: PathPattern): boolean {
|
|
100
|
+
if (path.length !== pattern.length) return false;
|
|
101
|
+
return pattern.every((segment, index) => {
|
|
102
|
+
const value = path[index];
|
|
103
|
+
if (value === undefined) return false;
|
|
104
|
+
if (segment === '*') return true;
|
|
105
|
+
return typeof segment === 'string' ? value === segment : segment.includes(value);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const FRAMEWORK_REQUIRED: readonly PathPattern[] = [
|
|
110
|
+
['domain', 'namespaces'],
|
|
111
|
+
['domain', 'namespaces', '*'],
|
|
112
|
+
['domain', 'namespaces', '*', 'models'],
|
|
113
|
+
['domain', 'namespaces', '*', 'models', '*', 'relations'],
|
|
114
|
+
['domain', 'namespaces', '*', 'models', '*', 'storage'],
|
|
115
|
+
['storage', 'namespaces'],
|
|
116
|
+
['storage', 'namespaces', '*', 'entries'],
|
|
117
|
+
['roots'],
|
|
118
|
+
['extensions'],
|
|
119
|
+
['extensions', '*'],
|
|
120
|
+
['capabilities'],
|
|
121
|
+
['meta'],
|
|
122
|
+
['execution', 'mutations', 'defaults'],
|
|
123
|
+
];
|
|
124
|
+
|
|
125
|
+
const SQL_PRESERVED_EMPTY: readonly PathPattern[] = [
|
|
126
|
+
['storage', 'namespaces', '*', 'entries', 'table'],
|
|
127
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*'],
|
|
128
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', ['uniques', 'indexes', 'foreignKeys']],
|
|
129
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', 'indexes', 'unique'],
|
|
130
|
+
['storage', 'namespaces', '*', 'entries', 'table', '*', 'columns', '*', 'default', 'value'],
|
|
131
|
+
['domain', 'namespaces', '*', 'models', '*', 'fields'],
|
|
132
|
+
['domain', 'namespaces', '*', 'models', '*', 'storage', 'fields'],
|
|
133
|
+
];
|
|
134
|
+
const SQL_COLUMN_DEFAULT_VALUE: PathPattern = [
|
|
135
|
+
'storage',
|
|
136
|
+
'namespaces',
|
|
137
|
+
'*',
|
|
138
|
+
'entries',
|
|
139
|
+
'table',
|
|
140
|
+
'*',
|
|
141
|
+
'columns',
|
|
142
|
+
'*',
|
|
143
|
+
'default',
|
|
144
|
+
'value',
|
|
145
|
+
];
|
|
146
|
+
const MONGO_PRESERVED_EMPTY: readonly PathPattern[] = [
|
|
147
|
+
['storage', 'namespaces', '*', 'entries', 'collection'],
|
|
148
|
+
['storage', 'namespaces', '*', 'entries', 'collection', '*'],
|
|
149
|
+
['domain', 'namespaces', '*', 'models', '*', 'fields'],
|
|
150
|
+
['domain', 'namespaces', '*', 'models', '*', 'storage', 'fields'],
|
|
151
|
+
];
|
|
152
|
+
|
|
153
|
+
type PreserveEmpty = (path: readonly string[]) => boolean;
|
|
154
|
+
|
|
155
|
+
const PRESERVE_EMPTY: Record<Family, PreserveEmpty> = {
|
|
156
|
+
sql: (path) =>
|
|
157
|
+
(path.length >= SQL_COLUMN_DEFAULT_VALUE.length &&
|
|
158
|
+
matchesPath(path.slice(0, SQL_COLUMN_DEFAULT_VALUE.length), SQL_COLUMN_DEFAULT_VALUE)) ||
|
|
159
|
+
SQL_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern)),
|
|
160
|
+
mongo: (path) =>
|
|
161
|
+
path.at(-1) === 'additionalProperties' ||
|
|
162
|
+
(path.includes('jsonSchema') && (path.at(-2) === 'properties' || path.at(-1) === 'items')) ||
|
|
163
|
+
MONGO_PRESERVED_EMPTY.some((pattern) => matchesPath(path, pattern)),
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
function isDefaultValue(value: Json): boolean {
|
|
167
|
+
if (value === false) return true;
|
|
168
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
169
|
+
return isRecord(value) && Object.keys(value).length === 0;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function omitDefaults(
|
|
173
|
+
value: Json,
|
|
174
|
+
path: readonly string[],
|
|
175
|
+
preserveEmpty: PreserveEmpty | undefined,
|
|
176
|
+
): Json {
|
|
177
|
+
if (Array.isArray(value)) return value.map((item) => omitDefaults(item, path, preserveEmpty));
|
|
178
|
+
if (!isRecord(value)) return value;
|
|
179
|
+
const result: JsonRecord = {};
|
|
180
|
+
for (const [key, child] of Object.entries(value)) {
|
|
181
|
+
const childPath = [...path, key];
|
|
182
|
+
if (key === '_generated') continue;
|
|
183
|
+
if (key === 'generated' && child === false) continue;
|
|
184
|
+
if ((key === 'onDelete' || key === 'onUpdate') && child === 'noAction') continue;
|
|
185
|
+
if (
|
|
186
|
+
isDefaultValue(child) &&
|
|
187
|
+
key !== 'nullable' &&
|
|
188
|
+
!(key === 'elementNullable' && path.at(-1) === 'many') &&
|
|
189
|
+
!FRAMEWORK_REQUIRED.some((pattern) => matchesPath(childPath, pattern)) &&
|
|
190
|
+
!(preserveEmpty?.(childPath) ?? false)
|
|
191
|
+
)
|
|
192
|
+
continue;
|
|
193
|
+
defineOwn(result, key, omitDefaults(child, childPath, preserveEmpty));
|
|
194
|
+
}
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function compareByName(a: Json, b: Json): number {
|
|
199
|
+
const nameA = isRecord(a) && typeof a['name'] === 'string' ? a['name'] : '';
|
|
200
|
+
const nameB = isRecord(b) && typeof b['name'] === 'string' ? b['name'] : '';
|
|
201
|
+
return compareCodeUnits(nameA, nameB);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The SQL family's storage sort: each table's `checks`, `indexes` and `uniques` by name. */
|
|
205
|
+
function sortSqlStorage(storage: Json): Json {
|
|
206
|
+
if (!isRecord(storage) || !isRecord(storage['namespaces'])) return storage;
|
|
207
|
+
const namespaces: JsonRecord = { ...storage['namespaces'] };
|
|
208
|
+
for (const [namespaceId, namespace] of Object.entries(namespaces)) {
|
|
209
|
+
if (!isRecord(namespace) || !isRecord(namespace['entries'])) continue;
|
|
210
|
+
const entries = namespace['entries'];
|
|
211
|
+
if (!isRecord(entries['table'])) continue;
|
|
212
|
+
const tables: JsonRecord = { ...entries['table'] };
|
|
213
|
+
for (const [tableName, table] of Object.entries(tables)) {
|
|
214
|
+
if (!isRecord(table)) continue;
|
|
215
|
+
const sorted: JsonRecord = { ...table };
|
|
216
|
+
for (const key of ['checks', 'indexes', 'uniques']) {
|
|
217
|
+
const list = table[key];
|
|
218
|
+
if (Array.isArray(list)) sorted[key] = [...list].sort(compareByName);
|
|
219
|
+
}
|
|
220
|
+
defineOwn(tables, tableName, sorted);
|
|
221
|
+
}
|
|
222
|
+
defineOwn(namespaces, namespaceId, {
|
|
223
|
+
...namespace,
|
|
224
|
+
entries: { ...entries, table: tables },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return { ...storage, namespaces };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
interface Hooks {
|
|
231
|
+
readonly preserveEmpty?: PreserveEmpty;
|
|
232
|
+
readonly sortStorage?: (storage: Json) => Json;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function storageHooks(family: Family): Hooks {
|
|
236
|
+
return family === 'sql'
|
|
237
|
+
? { preserveEmpty: PRESERVE_EMPTY.sql, sortStorage: sortSqlStorage }
|
|
238
|
+
: { preserveEmpty: PRESERVE_EMPTY.mongo };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function canonicalSections(sections: JsonRecord, hooks: Hooks): JsonRecord {
|
|
242
|
+
const withoutDefaults = omitDefaults(sections, [], hooks.preserveEmpty);
|
|
243
|
+
if (!isRecord(withoutDefaults)) return {};
|
|
244
|
+
const withSortedStorage =
|
|
245
|
+
hooks.sortStorage !== undefined && withoutDefaults['storage'] !== undefined
|
|
246
|
+
? { ...withoutDefaults, storage: hooks.sortStorage(withoutDefaults['storage']) }
|
|
247
|
+
: withoutDefaults;
|
|
248
|
+
const sorted = sortKeys(withSortedStorage);
|
|
249
|
+
return isRecord(sorted) ? sorted : {};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
// The hash inputs.
|
|
254
|
+
|
|
255
|
+
interface ContractSections {
|
|
256
|
+
readonly family: Family;
|
|
257
|
+
readonly target: string;
|
|
258
|
+
readonly storage: JsonRecord;
|
|
259
|
+
/** The capabilities as the file stores them under `capabilities`, which the old profile hash of a MongoDB contract covered; empty for any other file. */
|
|
260
|
+
readonly storedCapabilities: JsonRecord;
|
|
261
|
+
/** The keys of the capabilities, as this release stores them under `requiredCapabilities`: sorted, without duplicates. */
|
|
262
|
+
readonly requiredCapabilities: readonly string[];
|
|
263
|
+
/** The capabilities grouped by provider, when the file stores them so, as development builds wrote them. Their profile hash covered the flags that are on. */
|
|
264
|
+
readonly groupedCapabilities: JsonRecord | undefined;
|
|
265
|
+
/** Whether the file stores them in an earlier form, under `capabilities` or grouped by provider, so the script writes the list. */
|
|
266
|
+
readonly rewritesCapabilities: boolean;
|
|
267
|
+
readonly execution: JsonRecord | undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
type HashSet = { readonly [kind in HashKind]?: string };
|
|
271
|
+
|
|
272
|
+
function withoutNamespaceKinds(storage: JsonRecord): JsonRecord {
|
|
273
|
+
const namespaces = storage['namespaces'];
|
|
274
|
+
if (!isRecord(namespaces)) return storage;
|
|
275
|
+
const stripped: JsonRecord = {};
|
|
276
|
+
for (const [namespaceId, namespace] of Object.entries(namespaces)) {
|
|
277
|
+
if (isRecord(namespace)) {
|
|
278
|
+
const { kind: _kind, ...rest } = namespace;
|
|
279
|
+
defineOwn(stripped, namespaceId, rest);
|
|
280
|
+
} else {
|
|
281
|
+
defineOwn(stripped, namespaceId, namespace);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { ...storage, namespaces: stripped };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The capabilities a development build's profile hash covered: a flag that is `false` means the same as an absent one. */
|
|
288
|
+
function capabilitiesThatAreOn(capabilities: JsonRecord): JsonRecord {
|
|
289
|
+
const on: JsonRecord = {};
|
|
290
|
+
for (const [namespace, flags] of Object.entries(capabilities)) {
|
|
291
|
+
if (!isRecord(flags)) continue;
|
|
292
|
+
const kept = without(flags, (_flag, value) => value !== true);
|
|
293
|
+
if (Object.keys(kept).length > 0) defineOwn(on, namespace, kept);
|
|
294
|
+
}
|
|
295
|
+
return on;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The capabilities the old rule's profile hash covered: none for SQL, the contract's own for MongoDB. */
|
|
299
|
+
function oldProfileCapabilities(contract: ContractSections): JsonRecord {
|
|
300
|
+
return contract.family === 'sql' ? {} : contract.storedCapabilities;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const OLD_TOP_LEVEL_ORDER = [
|
|
304
|
+
'targetFamily',
|
|
305
|
+
'target',
|
|
306
|
+
'profileHash',
|
|
307
|
+
'roots',
|
|
308
|
+
'domain',
|
|
309
|
+
'storage',
|
|
310
|
+
'execution',
|
|
311
|
+
'capabilities',
|
|
312
|
+
'extensions',
|
|
313
|
+
'meta',
|
|
314
|
+
];
|
|
315
|
+
|
|
316
|
+
/** The hash rule up to this release: the section inside a stand-in contract, with `schemaVersion: "1"` first. */
|
|
317
|
+
function oldHash(contract: ContractSections, section: JsonRecord, hooks: Hooks): string {
|
|
318
|
+
const standIn: JsonRecord = {
|
|
319
|
+
targetFamily: contract.family,
|
|
320
|
+
target: contract.target,
|
|
321
|
+
profileHash: '',
|
|
322
|
+
roots: {},
|
|
323
|
+
domain: { namespaces: {} },
|
|
324
|
+
storage: {},
|
|
325
|
+
extensions: {},
|
|
326
|
+
capabilities: {},
|
|
327
|
+
meta: {},
|
|
328
|
+
...section,
|
|
329
|
+
};
|
|
330
|
+
const canonical = canonicalSections(standIn, hooks);
|
|
331
|
+
const ordered: JsonRecord = { schemaVersion: '1' };
|
|
332
|
+
for (const key of OLD_TOP_LEVEL_ORDER) {
|
|
333
|
+
const value = canonical[key];
|
|
334
|
+
if (value !== undefined) ordered[key] = value;
|
|
335
|
+
}
|
|
336
|
+
return sha256(JSON.stringify(ordered, null, 2));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The required fields of the PostgreSQL entity kinds that can hold a `false`, `[]` or `{}`: a policy's `roles` and `permissive`, and a native enum's `members`. The earlier release's PostgreSQL serializer kept every required field of an entity kind in the file, and its hash left them out like any other such value.
|
|
341
|
+
*/
|
|
342
|
+
const WRITTEN_BUT_NOT_HASHED: readonly PathPattern[] = [
|
|
343
|
+
['storage', 'namespaces', '*', 'entries', 'policy', '*', ['roles', 'permissive']],
|
|
344
|
+
['storage', 'namespaces', '*', 'entries', 'native_enum', '*', 'members'],
|
|
345
|
+
];
|
|
346
|
+
|
|
347
|
+
function isWrittenButNotHashed(path: readonly string[]): boolean {
|
|
348
|
+
return WRITTEN_BUT_NOT_HASHED.some((pattern) => matchesPath(path, pattern));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* The old rule as the earlier release applied it when it wrote a file. It left out each `false`, `[]` and `{}` once, so a value that held only such values, such as an index's `options: { fastupdate: false }`, was hashed and written as `{}`. Read back, the old rule leaves that `{}` out too, which gives another hash; the hash the release stored is the one of the section as written, without the fields it wrote but did not hash.
|
|
353
|
+
*/
|
|
354
|
+
function oldHashAsWritten(contract: ContractSections, section: JsonRecord, hooks: Hooks): string {
|
|
355
|
+
const sectionKeys = Object.keys(section);
|
|
356
|
+
return oldHash(contract, section, {
|
|
357
|
+
...hooks,
|
|
358
|
+
preserveEmpty: (path) =>
|
|
359
|
+
(sectionKeys.includes(path[0] ?? '') && !isWrittenButNotHashed(path)) ||
|
|
360
|
+
(hooks.preserveEmpty?.(path) ?? false),
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* The old hash of each kind the contract stores: by the old rule, or by the old rule as the earlier release applied it when it wrote the file. A snapshot named by its storage hash as written keeps that name until the script renames its directory, after it has rewritten the stored hash, so a run that stopped in between is finished by the next.
|
|
366
|
+
*/
|
|
367
|
+
function storedOldHashes(
|
|
368
|
+
sections: ContractSections,
|
|
369
|
+
stored: StoredHashes,
|
|
370
|
+
snapshotHash: string | undefined,
|
|
371
|
+
): HashSet {
|
|
372
|
+
const profileSection = { capabilities: oldProfileCapabilities(sections) };
|
|
373
|
+
const byRule = contractHashes(sections, oldHash, profileSection);
|
|
374
|
+
const asWritten = contractHashes(sections, oldHashAsWritten, profileSection);
|
|
375
|
+
const hashes: { [kind in HashKind]?: string } = {};
|
|
376
|
+
const grouped = groupedProfileHash(sections);
|
|
377
|
+
if (grouped !== undefined && stored.profile === grouped) hashes.profile = grouped;
|
|
378
|
+
for (const kind of ['storage', 'profile', 'execution'] as const) {
|
|
379
|
+
const isAsWritten =
|
|
380
|
+
(stored[kind] !== byRule[kind] && stored[kind] === asWritten[kind]) ||
|
|
381
|
+
(kind === 'storage' && snapshotHash !== undefined && snapshotHash === asWritten[kind]);
|
|
382
|
+
const hash = isAsWritten ? asWritten[kind] : byRule[kind];
|
|
383
|
+
if (hash !== undefined && hashes[kind] === undefined) hashes[kind] = hash;
|
|
384
|
+
}
|
|
385
|
+
return hashes;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ---------------------------------------------------------------------------
|
|
389
|
+
// The families' normal form of storage under the new rule. The canonicalizer leaves out no value; each family leaves out only the fields it names, and orders the lists whose order has no meaning.
|
|
390
|
+
|
|
391
|
+
type Normalize = (value: JsonRecord) => JsonRecord;
|
|
392
|
+
|
|
393
|
+
function without(record: JsonRecord, leaveOut: (key: string, value: Json) => boolean): JsonRecord {
|
|
394
|
+
const kept: JsonRecord = {};
|
|
395
|
+
for (const [key, value] of Object.entries(record)) {
|
|
396
|
+
if (!leaveOut(key, value)) defineOwn(kept, key, value);
|
|
397
|
+
}
|
|
398
|
+
return kept;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function withEntry(record: JsonRecord, key: string, value: Json | undefined): JsonRecord {
|
|
402
|
+
if (value === undefined) return record;
|
|
403
|
+
const next: JsonRecord = { ...record };
|
|
404
|
+
defineOwn(next, key, value);
|
|
405
|
+
return next;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function mapRecordValues(value: Json | undefined, map: Normalize): Json | undefined {
|
|
409
|
+
if (!isRecord(value)) return value;
|
|
410
|
+
const mapped: JsonRecord = {};
|
|
411
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
412
|
+
defineOwn(mapped, key, isRecord(entry) ? map(entry) : entry);
|
|
413
|
+
}
|
|
414
|
+
return mapped;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function mapListItems(value: Json | undefined, map: Normalize): Json | undefined {
|
|
418
|
+
return Array.isArray(value)
|
|
419
|
+
? value.map((entry) => (isRecord(entry) ? map(entry) : entry))
|
|
420
|
+
: value;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const isEmptyRecord = (value: Json): boolean => isRecord(value) && Object.keys(value).length === 0;
|
|
424
|
+
const isEmptyList = (value: Json): boolean => Array.isArray(value) && value.length === 0;
|
|
425
|
+
const withoutManyFalse: Normalize = (field) =>
|
|
426
|
+
without(field, (key, value) => key === 'many' && value === false);
|
|
427
|
+
const withoutEmptyTypeParams: Normalize = (record) =>
|
|
428
|
+
without(record, (key, value) => key === 'typeParams' && isEmptyRecord(value));
|
|
429
|
+
|
|
430
|
+
function normalFieldType(fieldType: JsonRecord): JsonRecord {
|
|
431
|
+
const kept = withoutEmptyTypeParams(fieldType);
|
|
432
|
+
return withEntry(kept, 'members', mapListItems(kept['members'], withoutEmptyTypeParams));
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function normalValueObjectField(field: JsonRecord): JsonRecord {
|
|
436
|
+
const kept = withoutManyFalse(field);
|
|
437
|
+
return isRecord(kept['type']) ? withEntry(kept, 'type', normalFieldType(kept['type'])) : kept;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function normalValueObject(valueObject: JsonRecord): JsonRecord {
|
|
441
|
+
return withEntry(
|
|
442
|
+
valueObject,
|
|
443
|
+
'fields',
|
|
444
|
+
mapRecordValues(valueObject['fields'], normalValueObjectField),
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function contentOf(entry: Json): string {
|
|
449
|
+
return JSON.stringify(sortKeys(entry));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function compareByNameThenContent(a: Json, b: Json): number {
|
|
453
|
+
return compareByName(a, b) || compareCodeUnits(contentOf(a), contentOf(b));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function sortListsOf(
|
|
457
|
+
record: JsonRecord,
|
|
458
|
+
keys: readonly string[],
|
|
459
|
+
compare: (a: Json, b: Json) => number,
|
|
460
|
+
): JsonRecord {
|
|
461
|
+
let next = record;
|
|
462
|
+
for (const key of keys) {
|
|
463
|
+
const list = next[key];
|
|
464
|
+
if (Array.isArray(list)) next = withEntry(next, key, [...list].sort(compare));
|
|
465
|
+
}
|
|
466
|
+
return next;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function normalStorageWith(entriesOf: Normalize): (storage: JsonRecord) => JsonRecord {
|
|
470
|
+
return (storage) =>
|
|
471
|
+
withEntry(
|
|
472
|
+
storage,
|
|
473
|
+
'namespaces',
|
|
474
|
+
mapRecordValues(storage['namespaces'], (namespace) =>
|
|
475
|
+
isRecord(namespace['entries'])
|
|
476
|
+
? withEntry(namespace, 'entries', entriesOf(namespace['entries']))
|
|
477
|
+
: namespace,
|
|
478
|
+
),
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function sqlIndex(index: JsonRecord): JsonRecord {
|
|
483
|
+
return without(
|
|
484
|
+
index,
|
|
485
|
+
(key, value) =>
|
|
486
|
+
(key === 'columns' && isEmptyList(value)) || (key === 'options' && isEmptyRecord(value)),
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function sqlForeignKey(foreignKey: JsonRecord): JsonRecord {
|
|
491
|
+
return without(
|
|
492
|
+
foreignKey,
|
|
493
|
+
(key, value) =>
|
|
494
|
+
(key === 'index' && typeof value === 'boolean') ||
|
|
495
|
+
((key === 'onDelete' || key === 'onUpdate') && value === 'noAction'),
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function sqlTable(table: JsonRecord): JsonRecord {
|
|
500
|
+
let next = without(table, (key, value) => key === 'checks' && isEmptyList(value));
|
|
501
|
+
next = withEntry(
|
|
502
|
+
next,
|
|
503
|
+
'columns',
|
|
504
|
+
mapRecordValues(next['columns'], (column) => withoutEmptyTypeParams(withoutManyFalse(column))),
|
|
505
|
+
);
|
|
506
|
+
next = withEntry(next, 'indexes', mapListItems(next['indexes'], sqlIndex));
|
|
507
|
+
next = withEntry(next, 'foreignKeys', mapListItems(next['foreignKeys'], sqlForeignKey));
|
|
508
|
+
return sortListsOf(
|
|
509
|
+
next,
|
|
510
|
+
['checks', 'foreignKeys', 'indexes', 'uniques'],
|
|
511
|
+
compareByNameThenContent,
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function sqlEntries(entries: JsonRecord): JsonRecord {
|
|
516
|
+
const kept = without(entries, (key, value) => key !== 'table' && isEmptyRecord(value));
|
|
517
|
+
const withTables = withEntry(kept, 'table', mapRecordValues(kept['table'], sqlTable));
|
|
518
|
+
return withEntry(
|
|
519
|
+
withTables,
|
|
520
|
+
'valueObject',
|
|
521
|
+
mapRecordValues(kept['valueObject'], normalValueObject),
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function sqlNormalStorage(storage: JsonRecord): JsonRecord {
|
|
526
|
+
const withNamespaces = normalStorageWith(sqlEntries)(storage);
|
|
527
|
+
return withEntry(
|
|
528
|
+
withNamespaces,
|
|
529
|
+
'types',
|
|
530
|
+
mapRecordValues(withNamespaces['types'], withoutEmptyTypeParams),
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const MONGO_FALSE_BY_DEFAULT_COLLATION_FLAGS = new Set(['caseLevel', 'numericOrdering']);
|
|
535
|
+
const MONGO_FALSE_BY_DEFAULT_INDEX_FLAGS = new Set(['unique', 'sparse']);
|
|
536
|
+
const MONGO_SUBSCHEMA_KEYWORDS = new Set([
|
|
537
|
+
'items',
|
|
538
|
+
'not',
|
|
539
|
+
'additionalProperties',
|
|
540
|
+
'additionalItems',
|
|
541
|
+
]);
|
|
542
|
+
const MONGO_SUBSCHEMA_LIST_KEYWORDS = new Set(['oneOf', 'anyOf', 'allOf', 'items']);
|
|
543
|
+
const MONGO_SUBSCHEMA_MAP_KEYWORDS = new Set(['properties', 'patternProperties', 'dependencies']);
|
|
544
|
+
|
|
545
|
+
const mongoCollation: Normalize = (collation) =>
|
|
546
|
+
without(
|
|
547
|
+
collation,
|
|
548
|
+
(key, value) => MONGO_FALSE_BY_DEFAULT_COLLATION_FLAGS.has(key) && value === false,
|
|
549
|
+
);
|
|
550
|
+
|
|
551
|
+
function mongoIndex(index: JsonRecord): JsonRecord {
|
|
552
|
+
const kept = without(
|
|
553
|
+
index,
|
|
554
|
+
(key, value) => MONGO_FALSE_BY_DEFAULT_INDEX_FLAGS.has(key) && value === false,
|
|
555
|
+
);
|
|
556
|
+
return isRecord(kept['collation'])
|
|
557
|
+
? withEntry(kept, 'collation', mongoCollation(kept['collation']))
|
|
558
|
+
: kept;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function mongoJsonSchema(schema: JsonRecord): JsonRecord {
|
|
562
|
+
const kept = without(
|
|
563
|
+
schema,
|
|
564
|
+
(key, value) =>
|
|
565
|
+
(key === 'required' && isEmptyList(value)) || (key === 'properties' && isEmptyRecord(value)),
|
|
566
|
+
);
|
|
567
|
+
const next: JsonRecord = {};
|
|
568
|
+
for (const [key, value] of Object.entries(kept)) {
|
|
569
|
+
let mapped: Json | undefined = value;
|
|
570
|
+
if (MONGO_SUBSCHEMA_MAP_KEYWORDS.has(key)) mapped = mapRecordValues(value, mongoJsonSchema);
|
|
571
|
+
else if (MONGO_SUBSCHEMA_LIST_KEYWORDS.has(key) && Array.isArray(value))
|
|
572
|
+
mapped = mapListItems(value, mongoJsonSchema);
|
|
573
|
+
else if (MONGO_SUBSCHEMA_KEYWORDS.has(key) && isRecord(value)) mapped = mongoJsonSchema(value);
|
|
574
|
+
defineOwn(next, key, mapped ?? value);
|
|
575
|
+
}
|
|
576
|
+
return next;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function mongoCollection(collection: JsonRecord): JsonRecord {
|
|
580
|
+
let next = without(collection, (key, value) => key === 'indexes' && isEmptyList(value));
|
|
581
|
+
next = withEntry(next, 'indexes', mapListItems(next['indexes'], mongoIndex));
|
|
582
|
+
next = sortListsOf(next, ['indexes'], compareByNameThenContent);
|
|
583
|
+
const validator = next['validator'];
|
|
584
|
+
if (isRecord(validator) && isRecord(validator['jsonSchema'])) {
|
|
585
|
+
next = withEntry(
|
|
586
|
+
next,
|
|
587
|
+
'validator',
|
|
588
|
+
withEntry(validator, 'jsonSchema', mongoJsonSchema(validator['jsonSchema'])),
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
const options = next['options'];
|
|
592
|
+
if (isRecord(options) && isRecord(options['collation'])) {
|
|
593
|
+
next = withEntry(
|
|
594
|
+
next,
|
|
595
|
+
'options',
|
|
596
|
+
withEntry(options, 'collation', mongoCollation(options['collation'])),
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
return next;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function mongoEntries(entries: JsonRecord): JsonRecord {
|
|
603
|
+
const kept = without(entries, (key, value) => key !== 'collection' && isEmptyRecord(value));
|
|
604
|
+
const withCollections = withEntry(
|
|
605
|
+
kept,
|
|
606
|
+
'collection',
|
|
607
|
+
mapRecordValues(kept['collection'], mongoCollection),
|
|
608
|
+
);
|
|
609
|
+
return withEntry(
|
|
610
|
+
withCollections,
|
|
611
|
+
'valueObject',
|
|
612
|
+
mapRecordValues(kept['valueObject'], normalValueObject),
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const NEW_NORMAL_STORAGE: Record<Family, Normalize> = {
|
|
617
|
+
sql: sqlNormalStorage,
|
|
618
|
+
mongo: normalStorageWith(mongoEntries),
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
/** The hash rule from this release: the section alone, under its own key, with no value left out but the defaults the family names in its storage. The profile hash covers the contract's own required capabilities that are on, in every family. */
|
|
622
|
+
function newHash(contract: ContractSections, section: JsonRecord): string {
|
|
623
|
+
const storage = section['storage'];
|
|
624
|
+
const normal = isRecord(storage)
|
|
625
|
+
? { ...section, storage: NEW_NORMAL_STORAGE[contract.family](storage) }
|
|
626
|
+
: section;
|
|
627
|
+
return sha256(JSON.stringify(sortKeys(normal), null, 2));
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* The new storage hash of the contract as the earlier release wrote it from the same source: each `false`, `[]` and `{}` it left out once, but the ones it kept. Databases that release migrated were built from that contract, so this is the hash they are at.
|
|
632
|
+
*/
|
|
633
|
+
function newStorageHashAsTheEarlierReleaseWrote(contract: ContractSections): string {
|
|
634
|
+
const preserveEmpty = PRESERVE_EMPTY[contract.family];
|
|
635
|
+
const written = omitDefaults(
|
|
636
|
+
{ storage: contract.storage },
|
|
637
|
+
[],
|
|
638
|
+
(path) => isWrittenButNotHashed(path) || preserveEmpty(path),
|
|
639
|
+
);
|
|
640
|
+
const storage = isRecord(written) && isRecord(written['storage']) ? written['storage'] : {};
|
|
641
|
+
return newHash(contract, { storage: withoutNamespaceKinds(storage) });
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function contractHashes(
|
|
645
|
+
contract: ContractSections,
|
|
646
|
+
rule: (contract: ContractSections, section: JsonRecord, hooks: Hooks) => string,
|
|
647
|
+
profileSection: JsonRecord,
|
|
648
|
+
): HashSet {
|
|
649
|
+
const storage = rule(
|
|
650
|
+
contract,
|
|
651
|
+
{ storage: withoutNamespaceKinds(contract.storage) },
|
|
652
|
+
storageHooks(contract.family),
|
|
653
|
+
);
|
|
654
|
+
const profile = rule(contract, profileSection, {});
|
|
655
|
+
if (contract.execution === undefined) return { storage, profile };
|
|
656
|
+
return { storage, profile, execution: rule(contract, { execution: contract.execution }, {}) };
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function computeMigrationHash(metadata: JsonRecord, ops: Json): string {
|
|
660
|
+
const { migrationHash: _migrationHash, formatVersion: _formatVersion, ...rest } = metadata;
|
|
661
|
+
const parts = [canonicalizeJson(rest), canonicalizeJson(ops)].map(sha256);
|
|
662
|
+
return sha256(canonicalizeJson(parts));
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// ---------------------------------------------------------------------------
|
|
666
|
+
// The required capabilities. Up to this release a contract stored them as `capabilities`, each key in the namespace of its vocabulary: `sql.` for a key the SQL targets share, `postgres.` for PostgreSQL's own. Now it stores them as `requiredCapabilities`, each key in the namespace of who provides it: `db.` for the database and `conn.` for the connection.
|
|
667
|
+
|
|
668
|
+
const CONNECTION_FLAGS: ReadonlySet<string> = new Set(['interactiveTransactions']);
|
|
669
|
+
const VOCABULARY_NAMESPACES: ReadonlySet<string> = new Set(['sql', 'postgres']);
|
|
670
|
+
|
|
671
|
+
/** The flags the release candidates wrote into every PostgreSQL contract that nothing reads, which no PostgreSQL contract keeps. */
|
|
672
|
+
const RETIRED_POSTGRES_CAPABILITIES: Readonly<Record<string, ReadonlySet<string>>> = {
|
|
673
|
+
postgres: new Set([
|
|
674
|
+
'jsonAgg',
|
|
675
|
+
'lateral',
|
|
676
|
+
'limit',
|
|
677
|
+
'orderBy',
|
|
678
|
+
'returning',
|
|
679
|
+
'paradedb/bm25',
|
|
680
|
+
'pgvector.cosine',
|
|
681
|
+
'postgis.geometry',
|
|
682
|
+
]),
|
|
683
|
+
sql: new Set(['enums']),
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
function isRetired(target: string, namespace: string, flag: string): boolean {
|
|
687
|
+
return target === 'postgres' && RETIRED_POSTGRES_CAPABILITIES[namespace]?.has(flag) === true;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function sortedKeys(keys: Iterable<string>): readonly string[] {
|
|
691
|
+
return [...new Set(keys)].sort(compareCodeUnits);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** `capabilities` as keys, each in the namespace of its provider, or why it cannot be. It leaves out what nothing reads: PostgreSQL's retired keys, and every key in another namespace, such as one an extension declared in an earlier release. */
|
|
695
|
+
function requiredCapabilitiesFrom(
|
|
696
|
+
capabilities: JsonRecord,
|
|
697
|
+
target: string,
|
|
698
|
+
): readonly string[] | string {
|
|
699
|
+
const required = new Map<string, Json>();
|
|
700
|
+
for (const [namespace, flags] of Object.entries(capabilities)) {
|
|
701
|
+
if (!VOCABULARY_NAMESPACES.has(namespace)) continue;
|
|
702
|
+
if (!isRecord(flags)) return `its "capabilities.${namespace}" is not an object`;
|
|
703
|
+
for (const [flag, value] of Object.entries(flags)) {
|
|
704
|
+
if (isRetired(target, namespace, flag)) continue;
|
|
705
|
+
const provider = namespace === 'sql' && CONNECTION_FLAGS.has(flag) ? 'conn' : 'db';
|
|
706
|
+
const key = `${provider}.${flag}`;
|
|
707
|
+
const earlier = required.get(key);
|
|
708
|
+
if (earlier !== undefined && earlier !== value)
|
|
709
|
+
return `its "capabilities" give the flag ${JSON.stringify(flag)} two values, which become one key, ${key}`;
|
|
710
|
+
required.set(key, value);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return sortedKeys([...required].filter(([, value]) => value === true).map(([key]) => key));
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** The keys of capabilities a development build grouped by provider, or why they cannot be read. */
|
|
717
|
+
function keysOfGroupedCapabilities(grouped: JsonRecord): readonly string[] | string {
|
|
718
|
+
const keys: string[] = [];
|
|
719
|
+
for (const [provider, flags] of Object.entries(grouped)) {
|
|
720
|
+
if (!isRecord(flags)) return `its "requiredCapabilities.${provider}" is not an object`;
|
|
721
|
+
for (const [flag, value] of Object.entries(flags))
|
|
722
|
+
if (value === true) keys.push(`${provider}.${flag}`);
|
|
723
|
+
}
|
|
724
|
+
return sortedKeys(keys);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
type StoredCapabilities = Pick<
|
|
728
|
+
ContractSections,
|
|
729
|
+
'storedCapabilities' | 'requiredCapabilities' | 'groupedCapabilities' | 'rewritesCapabilities'
|
|
730
|
+
>;
|
|
731
|
+
|
|
732
|
+
/** The capabilities `value` stores, as it stores them and as this release stores them, or why they cannot be read. A release candidate stored them as `capabilities`, a development build grouped them by provider under `requiredCapabilities`, and this release stores the list of keys. */
|
|
733
|
+
function capabilitiesOf(value: JsonRecord, target: string): StoredCapabilities | string {
|
|
734
|
+
const stored = value['capabilities'];
|
|
735
|
+
const required = value['requiredCapabilities'];
|
|
736
|
+
if (stored !== undefined && required !== undefined)
|
|
737
|
+
return 'it has both "capabilities" and "requiredCapabilities"';
|
|
738
|
+
if (Array.isArray(required)) {
|
|
739
|
+
if (!required.every((key) => typeof key === 'string'))
|
|
740
|
+
return 'its "requiredCapabilities" lists a value that is not a string';
|
|
741
|
+
return {
|
|
742
|
+
storedCapabilities: {},
|
|
743
|
+
requiredCapabilities: sortedKeys(required),
|
|
744
|
+
groupedCapabilities: undefined,
|
|
745
|
+
rewritesCapabilities: false,
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
if (required !== undefined) {
|
|
749
|
+
if (!isRecord(required)) return 'its "requiredCapabilities" is neither a list nor an object';
|
|
750
|
+
const keys = keysOfGroupedCapabilities(required);
|
|
751
|
+
if (typeof keys === 'string') return keys;
|
|
752
|
+
return {
|
|
753
|
+
storedCapabilities: {},
|
|
754
|
+
requiredCapabilities: keys,
|
|
755
|
+
groupedCapabilities: required,
|
|
756
|
+
rewritesCapabilities: true,
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
const storedCapabilities = isRecord(stored) ? stored : {};
|
|
760
|
+
const converted = requiredCapabilitiesFrom(storedCapabilities, target);
|
|
761
|
+
if (typeof converted === 'string') return converted;
|
|
762
|
+
return {
|
|
763
|
+
storedCapabilities,
|
|
764
|
+
requiredCapabilities: converted,
|
|
765
|
+
groupedCapabilities: undefined,
|
|
766
|
+
rewritesCapabilities: stored !== undefined,
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** The profile hash a development build stored for capabilities it grouped by provider. */
|
|
771
|
+
function groupedProfileHash(sections: ContractSections): string | undefined {
|
|
772
|
+
if (sections.groupedCapabilities === undefined) return undefined;
|
|
773
|
+
return newHash(sections, {
|
|
774
|
+
requiredCapabilities: capabilitiesThatAreOn(sections.groupedCapabilities),
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function withRequiredCapabilities(value: JsonRecord, sections: ContractSections): JsonRecord {
|
|
779
|
+
if (!sections.rewritesCapabilities) return value;
|
|
780
|
+
const { capabilities: _capabilities, requiredCapabilities: _required, ...rest } = value;
|
|
781
|
+
return { ...rest, requiredCapabilities: [...sections.requiredCapabilities] };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** The index just past the JSON string that starts at `start`. */
|
|
785
|
+
function stringEnd(text: string, start: number): number {
|
|
786
|
+
let i = start + 1;
|
|
787
|
+
while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
|
|
788
|
+
return i + 1;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** The index just past the JSON value that starts at `start`. */
|
|
792
|
+
function valueEnd(text: string, start: number): number {
|
|
793
|
+
let depth = 0;
|
|
794
|
+
let i = start;
|
|
795
|
+
while (i < text.length) {
|
|
796
|
+
const char = text[i];
|
|
797
|
+
if (char === '"') {
|
|
798
|
+
i = stringEnd(text, i);
|
|
799
|
+
if (depth === 0) return i;
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
if (char === '{' || char === '[') depth++;
|
|
803
|
+
else if (char === '}' || char === ']') {
|
|
804
|
+
if (depth === 0) return i;
|
|
805
|
+
depth--;
|
|
806
|
+
if (depth === 0) return i + 1;
|
|
807
|
+
} else if (char === ',' && depth === 0) return i;
|
|
808
|
+
i++;
|
|
809
|
+
}
|
|
810
|
+
return i;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** Where the member `key` of the top-level JSON object in `text` starts, and where its value starts and ends. */
|
|
814
|
+
function topLevelMember(
|
|
815
|
+
text: string,
|
|
816
|
+
key: string,
|
|
817
|
+
): { readonly start: number; readonly valueStart: number; readonly end: number } | undefined {
|
|
818
|
+
let depth = 0;
|
|
819
|
+
let i = 0;
|
|
820
|
+
while (i < text.length) {
|
|
821
|
+
const char = text[i];
|
|
822
|
+
if (char === '"') {
|
|
823
|
+
const end = stringEnd(text, i);
|
|
824
|
+
if (depth === 1) {
|
|
825
|
+
let colon = end;
|
|
826
|
+
while (/\s/.test(text[colon] ?? '')) colon++;
|
|
827
|
+
if (text[colon] === ':' && JSON.parse(text.slice(i, end)) === key) {
|
|
828
|
+
let valueStart = colon + 1;
|
|
829
|
+
while (/\s/.test(text[valueStart] ?? '')) valueStart++;
|
|
830
|
+
return { start: i, valueStart, end: valueEnd(text, valueStart) };
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
i = end;
|
|
834
|
+
continue;
|
|
835
|
+
}
|
|
836
|
+
if (char === '{' || char === '[') depth++;
|
|
837
|
+
else if (char === '}' || char === ']') depth--;
|
|
838
|
+
i++;
|
|
839
|
+
}
|
|
840
|
+
return undefined;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** The indentation of the line `index` is on. */
|
|
844
|
+
function indentationAt(text: string, index: number): string {
|
|
845
|
+
const lineStart = text.lastIndexOf('\n', index - 1) + 1;
|
|
846
|
+
return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? '';
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/** How a value written over several lines lays them out: its line ending, and the indentation each level adds to `indentation`, the indentation of the line it starts on. */
|
|
850
|
+
interface Layout {
|
|
851
|
+
readonly newline: string;
|
|
852
|
+
readonly step: string;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function layoutOf(value: string, indentation: string): Layout {
|
|
856
|
+
const newline = value.includes('\r\n') ? '\r\n' : '\n';
|
|
857
|
+
const inner = /\n([ \t]*)\S/.exec(value)?.[1] ?? '';
|
|
858
|
+
const step =
|
|
859
|
+
inner.startsWith(indentation) && inner.length > indentation.length
|
|
860
|
+
? inner.slice(indentation.length)
|
|
861
|
+
: ' ';
|
|
862
|
+
return { newline, step };
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** The contract's text with its `capabilities` member, or a development build's grouped `requiredCapabilities`, replaced by `requiredCapabilities` holding `required`, written as the old value was: on one line, or over lines with its line ending and indentation. Every other byte stays. */
|
|
866
|
+
function withRequiredCapabilitiesText(
|
|
867
|
+
text: string,
|
|
868
|
+
required: readonly string[],
|
|
869
|
+
): string | undefined {
|
|
870
|
+
const name = topLevelMember(text, 'capabilities') ? 'capabilities' : 'requiredCapabilities';
|
|
871
|
+
const member = topLevelMember(text, name);
|
|
872
|
+
if (member === undefined) return undefined;
|
|
873
|
+
const oldValue = text.slice(member.valueStart, member.end);
|
|
874
|
+
const indentation = indentationAt(text, member.start);
|
|
875
|
+
const { newline, step } = layoutOf(oldValue, indentation);
|
|
876
|
+
const newValue =
|
|
877
|
+
oldValue.includes('\n') && required.length > 0
|
|
878
|
+
? JSON.stringify(required, null, step).split('\n').join(`${newline}${indentation}`)
|
|
879
|
+
: JSON.stringify(required);
|
|
880
|
+
const keyAndColon = text
|
|
881
|
+
.slice(member.start, member.valueStart)
|
|
882
|
+
.replace(`"${name}"`, '"requiredCapabilities"');
|
|
883
|
+
return text.slice(0, member.start) + keyAndColon + newValue + text.slice(member.end);
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** The index just past the brace that closes the one at `open`. */
|
|
887
|
+
function closingBrace(text: string, open: number): number | undefined {
|
|
888
|
+
let depth = 0;
|
|
889
|
+
for (let i = open; i < text.length; i++) {
|
|
890
|
+
const char = text[i];
|
|
891
|
+
if (char === "'" || char === '"') {
|
|
892
|
+
const close = text.indexOf(char, i + 1);
|
|
893
|
+
if (close < 0) return undefined;
|
|
894
|
+
i = close;
|
|
895
|
+
} else if (char === '{') depth++;
|
|
896
|
+
else if (char === '}') {
|
|
897
|
+
depth--;
|
|
898
|
+
if (depth === 0) return i + 1;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
return undefined;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** The width `prisma contract emit` formats `contract.d.ts` to. */
|
|
905
|
+
const DTS_PRINT_WIDTH = 100;
|
|
906
|
+
|
|
907
|
+
/** `required` as `contract.d.ts` writes the type of the list, an array of the union of its keys, laid out as prettier lays it out at the print width: on one line when the member fits; otherwise the union on one line inside the parentheses when that fits; otherwise one key to a line. `layout` gives the line ending and indentation step. */
|
|
908
|
+
function unionArrayType(required: readonly string[], layout: Layout, indentation: string): string {
|
|
909
|
+
const keys = required.map((key) => `'${key.replaceAll("'", "\\'")}'`);
|
|
910
|
+
if (keys.length === 0) return 'readonly never[]';
|
|
911
|
+
const [only] = keys;
|
|
912
|
+
if (keys.length === 1 && only !== undefined) return `readonly ${only}[]`;
|
|
913
|
+
const union = keys.join(' | ');
|
|
914
|
+
const oneLine = `readonly (${union})[]`;
|
|
915
|
+
const member = `${indentation}readonly requiredCapabilities: ${oneLine};`;
|
|
916
|
+
if (member.length <= DTS_PRINT_WIDTH) return oneLine;
|
|
917
|
+
const { newline, step } = layout;
|
|
918
|
+
const unionLine = `${indentation}${step}${union}`;
|
|
919
|
+
const lines =
|
|
920
|
+
unionLine.length <= DTS_PRINT_WIDTH
|
|
921
|
+
? unionLine
|
|
922
|
+
: keys.map((key) => `${indentation}${step}| ${key}`).join(newline);
|
|
923
|
+
return `readonly (${newline}${lines}${newline}${indentation})[]`;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** The `contract.d.ts` text with the contract's `capabilities` type, or a development build's grouped `requiredCapabilities` type, the one just before its `extensions` (or, in an older file, `extensionPacks`), replaced by `requiredCapabilities`, the array of the union of `required`'s keys. A file where that type is not found, such as one already in the list form, is returned as it is: its contract type stays valid, and `prisma contract emit` writes it again. */
|
|
927
|
+
function withRequiredCapabilitiesType(text: string, required: readonly string[]): string {
|
|
928
|
+
const matches = [
|
|
929
|
+
...text.matchAll(/\breadonly (?:capabilities|requiredCapabilities):\s*\{/g),
|
|
930
|
+
].flatMap((match) => {
|
|
931
|
+
const open = match.index + match[0].length - 1;
|
|
932
|
+
const close = closingBrace(text, open);
|
|
933
|
+
if (close === undefined) return [];
|
|
934
|
+
return /^;\s*readonly (extensions|extensionPacks):/.test(text.slice(close))
|
|
935
|
+
? [{ start: match.index, open, close }]
|
|
936
|
+
: [];
|
|
937
|
+
});
|
|
938
|
+
const [only] = matches;
|
|
939
|
+
if (only === undefined || matches.length > 1) return text;
|
|
940
|
+
const oldType = text.slice(only.open, only.close);
|
|
941
|
+
const indentation = indentationAt(text, only.start);
|
|
942
|
+
const newType = unionArrayType(required, layoutOf(oldType, indentation), indentation);
|
|
943
|
+
return `${text.slice(0, only.start)}readonly requiredCapabilities: ${newType}${text.slice(only.close)}`;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// ---------------------------------------------------------------------------
|
|
947
|
+
// Finding stored files.
|
|
948
|
+
|
|
949
|
+
function isDirectory(path: string): boolean {
|
|
950
|
+
try {
|
|
951
|
+
return statSync(path).isDirectory();
|
|
952
|
+
} catch {
|
|
953
|
+
return false;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function errorText(error: unknown): string {
|
|
958
|
+
if (error instanceof Error && 'code' in error) return String(error.code);
|
|
959
|
+
return error instanceof Error ? error.message : String(error);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function listDirectory(dir: string): Dirent[] | string {
|
|
963
|
+
try {
|
|
964
|
+
return readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
|
965
|
+
compareCodeUnits(a.name, b.name),
|
|
966
|
+
);
|
|
967
|
+
} catch (error) {
|
|
968
|
+
return errorText(error);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function isMigrationPackage(dir: string): boolean {
|
|
973
|
+
return existsSync(join(dir, 'migration.json')) && existsSync(join(dir, 'ops.json'));
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function hasSubdirectory(dir: string, holds: (path: string, name: string) => boolean): boolean {
|
|
977
|
+
const entries = listDirectory(dir);
|
|
978
|
+
return (
|
|
979
|
+
typeof entries !== 'string' &&
|
|
980
|
+
entries.some((entry) => {
|
|
981
|
+
const path = join(dir, entry.name);
|
|
982
|
+
return isDirectory(path) && holds(path, entry.name);
|
|
983
|
+
})
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function isSnapshotStore(dir: string): boolean {
|
|
988
|
+
return hasSubdirectory(
|
|
989
|
+
dir,
|
|
990
|
+
(path, name) => HASH.test(name) && existsSync(join(path, 'contract.json')),
|
|
991
|
+
);
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
function isMigrationsDirectory(dir: string): boolean {
|
|
995
|
+
return isSnapshotStore(join(dir, 'snapshots')) || hasSubdirectory(dir, isMigrationPackage);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
function isRefLocation(root: string, path: string): boolean {
|
|
999
|
+
const segments = relative(root, dirname(path)).split(sep);
|
|
1000
|
+
for (let i = segments.length - 1; i >= 0; i--) {
|
|
1001
|
+
if (segments[i] !== 'refs') continue;
|
|
1002
|
+
const owner = join(root, ...segments.slice(0, i));
|
|
1003
|
+
if (isMigrationsDirectory(owner)) return true;
|
|
1004
|
+
if (i > 0 && SPACE_ID.test(segments[i - 1] ?? '') && isMigrationsDirectory(dirname(owner)))
|
|
1005
|
+
return true;
|
|
1006
|
+
}
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function isInRefsDirectory(root: string, path: string): boolean {
|
|
1011
|
+
return relative(root, dirname(path)).split(sep).includes('refs');
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
function hasRefContent(value: JsonRecord): boolean {
|
|
1015
|
+
const hash = value['hash'];
|
|
1016
|
+
return (
|
|
1017
|
+
typeof hash === 'string' &&
|
|
1018
|
+
REF_HASH.test(hash) &&
|
|
1019
|
+
Array.isArray(value['invariants']) &&
|
|
1020
|
+
value['invariants'].every((item) => typeof item === 'string')
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
function isContract(value: JsonRecord): boolean {
|
|
1025
|
+
return typeof value['targetFamily'] === 'string' && isRecord(value['storage']);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function isSnapshotDirectory(dir: string): boolean {
|
|
1029
|
+
return HASH.test(basename(dir)) && basename(dirname(dir)) === 'snapshots';
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/** Whether the link at `path` is a snapshot directory or its `contract.json`, and the walk would read a contract there. */
|
|
1033
|
+
function holdsSnapshotContract(root: string, path: string): boolean {
|
|
1034
|
+
const contract = isSnapshotDirectory(path) ? join(path, 'contract.json') : path;
|
|
1035
|
+
if (snapshotDirectoryHash(contract) === undefined) return false;
|
|
1036
|
+
const probe = emptyFiles();
|
|
1037
|
+
classify(root, contract, probe, [], relative(root, contract));
|
|
1038
|
+
return probe.contracts.length > 0;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
function isInSnapshotDirectory(root: string, path: string): boolean {
|
|
1042
|
+
for (let dir = path; dir !== root && isInside(root, dir); dir = dirname(dir))
|
|
1043
|
+
if (isSnapshotDirectory(dir)) return true;
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** The hash a snapshot's directory is named by, when `path` is a snapshot's `contract.json`. */
|
|
1048
|
+
function snapshotDirectoryHash(path: string): string | undefined {
|
|
1049
|
+
const dir = dirname(path);
|
|
1050
|
+
return basename(path) === 'contract.json' && isSnapshotDirectory(dir) ? basename(dir) : undefined;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
interface StoredText {
|
|
1054
|
+
readonly path: string;
|
|
1055
|
+
readonly bom: string;
|
|
1056
|
+
readonly text: string;
|
|
1057
|
+
readonly value: JsonRecord;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
interface ProjectFiles {
|
|
1061
|
+
readonly contracts: StoredText[];
|
|
1062
|
+
readonly migrations: StoredText[];
|
|
1063
|
+
readonly refs: StoredText[];
|
|
1064
|
+
readonly migrationTs: string[];
|
|
1065
|
+
readonly unversioned: string[];
|
|
1066
|
+
/** Files and directories an interrupted run of this script left behind. */
|
|
1067
|
+
readonly leftovers: string[];
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
function emptyFiles(): ProjectFiles {
|
|
1071
|
+
return {
|
|
1072
|
+
contracts: [],
|
|
1073
|
+
migrations: [],
|
|
1074
|
+
refs: [],
|
|
1075
|
+
migrationTs: [],
|
|
1076
|
+
unversioned: [],
|
|
1077
|
+
leftovers: [],
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/** A file's text without a leading byte order mark, and the mark, so a rewrite can keep it. */
|
|
1082
|
+
function readText(path: string): { readonly bom: string; readonly text: string } {
|
|
1083
|
+
const raw = readFileSync(path, 'utf8');
|
|
1084
|
+
const bom = raw.startsWith(BYTE_ORDER_MARK) ? BYTE_ORDER_MARK : '';
|
|
1085
|
+
return { bom, text: raw.slice(bom.length) };
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function readStored(path: string): StoredText | string {
|
|
1089
|
+
let bom: string;
|
|
1090
|
+
let text: string;
|
|
1091
|
+
try {
|
|
1092
|
+
({ bom, text } = readText(path));
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
return `cannot be read (${errorText(error)})`;
|
|
1095
|
+
}
|
|
1096
|
+
let value: Json;
|
|
1097
|
+
try {
|
|
1098
|
+
value = JSON.parse(text);
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
return `is not valid JSON (${errorText(error)})`;
|
|
1101
|
+
}
|
|
1102
|
+
if (!isRecord(value)) return 'is not a JSON object';
|
|
1103
|
+
return { path, bom, text, value };
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
function classify(
|
|
1107
|
+
root: string,
|
|
1108
|
+
path: string,
|
|
1109
|
+
files: ProjectFiles,
|
|
1110
|
+
stops: string[],
|
|
1111
|
+
shown: string,
|
|
1112
|
+
): void {
|
|
1113
|
+
const name = basename(path);
|
|
1114
|
+
const inPackage = name === 'migration.json' && isMigrationPackage(dirname(path));
|
|
1115
|
+
const atRefLocation = !name.endsWith('.contract.json') && isRefLocation(root, path);
|
|
1116
|
+
const mustParse = inPackage || atRefLocation || name === 'contract.json';
|
|
1117
|
+
const stored = readStored(path);
|
|
1118
|
+
if (typeof stored === 'string') {
|
|
1119
|
+
if (mustParse) stops.push(`${shown}: ${stored}`);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const { value } = stored;
|
|
1123
|
+
if (inPackage) {
|
|
1124
|
+
files.migrations.push(stored);
|
|
1125
|
+
} else if (atRefLocation || (isInRefsDirectory(root, path) && hasRefContent(value))) {
|
|
1126
|
+
files.refs.push(stored);
|
|
1127
|
+
} else if (isContract(value)) {
|
|
1128
|
+
if (value['formatVersion'] === undefined && value['schemaVersion'] === undefined) {
|
|
1129
|
+
if (name === 'contract.json') {
|
|
1130
|
+
const remedy =
|
|
1131
|
+
snapshotDirectoryHash(path) === undefined
|
|
1132
|
+
? 'Emit it again with `prisma contract emit`, or restore it from version control'
|
|
1133
|
+
: 'Restore it from version control';
|
|
1134
|
+
files.unversioned.push(
|
|
1135
|
+
`${shown}: has neither "formatVersion" nor "schemaVersion", so no release of Prisma wrote it; the script leaves it alone. ${remedy}`,
|
|
1136
|
+
);
|
|
1137
|
+
}
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
files.contracts.push(stored);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
function isWalked(name: string): boolean {
|
|
1145
|
+
return !SKIPPED_DIRECTORIES.has(name) && !name.startsWith('.');
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
function isInside(dir: string, path: string): boolean {
|
|
1149
|
+
return path === dir || path.startsWith(`${dir}${sep}`);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function visit(
|
|
1153
|
+
root: string,
|
|
1154
|
+
dir: string,
|
|
1155
|
+
files: ProjectFiles,
|
|
1156
|
+
stops: string[],
|
|
1157
|
+
checkLinks = true,
|
|
1158
|
+
): void {
|
|
1159
|
+
const entries = listDirectory(dir);
|
|
1160
|
+
if (typeof entries === 'string') {
|
|
1161
|
+
stops.push(`${relative(root, dir) || '.'}: directory cannot be read (${entries})`);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
for (const entry of entries) {
|
|
1165
|
+
const path = join(dir, entry.name);
|
|
1166
|
+
const shown = relative(root, path);
|
|
1167
|
+
if (entry.isDirectory()) {
|
|
1168
|
+
if (entry.name.startsWith('.') && entry.name.endsWith(REMOVED_SUFFIX))
|
|
1169
|
+
files.leftovers.push(path);
|
|
1170
|
+
else if (isWalked(entry.name)) visit(root, path, files, stops, checkLinks);
|
|
1171
|
+
} else if (entry.isFile() && entry.name.endsWith(TEMPORARY_SUFFIX)) {
|
|
1172
|
+
files.leftovers.push(path);
|
|
1173
|
+
} else if (entry.isFile() && entry.name.endsWith('.json')) {
|
|
1174
|
+
classify(root, path, files, stops, shown);
|
|
1175
|
+
} else if (entry.isFile() && entry.name === 'migration.ts' && isMigrationPackage(dir)) {
|
|
1176
|
+
files.migrationTs.push(path);
|
|
1177
|
+
} else if (checkLinks && entry.isSymbolicLink()) {
|
|
1178
|
+
checkLink(root, path, entry.name, stops);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
/** Stops on a symbolic link to stored files the walk does not reach, outside the project root or inside it where the walk skips, and on a link inside the root to a place the walk reads as another kind of file than at the link, or that holds a snapshot the walk would not rename through the link, and on a link inside the root into a snapshot directory, which the rename would leave pointing at nothing; the script does not follow links. A link to the root or a folder above it leads back to the project itself and stops the run only when it is a snapshot directory or its `contract.json` and a contract is read there. */
|
|
1184
|
+
function checkLink(root: string, path: string, name: string, stops: string[]): void {
|
|
1185
|
+
let target: string;
|
|
1186
|
+
try {
|
|
1187
|
+
target = realpathSync(path);
|
|
1188
|
+
} catch {
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
const realRoot = realpathSync(root);
|
|
1192
|
+
const snapshotStop = `${relative(root, path)}: is a symbolic link to ${relative(realRoot, target) || '.'}, and holds a migration snapshot at the link; the script renames each snapshot directory to its new storage hash, and through a link the snapshot would keep its old name. Replace the link with what it points to`;
|
|
1193
|
+
if (holdsSnapshotContract(root, path)) {
|
|
1194
|
+
stops.push(snapshotStop);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (isInside(target, realRoot)) return;
|
|
1198
|
+
const inside = isInside(realRoot, target);
|
|
1199
|
+
const reached =
|
|
1200
|
+
relative(realRoot, target).split(sep).every(isWalked) &&
|
|
1201
|
+
(isDirectory(target) || target.endsWith('.json'));
|
|
1202
|
+
const intoSnapshot = inside && isInSnapshotDirectory(realRoot, target);
|
|
1203
|
+
const reading = inside && reached ? linkReading(root, path, realRoot, target, name) : undefined;
|
|
1204
|
+
if (reading === 'snapshot') {
|
|
1205
|
+
stops.push(snapshotStop);
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
if (intoSnapshot) {
|
|
1209
|
+
stops.push(
|
|
1210
|
+
`${relative(root, path)}: is a symbolic link into the snapshot directory of ${relative(realRoot, target)}; the script renames each snapshot directory to its new storage hash, so the link would point at nothing. Replace the link with a copy of what it points to, or point it somewhere else`,
|
|
1211
|
+
);
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
if (reading !== undefined) {
|
|
1215
|
+
if (reading === 'alike') return;
|
|
1216
|
+
stops.push(
|
|
1217
|
+
`${relative(root, path)}: is a symbolic link to ${relative(realRoot, target)}, where the script does not read what it holds as it would at the link, such as a ref file it finds only in a refs folder; the script does not follow links. Replace the link with what it points to`,
|
|
1218
|
+
);
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
const probe = emptyFiles();
|
|
1222
|
+
const probeStops: string[] = [];
|
|
1223
|
+
const targetIsDirectory = isDirectory(target);
|
|
1224
|
+
if (targetIsDirectory) {
|
|
1225
|
+
if (!isWalked(name)) return;
|
|
1226
|
+
// The probe reports the stored files the link reaches directly; following its own links could loop between two folders that link to each other.
|
|
1227
|
+
visit(target, target, probe, probeStops, false);
|
|
1228
|
+
} else if (name.endsWith('.json')) {
|
|
1229
|
+
classify(dirname(target), target, probe, probeStops, name);
|
|
1230
|
+
}
|
|
1231
|
+
const holds =
|
|
1232
|
+
probe.contracts.length + probe.migrations.length + probe.refs.length + probeStops.length > 0;
|
|
1233
|
+
if (!holds) return;
|
|
1234
|
+
stops.push(
|
|
1235
|
+
inside
|
|
1236
|
+
? `${relative(root, path)}: is a symbolic link to ${relative(realRoot, target)}, which the script skips, and which holds stored files; the script does not follow links. Replace the link with what it points to, or move ${relative(realRoot, target)} where the script walks`
|
|
1237
|
+
: `${relative(root, path)}: is a symbolic link to ${target}, outside the project, which holds stored files; the script does not follow links. Run it on ${target} as well, or replace the link with what it points to`,
|
|
1238
|
+
);
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/** Whether the walk, which reaches the target of the link at `path`, reads the stored files there as it would at the link's own place. A link that holds a snapshot at the link that the target does not hold under the same hash reads as `snapshot`: the script renames a snapshot directory to the new hash, and renaming the target leaves the link's own name. */
|
|
1242
|
+
function linkReading(
|
|
1243
|
+
root: string,
|
|
1244
|
+
path: string,
|
|
1245
|
+
realRoot: string,
|
|
1246
|
+
target: string,
|
|
1247
|
+
name: string,
|
|
1248
|
+
): 'alike' | 'snapshot' | 'other' {
|
|
1249
|
+
const atLink = emptyFiles();
|
|
1250
|
+
const atTarget = emptyFiles();
|
|
1251
|
+
const stopsAtLink: string[] = [];
|
|
1252
|
+
const stopsAtTarget: string[] = [];
|
|
1253
|
+
if (isDirectory(target)) {
|
|
1254
|
+
if (!isWalked(name)) return 'alike';
|
|
1255
|
+
visit(root, path, atLink, stopsAtLink, false);
|
|
1256
|
+
visit(realRoot, target, atTarget, stopsAtTarget, false);
|
|
1257
|
+
} else if (name.endsWith('.json')) {
|
|
1258
|
+
classify(root, path, atLink, stopsAtLink, relative(root, path));
|
|
1259
|
+
classify(realRoot, target, atTarget, stopsAtTarget, relative(realRoot, target));
|
|
1260
|
+
}
|
|
1261
|
+
const snapshotAtTarget = new Map(
|
|
1262
|
+
atTarget.contracts.map((file) => [
|
|
1263
|
+
relative(target, file.path),
|
|
1264
|
+
snapshotDirectoryHash(file.path),
|
|
1265
|
+
]),
|
|
1266
|
+
);
|
|
1267
|
+
const keepsSnapshot = (file: StoredText) => {
|
|
1268
|
+
const hash = snapshotDirectoryHash(file.path);
|
|
1269
|
+
return hash === undefined || snapshotAtTarget.get(relative(path, file.path)) === hash;
|
|
1270
|
+
};
|
|
1271
|
+
if (!atLink.contracts.every(keepsSnapshot)) return 'snapshot';
|
|
1272
|
+
const read = (files: ProjectFiles, stopped: readonly string[], prefix: string) => {
|
|
1273
|
+
const under = (file: string) => relative(prefix, file);
|
|
1274
|
+
return JSON.stringify({
|
|
1275
|
+
contracts: files.contracts.map((file) => under(file.path)),
|
|
1276
|
+
migrations: files.migrations.map((file) => under(file.path)),
|
|
1277
|
+
refs: files.refs.map((file) => under(file.path)),
|
|
1278
|
+
migrationTs: files.migrationTs.map(under),
|
|
1279
|
+
unversioned: files.unversioned.length,
|
|
1280
|
+
stops: stopped.length,
|
|
1281
|
+
});
|
|
1282
|
+
};
|
|
1283
|
+
return read(atLink, stopsAtLink, path) === read(atTarget, stopsAtTarget, target)
|
|
1284
|
+
? 'alike'
|
|
1285
|
+
: 'other';
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
// ---------------------------------------------------------------------------
|
|
1289
|
+
// Planning.
|
|
1290
|
+
|
|
1291
|
+
const KIND_LABEL: Record<HashKind, string> = {
|
|
1292
|
+
storage: 'storage hash',
|
|
1293
|
+
profile: 'profile hash',
|
|
1294
|
+
execution: 'execution hash',
|
|
1295
|
+
};
|
|
1296
|
+
|
|
1297
|
+
interface StoredHashes {
|
|
1298
|
+
readonly storage: unknown;
|
|
1299
|
+
readonly profile: unknown;
|
|
1300
|
+
readonly execution: unknown;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
function storedHashes(value: JsonRecord): StoredHashes {
|
|
1304
|
+
const storage = isRecord(value['storage']) ? value['storage'] : {};
|
|
1305
|
+
const execution = isRecord(value['execution']) ? value['execution'] : undefined;
|
|
1306
|
+
return {
|
|
1307
|
+
storage: storage['storageHash'],
|
|
1308
|
+
profile: value['profileHash'],
|
|
1309
|
+
execution: execution?.['executionHash'],
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
function sectionsOf(value: JsonRecord): ContractSections | string {
|
|
1314
|
+
const family = value['targetFamily'];
|
|
1315
|
+
if (family !== 'sql' && family !== 'mongo')
|
|
1316
|
+
return `its family is ${JSON.stringify(family)}; the script knows the hash rules of the "sql" and "mongo" families only`;
|
|
1317
|
+
const target = value['target'];
|
|
1318
|
+
if (typeof target !== 'string') return 'it has no "target" string';
|
|
1319
|
+
const storage = isRecord(value['storage']) ? value['storage'] : {};
|
|
1320
|
+
const { storageHash: _storageHash, ...storageSection } = storage;
|
|
1321
|
+
const capabilities = capabilitiesOf(value, target);
|
|
1322
|
+
if (typeof capabilities === 'string') return capabilities;
|
|
1323
|
+
const executionValue = value['execution'];
|
|
1324
|
+
let execution: JsonRecord | undefined;
|
|
1325
|
+
if (isRecord(executionValue)) {
|
|
1326
|
+
const { executionHash: _executionHash, ...rest } = executionValue;
|
|
1327
|
+
execution = rest;
|
|
1328
|
+
}
|
|
1329
|
+
return { family, target, storage: storageSection, ...capabilities, execution };
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
interface ContractPlan {
|
|
1333
|
+
readonly file: StoredText;
|
|
1334
|
+
readonly sections: ContractSections;
|
|
1335
|
+
readonly oldHashes: HashSet;
|
|
1336
|
+
readonly newHashes: HashSet;
|
|
1337
|
+
readonly snapshotHash: string | undefined;
|
|
1338
|
+
/** The new storage hash of the contract the earlier release wrote from the same source. */
|
|
1339
|
+
readonly earlierReleaseStorageHash: string;
|
|
1340
|
+
/** The hash a MongoDB snapshot is named by when an earlier upgrade step rewrote its content and kept the hash. */
|
|
1341
|
+
readonly keptStorageHash: string | undefined;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
class HashMap {
|
|
1345
|
+
readonly byKind: Record<Exclude<HashKind, 'profile'>, Map<string, string>> = {
|
|
1346
|
+
storage: new Map(),
|
|
1347
|
+
execution: new Map(),
|
|
1348
|
+
};
|
|
1349
|
+
/**
|
|
1350
|
+
* Each old profile hash and a new one it became. The old SQL profile hash covered no capabilities, so contracts of one target with different capabilities share an old value and get different new ones. No file but the contract and its `contract.d.ts` stores a profile hash, so it is replaced contract by contract and only reported here.
|
|
1351
|
+
*/
|
|
1352
|
+
readonly profiles = new Set<string>();
|
|
1353
|
+
readonly all = new Map<string, string>();
|
|
1354
|
+
readonly newValues = new Set<string>();
|
|
1355
|
+
|
|
1356
|
+
add(kind: HashKind, from: string, to: string, conflicts: string[]): void {
|
|
1357
|
+
if (kind === 'profile') {
|
|
1358
|
+
if (from !== to) this.profiles.add(`${from} -> ${to}`);
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
const known = this.all.get(from);
|
|
1362
|
+
if (known !== undefined && known !== to) {
|
|
1363
|
+
conflicts.push(`the hash ${from} maps to both ${known} and ${to}`);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
this.newValues.add(to);
|
|
1367
|
+
if (from === to) return;
|
|
1368
|
+
this.all.set(from, to);
|
|
1369
|
+
this.byKind[kind].set(from, to);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** The new value of `hash`, or undefined when `hash` is neither an old nor a new hash of a contract. */
|
|
1373
|
+
resolve(hash: string): string | undefined {
|
|
1374
|
+
return this.all.get(hash) ?? (this.newValues.has(hash) ? hash : undefined);
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
age(hash: string): 'old' | 'new' | 'unknown' {
|
|
1378
|
+
if (this.all.has(hash)) return 'old';
|
|
1379
|
+
return this.newValues.has(hash) ? 'new' : 'unknown';
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
/**
|
|
1384
|
+
* A MongoDB snapshot may hold a storage hash its content does not give: the index-name and field-storage-name upgrade steps rewrote snapshots in place and kept their hashes, because database signatures, the ledger and migrations name a snapshot by its hash. Such a snapshot's directory name is the hash it was kept under. Its stored hash is that hash too, or already the new one when a run of this script stopped before it renamed the directory.
|
|
1385
|
+
*/
|
|
1386
|
+
function keptStorageHash(
|
|
1387
|
+
family: Family,
|
|
1388
|
+
snapshotHash: string | undefined,
|
|
1389
|
+
stored: unknown,
|
|
1390
|
+
oldHash: string | undefined,
|
|
1391
|
+
newHash: string | undefined,
|
|
1392
|
+
): string | undefined {
|
|
1393
|
+
if (family !== 'mongo' || snapshotHash === undefined) return undefined;
|
|
1394
|
+
if (snapshotHash === oldHash || snapshotHash === newHash) return undefined;
|
|
1395
|
+
return stored === snapshotHash || stored === newHash ? snapshotHash : undefined;
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
function hashList(hashes: HashSet): string {
|
|
1399
|
+
const kinds = (['storage', 'profile', 'execution'] as const).filter(
|
|
1400
|
+
(kind) => hashes[kind] !== undefined,
|
|
1401
|
+
);
|
|
1402
|
+
const join = (items: readonly string[]) =>
|
|
1403
|
+
items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
|
|
1404
|
+
return `${join(kinds)} hashes to ${join(kinds.map((kind) => hashes[kind] ?? ''))}`;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
interface ContractChecks {
|
|
1408
|
+
readonly stops: string[];
|
|
1409
|
+
/** Contracts the script leaves unchanged and reports, without refusing the project. */
|
|
1410
|
+
readonly left: string[];
|
|
1411
|
+
/** Snapshots whose profile or execution hash an earlier release wrote by other rules. */
|
|
1412
|
+
readonly notes: string[];
|
|
1413
|
+
/** Every storage hash a migration, ref or snapshot names. */
|
|
1414
|
+
readonly named: ReadonlySet<string>;
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
function planContract(
|
|
1418
|
+
file: StoredText,
|
|
1419
|
+
shown: string,
|
|
1420
|
+
checks: ContractChecks,
|
|
1421
|
+
): ContractPlan | undefined {
|
|
1422
|
+
const sections = sectionsOf(file.value);
|
|
1423
|
+
if (typeof sections === 'string') {
|
|
1424
|
+
checks.stops.push(`${shown}: ${sections}`);
|
|
1425
|
+
return undefined;
|
|
1426
|
+
}
|
|
1427
|
+
const stored = storedHashes(file.value);
|
|
1428
|
+
const snapshotHash = snapshotDirectoryHash(file.path);
|
|
1429
|
+
const oldHashes = storedOldHashes(sections, stored, snapshotHash);
|
|
1430
|
+
const newHashes = contractHashes(sections, newHash, {
|
|
1431
|
+
requiredCapabilities: sections.requiredCapabilities,
|
|
1432
|
+
});
|
|
1433
|
+
const kept = keptStorageHash(
|
|
1434
|
+
sections.family,
|
|
1435
|
+
snapshotHash,
|
|
1436
|
+
stored.storage,
|
|
1437
|
+
oldHashes.storage,
|
|
1438
|
+
newHashes.storage,
|
|
1439
|
+
);
|
|
1440
|
+
const problems: string[] = [];
|
|
1441
|
+
const stale: string[] = [];
|
|
1442
|
+
for (const kind of ['storage', 'profile', 'execution'] as const) {
|
|
1443
|
+
const value = stored[kind];
|
|
1444
|
+
const expectedOld = oldHashes[kind];
|
|
1445
|
+
if (expectedOld === undefined) continue;
|
|
1446
|
+
if (value === expectedOld || value === newHashes[kind]) continue;
|
|
1447
|
+
if (kind === 'storage' && kept !== undefined && value === kept) continue;
|
|
1448
|
+
if (value === undefined) problems.push(`it has no ${KIND_LABEL[kind]}`);
|
|
1449
|
+
else if (kind !== 'storage' && snapshotHash !== undefined) stale.push(KIND_LABEL[kind]);
|
|
1450
|
+
else
|
|
1451
|
+
problems.push(
|
|
1452
|
+
`its ${KIND_LABEL[kind]} ${JSON.stringify(value)} is not the one its content gives, ${expectedOld}`,
|
|
1453
|
+
);
|
|
1454
|
+
}
|
|
1455
|
+
if (
|
|
1456
|
+
snapshotHash !== undefined &&
|
|
1457
|
+
kept === undefined &&
|
|
1458
|
+
snapshotHash !== oldHashes.storage &&
|
|
1459
|
+
snapshotHash !== newHashes.storage
|
|
1460
|
+
)
|
|
1461
|
+
problems.push(
|
|
1462
|
+
`its snapshot directory is named ${snapshotHash}, which is not the storage hash its content gives, ${oldHashes.storage}`,
|
|
1463
|
+
);
|
|
1464
|
+
if (problems.length > 0) {
|
|
1465
|
+
const isNamed = typeof stored.storage === 'string' && checks.named.has(stored.storage);
|
|
1466
|
+
if (snapshotHash === undefined && !isNamed)
|
|
1467
|
+
checks.left.push(
|
|
1468
|
+
`${shown}: ${problems.join('; ')}. It is not a snapshot, and no migration, ref or snapshot names its hashes, so the script leaves it alone. If Prisma emits it, emit it again with \`prisma contract emit\`; otherwise set its ${hashList(newHashes)}, the hashes its content gives`,
|
|
1469
|
+
);
|
|
1470
|
+
else
|
|
1471
|
+
checks.stops.push(
|
|
1472
|
+
`${shown}: ${problems.join('; ')}. The file was edited by hand or comes from another release: restore it from version control${snapshotHash === undefined ? ', or emit it again,' : ''} and run the script again`,
|
|
1473
|
+
);
|
|
1474
|
+
return undefined;
|
|
1475
|
+
}
|
|
1476
|
+
if (stale.length > 0) checks.notes.push(`${shown} (${stale.join(' and ')})`);
|
|
1477
|
+
return {
|
|
1478
|
+
file,
|
|
1479
|
+
sections,
|
|
1480
|
+
oldHashes,
|
|
1481
|
+
newHashes,
|
|
1482
|
+
snapshotHash,
|
|
1483
|
+
earlierReleaseStorageHash: newStorageHashAsTheEarlierReleaseWrote(sections),
|
|
1484
|
+
keptStorageHash: kept,
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/**
|
|
1489
|
+
* Whether `prisma contract emit` wrote the contract with this release: it is not a snapshot, it has the `_generated` block that `prisma contract emit` writes, and it stores the new hash its content gives, not the old one. Its old hash is the one the earlier release computed for the same source. When the source holds a value the earlier release left out, its new hash differs from the new hash of the contract that release wrote, which is the one migrations and databases are at, whether or not a snapshot of it is left.
|
|
1490
|
+
*/
|
|
1491
|
+
function isEmittedByThisRelease(plan: ContractPlan, kind: HashKind): boolean {
|
|
1492
|
+
const to = plan.newHashes[kind];
|
|
1493
|
+
return (
|
|
1494
|
+
plan.snapshotHash === undefined &&
|
|
1495
|
+
Object.hasOwn(plan.file.value, '_generated') &&
|
|
1496
|
+
to !== plan.oldHashes[kind] &&
|
|
1497
|
+
storedHashes(plan.file.value)[kind] === to
|
|
1498
|
+
);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
/** Every storage hash a migration's `from` or `to`, a ref, or a snapshot's directory name or stored hash names. */
|
|
1502
|
+
function namedHashes(files: ProjectFiles): Set<string> {
|
|
1503
|
+
const named = new Set<string>();
|
|
1504
|
+
const add = (hash: unknown) => {
|
|
1505
|
+
if (typeof hash === 'string') named.add(hash);
|
|
1506
|
+
};
|
|
1507
|
+
for (const { value } of files.migrations) {
|
|
1508
|
+
add(value['from']);
|
|
1509
|
+
add(value['to']);
|
|
1510
|
+
}
|
|
1511
|
+
for (const { value } of files.refs) add(value['hash']);
|
|
1512
|
+
for (const { path, value } of files.contracts) {
|
|
1513
|
+
const snapshotHash = snapshotDirectoryHash(path);
|
|
1514
|
+
if (snapshotHash === undefined) continue;
|
|
1515
|
+
add(snapshotHash);
|
|
1516
|
+
add(storedHashes(value).storage);
|
|
1517
|
+
}
|
|
1518
|
+
return named;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/**
|
|
1522
|
+
* The hashes no contract of the project has that a migration links, through the `from` and `to` of other migrations, only to hashes that already have their new value. Prisma copies an extension's migrations into an application without a snapshot of each contract in between, and after `prisma contract emit` writes them again from an upgraded extension, they name those contracts by their new hashes.
|
|
1523
|
+
*/
|
|
1524
|
+
function unknownHashesAlreadyNew(migrations: readonly StoredText[], hashes: HashMap): Set<string> {
|
|
1525
|
+
const neighbours = new Map<string, string[]>();
|
|
1526
|
+
for (const { value } of migrations) {
|
|
1527
|
+
const ends = [value['from'], value['to']].filter(
|
|
1528
|
+
(hash): hash is string => typeof hash === 'string' && HASH.test(hash),
|
|
1529
|
+
);
|
|
1530
|
+
for (const hash of ends) if (!neighbours.has(hash)) neighbours.set(hash, []);
|
|
1531
|
+
const [from, to] = ends;
|
|
1532
|
+
if (from !== undefined && to !== undefined) {
|
|
1533
|
+
neighbours.get(from)?.push(to);
|
|
1534
|
+
neighbours.get(to)?.push(from);
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
const alreadyNew = new Set<string>();
|
|
1538
|
+
const seen = new Set<string>();
|
|
1539
|
+
for (const start of neighbours.keys()) {
|
|
1540
|
+
if (seen.has(start)) continue;
|
|
1541
|
+
const component: string[] = [];
|
|
1542
|
+
const pending = [start];
|
|
1543
|
+
seen.add(start);
|
|
1544
|
+
for (let hash = pending.pop(); hash !== undefined; hash = pending.pop()) {
|
|
1545
|
+
component.push(hash);
|
|
1546
|
+
for (const next of neighbours.get(hash) ?? [])
|
|
1547
|
+
if (!seen.has(next)) {
|
|
1548
|
+
seen.add(next);
|
|
1549
|
+
pending.push(next);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
const ages = new Set(component.map((hash) => hashes.age(hash)));
|
|
1553
|
+
if (ages.has('new') && !ages.has('old'))
|
|
1554
|
+
for (const hash of component) if (hashes.age(hash) === 'unknown') alreadyNew.add(hash);
|
|
1555
|
+
}
|
|
1556
|
+
return alreadyNew;
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/** `text` with each quoted occurrence of a key of `replacements` replaced by its value. */
|
|
1560
|
+
function replaceQuoted(text: string, replacements: ReadonlyMap<string, string>): string {
|
|
1561
|
+
return text.replace(/"([0-9a-f]{64})"/g, (match: string, hash: string) => {
|
|
1562
|
+
const next = replacements.get(hash);
|
|
1563
|
+
return next === undefined ? match : `"${next}"`;
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
function replaceTokens(text: string, replacements: ReadonlyMap<string, string>): string {
|
|
1568
|
+
return text.replace(
|
|
1569
|
+
/(?<![0-9a-f])[0-9a-f]{64}(?![0-9a-f])/g,
|
|
1570
|
+
(hash: string) => replacements.get(hash) ?? hash,
|
|
1571
|
+
);
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
function withHashes(value: JsonRecord, hashes: HashSet): JsonRecord {
|
|
1575
|
+
const storage = isRecord(value['storage']) ? value['storage'] : {};
|
|
1576
|
+
const execution = value['execution'];
|
|
1577
|
+
return {
|
|
1578
|
+
...value,
|
|
1579
|
+
profileHash: hashes.profile ?? null,
|
|
1580
|
+
storage: { ...storage, storageHash: hashes.storage ?? null },
|
|
1581
|
+
...(isRecord(execution) && hashes.execution !== undefined
|
|
1582
|
+
? { execution: { ...execution, executionHash: hashes.execution } }
|
|
1583
|
+
: {}),
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
/** Each hash the contract stores, the old hash its content gives, and a snapshot's directory name, mapped to the new hash its content gives. */
|
|
1588
|
+
function storedReplacements(plan: ContractPlan): Map<string, string> {
|
|
1589
|
+
const stored = storedHashes(plan.file.value);
|
|
1590
|
+
const replacements = new Map<string, string>();
|
|
1591
|
+
for (const kind of ['storage', 'profile', 'execution'] as const) {
|
|
1592
|
+
const to = plan.newHashes[kind];
|
|
1593
|
+
if (to === undefined) continue;
|
|
1594
|
+
const from = [stored[kind], plan.oldHashes[kind]];
|
|
1595
|
+
if (kind === 'storage') from.push(plan.snapshotHash);
|
|
1596
|
+
for (const hash of from)
|
|
1597
|
+
if (typeof hash === 'string' && hash !== to) replacements.set(hash, to);
|
|
1598
|
+
}
|
|
1599
|
+
return replacements;
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
/** The contract file's text with its capabilities renamed and its stored hashes replaced by the new ones, or undefined when that edit would change anything else. */
|
|
1603
|
+
function rewrittenContract(plan: ContractPlan): string | undefined {
|
|
1604
|
+
const { value, text } = plan.file;
|
|
1605
|
+
const replacements = storedReplacements(plan);
|
|
1606
|
+
if (replacements.size === 0 && !plan.sections.rewritesCapabilities) return text;
|
|
1607
|
+
const renamed = plan.sections.rewritesCapabilities
|
|
1608
|
+
? withRequiredCapabilitiesText(text, plan.sections.requiredCapabilities)
|
|
1609
|
+
: text;
|
|
1610
|
+
if (renamed === undefined) return undefined;
|
|
1611
|
+
const next = replaceQuoted(renamed, replacements);
|
|
1612
|
+
const expected = withHashes(withRequiredCapabilities(value, plan.sections), plan.newHashes);
|
|
1613
|
+
return canonicalizeJson(JSON.parse(next)) === canonicalizeJson(expected) ? next : undefined;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
function dtsPathOf(contractPath: string): string {
|
|
1617
|
+
return `${contractPath.slice(0, -'.json'.length)}.d.ts`;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
const DTS_HASH = /\b(Storage|Profile|Execution)HashBase<\s*(['"])([0-9a-f]{64})\2\s*>/g;
|
|
1621
|
+
const DTS_KIND: Record<string, HashKind> = {
|
|
1622
|
+
Storage: 'storage',
|
|
1623
|
+
Profile: 'profile',
|
|
1624
|
+
Execution: 'execution',
|
|
1625
|
+
};
|
|
1626
|
+
|
|
1627
|
+
/** The `contract.d.ts` text with the contract's old hashes replaced, or a reason it cannot be. */
|
|
1628
|
+
function rewrittenDts(text: string, plan: ContractPlan): string | { readonly problem: string } {
|
|
1629
|
+
const renamed = withRequiredCapabilitiesType(text, plan.sections.requiredCapabilities);
|
|
1630
|
+
const next = replaceTokens(renamed, storedReplacements(plan));
|
|
1631
|
+
const stale = [...next.matchAll(DTS_HASH)]
|
|
1632
|
+
.filter((match) => {
|
|
1633
|
+
const kind = DTS_KIND[match[1] ?? ''];
|
|
1634
|
+
return kind === undefined || plan.newHashes[kind] !== match[3];
|
|
1635
|
+
})
|
|
1636
|
+
.map((match) => match[0]);
|
|
1637
|
+
if (stale.length === 0) return next;
|
|
1638
|
+
return {
|
|
1639
|
+
problem: `names ${stale.join(', ')}, which is not a hash of the contract beside it; emit the contract again with \`prisma contract emit\`, or, for a snapshot, restore both files from version control`,
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
interface Plan {
|
|
1644
|
+
readonly writes: Map<string, string>;
|
|
1645
|
+
readonly renames: [string, string][];
|
|
1646
|
+
readonly removals: string[];
|
|
1647
|
+
readonly notes: string[];
|
|
1648
|
+
readonly kept: string[];
|
|
1649
|
+
/** Contracts `prisma contract emit` wrote with this release before the script ran, whose old hash a snapshot maps to another new hash. */
|
|
1650
|
+
readonly emitted: string[];
|
|
1651
|
+
readonly merged: string[];
|
|
1652
|
+
/** Old snapshot directories removed because `prisma contract emit` already wrote their contract under its new storage hash. */
|
|
1653
|
+
readonly superseded: string[];
|
|
1654
|
+
/** Contracts whose capabilities the script writes as the list of keys `requiredCapabilities`. */
|
|
1655
|
+
readonly renamedCapabilities: string[];
|
|
1656
|
+
readonly problems: string[];
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
function main(args: readonly string[]): number {
|
|
1660
|
+
if (args.length > 1 || args.some((arg) => arg.startsWith('-'))) {
|
|
1661
|
+
process.stderr.write('Usage: node contract-hash-inputs.ts [project-root]\n');
|
|
1662
|
+
return 1;
|
|
1663
|
+
}
|
|
1664
|
+
const root = resolve(args[0] ?? process.cwd());
|
|
1665
|
+
if (!isDirectory(root)) {
|
|
1666
|
+
process.stderr.write(`${root}: not a directory\n`);
|
|
1667
|
+
return 1;
|
|
1668
|
+
}
|
|
1669
|
+
const shown = (path: string) => relative(root, path).split(sep).join('/');
|
|
1670
|
+
const files = emptyFiles();
|
|
1671
|
+
const stops: string[] = [];
|
|
1672
|
+
visit(root, root, files, stops);
|
|
1673
|
+
if (stops.length > 0) return refuse(stops);
|
|
1674
|
+
|
|
1675
|
+
const contracts: ContractPlan[] = [];
|
|
1676
|
+
const checks: ContractChecks = {
|
|
1677
|
+
stops,
|
|
1678
|
+
left: [...files.unversioned],
|
|
1679
|
+
notes: [],
|
|
1680
|
+
named: namedHashes(files),
|
|
1681
|
+
};
|
|
1682
|
+
for (const file of files.contracts) {
|
|
1683
|
+
const plan = planContract(file, shown(file.path), checks);
|
|
1684
|
+
if (plan !== undefined) contracts.push(plan);
|
|
1685
|
+
}
|
|
1686
|
+
const hashes = new HashMap();
|
|
1687
|
+
const kept: string[] = [];
|
|
1688
|
+
const emittedFirst: { plan: ContractPlan; from: string; to: string }[] = [];
|
|
1689
|
+
for (const plan of contracts) {
|
|
1690
|
+
for (const kind of ['storage', 'profile', 'execution'] as const) {
|
|
1691
|
+
const from = plan.oldHashes[kind];
|
|
1692
|
+
const to = plan.newHashes[kind];
|
|
1693
|
+
if (from === undefined || to === undefined) continue;
|
|
1694
|
+
if (!isEmittedByThisRelease(plan, kind)) hashes.add(kind, from, to, stops);
|
|
1695
|
+
else if (kind === 'storage') emittedFirst.push({ plan, from, to });
|
|
1696
|
+
}
|
|
1697
|
+
const to = plan.newHashes.storage;
|
|
1698
|
+
if (plan.keptStorageHash === undefined || to === undefined) continue;
|
|
1699
|
+
hashes.add('storage', plan.keptStorageHash, to, stops);
|
|
1700
|
+
kept.push(`${shown(plan.file.path)} (${plan.keptStorageHash} -> ${to})`);
|
|
1701
|
+
}
|
|
1702
|
+
const emitted: string[] = [];
|
|
1703
|
+
for (const { plan, from, to } of emittedFirst) {
|
|
1704
|
+
const known = hashes.all.get(from);
|
|
1705
|
+
const databases = known ?? plan.earlierReleaseStorageHash;
|
|
1706
|
+
if (known === undefined) hashes.add('storage', from, databases, stops);
|
|
1707
|
+
hashes.newValues.add(to);
|
|
1708
|
+
if (databases !== to)
|
|
1709
|
+
emitted.push(`${shown(plan.file.path)} (${to}; without the value, ${databases})`);
|
|
1710
|
+
}
|
|
1711
|
+
if (stops.length > 0) return refuse(stops);
|
|
1712
|
+
|
|
1713
|
+
const plan: Plan = {
|
|
1714
|
+
writes: new Map(),
|
|
1715
|
+
renames: [],
|
|
1716
|
+
removals: [],
|
|
1717
|
+
notes: checks.notes,
|
|
1718
|
+
kept,
|
|
1719
|
+
emitted,
|
|
1720
|
+
merged: [],
|
|
1721
|
+
superseded: [],
|
|
1722
|
+
renamedCapabilities: [],
|
|
1723
|
+
problems: checks.left,
|
|
1724
|
+
};
|
|
1725
|
+
const alreadyNew = unknownHashesAlreadyNew(files.migrations, hashes);
|
|
1726
|
+
const newValueOf = (hash: string) =>
|
|
1727
|
+
hashes.resolve(hash) ?? (alreadyNew.has(hash) ? hash : undefined);
|
|
1728
|
+
planMigrations(files, hashes, newValueOf, plan, stops, shown);
|
|
1729
|
+
planRefs(files, newValueOf, plan, shown);
|
|
1730
|
+
planContracts(contracts, plan, stops, shown);
|
|
1731
|
+
if (stops.length > 0) return refuse(stops);
|
|
1732
|
+
for (const path of files.migrationTs) {
|
|
1733
|
+
const { text } = readText(path);
|
|
1734
|
+
const next = replaceTokens(text, hashes.byKind.storage);
|
|
1735
|
+
if (next !== text) plan.writes.set(path, next);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
const written: string[] = [];
|
|
1739
|
+
try {
|
|
1740
|
+
for (const path of files.leftovers) rmSync(path, { recursive: true, force: true });
|
|
1741
|
+
for (const [path, text] of plan.writes) {
|
|
1742
|
+
const current = readText(path);
|
|
1743
|
+
if (current.text === text) continue;
|
|
1744
|
+
replaceFile(path, current.bom + text);
|
|
1745
|
+
written.push(path);
|
|
1746
|
+
}
|
|
1747
|
+
for (const dir of plan.removals) {
|
|
1748
|
+
const removed = join(dirname(dir), `.${basename(dir)}${REMOVED_SUFFIX}`);
|
|
1749
|
+
renameSync(dir, removed);
|
|
1750
|
+
rmSync(removed, { recursive: true, force: true });
|
|
1751
|
+
}
|
|
1752
|
+
for (const [from, to] of plan.renames) renameSync(from, to);
|
|
1753
|
+
} catch (error) {
|
|
1754
|
+
process.stderr.write(
|
|
1755
|
+
`${errorText(error)}; the upgrade stopped partway. Run the script again to finish it\n`,
|
|
1756
|
+
);
|
|
1757
|
+
return 1;
|
|
1758
|
+
}
|
|
1759
|
+
report(
|
|
1760
|
+
written.map((path) => shown(renamedPath(path, plan.renames))),
|
|
1761
|
+
plan,
|
|
1762
|
+
hashes,
|
|
1763
|
+
shown,
|
|
1764
|
+
);
|
|
1765
|
+
if (plan.problems.length === 0) return 0;
|
|
1766
|
+
process.stderr.write(`Left unchanged:\n${plan.problems.map((line) => ` ${line}\n`).join('')}`);
|
|
1767
|
+
return 1;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
/** Writes the new text beside the file and renames it over the file, so a run that stops leaves each file either as it was or as it should be. */
|
|
1771
|
+
function replaceFile(path: string, text: string): void {
|
|
1772
|
+
const temporary = `${path}${TEMPORARY_SUFFIX}`;
|
|
1773
|
+
writeFileSync(temporary, text);
|
|
1774
|
+
chmodSync(temporary, statSync(path).mode & 0o7777);
|
|
1775
|
+
renameSync(temporary, path);
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
function refuse(stops: readonly string[]): number {
|
|
1779
|
+
process.stderr.write(
|
|
1780
|
+
`Changed no file, because:\n${[...new Set(stops)].map((line) => ` ${line}\n`).join('')}`,
|
|
1781
|
+
);
|
|
1782
|
+
return 1;
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
/**
|
|
1786
|
+
* Plans each migration's new `from`, `to`, `ops.json` and `migrationHash`. The script writes a `migration.json` before the `ops.json` beside it, so a run that stopped between the two leaves a `migrationHash` that covers the new `ops.json`; such a migration is finished, not refused.
|
|
1787
|
+
*/
|
|
1788
|
+
function planMigrations(
|
|
1789
|
+
files: ProjectFiles,
|
|
1790
|
+
hashes: HashMap,
|
|
1791
|
+
newValueOf: (hash: string) => string | undefined,
|
|
1792
|
+
plan: Plan,
|
|
1793
|
+
stops: string[],
|
|
1794
|
+
shown: (path: string) => string,
|
|
1795
|
+
): void {
|
|
1796
|
+
for (const file of files.migrations) {
|
|
1797
|
+
const { value, text } = file;
|
|
1798
|
+
const opsPath = join(dirname(file.path), 'ops.json');
|
|
1799
|
+
let opsText: string;
|
|
1800
|
+
let ops: Json;
|
|
1801
|
+
try {
|
|
1802
|
+
opsText = readText(opsPath).text;
|
|
1803
|
+
ops = JSON.parse(opsText);
|
|
1804
|
+
} catch (error) {
|
|
1805
|
+
stops.push(`${shown(opsPath)}: cannot be read as JSON (${errorText(error)})`);
|
|
1806
|
+
continue;
|
|
1807
|
+
}
|
|
1808
|
+
const stored = value['migrationHash'];
|
|
1809
|
+
const nextOpsText = replaceQuoted(opsText, hashes.byKind.storage);
|
|
1810
|
+
const opsLeftBehind =
|
|
1811
|
+
nextOpsText !== opsText && stored === computeMigrationHash(value, JSON.parse(nextOpsText));
|
|
1812
|
+
if (stored !== computeMigrationHash(value, ops) && !opsLeftBehind) {
|
|
1813
|
+
stops.push(
|
|
1814
|
+
`${shown(file.path)}: its "migrationHash" is not the hash of the migration; it was edited by hand. Restore it from version control, or plan the migration again, and run the script again`,
|
|
1815
|
+
);
|
|
1816
|
+
continue;
|
|
1817
|
+
}
|
|
1818
|
+
const next: JsonRecord = { ...value };
|
|
1819
|
+
const unknown: string[] = [];
|
|
1820
|
+
for (const field of ['from', 'to'] as const) {
|
|
1821
|
+
const hash = value[field];
|
|
1822
|
+
if (typeof hash !== 'string' || !HASH.test(hash)) continue;
|
|
1823
|
+
const resolved = newValueOf(hash);
|
|
1824
|
+
if (resolved === undefined) unknown.push(`its "${field}", ${hash}`);
|
|
1825
|
+
else next[field] = resolved;
|
|
1826
|
+
}
|
|
1827
|
+
if (unknown.length > 0) {
|
|
1828
|
+
plan.problems.push(
|
|
1829
|
+
`${shown(file.path)}: ${unknown.join(' and ')}, ${UNKNOWN_HASH} If the migration is in an extension's folder, migrations/<extension>/, Prisma copied it from the extension: delete its folder, and \`prisma contract emit\` writes it again from the upgraded extension. Otherwise restore the snapshot from version control and run the script again`,
|
|
1830
|
+
);
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1833
|
+
if (next['from'] === value['from'] && next['to'] === value['to'] && nextOpsText === opsText)
|
|
1834
|
+
continue;
|
|
1835
|
+
const nextOps: Json = JSON.parse(nextOpsText);
|
|
1836
|
+
const migrationHash = computeMigrationHash(next, nextOps);
|
|
1837
|
+
next['migrationHash'] = migrationHash;
|
|
1838
|
+
const replacements = new Map<string, string>();
|
|
1839
|
+
for (const field of ['from', 'to', 'migrationHash'] as const) {
|
|
1840
|
+
const from = value[field];
|
|
1841
|
+
const to = next[field];
|
|
1842
|
+
if (typeof from === 'string' && typeof to === 'string' && from !== to)
|
|
1843
|
+
replacements.set(from, to);
|
|
1844
|
+
}
|
|
1845
|
+
const rewritten = replaceQuoted(text, replacements);
|
|
1846
|
+
if (canonicalizeJson(JSON.parse(rewritten)) !== canonicalizeJson(next)) {
|
|
1847
|
+
plan.problems.push(
|
|
1848
|
+
`${shown(file.path)}: could not be rewritten without changing other content; set "from", "to" and "migrationHash" by hand to ${JSON.stringify(next['from'])}, ${JSON.stringify(next['to'])} and "${migrationHash}"`,
|
|
1849
|
+
);
|
|
1850
|
+
continue;
|
|
1851
|
+
}
|
|
1852
|
+
plan.writes.set(file.path, rewritten);
|
|
1853
|
+
if (nextOpsText !== opsText) plan.writes.set(opsPath, nextOpsText);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
function planRefs(
|
|
1858
|
+
files: ProjectFiles,
|
|
1859
|
+
newValueOf: (hash: string) => string | undefined,
|
|
1860
|
+
plan: Plan,
|
|
1861
|
+
shown: (path: string) => string,
|
|
1862
|
+
): void {
|
|
1863
|
+
for (const file of files.refs) {
|
|
1864
|
+
const hash = file.value['hash'];
|
|
1865
|
+
if (typeof hash !== 'string' || !HASH.test(hash)) continue;
|
|
1866
|
+
const resolved = newValueOf(hash);
|
|
1867
|
+
if (resolved === undefined) {
|
|
1868
|
+
plan.problems.push(
|
|
1869
|
+
`${shown(file.path)}: its "hash", ${hash}, ${UNKNOWN_HASH} If the ref is migrations/<extension>/refs/head.json, \`prisma contract emit\` writes it again from the upgraded extension. Otherwise set the ref again with \`prisma migration ref set\` after the upgrade`,
|
|
1870
|
+
);
|
|
1871
|
+
continue;
|
|
1872
|
+
}
|
|
1873
|
+
if (resolved !== hash)
|
|
1874
|
+
plan.writes.set(file.path, replaceQuoted(file.text, new Map([[hash, resolved]])));
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
function planContracts(
|
|
1879
|
+
contracts: readonly ContractPlan[],
|
|
1880
|
+
plan: Plan,
|
|
1881
|
+
stops: string[],
|
|
1882
|
+
shown: (path: string) => string,
|
|
1883
|
+
): void {
|
|
1884
|
+
const targets = new Map<string, string>();
|
|
1885
|
+
const storageHashByPath = new Map(
|
|
1886
|
+
contracts.map((contract) => [contract.file.path, contract.newHashes.storage]),
|
|
1887
|
+
);
|
|
1888
|
+
for (const contract of contracts) {
|
|
1889
|
+
const path = contract.file.path;
|
|
1890
|
+
const text = rewrittenContract(contract);
|
|
1891
|
+
if (text === undefined) {
|
|
1892
|
+
const problem = `${shown(path)}: could not be rewritten without changing other content; ${contract.sections.rewritesCapabilities ? `replace its capabilities by "requiredCapabilities": ${JSON.stringify(contract.sections.requiredCapabilities)}, and ` : ''}set its storage, profile and execution hashes by hand to ${[contract.newHashes.storage, contract.newHashes.profile, contract.newHashes.execution].filter((hash) => hash !== undefined).join(', ')}`;
|
|
1893
|
+
const renamesSnapshot =
|
|
1894
|
+
contract.snapshotHash !== undefined &&
|
|
1895
|
+
contract.newHashes.storage !== undefined &&
|
|
1896
|
+
contract.snapshotHash !== contract.newHashes.storage;
|
|
1897
|
+
// Migrations and refs would be given the new hash of a snapshot directory that keeps its old name.
|
|
1898
|
+
if (renamesSnapshot) stops.push(problem);
|
|
1899
|
+
else plan.problems.push(problem);
|
|
1900
|
+
continue;
|
|
1901
|
+
}
|
|
1902
|
+
// The declaration is written first: until the contract is rewritten, a run that stops between the two can still read the old hashes from it.
|
|
1903
|
+
const dtsPath = dtsPathOf(path);
|
|
1904
|
+
let dtsText: string | undefined;
|
|
1905
|
+
if (existsSync(dtsPath)) {
|
|
1906
|
+
const dts = rewrittenDts(readText(dtsPath).text, contract);
|
|
1907
|
+
if (typeof dts === 'string') {
|
|
1908
|
+
plan.writes.set(dtsPath, dts);
|
|
1909
|
+
dtsText = dts;
|
|
1910
|
+
} else {
|
|
1911
|
+
plan.problems.push(`${shown(dtsPath)}: ${dts.problem}`);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
plan.writes.set(path, text);
|
|
1915
|
+
if (contract.sections.rewritesCapabilities) plan.renamedCapabilities.push(path);
|
|
1916
|
+
const from = contract.snapshotHash;
|
|
1917
|
+
const to = contract.newHashes.storage;
|
|
1918
|
+
if (from === undefined || to === undefined || from === to) continue;
|
|
1919
|
+
const oldDir = dirname(path);
|
|
1920
|
+
const newDir = join(dirname(oldDir), to);
|
|
1921
|
+
const content = snapshotContent(oldDir, text, dtsText);
|
|
1922
|
+
const planned = targets.get(newDir);
|
|
1923
|
+
if (planned !== undefined || existsSync(newDir)) {
|
|
1924
|
+
const existing = planned ?? snapshotContent(newDir, undefined, undefined);
|
|
1925
|
+
if (existing !== content) {
|
|
1926
|
+
const existingHash = storageHashByPath.get(join(newDir, 'contract.json'));
|
|
1927
|
+
if (planned === undefined && existingHash === to) {
|
|
1928
|
+
plan.writes.delete(path);
|
|
1929
|
+
plan.writes.delete(join(oldDir, 'contract.d.ts'));
|
|
1930
|
+
plan.removals.push(oldDir);
|
|
1931
|
+
plan.superseded.push(`${shown(oldDir)} (kept ${shown(newDir)}/)`);
|
|
1932
|
+
continue;
|
|
1933
|
+
}
|
|
1934
|
+
stops.push(
|
|
1935
|
+
`${shown(oldDir)}: becomes snapshots/${to}/, which already exists with other content. Compare the two directories, keep the right one, and run the script again`,
|
|
1936
|
+
);
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
plan.writes.delete(path);
|
|
1940
|
+
plan.writes.delete(join(oldDir, 'contract.d.ts'));
|
|
1941
|
+
plan.removals.push(oldDir);
|
|
1942
|
+
plan.merged.push(`${shown(oldDir)}, the same as snapshots/${to}/`);
|
|
1943
|
+
continue;
|
|
1944
|
+
}
|
|
1945
|
+
targets.set(newDir, content);
|
|
1946
|
+
plan.renames.push([oldDir, newDir]);
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
/** The files of a snapshot directory, with `contract.json` and `contract.d.ts` as they will be written, for comparing two directories. */
|
|
1951
|
+
function snapshotContent(
|
|
1952
|
+
dir: string,
|
|
1953
|
+
contractJson: string | undefined,
|
|
1954
|
+
dts: string | undefined,
|
|
1955
|
+
): string {
|
|
1956
|
+
const entries = listDirectory(dir);
|
|
1957
|
+
if (typeof entries === 'string') return '';
|
|
1958
|
+
const files = entries
|
|
1959
|
+
.filter((entry) => entry.isFile() && !entry.name.endsWith(TEMPORARY_SUFFIX))
|
|
1960
|
+
.map((entry) => {
|
|
1961
|
+
const path = join(dir, entry.name);
|
|
1962
|
+
const text =
|
|
1963
|
+
entry.name === 'contract.json' && contractJson !== undefined
|
|
1964
|
+
? contractJson
|
|
1965
|
+
: entry.name === 'contract.d.ts' && dts !== undefined
|
|
1966
|
+
? dts
|
|
1967
|
+
: readText(path).text;
|
|
1968
|
+
return [entry.name, text];
|
|
1969
|
+
});
|
|
1970
|
+
return JSON.stringify(files);
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
/** Where `path` is after its snapshot directory was renamed. */
|
|
1974
|
+
function renamedPath(path: string, renames: readonly [string, string][]): string {
|
|
1975
|
+
for (const [from, to] of renames) if (isInside(from, path)) return to + path.slice(from.length);
|
|
1976
|
+
return path;
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
function report(
|
|
1980
|
+
written: readonly string[],
|
|
1981
|
+
plan: Plan,
|
|
1982
|
+
hashes: HashMap,
|
|
1983
|
+
shown: (path: string) => string,
|
|
1984
|
+
): void {
|
|
1985
|
+
const lines: string[] = [];
|
|
1986
|
+
if (written.length === 0 && plan.renames.length === 0 && plan.removals.length === 0) {
|
|
1987
|
+
lines.push(
|
|
1988
|
+
plan.problems.length === 0
|
|
1989
|
+
? 'Every stored hash already has the value this release computes; nothing changed.'
|
|
1990
|
+
: 'Changed no file.',
|
|
1991
|
+
);
|
|
1992
|
+
} else {
|
|
1993
|
+
lines.push(`Rewrote ${written.length} ${written.length === 1 ? 'file' : 'files'}:`);
|
|
1994
|
+
lines.push(...[...written].sort(compareCodeUnits).map((path) => ` ${path}`));
|
|
1995
|
+
if (plan.renames.length > 0) {
|
|
1996
|
+
lines.push('Renamed snapshot directories:');
|
|
1997
|
+
lines.push(...plan.renames.map(([from, to]) => ` ${shown(from)} -> ${basename(to)}`));
|
|
1998
|
+
}
|
|
1999
|
+
for (const kind of ['storage', 'profile', 'execution'] as const) {
|
|
2000
|
+
const changed =
|
|
2001
|
+
kind === 'profile'
|
|
2002
|
+
? [...hashes.profiles]
|
|
2003
|
+
: [...hashes.byKind[kind]].map(([from, to]) => `${from} -> ${to}`);
|
|
2004
|
+
if (changed.length === 0) continue;
|
|
2005
|
+
lines.push(
|
|
2006
|
+
`${KIND_LABEL[kind][0]?.toUpperCase()}${KIND_LABEL[kind].slice(1)}es (old -> new):`,
|
|
2007
|
+
);
|
|
2008
|
+
lines.push(...changed.sort(compareCodeUnits).map((pair) => ` ${pair}`));
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
if (plan.kept.length > 0)
|
|
2012
|
+
lines.push(
|
|
2013
|
+
'MongoDB snapshots whose content an earlier upgrade step rewrote without changing their storage hash. They now have the storage hash their content gives, and so does every file that names them:',
|
|
2014
|
+
...plan.kept.map((note) => ` ${note}`),
|
|
2015
|
+
);
|
|
2016
|
+
if (plan.emitted.length > 0)
|
|
2017
|
+
lines.push(
|
|
2018
|
+
'Contracts `prisma contract emit` already wrote with this release, left as they are. The contract source holds a value the earlier release left out of `contract.json`, so the databases were built without it. Each line gives the emitted storage hash, then the new storage hash of the contract without the value, which every migration, ref and snapshot that named the old hash now names. The upgrade instructions say what to do, under "When the emitted contract gets a different storage hash":',
|
|
2019
|
+
...plan.emitted.map((note) => ` ${note}`),
|
|
2020
|
+
);
|
|
2021
|
+
if (plan.notes.length > 0)
|
|
2022
|
+
lines.push(
|
|
2023
|
+
"Snapshots whose profile or execution hash an earlier release wrote by other rules, which no version of the files corrects. They now have the hashes their content gives, so `prisma db sign <contract reference>`, which copies a snapshot's profile hash into the database's contract signature, copies the right one:",
|
|
2024
|
+
...plan.notes.map((note) => ` ${note}`),
|
|
2025
|
+
);
|
|
2026
|
+
if (plan.merged.length > 0)
|
|
2027
|
+
lines.push(
|
|
2028
|
+
'Snapshot directories that held the same contract as another one, and were removed:',
|
|
2029
|
+
...plan.merged.map((note) => ` ${note}`),
|
|
2030
|
+
);
|
|
2031
|
+
const renamed = plan.renamedCapabilities
|
|
2032
|
+
.filter((path) => plan.writes.has(path))
|
|
2033
|
+
.map((path) => shown(renamedPath(path, plan.renames)))
|
|
2034
|
+
.sort(compareCodeUnits);
|
|
2035
|
+
if (renamed.length > 0)
|
|
2036
|
+
lines.push(
|
|
2037
|
+
'Contracts whose capabilities became "requiredCapabilities", a sorted list of keys, each prefixed by who provides it: `db.` for the database, `conn.` for the connection. A contract no longer lists the capabilities nothing reads:',
|
|
2038
|
+
...renamed.map((path) => ` ${path}`),
|
|
2039
|
+
);
|
|
2040
|
+
if (plan.superseded.length > 0)
|
|
2041
|
+
lines.push(
|
|
2042
|
+
'Snapshot directories whose new name already held a snapshot with the same storage hash, which `prisma contract emit` wrote with this release. The script kept that snapshot unchanged and removed the old directory:',
|
|
2043
|
+
...plan.superseded.map((note) => ` ${note}`),
|
|
2044
|
+
);
|
|
2045
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
process.exitCode = main(process.argv.slice(2));
|