@open-workspace/create 0.3.0 → 0.4.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.
@@ -0,0 +1,182 @@
1
+ import * as p from "@clack/prompts";
2
+ import { ImapFlow } from "imapflow";
3
+
4
+ import { parseCliArgs } from "./args.ts";
5
+ import {
6
+ commonOptions,
7
+ connect,
8
+ describeItems,
9
+ jobs,
10
+ placementList,
11
+ runJob,
12
+ UsageError,
13
+ } from "./cli.ts";
14
+ import type { CliDeps, Job } from "./cli.ts";
15
+ import { imapSource } from "./imap-source.ts";
16
+ import type { ImapSourceOptions } from "./imap-source.ts";
17
+ import { MAIL_IMPORT_SCOPES } from "./protocol.ts";
18
+ import { ResumeState } from "./uploader.ts";
19
+ import type { UploadStats } from "./uploader.ts";
20
+
21
+ /**
22
+ * `import imap`: one account (--user, --into) or many (--map rows of
23
+ * "user,target[,password]"). Authenticates with a password (an app
24
+ * password for Gmail) or an OAuth access token (XOAUTH2).
25
+ */
26
+ export async function imapCommand(args: string[], deps: CliDeps) {
27
+ const { values } = parseCliArgs({
28
+ args,
29
+ options: {
30
+ ...commonOptions,
31
+ host: { type: "string" },
32
+ port: { type: "string" },
33
+ plain: { type: "boolean" },
34
+ user: { type: "string" },
35
+ password: { type: "string" },
36
+ "password-env": { type: "string" },
37
+ "access-token": { type: "string" },
38
+ skip: { type: "string" },
39
+ "archived-labels": { type: "string" },
40
+ "folder-priority": { type: "string" },
41
+ },
42
+ });
43
+
44
+ if (values.help) {
45
+ console.log(`bunx @open-workspace/create import imap --host imap.gmail.com --user ada@acme.com --into ada@acme.com
46
+
47
+ --host, --port (993) The IMAP server; --plain for an unencrypted connection (local testing only)
48
+ --user The account (or --map rows of "user,target[,password]")
49
+ --password-env <VAR> Read the password (a Gmail app password) from this variable; else you are asked
50
+ --password <password> The password on the command line (visible in your shell history)
51
+ --access-token <token> An OAuth access token instead (XOAUTH2), e.g. from your own Google Cloud client
52
+ --skip, --archived-labels, --folder-priority, --concurrency, --state-dir, --dry-run as for mbox`);
53
+
54
+ return 0;
55
+ }
56
+
57
+ const { host } = values;
58
+
59
+ if (!host) throw new UsageError("Pass --host, e.g. imap.gmail.com");
60
+ const port = Number(values.port ?? (values.plain ? 143 : 993));
61
+ const archivedLabels = values["archived-labels"] ?? "archive";
62
+
63
+ if (archivedLabels !== "archive" && archivedLabels !== "folder") {
64
+ throw new UsageError("--archived-labels is archive or folder");
65
+ }
66
+
67
+ const skip = placementList(values.skip);
68
+ const log = deps.log ?? ((message: string) => console.error(message));
69
+
70
+ if (!values.map && (!values.user || !values.into)) {
71
+ throw new UsageError("Pass --user and --into, or --map");
72
+ }
73
+
74
+ const pairs: Job[] = values.map
75
+ ? jobs(values, [])
76
+ : [{ source: values.user ?? "", target: values.into ?? "" }];
77
+
78
+ const workspace = values["dry-run"]
79
+ ? null
80
+ : await connect(values, MAIL_IMPORT_SCOPES, deps);
81
+
82
+ const results: UploadStats[] = [];
83
+
84
+ const importAccount = async ({
85
+ source: user,
86
+ target,
87
+ password: rowPassword,
88
+ }: Job) => {
89
+ const accessToken = values["access-token"];
90
+
91
+ const auth = accessToken
92
+ ? { user, accessToken }
93
+ : {
94
+ user,
95
+ pass:
96
+ rowPassword ||
97
+ (values["password-env"]
98
+ ? process.env[values["password-env"]]
99
+ : undefined) ||
100
+ values.password ||
101
+ (await askPassword(user)),
102
+ };
103
+
104
+ const client = new ImapFlow({
105
+ host,
106
+ port,
107
+ secure: !values.plain,
108
+ auth,
109
+ logger: false,
110
+ // A long import outlives the server's idea of an idle session.
111
+ disableAutoIdle: true,
112
+ });
113
+
114
+ await client.connect();
115
+
116
+ try {
117
+ const account = `${host}/${user}`;
118
+ const job = `imap-${account}`;
119
+
120
+ const state = workspace
121
+ ? new ResumeState(
122
+ values["state-dir"] ?? ".openworkspace-import",
123
+ `${new URL(workspace.origin).host}-${(await workspace.importTarget(target)).id}-${job}`
124
+ )
125
+ : null;
126
+
127
+ const options: ImapSourceOptions = {
128
+ archivedLabels,
129
+ folderPriority: (values["folder-priority"] ?? "")
130
+ .split(",")
131
+ .map((label) => label.trim())
132
+ .filter(Boolean),
133
+ skip,
134
+ account,
135
+ done: (sourceId) => state?.has(sourceId) ?? false,
136
+ };
137
+
138
+ const source = await imapSource(client, options);
139
+ log(
140
+ `${user}: ${source.total} messages${source.gmail ? " in All Mail (Gmail)" : ""}`
141
+ );
142
+
143
+ if (!workspace) {
144
+ await describeItems(source.items, log, `${user} → ${target}`);
145
+
146
+ return;
147
+ }
148
+
149
+ results.push(
150
+ await runJob({
151
+ workspace,
152
+ target,
153
+ label: user,
154
+ job,
155
+ items: source.items,
156
+ total: source.total,
157
+ values,
158
+ deps,
159
+ })
160
+ );
161
+ } finally {
162
+ await client.logout().catch(() => client.close());
163
+ }
164
+ };
165
+
166
+ for (const job of pairs) {
167
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one account at a time: a password may be asked for each, and each job reports on the one progress line
168
+ await importAccount(job);
169
+ }
170
+
171
+ return results.some((stats) => stats.failed) ? 1 : 0;
172
+ }
173
+
174
+ async function askPassword(user: string) {
175
+ const value = await p.password({
176
+ message: `IMAP password for ${user} (for Gmail, an app password)`,
177
+ });
178
+
179
+ if (p.isCancel(value)) throw new UsageError("No password given");
180
+
181
+ return value;
182
+ }
@@ -0,0 +1,397 @@
1
+ import type { FetchMessageObject, ImapFlow, ListResponse } from "imapflow";
2
+
3
+ import { gmailMessage, ThreadFolders } from "./gmail.ts";
4
+ import type { GmailOptions } from "./gmail.ts";
5
+ import { headerText, parseHeaders, rootThreadKey } from "./headers.ts";
6
+ import { MAX_IMPORT_MESSAGE_BYTES } from "./protocol.ts";
7
+ import type { ImportItem, Placement, SkippedItem } from "./protocol.ts";
8
+
9
+ /**
10
+ * Mail from an IMAP account. Gmail (X-GM-EXT-1) is read from "[Gmail]/All
11
+ * Mail" alone, with its labels (X-GM-LABELS) and threads (X-GM-THRID): its
12
+ * label folders hold the same messages again. Other servers are read folder
13
+ * by folder, each placed by its special use (RFC 6154).
14
+ */
15
+
16
+ export type ImapSourceOptions = GmailOptions & {
17
+ folderPriority: string[];
18
+ skip: Set<Placement>;
19
+ /** Names the account in source ids (host and user), so two accounts never collide. */
20
+ account: string;
21
+ /** Has this source id been imported already? Its body is then not downloaded. */
22
+ done: (sourceId: string) => boolean;
23
+ /** Messages fetched per round trip. */
24
+ batchSize?: number;
25
+ };
26
+
27
+ /** Where a folder's mail goes on a server without Gmail labels. */
28
+ export type FolderPlan = {
29
+ path: string;
30
+ placement: Placement;
31
+ /** A custom folder, for mail placed in the Inbox. */
32
+ folder: string | null;
33
+ direction?: "incoming" | "outgoing";
34
+ };
35
+
36
+ /** Folders that hold copies or nothing to import: drafts, virtual views, and the all-mail view. */
37
+ const SKIPPED_USES = new Set(["\\Drafts", "\\All", "\\Flagged", "\\Important"]);
38
+
39
+ /**
40
+ * Each selectable folder's place: Inbox, Sent (sent mail), Junk (Spam),
41
+ * Trash, Archive, and other folders as Archive or their own folder
42
+ * (`archivedLabels`). Nested names use "/".
43
+ */
44
+ export function folderPlans(
45
+ folders: Pick<ListResponse, "path" | "delimiter" | "flags" | "specialUse">[],
46
+ options: GmailOptions
47
+ ): FolderPlan[] {
48
+ return folders.flatMap((folder): FolderPlan[] => {
49
+ if (folder.flags?.has("\\Noselect") || folder.flags?.has("\\NonExistent")) {
50
+ return [];
51
+ }
52
+
53
+ const use =
54
+ folder.specialUse ??
55
+ (folder.path.toUpperCase() === "INBOX" ? "\\Inbox" : undefined);
56
+
57
+ if (use && SKIPPED_USES.has(use)) return [];
58
+
59
+ switch (use) {
60
+ case "\\Inbox": {
61
+ return [{ path: folder.path, placement: "inbox", folder: null }];
62
+ }
63
+
64
+ case "\\Sent": {
65
+ return [
66
+ {
67
+ path: folder.path,
68
+ placement: "sent",
69
+ folder: null,
70
+ direction: "outgoing",
71
+ },
72
+ ];
73
+ }
74
+
75
+ case "\\Junk": {
76
+ return [{ path: folder.path, placement: "spam", folder: null }];
77
+ }
78
+
79
+ case "\\Trash": {
80
+ return [{ path: folder.path, placement: "trash", folder: null }];
81
+ }
82
+
83
+ case "\\Archive": {
84
+ return [{ path: folder.path, placement: "archive", folder: null }];
85
+ }
86
+
87
+ default: {
88
+ // Any other folder, special use or not: placed by `archivedLabels` below.
89
+ break;
90
+ }
91
+ }
92
+
93
+ const delimiter = folder.delimiter || "/";
94
+ // Courier and Dovecot setups nest everything under INBOX.
95
+ const parts = folder.path.split(delimiter);
96
+ const [top = ""] = parts;
97
+
98
+ if (parts.length > 1 && top.toUpperCase() === "INBOX") parts.shift();
99
+ const name = parts.join("/").slice(0, 80);
100
+
101
+ return [
102
+ options.archivedLabels === "folder"
103
+ ? { path: folder.path, placement: "inbox", folder: name }
104
+ : { path: folder.path, placement: "archive", folder: null },
105
+ ];
106
+ });
107
+ }
108
+
109
+ function receivedAt(message: FetchMessageObject) {
110
+ if (!message.internalDate) return undefined;
111
+ const time = new Date(message.internalDate).getTime();
112
+
113
+ return Number.isFinite(time) ? time : undefined;
114
+ }
115
+
116
+ function labelsOf(message: FetchMessageObject) {
117
+ return [...(message.labels ?? [])];
118
+ }
119
+
120
+ export type ImapSource = {
121
+ gmail: boolean;
122
+ /** Messages to go through (after skipping folders), counted before any body is fetched. */
123
+ total: number;
124
+ items: AsyncIterable<ImportItem | SkippedItem>;
125
+ };
126
+
127
+ type Work = {
128
+ uid: number;
129
+ sourceId: string;
130
+ size?: number;
131
+ meta: FetchMessageObject;
132
+ };
133
+
134
+ async function* fetchBodies(
135
+ client: ImapFlow,
136
+ work: Work[],
137
+ batchSize: number,
138
+ toItem: (
139
+ meta: FetchMessageObject,
140
+ sourceId: string,
141
+ raw: Uint8Array<ArrayBuffer>
142
+ ) => ImportItem | SkippedItem
143
+ ): AsyncGenerator<ImportItem | SkippedItem> {
144
+ for (let start = 0; start < work.length; start += batchSize) {
145
+ const batch = work.slice(start, start + batchSize);
146
+ const byUid = new Map(batch.map((entry) => [entry.uid, entry]));
147
+ const fetched: (ImportItem | SkippedItem)[] = [];
148
+
149
+ // Collected per batch: imapflow cannot run another command while a FETCH streams.
150
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one IMAP connection runs one command at a time, and the next batch is fetched only once this one is consumed
151
+ const messages = await client.fetchAll(
152
+ batch.map((entry) => entry.uid).join(","),
153
+ { uid: true, source: true },
154
+ { uid: true }
155
+ );
156
+
157
+ for (const message of messages) {
158
+ const entry = byUid.get(message.uid);
159
+
160
+ if (!entry || !message.source) continue;
161
+ byUid.delete(message.uid);
162
+ fetched.push(
163
+ toItem(entry.meta, entry.sourceId, new Uint8Array(message.source))
164
+ );
165
+ }
166
+
167
+ yield* fetched;
168
+
169
+ // Gone since it was listed (expunged meanwhile).
170
+ for (const entry of byUid.values()) {
171
+ yield { sourceId: entry.sourceId, skipped: "gone" };
172
+ }
173
+ }
174
+ }
175
+
176
+ function sortedWork(work: Work[], options: ImapSourceOptions) {
177
+ const pending: Work[] = [];
178
+ const done: SkippedItem[] = [];
179
+ const large: SkippedItem[] = [];
180
+
181
+ for (const entry of work) {
182
+ if (options.done(entry.sourceId)) {
183
+ done.push({ sourceId: entry.sourceId, skipped: "done" });
184
+ } else if ((entry.size ?? 0) > MAX_IMPORT_MESSAGE_BYTES) {
185
+ large.push({ sourceId: entry.sourceId, skipped: "too large" });
186
+ } else pending.push(entry);
187
+ }
188
+
189
+ return { pending, done, large };
190
+ }
191
+
192
+ /** Gmail: All Mail, its labels and threads. */
193
+ async function gmailSource(
194
+ client: ImapFlow,
195
+ allMail: string,
196
+ options: ImapSourceOptions
197
+ ): Promise<ImapSource> {
198
+ const lock = await client.getMailboxLock(allMail, { readOnly: true });
199
+
200
+ try {
201
+ const threads = new ThreadFolders(options.folderPriority);
202
+ const work: Work[] = [];
203
+
204
+ for await (const meta of client.fetch(
205
+ "1:*",
206
+ {
207
+ uid: true,
208
+ flags: true,
209
+ labels: true,
210
+ threadId: true,
211
+ emailId: true,
212
+ internalDate: true,
213
+ size: true,
214
+ },
215
+ { uid: true }
216
+ )) {
217
+ const thread = meta.threadId ? `gmail:${meta.threadId}` : undefined;
218
+
219
+ if (thread) {
220
+ threads.add(thread, gmailMessage(labelsOf(meta), options).userLabels);
221
+ }
222
+
223
+ work.push({
224
+ uid: meta.uid,
225
+ size: meta.size,
226
+ sourceId: `gmail:${meta.emailId ?? `${options.account}:${meta.uid}`}`,
227
+ meta,
228
+ });
229
+ }
230
+
231
+ const { pending, done, large } = sortedWork(work, options);
232
+
233
+ // oxlint-disable-next-line no-inner-declarations -- the generator closes over this block's state
234
+ async function* items() {
235
+ // Report what earlier runs did, and what cannot be imported, before downloading.
236
+ yield* done;
237
+ yield* large;
238
+
239
+ const bodiesLock = await client.getMailboxLock(allMail, {
240
+ readOnly: true,
241
+ });
242
+
243
+ try {
244
+ yield* fetchBodies(
245
+ client,
246
+ pending,
247
+ options.batchSize ?? 50,
248
+ (meta, sourceId, raw): ImportItem | SkippedItem => {
249
+ const gmail = gmailMessage(labelsOf(meta), options);
250
+
251
+ if (gmail.skip) return { sourceId, skipped: gmail.skip };
252
+
253
+ if (options.skip.has(gmail.placement)) {
254
+ return { sourceId, skipped: gmail.placement };
255
+ }
256
+
257
+ const thread = meta.threadId
258
+ ? `gmail:${meta.threadId}`
259
+ : rootThreadKey(parseHeaders(headerText(raw)));
260
+
261
+ return {
262
+ sourceId,
263
+ raw,
264
+ placement: gmail.placement,
265
+ folder:
266
+ gmail.placement === "inbox" && thread
267
+ ? threads.folder(thread, gmail.userLabels)
268
+ : null,
269
+ seen: meta.flags?.has("\\Seen") ?? false,
270
+ thread,
271
+ receivedAt: receivedAt(meta),
272
+ direction: gmail.sent ? "outgoing" : "incoming",
273
+ };
274
+ }
275
+ );
276
+ } finally {
277
+ bodiesLock.release();
278
+ }
279
+ }
280
+
281
+ return { gmail: true, total: work.length, items: items() };
282
+ } finally {
283
+ lock.release();
284
+ }
285
+ }
286
+
287
+ /** A folder's messages, listed without their bodies. */
288
+ async function folderWork(
289
+ client: ImapFlow,
290
+ plan: FolderPlan,
291
+ options: ImapSourceOptions
292
+ ): Promise<Work[]> {
293
+ const lock = await client.getMailboxLock(plan.path, { readOnly: true });
294
+
295
+ try {
296
+ const { mailbox } = client;
297
+
298
+ if (!mailbox || mailbox.exists === 0) return [];
299
+ const uidValidity = String(mailbox.uidValidity);
300
+
301
+ const messages = await client.fetchAll(
302
+ "1:*",
303
+ { uid: true, flags: true, internalDate: true, size: true },
304
+ { uid: true }
305
+ );
306
+
307
+ return messages.map((meta) => ({
308
+ uid: meta.uid,
309
+ size: meta.size,
310
+ sourceId: `imap:${options.account}/${plan.path}/${uidValidity}/${meta.uid}`,
311
+ meta,
312
+ }));
313
+ } finally {
314
+ lock.release();
315
+ }
316
+ }
317
+
318
+ /** Any other server: folder by folder. */
319
+ async function foldersSource(
320
+ client: ImapFlow,
321
+ options: ImapSourceOptions
322
+ ): Promise<ImapSource> {
323
+ const plans = folderPlans(await client.list(), options).filter(
324
+ (plan) => !options.skip.has(plan.placement)
325
+ );
326
+
327
+ const perFolder: { plan: FolderPlan; work: Work[] }[] = [];
328
+ let total = 0;
329
+
330
+ for (const plan of plans) {
331
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one IMAP connection has one folder selected at a time
332
+ const work = await folderWork(client, plan, options);
333
+ total += work.length;
334
+ perFolder.push({ plan, work });
335
+ }
336
+
337
+ async function* items() {
338
+ for (const { plan, work } of perFolder) {
339
+ const { pending, done, large } = sortedWork(work, options);
340
+ yield* done;
341
+ yield* large;
342
+
343
+ if (!pending.length) continue;
344
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one IMAP connection has one folder selected at a time
345
+ const lock = await client.getMailboxLock(plan.path, { readOnly: true });
346
+
347
+ try {
348
+ yield* fetchBodies(
349
+ client,
350
+ pending,
351
+ options.batchSize ?? 50,
352
+ (meta, sourceId, raw) => {
353
+ const item: ImportItem = {
354
+ sourceId,
355
+ raw,
356
+ placement: plan.placement,
357
+ folder: plan.folder,
358
+ seen: meta.flags?.has("\\Seen") ?? false,
359
+ thread: rootThreadKey(parseHeaders(headerText(raw))),
360
+ receivedAt: receivedAt(meta),
361
+ };
362
+
363
+ if (plan.direction) item.direction = plan.direction;
364
+
365
+ return item;
366
+ }
367
+ );
368
+ } finally {
369
+ lock.release();
370
+ }
371
+ }
372
+ }
373
+
374
+ return { gmail: false, total, items: items() };
375
+ }
376
+
377
+ /** The account's mail as import items, Gmail or not. */
378
+ export async function imapSource(
379
+ client: ImapFlow,
380
+ options: ImapSourceOptions
381
+ ): Promise<ImapSource> {
382
+ if (client.capabilities.has("X-GM-EXT-1")) {
383
+ const allMail = (await client.list()).find(
384
+ (folder) => folder.specialUse === "\\All"
385
+ );
386
+
387
+ if (!allMail) {
388
+ throw new Error(
389
+ 'This Gmail account shows no All Mail folder over IMAP; turn on "Show in IMAP" for All Mail in Gmail\'s settings'
390
+ );
391
+ }
392
+
393
+ return gmailSource(client, allMail.path, options);
394
+ }
395
+
396
+ return foldersSource(client, options);
397
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Invariants: conditions the code relies on but the type checker can't see.
3
+ * A failure is a bug in this code, not bad input, so it throws instead of
4
+ * reporting a usage error. (A local copy of `@open-workspace/core/shared`'s
5
+ * helpers: this CLI is published on its own and does not depend on core.)
6
+ */
7
+ export class InvariantError extends Error {}
8
+
9
+ /** Throws an InvariantError with `message` unless `condition` holds. */
10
+ export function invariant(
11
+ condition: boolean,
12
+ message: string
13
+ ): asserts condition {
14
+ if (!condition) throw new InvariantError(message);
15
+ }
16
+
17
+ /** `value`, or an InvariantError with `message` when it is null or undefined. */
18
+ export function required<T>(value: T, message: string): NonNullable<T> {
19
+ if (value == null) throw new InvariantError(message);
20
+
21
+ return value;
22
+ }