@open-workspace/create 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +9 -5
  2. package/dist/backup-schema.ts +110 -0
  3. package/dist/workspace.ts +162 -0
  4. package/import/backup-snapshot.ts +254 -0
  5. package/import/backup-source.ts +270 -0
  6. package/import/cli.ts +134 -90
  7. package/import/concurrency.ts +34 -37
  8. package/import/csv.ts +1 -1
  9. package/import/directory/command.ts +293 -72
  10. package/import/directory/google.ts +158 -120
  11. package/import/directory/invitation-file.ts +108 -0
  12. package/import/directory/plan.ts +314 -38
  13. package/import/directory/read.ts +55 -0
  14. package/import/gmail.ts +9 -12
  15. package/import/headers.ts +1 -1
  16. package/import/idp/apps.ts +244 -0
  17. package/import/idp/command.ts +161 -0
  18. package/import/idp/csv.ts +70 -0
  19. package/import/idp/entra.ts +297 -0
  20. package/import/idp/keycloak.ts +250 -0
  21. package/import/idp/model.ts +108 -0
  22. package/import/idp/okta.ts +159 -0
  23. package/import/idp/pages.ts +65 -0
  24. package/import/imap-command.ts +42 -18
  25. package/import/imap-source.ts +245 -220
  26. package/import/invariant.ts +1 -1
  27. package/import/loopback.ts +136 -0
  28. package/import/mbox-source.ts +106 -55
  29. package/import/mbox.ts +1 -1
  30. package/import/oauth.ts +234 -138
  31. package/import/preview.ts +48 -0
  32. package/import/uploader.ts +169 -115
  33. package/import/workspace.ts +78 -15
  34. package/index.ts +3 -0
  35. package/module-templates.ts +9 -12
  36. package/module.ts +1 -5
  37. package/package.json +13 -2
  38. package/setup/alchemy.ts +2 -2
  39. package/setup/args.ts +16 -17
  40. package/setup/cloudflare-api.ts +75 -19
  41. package/setup/domains.ts +18 -6
  42. package/setup/flow.ts +217 -58
  43. package/setup/migration-guide.ts +255 -0
  44. package/setup/mx-recovery.ts +115 -0
  45. package/setup/ui.ts +4 -1
  46. package/templates.ts +26 -18
