@open-workspace/create 0.2.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,156 @@
1
+ // The few Cloudflare API reads create needs: the accounts a login reaches,
2
+ // an account's zones, and a zone's MX records. Authenticated with the
3
+ // credentials Alchemy resolved, so they see what the deploy will.
4
+ import { z } from "zod";
5
+
6
+ import type { CloudflareAuth } from "./alchemy-protocol.ts";
7
+ import type { Account, MxRecord, Zone } from "./domains.ts";
8
+
9
+ export const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
10
+
11
+ export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
12
+
13
+ export type CloudflareApi = {
14
+ accounts(): Promise<Account[]>;
15
+ zones(accountId: string): Promise<Zone[]>;
16
+ mxRecords(zoneId: string): Promise<MxRecord[]>;
17
+ };
18
+
19
+ export class CloudflareApiError extends Error {
20
+ constructor(
21
+ message: string,
22
+ readonly status: number
23
+ ) {
24
+ super(message);
25
+ }
26
+ }
27
+
28
+ const envelopeSchema = z.object({
29
+ success: z.boolean(),
30
+ errors: z.array(z.object({ code: z.number(), message: z.string() })),
31
+ result: z.array(z.unknown()).nullable(),
32
+ result_info: z
33
+ .object({ page: z.number(), total_pages: z.number() })
34
+ .partial()
35
+ .optional(),
36
+ });
37
+
38
+ const accountSchema = z.object({ id: z.string(), name: z.string() });
39
+
40
+ const membershipSchema = z.object({
41
+ status: z.string().optional(),
42
+ account: accountSchema.nullable().optional(),
43
+ });
44
+
45
+ const zoneSchema = z.object({
46
+ id: z.string(),
47
+ name: z.string(),
48
+ status: z.string(),
49
+ });
50
+
51
+ const mxSchema = z.object({
52
+ name: z.string(),
53
+ content: z.string(),
54
+ priority: z.number().optional(),
55
+ });
56
+
57
+ function headers(auth: CloudflareAuth): Record<string, string> {
58
+ return auth.type === "token"
59
+ ? { Authorization: `Bearer ${auth.token}` }
60
+ : { "X-Auth-Key": auth.key, "X-Auth-Email": auth.email };
61
+ }
62
+
63
+ export function cloudflareApi(
64
+ auth: CloudflareAuth,
65
+ fetchImpl: Fetch = fetch,
66
+ base = CLOUDFLARE_API
67
+ ): CloudflareApi {
68
+ /** One page of a list endpoint: its items, parsed, and how many pages there are. */
69
+ async function page<T>(path: string, item: z.ZodType<T>, number: number) {
70
+ const url = new URL(`${base}${path}`);
71
+
72
+ url.searchParams.set("page", String(number));
73
+
74
+ const response = await fetchImpl(url.toString(), {
75
+ headers: { ...headers(auth), Accept: "application/json" },
76
+ });
77
+
78
+ const body = envelopeSchema.safeParse(
79
+ await response.json().catch(() => null)
80
+ );
81
+
82
+ if (!response.ok || !body.success || !body.data.success) {
83
+ const reason = body.success
84
+ ? body.data.errors.map((error) => error.message).join("; ")
85
+ : "";
86
+
87
+ throw new CloudflareApiError(
88
+ `GET ${url.pathname} failed with HTTP ${response.status}${reason ? `: ${reason}` : ""}`,
89
+ response.status
90
+ );
91
+ }
92
+
93
+ return {
94
+ items: z.array(item).parse(body.data.result ?? []),
95
+ pages: body.data.result_info?.total_pages ?? 1,
96
+ };
97
+ }
98
+
99
+ /** Every page of a list endpoint. */
100
+ async function list<T>(path: string, item: z.ZodType<T>) {
101
+ const first = await page(path, item, 1);
102
+
103
+ const rest = await Promise.all(
104
+ Array.from({ length: Math.max(0, first.pages - 1) }, (_, index) =>
105
+ page(path, item, index + 2)
106
+ )
107
+ );
108
+
109
+ return [first, ...rest].flatMap((result) => result.items);
110
+ }
111
+
112
+ return {
113
+ /**
114
+ * Accounts the login reaches. Memberships list them for a user's OAuth
115
+ * login; an account API token has none, so /accounts is the fallback
116
+ * (as in Alchemy's own account picker).
117
+ */
118
+ async accounts() {
119
+ const memberships = await list(
120
+ "/memberships?per_page=50",
121
+ membershipSchema
122
+ ).catch(() => []);
123
+
124
+ const accounts = memberships.flatMap((membership) =>
125
+ membership.account &&
126
+ (membership.status === undefined || membership.status === "accepted")
127
+ ? [membership.account]
128
+ : []
129
+ );
130
+
131
+ if (accounts.length > 0) return accounts;
132
+
133
+ return list("/accounts?per_page=50", accountSchema);
134
+ },
135
+
136
+ zones(accountId) {
137
+ return list(
138
+ `/zones?per_page=50&account.id=${encodeURIComponent(accountId)}`,
139
+ zoneSchema
140
+ );
141
+ },
142
+
143
+ async mxRecords(zoneId) {
144
+ const records = await list(
145
+ `/zones/${encodeURIComponent(zoneId)}/dns_records?type=MX&per_page=100`,
146
+ mxSchema
147
+ );
148
+
149
+ return records.map((record) => ({
150
+ name: record.name,
151
+ content: record.content,
152
+ priority: record.priority ?? 0,
153
+ }));
154
+ },
155
+ };
156
+ }
@@ -0,0 +1,102 @@
1
+ // Choosing mail domains and the hostname from the zones of a Cloudflare
2
+ // account, and spotting MX records that would stop Email Routing.
3
+
4
+ export type Account = { id: string; name: string };
5
+
6
+ export type Zone = { id: string; name: string; status: string };
7
+
8
+ export type MxRecord = { name: string; content: string; priority: number };
9
+
10
+ const HOSTNAME =
11
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
12
+
13
+ /** Cloudflare Email Routing's own MX hosts (`route1.mx.cloudflare.net` …). */
14
+ const CLOUDFLARE_MX = /(?:^|\.)mx\.cloudflare\.net\.?$/iu;
15
+
16
+ /** Lowercase, without spaces or a trailing dot. */
17
+ export function normalizeDomain(value: string) {
18
+ return value.trim().toLowerCase().replace(/\.$/u, "");
19
+ }
20
+
21
+ /** "acme.com, acme.org" or "acme.com acme.org" as a list. */
22
+ export function parseDomainList(value: string) {
23
+ return value
24
+ .split(/[\s,]+/u)
25
+ .filter(Boolean)
26
+ .map(normalizeDomain);
27
+ }
28
+
29
+ /** The account a `--account` value names: its id, or its name ignoring case. */
30
+ export function findAccount(accounts: readonly Account[], wanted: string) {
31
+ const id = wanted.trim().toLowerCase();
32
+
33
+ return (
34
+ accounts.find((account) => account.id.toLowerCase() === id) ??
35
+ accounts.find((account) => account.name.toLowerCase() === id)
36
+ );
37
+ }
38
+
39
+ /** The zone a hostname is in: the longest zone name it equals or ends with. */
40
+ export function zoneOf(hostname: string, zones: readonly Zone[]) {
41
+ const host = normalizeDomain(hostname);
42
+
43
+ return zones
44
+ .filter((zone) => host === zone.name || host.endsWith(`.${zone.name}`))
45
+ .sort((a, b) => b.name.length - a.name.length)[0];
46
+ }
47
+
48
+ /** Why a hostname can't serve the app, or undefined when it can. */
49
+ export function hostnameProblem(hostname: string, zones: readonly Zone[]) {
50
+ const host = normalizeDomain(hostname);
51
+
52
+ if (!HOSTNAME.test(host)) return "Use a hostname such as mail.acme.com";
53
+
54
+ if (!zoneOf(host, zones)) {
55
+ return `${host} isn't in a zone of this account (${zones.map((zone) => zone.name).join(", ")})`;
56
+ }
57
+
58
+ return undefined;
59
+ }
60
+
61
+ /** The suggested hostname: mail.<primary domain>. */
62
+ export function suggestedHostname(primary: string) {
63
+ return `mail.${primary}`;
64
+ }
65
+
66
+ /**
67
+ * The zones a list of mail domains names, in the list's order, or the names
68
+ * that aren't zones of the account. Email Routing works on whole zones, so a
69
+ * mail domain must be one.
70
+ */
71
+ export function zonesNamed(names: readonly string[], zones: readonly Zone[]) {
72
+ const byName = new Map(zones.map((zone) => [zone.name, zone]));
73
+ const wanted = [...new Set(names.map(normalizeDomain))];
74
+ const found: Zone[] = [];
75
+ const missing: string[] = [];
76
+
77
+ for (const name of wanted) {
78
+ const zone = byName.get(name);
79
+
80
+ if (zone) found.push(zone);
81
+ else missing.push(name);
82
+ }
83
+
84
+ return { found, missing };
85
+ }
86
+
87
+ /** The mail domains with the primary first; the others keep their order. */
88
+ export function primaryFirst(domains: readonly string[], primary: string) {
89
+ return [primary, ...domains.filter((domain) => domain !== primary)];
90
+ }
91
+
92
+ /** MX records that send a zone's mail somewhere other than Cloudflare Email Routing. */
93
+ export function foreignMx(records: readonly MxRecord[]) {
94
+ return records.filter((record) => !CLOUDFLARE_MX.test(record.content));
95
+ }
96
+
97
+ /** "acme.com MX 10 aspmx.l.google.com", one line per record. */
98
+ export function describeMx(records: readonly MxRecord[]) {
99
+ return [...records]
100
+ .sort((a, b) => a.priority - b.priority)
101
+ .map((record) => `${record.name} MX ${record.priority} ${record.content}`);
102
+ }