@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,174 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import {
5
+ folderName,
6
+ gmailMessage,
7
+ parseGmailLabelsHeader,
8
+ ThreadFolders,
9
+ } from "./gmail.ts";
10
+ import type { GmailOptions } from "./gmail.ts";
11
+ import { header, headerText, parseHeaders, rootThreadKey } from "./headers.ts";
12
+ import type { HeaderFields } from "./headers.ts";
13
+ import { fromLineDate, readMbox } from "./mbox.ts";
14
+ import type { MboxMessage } from "./mbox.ts";
15
+ import { MAX_IMPORT_MESSAGE_BYTES } from "./protocol.ts";
16
+ import type { ImportItem, Placement, SkippedItem } from "./protocol.ts";
17
+
18
+ /**
19
+ * Mail from mbox files: a Google Takeout export (its X-Gmail-Labels and
20
+ * X-GM-THRID headers give each message's place, read state and thread) or
21
+ * any other mbox (one place for all of it, read state from Status).
22
+ */
23
+
24
+ export type MboxSourceOptions = GmailOptions & {
25
+ /** Labels to prefer as a thread's folder, in order. */
26
+ folderPriority: string[];
27
+ /** Places not to import (e.g. spam, trash). */
28
+ skip: Set<Placement>;
29
+ /** For mbox files without Gmail labels: where the mail goes, and in which folder. */
30
+ placement: Placement;
31
+ folder: string | null;
32
+ };
33
+
34
+ /** The mbox files at these paths: files as given, directories searched for *.mbox (a Takeout folder). */
35
+ export function mboxFiles(paths: string[]) {
36
+ const files: string[] = [];
37
+
38
+ const walk = (path: string) => {
39
+ if (statSync(path).isDirectory()) {
40
+ for (const entry of readdirSync(path).sort()) walk(join(path, entry));
41
+ } else if (path.toLowerCase().endsWith(".mbox") || paths.includes(path)) {
42
+ files.push(path);
43
+ }
44
+ };
45
+
46
+ for (const path of paths) walk(path);
47
+
48
+ return files;
49
+ }
50
+
51
+ /**
52
+ * The files' messages, one file after another.
53
+ * @yields {MboxMessage} Each message of each file, in order.
54
+ */
55
+ async function* messages(files: string[]) {
56
+ for (const file of files) {
57
+ yield* readMbox(Bun.file(file).stream(), {
58
+ maxBytes: MAX_IMPORT_MESSAGE_BYTES,
59
+ });
60
+ }
61
+ }
62
+
63
+ function threadOf(fields: HeaderFields) {
64
+ const gmailThread = header(fields, "x-gm-thrid");
65
+
66
+ return gmailThread ? `gmail:${gmailThread}` : rootThreadKey(fields);
67
+ }
68
+
69
+ /** First pass: how many messages there are, and which labels each Gmail thread carries. */
70
+ export async function scanMbox(files: string[], options: MboxSourceOptions) {
71
+ const threads = new ThreadFolders(options.folderPriority);
72
+ let count = 0;
73
+ let bytes = 0;
74
+
75
+ for await (const message of messages(files)) {
76
+ count += 1;
77
+ bytes += message.size;
78
+
79
+ if (message.tooLarge) continue;
80
+ const fields = parseHeaders(headerText(message.raw));
81
+ const labels = header(fields, "x-gmail-labels");
82
+ const thread = threadOf(fields);
83
+
84
+ if (labels !== undefined && thread) {
85
+ threads.add(
86
+ thread,
87
+ gmailMessage(parseGmailLabelsHeader(labels), options).userLabels
88
+ );
89
+ }
90
+ }
91
+
92
+ return { count, bytes, threads };
93
+ }
94
+
95
+ /** Read state from a Status header (R is read); mail without one is old, so read. */
96
+ function statusSeen(fields: HeaderFields) {
97
+ const status = header(fields, "status");
98
+
99
+ return status === undefined ? true : status.includes("R");
100
+ }
101
+
102
+ /** What to import for one mbox message, or why it is skipped. */
103
+ export function mboxItem(
104
+ message: MboxMessage,
105
+ options: MboxSourceOptions,
106
+ threads: ThreadFolders
107
+ ): ImportItem | SkippedItem {
108
+ if (message.tooLarge) {
109
+ return {
110
+ sourceId: `mbox-large:${message.fromLine}:${message.size}`,
111
+ skipped: "too large",
112
+ };
113
+ }
114
+
115
+ const sourceId = `mbox:${new Bun.CryptoHasher("sha256").update(message.raw).digest("hex")}`;
116
+ const fields = parseHeaders(headerText(message.raw));
117
+ const thread = threadOf(fields);
118
+ const receivedAt = fromLineDate(message.fromLine);
119
+ const labels = header(fields, "x-gmail-labels");
120
+
121
+ if (labels === undefined) {
122
+ if (options.skip.has(options.placement)) {
123
+ return { sourceId, skipped: options.placement };
124
+ }
125
+
126
+ return {
127
+ sourceId,
128
+ raw: message.raw,
129
+ placement: options.placement,
130
+ folder: options.placement === "inbox" ? options.folder : null,
131
+ seen: statusSeen(fields),
132
+ thread,
133
+ receivedAt,
134
+ };
135
+ }
136
+
137
+ const gmail = gmailMessage(parseGmailLabelsHeader(labels), options);
138
+
139
+ if (gmail.skip) return { sourceId, skipped: gmail.skip };
140
+
141
+ if (options.skip.has(gmail.placement)) {
142
+ return { sourceId, skipped: gmail.placement };
143
+ }
144
+
145
+ const folder =
146
+ gmail.placement === "inbox" && thread
147
+ ? threads.folder(thread, gmail.userLabels)
148
+ : gmail.placement === "inbox" && gmail.userLabels[0]
149
+ ? folderName(gmail.userLabels[0])
150
+ : null;
151
+
152
+ return {
153
+ sourceId,
154
+ raw: message.raw,
155
+ placement: gmail.placement,
156
+ folder,
157
+ // Takeout says Unread or Opened; neither is old mail, read.
158
+ seen: gmail.seen ?? true,
159
+ thread,
160
+ receivedAt,
161
+ // Gmail's Sent label says it, not the From address (which may be an alias).
162
+ direction: gmail.sent ? "outgoing" : "incoming",
163
+ };
164
+ }
165
+
166
+ export async function* mboxItems(
167
+ files: string[],
168
+ options: MboxSourceOptions,
169
+ threads: ThreadFolders
170
+ ) {
171
+ for await (const message of messages(files)) {
172
+ yield mboxItem(message, options, threads);
173
+ }
174
+ }
package/import/mbox.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * A streaming mbox reader: messages one at a time, however large the file.
3
+ * Messages start at a "From " line at the start of the file or after an
4
+ * empty line; the empty line before it belongs to no message. Body lines
5
+ * escaped as ">From " (mboxrd's ">+From ") lose one ">".
6
+ */
7
+
8
+ export type MboxMessage = {
9
+ /** The message's bytes, or empty when it was larger than `maxBytes`. */
10
+ raw: Uint8Array<ArrayBuffer>;
11
+ /** The separator line ("From sender date"), without the line break. */
12
+ fromLine: string;
13
+ /** Position in the file, from 0. */
14
+ index: number;
15
+ /** The message's size in bytes (counted even when it was too large to keep). */
16
+ size: number;
17
+ tooLarge: boolean;
18
+ };
19
+
20
+ const FROM = [70, 114, 111, 109, 32]; // "From "
21
+ const decoder = new TextDecoder("latin1");
22
+
23
+ function startsWithFrom(line: Uint8Array, offset = 0) {
24
+ for (let index = 0; index < FROM.length; index += 1) {
25
+ if (line[offset + index] !== FROM[index]) return false;
26
+ }
27
+
28
+ return true;
29
+ }
30
+
31
+ function isBlank(line: Uint8Array) {
32
+ return (
33
+ (line.length === 1 && line[0] === 10) ||
34
+ (line.length === 2 && line[0] === 13 && line[1] === 10)
35
+ );
36
+ }
37
+
38
+ function concat(parts: Uint8Array[], size: number) {
39
+ const out = new Uint8Array(size);
40
+ let offset = 0;
41
+
42
+ for (const part of parts) {
43
+ out.set(part, offset);
44
+ offset += part.byteLength;
45
+ }
46
+
47
+ return out;
48
+ }
49
+
50
+ export async function* readMbox(
51
+ stream: AsyncIterable<Uint8Array>,
52
+ options: { maxBytes: number }
53
+ ): AsyncGenerator<MboxMessage> {
54
+ let pending: Uint8Array = new Uint8Array(0);
55
+ let lines: Uint8Array[] = [];
56
+ let size = 0;
57
+ let fromLine: string | null = null;
58
+ let index = 0;
59
+ let tooLarge = false;
60
+ let previousBlank = true;
61
+ const ready: MboxMessage[] = [];
62
+
63
+ const finishMessage = () => {
64
+ if (fromLine === null) return;
65
+ // The empty line before the next "From " separates; it is not the message's.
66
+ const last = lines.at(-1);
67
+
68
+ if (last && isBlank(last)) {
69
+ lines.pop();
70
+ size -= last.byteLength;
71
+ }
72
+
73
+ ready.push({
74
+ raw: tooLarge ? new Uint8Array(0) : concat(lines, size),
75
+ fromLine,
76
+ index,
77
+ size,
78
+ tooLarge,
79
+ });
80
+ index += 1;
81
+ lines = [];
82
+ size = 0;
83
+ tooLarge = false;
84
+ };
85
+
86
+ const line = (bytes: Uint8Array) => {
87
+ if (previousBlank && startsWithFrom(bytes)) {
88
+ finishMessage();
89
+ fromLine = decoder.decode(bytes).replace(/\r?\n$/u, "");
90
+ previousBlank = false;
91
+
92
+ return;
93
+ }
94
+
95
+ previousBlank = isBlank(bytes);
96
+
97
+ if (fromLine === null) return;
98
+ let content = bytes;
99
+
100
+ if (content[0] === 62) {
101
+ let quotes = 0;
102
+
103
+ while (content[quotes] === 62) quotes += 1;
104
+
105
+ if (startsWithFrom(content, quotes)) content = content.subarray(1);
106
+ }
107
+
108
+ size += content.byteLength;
109
+
110
+ if (tooLarge) return;
111
+
112
+ if (size > options.maxBytes) {
113
+ tooLarge = true;
114
+ // An empty line may end the message; keep only that much.
115
+ lines = isBlank(content) ? [content] : [];
116
+
117
+ return;
118
+ }
119
+
120
+ lines.push(content);
121
+ };
122
+
123
+ for await (const chunk of stream) {
124
+ const data = pending.byteLength
125
+ ? concat([pending, chunk], pending.byteLength + chunk.byteLength)
126
+ : chunk;
127
+
128
+ let start = 0;
129
+
130
+ for (
131
+ let newline = data.indexOf(10, start);
132
+ newline !== -1;
133
+ newline = data.indexOf(10, start)
134
+ ) {
135
+ line(data.subarray(start, newline + 1));
136
+ start = newline + 1;
137
+ }
138
+
139
+ pending = data.slice(start);
140
+ yield* ready.splice(0);
141
+ }
142
+
143
+ if (pending.byteLength) line(pending);
144
+ finishMessage();
145
+ yield* ready.splice(0);
146
+ }
147
+
148
+ const MONTHS = [
149
+ "jan",
150
+ "feb",
151
+ "mar",
152
+ "apr",
153
+ "may",
154
+ "jun",
155
+ "jul",
156
+ "aug",
157
+ "sep",
158
+ "oct",
159
+ "nov",
160
+ "dec",
161
+ ];
162
+
163
+ /**
164
+ * The date on an mbox "From " line, in ms: Gmail's Takeout writes when the
165
+ * message arrived there ("From 1781…@xxx Tue Mar 03 10:00:00 +0000 2026").
166
+ * Classic ctime dates without a zone are read as UTC.
167
+ */
168
+ export function fromLineDate(fromLine: string) {
169
+ const match =
170
+ /\s(?:[A-Za-z]{3}),?\s+([A-Za-z]{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})(?:\s+([+-]\d{4}))?\s+(\d{4})\s*$/u.exec(
171
+ fromLine
172
+ );
173
+
174
+ if (!match) return undefined;
175
+ const [, monthName = ""] = match;
176
+ const month = MONTHS.indexOf(monthName.toLowerCase());
177
+
178
+ if (month === -1) return undefined;
179
+
180
+ const utc = Date.UTC(
181
+ Number(match[7]),
182
+ month,
183
+ Number(match[2]),
184
+ Number(match[3]),
185
+ Number(match[4]),
186
+ Number(match[5])
187
+ );
188
+
189
+ const zone = match[6];
190
+
191
+ const offset = zone
192
+ ? (zone[0] === "-" ? -1 : 1) *
193
+ (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(3, 5))) *
194
+ 60_000
195
+ : 0;
196
+
197
+ return utc - offset;
198
+ }