@@ -0,0 +1,270 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+
4
+ import { z } from "zod";
5
+
6
+ import { coreBackupSchema } from "#backup-schema";
7
+
8
+ import { parseCliArgs } from "./args.ts";
9
+ import {
10
+ backupItems,
11
+ inspectSnapshot,
12
+ readBackupObject,
13
+ restoreBody,
14
+ sha256,
15
+ } from "./backup-snapshot.ts";
16
+ import type { BackupLine } from "./backup-snapshot.ts";
17
+ import {
18
+ commonOptions,
19
+ concurrency,
20
+ connect,
21
+ reportedRun,
22
+ UsageError,
23
+ } from "./cli.ts";
24
+ import type { CliDeps } from "./cli.ts";
25
+ import { ResumeState, runResumable } from "./uploader.ts";
26
+ import type { Workspace } from "./workspace.ts";
27
+
28
+ export { backupItems } from "./backup-snapshot.ts";
29
+
30
+ export type { BackupItem } from "./backup-snapshot.ts";
31
+
32
+ /**
33
+ * `import backup`: a snapshot of the workspace's scheduled backups,
34
+ * copied out of the bucket (`backups/<id>/` next to `backups/objects/`).
35
+ * core.json goes back first (people, teams, addresses, SSO apps, webhooks,
36
+ * branding), then each module's lines, each with the object it names
37
+ * (`@open-workspace/core`, worker/backups/). What exists is left alone.
38
+ */
39
+
40
+ /**
41
+ * What a full restore needs, from an administrator: the workspace restores
42
+ * each part only as far as the token reaches, as its admin API would
43
+ * (people and their addresses, teams and theirs, webhooks, single sign-on
44
+ * apps; roles and apps also need admin.access), and mail as far as its
45
+ * own routes would let it be written (messages and settings into any
46
+ * mailbox with admin.import_mail, settings with mail.organize, drafts with
47
+ * mail.send, the workspace's blocked senders with admin.blocked_senders).
48
+ */
49
+ const CORE_BACKUP_SCOPES = [
50
+ "admin.workspace",
51
+ "admin.people",
52
+ "admin.teams",
53
+ "admin.webhooks",
54
+ "admin.apps",
55
+ "admin.access",
56
+ "offline_access",
57
+ ];
58
+
59
+ const EMAIL_BACKUP_SCOPES = [
60
+ "admin.import_mail",
61
+ "admin.blocked_senders",
62
+ "mail.organize",
63
+ "mail.send",
64
+ ];
65
+
66
+ export const BACKUP_SCOPES = [...CORE_BACKUP_SCOPES, ...EMAIL_BACKUP_SCOPES];
67
+
68
+ const restoreAnswer = z.discriminatedUnion("status", [
69
+ z.object({ status: z.enum(["restored", "exists"]) }),
70
+ z.object({ status: z.literal("skipped"), reason: z.string() }),
71
+ ]);
72
+
73
+ /** Sends one line to its module, as `runResumable` sends each. */
74
+ async function restoreLine(workspace: Workspace, line: BackupLine) {
75
+ const path = `/api/admin/backups/restore/${encodeURIComponent(line.module)}?folder=${encodeURIComponent(line.folder)}`;
76
+
77
+ for (const part of line.parts) {
78
+ const name = basename(part);
79
+ const data = readBackupObject(dirname(part), name);
80
+
81
+ if (!data.bytes) return { skipped: data.problem ?? "damaged" };
82
+
83
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one file part in memory per concurrent restore
84
+ const answer = await workspace.json(path, restoreAnswer, {
85
+ method: "POST",
86
+ raw: restoreBody(
87
+ JSON.stringify({ kind: "backup-part", object: name }),
88
+ data.bytes
89
+ ),
90
+ });
91
+
92
+ if (answer.status === "skipped") {
93
+ return { skipped: answer.reason };
94
+ }
95
+ }
96
+
97
+ const answer = await workspace.json(path, restoreAnswer, {
98
+ method: "POST",
99
+ raw: line.body,
100
+ });
101
+
102
+ // A line the workspace skipped (its address is missing, say) is not
103
+ // done: it is sent again once that changes.
104
+ return answer.status === "skipped"
105
+ ? { skipped: answer.reason }
106
+ : { done: answer.status };
107
+ }
108
+
109
+ const coreAnswer = z.object({
110
+ restored: z.record(z.string(), z.union([z.number(), z.boolean()])),
111
+ /** What the workspace left out, and why. */
112
+ skipped: z.array(z.string()),
113
+ clientsNeedingSecret: z.array(z.string()),
114
+ });
115
+
116
+ export async function backupCommand(args: string[], deps: CliDeps) {
117
+ const { values, positionals } = parseCliArgs({
118
+ args,
119
+ allowPositionals: true,
120
+ options: { ...commonOptions, partial: { type: "boolean" } },
121
+ });
122
+
123
+ if (values.help) {
124
+ console.log(`bunx @open-workspace/create import backup <backups/<id>>
125
+
126
+ Restores a snapshot of the workspace's backups: people (invited again),
127
+ teams, addresses, SSO apps, webhooks and branding that are missing, then
128
+ each module's data, such as mail each address is missing.
129
+ --partial restore available data from an incomplete or damaged snapshot
130
+ --concurrency, --state-dir, --dry-run as for mbox`);
131
+
132
+ return 0;
133
+ }
134
+
135
+ const [snapshot] = positionals;
136
+
137
+ if (!snapshot || !existsSync(join(snapshot, "core.json"))) {
138
+ throw new UsageError("Name a snapshot folder, the one with core.json");
139
+ }
140
+
141
+ const raw: unknown = JSON.parse(
142
+ readFileSync(join(snapshot, "core.json"), "utf-8")
143
+ );
144
+
145
+ const core = coreBackupSchema.safeParse(raw);
146
+
147
+ if (!core.success) {
148
+ if (core.error.issues.some((issue) => issue.path[0] === "version")) {
149
+ throw new UsageError(
150
+ "Unsupported snapshot format. Restore this snapshot with its matching OpenWorkspace release."
151
+ );
152
+ }
153
+
154
+ throw new UsageError(`Invalid core.json: ${z.prettifyError(core.error)}`);
155
+ }
156
+
157
+ // complete.json is written last: without it the snapshot was still being
158
+ // written (or failed) when it was copied, and may lack part of the data.
159
+ const manifestPath = join(snapshot, "complete.json");
160
+
161
+ const manifest = existsSync(manifestPath)
162
+ ? z
163
+ .object({
164
+ id: z.string().min(1),
165
+ items: z.number().int().nonnegative(),
166
+ errors: z.array(z.string()),
167
+ })
168
+ .parse(JSON.parse(readFileSync(manifestPath, "utf-8")))
169
+ : null;
170
+
171
+ const log = deps.log ?? ((message: string) => console.error(message));
172
+
173
+ const problem = manifest
174
+ ? manifest.errors.length > 0
175
+ ? `This snapshot recorded ${manifest.errors.length} backup error(s)`
176
+ : null
177
+ : "This snapshot is incomplete (no complete.json)";
178
+
179
+ if (problem) {
180
+ for (const reason of manifest?.errors ?? []) log(reason);
181
+
182
+ if (!values.partial) {
183
+ throw new UsageError(
184
+ `${problem}: pick an earlier snapshot, or pass --partial to restore what it has`
185
+ );
186
+ }
187
+
188
+ log(`${problem}. Restoring available data only.`);
189
+ }
190
+
191
+ const inspection = inspectSnapshot(snapshot, manifest?.items, log);
192
+
193
+ if (values["dry-run"]) {
194
+ for (const [key, count] of inspection.counts) log(`${key}: ${count} lines`);
195
+ }
196
+
197
+ if (inspection.incomplete && !values.partial) {
198
+ throw new UsageError(
199
+ "Copy the missing or damaged records again, or use --partial to restore available records."
200
+ );
201
+ }
202
+
203
+ if (values["dry-run"]) return inspection.incomplete ? 1 : 0;
204
+
205
+ const snapshotKey = manifest?.id ?? `partial:${snapshot}`;
206
+
207
+ const workspace = await connect(
208
+ values,
209
+ CORE_BACKUP_SCOPES,
210
+ deps,
211
+ EMAIL_BACKUP_SCOPES
212
+ );
213
+
214
+ const { restored, skipped, clientsNeedingSecret } = await workspace.json(
215
+ "/api/admin/backups/restore",
216
+ coreAnswer,
217
+ {
218
+ method: "POST",
219
+ body: core.data,
220
+ }
221
+ );
222
+
223
+ log(
224
+ `Workspace: ${Object.entries(restored)
225
+ .map(([kind, count]) => `${kind} ${String(count)}`)
226
+ .join(", ")} restored (people are invited again)`
227
+ );
228
+
229
+ for (const reason of skipped) log(`Workspace: skipped ${reason}`);
230
+
231
+ for (const name of clientsNeedingSecret) {
232
+ log(
233
+ `OIDC app "${name}" is disabled. Rotate its client secret and configure it in the app before enabling sign-in.`
234
+ );
235
+ }
236
+
237
+ const state = new ResumeState(
238
+ values["state-dir"] ?? ".openworkspace-import",
239
+ `restore-in-progress-${sha256(JSON.stringify([workspace.origin, snapshotKey]))}`
240
+ );
241
+
242
+ const stats = await reportedRun({
243
+ deps,
244
+ label: "Lines",
245
+ outcomes: { restored: "restored", exists: "already there" },
246
+ state,
247
+ run: (onProgress) =>
248
+ runResumable<BackupLine>({
249
+ // Each part is checked again on the bytes actually sent by restoreLine.
250
+ items: backupItems(snapshot, values.partial ? null : undefined, false),
251
+ state,
252
+ concurrency: concurrency(values),
253
+ exclusive: (line) => !("skipped" in line) && line.ordered,
254
+ size: (line) => line.bytes,
255
+ send: (line) => restoreLine(workspace, line),
256
+ onProgress,
257
+ }),
258
+ });
259
+
260
+ const incomplete =
261
+ inspection.incomplete ||
262
+ skipped.length > 0 ||
263
+ stats.failed > 0 ||
264
+ stats.skipped.size > 0;
265
+
266
+ // A later restore of the same snapshot must check what the workspace still has.
267
+ if (!incomplete) state.clearProgress();
268
+
269
+ return incomplete ? 1 : 0;
270
+ }
package/import/cli.ts CHANGED
@@ -7,20 +7,33 @@ import { mboxFiles, mboxItems, scanMbox } from "./mbox-source.ts";
7
7
  import type { MboxSourceOptions } from "./mbox-source.ts";
