@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,258 @@
1
+ #!/usr/bin/env bun
2
+ // Runs inside a new project (its working directory) with the project's own
3
+ // Alchemy, so it reads and writes Alchemy profiles exactly as `alchemy deploy`
4
+ // will. `create` spawns it and reads one JSON line from stdout:
5
+ //
6
+ // bun alchemy-helper.ts credentials the Cloudflare credentials a deploy would use
7
+ // bun alchemy-helper.ts profiles every profile's Cloudflare method and account
8
+ // bun alchemy-helper.ts set-account <id> point the profile's Cloudflare login at an account
9
+ //
10
+ // The profile is the one Alchemy selects: $ALCHEMY_PROFILE, else "default".
11
+ // Nothing here prompts; signing in is `alchemy profile edit`, run by create.
12
+ import { join } from "node:path";
13
+
14
+ import type {
15
+ CloudflareAuthConfig,
16
+ CloudflareResolvedCredentials,
17
+ } from "@alchemy.run/cloudflare/Auth/AuthConfig";
18
+ import type { Services } from "alchemy/Alchemist/Runtime";
19
+ import type { AuthProviders } from "alchemy/Auth/AuthProvider";
20
+ import type { Effect as Program } from "effect/Effect";
21
+ import type { Scope } from "effect/Scope";
22
+
23
+ import type {
24
+ CredentialsReply,
25
+ HelperReply,
26
+ ProfilesReply,
27
+ SetAccountReply,
28
+ } from "./alchemy-protocol.ts";
29
+
30
+ /** Resolves a module from the project's dependencies, not this package's. */
31
+ function fromProject(specifier: string) {
32
+ return Bun.resolveSync(specifier, join(process.cwd(), "package.json"));
33
+ }
34
+
35
+ const Effect: typeof import("effect/Effect") = await import(
36
+ fromProject("effect/Effect")
37
+ );
38
+
39
+ const Layer: typeof import("effect/Layer") = await import(
40
+ fromProject("effect/Layer")
41
+ );
42
+
43
+ const Option: typeof import("effect/Option") = await import(
44
+ fromProject("effect/Option")
45
+ );
46
+
47
+ const Schema: typeof import("effect/Schema") = await import(
48
+ fromProject("effect/Schema")
49
+ );
50
+
51
+ const Redacted: typeof import("effect/Redacted") = await import(
52
+ fromProject("effect/Redacted")
53
+ );
54
+
55
+ const Alchemist: typeof import("alchemy/Alchemist") = await import(
56
+ fromProject("alchemy/Alchemist")
57
+ );
58
+
59
+ const Auth: typeof import("alchemy/Auth/AuthProvider") = await import(
60
+ fromProject("alchemy/Auth/AuthProvider")
61
+ );
62
+
63
+ const Profile: typeof import("alchemy/Auth/Profile") = await import(
64
+ fromProject("alchemy/Auth/Profile")
65
+ );
66
+
67
+ const Resolve: typeof import("alchemy/Auth/Resolve") = await import(
68
+ fromProject("alchemy/Auth/Resolve")
69
+ );
70
+
71
+ const CloudflareAuth: typeof import("@alchemy.run/cloudflare/Auth/AuthProvider") =
72
+ await import(fromProject("@alchemy.run/cloudflare/Auth/AuthProvider"));
73
+
74
+ const CloudflareConfig: typeof import("@alchemy.run/cloudflare/Auth/AuthConfig") =
75
+ await import(fromProject("@alchemy.run/cloudflare/Auth/AuthConfig"));
76
+
77
+ const PROVIDER = CloudflareConfig.CLOUDFLARE_AUTH_PROVIDER_NAME;
78
+
79
+ const storedAccountSchema = Schema.Struct({
80
+ method: Schema.String,
81
+ accountId: Schema.optional(Schema.String),
82
+ });
83
+
84
+ /**
85
+ * The Cloudflare credentials `alchemy deploy` resolves, by the same rules:
86
+ * CLOUDFLARE_API_TOKEN (or _API_KEY) with CLOUDFLARE_ACCOUNT_ID first, then
87
+ * the selected profile, refreshing an expired OAuth token and saving it.
88
+ */
89
+ function credentials() {
90
+ return Effect.gen(function* () {
91
+ const registry: AuthProviders["Service"] = {};
92
+ const withRegistry = Effect.provideService(Auth.AuthProviders, registry);
93
+
94
+ yield* Layer.build(CloudflareAuth.CloudflareAuth).pipe(withRegistry);
95
+
96
+ const store = yield* Profile.ProfileStore;
97
+ const { name: profile } = yield* store.current;
98
+
99
+ const stored = Schema.decodeUnknownOption(storedAccountSchema)(
100
+ (yield* store.getProfile(profile))?.providers[PROVIDER]
101
+ );
102
+
103
+ const selected = yield* Resolve.resolveProviderConfig<
104
+ CloudflareAuthConfig,
105
+ CloudflareResolvedCredentials
106
+ >(PROVIDER).pipe(
107
+ withRegistry,
108
+ Effect.provideService(Profile.SuppressMissingProviderConfig, true)
109
+ );
110
+
111
+ const resolved = yield* selected.resolve;
112
+ const { source } = selected;
113
+
114
+ const auth =
115
+ resolved.type === "apiKey"
116
+ ? {
117
+ type: "apiKey" as const,
118
+ key: Redacted.value(resolved.apiKey),
119
+ email: Redacted.value(resolved.email),
120
+ }
121
+ : {
122
+ type: "token" as const,
123
+ token: Redacted.value(
124
+ resolved.type === "apiToken"
125
+ ? resolved.apiToken
126
+ : resolved.accessToken
127
+ ),
128
+ };
129
+
130
+ const reply: CredentialsReply = {
131
+ status: "ok",
132
+ source,
133
+ profile,
134
+ method:
135
+ source === "environment"
136
+ ? "environment"
137
+ : Option.match(stored, {
138
+ onNone: () => "unknown",
139
+ onSome: (value) => value.method,
140
+ }),
141
+ accountId: resolved.accountId,
142
+ auth,
143
+ };
144
+
145
+ return reply;
146
+ }).pipe(
147
+ Effect.catch((failure) => {
148
+ const reply: CredentialsReply = {
149
+ status:
150
+ failure._tag === "MissingProviderConfig" ? "missing" : "invalid",
151
+ message: failure.message,
152
+ };
153
+
154
+ return Effect.succeed(reply);
155
+ })
156
+ );
157
+ }
158
+
159
+ /** Every profile with a Cloudflare login, and the account it deploys to. */
160
+ function profiles() {
161
+ return Effect.gen(function* () {
162
+ const store = yield* Profile.ProfileStore;
163
+ const { name: active } = yield* store.current;
164
+ const manifest = yield* store.readManifest;
165
+
166
+ const reply: ProfilesReply = {
167
+ status: "ok",
168
+ active,
169
+ profiles: Object.entries(manifest.profiles).map(([name, profile]) => ({
170
+ name,
171
+ cloudflare: Option.getOrUndefined(
172
+ Schema.decodeUnknownOption(storedAccountSchema)(
173
+ profile.providers[PROVIDER]
174
+ )
175
+ ),
176
+ })),
177
+ };
178
+
179
+ return reply;
180
+ }).pipe(
181
+ Effect.catch((failure) => {
182
+ const reply: ProfilesReply = {
183
+ status: "invalid",
184
+ message: failure.message,
185
+ };
186
+
187
+ return Effect.succeed(reply);
188
+ })
189
+ );
190
+ }
191
+
192
+ /** Points the selected profile's Cloudflare login at another account its credentials reach. */
193
+ function setAccount(accountId: string) {
194
+ return Effect.gen(function* () {
195
+ const store = yield* Profile.ProfileStore;
196
+ const { name: profile } = yield* store.current;
197
+ const stored = (yield* store.getProfile(profile))?.providers[PROVIDER];
198
+
199
+ if (stored === undefined) {
200
+ const missing: SetAccountReply = {
201
+ status: "missing",
202
+ message: `Profile '${profile}' has no Cloudflare login.`,
203
+ };
204
+
205
+ return missing;
206
+ }
207
+
208
+ const id = yield* CloudflareConfig.validateAccountId(
209
+ accountId,
210
+ "chosen in bun create @open-workspace"
211
+ );
212
+
213
+ yield* store.setProviderConfig(profile, PROVIDER, {
214
+ ...stored,
215
+ accountId: id,
216
+ });
217
+
218
+ const reply: SetAccountReply = { status: "ok", profile, accountId: id };
219
+
220
+ return reply;
221
+ }).pipe(
222
+ Effect.catch((failure) => {
223
+ const reply: SetAccountReply = {
224
+ status: "invalid",
225
+ message: failure.message,
226
+ };
227
+
228
+ return Effect.succeed(reply);
229
+ })
230
+ );
231
+ }
232
+
233
+ /** Runs one command under Alchemy's own services (profile store, credentials store, HTTP). */
234
+ function run(program: Program<HelperReply, never, Services | Scope>) {
235
+ return Effect.runPromise(
236
+ program.pipe(Effect.provide(Alchemist.layer()), Effect.scoped)
237
+ );
238
+ }
239
+
240
+ const [command, argument] = process.argv.slice(2);
241
+
242
+ const reply =
243
+ command === "credentials"
244
+ ? await run(credentials())
245
+ : command === "profiles"
246
+ ? await run(profiles())
247
+ : command === "set-account" && argument
248
+ ? await run(setAccount(argument))
249
+ : undefined;
250
+
251
+ if (reply === undefined) {
252
+ process.stderr.write(
253
+ "Usage: alchemy-helper.ts credentials | profiles | set-account <account id>\n"
254
+ );
255
+ process.exitCode = 2;
256
+ } else {
257
+ process.stdout.write(`${JSON.stringify(reply)}\n`);
258
+ }
@@ -0,0 +1,63 @@
1
+ import { z } from "zod";
2
+
3
+ /** How create authenticates to the Cloudflare API: the credentials a deploy would use. */
4
+ export const cloudflareAuthSchema = z.discriminatedUnion("type", [
5
+ z.object({ type: z.literal("token"), token: z.string().min(1) }),
6
+ z.object({
7
+ type: z.literal("apiKey"),
8
+ key: z.string().min(1),
9
+ email: z.string().min(1),
10
+ }),
11
+ ]);
12
+
13
+ export type CloudflareAuth = z.infer<typeof cloudflareAuthSchema>;
14
+
15
+ export const credentialsReplySchema = z.discriminatedUnion("status", [
16
+ z.object({
17
+ status: z.literal("ok"),
18
+ /** "environment" when CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are set: they win over every profile. */
19
+ source: z.enum(["profile", "environment"]),
20
+ profile: z.string(),
21
+ /** "oauth", "stored", or "environment". */
22
+ method: z.string(),
23
+ accountId: z.string(),
24
+ auth: cloudflareAuthSchema,
25
+ }),
26
+ z.object({ status: z.literal("missing"), message: z.string() }),
27
+ z.object({ status: z.literal("invalid"), message: z.string() }),
28
+ ]);
29
+
30
+ export type CredentialsReply = z.infer<typeof credentialsReplySchema>;
31
+
32
+ export const profilesReplySchema = z.discriminatedUnion("status", [
33
+ z.object({
34
+ status: z.literal("ok"),
35
+ active: z.string(),
36
+ profiles: z.array(
37
+ z.object({
38
+ name: z.string(),
39
+ cloudflare: z
40
+ .object({ method: z.string(), accountId: z.string().optional() })
41
+ .optional(),
42
+ })
43
+ ),
44
+ }),
45
+ z.object({ status: z.literal("invalid"), message: z.string() }),
46
+ ]);
47
+
48
+ export type ProfilesReply = z.infer<typeof profilesReplySchema>;
49
+
50
+ export const setAccountReplySchema = z.discriminatedUnion("status", [
51
+ z.object({
52
+ status: z.literal("ok"),
53
+ profile: z.string(),
54
+ accountId: z.string(),
55
+ }),
56
+ z.object({ status: z.literal("missing"), message: z.string() }),
57
+ z.object({ status: z.literal("invalid"), message: z.string() }),
58
+ ]);
59
+
60
+ export type SetAccountReply = z.infer<typeof setAccountReplySchema>;
61
+
62
+ /** Everything the helper may print. */
63
+ export type HelperReply = CredentialsReply | ProfilesReply | SetAccountReply;
@@ -0,0 +1,163 @@
1
+ // Alchemy as the new project sees it. Every command runs in the project's
2
+ // directory with the project's installed `alchemy` and
3
+ // `@alchemy.run/cloudflare`, so signing in, reading the login and deploying
4
+ // all use the same version, the same `~/.alchemy` profiles and the same rules
5
+ // for picking credentials.
6
+ import { join } from "node:path";
7
+
8
+ import type { z } from "zod";
9
+
10
+ import {
11
+ credentialsReplySchema,
12
+ profilesReplySchema,
13
+ setAccountReplySchema,
14
+ } from "./alchemy-protocol.ts";
15
+ import type {
16
+ CredentialsReply,
17
+ ProfilesReply,
18
+ SetAccountReply,
19
+ } from "./alchemy-protocol.ts";
20
+
21
+ export type ProjectAlchemy = {
22
+ /** The Cloudflare credentials a deploy would use (environment variables, else the profile). */
23
+ credentials(): Promise<CredentialsReply>;
24
+ /** Every Alchemy profile, with the Cloudflare account each deploys to. */
25
+ profiles(): Promise<ProfilesReply>;
26
+ /** Points the profile's Cloudflare login at another account it reaches. */
27
+ setAccount(accountId: string): Promise<SetAccountReply>;
28
+ /** `alchemy profile create <name>`. */
29
+ createProfile(name: string): Promise<boolean>;
30
+ /** `alchemy profile edit --add|--reconfigure Cloudflare`: Alchemy's own sign-in, on this terminal. */
31
+ signIn(mode: "add" | "reconfigure"): Promise<boolean>;
32
+ /** `bun run deploy`, its output on this terminal. */
33
+ deploy(): Promise<boolean>;
34
+ };
35
+
36
+ const HELPER = join(import.meta.dirname, "alchemy-helper.ts");
37
+
38
+ /**
39
+ * Claude Code's variables make Alchemy's CLI treat any terminal as an agent's
40
+ * and refuse to prompt. When a person is at this terminal (create itself is
41
+ * prompting them), the children get it without them.
42
+ */
43
+ const AGENT_VARIABLES = new Set(["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"]);
44
+
45
+ export function childEnv(
46
+ env: Readonly<Record<string, string | undefined>>,
47
+ options: { profile: string | undefined; interactive: boolean }
48
+ ) {
49
+ const child: Record<string, string> = {};
50
+
51
+ for (const [key, value] of Object.entries(env)) {
52
+ if (value === undefined) continue;
53
+
54
+ if (options.interactive && AGENT_VARIABLES.has(key)) continue;
55
+
56
+ child[key] = value;
57
+ }
58
+
59
+ if (options.profile) child.ALCHEMY_PROFILE = options.profile;
60
+
61
+ return child;
62
+ }
63
+
64
+ /** The helper's reply: the last line of its output that parses. */
65
+ export function parseReply<T>(output: string, schema: z.ZodType<T>) {
66
+ const lines = output.trim().split("\n").reverse();
67
+
68
+ for (const line of lines) {
69
+ try {
70
+ const parsed = schema.safeParse(JSON.parse(line));
71
+
72
+ if (parsed.success) return parsed.data;
73
+ } catch {
74
+ // Not the JSON reply: Alchemy may log a line first.
75
+ }
76
+ }
77
+
78
+ return undefined;
79
+ }
80
+
81
+ export function projectAlchemy(
82
+ directory: string,
83
+ options: {
84
+ profile: string | undefined;
85
+ interactive: boolean;
86
+ env?: Readonly<Record<string, string | undefined>>;
87
+ }
88
+ ): ProjectAlchemy {
89
+ const env = childEnv(options.env ?? process.env, options);
90
+
91
+ async function helper<T extends { status: string }>(
92
+ args: string[],
93
+ schema: z.ZodType<T>,
94
+ invalid: (message: string) => T
95
+ ) {
96
+ const child = Bun.spawn([process.execPath, HELPER, ...args], {
97
+ cwd: directory,
98
+ env,
99
+ stdin: "ignore",
100
+ stdout: "pipe",
101
+ stderr: "pipe",
102
+ });
103
+
104
+ const [output, errors, exitCode] = await Promise.all([
105
+ new Response(child.stdout).text(),
106
+ new Response(child.stderr).text(),
107
+ child.exited,
108
+ ]);
109
+
110
+ return (
111
+ parseReply(output, schema) ??
112
+ invalid(
113
+ `Alchemy exited with code ${exitCode}${errors.trim() ? `: ${errors.trim()}` : ""}`
114
+ )
115
+ );
116
+ }
117
+
118
+ /** Runs a command on this terminal: Alchemy prompts and prints straight to the person. */
119
+ async function onTerminal(command: string[]) {
120
+ const child = Bun.spawn(command, {
121
+ cwd: directory,
122
+ env,
123
+ stdin: "inherit",
124
+ stdout: "inherit",
125
+ stderr: "inherit",
126
+ });
127
+
128
+ return (await child.exited) === 0;
129
+ }
130
+
131
+ const profileFlag = options.profile ? ["--profile", options.profile] : [];
132
+
133
+ return {
134
+ credentials: () =>
135
+ helper(["credentials"], credentialsReplySchema, (message) => ({
136
+ status: "invalid",
137
+ message,
138
+ })),
139
+ profiles: () =>
140
+ helper(["profiles"], profilesReplySchema, (message) => ({
141
+ status: "invalid",
142
+ message,
143
+ })),
144
+ setAccount: (accountId) =>
145
+ helper(["set-account", accountId], setAccountReplySchema, (message) => ({
146
+ status: "invalid",
147
+ message,
148
+ })),
149
+ createProfile: (name) =>
150
+ onTerminal([process.execPath, "alchemy", "profile", "create", name]),
151
+ signIn: (mode) =>
152
+ onTerminal([
153
+ process.execPath,
154
+ "alchemy",
155
+ "profile",
156
+ "edit",
157
+ ...profileFlag,
158
+ `--${mode}`,
159
+ "Cloudflare",
160
+ ]),
161
+ deploy: () => onTerminal([process.execPath, "run", "deploy", "--yes"]),
162
+ };
163
+ }
package/setup/args.ts ADDED
@@ -0,0 +1,128 @@
1
+ // `bun create @open-workspace [name] [options]`.
2
+ import { parseCliArgs } from "../import/args.ts";
3
+ import { parseDomainList } from "./domains.ts";
4
+
5
+ export const AI_CHOICES = [
6
+ "cloudflare",
7
+ "openai",
8
+ "anthropic",
9
+ "none",
10
+ ] as const;
11
+
12
+ export type AiChoice = (typeof AI_CHOICES)[number];
13
+
14
+ export type CreateOptions = {
15
+ name?: string;
16
+ /** Cloudflare account id or name. */
17
+ account?: string;
18
+ /** Alchemy profile to sign in with; defaults to $ALCHEMY_PROFILE, else "default". */
19
+ profile?: string;
20
+ /** Mail domains, primary first. */
21
+ mailDomains?: string[];
22
+ hostname?: string;
23
+ ai?: AiChoice;
24
+ deploy: boolean;
25
+ /** Start a git repository with the project as its first commit. */
26
+ git: boolean;
27
+ /** Ask nothing: take defaults, and stop where a choice is needed. */
28
+ yes: boolean;
29
+ help: boolean;
30
+ };
31
+
32
+ export const createUsage = `Usage: bun create @open-workspace [name] [options]
33
+
34
+ Writes a project, signs in to Cloudflare with Alchemy, and deploys it.
35
+
36
+ Options:
37
+ --account <id or name> Cloudflare account to deploy to
38
+ --profile <name> Alchemy profile to sign in with
39
+ (default: $ALCHEMY_PROFILE, else "default")
40
+ --mail-domains <list> Mail domains, primary first, comma-separated:
41
+ zones in the account
42
+ --hostname <host> Where the app is served (default: mail.<primary>)
43
+ --ai <provider> cloudflare (default), openai, anthropic or none;
44
+ keys come from OPENAI_API_KEY / ANTHROPIC_API_KEY
45
+ --no-deploy Write and install the project, but don't deploy
46
+ --no-git Don't start a git repository in the project
47
+ -y, --yes Ask nothing; fail where a choice is needed
48
+ -h, --help Show this help
49
+
50
+ Without a terminal, or with --yes, nothing is asked, and signing in
51
+ can't happen: it needs a Cloudflare login in your Alchemy profile (from
52
+ an earlier run), or CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID.`;
53
+
54
+ const options = {
55
+ account: { type: "string" },
56
+ profile: { type: "string" },
57
+ "mail-domains": { type: "string" },
58
+ hostname: { type: "string" },
59
+ ai: { type: "string" },
60
+ "no-deploy": { type: "boolean" },
61
+ "no-git": { type: "boolean" },
62
+ yes: { type: "boolean", short: "y" },
63
+ help: { type: "boolean", short: "h" },
64
+ } as const;
65
+
66
+ function isAiChoice(value: string): value is AiChoice {
67
+ return AI_CHOICES.some((choice) => choice === value);
68
+ }
69
+
70
+ /** The options, or what's wrong with them. */
71
+ export function parseCreateArgs(
72
+ args: readonly string[]
73
+ ): { options: CreateOptions } | { error: string } {
74
+ let parsed: ReturnType<typeof parse>;
75
+
76
+ try {
77
+ parsed = parse(args);
78
+ } catch (failure) {
79
+ return {
80
+ error: failure instanceof Error ? failure.message : String(failure),
81
+ };
82
+ }
83
+
84
+ const { values, positionals } = parsed;
85
+
86
+ if (positionals.length > 1) {
87
+ return { error: `Expected one project name, got ${positionals.join(" ")}` };
88
+ }
89
+
90
+ const ai = values.ai?.toLowerCase();
91
+
92
+ if (ai !== undefined && !isAiChoice(ai)) {
93
+ return { error: `--ai must be one of ${AI_CHOICES.join(", ")}` };
94
+ }
95
+
96
+ const mailDomains =
97
+ values["mail-domains"] === undefined
98
+ ? undefined
99
+ : parseDomainList(values["mail-domains"]);
100
+
101
+ if (mailDomains?.length === 0) {
102
+ return { error: "--mail-domains needs at least one domain" };
103
+ }
104
+
105
+ return {
106
+ options: {
107
+ name: positionals[0],
108
+ account: values.account,
109
+ profile: values.profile,
110
+ mailDomains,
111
+ hostname: values.hostname?.trim().toLowerCase(),
112
+ ai,
113
+ deploy: !values["no-deploy"],
114
+ git: !values["no-git"],
115
+ yes: values.yes ?? false,
116
+ help: values.help ?? false,
117
+ },
118
+ };
119
+ }
120
+
121
+ function parse(args: readonly string[]) {
122
+ return parseCliArgs({
123
+ args: [...args],
124
+ options,
125
+ allowPositionals: true,
126
+ strict: true,
127
+ });
128
+ }