anhedral 0.22.0 → 0.23.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.
- package/README.md +37 -51
- package/assets/contracts/deployment-provenance.json +4 -4
- package/assets/contracts/environment-provenance.json +2 -2
- package/dist/cli-commands.js +5 -17
- package/dist/cli-errors.js +1 -1
- package/dist/cli-output.js +1 -1
- package/dist/command-schema.d.ts +1 -0
- package/dist/command-schema.js +19 -1
- package/dist/completion.js +1 -1
- package/dist/{capability-catalog.d.ts → composition/catalog.d.ts} +2 -2
- package/dist/{capability-catalog.js → composition/catalog.js} +2 -2
- package/dist/{capability-command.d.ts → composition/command.d.ts} +3 -3
- package/dist/{capability-command.js → composition/command.js} +29 -22
- package/dist/{composition.d.ts → composition/composition.d.ts} +1 -1
- package/dist/{composition.js → composition/composition.js} +2 -2
- package/dist/{capability-editor.js → composition/editor.js} +1 -1
- package/dist/{capability-recipes.d.ts → composition/recipes.d.ts} +2 -2
- package/dist/{capability-recipes.js → composition/recipes.js} +7 -7
- package/dist/{capability-references.js → composition/references.js} +2 -2
- package/dist/{stack-update.d.ts → composition/update.d.ts} +3 -3
- package/dist/{stack-update.js → composition/update.js} +11 -11
- package/dist/contracts/cli-transport.d.ts +1 -1
- package/dist/contracts/deployment.d.ts +4 -65
- package/dist/contracts/deployment.js +0 -29
- package/dist/contracts/environment-file.d.ts +3 -0
- package/dist/contracts/environment-file.js +8 -5
- package/dist/contracts/production-transport.d.ts +2 -2
- package/dist/contracts/staging-transport.d.ts +2 -2
- package/dist/dependencies.d.ts +1 -1
- package/dist/dependencies.js +1 -1
- package/dist/launch.js +8 -8
- package/dist/platform/auth.d.ts +14 -0
- package/dist/platform/auth.js +62 -0
- package/dist/{platform-command.d.ts → platform/command.d.ts} +2 -2
- package/dist/platform/command.js +279 -0
- package/dist/{credential-helper.js → platform/credential-helper.js} +1 -1
- package/dist/platform/deploy.d.ts +2 -0
- package/dist/platform/deploy.js +158 -0
- package/dist/{platform-environment.d.ts → platform/environment.d.ts} +1 -1
- package/dist/{platform-environment.js → platform/environment.js} +12 -12
- package/dist/platform/http.d.ts +7 -0
- package/dist/platform/http.js +105 -0
- package/dist/{platform-operations.d.ts → platform/operations.d.ts} +1 -1
- package/dist/{platform-operations.js → platform/operations.js} +5 -5
- package/dist/platform/output.d.ts +2 -0
- package/dist/platform/output.js +79 -0
- package/dist/{platform-production.d.ts → platform/production.d.ts} +1 -1
- package/dist/{platform-production.js → platform/production.js} +4 -4
- package/dist/platform/projects.d.ts +12 -0
- package/dist/platform/projects.js +125 -0
- package/dist/{platform-source.js → platform/source.js} +7 -7
- package/dist/platform/state-schema.d.ts +25 -0
- package/dist/platform/state-schema.js +11 -0
- package/dist/{platform-state.d.ts → platform/state.d.ts} +1 -1
- package/dist/{platform-state.js → platform/state.js} +3 -4
- package/dist/platform/types.d.ts +26 -0
- package/dist/platform/upload.d.ts +2 -0
- package/dist/platform/upload.js +60 -0
- package/dist/process/runner.d.ts +1 -0
- package/dist/{command-runner.js → process/runner.js} +1 -1
- package/dist/registry/usage.d.ts +1 -0
- package/dist/{platforms → scaffold}/tanstack.d.ts +2 -2
- package/dist/{platforms → scaffold}/tanstack.js +2 -2
- package/dist/transactions/durable-files.d.ts +8 -0
- package/dist/transactions/durable-files.js +132 -0
- package/dist/transactions/journal.d.ts +4 -0
- package/dist/transactions/journal.js +141 -0
- package/dist/{transaction-lock.js → transactions/lock.js} +2 -2
- package/dist/transactions/model.d.ts +18 -0
- package/dist/transactions/model.js +4 -0
- package/dist/transactions/paths.d.ts +12 -0
- package/dist/transactions/paths.js +155 -0
- package/dist/transactions/recovery.d.ts +7 -0
- package/dist/transactions/recovery.js +132 -0
- package/dist/{transaction.d.ts → transactions/transaction.d.ts} +1 -2
- package/dist/transactions/transaction.js +179 -0
- package/dist/util.js +2 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/capabilities.md +8 -6
- package/docs/software-factory.md +36 -6
- package/package.json +22 -22
- package/dist/platform-command.js +0 -787
- package/dist/transaction.js +0 -716
- /package/dist/{capability-editor.d.ts → composition/editor.d.ts} +0 -0
- /package/dist/{capability-references.d.ts → composition/references.d.ts} +0 -0
- /package/dist/{credential-helper.d.ts → platform/credential-helper.d.ts} +0 -0
- /package/dist/{platform-source.d.ts → platform/source.d.ts} +0 -0
- /package/dist/{command-runner.d.ts → platform/types.js} +0 -0
- /package/dist/{command.d.ts → process/resolve-command.d.ts} +0 -0
- /package/dist/{command.js → process/resolve-command.js} +0 -0
- /package/dist/{transaction-lock.d.ts → transactions/lock.d.ts} +0 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const linkSchema: z.ZodObject<{
|
|
3
|
+
protocol: z.ZodLiteral<1>;
|
|
4
|
+
projectId: z.ZodUUID;
|
|
5
|
+
teamId: z.ZodUUID;
|
|
6
|
+
principalId: z.ZodUUID;
|
|
7
|
+
name: z.ZodString;
|
|
8
|
+
origin: z.ZodString;
|
|
9
|
+
}, z.core.$strict>;
|
|
10
|
+
export declare const uploadState: z.ZodObject<{
|
|
11
|
+
origin: z.ZodString;
|
|
12
|
+
principalId: z.ZodUUID;
|
|
13
|
+
input: z.ZodObject<{
|
|
14
|
+
protocol: z.ZodLiteral<1>;
|
|
15
|
+
requestId: z.ZodUUID;
|
|
16
|
+
projectId: z.ZodUUID;
|
|
17
|
+
teamId: z.ZodUUID;
|
|
18
|
+
archiveDigest: z.ZodString;
|
|
19
|
+
archiveBytes: z.ZodNumber;
|
|
20
|
+
inventoryDigest: z.ZodString;
|
|
21
|
+
cliVersion: z.ZodString;
|
|
22
|
+
chunks: z.ZodArray<z.ZodString>;
|
|
23
|
+
}, z.core.$strict>;
|
|
24
|
+
uploadId: z.ZodOptional<z.ZodUUID>;
|
|
25
|
+
}, z.core.$strict>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { cliLinkSchema, sourceUploadInputSchema } from '../contracts/cli-transport.js';
|
|
3
|
+
export const linkSchema = cliLinkSchema.extend({ origin: z.string() }).strict();
|
|
4
|
+
export const uploadState = z
|
|
5
|
+
.object({
|
|
6
|
+
origin: z.string(),
|
|
7
|
+
principalId: z.uuid(),
|
|
8
|
+
input: sourceUploadInputSchema,
|
|
9
|
+
uploadId: z.uuid().optional(),
|
|
10
|
+
})
|
|
11
|
+
.strict();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CliFailure } from '
|
|
1
|
+
import { CliFailure } from '../cli-errors.js';
|
|
2
2
|
import { trustedLinuxCredentialHelper } from './credential-helper.js';
|
|
3
3
|
export type PlatformFailureCategory = ConstructorParameters<typeof CliFailure>[3];
|
|
4
4
|
export declare const platformFailure: (message: string, nextAction?: string, category?: PlatformFailureCategory, retryable?: boolean) => CliFailure;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { dirname, join } from 'node:path';
|
|
4
3
|
import { lstat, mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { CliArgumentError } from '../cli-arguments.js';
|
|
6
|
+
import { CliFailure } from '../cli-errors.js';
|
|
7
7
|
import { trustedLinuxCredentialHelper } from './credential-helper.js';
|
|
8
8
|
export const platformFailure = (message, nextAction = 'Run anhedral login --help.', category = 'context', retryable = false) => new CliFailure(message, 'PLATFORM_ACCESS_FAILED', nextAction, category, retryable);
|
|
9
9
|
export function platformOrigin(value = 'https://platform.anhedral.com') {
|
|
@@ -46,7 +46,6 @@ async function safeDirectory(path, privateMode = true) {
|
|
|
46
46
|
throw platformFailure('State directory must be owned by you with mode 0700.');
|
|
47
47
|
}
|
|
48
48
|
export async function readPrivate(path) {
|
|
49
|
-
// Validate every existing ancestor before following it.
|
|
50
49
|
for (let p = dirname(path);; p = dirname(p)) {
|
|
51
50
|
const info = await lstat(p).catch(() => null);
|
|
52
51
|
if (info?.isSymbolicLink() || (info && !info.isDirectory()))
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { commandArguments } from '../cli-arguments.js';
|
|
3
|
+
import type { CliFailure } from '../cli-errors.js';
|
|
4
|
+
import type { cliLinkSchema } from '../contracts/cli-transport.js';
|
|
5
|
+
import type { PlatformFailureCategory } from './state.js';
|
|
6
|
+
export type PlatformRequest = (path: string, method: string, body?: unknown, token?: string, team?: string) => Promise<unknown>;
|
|
7
|
+
export type PlatformFailure = (message: string, category?: PlatformFailureCategory, retryable?: boolean, nextAction?: string) => CliFailure;
|
|
8
|
+
export type ProjectOperation = {
|
|
9
|
+
options: ReturnType<typeof commandArguments>;
|
|
10
|
+
origin: string;
|
|
11
|
+
actor: {
|
|
12
|
+
principalId: string;
|
|
13
|
+
teamId?: string | null;
|
|
14
|
+
};
|
|
15
|
+
token: string;
|
|
16
|
+
stateDir: string;
|
|
17
|
+
linkPath: string;
|
|
18
|
+
request: PlatformRequest;
|
|
19
|
+
emit: (result: unknown) => void;
|
|
20
|
+
platformFailure: PlatformFailure;
|
|
21
|
+
};
|
|
22
|
+
export type SourceOperation = ProjectOperation & {
|
|
23
|
+
link: z.infer<typeof cliLinkSchema>;
|
|
24
|
+
uploadPath: string;
|
|
25
|
+
root: string;
|
|
26
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { SOURCE_LIMITS, sourceUploadInputSchema, sourceUploadReceiptSchema, } from '../contracts/cli-transport.js';
|
|
3
|
+
import { packageSource } from './source.js';
|
|
4
|
+
import { uploadState } from './state-schema.js';
|
|
5
|
+
import { readPrivate, writePrivate } from './state.js';
|
|
6
|
+
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
export async function runSourceUpload({ options, origin, actor, token, link, uploadPath, root, request, emit, platformFailure, }) {
|
|
8
|
+
const state = uploadState.safeParse(await readPrivate(uploadPath));
|
|
9
|
+
const checkedState = state.success &&
|
|
10
|
+
state.data.origin === origin &&
|
|
11
|
+
state.data.principalId === actor.principalId &&
|
|
12
|
+
state.data.input.projectId === link.projectId &&
|
|
13
|
+
state.data.input.teamId === link.teamId
|
|
14
|
+
? state.data
|
|
15
|
+
: null;
|
|
16
|
+
if (options.positional[0] === 'status') {
|
|
17
|
+
if (!checkedState?.uploadId)
|
|
18
|
+
throw platformFailure('No resumable upload is saved for this project.');
|
|
19
|
+
emit(sourceUploadReceiptSchema.parse(await request(`/uploads/${checkedState.uploadId}`, 'GET', undefined, token, link.teamId)));
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const source = await packageSource(root), archiveDigest = hash(source.archive);
|
|
23
|
+
if (checkedState && checkedState.input.archiveDigest !== archiveDigest && !options.has('--new'))
|
|
24
|
+
throw platformFailure('Source changed since the saved upload. Restore those files or explicitly use source upload --new.');
|
|
25
|
+
const chunks = Array.from({ length: Math.ceil(source.archive.length / SOURCE_LIMITS.chunkBytes) }, (_, i) => source.archive.subarray(i * SOURCE_LIMITS.chunkBytes, (i + 1) * SOURCE_LIMITS.chunkBytes));
|
|
26
|
+
const input = sourceUploadInputSchema.parse({
|
|
27
|
+
protocol: 1,
|
|
28
|
+
requestId: checkedState && !options.has('--new') ? checkedState.input.requestId : randomUUID(),
|
|
29
|
+
projectId: link.projectId,
|
|
30
|
+
teamId: link.teamId,
|
|
31
|
+
archiveDigest,
|
|
32
|
+
archiveBytes: source.archive.length,
|
|
33
|
+
inventoryDigest: source.inventoryDigest,
|
|
34
|
+
cliVersion: source.cliVersion,
|
|
35
|
+
chunks: chunks.map(hash),
|
|
36
|
+
});
|
|
37
|
+
// Persist the request identity before the first network mutation, including lost responses.
|
|
38
|
+
const local = { origin, principalId: actor.principalId, input };
|
|
39
|
+
await writePrivate(uploadPath, local);
|
|
40
|
+
const receipt = sourceUploadReceiptSchema.parse(await request('/uploads', 'POST', input, token, link.teamId));
|
|
41
|
+
if (receipt.projectId !== link.projectId ||
|
|
42
|
+
receipt.requestId !== input.requestId ||
|
|
43
|
+
receipt.archiveDigest !== input.archiveDigest ||
|
|
44
|
+
receipt.inventoryDigest !== input.inventoryDigest)
|
|
45
|
+
throw platformFailure('Upload receipt identity differs.');
|
|
46
|
+
await writePrivate(uploadPath, { ...local, uploadId: receipt.id });
|
|
47
|
+
if (receipt.state === 'cancelled')
|
|
48
|
+
throw platformFailure('Upload was cancelled. Start source upload --new.');
|
|
49
|
+
if (receipt.state !== 'sealed') {
|
|
50
|
+
for (let i = 0; i < chunks.length; i++)
|
|
51
|
+
if (!receipt.received.includes(i))
|
|
52
|
+
await request(`/uploads/${receipt.id}/chunks/${i}`, 'PUT', chunks[i], token, link.teamId);
|
|
53
|
+
}
|
|
54
|
+
const complete = sourceUploadReceiptSchema.parse(await request(`/uploads/${receipt.id}/complete`, 'POST', {}, token, link.teamId));
|
|
55
|
+
if (complete.id !== receipt.id ||
|
|
56
|
+
complete.sourceRevision !== archiveDigest ||
|
|
57
|
+
complete.state !== 'sealed')
|
|
58
|
+
throw platformFailure('Source completion was not sealed. Resume this upload.');
|
|
59
|
+
emit({ ...complete, hostedAdmission: false });
|
|
60
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Internal synchronous-runner companion. Owns only its spawned command tree.
|
|
2
2
|
import { spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import { writeFileSync } from 'node:fs';
|
|
4
|
-
import { readBoundedFile } from '
|
|
4
|
+
import { readBoundedFile } from '../bounded-file.js';
|
|
5
5
|
const [configuration, resultFile] = process.argv.slice(2);
|
|
6
6
|
if (!configuration || !resultFile)
|
|
7
7
|
throw Error('Command runner requires private input and result files.');
|
package/dist/registry/usage.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CapabilityEditor } from '../
|
|
2
|
-
import type { Capability } from '../
|
|
1
|
+
import { CapabilityEditor } from '../composition/editor.js';
|
|
2
|
+
import type { Capability } from '../composition/catalog.js';
|
|
3
3
|
/** The launch foundation is a web service; Hono owns application services and data. */
|
|
4
4
|
export declare function scaffoldTanstack(root: string, name: string): void;
|
|
5
5
|
/** One-time source upgrade, planned in the same bounded overlay as each addition. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import { ANHEDRAL_STACK_DEPENDENCIES, WEB_DEPENDENCIES } from '../dependencies.js';
|
|
3
|
-
import { CapabilityEditor, fingerprint } from '../
|
|
3
|
+
import { CapabilityEditor, fingerprint } from '../composition/editor.js';
|
|
4
4
|
import { resourceName } from '../render.js';
|
|
5
|
-
import { json, put, workerConfig } from '
|
|
5
|
+
import { json, put, workerConfig } from './files.js';
|
|
6
6
|
const template = (name) => readFileSync(new URL(`../../assets/launch/${name}`, import.meta.url), 'utf8');
|
|
7
7
|
/** The launch foundation is a web service; Hono owns application services and data. */
|
|
8
8
|
export function scaffoldTanstack(root, name) {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { lstatSync } from 'node:fs';
|
|
2
|
+
export declare function lstatIfPresent(target: string): ReturnType<typeof lstatSync> | null;
|
|
3
|
+
export declare function syncDirectory(directory: string): void;
|
|
4
|
+
export declare function syncEntryRecursively(target: string): void;
|
|
5
|
+
export declare function renameDurably(source: string, target: string, root: string): void;
|
|
6
|
+
export declare function removeEntryDurably(target: string): void;
|
|
7
|
+
export declare function pathEntryExists(target: string): boolean;
|
|
8
|
+
export declare function fingerprintEntry(target: string): string;
|
|
@@ -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 '
|
|
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;
|