@open-workspace/create 0.3.0 → 0.4.1

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,367 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Turning a directory (people, their aliases, groups and their members)
5
+ * into OpenWorkspace members, mailboxes and teams. Pure: the plan is what
6
+ * a dry run prints and what the command then carries out.
7
+ */
8
+
9
+ const directoryUserSchema = z.object({
10
+ email: z.string(),
11
+ name: z.string(),
12
+ aliases: z.array(z.string()),
13
+ suspended: z.boolean(),
14
+ isAdmin: z.boolean(),
15
+ });
16
+
17
+ export type DirectoryUser = z.infer<typeof directoryUserSchema>;
18
+
19
+ const directoryGroupSchema = z.object({
20
+ email: z.string(),
21
+ name: z.string(),
22
+ description: z.string().nullable(),
23
+ aliases: z.array(z.string()),
24
+ /** Member addresses (people or other groups), or "*" for everyone in the organization. */
25
+ members: z.array(z.string()),
26
+ /** A Google collaborative inbox: a shared inbox rather than a mailing list. */
27
+ sharedInbox: z.boolean(),
28
+ /** Who may write to it, when known. */
29
+ posting: z.enum(["anyone", "workspace", "members"]).nullable(),
30
+ });
31
+
32
+ export type DirectoryGroup = z.infer<typeof directoryGroupSchema>;
33
+
34
+ /** A directory, as read from Google or saved with --save-directory. */
35
+ export const directorySchema = z.object({
36
+ users: z.array(directoryUserSchema),
37
+ groups: z.array(directoryGroupSchema),
38
+ });
39
+
40
+ export type Directory = z.infer<typeof directorySchema>;
41
+
42
+ /** What the workspace already has (GET /api/admin/state, trimmed). */
43
+ export const workspaceStateSchema = z.object({
44
+ /** `mailDomains` from alchemy.run.ts, primary first: where new addresses may go. */
45
+ mailDomains: z.array(z.string()),
46
+ users: z.array(
47
+ z.object({
48
+ id: z.string(),
49
+ name: z.string(),
50
+ personalEmail: z.string().nullable(),
51
+ status: z.string(),
52
+ })
53
+ ),
54
+ mailboxes: z.array(
55
+ z.object({
56
+ id: z.string(),
57
+ address: z.string(),
58
+ ownerUserId: z.string().nullable(),
59
+ teamId: z.string().nullable(),
60
+ })
61
+ ),
62
+ teams: z.array(
63
+ z.object({ id: z.string(), slug: z.string(), name: z.string() })
64
+ ),
65
+ });
66
+
67
+ export type WorkspaceState = z.infer<typeof workspaceStateSchema>;
68
+
69
+ export type PlanOptions = {
70
+ includeSuspended: boolean;
71
+ /** Groups that are not collaborative inboxes become mailing lists (default) or shared inboxes. */
72
+ groupDelivery: "list" | "inbox";
73
+ };
74
+
75
+ export type Action =
76
+ | { kind: "invite"; name: string; email: string }
77
+ | { kind: "alias"; ownerEmail: string; address: string; displayName: string }
78
+ | {
79
+ kind: "team";
80
+ slug: string;
81
+ name: string;
82
+ description: string | null;
83
+ everyone: boolean;
84
+ memberEmails: string[];
85
+ }
86
+ | {
87
+ kind: "team-mailbox";
88
+ teamSlug: string;
89
+ address: string;
90
+ displayName: string;
91
+ delivery: "list" | "inbox";
92
+ listPosting: "anyone" | "workspace" | "members";
93
+ };
94
+
95
+ export type Plan = {
96
+ actions: Action[];
97
+ /** Already in the workspace, left as they are. */
98
+ existing: string[];
99
+ skipped: { what: string; reason: string }[];
100
+ /** Directory administrators, to make administrators by hand (that needs admin.access). */
101
+ administrators: string[];
102
+ };
103
+
104
+ const normalize = (address: string) => address.trim().toLowerCase();
105
+ const domainOf = (address: string) => normalize(address).split("@")[1] ?? "";
106
+ const localPart = (address: string) => normalize(address).split("@")[0] ?? "";
107
+
108
+ /** A team handle from a group address: lowercase letters, digits and single dashes. */
109
+ export function teamSlug(email: string) {
110
+ const slug = localPart(email)
111
+ .replaceAll(/[^a-z0-9]+/gu, "-")
112
+ .replaceAll(/^-+|-+$/gu, "")
113
+ .slice(0, 64)
114
+ .replace(/-+$/u, "");
115
+
116
+ return slug.length >= 2 ? slug : `team-${slug || "x"}`;
117
+ }
118
+
119
+ /** Names must be 2–80 characters. */
120
+ function displayName(name: string, fallback: string) {
121
+ const trimmed = name.trim().slice(0, 80);
122
+
123
+ return trimmed.length >= 2
124
+ ? trimmed
125
+ : localPart(fallback).slice(0, 80).padEnd(2, "-");
126
+ }
127
+
128
+ /** A group's members with nested groups flattened: everyone in the organization, or these people. */
129
+ type GroupMembers = { everyone: boolean; people: Set<string> };
130
+
131
+ export function planDirectory(
132
+ directory: Directory,
133
+ state: WorkspaceState,
134
+ options: PlanOptions
135
+ ): Plan {
136
+ const domains = new Set(state.mailDomains.map((domain) => normalize(domain)));
137
+
138
+ const takenAddresses = new Set(
139
+ state.mailboxes.map((mailbox) => normalize(mailbox.address))
140
+ );
141
+
142
+ const knownPeople = new Set(
143
+ state.users.flatMap((user) =>
144
+ user.personalEmail ? [normalize(user.personalEmail)] : []
145
+ )
146
+ );
147
+
148
+ const takenSlugs = new Set(state.teams.map((team) => team.slug));
149
+
150
+ const plan: Plan = {
151
+ actions: [],
152
+ existing: [],
153
+ skipped: [],
154
+ administrators: [],
155
+ };
156
+
157
+ const inWorkspace = (address: string) => domains.has(domainOf(address));
158
+
159
+ const claim = (address: string) => {
160
+ const key = normalize(address);
161
+
162
+ if (takenAddresses.has(key)) return false;
163
+ takenAddresses.add(key);
164
+
165
+ return true;
166
+ };
167
+
168
+ // People first: teams name them as members.
169
+ const people = new Set<string>(knownPeople);
170
+
171
+ for (const user of directory.users) {
172
+ const email = normalize(user.email);
173
+
174
+ if (user.suspended && !options.includeSuspended) {
175
+ plan.skipped.push({ what: email, reason: "suspended" });
176
+ continue;
177
+ }
178
+
179
+ if (!inWorkspace(email)) {
180
+ plan.skipped.push({
181
+ what: email,
182
+ reason: `${domainOf(email)} is not one of the workspace's mail domains`,
183
+ });
184
+ continue;
185
+ }
186
+
187
+ if (knownPeople.has(email)) {
188
+ plan.existing.push(email);
189
+ } else if (claim(email)) {
190
+ plan.actions.push({
191
+ kind: "invite",
192
+ name: displayName(user.name, email),
193
+ email,
194
+ });
195
+ } else {
196
+ plan.skipped.push({
197
+ what: email,
198
+ reason: "the address is already a mailbox",
199
+ });
200
+ continue;
201
+ }
202
+
203
+ people.add(email);
204
+
205
+ if (user.isAdmin) plan.administrators.push(email);
206
+
207
+ for (const alias of user.aliases.map(normalize)) {
208
+ if (!inWorkspace(alias)) {
209
+ plan.skipped.push({
210
+ what: alias,
211
+ reason: `alias of ${email} in another domain`,
212
+ });
213
+ } else if (claim(alias)) {
214
+ plan.actions.push({
215
+ kind: "alias",
216
+ ownerEmail: email,
217
+ address: alias,
218
+ displayName: displayName(user.name, email),
219
+ });
220
+ } else {
221
+ plan.existing.push(alias);
222
+ }
223
+ }
224
+ }
225
+
226
+ // Group members, nested groups flattened.
227
+ const groupsByEmail = new Map(
228
+ directory.groups.map((group) => [normalize(group.email), group])
229
+ );
230
+
231
+ const membersOf = (
232
+ group: DirectoryGroup,
233
+ seen = new Set<string>()
234
+ ): GroupMembers => {
235
+ const result: GroupMembers = { everyone: false, people: new Set<string>() };
236
+ seen.add(normalize(group.email));
237
+
238
+ for (const member of group.members.map(normalize)) {
239
+ if (member === "*") result.everyone = true;
240
+ const nested = groupsByEmail.get(member);
241
+
242
+ if (nested && !seen.has(member)) {
243
+ const inner = membersOf(nested, seen);
244
+ result.everyone ||= inner.everyone;
245
+
246
+ for (const person of inner.people) result.people.add(person);
247
+ } else if (people.has(member)) {
248
+ result.people.add(member);
249
+ }
250
+ }
251
+
252
+ return result;
253
+ };
254
+
255
+ for (const group of directory.groups) {
256
+ const email = normalize(group.email);
257
+ const addresses = [email, ...group.aliases.map(normalize)];
258
+ const slug = teamSlug(email);
259
+ const { everyone, people: members } = membersOf(group);
260
+
261
+ const outside = group.members
262
+ .map(normalize)
263
+ .filter(
264
+ (member) =>
265
+ member !== "*" && !groupsByEmail.has(member) && !people.has(member)
266
+ );
267
+
268
+ if (outside.length) {
269
+ plan.skipped.push({
270
+ what: `${email} members`,
271
+ reason: `not people here: ${outside.join(", ")}`,
272
+ });
273
+ }
274
+
275
+ if (takenSlugs.has(slug)) {
276
+ plan.existing.push(`team ${slug}`);
277
+ } else {
278
+ takenSlugs.add(slug);
279
+ plan.actions.push({
280
+ kind: "team",
281
+ slug,
282
+ name: displayName(group.name, email),
283
+ description: group.description?.slice(0, 240) || null,
284
+ everyone,
285
+ memberEmails: everyone ? [] : [...members],
286
+ });
287
+ }
288
+
289
+ const delivery = group.sharedInbox ? "inbox" : options.groupDelivery;
290
+
291
+ for (const address of addresses) {
292
+ if (!inWorkspace(address)) {
293
+ plan.skipped.push({
294
+ what: address,
295
+ reason: `${domainOf(address)} is not one of the workspace's mail domains`,
296
+ });
297
+ } else if (claim(address)) {
298
+ plan.actions.push({
299
+ kind: "team-mailbox",
300
+ teamSlug: slug,
301
+ address,
302
+ displayName: displayName(group.name, email),
303
+ delivery,
304
+ listPosting: group.posting ?? "workspace",
305
+ });
306
+ } else {
307
+ plan.existing.push(address);
308
+ }
309
+ }
310
+ }
311
+
312
+ return plan;
313
+ }
314
+
315
+ /** The plan as lines for a terminal. */
316
+ export function describePlan(plan: Plan) {
317
+ const lines: string[] = [];
318
+
319
+ for (const action of plan.actions) {
320
+ switch (action.kind) {
321
+ case "invite": {
322
+ lines.push(
323
+ `invite ${action.name} <${action.email}> (with a personal mailbox)`
324
+ );
325
+ break;
326
+ }
327
+
328
+ case "alias": {
329
+ lines.push(`mailbox ${action.address} for ${action.ownerEmail}`);
330
+ break;
331
+ }
332
+
333
+ case "team": {
334
+ lines.push(
335
+ `team ${action.name} (${action.slug}): ${action.everyone ? "everyone" : `${action.memberEmails.length} members`}`
336
+ );
337
+ break;
338
+ }
339
+
340
+ case "team-mailbox": {
341
+ lines.push(
342
+ `mailbox ${action.address} for team ${action.teamSlug}, ${action.delivery === "list" ? `mailing list (${action.listPosting} may post)` : "shared inbox"}`
343
+ );
344
+ break;
345
+ }
346
+
347
+ default: {
348
+ const unexpected: never = action;
349
+ throw new Error(`Unknown plan action ${JSON.stringify(unexpected)}`);
350
+ }
351
+ }
352
+ }
353
+
354
+ for (const what of plan.existing) lines.push(`exists ${what}`);
355
+
356
+ for (const { what, reason } of plan.skipped) {
357
+ lines.push(`skip ${what}: ${reason}`);
358
+ }
359
+
360
+ if (plan.administrators.length) {
361
+ lines.push(
362
+ `note administrators in the directory, to promote by hand: ${plan.administrators.join(", ")}`
363
+ );
364
+ }
365
+
366
+ return lines;
367
+ }
@@ -0,0 +1,195 @@
1
+ import { decodeWords } from "./headers.ts";
2
+ import type { Placement } from "./protocol.ts";
3
+
4
+ /**
5
+ * Gmail labels (Takeout's X-Gmail-Labels header, IMAP's X-GM-LABELS) mapped
6
+ * onto OpenWorkspace, where a conversation has one place and at most one
7
+ * custom folder, and read state is per message.
8
+ */
9
+
10
+ /** Splits Takeout's X-Gmail-Labels value: comma-separated, quoted when a label has a comma. */
11
+ export function parseGmailLabelsHeader(value: string) {
12
+ const labels: string[] = [];
13
+ let current = "";
14
+ let quoted = false;
15
+
16
+ for (let index = 0; index < value.length; index += 1) {
17
+ const char = value.charAt(index);
18
+
19
+ if (char === "\\" && quoted && index + 1 < value.length) {
20
+ current += value[index + 1];
21
+ index += 1;
22
+ } else if (char === '"') {
23
+ quoted = !quoted;
24
+ } else if (char === "," && !quoted) {
25
+ labels.push(current);
26
+ current = "";
27
+ } else {
28
+ current += char;
29
+ }
30
+ }
31
+
32
+ labels.push(current);
33
+
34
+ return labels.flatMap((label) => {
35
+ const decoded = decodeWords(label.trim());
36
+
37
+ return decoded ? [decoded] : [];
38
+ });
39
+ }
40
+
41
+ /** Labels that are Gmail's own state, not folders the person made. */
42
+ const SYSTEM_LABELS = new Set([
43
+ "inbox",
44
+ "sent",
45
+ "spam",
46
+ "trash",
47
+ "draft",
48
+ "drafts",
49
+ "unread",
50
+ "opened",
51
+ "starred",
52
+ "important",
53
+ "archived",
54
+ "chat",
55
+ "chats",
56
+ "all mail",
57
+ "muted",
58
+ "scheduled",
59
+ "snoozed",
60
+ ]);
61
+
62
+ function systemName(label: string) {
63
+ // IMAP spells system labels \Inbox, \Sent, \Important, ...
64
+ return label.replace(/^\\/u, "").toLowerCase();
65
+ }
66
+
67
+ function isUserLabel(label: string) {
68
+ const name = systemName(label);
69
+
70
+ return (
71
+ !label.startsWith("\\") &&
72
+ !SYSTEM_LABELS.has(name) &&
73
+ !name.startsWith("category ") &&
74
+ !name.startsWith("[imap]") &&
75
+ !name.startsWith("[gmail]")
76
+ );
77
+ }
78
+
79
+ export type GmailMessage = {
80
+ /** Drafts and chats have no place in a mailbox; they are skipped. */
81
+ skip: "draft" | "chat" | null;
82
+ placement: Placement;
83
+ /** Whether the message was read; null when the labels do not say. */
84
+ seen: boolean | null;
85
+ /**
86
+ * Whether it is mail the account sent. Mail sent to oneself is both Sent
87
+ * and in the Inbox; it is imported as received, so it shows in the Inbox.
88
+ */
89
+ sent: boolean;
90
+ /** The person's own labels, as folder candidates. */
91
+ userLabels: string[];
92
+ };
93
+
94
+ export type GmailOptions = {
95
+ /**
96
+ * What a message with the person's labels but not in the Inbox becomes:
97
+ * Archive (the labels are lost), or the Inbox in the label's folder.
98
+ * Custom folders here are views of the Inbox, so "folder" brings such
99
+ * mail back to the Inbox.
100
+ */
101
+ archivedLabels: "archive" | "folder";
102
+ };
103
+
104
+ /**
105
+ * A message's place from its labels: Trash, then Spam, then the Inbox, then
106
+ * (for labelled mail outside the Inbox) Archive or its folder, then Sent
107
+ * alone (no say over the conversation), then Archive.
108
+ */
109
+ export function gmailMessage(
110
+ labels: string[],
111
+ options: GmailOptions
112
+ ): GmailMessage {
113
+ const names = new Set(labels.map(systemName));
114
+
115
+ const userLabels = [
116
+ ...new Set(
117
+ labels.flatMap((label) => (isUserLabel(label) ? [label.trim()] : []))
118
+ ),
119
+ ];
120
+
121
+ const skip =
122
+ names.has("draft") || names.has("drafts")
123
+ ? "draft"
124
+ : names.has("chat") || names.has("chats")
125
+ ? "chat"
126
+ : null;
127
+
128
+ const sent = names.has("sent") && !names.has("inbox");
129
+
130
+ const placement: Placement = names.has("trash")
131
+ ? "trash"
132
+ : names.has("spam")
133
+ ? "spam"
134
+ : names.has("inbox")
135
+ ? "inbox"
136
+ : userLabels.length && options.archivedLabels === "folder"
137
+ ? "inbox"
138
+ : sent
139
+ ? "sent"
140
+ : "archive";
141
+
142
+ const seen = names.has("unread") ? false : names.has("opened") ? true : null;
143
+
144
+ return { skip, placement, seen, sent, userLabels };
145
+ }
146
+
147
+ /** OpenWorkspace folder names are at most 80 characters; nested labels keep their slashes. */
148
+ export function folderName(label: string) {
149
+ return label.trim().slice(0, 80);
150
+ }
151
+
152
+ /**
153
+ * Tallies the person's labels over each thread's messages, so every message
154
+ * of a thread names the same folder.
155
+ */
156
+ export class ThreadFolders {
157
+ private readonly counts = new Map<string, Map<string, number>>();
158
+
159
+ constructor(private readonly priority: string[] = []) {}
160
+
161
+ add(thread: string, labels: string[]) {
162
+ let tally = this.counts.get(thread);
163
+
164
+ if (!tally) this.counts.set(thread, (tally = new Map()));
165
+
166
+ for (const label of labels) tally.set(label, (tally.get(label) ?? 0) + 1);
167
+ }
168
+
169
+ /**
170
+ * The thread's folder: the first of `priority` it carries, else the label
171
+ * on most of its messages, else (ties) the first alphabetically.
172
+ */
173
+ folder(thread: string, fallback: string[] = []): string | null {
174
+ const tally =
175
+ this.counts.get(thread) ?? new Map(fallback.map((label) => [label, 1]));
176
+
177
+ if (!tally.size) return null;
178
+
179
+ const lower = new Map(
180
+ [...tally.keys()].map((label) => [label.toLowerCase(), label])
181
+ );
182
+
183
+ for (const preferred of this.priority) {
184
+ const found = lower.get(preferred.toLowerCase());
185
+
186
+ if (found) return folderName(found);
187
+ }
188
+
189
+ const [best] = [...tally.entries()].sort(
190
+ (a, b) => b[1] - a[1] || a[0].localeCompare(b[0])
191
+ );
192
+
193
+ return best ? folderName(best[0]) : null;
194
+ }
195
+ }
@@ -0,0 +1,105 @@
1
+ /** Reading the top-level headers of a raw RFC 5322 message, as much as an importer needs. */
2
+
3
+ const MAX_HEADER_BYTES = 256 * 1024;
4
+ const latin1 = new TextDecoder("latin1");
5
+
6
+ /** The header section of a raw message (bytes up to the first empty line), as text. */
7
+ export function headerText(raw: Uint8Array) {
8
+ const limit = Math.min(raw.byteLength, MAX_HEADER_BYTES);
9
+
10
+ for (let index = 0; index < limit; index += 1) {
11
+ if (raw[index] !== 10) continue;
12
+
13
+ if (raw[index + 1] === 10) return decodeHeader(raw.subarray(0, index));
14
+
15
+ if (raw[index + 1] === 13 && raw[index + 2] === 10) {
16
+ return decodeHeader(raw.subarray(0, index));
17
+ }
18
+ }
19
+
20
+ return decodeHeader(raw.subarray(0, limit));
21
+ }
22
+
23
+ /** UTF-8 where it is valid (raw UTF-8 headers are common), Latin-1 otherwise. */
24
+ function decodeHeader(bytes: Uint8Array) {
25
+ try {
26
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
27
+ } catch {
28
+ return latin1.decode(bytes);
29
+ }
30
+ }
31
+
32
+ export type HeaderFields = Map<string, string[]>;
33
+
34
+ /** Unfolded header fields by lowercased name, in order. */
35
+ export function parseHeaders(text: string): HeaderFields {
36
+ const fields: HeaderFields = new Map();
37
+
38
+ for (const line of text.replaceAll(/\r?\n[\t ]+/gu, " ").split(/\r?\n/u)) {
39
+ const colon = line.indexOf(":");
40
+
41
+ if (colon < 1) continue;
42
+ const name = line.slice(0, colon).trim().toLowerCase();
43
+ const value = line.slice(colon + 1).trim();
44
+ fields.set(name, [...(fields.get(name) ?? []), value]);
45
+ }
46
+
47
+ return fields;
48
+ }
49
+
50
+ export function header(fields: HeaderFields, name: string) {
51
+ return fields.get(name)?.[0];
52
+ }
53
+
54
+ /** Decodes RFC 2047 encoded words (`=?UTF-8?Q?...?=`), as Gmail writes non-ASCII label names. */
55
+ export function decodeWords(value: string) {
56
+ return value
57
+ .replaceAll(/(=\?[^?\s]+\?[BbQq]\?[^?\s]*\?=)\s+(?==\?)/gu, "$1")
58
+ .replaceAll(
59
+ /[=]\?([^?\s]+)\?([BbQq])\?([^?\s]*)\?=/gu,
60
+ (word, charset: string, encoding: string, text: string) => {
61
+ try {
62
+ const bytes =
63
+ encoding.toUpperCase() === "B"
64
+ ? Uint8Array.from(atob(text), (char) => char.charCodeAt(0))
65
+ : Uint8Array.from(
66
+ text
67
+ .replaceAll("_", " ")
68
+ .replaceAll(/[=]([0-9A-Fa-f]{2})/gu, (_, hex: string) =>
69
+ String.fromCharCode(Number.parseInt(hex, 16))
70
+ ),
71
+ (char) => char.charCodeAt(0)
72
+ );
73
+
74
+ // RFC 2231 puts a language after "*": "utf-8*en".
75
+ const [label = ""] = charset.split("*");
76
+
77
+ // SAFETY: Bun types the label as its list of known encodings; the constructor checks it at runtime and throws a RangeError for any other, which the catch below turns into the undecoded word.
78
+ return new TextDecoder(label.toLowerCase() as Bun.Encoding).decode(
79
+ bytes
80
+ );
81
+ } catch {
82
+ return word;
83
+ }
84
+ }
85
+ );
86
+ }
87
+
88
+ /** The message ids in a Message-ID, In-Reply-To or References value, in order. */
89
+ export function messageIds(value: string | undefined) {
90
+ return [...(value ?? "").matchAll(/<([^<>\s]+)>/gu)].map(([, id]) => id);
91
+ }
92
+
93
+ /**
94
+ * A thread key for mail without a source thread id: the first message of
95
+ * the thread its References name (else the one it replies to, else itself).
96
+ * Unlike threading by parent, it does not depend on import order.
97
+ */
98
+ export function rootThreadKey(fields: HeaderFields) {
99
+ const root =
100
+ messageIds(header(fields, "references"))[0] ??
101
+ messageIds(header(fields, "in-reply-to"))[0] ??
102
+ messageIds(header(fields, "message-id"))[0];
103
+
104
+ return root ? `mid:${root.toLowerCase()}` : undefined;
105
+ }