anhedral 0.22.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +4 -2
  2. package/assets/contracts/deployment-provenance.json +4 -4
  3. package/dist/cli-commands.js +5 -17
  4. package/dist/cli-errors.js +1 -1
  5. package/dist/command-schema.d.ts +1 -0
  6. package/dist/command-schema.js +14 -0
  7. package/dist/completion.js +1 -1
  8. package/dist/{capability-command.d.ts → composition/command.d.ts} +3 -3
  9. package/dist/{capability-command.js → composition/command.js} +12 -12
  10. package/dist/{composition.d.ts → composition/composition.d.ts} +1 -1
  11. package/dist/{composition.js → composition/composition.js} +2 -2
  12. package/dist/{capability-editor.js → composition/editor.js} +1 -1
  13. package/dist/{capability-recipes.d.ts → composition/recipes.d.ts} +2 -2
  14. package/dist/{capability-recipes.js → composition/recipes.js} +7 -7
  15. package/dist/{capability-references.js → composition/references.js} +2 -2
  16. package/dist/{stack-update.d.ts → composition/update.d.ts} +3 -3
  17. package/dist/{stack-update.js → composition/update.js} +11 -11
  18. package/dist/contracts/cli-transport.d.ts +1 -1
  19. package/dist/contracts/deployment.d.ts +4 -65
  20. package/dist/contracts/deployment.js +0 -29
  21. package/dist/contracts/production-transport.d.ts +2 -2
  22. package/dist/contracts/staging-transport.d.ts +2 -2
  23. package/dist/launch.js +5 -5
  24. package/dist/platform/auth.d.ts +14 -0
  25. package/dist/platform/auth.js +62 -0
  26. package/dist/{platform-command.d.ts → platform/command.d.ts} +2 -2
  27. package/dist/platform/command.js +279 -0
  28. package/dist/{credential-helper.js → platform/credential-helper.js} +1 -1
  29. package/dist/platform/deploy.d.ts +2 -0
  30. package/dist/platform/deploy.js +158 -0
  31. package/dist/{platform-environment.d.ts → platform/environment.d.ts} +1 -1
  32. package/dist/{platform-environment.js → platform/environment.js} +7 -7
  33. package/dist/platform/http.d.ts +7 -0
  34. package/dist/platform/http.js +105 -0
  35. package/dist/{platform-operations.d.ts → platform/operations.d.ts} +1 -1
  36. package/dist/{platform-operations.js → platform/operations.js} +5 -5
  37. package/dist/platform/output.d.ts +2 -0
  38. package/dist/platform/output.js +79 -0
  39. package/dist/{platform-production.d.ts → platform/production.d.ts} +1 -1
  40. package/dist/{platform-production.js → platform/production.js} +4 -4
  41. package/dist/platform/projects.d.ts +12 -0
  42. package/dist/platform/projects.js +125 -0
  43. package/dist/{platform-source.js → platform/source.js} +7 -7
  44. package/dist/platform/state-schema.d.ts +25 -0
  45. package/dist/platform/state-schema.js +11 -0
  46. package/dist/{platform-state.d.ts → platform/state.d.ts} +1 -1
  47. package/dist/{platform-state.js → platform/state.js} +3 -4
  48. package/dist/platform/types.d.ts +26 -0
  49. package/dist/platform/upload.d.ts +2 -0
  50. package/dist/platform/upload.js +60 -0
  51. package/dist/process/runner.d.ts +1 -0
  52. package/dist/{command-runner.js → process/runner.js} +1 -1
  53. package/dist/registry/usage.d.ts +1 -0
  54. package/dist/{platforms → scaffold}/tanstack.d.ts +2 -2
  55. package/dist/{platforms → scaffold}/tanstack.js +2 -2
  56. package/dist/transactions/durable-files.d.ts +8 -0
  57. package/dist/transactions/durable-files.js +132 -0
  58. package/dist/transactions/journal.d.ts +4 -0
  59. package/dist/transactions/journal.js +141 -0
  60. package/dist/{transaction-lock.js → transactions/lock.js} +2 -2
  61. package/dist/transactions/model.d.ts +18 -0
  62. package/dist/transactions/model.js +4 -0
  63. package/dist/transactions/paths.d.ts +12 -0
  64. package/dist/transactions/paths.js +155 -0
  65. package/dist/transactions/recovery.d.ts +7 -0
  66. package/dist/transactions/recovery.js +132 -0
  67. package/dist/{transaction.d.ts → transactions/transaction.d.ts} +1 -2
  68. package/dist/transactions/transaction.js +179 -0
  69. package/dist/util.js +2 -2
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/docs/software-factory.md +32 -6
  73. package/package.json +18 -18
  74. package/dist/platform-command.js +0 -787
  75. package/dist/transaction.js +0 -716
  76. /package/dist/{capability-catalog.d.ts → composition/catalog.d.ts} +0 -0
  77. /package/dist/{capability-catalog.js → composition/catalog.js} +0 -0
  78. /package/dist/{capability-editor.d.ts → composition/editor.d.ts} +0 -0
  79. /package/dist/{capability-references.d.ts → composition/references.d.ts} +0 -0
  80. /package/dist/{credential-helper.d.ts → platform/credential-helper.d.ts} +0 -0
  81. /package/dist/{platform-source.d.ts → platform/source.d.ts} +0 -0
  82. /package/dist/{command-runner.d.ts → platform/types.js} +0 -0
  83. /package/dist/{command.d.ts → process/resolve-command.d.ts} +0 -0
  84. /package/dist/{command.js → process/resolve-command.js} +0 -0
  85. /package/dist/{transaction-lock.d.ts → transactions/lock.d.ts} +0 -0
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, fsyncSync, lstatSync, openSync, readdirSync, readFileSync, renameSync, rmSync, } from 'node:fs';
3
+ import path from 'node:path';
4
+ export function lstatIfPresent(target) {
5
+ try {
6
+ return lstatSync(target);
7
+ }
8
+ catch (error) {
9
+ if (error.code === 'ENOENT')
10
+ return null;
11
+ throw error;
12
+ }
13
+ }
14
+ function isUnsupportedDirectorySync(error, operation) {
15
+ const code = error.code;
16
+ if (['ENOTSUP', 'EOPNOTSUPP'].includes(code ?? ''))
17
+ return true;
18
+ // Some filesystems expose directories as readable handles but reject fsync.
19
+ // Windows may reject opening or syncing directory handles altogether. Keep
20
+ // these narrowly scoped so permission and I/O failures remain actionable.
21
+ if (operation === 'fsync' && code === 'EINVAL')
22
+ return true;
23
+ if (process.platform !== 'win32')
24
+ return false;
25
+ const windowsCodes = operation === 'open' ? ['EISDIR', 'EPERM'] : ['EBADF', 'EPERM'];
26
+ return windowsCodes.includes(code ?? '');
27
+ }
28
+ export function syncDirectory(directory) {
29
+ let descriptor;
30
+ try {
31
+ descriptor = openSync(directory, 'r');
32
+ }
33
+ catch (error) {
34
+ if (isUnsupportedDirectorySync(error, 'open'))
35
+ return;
36
+ throw error;
37
+ }
38
+ try {
39
+ try {
40
+ fsyncSync(descriptor);
41
+ }
42
+ catch (error) {
43
+ if (!isUnsupportedDirectorySync(error, 'fsync'))
44
+ throw error;
45
+ }
46
+ }
47
+ finally {
48
+ closeSync(descriptor);
49
+ }
50
+ }
51
+ function directoryChainToRoot(directory, root) {
52
+ const resolvedRoot = path.resolve(root);
53
+ let cursor = path.resolve(directory);
54
+ if (cursor !== resolvedRoot && !cursor.startsWith(`${resolvedRoot}${path.sep}`)) {
55
+ throw new Error(`Cannot sync transaction directory outside its root: ${directory}`);
56
+ }
57
+ const directories = [];
58
+ while (true) {
59
+ directories.push(cursor);
60
+ if (cursor === resolvedRoot)
61
+ return directories;
62
+ cursor = path.dirname(cursor);
63
+ }
64
+ }
65
+ function syncDirectories(directories) {
66
+ const seen = new Set();
67
+ for (const directory of directories) {
68
+ const resolved = path.resolve(directory);
69
+ if (seen.has(resolved))
70
+ continue;
71
+ seen.add(resolved);
72
+ syncDirectory(resolved);
73
+ }
74
+ }
75
+ export function syncEntryRecursively(target) {
76
+ const stat = lstatSync(target);
77
+ if (stat.isDirectory()) {
78
+ for (const entry of readdirSync(target))
79
+ syncEntryRecursively(path.join(target, entry));
80
+ syncDirectory(target);
81
+ return;
82
+ }
83
+ if (!stat.isFile())
84
+ return;
85
+ // Windows FlushFileBuffers requires a handle opened with write access. The
86
+ // staged file is owned by this transaction, so opening it read/write retains
87
+ // the durability guarantee instead of treating EPERM as an unsupported sync.
88
+ const descriptor = openSync(target, process.platform === 'win32' ? 'r+' : 'r');
89
+ try {
90
+ fsyncSync(descriptor);
91
+ }
92
+ finally {
93
+ closeSync(descriptor);
94
+ }
95
+ }
96
+ export function renameDurably(source, target, root) {
97
+ renameSync(source, target);
98
+ const targetDirectories = directoryChainToRoot(path.dirname(target), root);
99
+ const sourceParent = path.dirname(source);
100
+ syncDirectories([...targetDirectories, sourceParent]);
101
+ }
102
+ export function removeEntryDurably(target) {
103
+ rmSync(target, { recursive: true, force: true });
104
+ const parent = path.dirname(target);
105
+ if (lstatIfPresent(parent))
106
+ syncDirectory(parent);
107
+ }
108
+ export function pathEntryExists(target) {
109
+ return lstatIfPresent(target) !== null;
110
+ }
111
+ export function fingerprintEntry(target) {
112
+ const hash = createHash('sha256');
113
+ const visit = (absolutePath, relativePath) => {
114
+ const stat = lstatSync(absolutePath);
115
+ const mode = stat.mode & 0o7777;
116
+ if (stat.isDirectory()) {
117
+ hash.update(`directory\0${relativePath}\0${mode}\0`);
118
+ for (const entry of readdirSync(absolutePath).sort()) {
119
+ visit(path.join(absolutePath, entry), relativePath === '.' ? entry : `${relativePath}/${entry}`);
120
+ }
121
+ return;
122
+ }
123
+ if (stat.isFile()) {
124
+ hash.update(`file\0${relativePath}\0${mode}\0${stat.size}\0`);
125
+ hash.update(readFileSync(absolutePath));
126
+ return;
127
+ }
128
+ throw new Error(`Cannot fingerprint unsupported transaction entry: ${absolutePath}`);
129
+ };
130
+ visit(target, '.');
131
+ return hash.digest('hex');
132
+ }
@@ -0,0 +1,4 @@
1
+ import { type TransactionJournal } from './model.js';
2
+ export declare function validateJournal(root: string, value: unknown): TransactionJournal;
3
+ export declare function writeJournal(root: string, journal: TransactionJournal): void;
4
+ export declare function removeJournal(root: string): void;
@@ -0,0 +1,141 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, fsyncSync, openSync, renameSync, rmSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { syncDirectory } from './durable-files.js';
5
+ import { JOURNAL_FILE, JOURNAL_VERSION, } from './model.js';
6
+ import { assertJournalRoots, assertNoPathAncestry, assertRelativePath, resolveTransactionPath, } from './paths.js';
7
+ function isRecord(value) {
8
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
9
+ }
10
+ function assertExactObjectKeys(value, expected, context) {
11
+ const expectedKeys = new Set(expected);
12
+ const missing = expected.filter((key) => !Object.hasOwn(value, key));
13
+ const unknown = Object.keys(value).filter((key) => !expectedKeys.has(key));
14
+ if (missing.length === 0 && unknown.length === 0)
15
+ return;
16
+ const details = [
17
+ missing.length > 0 ? `missing ${missing.join(', ')}` : null,
18
+ unknown.length > 0 ? `unknown ${unknown.join(', ')}` : null,
19
+ ]
20
+ .filter((entry) => entry !== null)
21
+ .join('; ');
22
+ throw new Error(`Invalid ${context} fields (${details}).`);
23
+ }
24
+ export function validateJournal(root, value) {
25
+ if (!isRecord(value) || value.version !== JOURNAL_VERSION) {
26
+ throw new Error(`Cannot recover unsupported transaction journal at ${path.join(root, JOURNAL_FILE)}`);
27
+ }
28
+ assertExactObjectKeys(value, ['version', 'backupRoot', 'stageRoot', 'entries', 'createdDirectories'], 'transaction journal');
29
+ if (typeof value.backupRoot !== 'string' ||
30
+ typeof value.stageRoot !== 'string' ||
31
+ !Array.isArray(value.entries)) {
32
+ throw new Error(`Invalid transaction journal at ${path.join(root, JOURNAL_FILE)}`);
33
+ }
34
+ assertJournalRoots(root, value.backupRoot, value.stageRoot);
35
+ const seen = new Set();
36
+ const entries = value.entries.map((entry, index) => {
37
+ if (!isRecord(entry) ||
38
+ typeof entry.relativePath !== 'string' ||
39
+ typeof entry.installed !== 'boolean') {
40
+ throw new Error(`Invalid transaction journal entry at index ${index}`);
41
+ }
42
+ assertExactObjectKeys(entry, [
43
+ 'relativePath',
44
+ 'backupPath',
45
+ 'installed',
46
+ 'installedFingerprint',
47
+ ...(Object.hasOwn(entry, 'backupFingerprint') ? ['backupFingerprint'] : []),
48
+ ], `transaction journal entry at index ${index}`);
49
+ assertRelativePath(entry.relativePath);
50
+ if (seen.has(entry.relativePath))
51
+ throw new Error(`Duplicate transaction journal path: ${entry.relativePath}`);
52
+ seen.add(entry.relativePath);
53
+ if (entry.backupPath !== null && typeof entry.backupPath !== 'string') {
54
+ throw new Error(`Invalid transaction backup path at index ${index}`);
55
+ }
56
+ if (Object.hasOwn(entry, 'backupFingerprint') &&
57
+ (typeof entry.backupFingerprint !== 'string' ||
58
+ !/^[a-f0-9]{64}$/.test(entry.backupFingerprint)))
59
+ throw new Error(`Invalid backup transaction fingerprint at index ${index}`);
60
+ const installedFingerprint = entry.installedFingerprint;
61
+ if (installedFingerprint !== null &&
62
+ (typeof installedFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(installedFingerprint))) {
63
+ throw new Error(`Invalid installed transaction fingerprint at index ${index}`);
64
+ }
65
+ if (entry.installed ? installedFingerprint === null : installedFingerprint !== null) {
66
+ throw new Error(`Transaction journal entry fingerprint state is inconsistent at index ${index}`);
67
+ }
68
+ const expectedBackup = resolveTransactionPath(value.backupRoot, entry.relativePath);
69
+ if (entry.backupPath !== null &&
70
+ path.resolve(entry.backupPath) !== path.resolve(expectedBackup)) {
71
+ throw new Error(`Unsafe transaction backup path: ${entry.backupPath}`);
72
+ }
73
+ return {
74
+ relativePath: entry.relativePath,
75
+ backupPath: entry.backupPath,
76
+ ...(typeof entry.backupFingerprint === 'string'
77
+ ? { backupFingerprint: entry.backupFingerprint }
78
+ : {}),
79
+ installed: entry.installed,
80
+ installedFingerprint,
81
+ };
82
+ });
83
+ assertNoPathAncestry(entries.map((entry) => entry.relativePath), 'journal paths');
84
+ const rawCreatedDirectories = value.createdDirectories;
85
+ if (!Array.isArray(rawCreatedDirectories)) {
86
+ throw new Error(`Invalid transaction created-directory inventory at ${path.join(root, JOURNAL_FILE)}`);
87
+ }
88
+ const createdDirectories = rawCreatedDirectories.map((entry, index) => {
89
+ if (typeof entry !== 'string')
90
+ throw new Error(`Invalid transaction created directory at index ${index}`);
91
+ assertRelativePath(entry);
92
+ return entry;
93
+ });
94
+ if (new Set(createdDirectories).size !== createdDirectories.length) {
95
+ throw new Error('Duplicate transaction created-directory path.');
96
+ }
97
+ for (const directory of createdDirectories) {
98
+ if (!entries.some((entry) => entry.relativePath.startsWith(`${directory}/`))) {
99
+ throw new Error(`Transaction created directory is not a parent of any journal entry: ${directory}`);
100
+ }
101
+ }
102
+ return {
103
+ version: JOURNAL_VERSION,
104
+ backupRoot: value.backupRoot,
105
+ stageRoot: value.stageRoot,
106
+ entries,
107
+ createdDirectories,
108
+ };
109
+ }
110
+ export function writeJournal(root, journal) {
111
+ const journalPath = path.join(root, JOURNAL_FILE);
112
+ const temporaryPath = `${journalPath}.tmp-${process.pid}-${randomUUID()}`;
113
+ let descriptor = null;
114
+ try {
115
+ descriptor = openSync(temporaryPath, 'wx', 0o600);
116
+ writeFileSync(descriptor, JSON.stringify(journal, null, 2) + '\n', { encoding: 'utf8' });
117
+ fsyncSync(descriptor);
118
+ const completedDescriptor = descriptor;
119
+ descriptor = null;
120
+ closeSync(completedDescriptor);
121
+ renameSync(temporaryPath, journalPath);
122
+ syncDirectory(path.dirname(journalPath));
123
+ }
124
+ finally {
125
+ if (descriptor !== null)
126
+ closeSync(descriptor);
127
+ rmSync(temporaryPath, { force: true });
128
+ }
129
+ }
130
+ export function removeJournal(root) {
131
+ const journalPath = path.join(root, JOURNAL_FILE);
132
+ try {
133
+ unlinkSync(journalPath);
134
+ }
135
+ catch (error) {
136
+ if (error.code === 'ENOENT')
137
+ return;
138
+ throw error;
139
+ }
140
+ syncDirectory(path.dirname(journalPath));
141
+ }
@@ -1,8 +1,8 @@
1
- import { linkSync, lstatSync, readdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
2
1
  import { randomUUID } from 'node:crypto';
2
+ import { linkSync, lstatSync, readdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { readBoundedFile } from './bounded-file.js';
5
+ import { readBoundedFile } from '../bounded-file.js';
6
6
  export const LOCK_FILE = '.anhedral.lock';
7
7
  function isRecord(value) {
8
8
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -0,0 +1,18 @@
1
+ export declare const JOURNAL_FILE = ".anhedral-journal.json";
2
+ export declare const TRANSACTION_DIRECTORY = ".anhedral-txn";
3
+ export declare const JOURNAL_VERSION: 2;
4
+ export declare const LOCAL_TRANSACTION_ROOT_PATTERN: RegExp;
5
+ export type JournalEntry = {
6
+ relativePath: string;
7
+ backupPath: string | null;
8
+ backupFingerprint?: string;
9
+ installed: boolean;
10
+ installedFingerprint: string | null;
11
+ };
12
+ export type TransactionJournal = {
13
+ version: typeof JOURNAL_VERSION;
14
+ backupRoot: string;
15
+ stageRoot: string;
16
+ entries: JournalEntry[];
17
+ createdDirectories: string[];
18
+ };
@@ -0,0 +1,4 @@
1
+ export const JOURNAL_FILE = '.anhedral-journal.json';
2
+ export const TRANSACTION_DIRECTORY = '.anhedral-txn';
3
+ export const JOURNAL_VERSION = 2;
4
+ export const LOCAL_TRANSACTION_ROOT_PATTERN = /^(?:stage|backup)-\d+-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -0,0 +1,12 @@
1
+ export declare function assertRelativePath(relativePath: string): void;
2
+ export declare function resolveTransactionPath(root: string, relativePath: string): string;
3
+ export declare function assertNoPathAncestry(paths: readonly string[], context: string): void;
4
+ export declare function normalizeTransactionPaths(rawCommitPaths: readonly string[], rawDeletePaths: readonly string[]): {
5
+ commitPaths: string[];
6
+ deletePaths: string[];
7
+ uniquePaths: string[];
8
+ };
9
+ export declare function assertNoSymlinkComponents(root: string, relativePath: string): void;
10
+ export declare function assertNoSymlinksRecursively(target: string): void;
11
+ export declare function assertJournalRoots(root: string, backupRoot: string, stageRoot: string): void;
12
+ export declare function assertTransactionNamespace(transactionDirectory: string): void;
@@ -0,0 +1,155 @@
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { lstatIfPresent } from './durable-files.js';
4
+ import { LOCK_FILE } from './lock.js';
5
+ import { JOURNAL_FILE, LOCAL_TRANSACTION_ROOT_PATTERN, TRANSACTION_DIRECTORY } from './model.js';
6
+ export function assertRelativePath(relativePath) {
7
+ const normalized = path.normalize(relativePath);
8
+ const rawSegments = relativePath.split(/[\\/]/);
9
+ if (!relativePath ||
10
+ relativePath.includes('\0') ||
11
+ relativePath.includes('\\') ||
12
+ path.isAbsolute(relativePath) ||
13
+ rawSegments.some((segment) => segment === '' || segment === '.' || segment === '..') ||
14
+ normalized === '.' ||
15
+ normalized === '..' ||
16
+ normalized.startsWith(`..${path.sep}`) ||
17
+ normalized.split(path.sep).includes('..') ||
18
+ rawSegments[0] === TRANSACTION_DIRECTORY ||
19
+ rawSegments[0] === LOCK_FILE ||
20
+ rawSegments[0] === JOURNAL_FILE) {
21
+ throw new Error(`Unsafe transaction path: ${relativePath}`);
22
+ }
23
+ }
24
+ export function resolveTransactionPath(root, relativePath) {
25
+ assertRelativePath(relativePath);
26
+ const resolvedRoot = path.resolve(root);
27
+ const resolved = path.resolve(resolvedRoot, relativePath);
28
+ if (!resolved.startsWith(`${resolvedRoot}${path.sep}`)) {
29
+ throw new Error(`Unsafe transaction path: ${relativePath}`);
30
+ }
31
+ return resolved;
32
+ }
33
+ function ancestorInSet(relativePath, candidates) {
34
+ const segments = relativePath.split('/');
35
+ for (let index = 1; index < segments.length; index += 1) {
36
+ const ancestor = segments.slice(0, index).join('/');
37
+ if (candidates.has(ancestor))
38
+ return ancestor;
39
+ }
40
+ return null;
41
+ }
42
+ export function assertNoPathAncestry(paths, context) {
43
+ const seen = new Set();
44
+ const ordered = [...paths].sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
45
+ for (const relativePath of ordered) {
46
+ assertRelativePath(relativePath);
47
+ const ancestor = ancestorInSet(relativePath, seen);
48
+ if (ancestor) {
49
+ throw new Error(`Ambiguous transaction ${context}: ${ancestor} is an ancestor of ${relativePath}.`);
50
+ }
51
+ seen.add(relativePath);
52
+ }
53
+ }
54
+ export function normalizeTransactionPaths(rawCommitPaths, rawDeletePaths) {
55
+ const commitPaths = [...new Set(rawCommitPaths)];
56
+ for (const relativePath of commitPaths)
57
+ assertRelativePath(relativePath);
58
+ assertNoPathAncestry(commitPaths, 'write paths');
59
+ const deleteCandidates = [...new Set(rawDeletePaths)];
60
+ for (const relativePath of deleteCandidates)
61
+ assertRelativePath(relativePath);
62
+ deleteCandidates.sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right));
63
+ const deleteSet = new Set();
64
+ const deletePaths = deleteCandidates.filter((candidate) => {
65
+ if (ancestorInSet(candidate, deleteSet))
66
+ return false;
67
+ deleteSet.add(candidate);
68
+ return true;
69
+ });
70
+ const deleteAncestorPaths = new Set();
71
+ for (const deleted of deletePaths) {
72
+ const segments = deleted.split('/');
73
+ for (let index = 1; index < segments.length; index += 1) {
74
+ deleteAncestorPaths.add(segments.slice(0, index).join('/'));
75
+ }
76
+ }
77
+ for (const written of commitPaths) {
78
+ const deletedAncestor = ancestorInSet(written, deleteSet);
79
+ if (deleteSet.has(written) || deletedAncestor || deleteAncestorPaths.has(written)) {
80
+ throw new Error(`Ambiguous transaction write/delete paths include ${written}` +
81
+ (deletedAncestor ? ` below ${deletedAncestor}` : ''));
82
+ }
83
+ }
84
+ const uniquePaths = [...commitPaths, ...deletePaths].sort();
85
+ return { commitPaths, deletePaths, uniquePaths };
86
+ }
87
+ function assertExpectedTempRoot(root, candidate, kind) {
88
+ const resolved = path.resolve(candidate);
89
+ const tokenPattern = '(\\d+-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})';
90
+ const localParent = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
91
+ const localMatch = new RegExp(`^${kind}-${tokenPattern}$`, 'i').exec(path.basename(resolved));
92
+ if (path.dirname(resolved) === localParent && localMatch) {
93
+ const namespaceStat = lstatIfPresent(localParent);
94
+ if (namespaceStat && (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory())) {
95
+ throw new Error(`Unsafe reserved transaction namespace: ${localParent}`);
96
+ }
97
+ return { token: localMatch[1] };
98
+ }
99
+ throw new Error(`Unsafe transaction ${kind} root: ${candidate}`);
100
+ }
101
+ export function assertNoSymlinkComponents(root, relativePath) {
102
+ resolveTransactionPath(root, relativePath);
103
+ let cursor = path.resolve(root);
104
+ if (lstatIfPresent(cursor)?.isSymbolicLink()) {
105
+ throw new Error(`Refusing transaction root that is a symbolic link: ${root}`);
106
+ }
107
+ for (const segment of relativePath.split('/')) {
108
+ cursor = path.join(cursor, segment);
109
+ if (lstatIfPresent(cursor)?.isSymbolicLink()) {
110
+ throw new Error(`Refusing transaction path containing a symbolic link: ${relativePath}`);
111
+ }
112
+ }
113
+ }
114
+ export function assertNoSymlinksRecursively(target) {
115
+ const stat = lstatSync(target);
116
+ if (stat.isSymbolicLink())
117
+ throw new Error(`Refusing symbolic link in staged output: ${target}`);
118
+ if (!stat.isDirectory())
119
+ return;
120
+ for (const entry of readdirSync(target))
121
+ assertNoSymlinksRecursively(path.join(target, entry));
122
+ }
123
+ export function assertJournalRoots(root, backupRoot, stageRoot) {
124
+ const backupIdentity = assertExpectedTempRoot(root, backupRoot, 'backup');
125
+ const stageIdentity = assertExpectedTempRoot(root, stageRoot, 'stage');
126
+ if (backupIdentity.token !== stageIdentity.token) {
127
+ throw new Error('Transaction stage and backup roots do not share one token.');
128
+ }
129
+ for (const temporaryRoot of [backupRoot, stageRoot]) {
130
+ const stat = lstatIfPresent(temporaryRoot);
131
+ if (stat) {
132
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
133
+ throw new Error(`Unsafe transaction temporary root: ${temporaryRoot}`);
134
+ }
135
+ }
136
+ }
137
+ }
138
+ export function assertTransactionNamespace(transactionDirectory) {
139
+ const namespaceStat = lstatIfPresent(transactionDirectory);
140
+ if (namespaceStat && (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory())) {
141
+ throw new Error(`Unsafe reserved transaction namespace requires manual inspection: ${transactionDirectory}`);
142
+ }
143
+ if (!namespaceStat)
144
+ return;
145
+ for (const entry of readdirSync(transactionDirectory)) {
146
+ const candidate = path.join(transactionDirectory, entry);
147
+ const stat = lstatIfPresent(candidate);
148
+ if (!LOCAL_TRANSACTION_ROOT_PATTERN.test(entry) ||
149
+ !stat ||
150
+ stat.isSymbolicLink() ||
151
+ !stat.isDirectory()) {
152
+ throw new Error(`Unknown or unsafe artifact in reserved transaction namespace requires manual inspection: ${candidate}`);
153
+ }
154
+ }
155
+ }
@@ -0,0 +1,7 @@
1
+ import { type TransactionJournal } from './model.js';
2
+ export declare function removeEmptyTransactionDirectory(root: string): void;
3
+ export declare function cleanupOrphanTransactionRoots(root: string): void;
4
+ export declare function restoreJournal(root: string, journal: TransactionJournal): void;
5
+ export declare function recoverInterruptedTransactionUnlocked(root: string): boolean;
6
+ /** Recover an interrupted commit while holding the same lock used by normal transactions. */
7
+ export declare function recoverInterruptedTransaction(root: string): boolean;
@@ -0,0 +1,132 @@
1
+ import { lstatSync, mkdirSync, readdirSync, rmSync, rmdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readBoundedFile } from '../bounded-file.js';
4
+ import { fingerprintEntry, lstatIfPresent, pathEntryExists, removeEntryDurably, renameDurably, syncDirectory, } from './durable-files.js';
5
+ import { removeJournal, validateJournal, writeJournal } from './journal.js';
6
+ import { acquireTransactionLock, releaseTransactionLock } from './lock.js';
7
+ import { JOURNAL_FILE, LOCAL_TRANSACTION_ROOT_PATTERN, TRANSACTION_DIRECTORY, } from './model.js';
8
+ import { assertNoSymlinkComponents, resolveTransactionPath } from './paths.js';
9
+ export function removeEmptyTransactionDirectory(root) {
10
+ const transactionDirectory = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
11
+ try {
12
+ rmdirSync(transactionDirectory);
13
+ }
14
+ catch (error) {
15
+ const code = error.code;
16
+ // Preserve rejected files/symlinks and the original namespace validation error.
17
+ if (!['ENOENT', 'ENOTDIR', 'ENOTEMPTY', 'EEXIST'].includes(code ?? ''))
18
+ throw error;
19
+ }
20
+ }
21
+ export function cleanupOrphanTransactionRoots(root) {
22
+ const transactionDirectory = path.join(path.resolve(root), TRANSACTION_DIRECTORY);
23
+ const namespaceStat = lstatIfPresent(transactionDirectory);
24
+ if (!namespaceStat)
25
+ return;
26
+ if (namespaceStat.isSymbolicLink() || !namespaceStat.isDirectory()) {
27
+ throw new Error(`Unsafe reserved transaction namespace requires manual inspection: ${transactionDirectory}`);
28
+ }
29
+ for (const entry of readdirSync(transactionDirectory)) {
30
+ if (!LOCAL_TRANSACTION_ROOT_PATTERN.test(entry)) {
31
+ throw new Error(`Unknown artifact in reserved transaction namespace requires manual inspection: ${path.join(transactionDirectory, entry)}`);
32
+ }
33
+ const candidate = path.join(transactionDirectory, entry);
34
+ const stat = lstatIfPresent(candidate);
35
+ if (!stat)
36
+ continue;
37
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
38
+ throw new Error(`Unsafe orphan transaction root requires manual inspection: ${candidate}`);
39
+ }
40
+ rmSync(candidate, { recursive: true });
41
+ }
42
+ removeEmptyTransactionDirectory(root);
43
+ }
44
+ function restoreInstalledEntry(root, journal, entry, target) {
45
+ if (entry.installed) {
46
+ if (pathEntryExists(target)) {
47
+ if (entry.installedFingerprint === null) {
48
+ throw new Error(`Installed transaction path has no trusted fingerprint: ${entry.relativePath}. ` +
49
+ 'Recovery stopped without modifying it; inspect the journal, target, and backup manually.');
50
+ }
51
+ const actualFingerprint = fingerprintEntry(target);
52
+ if (actualFingerprint !== entry.installedFingerprint) {
53
+ throw new Error(`Installed transaction path changed after an interrupted commit: ${entry.relativePath}. ` +
54
+ 'Recovery stopped without modifying it; inspect the journal, target, and backup manually.');
55
+ }
56
+ }
57
+ removeEntryDurably(target);
58
+ entry.installed = false;
59
+ entry.installedFingerprint = null;
60
+ writeJournal(root, journal);
61
+ }
62
+ }
63
+ export function restoreJournal(root, journal) {
64
+ for (const entry of [...journal.entries].reverse()) {
65
+ assertNoSymlinkComponents(root, entry.relativePath);
66
+ const target = resolveTransactionPath(root, entry.relativePath);
67
+ restoreInstalledEntry(root, journal, entry, target);
68
+ if (entry.backupPath) {
69
+ assertNoSymlinkComponents(journal.backupRoot, entry.relativePath);
70
+ if (pathEntryExists(entry.backupPath)) {
71
+ if (pathEntryExists(target))
72
+ throw new Error(`Transaction recovery target was recreated: ${entry.relativePath}. Recovery stopped without modifying it; preserve the journal, target and backup for manual inspection.`);
73
+ const backupFingerprint = fingerprintEntry(entry.backupPath);
74
+ if (entry.backupFingerprint && entry.backupFingerprint !== backupFingerprint)
75
+ throw new Error(`Transaction backup changed: ${entry.relativePath}. Preserve the journal and backup for manual inspection.`);
76
+ // Persist original identity before restore so a crash after rename can be replayed.
77
+ entry.backupFingerprint = backupFingerprint;
78
+ writeJournal(root, journal);
79
+ mkdirSync(path.dirname(target), { recursive: true });
80
+ renameDurably(entry.backupPath, target, root);
81
+ }
82
+ else if (!pathEntryExists(target) ||
83
+ !entry.backupFingerprint ||
84
+ fingerprintEntry(target) !== entry.backupFingerprint) {
85
+ throw new Error(`Cannot recover missing transaction backup or unverified target: ${entry.backupPath}. Recovery stopped; preserve the journal and target for manual inspection.`);
86
+ }
87
+ entry.backupPath = null;
88
+ delete entry.backupFingerprint;
89
+ writeJournal(root, journal);
90
+ }
91
+ }
92
+ for (const relativePath of [...journal.createdDirectories].sort((left, right) => right.split('/').length - left.split('/').length || right.localeCompare(left))) {
93
+ assertNoSymlinkComponents(root, relativePath);
94
+ const target = resolveTransactionPath(root, relativePath);
95
+ try {
96
+ rmdirSync(target);
97
+ syncDirectory(path.dirname(target));
98
+ }
99
+ catch (error) {
100
+ const code = error.code;
101
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(code ?? ''))
102
+ throw error;
103
+ }
104
+ }
105
+ removeJournal(root);
106
+ rmSync(journal.stageRoot, { recursive: true, force: true });
107
+ rmSync(journal.backupRoot, { recursive: true, force: true });
108
+ removeEmptyTransactionDirectory(root);
109
+ }
110
+ export function recoverInterruptedTransactionUnlocked(root) {
111
+ const journalPath = path.join(root, JOURNAL_FILE);
112
+ if (!pathEntryExists(journalPath))
113
+ return false;
114
+ if (lstatSync(journalPath).isSymbolicLink()) {
115
+ throw new Error(`Refusing symbolic-link transaction journal at ${journalPath}.`);
116
+ }
117
+ const journal = validateJournal(root, JSON.parse(readBoundedFile(journalPath, 16 * 1024 * 1024).toString('utf8')));
118
+ restoreJournal(root, journal);
119
+ return true;
120
+ }
121
+ /** Recover an interrupted commit while holding the same lock used by normal transactions. */
122
+ export function recoverInterruptedTransaction(root) {
123
+ const lock = acquireTransactionLock(root);
124
+ try {
125
+ const recovered = recoverInterruptedTransactionUnlocked(root);
126
+ cleanupOrphanTransactionRoots(root);
127
+ return recovered;
128
+ }
129
+ finally {
130
+ releaseTransactionLock(lock);
131
+ }
132
+ }
@@ -1,5 +1,4 @@
1
- /** Recover an interrupted commit while holding the same lock used by normal transactions. */
2
- export declare function recoverInterruptedTransaction(root: string): boolean;
1
+ export { recoverInterruptedTransaction } from './recovery.js';
3
2
  /** The filesystem commit succeeded, but a follow-up action such as install failed. */
4
3
  export declare class PostCommitError extends Error {
5
4
  readonly committedPaths: readonly string[];