@inventarch/distribution 3.5.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/SPEC.md +2 -2
  2. package/dist/adoption.d.ts +2 -0
  3. package/dist/adoption.d.ts.map +1 -1
  4. package/dist/adoption.js +13 -0
  5. package/dist/adoption.js.map +1 -1
  6. package/dist/bootstrap.d.ts +15 -2
  7. package/dist/bootstrap.d.ts.map +1 -1
  8. package/dist/bootstrap.js +55 -12
  9. package/dist/bootstrap.js.map +1 -1
  10. package/dist/home-lock.d.ts +67 -0
  11. package/dist/home-lock.d.ts.map +1 -0
  12. package/dist/home-lock.js +281 -0
  13. package/dist/home-lock.js.map +1 -0
  14. package/dist/install.d.ts +17 -0
  15. package/dist/install.d.ts.map +1 -1
  16. package/dist/install.js +65 -0
  17. package/dist/install.js.map +1 -1
  18. package/dist/kit-collections.d.ts +182 -0
  19. package/dist/kit-collections.d.ts.map +1 -0
  20. package/dist/kit-collections.js +457 -0
  21. package/dist/kit-collections.js.map +1 -0
  22. package/dist/kit-inventory.d.ts +36 -0
  23. package/dist/kit-inventory.d.ts.map +1 -0
  24. package/dist/kit-inventory.js +69 -0
  25. package/dist/kit-inventory.js.map +1 -0
  26. package/dist/native-command.d.ts +1 -1
  27. package/dist/native-command.d.ts.map +1 -1
  28. package/dist/native-command.js +45 -16
  29. package/dist/native-command.js.map +1 -1
  30. package/dist/registry-resolve.d.ts +32 -0
  31. package/dist/registry-resolve.d.ts.map +1 -1
  32. package/dist/registry-resolve.js +113 -5
  33. package/dist/registry-resolve.js.map +1 -1
  34. package/dist/registry.d.ts +2 -2
  35. package/dist/registry.d.ts.map +1 -1
  36. package/dist/registry.js +2 -2
  37. package/dist/registry.js.map +1 -1
  38. package/dist/updates.d.ts +76 -4
  39. package/dist/updates.d.ts.map +1 -1
  40. package/dist/updates.js +185 -20
  41. package/dist/updates.js.map +1 -1
  42. package/package.json +31 -7
  43. package/references/registry-collections.md +13 -1