8
8
  import { OAuthSession, StaticToken } from "./oauth.ts";
9
9
  import type { Fetch, TokenSource } from "./oauth.ts";
10
+ import { ImportPreview } from "./preview.ts";
10
11
  import { MAIL_IMPORT_SCOPES, placementSchema } from "./protocol.ts";
11
- import type { ImportItem, Placement, SkippedItem } from "./protocol.ts";
12
- import { progressLine, ResumeState, upload } from "./uploader.ts";
13
- import type { UploadStats } from "./uploader.ts";
12
+ import type {
13
+ ImportItem,
14
+ ImportTarget,
15
+ Placement,
16
+ SkippedItem,
17
+ } from "./protocol.ts";
18
+ import {
19
+ progressLine,
20
+ ResumeState,
21
+ upload,
22
+ UPLOAD_OUTCOMES,
23
+ } from "./uploader.ts";
24
+ import type { RunStats } from "./uploader.ts";
14
25
  import { Workspace } from "./workspace.ts";
15
26
 
16
- const USAGE = `Bring people and mail into an OpenWorkspace.
27
+ const USAGE = `Bring people, teams, SSO apps and mail into an OpenWorkspace.
17
28
 
18
- bunx @open-workspace/create import mbox <file or Takeout folder>... --into <mailbox>
29
+ bunx @open-workspace/create import mbox <mbox file, Apple Mail package or export folder>... --into <mailbox>
19
30
  bunx @open-workspace/create import imap --host <host> --user <user> --into <mailbox>
