@wirecat/cli-core 0.704.0 → 0.706.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/CHANGELOG.md +116 -0
- package/dist/cli/bot/api-http.d.ts +8 -2
- package/dist/cli/bot/api-http.js +20 -4
- package/dist/cli/bot/api.d.ts +8 -0
- package/dist/cli/bot/api.js +31 -3
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/index.d.ts +4 -4
- package/dist/cli/index.js +3 -3
- package/dist/cli/messenger/lacks.js +3 -0
- package/dist/cli/messenger/messages-delete-command.js +30 -25
- package/dist/cli/messenger/messages-edit-command.js +2 -0
- package/dist/cli/messenger/messages-scheduled-command.js +110 -4
- package/dist/cli/messenger/store-maintenance-command.js +6 -2
- package/dist/cli/service-api-call.d.ts +13 -3
- package/dist/cli/service-api-call.js +19 -9
- package/dist/cli/service-api-manifest.d.ts +11 -2
- package/dist/cli/service-api-manifest.js +30 -9
- package/dist/cli/service-api.d.ts +14 -6
- package/dist/cli/service-api.js +198 -52
- package/dist/cli/token-session.d.ts +5 -2
- package/dist/cli/token-session.js +13 -4
- package/dist/content/cli/index.d.ts +33 -0
- package/dist/content/cli/index.js +368 -0
- package/dist/content/index.d.ts +8 -0
- package/dist/content/index.js +7 -0
- package/dist/content/manifest/index.d.ts +4 -0
- package/dist/content/manifest/index.js +4 -0
- package/dist/content/manifest/manifest.d.ts +92 -0
- package/dist/content/manifest/manifest.js +137 -0
- package/dist/content/manifest/map.d.ts +25 -0
- package/dist/content/manifest/map.js +94 -0
- package/dist/content/manifest/source.d.ts +41 -0
- package/dist/content/manifest/source.js +288 -0
- package/dist/content/manifest/writer.d.ts +26 -0
- package/dist/content/manifest/writer.js +133 -0
- package/dist/content/source.d.ts +64 -0
- package/dist/content/source.js +2 -0
- package/dist/content/sync.d.ts +61 -0
- package/dist/content/sync.js +387 -0
- package/dist/content/testing/index.d.ts +4 -0
- package/dist/content/testing/index.js +4 -0
- package/dist/content/testing/source-contract.d.ts +38 -0
- package/dist/content/testing/source-contract.js +274 -0
- package/dist/content/testing/source.d.ts +55 -0
- package/dist/content/testing/source.js +276 -0
- package/dist/content/testing/sync-contract.d.ts +10 -0
- package/dist/content/testing/sync-contract.js +172 -0
- package/dist/content/testing/write-contract.d.ts +14 -0
- package/dist/content/testing/write-contract.js +102 -0
- package/dist/content/writer.d.ts +64 -0
- package/dist/content/writer.js +38 -0
- package/dist/content/writes.d.ts +58 -0
- package/dist/content/writes.js +129 -0
- package/dist/documents/file-mirror-model.d.ts +3 -1
- package/dist/documents/index.d.ts +3 -3
- package/dist/documents/index.js +1 -1
- package/dist/domain/content.d.ts +102 -0
- package/dist/domain/content.js +11 -0
- package/dist/entities/index.d.ts +8 -2
- package/dist/entities/index.js +4 -2
- package/dist/entities/message-change.d.ts +240 -0
- package/dist/entities/message-change.js +6 -0
- package/dist/errors/reasons.js +14 -0
- package/dist/kit/fake.d.ts +2 -2
- package/dist/kit/fake.js +21 -0
- package/dist/manifest/index.d.ts +21 -7
- package/dist/manifest/index.js +7 -4
- package/dist/mcp/surface.js +6 -3
- package/dist/ports/messenger.d.ts +20 -1
- package/dist/sends/permissions.js +11 -1
- package/dist/services/documents/mirrors.d.ts +13 -1
- package/dist/services/documents/mirrors.js +12 -3
- package/dist/services/files/mirror.d.ts +20 -8
- package/dist/services/files/mirror.js +84 -27
- package/dist/services/files/versions.d.ts +17 -7
- package/dist/services/files/versions.js +56 -21
- package/dist/services/messages.d.ts +31 -0
- package/dist/services/messages.js +62 -0
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/recover.js +2 -0
- package/dist/store/sqlite/account-purge.js +7 -0
- package/dist/store/sqlite/content.d.ts +100 -0
- package/dist/store/sqlite/content.js +375 -0
- package/dist/store/sqlite/entity-types.d.ts +1 -0
- package/dist/store/sqlite/entity-types.js +1 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +26 -0
- package/dist/store/sqlite/schema.d.ts +1140 -0
- package/dist/store/sqlite/schema.js +100 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +12 -4
package/dist/manifest/index.js
CHANGED
|
@@ -11,6 +11,7 @@ export const CLI_CATEGORIES = [
|
|
|
11
11
|
"calendar",
|
|
12
12
|
"crm",
|
|
13
13
|
"tracker",
|
|
14
|
+
"content",
|
|
14
15
|
"other",
|
|
15
16
|
];
|
|
16
17
|
/** Types the config in the editor; it returns what it is given. */
|
|
@@ -64,12 +65,14 @@ const schema = v.strictObject({
|
|
|
64
65
|
owner: v.pipe(v.string(), v.regex(/^[A-Za-z0-9](?:-?[A-Za-z0-9]){0,38}$/, "a GitHub owner")),
|
|
65
66
|
}),
|
|
66
67
|
spec: v.strictObject({
|
|
67
|
-
kind: v.picklist(["openapi", "swagger", "graphql"]),
|
|
68
|
+
kind: v.picklist(["openapi", "swagger", "graphql", "wp-json"]),
|
|
68
69
|
from: httpsUrl,
|
|
70
|
+
version: v.optional(v.pipe(v.string(), v.regex(/^\d+\.\d+(\.\d+)?$/, "a version such as 6.9.4"))),
|
|
69
71
|
}),
|
|
70
72
|
auth: v.variant("preset", [
|
|
71
73
|
v.strictObject({ preset: v.literal("none") }),
|
|
72
74
|
v.strictObject({ preset: v.literal("token"), verify }),
|
|
75
|
+
v.strictObject({ preset: v.literal("app-password"), verify }),
|
|
73
76
|
v.strictObject({
|
|
74
77
|
preset: v.literal("oauth2-pkce"),
|
|
75
78
|
verify,
|
|
@@ -89,7 +92,7 @@ const schema = v.strictObject({
|
|
|
89
92
|
hooks: v.optional(v.pipe(v.string(), v.regex(/^\.\/([^\s]*\/)?[^/\s.][^/\s]*\.[cm]?[jt]s$/, "a module in the project, such as ./src/hooks.ts"), v.check((text) => !/\.d\.[cm]?ts$/.test(text), "a module, not a .d.ts declaration file"), v.check((text) => !text.split(/[\\/]/).includes(".."), "a module in the project, without .."))),
|
|
90
93
|
});
|
|
91
94
|
/**
|
|
92
|
-
* The config checked against its shape; every error names where it is. A crm or
|
|
95
|
+
* The config checked against its shape; every error names where it is. A crm, tracker or content CLI needs its source. `source` comes back
|
|
93
96
|
* unchecked: `parseCrmManifest` checks it against the generated API.
|
|
94
97
|
*/
|
|
95
98
|
export const parseCliConfig = (input) => {
|
|
@@ -111,9 +114,9 @@ export const parseCliConfig = (input) => {
|
|
|
111
114
|
// Typed, not cast: a field CliConfig needs that the schema lacks or types otherwise fails to compile (not the reverse).
|
|
112
115
|
const output = parsed.output;
|
|
113
116
|
const config = output;
|
|
114
|
-
const sourced = config.category === "crm" || config.category === "tracker";
|
|
117
|
+
const sourced = config.category === "crm" || config.category === "tracker" || config.category === "content";
|
|
115
118
|
if (!sourced && config.source)
|
|
116
|
-
throw new CliError("configuration_error", "wirecat.config: source: only a crm or
|
|
119
|
+
throw new CliError("configuration_error", "wirecat.config: source: only a crm, tracker or content CLI reads a source yet", {
|
|
117
120
|
reason: "manifest.invalid",
|
|
118
121
|
});
|
|
119
122
|
if (sourced && !config.source)
|
package/dist/mcp/surface.js
CHANGED
|
@@ -80,7 +80,7 @@ export const search = (commands, query) => {
|
|
|
80
80
|
.filter((word) => word.length > 1 && !STOP_WORDS.has(word))
|
|
81
81
|
.map(stem)),
|
|
82
82
|
];
|
|
83
|
-
return all
|
|
83
|
+
return (all
|
|
84
84
|
.map((entry) => {
|
|
85
85
|
const fields = fieldsOf(entry[0], entry[1]);
|
|
86
86
|
const weights = words.map((word) => fields.reduce((best, [weight, known]) => (known.some((one) => sameWord(word, one)) ? Math.max(best, weight) : best), 0));
|
|
@@ -89,8 +89,11 @@ export const search = (commands, query) => {
|
|
|
89
89
|
return { entry, matched, rank: (exact ? 1000 : 0) + matched * 10 + weights.reduce((a, b) => a + b, 0) };
|
|
90
90
|
})
|
|
91
91
|
.filter(({ matched, rank }) => matched > 0 || rank >= 1000)
|
|
92
|
-
|
|
93
|
-
.
|
|
92
|
+
// A tie goes to the shorter name, which holds less the task did not ask for: `messages send` first.
|
|
93
|
+
.sort((a, b) => b.rank - a.rank ||
|
|
94
|
+
wordsOf(a.entry[0]).length - wordsOf(b.entry[0]).length ||
|
|
95
|
+
a.entry[0].localeCompare(b.entry[0]))
|
|
96
|
+
.map(({ entry }) => entry));
|
|
94
97
|
};
|
|
95
98
|
const nearest = (commands, asked) => {
|
|
96
99
|
const words = normal(asked).split(" ");
|
|
@@ -485,6 +485,25 @@ export interface ScheduledMessages {
|
|
|
485
485
|
/** Messages waiting to be sent later in a chat, soonest first, each with `scheduledFor`. */
|
|
486
486
|
scheduled(chat: string): Promise<Message[]>;
|
|
487
487
|
}
|
|
488
|
+
/**
|
|
489
|
+
* Changes to what `scheduled` lists. An id here is one `scheduled` gave: a scheduled message has ids of its own, and
|
|
490
|
+
* the same number in the chat's history is another, already sent message.
|
|
491
|
+
*/
|
|
492
|
+
export interface ScheduledChanges {
|
|
493
|
+
/** Takes them off the list unsent; nobody can get them back. */
|
|
494
|
+
cancelScheduled(chatId: Id, ids: Id[]): Promise<void>;
|
|
495
|
+
/**
|
|
496
|
+
* New text, a new time, or both; the answer is the message as it now waits. `at` is always given, the current time
|
|
497
|
+
* when only the text changes, as the messenger may take the id for a sent message's without it.
|
|
498
|
+
*/
|
|
499
|
+
editScheduled(chatId: Id, id: Id, change: {
|
|
500
|
+
text?: string;
|
|
501
|
+
formatting?: TextSpan[];
|
|
502
|
+
at: string;
|
|
503
|
+
}): Promise<Message>;
|
|
504
|
+
/** Sends them now; the answer is the messages as sent, with their new ids. */
|
|
505
|
+
sendScheduled(chatId: Id, ids: Id[]): Promise<Message[]>;
|
|
506
|
+
}
|
|
488
507
|
/** Who is in a group, who runs it, and who came and went. */
|
|
489
508
|
export interface GroupModeration {
|
|
490
509
|
/**
|
|
@@ -703,7 +722,7 @@ export interface AccountHealth {
|
|
|
703
722
|
* be held to all of it. A method added from now on goes into a group, never the core, and returns a
|
|
704
723
|
* promise: the wrappers time and pass it through without being told about it (`throughWrapper`).
|
|
705
724
|
*/
|
|
706
|
-
export interface MessengerAdapter extends MessengerCore, Partial<MarkdownFormatting>, Partial<HtmlFormatting>, Partial<ServerReads>, Partial<PersonProfiles>, Partial<ChatReading>, Partial<SenderSearch>, Partial<MessageSearch>, Partial<MessageEditing>, Partial<MessagePins>, Partial<MessageStars>, Partial<MessageReactions>, Partial<ReadState>, Partial<TopicReadState>, Partial<MessagePolls>, Partial<MessageButtons>, Partial<BotChats>, Partial<ThreadAddressing>, Partial<TopicHistory>, Partial<ForumControl>, Partial<TopicEditing>, Partial<LiveUpdates>, Partial<PassiveUpdates>, Partial<PushedHistory>, Partial<MessageMedia>, Partial<ScheduledMessages>, Partial<ChannelComments>, Partial<MessagePermalinks>, Partial<SenderIdentities>, Partial<GroupModeration>, Partial<AccountTools>, Partial<ProfilePhotos>, Partial<GroupAdmin>, Partial<JoinRequests>, Partial<InviteLinks>, Partial<ChatFolders>, Partial<ContactBook>, Partial<AccountEditing>, Partial<AccountRecords>, Partial<AccountSettings>, Partial<ChatDeletion>, Partial<AccountHealth>, Partial<OfficialStats> {
|
|
725
|
+
export interface MessengerAdapter extends MessengerCore, Partial<MarkdownFormatting>, Partial<HtmlFormatting>, Partial<ServerReads>, Partial<PersonProfiles>, Partial<ChatReading>, Partial<SenderSearch>, Partial<MessageSearch>, Partial<MessageEditing>, Partial<MessagePins>, Partial<MessageStars>, Partial<MessageReactions>, Partial<ReadState>, Partial<TopicReadState>, Partial<MessagePolls>, Partial<MessageButtons>, Partial<BotChats>, Partial<ThreadAddressing>, Partial<TopicHistory>, Partial<ForumControl>, Partial<TopicEditing>, Partial<LiveUpdates>, Partial<PassiveUpdates>, Partial<PushedHistory>, Partial<MessageMedia>, Partial<ScheduledMessages>, Partial<ScheduledChanges>, Partial<ChannelComments>, Partial<MessagePermalinks>, Partial<SenderIdentities>, Partial<GroupModeration>, Partial<AccountTools>, Partial<ProfilePhotos>, Partial<GroupAdmin>, Partial<JoinRequests>, Partial<InviteLinks>, Partial<ChatFolders>, Partial<ContactBook>, Partial<AccountEditing>, Partial<AccountRecords>, Partial<AccountSettings>, Partial<ChatDeletion>, Partial<AccountHealth>, Partial<OfficialStats> {
|
|
707
726
|
}
|
|
708
727
|
type Method = (...args: never[]) => unknown;
|
|
709
728
|
/**
|
|
@@ -2,7 +2,14 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
/** What a profile may do with one command path — the standard's "Permissions". */
|
|
3
3
|
export const LEVELS = ["deny", "readonly", "ask", "allow"];
|
|
4
4
|
/** The deletions nobody gets back: the word that skips their question is `--allow-dangerous`, never `--yes`. */
|
|
5
|
-
const DANGEROUS = new Set([
|
|
5
|
+
const DANGEROUS = new Set([
|
|
6
|
+
"messages.delete",
|
|
7
|
+
"messages.scheduled.cancel",
|
|
8
|
+
"bot.messages.delete",
|
|
9
|
+
"topics.delete",
|
|
10
|
+
"chats.delete",
|
|
11
|
+
"chats.clear",
|
|
12
|
+
]);
|
|
6
13
|
/** Deleting has its own word for "yes": the flag a person has to mean, not a habit (max-cli `NEED-238`). */
|
|
7
14
|
export const skipFlagFor = (key) => DANGEROUS.has(key) ? "--allow-dangerous" : "--yes";
|
|
8
15
|
/** Only what cannot be undone asks; the tool is meant to work without questions (owner, NEED-460). */
|
|
@@ -268,6 +275,9 @@ const NAMED_WRITE_KEYS = [
|
|
|
268
275
|
"messages.sync-first",
|
|
269
276
|
"messages.server-search",
|
|
270
277
|
"messages.press",
|
|
278
|
+
"messages.scheduled.cancel",
|
|
279
|
+
"messages.scheduled.edit",
|
|
280
|
+
"messages.scheduled.send",
|
|
271
281
|
"chats.start",
|
|
272
282
|
"chats.app",
|
|
273
283
|
"stats.messages.counters.sync",
|
|
@@ -47,6 +47,16 @@ interface MirrorLock {
|
|
|
47
47
|
assertHeld(): void;
|
|
48
48
|
release(): Promise<void> | void;
|
|
49
49
|
}
|
|
50
|
+
/** A sync lock: one as `acquireLock` returns it (`held()`), or one with a synchronous `assertHeld`. */
|
|
51
|
+
export type HeldLock = {
|
|
52
|
+
release(): Promise<void> | void;
|
|
53
|
+
} & ({
|
|
54
|
+
assertHeld(): void;
|
|
55
|
+
} | {
|
|
56
|
+
held(): Promise<boolean>;
|
|
57
|
+
});
|
|
58
|
+
/** The check a write runs first: it throws once the lock is no longer this process's. */
|
|
59
|
+
export declare const heldCheck: (lock: HeldLock) => () => Promise<void>;
|
|
50
60
|
/**
|
|
51
61
|
* Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
|
|
52
62
|
* the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
|
|
@@ -56,7 +66,9 @@ export declare const eachMirror: <R extends {
|
|
|
56
66
|
errors: unknown[];
|
|
57
67
|
missing?: unknown[];
|
|
58
68
|
unknown?: unknown[];
|
|
59
|
-
}
|
|
69
|
+
}, L extends {
|
|
70
|
+
release(): Promise<void> | void;
|
|
71
|
+
}>(mirrors: Mirror[], lock: () => Promise<L>, remote: string, sync: (mirror: Mirror, held: L) => Promise<R>) => Promise<{
|
|
60
72
|
items: (Omit<{
|
|
61
73
|
id: string;
|
|
62
74
|
path: string;
|
|
@@ -99,6 +99,15 @@ export const conflictReport = (conflict, remote) => ({
|
|
|
99
99
|
...(conflict.localSize !== undefined ? { local_size: conflict.localSize } : {}),
|
|
100
100
|
...(conflict.remoteSize !== undefined ? { [`${remote}_size`]: conflict.remoteSize } : {}),
|
|
101
101
|
});
|
|
102
|
+
/** The check a write runs first: it throws once the lock is no longer this process's. */
|
|
103
|
+
export const heldCheck = (lock) => async () => {
|
|
104
|
+
if ("assertHeld" in lock)
|
|
105
|
+
return lock.assertHeld();
|
|
106
|
+
if (!(await lock.held()))
|
|
107
|
+
throw new CliError("provider_unavailable", "the mirrors' sync lock was lost; sync again", {
|
|
108
|
+
reason: "profile.busy",
|
|
109
|
+
});
|
|
110
|
+
};
|
|
102
111
|
/**
|
|
103
112
|
* Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
|
|
104
113
|
* the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
|
|
@@ -108,7 +117,7 @@ export const eachMirror = async (mirrors, lock, remote, sync) => {
|
|
|
108
117
|
const results = [];
|
|
109
118
|
try {
|
|
110
119
|
for (const mirror of mirrors)
|
|
111
|
-
results.push({ id: mirror.id, path: mirror.path, ...(await sync(mirror,
|
|
120
|
+
results.push({ id: mirror.id, path: mirror.path, ...(await sync(mirror, held)) });
|
|
112
121
|
}
|
|
113
122
|
finally {
|
|
114
123
|
await held.release();
|
|
@@ -125,7 +134,7 @@ export const eachMirror = async (mirrors, lock, remote, sync) => {
|
|
|
125
134
|
};
|
|
126
135
|
};
|
|
127
136
|
/** Syncs each mirror both ways, as `eachMirror` runs them. */
|
|
128
|
-
export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror,
|
|
137
|
+
export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, held) => pushDocuments({
|
|
129
138
|
root: mirror.path,
|
|
130
139
|
folder: mirror.folder,
|
|
131
140
|
target: options.target,
|
|
@@ -136,6 +145,6 @@ export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock
|
|
|
136
145
|
guard: options.guard,
|
|
137
146
|
operationId: options.operationId,
|
|
138
147
|
errorOf: options.errorOf,
|
|
139
|
-
assertHeld,
|
|
148
|
+
assertHeld: () => held.assertHeld(),
|
|
140
149
|
...(options.signal ? { signal: options.signal } : {}),
|
|
141
150
|
}));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import type { FileMirrorStatePort, FileStepKind, FileTarget } from "../../documents/file-mirror-model.js";
|
|
3
3
|
import type { Keep } from "../../documents/push-model.js";
|
|
4
|
-
import { type Mirror } from "../documents/mirrors.js";
|
|
4
|
+
import { type HeldLock, type Mirror } from "../documents/mirrors.js";
|
|
5
5
|
import { type MirrorAction, type PushConflict } from "../documents/push.js";
|
|
6
6
|
import type { FileVersions } from "./versions.js";
|
|
7
7
|
type Side = "local" | "remote";
|
|
@@ -12,7 +12,10 @@ export interface FileMirrorOptions {
|
|
|
12
12
|
folder: string;
|
|
13
13
|
target: FileTarget;
|
|
14
14
|
state: FileMirrorStatePort;
|
|
15
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* Keeps every content before the sync overwrites or deletes it (a remote one an upload replaces is downloaded first
|
|
17
|
+
* unless the store has it; a remote deletion leaves it in the provider's trash), and logs each change.
|
|
18
|
+
*/
|
|
16
19
|
versions: FileVersions;
|
|
17
20
|
principal: string;
|
|
18
21
|
/** Settles conflicts; without it they are reported and left. */
|
|
@@ -27,6 +30,8 @@ export interface FileMirrorOptions {
|
|
|
27
30
|
repin?: boolean;
|
|
28
31
|
/** How the app names the remote side; it ends a conflict copy's name. */
|
|
29
32
|
remote: string;
|
|
33
|
+
/** How the app's commands are named in the deletion guard's and the repin message; the defaults are flags. */
|
|
34
|
+
hints?: Partial<MirrorHints>;
|
|
30
35
|
/** Runs one write behind the app's permission checks; `side` says which side it changes. */
|
|
31
36
|
guard<T>(attempt: {
|
|
32
37
|
action: MirrorAction;
|
|
@@ -36,11 +41,20 @@ export interface FileMirrorOptions {
|
|
|
36
41
|
}, act: () => Promise<T>): Promise<T>;
|
|
37
42
|
operationId(): string;
|
|
38
43
|
errorOf(error: unknown): CliError;
|
|
39
|
-
|
|
44
|
+
/** Throws once the sync lock is lost; checked before every write. */
|
|
45
|
+
assertHeld(): void | Promise<void>;
|
|
40
46
|
signal?: AbortSignal;
|
|
41
47
|
maxFiles?: number;
|
|
42
48
|
now?(): number;
|
|
43
49
|
}
|
|
50
|
+
export interface MirrorHints {
|
|
51
|
+
/** How to preview a run: `--dry-run`. */
|
|
52
|
+
preview: string;
|
|
53
|
+
/** How to record a replaced root again: `--repin`. */
|
|
54
|
+
repin: string;
|
|
55
|
+
/** How to allow a run's deletions: `explicitly`, as in "allow them explicitly". */
|
|
56
|
+
allowDeletions: string;
|
|
57
|
+
}
|
|
44
58
|
export interface FileStep {
|
|
45
59
|
kind: FileStepKind;
|
|
46
60
|
path: string;
|
|
@@ -106,14 +120,12 @@ export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mir
|
|
|
106
120
|
* at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
|
|
107
121
|
*/
|
|
108
122
|
export declare const fileRemoteChanges: (target: FileTarget) => (signal: AbortSignal) => Promise<string[] | "all">;
|
|
109
|
-
export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "guard" | "operationId" | "errorOf" | "signal"> {
|
|
123
|
+
export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal"> {
|
|
110
124
|
mirrors: Mirror[];
|
|
111
125
|
stateOf(mirror: Mirror): FileMirrorStatePort;
|
|
112
126
|
versionsOf(mirror: Mirror): FileVersions;
|
|
113
|
-
lock
|
|
114
|
-
|
|
115
|
-
release(): Promise<void> | void;
|
|
116
|
-
}>;
|
|
127
|
+
/** The sync lock, as `acquireLock` returns it or with a synchronous `assertHeld`. */
|
|
128
|
+
lock(): Promise<HeldLock>;
|
|
117
129
|
/** How the app names the remote side in reports and conflict copies. */
|
|
118
130
|
remote: string;
|
|
119
131
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { mkdir, rm, stat, unlink } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, posix } from "node:path";
|
|
4
|
-
import { CliError } from "@wirecat/cli-base";
|
|
4
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
5
5
|
import * as v from "valibot";
|
|
6
|
-
import { eachMirror, jsonState } from "../documents/mirrors.js";
|
|
6
|
+
import { eachMirror, heldCheck, jsonState } from "../documents/mirrors.js";
|
|
7
7
|
import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
|
|
8
|
+
const HINTS = { preview: "--dry-run", repin: "--repin", allowDeletions: "explicitly" };
|
|
8
9
|
/**
|
|
9
10
|
* A run that would delete more than `ALWAYS_DELETED` files and more than `MAX_DELETIONS` files or `MAX_DELETED_SHARE`
|
|
10
11
|
* of the mirror stops before writing.
|
|
@@ -128,6 +129,21 @@ const scan = async (root, entries, maxFiles) => {
|
|
|
128
129
|
};
|
|
129
130
|
/** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
|
|
130
131
|
const mirrored = (files) => files.filter((file) => !file.path.split("/").some(skippedName));
|
|
132
|
+
/** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
|
|
133
|
+
const linkFree = (root, path) => assertNoLink(root, path).then(() => true, (error) => {
|
|
134
|
+
if (isCliError(error) && error.details?.reason === "mirror.symlink")
|
|
135
|
+
return false;
|
|
136
|
+
throw error;
|
|
137
|
+
});
|
|
138
|
+
/** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
|
|
139
|
+
const whole = async (absolute, hashes) => {
|
|
140
|
+
try {
|
|
141
|
+
return hashes.includes((await hashFile(absolute)).sha256);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
return error.code === "ENOENT";
|
|
145
|
+
}
|
|
146
|
+
};
|
|
131
147
|
/** True when `path` is `link` or lies under it. */
|
|
132
148
|
const under = (path, link) => path === link || path.startsWith(`${link}/`);
|
|
133
149
|
/**
|
|
@@ -139,6 +155,7 @@ const under = (path, link) => path === link || path.startsWith(`${link}/`);
|
|
|
139
155
|
*/
|
|
140
156
|
export const syncFileMirror = async (options) => {
|
|
141
157
|
const { root, folder, target, principal, keep, signal, versions } = options;
|
|
158
|
+
const hints = { ...HINTS, ...options.hints };
|
|
142
159
|
const now = options.now ?? Date.now;
|
|
143
160
|
if (signal?.aborted)
|
|
144
161
|
throw new CliError("cancelled", "sync was cancelled");
|
|
@@ -172,7 +189,8 @@ export const syncFileMirror = async (options) => {
|
|
|
172
189
|
: localReplaced && !repin
|
|
173
190
|
? problem("local", "confirmation_required", "the local folder was replaced by another one", true)
|
|
174
191
|
: Object.keys(state.entries).length > 0 && !local.size
|
|
175
|
-
? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive"
|
|
192
|
+
? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive. Mount it, or if the files were really " +
|
|
193
|
+
"deleted, add a file to the folder or remove the mirror's state to start over")
|
|
176
194
|
: undefined;
|
|
177
195
|
const refused = rootProblem ? [] : (listed?.files ?? []).filter((file) => !safePath(file.path));
|
|
178
196
|
const refusedIds = new Set(refused.map((file) => file.id));
|
|
@@ -218,7 +236,8 @@ export const syncFileMirror = async (options) => {
|
|
|
218
236
|
path: ".",
|
|
219
237
|
code,
|
|
220
238
|
message: repinnable
|
|
221
|
-
? `${reason}; if it is the right folder now, sync again with
|
|
239
|
+
? `${reason}; if it is the right folder now, sync again with ${hints.repin} to record it ` +
|
|
240
|
+
"(that run deletes nothing)"
|
|
222
241
|
: reason,
|
|
223
242
|
});
|
|
224
243
|
return result;
|
|
@@ -253,7 +272,10 @@ export const syncFileMirror = async (options) => {
|
|
|
253
272
|
const here = local.get(path);
|
|
254
273
|
// Where links fail, a download is copied into place; a crash midway leaves a partial file under the real name,
|
|
255
274
|
// which must be neither sent nor overwritten.
|
|
256
|
-
|
|
275
|
+
const pending = state.pending[path];
|
|
276
|
+
// A replaced file is renamed into place whole; only a new file may be a partial copy.
|
|
277
|
+
const created = pending?.op === "download" && pending.created !== false;
|
|
278
|
+
if (created && here && here.hash !== file?.sha256 && here.hash !== entry?.sha256) {
|
|
257
279
|
cutOff.add(path);
|
|
258
280
|
steps.push({
|
|
259
281
|
kind: "conflict",
|
|
@@ -301,7 +323,8 @@ export const syncFileMirror = async (options) => {
|
|
|
301
323
|
return result;
|
|
302
324
|
}
|
|
303
325
|
if (tooMany && (options.allowDeletions ?? 0) < deletions)
|
|
304
|
-
throw new CliError("confirmation_required", `this sync would delete ${deletions} files;
|
|
326
|
+
throw new CliError("confirmation_required", `this sync would delete ${deletions} files; ` +
|
|
327
|
+
`check them with ${hints.preview} and allow them ${hints.allowDeletions}`, { reason: "mirror.too-many-deletions", deletions });
|
|
305
328
|
if (repin) {
|
|
306
329
|
state.entries = {};
|
|
307
330
|
state.rootId = listed?.rootId;
|
|
@@ -314,7 +337,8 @@ export const syncFileMirror = async (options) => {
|
|
|
314
337
|
state.localRoot ??= { dev: localRoot.dev, ino: localRoot.ino };
|
|
315
338
|
}
|
|
316
339
|
for (const [path, pending] of Object.entries(state.pending)) {
|
|
317
|
-
|
|
340
|
+
const parent = posix.dirname(path);
|
|
341
|
+
if (pending.op === "download" && (parent === "." || (await linkFree(root, parent))))
|
|
318
342
|
await rm(localTemp(join(root, path), tagOf(pending.operationId)), { force: true });
|
|
319
343
|
if (!cutOff.has(path))
|
|
320
344
|
delete state.pending[path];
|
|
@@ -340,8 +364,8 @@ export const syncFileMirror = async (options) => {
|
|
|
340
364
|
for (let up = path; up !== "."; up = posix.dirname(up))
|
|
341
365
|
folders.add(up);
|
|
342
366
|
let lastOperation = "";
|
|
343
|
-
const write = (action, side, path, act, operationId) => {
|
|
344
|
-
options.assertHeld();
|
|
367
|
+
const write = async (action, side, path, act, operationId) => {
|
|
368
|
+
await options.assertHeld();
|
|
345
369
|
lastOperation = operationId ?? options.operationId();
|
|
346
370
|
return options.guard({ action, side, path, operationId: lastOperation }, act);
|
|
347
371
|
};
|
|
@@ -358,7 +382,23 @@ export const syncFileMirror = async (options) => {
|
|
|
358
382
|
};
|
|
359
383
|
save();
|
|
360
384
|
};
|
|
361
|
-
|
|
385
|
+
/**
|
|
386
|
+
* Keeps the remote content an upload will replace, downloaded through the store unless it holds it already.
|
|
387
|
+
* Refused as `mirror.remote-changed` when the remote no longer has the listed content.
|
|
388
|
+
*/
|
|
389
|
+
const keepRemote = async (path, file) => {
|
|
390
|
+
const listed = file.sha256;
|
|
391
|
+
if (versions.has(listed))
|
|
392
|
+
return;
|
|
393
|
+
const kept = await versions.keep((temp) => target.download(remotePath(path), temp, signal));
|
|
394
|
+
if (kept !== listed)
|
|
395
|
+
throw new CliError("conflict", `the ${options.remote} file changed since the listing`, {
|
|
396
|
+
reason: "mirror.remote-changed",
|
|
397
|
+
});
|
|
398
|
+
};
|
|
399
|
+
const upload = async (path, from, expect, created, replaced) => {
|
|
400
|
+
if (replaced)
|
|
401
|
+
await keepRemote(path, replaced);
|
|
362
402
|
for (const up of ancestors(path))
|
|
363
403
|
if (!folders.has(up)) {
|
|
364
404
|
await write("folder", "remote", up, () => target.ensureFolder(remotePath(up), signal));
|
|
@@ -372,7 +412,7 @@ export const syncFileMirror = async (options) => {
|
|
|
372
412
|
path,
|
|
373
413
|
event: created ? "created" : "changed",
|
|
374
414
|
direction: "local-to-remote",
|
|
375
|
-
...("sha256" in expect ? { old: expect.sha256 } : {}),
|
|
415
|
+
...("sha256" in expect ? { old: expect.sha256, from: "remote" } : {}),
|
|
376
416
|
new: from.hash,
|
|
377
417
|
size: from.size,
|
|
378
418
|
});
|
|
@@ -384,16 +424,27 @@ export const syncFileMirror = async (options) => {
|
|
|
384
424
|
*/
|
|
385
425
|
const download = async (path, file, over, recorded = true) => {
|
|
386
426
|
const operationId = options.operationId();
|
|
387
|
-
state.pending[path] = { op: "download", operationId };
|
|
427
|
+
state.pending[path] = { op: "download", operationId, created: !over };
|
|
388
428
|
save(true);
|
|
389
429
|
const absolute = join(root, path);
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
430
|
+
let written;
|
|
431
|
+
let old;
|
|
432
|
+
try {
|
|
433
|
+
await assertNoLink(root, path);
|
|
434
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
435
|
+
old = over ? await versions.keep(absolute) : undefined;
|
|
436
|
+
written = await write(over ? "update" : "create", "local", path, () => replaceLocal(absolute, over?.hash, (temp) => target.download(remotePath(file.path), temp, signal), {
|
|
437
|
+
tag: tagOf(operationId),
|
|
438
|
+
sha256: file.sha256,
|
|
439
|
+
}), operationId);
|
|
440
|
+
}
|
|
441
|
+
catch (error) {
|
|
442
|
+
// A failed copy into place removes what it wrote; should that removal fail too, the marker keeps the partial
|
|
443
|
+
// file from being sent or overwritten.
|
|
444
|
+
if (await whole(absolute, [file.sha256, over?.hash]))
|
|
445
|
+
delete state.pending[path];
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
397
448
|
delete state.pending[path];
|
|
398
449
|
if (!written)
|
|
399
450
|
return false;
|
|
@@ -403,7 +454,7 @@ export const syncFileMirror = async (options) => {
|
|
|
403
454
|
path,
|
|
404
455
|
event: old ? "changed" : "created",
|
|
405
456
|
direction: "remote-to-local",
|
|
406
|
-
...(old ? { old } : {}),
|
|
457
|
+
...(old ? { old, from: "local" } : {}),
|
|
407
458
|
new: written.sha256,
|
|
408
459
|
size: file.size,
|
|
409
460
|
});
|
|
@@ -428,7 +479,7 @@ export const syncFileMirror = async (options) => {
|
|
|
428
479
|
return;
|
|
429
480
|
case "upload":
|
|
430
481
|
if (here)
|
|
431
|
-
await upload(path, here, expectOf(there), !there);
|
|
482
|
+
await upload(path, here, expectOf(there), !there, there);
|
|
432
483
|
return;
|
|
433
484
|
case "download":
|
|
434
485
|
if (there && !(await download(path, there, here)))
|
|
@@ -445,6 +496,9 @@ export const syncFileMirror = async (options) => {
|
|
|
445
496
|
event: "deleted",
|
|
446
497
|
direction: "local-to-remote",
|
|
447
498
|
old: there.sha256,
|
|
499
|
+
from: "remote",
|
|
500
|
+
// Not downloaded to be kept: the provider's trash holds it, and a deleted folder may be large.
|
|
501
|
+
...(versions.has(there.sha256) ? {} : { oldIn: "remote-trash" }),
|
|
448
502
|
size: there.size,
|
|
449
503
|
});
|
|
450
504
|
result.trashed.push({ path, side: "remote" });
|
|
@@ -457,7 +511,7 @@ export const syncFileMirror = async (options) => {
|
|
|
457
511
|
return changedHere(step);
|
|
458
512
|
delete state.entries[path];
|
|
459
513
|
save();
|
|
460
|
-
versions.log({ path, event: "deleted", direction: "remote-to-local", old, size: here.size });
|
|
514
|
+
versions.log({ path, event: "deleted", direction: "remote-to-local", old, from: "local", size: here.size });
|
|
461
515
|
result.trashed.push({ path, side: "local" });
|
|
462
516
|
return;
|
|
463
517
|
}
|
|
@@ -481,6 +535,8 @@ export const syncFileMirror = async (options) => {
|
|
|
481
535
|
const copy = copyName(path, options.remote, date, (name) => local.has(name) || remote.has(name));
|
|
482
536
|
if (!(await download(copy, there, undefined, false)))
|
|
483
537
|
return changedHere(step);
|
|
538
|
+
if ((await versions.keep(join(root, copy))) !== there.sha256)
|
|
539
|
+
await keepRemote(path, there);
|
|
484
540
|
await upload(path, here, expectOf(there), false);
|
|
485
541
|
const { size, mtimeMs } = await stat(join(root, copy));
|
|
486
542
|
const copied = { ...here, path: copy, absolute: join(root, copy), hash: there.sha256, size, mtimeMs };
|
|
@@ -511,7 +567,8 @@ export const syncFileMirror = async (options) => {
|
|
|
511
567
|
else
|
|
512
568
|
result.errors.push({ path: step.path, code: failure.code, message: failure.message });
|
|
513
569
|
// Not retried: the next listing shows whether it landed, and adopts it when it did.
|
|
514
|
-
|
|
570
|
+
// A download's outcome is known: its temporary file is gone and the file is in place or not.
|
|
571
|
+
if (failure.code === "outcome_unknown" && step.kind !== "download")
|
|
515
572
|
state.pending[step.path] = { op: step.kind, operationId: lastOperation };
|
|
516
573
|
}
|
|
517
574
|
}
|
|
@@ -519,7 +576,7 @@ export const syncFileMirror = async (options) => {
|
|
|
519
576
|
finally {
|
|
520
577
|
save(true);
|
|
521
578
|
}
|
|
522
|
-
options.assertHeld();
|
|
579
|
+
await options.assertHeld();
|
|
523
580
|
await versions.prune();
|
|
524
581
|
return result;
|
|
525
582
|
};
|
|
@@ -547,7 +604,7 @@ const stateSchema = v.object({
|
|
|
547
604
|
rootId: v.optional(v.string()),
|
|
548
605
|
localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
|
|
549
606
|
entries: v.record(v.string(), entrySchema),
|
|
550
|
-
pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string() })),
|
|
607
|
+
pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
|
|
551
608
|
});
|
|
552
609
|
/** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
|
|
553
610
|
export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
|
|
@@ -593,11 +650,11 @@ export const fileRemoteChanges = (target) => {
|
|
|
593
650
|
};
|
|
594
651
|
};
|
|
595
652
|
/** Syncs each file mirror under one lock, with one `mirror.partial` issue per mirror left with conflicts or errors. */
|
|
596
|
-
export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror,
|
|
653
|
+
export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, held) => syncFileMirror({
|
|
597
654
|
...options,
|
|
598
655
|
root: mirror.path,
|
|
599
656
|
folder: mirror.folder,
|
|
600
657
|
state: options.stateOf(mirror),
|
|
601
658
|
versions: options.versionsOf(mirror),
|
|
602
|
-
assertHeld,
|
|
659
|
+
assertHeld: heldCheck(held),
|
|
603
660
|
}));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type HeldLock } from "../documents/mirrors.js";
|
|
1
2
|
/** Which way a sync moved a change. */
|
|
2
3
|
export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
|
|
3
4
|
/** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
|
|
@@ -8,6 +9,10 @@ export interface VersionEvent {
|
|
|
8
9
|
direction: VersionDirection;
|
|
9
10
|
/** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
|
|
10
11
|
old?: string;
|
|
12
|
+
/** The side `old` was kept from. */
|
|
13
|
+
from?: "local" | "remote";
|
|
14
|
+
/** Where `old` is when the store does not hold it: a remote deletion leaves it in the provider's trash. */
|
|
15
|
+
oldIn?: "remote-trash";
|
|
11
16
|
new?: string;
|
|
12
17
|
size?: number;
|
|
13
18
|
/** A rename's new path. */
|
|
@@ -18,8 +23,15 @@ export interface FileVersion extends VersionEvent {
|
|
|
18
23
|
available: boolean;
|
|
19
24
|
}
|
|
20
25
|
export interface FileVersions {
|
|
21
|
-
/**
|
|
22
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Copies a content into the store before the sync overwrites or deletes it; returns the hash of what it copied. The
|
|
28
|
+
* source is a local file, or a writer that creates the temporary file it is given, such as a target's `download`.
|
|
29
|
+
* A failure of the store itself, the writer's local file-system errors (a full disk) included, is
|
|
30
|
+
* `mirror.version-not-kept`; the writer's other errors pass through.
|
|
31
|
+
*/
|
|
32
|
+
keep(source: string | ((temp: string) => Promise<void>)): Promise<string>;
|
|
33
|
+
/** Whether the store holds this content. */
|
|
34
|
+
has(sha256: string): boolean;
|
|
23
35
|
log(event: Omit<VersionEvent, "at">): void;
|
|
24
36
|
/** Every event of `path`, oldest first, including renames to or from it. */
|
|
25
37
|
list(path: string): FileVersion[];
|
|
@@ -42,9 +54,7 @@ export declare const fileVersions: (dir: string, now?: () => number) => FileVers
|
|
|
42
54
|
/**
|
|
43
55
|
* Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
|
|
44
56
|
* it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
|
|
45
|
-
* the mirrors' sync lock, so a sync never reads the folder halfway
|
|
57
|
+
* the mirrors' sync lock (as `acquireLock` returns it, or any `assertHeld`), so a sync never reads the folder halfway
|
|
58
|
+
* through.
|
|
46
59
|
*/
|
|
47
|
-
export declare const restoreFileVersion: (root: string, path: string, sha256: string, versions: FileVersions, lock: () => Promise<
|
|
48
|
-
assertHeld(): void;
|
|
49
|
-
release(): Promise<void> | void;
|
|
50
|
-
}>) => Promise<boolean>;
|
|
60
|
+
export declare const restoreFileVersion: (root: string, path: string, sha256: string, versions: FileVersions, lock: () => Promise<HeldLock>) => Promise<boolean>;
|