@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,218 @@
1
+ import { z } from "zod";
2
+
3
+ import type { Fetch, TokenSource } from "./oauth.ts";
4
+ import { importTargetSchema } from "./protocol.ts";
5
+ import type { ImportItem } from "./protocol.ts";
6
+
7
+ export class WorkspaceError extends Error {
8
+ constructor(
9
+ readonly status: number,
10
+ message: string,
11
+ readonly code?: string
12
+ ) {
13
+ super(message);
14
+ this.name = "WorkspaceError";
15
+ }
16
+ }
17
+
18
+ export type ImportResult =
19
+ | {
20
+ status: "imported";
21
+ id: string;
22
+ conversationId: string;
23
+ folderSkipped: string | null;
24
+ }
25
+ | { status: "duplicate"; id: string; conversationId: string };
26
+
27
+ /** The workspace's HTTP API, signed in with an OAuth token. */
28
+ export class Workspace {
29
+ readonly origin: string;
30
+
31
+ constructor(
32
+ workspace: string,
33
+ private readonly auth: TokenSource,
34
+ private readonly fetchImpl: Fetch = (input, init) => fetch(input, init)
35
+ ) {
36
+ this.origin = new URL(workspace).origin;
37
+ }
38
+
39
+ /** A request with the token; a refused token is refreshed once. */
40
+ async request(path: string, init: RequestInit = {}): Promise<Response> {
41
+ const send = (token: string) => {
42
+ const headers = new Headers(init.headers);
43
+ headers.set("authorization", `Bearer ${token}`);
44
+
45
+ return this.fetchImpl(`${this.origin}${path}`, { ...init, headers });
46
+ };
47
+
48
+ const response = await send(await this.auth.token());
49
+
50
+ if (response.status !== 401) return response;
51
+ await response.body?.cancel();
52
+
53
+ return send(await this.auth.refresh());
54
+ }
55
+
56
+ /** The API's JSON answer parsed with `schema`, or a WorkspaceError with its message. */
57
+ async json<Schema extends z.ZodType>(
58
+ path: string,
59
+ schema: Schema,
60
+ init: JsonRequest = {}
61
+ ): Promise<z.output<Schema>> {
62
+ return parse(await this.send(path, init), schema);
63
+ }
64
+
65
+ /** A request whose answer only needs to be a success; else a WorkspaceError. */
66
+ async call(path: string, init: JsonRequest = {}): Promise<void> {
67
+ await parse(await this.send(path, init), z.unknown());
68
+ }
69
+
70
+ private send(path: string, init: JsonRequest) {
71
+ return this.request(path, {
72
+ method: init.method ?? "GET",
73
+ headers:
74
+ init.body === undefined ? {} : { "content-type": "application/json" },
75
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
76
+ });
77
+ }
78
+
79
+ importTargets() {
80
+ return this.json(
81
+ "/api/mail/import/mailboxes",
82
+ z.object({ mailboxes: z.array(importTargetSchema) })
83
+ ).then((body) => body.mailboxes);
84
+ }
85
+
86
+ /** A mailbox this sign-in may import into, by id or address. */
87
+ async importTarget(idOrAddress: string) {
88
+ const wanted = idOrAddress.trim().toLowerCase();
89
+ const targets = await this.importTargets();
90
+
91
+ const target = targets.find(
92
+ (item) =>
93
+ item.id.toLowerCase() === wanted ||
94
+ item.address.toLowerCase() === wanted
95
+ );
96
+
97
+ if (!target) {
98
+ throw new Error(
99
+ `You may not import into ${idOrAddress} (or it does not exist). You may import into: ${
100
+ targets.map((item) => item.address).join(", ") || "no mailbox"
101
+ }`
102
+ );
103
+ }
104
+
105
+ return target;
106
+ }
107
+
108
+ async importMessage(
109
+ mailboxId: string,
110
+ item: ImportItem
111
+ ): Promise<ImportResult> {
112
+ const query = new URLSearchParams({
113
+ sourceId: item.sourceId,
114
+ placement: item.placement,
115
+ });
116
+
117
+ if (item.folder) query.set("folder", item.folder);
118
+
119
+ if (item.seen) query.set("seen", "1");
120
+
121
+ if (item.thread) query.set("thread", item.thread);
122
+
123
+ if (item.receivedAt !== undefined) {
124
+ query.set("receivedAt", String(item.receivedAt));
125
+ }
126
+
127
+ if (item.direction) query.set("direction", item.direction);
128
+
129
+ const response = await this.request(
130
+ `/api/mail/import/mailboxes/${encodeURIComponent(mailboxId)}/messages?${query}`,
131
+ {
132
+ method: "POST",
133
+ headers: { "content-type": "message/rfc822" },
134
+ body: item.raw,
135
+ }
136
+ );
137
+
138
+ const body = await parse(response, importResponseSchema);
139
+
140
+ return body.duplicate
141
+ ? {
142
+ status: "duplicate",
143
+ id: body.id,
144
+ conversationId: body.conversationId,
145
+ }
146
+ : {
147
+ status: "imported",
148
+ id: body.id,
149
+ conversationId: body.conversationId,
150
+ folderSkipped: body.folderSkipped ?? null,
151
+ };
152
+ }
153
+
154
+ finishImport(mailboxId: string) {
155
+ return this.json(
156
+ `/api/mail/import/mailboxes/${encodeURIComponent(mailboxId)}/finish`,
157
+ z.object({ version: z.number() }),
158
+ { method: "POST" }
159
+ );
160
+ }
161
+ }
162
+
163
+ type JsonRequest = { method?: string; body?: unknown };
164
+
165
+ const importResponseSchema = z.object({
166
+ duplicate: z.boolean(),
167
+ id: z.string(),
168
+ conversationId: z.string(),
169
+ folderSkipped: z.string().nullish(),
170
+ });
171
+
172
+ /** The API's error envelope; anything else (a proxy's error page) leaves it empty. */
173
+ const errorSchema = z.object({
174
+ error: z
175
+ .object({ code: z.string().optional(), message: z.string().optional() })
176
+ .optional(),
177
+ });
178
+
179
+ type JsonValue = z.core.util.JSONType;
180
+
181
+ function parseJson(text: string): JsonValue | undefined {
182
+ try {
183
+ return JSON.parse(text);
184
+ } catch {
185
+ // Not JSON: a proxy's or the platform's error page.
186
+ return undefined;
187
+ }
188
+ }
189
+
190
+ async function parse<Schema extends z.ZodType>(
191
+ response: Response,
192
+ schema: Schema
193
+ ): Promise<z.output<Schema>> {
194
+ const text = await response.text();
195
+ const json = parseJson(text);
196
+
197
+ if (!response.ok) {
198
+ const envelope = errorSchema.safeParse(json);
199
+ const error = envelope.success ? envelope.data.error : undefined;
200
+
201
+ throw new WorkspaceError(
202
+ response.status,
203
+ error?.message ?? (text.slice(0, 200) || response.statusText),
204
+ error?.code
205
+ );
206
+ }
207
+
208
+ const body = schema.safeParse(json);
209
+
210
+ if (!body.success) {
211
+ throw new WorkspaceError(
212
+ response.status,
213
+ `Unexpected answer from ${response.url || "the workspace"}: ${z.prettifyError(body.error)}`
214
+ );
215
+ }
216
+
217
+ return body.data;
218
+ }
package/index.ts CHANGED
@@ -1,118 +1,16 @@
1
1
  #!/usr/bin/env bun