20
31
  bunx @open-workspace/create import people --google-credentials <file.json> [--admin <email>]
32
+ bunx @open-workspace/create import idp <entra|okta|keycloak|csv|saml> --help
33
+ bunx @open-workspace/create import backup <backups/<id> folder>
21
34
 
22
35
  Common options:
23
- --workspace <url> The workspace, e.g. https://mail.acme.com (or OPENWORKSPACE_URL)
36
+ --workspace <url> The workspace, e.g. https://workspace.acme.com (or OPENWORKSPACE_URL)
24
37
  --into <mailbox> Target mailbox: its address or id
25
38
  --map <file.csv> Many sources at once: rows of "source,target" (imap: "user,target[,password]")
26
39
  --concurrency <n> Uploads in flight per mailbox (default 2)
@@ -76,7 +89,7 @@ export type CommonValues = {
76
89
 
77
90
  export class UsageError extends Error {}
78
91
 
79
- function required<T>(value: T | undefined, message: string): T {
92
+ function required<T>(value: T | undefined, message: string) {
80
93
  if (value === undefined || value === "") throw new UsageError(message);
81
94
 
82
95
  return value;
@@ -86,7 +99,8 @@ function required<T>(value: T | undefined, message: string): T {
86
99
  export async function connect(
87
100
  values: CommonValues,
88
101
  scopes: string[],
89
- deps: CliDeps
102
+ deps: CliDeps,
103
+ optionalScopes?: string[]
90
104
  ) {
91
105
  const url = required(
92
106
  values.workspace ?? process.env.OPENWORKSPACE_URL,
@@ -100,6 +114,7 @@ export async function connect(
100
114
  : await OAuthSession.login({
101
115
  workspace: url,
102
116
  scopes,
117
+ optionalScopes,
103
118
  fetch: deps.fetch,
104
119
  openBrowser: deps.openBrowser,
105
120
  credentialsPath: deps.credentialsPath,
@@ -114,11 +129,11 @@ export async function connect(
114
129
  export type Job = { source: string; target: string; password?: string };
115
130
 
116
131
  /** Source → target pairs from --map, or the one source with --into. */
117
- export function jobs(values: CommonValues, sources: string[]): Job[] {
132
+ export function jobs(values: CommonValues, sources: string[]) {
118
133
  if (values.map) {
119
134
  const rows = parseCsv(readFileSync(values.map, "utf-8"));
120
135
 
121
- return rows.flatMap((row, index): Job[] => {
136
+ return rows.flatMap((row, index) => {
122
137
  const [source = "", target = "", password] = row;
123
138
 
124
139
  // A header row ("source,target") is allowed.
@@ -164,95 +179,102 @@ function progressPrinter(deps: CliDeps) {
164
179
  };
165
180
  }
166
181
 
167
- /** Uploads one source's items into one mailbox and reports the outcome. */
168
- export async function runJob(input: {
169
- workspace: Workspace;
170
- target: string;
171
- label: string;
172
- job: string;
173
- items: AsyncIterable<ImportItem | SkippedItem>;
174
- total: number | null;
175
- values: CommonValues;
182
+ /** Requests in flight: --concurrency, 2 by default. */
183
+ export function concurrency(values: CommonValues) {
184
+ return Math.max(1, Number(values.concurrency ?? 2) || 2);
185
+ }
186
+
187
+ /**
188
+ * Runs a resumable run (`runResumable`) with a progress line, then reports
189
+ * what it did, each reason for skipping, and where its failures are.
190
+ */
191
+ export async function reportedRun(input: {
176
192
  deps: CliDeps;
193
+ label: string;
194
+ outcomes: Record<string, string>;
195
+ state: ResumeState;
196
+ run: (onProgress: (stats: RunStats) => void) => Promise<RunStats>;
177
197
  }) {
178
198
  const log = input.deps.log ?? ((message: string) => console.error(message));
179
- const mailbox = await input.workspace.importTarget(input.target);
180
-
181
- const state = new ResumeState(
182
- input.values["state-dir"] ?? ".openworkspace-import",
183
- `${new URL(input.workspace.origin).host}-${mailbox.id}-${input.job}`
184
- );
185
-
186
199
  const print = progressPrinter(input.deps);
187
- const label = `${input.label} → ${mailbox.address}`;
188
200
 
189
- const stats: UploadStats = await upload({
190
- workspace: input.workspace,
191
- mailboxId: mailbox.id,
192
- items: input.items,
193
- state,
194
- concurrency: Math.max(1, Number(input.values.concurrency ?? 2) || 2),
195
- total: input.total,
196
- onProgress: (current) => print(progressLine(label, current)),
197
- });
201
+ const stats = await input.run((current) =>
202
+ print(progressLine(input.label, current, input.outcomes))
203
+ );
198
204
 
199
205
  if (process.stderr.isTTY && !input.deps.progress) process.stderr.write("\n");
200
- log(progressLine(label, stats));
206
+ log(progressLine(input.label, stats, input.outcomes));
201
207
 
202
- if (stats.failed) {
203
- log(
204
- ` ${stats.failed} failed; see ${state.failuresPath}. Run the same command again to retry them.`
205
- );
208
+ for (const [reason, count] of stats.skipped) {
209
+ log(` skipped (${reason}): ${count}`);
206
210
  }
207
211
 
208
- if (stats.folderSkipped) {
212
+ if (stats.failed) {
209
213
  log(
210
- ` ${stats.folderSkipped} messages kept no folder (a mailbox has at most 100, and system folder names are taken).`
214
+ ` ${stats.failed} failed; see ${input.state.failuresPath}. Run the same command again to retry them.`
211
215
  );
212
216
  }
213
217
 
214
218
  return stats;
215
219
  }
216
220
 
217
- /** Tallies what a dry run would import. */
218
- export async function describeItems(
219
- items: AsyncIterable<ImportItem | SkippedItem>,
220
- log: (message: string) => void,
221
- label: string
221
+ /** The source reader and uploader share the same mailbox and resume state. */
222
+ export async function prepareImportJob(
223
+ workspace: Workspace,
224
+ target: string,
225
+ job: string,
226
+ directory = ".openworkspace-import"
222
227
  ) {
223
- const places = new Map<string, number>();
224
- const folders = new Map<string, number>();
225
- const skipped = new Map<string, number>();
226
- let unread = 0;
227
- let count = 0;
228
-
229
- for await (const item of items) {
230
- count += 1;
231
-
232
- if ("skipped" in item) {
233
- skipped.set(item.skipped, (skipped.get(item.skipped) ?? 0) + 1);
234
- continue;
235
- }
228
+ const mailbox = await workspace.importTarget(target);
236
229
 
237
- places.set(item.placement, (places.get(item.placement) ?? 0) + 1);
230
+ const state = new ResumeState(
231
+ directory,
232
+ `${new URL(workspace.origin).host}-${mailbox.id}-${job}`
233
+ );
238
234
 
239
- if (item.folder) {
240
- folders.set(item.folder, (folders.get(item.folder) ?? 0) + 1);
241
- }
235
+ return { workspace, mailbox, state };
236
+ }
242
237
 
243
- if (!item.seen) unread += 1;
244
- }
238
+ /** Uploads one source's items into one mailbox and reports the outcome. */
239
+ export async function runJob(input: {
240
+ workspace: Workspace;
241
+ mailbox: ImportTarget;
242
+ state: ResumeState;
243
+ label: string;
244
+ items: AsyncIterable<ImportItem | SkippedItem>;
245
+ total: number | null;
246
+ values: CommonValues;
247
+ deps: CliDeps;
248
+ }) {
249
+ const log = input.deps.log ?? ((message: string) => console.error(message));
250
+ const { mailbox, state } = input;
245
251
 
246
- const list = (map: Map<string, number>) =>
247
- [...map].map(([name, n]) => `${name} ${n}`).join(", ") || "none";
252
+ const stats = await reportedRun({
253
+ deps: input.deps,
254
+ label: `${input.label} → ${mailbox.address}`,
255
+ outcomes: UPLOAD_OUTCOMES,
256
+ state,
257
+ run: (onProgress) =>
258
+ upload({
259
+ workspace: input.workspace,
260
+ mailboxId: mailbox.id,
261
+ items: input.items,
262
+ state,
263
+ concurrency: concurrency(input.values),
264
+ total: input.total,
265
+ onProgress,
266
+ }),
267
+ });
248
268
 
249
- log(`${label}: ${count} messages`);
250
- log(` places: ${list(places)}`);
251
- log(` folders: ${list(folders)}`);
252
- log(` unread: ${unread}`);
253
- log(` skipped: ${list(skipped)}`);
269
+ const withoutFolder = stats.done.importedWithoutFolder;
270
+
271
+ if (withoutFolder) {
272
+ log(
273
+ ` ${withoutFolder} messages kept no folder (a mailbox has at most 100, and system folder names are taken).`
274
+ );
275
+ }
254
276
 
255
- return { count, places, folders, skipped, unread };
277
+ return stats;
256
278
  }
257
279
 
258
280
  /** --skip: comma-separated places. */
@@ -320,22 +342,32 @@ export async function mboxCommand(args: string[], deps: CliDeps) {
320
342
  };
321
343
 
322
344
  const log = deps.log ?? ((message: string) => console.error(message));
323
- const pairs = jobs(values, positionals);
345
+
346
+ const pairs = jobs(values, positionals).map(({ source, target }) => {
347
+ const files = mboxFiles(source.split("\u0000"));
348
+
349
+ if (!files.length) throw new UsageError(`No mbox files in ${source}`);
350
+ const archive = files.find((file) => /\.(?:zip|tgz|gz)$/iu.test(file));
351
+
352
+ if (archive) {
353
+ throw new UsageError(
354
+ `Extract ${archive} first, then pass the .mbox file or the extracted Takeout/Mail folder.`
355
+ );
356
+ }
357
+
358
+ return { files, target };
359
+ });
324
360
 
325
361
  const workspace = values["dry-run"]
326
362
  ? null
327
363
  : await connect(values, MAIL_IMPORT_SCOPES, deps);
328
364
 
329
- const results: UploadStats[] = [];
365
+ const results: RunStats[] = [];
330
366
 
331
- const mboxJob = async ({ source, target }: Job) => {
332
- const files = mboxFiles(source.split("\u0000"));
333
-
334
- if (!files.length) throw new UsageError(`No mbox files in ${source}`);
367
+ const mboxJob = async ({ files, target }: (typeof pairs)[number]) => {
335
368
  log(
336
369
  `Reading ${files.length === 1 ? files[0] : `${files.length} mbox files`}…`
337
370
  );
338
- const scan = await scanMbox(files, options);
339
371
  const [only] = files;
340
372
 
341
373
  const label =
@@ -344,21 +376,28 @@ export async function mboxCommand(args: string[], deps: CliDeps) {
344
376
  : `${files.length} mbox files`;
345
377
 
346
378
  if (!workspace) {
347
- await describeItems(
348
- mboxItems(files, options, scan.threads),
349
- log,
350
- `${label} → ${target}`
351
- );
379
+ const preview = new ImportPreview();
380
+ await scanMbox(files, options, preview);
381
+ preview.print(log, `${label} → ${target}`);
352
382
 
353
383
  return;
354
384
  }
355
385
 
386
+ const scan = await scanMbox(files, options);
387
+
388
+ const job = `mbox-${new Bun.CryptoHasher("sha256").update(files.join("\n")).digest("hex").slice(0, 12)}`;
389
+
390
+ const destination = await prepareImportJob(
391
+ workspace,
392
+ target,
393
+ job,
394
+ values["state-dir"]
395
+ );
396
+
356
397
  results.push(
357
398
  await runJob({
358
- workspace,
359
- target,
399
+ ...destination,
360
400
  label,
361
- job: `mbox-${new Bun.CryptoHasher("sha256").update(files.join("\n")).digest("hex").slice(0, 12)}`,
362
401
  items: mboxItems(files, options, scan.threads),
363
402
  total: scan.count,
364
403
  values,
@@ -379,12 +418,17 @@ type Command = (args: string[], deps: CliDeps) => Promise<number>;
379
418
 
380
419
  /** Each source's command; the IMAP and directory ones load their dependencies only when used. */
381
420
  const commands = new Map<string, () => Promise<Command>>([
421
+ ["idp", () => import("./idp/command.ts").then((module) => module.idpCommand)],
382
422
  ["mbox", () => Promise.resolve(mboxCommand)],
383
423
  ["takeout", () => Promise.resolve(mboxCommand)],
384
424
  [
385
425
  "imap",
386
426
  () => import("./imap-command.ts").then((module) => module.imapCommand),
387
427
  ],
428
+ [
429
+ "backup",
430
+ () => import("./backup-source.ts").then((module) => module.backupCommand),
431
+ ],
388
432
  [
389
433
  "people",
390
434
  () =>
@@ -7,46 +7,43 @@
7
7
  export async function forEachConcurrent<Item>(
8
8
  items: AsyncIterable<Item> | Iterable<Item>,
9
9
  limit: number,
10
- task: (item: Item, index: number) => Promise<void>
11
- ): Promise<void> {
12
- // An async generator queues concurrent next() calls, so workers can share it.
13
- const source = (async function* () {
14
- yield* items;
15
- })();
16
-
17
- let taken = 0;
18
- let stopped = false;
19
- const failures: Promise<void>[] = [];
20
-
21
- const work = async () => {
22
- /* oxlint-disable eslint/no-await-in-loop -- a worker takes its next item only when its last task is done: that is the concurrency bound */
23
- for (;;) {
24
- // Set by another worker's failure while this one waited.
25
- if (stopped) return;
26
- const next = await source.next();
27
-
28
- if (next.done) return;
29
- const index = taken;
30
- taken += 1;
31
- await task(next.value, index);
32
- }
33
- /* oxlint-enable eslint/no-await-in-loop */
10
+ task: (item: Item, index: number) => Promise<void>,
11
+ exclusive?: (item: Item) => boolean
12
+ ) {
13
+ const active = new Set<Promise<void>>();
14
+ let failure: { cause: unknown } | undefined;
15
+
16
+ const rememberFailure = (cause: unknown) => {
17
+ failure ??= { cause };
34
18
  };
35
19
 
36
- const worker = async () => {
37
- const running = work();
20
+ let index = 0;
38
21
 
39
- try {
40
- await running;
41
- } catch {
42
- stopped = true;
43
- failures.push(running);
44
- }
45
- };
22
+ try {
23
+ for await (const item of items) {
24
+ // An ordered restore line needs the preceding messages and draft owners.
25
+ const alone = exclusive?.(item);
26
+
27
+ if (alone) await Promise.all(active);
46
28
 
47
- await Promise.all(Array.from({ length: Math.max(1, limit) }, worker));
48
- await source.return(undefined);
29
+ if (failure) break;
30
+
31
+ const running = task(item, index++)
32
+ .catch(rememberFailure)
33
+ .finally(() => {
34
+ active.delete(running);
35
+ });
36
+
37
+ active.add(running);
38
+
39
+ if (alone) await running;
40
+ else if (active.size >= Math.max(1, limit)) await Promise.race(active);
41
+
42
+ if (failure) break;
43
+ }
44
+ } finally {
45
+ await Promise.all(active);
46
+ }
49
47
 
50
- // Rethrows the first failure, as it was thrown.
51
- if (failures.length > 0) await failures[0];
48
+ if (failure) throw failure.cause;
52
49
  }