@@ -0,0 +1,182 @@
1
+ import type { DistributionLock } from '@inventarch/db/distribution';
2
+ export declare const KIT_COLLECTIONS = ".ia/kit-collections.json";
3
+ export declare const KIT_COLLECTIONS_JOURNAL = ".ia/distributions/kit-collections.journal.json";
4
+ export declare const KIT_COLLECTIONS_FORMAT = "ia-kit-collections-1";
5
+ export interface CollectionMember {
6
+ readonly id: string;
7
+ readonly version: string;
8
+ readonly archive: string;
9
+ }
10
+ export interface CollectionRow {
11
+ readonly id: string;
12
+ readonly version: string;
13
+ /** The registry the collection index was read from: an HTTPS URL or a directory (`registryLocation`). */
14
+ readonly registry: string;
15
+ readonly members: readonly CollectionMember[];
16
+ }
17
+ /** A collection whose identity could not be established after an interrupted change: its id and both sides' members. */
18
+ export interface UnknownCollection {
19
+ readonly id: string;
20
+ readonly members: readonly string[];
21
+ }
22
+ export interface KitCollections {
23
+ readonly format: typeof KIT_COLLECTIONS_FORMAT;
24
+ /** The sha256 of the portable lock bytes this record describes. */
25
+ readonly lock: string;
26
+ readonly collections: readonly CollectionRow[];
27
+ readonly unknown: readonly UnknownCollection[];
28
+ /**
29
+ * The lock requests the user named directly that a recorded collection also lists. The lock cannot say who asked for
30
+ * a request, so this is where it is kept: a later install compares such a request as a string and never narrows it
31
+ * to a range a collection shares. Absent or empty, the key is not written.
32
+ */
33
+ readonly named?: readonly string[];
34
+ }
35
+ /** One collection an operation expanded: `registry-resolve`'s `expandedCollections`. Members are ids, not pins. */
36
+ export interface ExpandedCollection {
37
+ readonly id: string;
38
+ readonly version: string;
39
+ readonly registry: string;
40
+ readonly members: readonly string[];
41
+ }
42
+ export interface CollectionsJournal {
43
+ readonly formatVersion: 1;
44
+ /** The exact activation pointer bytes before the operation, or null when nothing was active. */
45
+ readonly beforeActive: string | null;
46
+ /** The exact activation pointer bytes the operation commits. */
47
+ readonly afterActive: string;
48
+ /** The record's bytes before, or null when there was none. */
49
+ readonly before: string | null;
50
+ /** The record's bytes after, or null when the operation leaves none. */
51
+ readonly after: string | null;
52
+ }
53
+ /** The record in `text`; a malformed one refuses (INPUT-INVALID), and so does another format (`unknownFormat`). */
54
+ export declare function decodeKitCollections(input: string): KitCollections;
55
+ /** The committed bytes: keys in one order, rows and members sorted by id, two-space indent, one trailing newline. */
56
+ export declare function serializeKitCollections(record: KitCollections): string;
57
+ export type RecordRead = {
58
+ readonly state: 'absent';
59
+ } | {
60
+ readonly state: 'present';
61
+ readonly record: KitCollections;
62
+ readonly bytes: string;
63
+ } | {
64
+ readonly state: 'invalid';
65
+ readonly problem: string;
66
+ };
67
+ /** The record file as it is on disk. Never throws: a malformed or foreign record is `invalid` with the reason. */
68
+ export declare function readKitCollections(rootInput: string): RecordRead;
69
+ export type JournalRead = {
70
+ readonly state: 'absent';
71
+ } | {
72
+ readonly state: 'present';
73
+ readonly journal: CollectionsJournal;
74
+ } | {
75
+ readonly state: 'invalid';
76
+ readonly problem: string;
77
+ };
78
+ export declare function readCollectionsJournal(root: string): JournalRead;
79
+ export declare const journalKitCollections: (root: string, journal: CollectionsJournal) => void;
80
+ export declare const removeCollectionsJournal: (root: string) => void;
81
+ declare const writeRecord: (root: string, content: string | null) => void;
82
+ /**
83
+ * The record a journal leaves when the activation pointer is neither side's: the collections both sides agree on byte
84
+ * for byte, and every other collection unknown, with the member ids either side recorded. `lock` is the side whose
85
+ * lock the workspace now holds, so the agreed collections still count.
86
+ */
87
+ export declare function undecidedRecord(journal: CollectionsJournal, currentLock: string | null): KitCollections | null;
88
+ export interface CurrentCollections {
89
+ /** The record that counts, or null: none, unreadable, or an interrupted operation. */
90
+ readonly record: KitCollections | null;
91
+ /**
92
+ * Where it came from: the file, a journal's side, a journal undecided between them, nothing, or, when the
93
+ * installation state kept changing while it was read, a record of unknown identities (`unstable`).
94
+ */
95
+ readonly source: 'none' | 'file' | 'before' | 'after' | 'undecided' | 'interrupted' | 'unstable';
96
+ readonly problems: readonly string[];
97
+ }
98
+ /**
99
+ * Test seams: `afterJournal` runs between reading the journal and reading the record it decides on, `afterRecord` after
100
+ * the record file is read, and `stat` stands in for the file identity the probes read (a volume that reports no
101
+ * inode, or timestamps too coarse to move).
102
+ */
103
+ export interface CollectionReadHooks {
104
+ readonly afterJournal?: () => void;
105
+ readonly afterRecord?: () => void;
106
+ readonly stat?: (path: string) => FileIdentity | undefined;
107
+ }
108
+ export interface FileIdentity {
109
+ readonly ino: bigint;
110
+ readonly mtimeNs: bigint;
111
+ readonly size: bigint;
112
+ }
113
+ /**
114
+ * Which record counts, read only:
115
+ * 1. a journal beside `pending.json`: an operation was interrupted and is not recovered, so no identity counts;
116
+ * 2. a journal without `pending.json`: its `after` while the activation pointer is exactly `afterActive`, its `before`
117
+ * while exactly `beforeActive`, and otherwise the collections both sides agree on, the rest unknown;
118
+ * 3. no journal: the record file.
119
+ */
120
+ export declare function currentCollections(rootInput: string, hooks?: CollectionReadHooks): CurrentCollections;
121
+ export interface IntactCollections {
122
+ /** The collections whose every recorded member is the lock's exact pin. */
123
+ readonly collections: readonly CollectionRow[];
124
+ /** Collections whose identity is unknown, with the member ids still in the lock. */
125
+ readonly unknown: readonly UnknownCollection[];
126
+ /** The record's direct requests (`KitCollections.named`) that are still lock requests. */
127
+ readonly named: readonly string[];
128
+ readonly problems: readonly string[];
129
+ }
130
+ /**
131
+ * The collections that count against `lock`, the portable lock now on disk: none unless the chosen record names those
132
+ * exact bytes (their sha256, `lockSha`), and within it only a collection whose every member equals the lock's row of that id.
133
+ */
134
+ export declare function intactAgainst(current: CurrentCollections, lock: DistributionLock | null, lockSha: string | null): IntactCollections;
135
+ /**
136
+ * Builds the rows an operation expanded from the resolved plan lock: each member id joined to the lock's `packages`
137
+ * row of that id, for its exact version and archive. A member the lock lacks is a defect, refused before anything
138
+ * commits.
139
+ */
140
+ export declare function expandedRows(expanded: readonly ExpandedCollection[], lock: DistributionLock): CollectionRow[];
141
+ /**
142
+ * The record after an operation, pure:
143
+ * 1. `current` is the record that counted before it, already matched against the lock before the operation (null
144
+ * otherwise);
145
+ * 2. every row of a collection this operation expanded is dropped, to be rewritten;
146
+ * 3. every other row is kept only while all its recorded members are `afterLock`'s exact pins; a row with any member
147
+ * removed, re-pinned or re-archived is removed whole, so its other members can never make it intact again;
148
+ * 4. the expanded rows are added, built from `afterLock`.
149
+ * An unknown entry is kept until its collection is installed again or none of its members is left in the lock.
150
+ * `named` adds the requests this operation counts as named by the user; with the record's own, each is kept while it is
151
+ * still an `afterLock` request that a row or unknown entry of the result lists.
152
+ */
153
+ export declare function mergeKitCollections(current: KitCollections | null, expanded: readonly ExpandedCollection[], afterLock: DistributionLock, afterLockBytes: string, named?: readonly string[]): KitCollections;
154
+ /** Whether a record carries nothing worth committing: an empty record is never written, and a record left empty is removed. */
155
+ export declare const emptyRecord: (record: KitCollections) => boolean;
156
+ /**
157
+ * Settles a journal no `pending.json` stands beside (an older CLI recovered the operation without reading it), under the
158
+ * installation lock: the record is written as the side the activation pointer exactly names, or, when it names
159
+ * neither, as the collections both sides agree on with the rest unknown; the journal is then removed. Returns whether
160
+ * a journal was settled.
161
+ */
162
+ export declare function settleOrphanJournal(root: string): boolean;
163
+ /** Recovery's side of the journal: the record as the operation left it when it committed, as before when it did not. */
164
+ export declare function settleKitCollections(root: string, committed: boolean): void;
165
+ export { writeRecord as writeKitCollections };
166
+ /**
167
+ * `currentCollections` matched against the portable lock now on disk. Never throws: a lock that cannot be read leaves
168
+ * no collection intact, with the reason.
169
+ */
170
+ export declare function intactCollections(rootInput: string, hooks?: CollectionReadHooks): IntactCollections;
171
+ /**
172
+ * The record that counts and the lock bytes it is judged against, read between two probes of the installation state:
173
+ * a reader never sees a record from before an operation began beside a pointer from after (or the reverse), because
174
+ * another process changing the files in between makes the probes differ. The read is tried once more, and when the
175
+ * state changes again it fails closed: every collection the record or journal names is reported with an unknown
176
+ * identity, never as intact.
177
+ */
178
+ export declare function stableCollections(rootInput: string, hooks?: CollectionReadHooks): {
179
+ readonly current: CurrentCollections;
180
+ readonly lock: Buffer | null;
181
+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EAAE,OAAO,GAAG,IAAI,CAK3E;AACD,OAAO,EAAE,WAAW,IAAI,mBAAmB,EAAE,CAAC;AAE9C;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,GAAE,mBAAwB,GAAG,iBAAiB,CAWvG;AA+BD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,EACjB,KAAK,GAAE,mBAAwB,GAC9B;IAAE,QAAQ,CAAC,OAAO,EAAE,kBAAkB,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAUxE"}
@@ -0,0 +1,457 @@
1
+ /**
2
+ * The identity of a registry collection install, kept beside the lock: apps/distribution/references/registry-collections.md
3
+ * "Collection record".
4
+ *
5
+ * `ia install <collection>` expands a registry `kit` collection into its member distributions, and the lock records
6
+ * only the members. The lock is not changed to remember the collection: a new entry kind would make every older CLI
7
+ * refuse the repository. So `.ia/kit-collections.json`, committed with the lock, names the lock bytes it describes and
8
+ * each collection's id, version, registry and exact member pins.
9
+ *
10
+ * While an installation changes it, a journal in the local install state binds the change to the activation it belongs
11
+ * to (`beforeActive`, `afterActive`), so an interrupted operation is never read as the collection version it was
12
+ * installing. The reader fails closed: when it cannot tell which side counts, the collection's identity is unknown and
13
+ * its members are inventoried as plain releases, never under a guessed source.
14
+ */
15
+ import { decodeDistributionJson, decodeDistributionLock, DISTRIBUTION_LIMITS, INSTALL_PATHS, packageId, } from '@inventarch/db/distribution';
16
+ import { lstatSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { bytes, fail, replace, sha256, utf8, workspace } from './files.js';
19
+ export const KIT_COLLECTIONS = '.ia/kit-collections.json';
20
+ export const KIT_COLLECTIONS_JOURNAL = '.ia/distributions/kit-collections.journal.json';
21
+ export const KIT_COLLECTIONS_FORMAT = 'ia-kit-collections-1';
22
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
23
+ const text = (value) => typeof value === 'string' && value !== '';
24
+ /**
25
+ * A distribution id (`provider/name`, the lock's own rule). The record is committed, and its ids reach the argument
26
+ * vectors doctor offers as fixes, so an id such as `--root=/other` must never decode.
27
+ */
28
+ const distributionId = (value) => {
29
+ try {
30
+ packageId(value);
31
+ return true;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ };
37
+ const HEX = /^[a-f0-9]{64}$/;
38
+ const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
39
+ function decodeMember(value) {
40
+ if (!isRecord(value) ||
41
+ !distributionId(value['id']) ||
42
+ !text(value['version']) ||
43
+ !HEX.test(String(value['archive'])))
44
+ fail('INPUT-INVALID', 'A collection member needs its id, version and archive digest');
45
+ return { id: value['id'], version: value['version'], archive: value['archive'] };
46
+ }
47
+ /** The record in `text`; a malformed one refuses (INPUT-INVALID), and so does another format (`unknownFormat`). */
48
+ export function decodeKitCollections(input) {
49
+ let value;
50
+ try {
51
+ value = JSON.parse(input);
52
+ }
53
+ catch {
54
+ return fail('INPUT-INVALID', `${KIT_COLLECTIONS} is not valid JSON`);
55
+ }
56
+ if (!isRecord(value))
57
+ return fail('INPUT-INVALID', `${KIT_COLLECTIONS} is not an object`);
58
+ if (value['format'] !== KIT_COLLECTIONS_FORMAT)
59
+ return fail('UNSUPPORTED-FORMAT', `${KIT_COLLECTIONS} has format ${String(value['format'])}`);
60
+ const collections = value['collections'], unknown = value['unknown'] ?? [], named = value['named'] ?? [];
61
+ if (!HEX.test(String(value['lock'])) || !Array.isArray(collections) || !Array.isArray(unknown))
62
+ return fail('INPUT-INVALID', `${KIT_COLLECTIONS} needs a lock digest, collections and unknown`);
63
+ if (!Array.isArray(named) || !named.every(distributionId))
64
+ return fail('INPUT-INVALID', `${KIT_COLLECTIONS} names a direct request that is not a distribution id`);
65
+ return {
66
+ format: KIT_COLLECTIONS_FORMAT,
67
+ lock: value['lock'],
68
+ collections: collections.map((row) => {
69
+ if (!isRecord(row) || !distributionId(row['id']) || !text(row['version']) || !text(row['registry']))
70
+ return fail('INPUT-INVALID', 'A collection needs its id, version and registry');
71
+ if (!Array.isArray(row['members']))
72
+ return fail('INPUT-INVALID', 'A collection needs its members');
73
+ return {
74
+ id: row['id'],
75
+ version: row['version'],
76
+ registry: row['registry'],
77
+ members: row['members'].map(decodeMember),
78
+ };
79
+ }),
80
+ unknown: unknown.map((row) => {
81
+ if (!isRecord(row) ||
82
+ !distributionId(row['id']) ||
83
+ !Array.isArray(row['members']) ||
84
+ !row['members'].every(distributionId))
85
+ return fail('INPUT-INVALID', 'An unknown collection needs its id and member ids');
86
+ return { id: row['id'], members: row['members'] };
87
+ }),
88
+ ...(named.length > 0 ? { named: [...new Set(named)].sort() } : {}),
89
+ };
90
+ }
91
+ /** The committed bytes: keys in one order, rows and members sorted by id, two-space indent, one trailing newline. */
92
+ export function serializeKitCollections(record) {
93
+ const ordered = {
94
+ format: record.format,
95
+ lock: record.lock,
96
+ collections: [...record.collections].sort(byId).map((row) => ({
97
+ id: row.id,
98
+ version: row.version,
99
+ registry: row.registry,
100
+ members: [...row.members].sort(byId).map((member) => ({
101
+ id: member.id,
102
+ version: member.version,
103
+ archive: member.archive,
104
+ })),
105
+ })),
106
+ unknown: [...record.unknown].sort(byId).map((row) => ({ id: row.id, members: [...row.members].sort() })),
107
+ ...(record.named !== undefined && record.named.length > 0 ? { named: [...new Set(record.named)].sort() } : {}),
108
+ };
109
+ return `${JSON.stringify(ordered, null, 2)}\n`;
110
+ }
111
+ /** The record file as it is on disk. Never throws: a malformed or foreign record is `invalid` with the reason. */
112
+ export function readKitCollections(rootInput) {
113
+ try {
114
+ const content = bytes(workspace(rootInput), KIT_COLLECTIONS, DISTRIBUTION_LIMITS.metadata);
115
+ if (content === null)
116
+ return { state: 'absent' };
117
+ const value = utf8(content);
118
+ return { state: 'present', record: decodeKitCollections(value), bytes: value };
119
+ }
120
+ catch (error) {
121
+ return {
122
+ state: 'invalid',
123
+ problem: `${KIT_COLLECTIONS}: ${error instanceof Error ? error.message : String(error)}`,
124
+ };
125
+ }
126
+ }
127
+ function decodeJournal(input) {
128
+ const value = JSON.parse(input);
129
+ const nullable = (key) => {
130
+ const v = isRecord(value) ? value[key] : undefined;
131
+ if (v !== null && typeof v !== 'string')
132
+ fail('INPUT-INVALID', `The collections journal's ${key} is invalid`);
133
+ return v;
134
+ };
135
+ if (!isRecord(value) || value['formatVersion'] !== 1 || typeof value['afterActive'] !== 'string')
136
+ fail('INPUT-INVALID', 'The collections journal is invalid');
137
+ return {
138
+ formatVersion: 1,
139
+ beforeActive: nullable('beforeActive'),
140
+ afterActive: value['afterActive'],
141
+ before: nullable('before'),
142
+ after: nullable('after'),
143
+ };
144
+ }
145
+ export function readCollectionsJournal(root) {
146
+ try {
147
+ const content = bytes(root, KIT_COLLECTIONS_JOURNAL, 4 * DISTRIBUTION_LIMITS.metadata);
148
+ if (content === null)
149
+ return { state: 'absent' };
150
+ return { state: 'present', journal: decodeJournal(utf8(content)) };
151
+ }
152
+ catch (error) {
153
+ return {
154
+ state: 'invalid',
155
+ problem: `${KIT_COLLECTIONS_JOURNAL}: ${error instanceof Error ? error.message : String(error)}`,
156
+ };
157
+ }
158
+ }
159
+ export const journalKitCollections = (root, journal) => replace(root, KIT_COLLECTIONS_JOURNAL, Buffer.from(`${JSON.stringify(journal)}\n`));
160
+ export const removeCollectionsJournal = (root) => replace(root, KIT_COLLECTIONS_JOURNAL, null);
161
+ const writeRecord = (root, content) => replace(root, KIT_COLLECTIONS, content === null ? null : Buffer.from(content));
162
+ const decodeOrNull = (content) => {
163
+ if (content === null)
164
+ return null;
165
+ try {
166
+ return decodeKitCollections(content);
167
+ }
168
+ catch {
169
+ return null;
170
+ }
171
+ };
172
+ const sameRow = (a, b) => serializeKitCollections({ format: KIT_COLLECTIONS_FORMAT, lock: '0'.repeat(64), collections: [a], unknown: [] }) ===
173
+ serializeKitCollections({ format: KIT_COLLECTIONS_FORMAT, lock: '0'.repeat(64), collections: [b], unknown: [] });
174
+ /**
175
+ * The record a journal leaves when the activation pointer is neither side's: the collections both sides agree on byte
176
+ * for byte, and every other collection unknown, with the member ids either side recorded. `lock` is the side whose
177
+ * lock the workspace now holds, so the agreed collections still count.
178
+ */
179
+ export function undecidedRecord(journal, currentLock) {
180
+ const before = decodeOrNull(journal.before), after = decodeOrNull(journal.after);
181
+ if (before === null && after === null)
182
+ return null;
183
+ const sides = [before, after].filter((side) => side !== null);
184
+ const ids = new Set(sides.flatMap((side) => [...side.collections, ...side.unknown].map((row) => row.id)));
185
+ const collections = [], unknown = [];
186
+ for (const id of ids) {
187
+ const rows = [before, after].map((side) => side?.collections.find((row) => row.id === id));
188
+ const agreed = rows[0] !== undefined && rows[1] !== undefined && sameRow(rows[0], rows[1]);
189
+ if (agreed)
190
+ collections.push(rows[0]);
191
+ else
192
+ unknown.push({
193
+ id,
194
+ members: [
195
+ ...new Set(sides.flatMap((side) => [
196
+ ...(side.collections.find((row) => row.id === id)?.members.map((member) => member.id) ?? []),
197
+ ...(side.unknown.find((row) => row.id === id)?.members ?? []),
198
+ ])),
199
+ ],
200
+ });
201
+ }
202
+ const locks = sides.map((side) => side.lock);
203
+ // Either side's direct requests stay direct: one compared as a string refuses where it might have narrowed.
204
+ const named = [...new Set(sides.flatMap((side) => side.named ?? []))].sort();
205
+ return {
206
+ format: KIT_COLLECTIONS_FORMAT,
207
+ lock: currentLock !== null && locks.includes(currentLock) ? currentLock : locks[locks.length - 1],
208
+ collections,
209
+ unknown,
210
+ ...(named.length > 0 ? { named } : {}),
211
+ };
212
+ }
213
+ const activeBytes = (root) => bytes(root, INSTALL_PATHS.active)?.toString('utf8') ?? null;
214
+ const lockDigest = (root) => {
215
+ const content = bytes(root, INSTALL_PATHS.lock, DISTRIBUTION_LIMITS.metadata);
216
+ return content === null ? null : sha256(content);
217
+ };
218
+ /**
219
+ * Which record counts, read only:
220
+ * 1. a journal beside `pending.json`: an operation was interrupted and is not recovered, so no identity counts;
221
+ * 2. a journal without `pending.json`: its `after` while the activation pointer is exactly `afterActive`, its `before`
222
+ * while exactly `beforeActive`, and otherwise the collections both sides agree on, the rest unknown;
223
+ * 3. no journal: the record file.
224
+ */
225
+ export function currentCollections(rootInput, hooks = {}) {
226
+ const root = workspace(rootInput);
227
+ const journal = readCollectionsJournal(root);
228
+ hooks.afterJournal?.();
229
+ if (journal.state === 'invalid')
230
+ return { record: null, source: 'none', problems: [journal.problem] };
231
+ if (journal.state === 'present') {
232
+ if (bytes(root, INSTALL_PATHS.pending, 4 * DISTRIBUTION_LIMITS.metadata) !== null)
233
+ return { record: null, source: 'interrupted', problems: ['installation interrupted; run ia recover'] };
234
+ const { journal: entry } = journal, active = activeBytes(root);
235
+ if (active === entry.afterActive)
236
+ return { record: decodeOrNull(entry.after), source: 'after', problems: [] };
237
+ if (active === entry.beforeActive)
238
+ return { record: decodeOrNull(entry.before), source: 'before', problems: [] };
239
+ return { record: undecidedRecord(entry, lockDigest(root)), source: 'undecided', problems: [] };
240
+ }
241
+ const read = readKitCollections(root);
242
+ hooks.afterRecord?.();
243
+ if (read.state === 'absent')
244
+ return { record: null, source: 'none', problems: [] };
245
+ if (read.state === 'invalid')
246
+ return { record: null, source: 'none', problems: [read.problem] };
247
+ return { record: read.record, source: 'file', problems: [] };
248
+ }
249
+ const pinned = (lock, member) => lock.packages.some((locked) => locked.id === member.id && locked.version === member.version && locked.archive === member.archive);
250
+ /**
251
+ * The collections that count against `lock`, the portable lock now on disk: none unless the chosen record names those
252
+ * exact bytes (their sha256, `lockSha`), and within it only a collection whose every member equals the lock's row of that id.
253
+ */
254
+ export function intactAgainst(current, lock, lockSha) {
255
+ const problems = [...current.problems];
256
+ if (current.record === null || lock === null)
257
+ return { collections: [], unknown: [], named: [], problems };
258
+ if (lockSha === null || current.record.lock !== lockSha) {
259
+ problems.push(`${KIT_COLLECTIONS} describes another lock; collection sources are unknown`);
260
+ return { collections: [], unknown: [], named: [], problems };
261
+ }
262
+ const ids = new Set(lock.packages.map((locked) => locked.id));
263
+ return {
264
+ collections: current.record.collections.filter((row) => row.members.every((member) => pinned(lock, member))),
265
+ unknown: current.record.unknown
266
+ .map((row) => ({ id: row.id, members: row.members.filter((member) => ids.has(member)) }))
267
+ .filter((row) => row.members.length > 0),
268
+ named: (current.record.named ?? []).filter((id) => lock.requests.some((request) => request.id === id)),
269
+ problems,
270
+ };
271
+ }
272
+ /**
273
+ * Builds the rows an operation expanded from the resolved plan lock: each member id joined to the lock's `packages`
274
+ * row of that id, for its exact version and archive. A member the lock lacks is a defect, refused before anything
275
+ * commits.
276
+ */
277
+ export function expandedRows(expanded, lock) {
278
+ return expanded.map((collection) => ({
279
+ id: collection.id,
280
+ version: collection.version,
281
+ registry: collection.registry,
282
+ members: collection.members.map((id) => {
283
+ const locked = lock.packages.find((row) => row.id === id);
284
+ if (locked === undefined)
285
+ return fail('INSTALL-COLLECTION-MISMATCH', `Collection ${collection.id}@${collection.version} lists ${id}, which the resolved lock does not hold`);
286
+ return { id, version: locked.version, archive: locked.archive };
287
+ }),
288
+ }));
289
+ }
290
+ /**
291
+ * The record after an operation, pure:
292
+ * 1. `current` is the record that counted before it, already matched against the lock before the operation (null
293
+ * otherwise);
294
+ * 2. every row of a collection this operation expanded is dropped, to be rewritten;
295
+ * 3. every other row is kept only while all its recorded members are `afterLock`'s exact pins; a row with any member
296
+ * removed, re-pinned or re-archived is removed whole, so its other members can never make it intact again;
297
+ * 4. the expanded rows are added, built from `afterLock`.
298
+ * An unknown entry is kept until its collection is installed again or none of its members is left in the lock.
299
+ * `named` adds the requests this operation counts as named by the user; with the record's own, each is kept while it is
300
+ * still an `afterLock` request that a row or unknown entry of the result lists.
301
+ */
302
+ export function mergeKitCollections(current, expanded, afterLock, afterLockBytes, named = []) {
303
+ const rewritten = new Set(expanded.map((collection) => collection.id)), ids = new Set(afterLock.packages.map((locked) => locked.id));
304
+ const kept = (current?.collections ?? []).filter((row) => !rewritten.has(row.id) && row.members.every((member) => pinned(afterLock, member)));
305
+ const collections = [...kept, ...expandedRows(expanded, afterLock)].sort(byId), unknown = (current?.unknown ?? [])
306
+ .filter((row) => !rewritten.has(row.id) && row.members.some((member) => ids.has(member)))
307
+ .sort(byId);
308
+ const listed = new Set([
309
+ ...collections.flatMap((row) => row.members.map((member) => member.id)),
310
+ ...unknown.flatMap((row) => row.members),
311
+ ]);
312
+ const direct = [...new Set([...(current?.named ?? []), ...named])]
313
+ .filter((id) => listed.has(id) && afterLock.requests.some((request) => request.id === id))
314
+ .sort();
315
+ return {
316
+ format: KIT_COLLECTIONS_FORMAT,
317
+ lock: sha256(afterLockBytes),
318
+ collections,
319
+ unknown,
320
+ ...(direct.length > 0 ? { named: direct } : {}),
321
+ };
322
+ }
323
+ /** Whether a record carries nothing worth committing: an empty record is never written, and a record left empty is removed. */
324
+ export const emptyRecord = (record) => record.collections.length === 0 && record.unknown.length === 0;
325
+ /**
326
+ * Settles a journal no `pending.json` stands beside (an older CLI recovered the operation without reading it), under the
327
+ * installation lock: the record is written as the side the activation pointer exactly names, or, when it names
328
+ * neither, as the collections both sides agree on with the rest unknown; the journal is then removed. Returns whether
329
+ * a journal was settled.
330
+ */
331
+ export function settleOrphanJournal(root) {
332
+ const journal = readCollectionsJournal(root);
333
+ if (journal.state === 'absent')
334
+ return false;
335
+ if (journal.state === 'present') {
336
+ const { journal: entry } = journal, active = activeBytes(root);
337
+ const content = active === entry.afterActive
338
+ ? entry.after
339
+ : active === entry.beforeActive
340
+ ? entry.before
341
+ : (() => {
342
+ const undecided = undecidedRecord(entry, lockDigest(root));
343
+ return undecided === null || emptyRecord(undecided) ? null : serializeKitCollections(undecided);
344
+ })();
345
+ writeRecord(root, content);
346
+ }
347
+ // An unreadable journal names no side, so it is dropped and the record file stands as it is.
348
+ removeCollectionsJournal(root);
349
+ return true;
350
+ }
351
+ /** Recovery's side of the journal: the record as the operation left it when it committed, as before when it did not. */
352
+ export function settleKitCollections(root, committed) {
353
+ const journal = readCollectionsJournal(root);
354
+ if (journal.state === 'absent')
355
+ return;
356
+ if (journal.state === 'present')
357
+ writeRecord(root, committed ? journal.journal.after : journal.journal.before);
358
+ removeCollectionsJournal(root);
359
+ }
360
+ export { writeRecord as writeKitCollections };
361
+ /**
362
+ * `currentCollections` matched against the portable lock now on disk. Never throws: a lock that cannot be read leaves
363
+ * no collection intact, with the reason.
364
+ */
365
+ export function intactCollections(rootInput, hooks = {}) {
366
+ const root = workspace(rootInput);
367
+ const { current, lock: content } = stableCollections(root, hooks);
368
+ let lock;
369
+ try {
370
+ lock = content === null ? null : decodeDistributionLock(decodeDistributionJson(utf8(content)));
371
+ }
372
+ catch (error) {
373
+ const reason = error instanceof Error ? error.message : String(error);
374
+ return { collections: [], unknown: [], named: [], problems: [`${INSTALL_PATHS.lock}: ${reason}`] };
375
+ }
376
+ return intactAgainst(current, lock, content === null ? null : sha256(content));
377
+ }
378
+ /** An inode the platform could not report: Node gives 0, and some file systems all ones. */
379
+ const NO_INODE = new Set([0n, 2n ** 64n - 1n, 2n ** 32n - 1n]);
380
+ /**
381
+ * One file's identity: its content hash with its inode, modification time in nanoseconds and size. Every writer here
382
+ * replaces a file by renaming a new one into place, so a file put back with identical bytes still reads as another
383
+ * file. Where no inode is reported, the modification time, size and hash stand alone.
384
+ */
385
+ function identity(root, path, limit, read) {
386
+ const content = bytes(root, path, limit);
387
+ if (content === null)
388
+ return '-';
389
+ const stat = read(join(root, path));
390
+ const inode = stat === undefined || NO_INODE.has(stat.ino) ? '-' : String(stat.ino);
391
+ return `${sha256(content)}/${inode}/${stat?.mtimeNs ?? '-'}/${stat?.size ?? '-'}`;
392
+ }
393
+ /**
394
+ * The files a collection read depends on: pending marker, journal, activation pointer, lock and record, each by
395
+ * content and file identity.
396
+ */
397
+ const lstatIdentity = (path) => lstatSync(path, { bigint: true, throwIfNoEntry: false });
398
+ function probe(root, read = lstatIdentity) {
399
+ return [
400
+ identity(root, INSTALL_PATHS.pending, 4 * DISTRIBUTION_LIMITS.metadata, read),
401
+ identity(root, KIT_COLLECTIONS_JOURNAL, 4 * DISTRIBUTION_LIMITS.metadata, read),
402
+ identity(root, INSTALL_PATHS.active, 1024 * 1024, read),
403
+ identity(root, INSTALL_PATHS.lock, DISTRIBUTION_LIMITS.metadata, read),
404
+ identity(root, KIT_COLLECTIONS, DISTRIBUTION_LIMITS.metadata, read),
405
+ ].join(':');
406
+ }
407
+ /**
408
+ * The record that counts and the lock bytes it is judged against, read between two probes of the installation state:
409
+ * a reader never sees a record from before an operation began beside a pointer from after (or the reverse), because
410
+ * another process changing the files in between makes the probes differ. The read is tried once more, and when the
411
+ * state changes again it fails closed: every collection the record or journal names is reported with an unknown
412
+ * identity, never as intact.
413
+ */
414
+ export function stableCollections(rootInput, hooks = {}) {
415
+ const root = workspace(rootInput);
416
+ for (let attempt = 0; attempt < 2; attempt += 1) {
417
+ const before = probe(root, hooks.stat);
418
+ const current = currentCollections(root, hooks);
419
+ const lock = bytes(root, INSTALL_PATHS.lock, DISTRIBUTION_LIMITS.metadata);
420
+ if (probe(root, hooks.stat) === before)
421
+ return { current, lock };
422
+ }
423
+ const lock = bytes(root, INSTALL_PATHS.lock, DISTRIBUTION_LIMITS.metadata);
424
+ return { current: unstableCollections(root, lock === null ? null : sha256(lock)), lock };
425
+ }
426
+ /** Every collection the record file or a journal side names, as unknown, with the member ids any of them recorded. */
427
+ function unstableCollections(root, lockSha) {
428
+ const journal = readCollectionsJournal(root), file = readKitCollections(root);
429
+ const sides = [
430
+ file.state === 'present' ? file.record : null,
431
+ journal.state === 'present' ? decodeOrNull(journal.journal.before) : null,
432
+ journal.state === 'present' ? decodeOrNull(journal.journal.after) : null,
433
+ ].filter((side) => side !== null);
434
+ const members = new Map();
435
+ for (const side of sides) {
436
+ for (const row of side.collections)
437
+ for (const member of row.members)
438
+ members.set(row.id, (members.get(row.id) ?? new Set()).add(member.id));
439
+ for (const row of side.unknown)
440
+ for (const member of row.members)
441
+ members.set(row.id, (members.get(row.id) ?? new Set()).add(member));
442
+ }
443
+ const problems = ['the installation changed while it was read; collection identity unknown'];
444
+ if (members.size === 0 || lockSha === null)
445
+ return { record: null, source: 'unstable', problems };
446
+ return {
447
+ record: {
448
+ format: KIT_COLLECTIONS_FORMAT,
449
+ lock: lockSha,
450
+ collections: [],
451
+ unknown: [...members].map(([id, ids]) => ({ id, members: [...ids].sort() })).sort(byId),
452
+ },
453
+ source: 'unstable',
454
+ problems,
455
+ };
456
+ }
457
+ //# sourceMappingURL=kit-collections.js.map