The best way to control Claude Code, Codex and more from any computer or phone

main
ts 322 lines 11.1 KB
Raw
1 import * as pages from "@distilled.cloud/cloudflare/pages";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.Pages.Domain" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * Lifecycle status of a Pages custom domain. Newly attached domains start
16 * `initializing`/`pending` and become `active` once DNS validation and
17 * certificate issuance complete.
18 */
19 export type DomainStatus =
20 | "initializing"
21 | "pending"
22 | "active"
23 | "deactivated"
24 | "blocked"
25 | "error"
26 // Keep the union open so new Cloudflare statuses aren't blocked by
27 // stale types.
28 | (string & {});
29
30 export interface DomainProps {
31 /**
32 * Name of the Pages project the domain is attached to (e.g.
33 * `project.name`). The attachment cannot be moved — changing the project
34 * triggers a replacement.
35 */
36 projectName: string;
37 /**
38 * The custom domain name (e.g. `www.example.com`). The domain is the
39 * attachment's identity — changing it triggers a replacement.
40 *
41 * Declared as plain `string` so it is statically knowable inside `diff`.
42 */
43 name: string;
44 }
45
46 export interface DomainAttributes {
47 /**
48 * Cloudflare-assigned UUID of the domain attachment.
49 */
50 domainId: string;
51 /**
52 * The Cloudflare account the project belongs to.
53 */
54 accountId: string;
55 /**
56 * Name of the Pages project the domain is attached to.
57 */
58 projectName: string;
59 /**
60 * The custom domain name.
61 */
62 name: string;
63 /**
64 * Current lifecycle status of the domain. Newly attached domains stay
65 * `pending` until DNS validation completes (the zone needs a CNAME from
66 * the domain to the project's `*.pages.dev` subdomain).
67 */
68 status: DomainStatus;
69 /**
70 * Certificate authority issuing the domain's TLS certificate.
71 */
72 certificateAuthority: string;
73 /**
74 * Status of the domain-ownership validation.
75 */
76 validationStatus: string;
77 /**
78 * Method used for domain-ownership validation (`http` or `txt`).
79 */
80 validationMethod: string;
81 /**
82 * Status of the domain verification.
83 */
84 verificationStatus: string;
85 /**
86 * Zone tag (zone id) of the Cloudflare zone the domain belongs to, when
87 * the zone is on the same account.
88 */
89 zoneTag: string;
90 /**
91 * When the domain was attached to the project.
92 */
93 createdOn: string;
94 }
95
96 export type Domain = Resource<TypeId, DomainProps, DomainAttributes, never, Providers>;
97
98 /**
99 * A custom domain attached to a Cloudflare Pages project.
100 *
101 * Attaching a domain starts Cloudflare's validation flow: the domain must
102 * resolve to the project (typically via a CNAME record pointing at the
103 * project's `*.pages.dev` subdomain) before its status becomes `active`.
104 * The resource does not wait for activation — compose it with
105 * `Cloudflare.DNS.Record` to create the CNAME, and certificate issuance
106 * completes asynchronously.
107 *
108 * Both properties are the attachment's identity, so every change triggers a
109 * replacement (detach + attach).
110 * ### Attaching a Domain
111 * **Example:** Custom domain with its CNAME record
112 * ```typescript
113 * const project = yield* Cloudflare.Pages.Project("site", {});
114 *
115 * const domain = yield* Cloudflare.Pages.Domain("site-domain", {
116 * projectName: project.name,
117 * name: "www.example.com",
118 * });
119 *
120 * yield* Cloudflare.DNS.Record("site-cname", {
121 * zoneId: zone.zoneId,
122 * name: "www.example.com",
123 * type: "CNAME",
124 * content: project.subdomain,
125 * proxied: true,
126 * });
127 * ```
128 *
129 * @see https://developers.cloudflare.com/pages/configuration/custom-domains/
130 *
131 * @resource
132 * @product Pages
133 * @category Workers & Compute
134 */
135 export const Domain = Resource<Domain>(TypeId);
136
137 /**
138 * Returns true if the given value is a Domain resource.
139 */
140 export const isDomain = (value: unknown): value is Domain =>
141 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
142
143 export const DomainProvider = () =>
144 Provider.succeed(Domain, {
145 stables: ["domainId", "accountId", "projectName", "name", "zoneTag", "createdOn"],
146 diff: Effect.fn(function* ({ olds, news, output }) {
147 const { accountId } = yield* yield* CloudflareEnvironment;
148 const o = olds as DomainProps | undefined;
149 const n = news as DomainProps;
150 if ((output?.accountId ?? accountId) !== accountId) {
151 return { action: "replace" } as const;
152 }
153 // The domain name is the attachment's identity — no rename API.
154 const oldName = output?.name ?? o?.name;
155 if (oldName !== undefined && oldName !== n.name) {
156 return { action: "replace" } as const;
157 }
158 // projectName is Input<string>; compare only once both sides are
159 // concrete strings.
160 const oldProject =
161 output?.projectName ?? (typeof o?.projectName === "string" ? o.projectName : undefined);
162 if (
163 oldProject !== undefined &&
164 typeof n.projectName === "string" &&
165 oldProject !== n.projectName
166 ) {
167 return { action: "replace" } as const;
168 }
169 return undefined;
170 }),
171 // Parent fan-out: domains are sub-resources of a Pages project, and
172 // there is no account-wide domain enumeration API. Enumerate every
173 // Pages project (account-scoped, paginated), then list each project's
174 // domains with bounded concurrency and flatten into the `read`
175 // Attributes shape.
176 list: Effect.fn(function* () {
177 const { accountId } = yield* yield* CloudflareEnvironment;
178
179 const projectNames = yield* pages.listProjects.pages({ accountId }).pipe(
180 Stream.runCollect,
181 Effect.map((chunk) =>
182 Array.from(chunk).flatMap((page) => (page.result ?? []).map((project) => project.name)),
183 ),
184 );
185
186 const perProject = yield* Effect.forEach(
187 projectNames,
188 (projectName) =>
189 pages.listProjectDomains.pages({ accountId, projectName }).pipe(
190 Stream.runCollect,
191 Effect.map((chunk) =>
192 Array.from(chunk).flatMap((page) =>
193 (page.result ?? []).map((domain) => toAttributes(domain, accountId, projectName)),
194 ),
195 ),
196 // The project can vanish between enumeration and the
197 // per-project list — skip it rather than failing the whole
198 // enumeration.
199 Effect.catchTag("ProjectNotFound", () => Effect.succeed([])),
200 ),
201 { concurrency: 10 },
202 );
203
204 return perProject.flat();
205 }),
206 read: Effect.fn(function* ({ output, olds }) {
207 const { accountId } = yield* yield* CloudflareEnvironment;
208 const acct = output?.accountId ?? accountId;
209 const projectName =
210 output?.projectName ??
211 (typeof olds?.projectName === "string" ? olds.projectName : undefined);
212 const name = output?.name ?? olds?.name;
213 if (projectName === undefined || name === undefined) return undefined;
214
215 const observed = yield* getDomain(acct, projectName, name);
216 if (!observed) return undefined;
217 const attrs = toAttributes(observed, acct, projectName);
218 // With persisted state the attachment is ours; on a cold read we
219 // cannot prove ownership (domain attachments carry no markers), so
220 // gate takeover behind the adopt policy.
221 return output?.domainId ? attrs : Unowned(attrs);
222 }),
223 reconcile: Effect.fn(function* ({ news }) {
224 const { accountId } = yield* yield* CloudflareEnvironment;
225 // Inputs have been resolved to concrete strings by Plan.
226 const projectName = news.projectName as string;
227
228 // 1. Observe — `(projectName, name)` is the attachment's identity.
229 let observed = yield* getDomain(accountId, projectName, news.name);
230
231 // 2. Ensure — existence-only resource: attach when missing,
232 // tolerating the AlreadyExists race by re-reading.
233 if (!observed) {
234 observed = yield* pages
235 .createProjectDomain({
236 accountId,
237 projectName,
238 name: news.name,
239 })
240 .pipe(
241 Effect.catchTag("PagesDomainAlreadyExists", (originalError) =>
242 Effect.gen(function* () {
243 const existing = yield* getDomain(accountId, projectName, news.name);
244 if (!existing) return yield* originalError;
245 return existing;
246 }),
247 ),
248 );
249 } else if (observed.status === "pending" || observed.status === "error") {
250 // 3. Sync — nothing is mutable on the attachment itself, but a
251 // stalled validation can be re-kicked. Tolerate the domain
252 // vanishing between observe and patch.
253 observed = yield* pages
254 .patchProjectDomain({
255 accountId,
256 projectName,
257 domainName: news.name,
258 })
259 .pipe(Effect.catchTag("PagesDomainNotFound", () => Effect.succeed(observed!)));
260 }
261
262 // 4. Return fresh attributes.
263 return toAttributes(observed, accountId, projectName);
264 }),
265 delete: Effect.fn(function* ({ output }) {
266 // Idempotent: the domain may already be detached, or the whole
267 // project may already be gone (deleting a project detaches its
268 // domains) — both count as success.
269 yield* pages
270 .deleteProjectDomain({
271 accountId: output.accountId,
272 projectName: output.projectName,
273 domainName: output.name,
274 })
275 .pipe(
276 Effect.catchTags({
277 PagesDomainNotFound: () => Effect.void,
278 ProjectNotFound: () => Effect.void,
279 }),
280 );
281 }),
282 });
283
284 type ObservedDomain =
285 | pages.GetProjectDomainResponse
286 | pages.CreateProjectDomainResponse
287 | pages.PatchProjectDomainResponse;
288
289 /**
290 * Read a domain attachment, mapping "gone" to `undefined` — either the
291 * domain is not attached (`PagesDomainNotFound`, code 8000021) or the
292 * whole project no longer exists (`ProjectNotFound`, code 8000007).
293 */
294 const getDomain = (accountId: string, projectName: string, domainName: string) =>
295 pages.getProjectDomain({ accountId, projectName, domainName }).pipe(
296 Effect.catchTags({
297 PagesDomainNotFound: () => Effect.undefined,
298 ProjectNotFound: () => Effect.undefined,
299 }),
300 );
301
302 const toAttributes = (
303 domain: ObservedDomain,
304 accountId: string,
305 projectName: string,
306 ): DomainAttributes => ({
307 domainId: domain.domainId,
308 accountId,
309 projectName,
310 name: domain.name,
311 status: domain.status,
312 // While a domain is still `initializing`/`pending`, Cloudflare omits the
313 // certificate authority, validation/verification blocks and (for an
314 // off-account zone) the zone tag entirely — coalesce to "" so the
315 // Attributes shape stays stable across the async activation lifecycle.
316 certificateAuthority: domain.certificateAuthority ?? "",
317 validationStatus: domain.validationData?.status ?? "",
318 validationMethod: domain.validationData?.method ?? "",
319 verificationStatus: domain.verificationData?.status ?? "",
320 zoneTag: domain.zoneTag ?? "",
321 createdOn: domain.createdOn,
322 });