2
- import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
3
- import { join, resolve } from "node:path";
4
- import * as p from "@clack/prompts";
5
- import {
6
- alchemyRunTs,
7
- envFile,
8
- gitignore,
9
- packageJson,
10
- readme,
11
- tsconfigJson,
12
- workerTs,
13
- type ProjectAnswers,
14
- } from "./templates";
15
-
16
- const DOMAIN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
17
- const NAME = /^[a-z0-9][a-z0-9-]{0,62}$/u;
18
-
19
- function cancelled<T>(value: T): Exclude<T, symbol> {
20
- if (p.isCancel(value)) {
21
- p.cancel("Nothing was created.");
22
- process.exit(1);
23
- }
24
- return value as Exclude<T, symbol>;
25
- }
26
-
27
- p.intro("OpenWorkspace");
28
-
29
- const name = cancelled(await p.text({
30
- message: "Project name (also the Worker's name)",
31
- placeholder: "acme-workspace",
32
- initialValue: process.argv[2] ?? "",
33
- validate: (value) => NAME.test(value ?? "") ? undefined : "Use lowercase letters, digits, and dashes",
34
- }));
35
- const directory = resolve(name);
36
- if (existsSync(directory) && readdirSync(directory).length > 0) {
37
- p.cancel(`${directory} is not empty.`);
38
- process.exit(1);
39
- }
40
-
41
- const mailDomains = cancelled(await p.text({
42
- message: "Mail domains, primary first (zones in your Cloudflare account)",
43
- placeholder: "acme.com",
44
- validate: (value) => {
45
- const domains = (value ?? "").split(/[\s,]+/u).filter(Boolean);
46
- if (domains.length === 0) return "Enter at least one domain";
47
- return domains.every((domain) => DOMAIN.test(domain.toLowerCase())) ? undefined : "Use bare domains such as acme.com";
48
- },
49
- })).split(/[\s,]+/u).filter(Boolean).map((domain) => domain.toLowerCase());
50
-
51
- const domain = cancelled(await p.text({
52
- message: "Where the app is served",
53
- initialValue: `mail.${mailDomains[0]}`,
54
- validate: (value) => DOMAIN.test((value ?? "").toLowerCase()) ? undefined : "Use a hostname such as mail.acme.com",
55
- })).toLowerCase();
56
-
57
- const configureMail = cancelled(await p.confirm({
58
- message: "Let Alchemy set up Email Routing and Email Sending for these domains?",
59
- initialValue: true,
60
- }));
61
-
62
- const ai = cancelled(await p.select({
63
- message: "AI for spam filtering, folders, and translation",
64
- options: [
65
- { value: "cloudflare", label: "Cloudflare AI Gateway", hint: "no key; uses your account's AI credits" },
66
- { value: "openai", label: "OpenAI", hint: "needs an API key" },
67
- { value: "anthropic", label: "Anthropic", hint: "needs an API key" },
68
- { value: "none", label: "None" },
69
- ],
70
- })) as ProjectAnswers["ai"];
71
-
72
- let aiKey: { name: string; value: string } | undefined;
73
- if (ai === "openai" || ai === "anthropic") {
74
- const keyName = ai === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY";
75
- const value = cancelled(await p.password({
76
- message: `${keyName} (stored in .env; leave empty to add it later)`,
77
- }));
78
- if (value) aiKey = { name: keyName, value };
79
- }
80
-
81
- const answers: ProjectAnswers = { name, domain, mailDomains, configureMail, ai };
82
- const spinner = p.spinner();
83
- spinner.start("Writing the project");
84
- mkdirSync(join(directory, "src"), { recursive: true });
85
- const files: Record<string, string> = {
86
- "package.json": packageJson(answers),
87
- "alchemy.run.ts": alchemyRunTs(answers),
88
- "src/worker.ts": workerTs(answers),
89
- "tsconfig.json": tsconfigJson,
90
- ".gitignore": gitignore,
91
- "README.md": readme(answers),
92
- ".env": envFile({ aiKey }),
93
- };
94
- for (const [file, content] of Object.entries(files)) {
95
- writeFileSync(join(directory, file), content);
96
- }
97
- spinner.stop("Project written");
98
-
99
- if (cancelled(await p.confirm({ message: "Install dependencies with bun?", initialValue: true }))) {
100
- spinner.start("bun install");
101
- const install = Bun.spawnSync(["bun", "install"], { cwd: directory, stdout: "ignore", stderr: "pipe" });
102
- if (install.exitCode === 0) {
103
- spinner.stop("Dependencies installed");
104
- } else {
105
- spinner.stop("bun install failed; run it yourself");
106
- p.log.error(install.stderr.toString());
107
- }
2
+ // `bun create @open-workspace` writes a new project; `… module <name>` adds a
3
+ // module to one; `… import` brings people and mail into a deployed workspace.
4
+ if (process.argv[2] === "module") {
5
+ const { main } = await import("./module.ts");
6
+ process.exitCode = main(process.argv.slice(3));
7
+ } else if (process.argv[2] === "import") {
8
+ const { main } = await import("./import/cli.ts");
9
+ process.exitCode = await main(process.argv.slice(3));
10
+ } else {
11
+ const { main } = await import("./create.ts");
12
+ process.exitCode = await main(process.argv.slice(2));
108
13
  }
109
14
 
110
- p.note(
111
- [
112
- `cd ${name}`,
113
- "bun alchemy profile edit --add Cloudflare # once",
114
- "bun run deploy",
115
- ].join("\n"),
116
- "Next",
117
- );
118
- p.outro(`Then open https://${domain} and create the first administrator.`);
15
+ // oxlint-disable-next-line unicorn/require-module-specifiers -- marks the bin script as a module for top-level await
16
+ export {};