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

main
ts 637 lines 20.9 KB
Raw
1 import * as pages from "@distilled.cloud/cloudflare/pages";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { arrayEqualsUnordered } from "alchemy/Util/equal";
9 import * as Effect from "effect/Effect";
10 import * as Predicate from "effect/Predicate";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 const TypeId = "Cloudflare.Pages.Project" as const;
16 type TypeId = typeof TypeId;
17
18 /**
19 * Build configuration for a Pages project. All fields are mutable in place.
20 */
21 export interface BuildConfig {
22 /**
23 * Enable build caching for the project.
24 */
25 buildCaching?: boolean;
26 /**
27 * Command used to build the project (e.g. `npm run build`).
28 */
29 buildCommand?: string;
30 /**
31 * Output directory of the build, relative to `rootDir` (e.g. `dist`).
32 */
33 destinationDir?: string;
34 /**
35 * Directory to run the build command in. Defaults to the repository root.
36 */
37 rootDir?: string;
38 }
39
40 /**
41 * A single environment variable on a Pages deployment environment.
42 */
43 export interface EnvVar {
44 /**
45 * Whether the value is stored as plain text or encrypted as a secret.
46 * @default "plain_text"
47 */
48 type?: "plain_text" | "secret_text";
49 /**
50 * The environment variable value.
51 */
52 value: string;
53 }
54
55 /**
56 * Per-environment (preview / production) deployment configuration.
57 *
58 * Record-shaped fields (`envVars`, `kvNamespaces`, `d1Databases`,
59 * `r2Buckets`) are reconciled key-by-key: Cloudflare's PATCH endpoint
60 * deep-merges, so keys observed on the project but absent from the desired
61 * config are explicitly removed.
62 */
63 export interface DeploymentConfig {
64 /**
65 * Environment variables, keyed by variable name.
66 */
67 envVars?: Record<string, EnvVar>;
68 /**
69 * KV namespace bindings, keyed by binding name. The value is the KV
70 * namespace id (e.g. `kvNamespace.namespaceId`).
71 */
72 kvNamespaces?: Record<string, string>;
73 /**
74 * D1 database bindings, keyed by binding name. The value is the D1
75 * database UUID (e.g. `database.databaseId`).
76 */
77 d1Databases?: Record<string, string>;
78 /**
79 * R2 bucket bindings, keyed by binding name. The value is the bucket
80 * name (e.g. `bucket.bucketName`).
81 */
82 r2Buckets?: Record<string, string>;
83 /**
84 * Compatibility date used by Pages Functions (e.g. `2025-01-01`).
85 */
86 compatibilityDate?: string;
87 /**
88 * Compatibility flags used by Pages Functions.
89 */
90 compatibilityFlags?: string[];
91 /**
92 * Whether requests are served (`true`) or rejected (`false`) when a
93 * Pages Function exceeds its limits.
94 */
95 failOpen?: boolean;
96 /**
97 * Placement settings for Pages Functions (e.g. `{ mode: "smart" }`).
98 */
99 placement?: { mode: string };
100 }
101
102 /**
103 * Deployment configuration for both Pages environments.
104 */
105 export interface DeploymentConfigs {
106 /**
107 * Configuration applied to preview (non-production-branch) deployments.
108 */
109 preview?: DeploymentConfig;
110 /**
111 * Configuration applied to production deployments.
112 */
113 production?: DeploymentConfig;
114 }
115
116 export interface ProjectProps {
117 /**
118 * Name of the project. Forms the `<name>.pages.dev` subdomain, so it must
119 * be unique across all of Cloudflare Pages and contain only lowercase
120 * letters, numbers, and dashes. The name is the project's identity —
121 * changing it triggers a replacement.
122 * @default ${app}-${stage}-${id}
123 */
124 name?: string;
125 /**
126 * Production branch of the project. Deployments to this branch are
127 * production deployments; any other branch produces a preview deployment.
128 * Mutable in place.
129 * @default "main"
130 */
131 productionBranch?: string;
132 /**
133 * Configs for the project build process. Mutable in place.
134 */
135 buildConfig?: BuildConfig;
136 /**
137 * Per-environment deployment configuration (env vars, bindings,
138 * compatibility settings). Mutable in place.
139 */
140 deploymentConfigs?: DeploymentConfigs;
141 }
142
143 export interface ProjectAttributes {
144 /**
145 * Cloudflare-assigned UUID of the project.
146 */
147 projectId: string;
148 /**
149 * The Cloudflare account the project belongs to.
150 */
151 accountId: string;
152 /**
153 * Name of the project.
154 */
155 name: string;
156 /**
157 * The `*.pages.dev` subdomain serving the project (e.g.
158 * `my-project.pages.dev`).
159 */
160 subdomain: string;
161 /**
162 * All domains attached to the project, including the `*.pages.dev`
163 * subdomain and any custom domains.
164 */
165 domains: string[];
166 /**
167 * Production branch of the project.
168 */
169 productionBranch: string;
170 /**
171 * When the project was created.
172 */
173 createdOn: string;
174 }
175
176 export type Project = Resource<TypeId, ProjectProps, ProjectAttributes, never, Providers>;
177
178 /**
179 * A Cloudflare Pages project (direct-upload).
180 *
181 * The project is the container for Pages deployments, custom domains, and
182 * per-environment configuration. Created without git `source` integration,
183 * it is a direct-upload project — deployments are pushed via the API or
184 * `wrangler pages deploy`.
185 *
186 * The project `name` is its identity (it forms the `<name>.pages.dev`
187 * subdomain), so renaming triggers a replacement. `productionBranch`,
188 * `buildConfig`, and `deploymentConfigs` are all mutable in place.
189 * ### Creating a Project
190 * **Example:** Minimal project (generated name)
191 * ```typescript
192 * const project = yield* Cloudflare.Pages.Project("site", {});
193 * // project.subdomain === "<generated-name>.pages.dev"
194 * ```
195 *
196 * **Example:** Named project with a build config
197 * ```typescript
198 * const project = yield* Cloudflare.Pages.Project("site", {
199 * name: "my-site",
200 * productionBranch: "main",
201 * buildConfig: {
202 * buildCommand: "npm run build",
203 * destinationDir: "dist",
204 * },
205 * });
206 * ```
207 *
208 * ### Deployment Configuration
209 * **Example:** Environment variables and bindings
210 * ```typescript
211 * const project = yield* Cloudflare.Pages.Project("site", {
212 * deploymentConfigs: {
213 * production: {
214 * compatibilityDate: "2026-08-31",
215 * envVars: {
216 * API_URL: { value: "https://api.example.com" },
217 * API_KEY: { type: "secret_text", value: apiKey },
218 * },
219 * kvNamespaces: {
220 * CACHE: kvNamespace.namespaceId,
221 * },
222 * },
223 * },
224 * });
225 * ```
226 *
227 * ### Custom Domains
228 * **Example:** Attach a custom domain
229 * ```typescript
230 * const domain = yield* Cloudflare.Pages.Domain("site-domain", {
231 * projectName: project.name,
232 * name: "www.example.com",
233 * });
234 * ```
235 *
236 * @see https://developers.cloudflare.com/pages/
237 *
238 * @resource
239 * @product Pages
240 * @category Workers & Compute
241 */
242 export const Project = Resource<Project>(TypeId);
243
244 /**
245 * Returns true if the given value is a Project resource.
246 */
247 export const isProject = (value: unknown): value is Project =>
248 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
249
250 export const ProjectProvider = () =>
251 Provider.succeed(Project, {
252 stables: ["projectId", "accountId", "name", "subdomain", "createdOn"],
253 diff: Effect.fn(function* ({ id, olds, news, output }) {
254 const { accountId } = yield* yield* CloudflareEnvironment;
255 if (!isResolved(news)) return undefined;
256 if ((output?.accountId ?? accountId) !== accountId) {
257 return { action: "replace" } as const;
258 }
259 // The name is the project's identity (it forms the *.pages.dev
260 // subdomain) — renames are a delete + create.
261 const oldName = output?.name ?? (yield* createProjectName(id, olds?.name));
262 // Auto-generated names are engine-owned: the deployed name stays
263 // authoritative even if the generator would name this id differently
264 // today. Only an explicit user-provided name can force a replace.
265 const name = news.name ?? oldName;
266 if (name !== oldName) {
267 return { action: "replace" } as const;
268 }
269 return undefined;
270 }),
271 read: Effect.fn(function* ({ id, output, olds }) {
272 const { accountId } = yield* yield* CloudflareEnvironment;
273 const acct = output?.accountId ?? accountId;
274 if (output?.name) {
275 const observed = yield* getProject(acct, output.name);
276 return observed ? toAttributes(observed, acct) : undefined;
277 }
278 // Cold read — the project name is deterministic, so look it up
279 // directly. Pages projects carry no ownership markers we can
280 // inspect, so an existing match is reported as Unowned and takeover
281 // is gated behind the adopt policy.
282 const name = yield* createProjectName(id, olds?.name);
283 const observed = yield* getProject(acct, name);
284 return observed ? Unowned(toAttributes(observed, acct)) : undefined;
285 }),
286 reconcile: Effect.fn(function* ({ id, news, output }) {
287 const { accountId } = yield* yield* CloudflareEnvironment;
288 const name = news.name ?? output?.name ?? (yield* createProjectName(id));
289
290 // 1. Observe — the project name is its identity; a 404 falls
291 // through to "missing" and we (re)create.
292 let observed = yield* getProject(accountId, name);
293
294 // 2. Ensure — create when missing, tolerating the AlreadyExists
295 // race by re-reading.
296 if (!observed) {
297 observed = yield* pages
298 .createProject({
299 accountId,
300 name,
301 productionBranch: news.productionBranch ?? "main",
302 buildConfig: toApiBuildConfig(news.buildConfig),
303 deploymentConfigs: toApiDeploymentConfigs(news.deploymentConfigs, undefined),
304 })
305 .pipe(
306 Effect.catchTag("ProjectAlreadyExists", (originalError) =>
307 Effect.gen(function* () {
308 const existing = yield* getProject(accountId, name);
309 if (!existing) return yield* originalError;
310 return existing;
311 }),
312 ),
313 );
314 }
315
316 // 3. Sync — diff observed cloud state against the desired props and
317 // PATCH only the delta. Cloudflare's PATCH deep-merges
318 // `deploymentConfigs`, so removed record keys are sent as
319 // explicit nulls.
320 const patch = buildProjectPatch(news, observed);
321 if (patch !== undefined) {
322 observed = yield* pages.patchProject({
323 accountId,
324 projectName: name,
325 ...patch,
326 });
327 }
328
329 // 4. Return fresh attributes.
330 return toAttributes(observed, accountId);
331 }),
332 delete: Effect.fn(function* ({ output }) {
333 // Deleting a project deletes its deployments and detaches custom
334 // domains. A missing project is success — delete is idempotent.
335 yield* pages
336 .deleteProject({
337 accountId: output.accountId,
338 projectName: output.name,
339 })
340 .pipe(Effect.catchTag("ProjectNotFound", () => Effect.void));
341 }),
342 // Pages projects are account-scoped; enumerate every project in the
343 // account, paginating exhaustively, and hydrate each into the same
344 // Attributes shape `read` returns.
345 list: Effect.fn(function* () {
346 const { accountId } = yield* yield* CloudflareEnvironment;
347 return yield* pages.listProjects.pages({ accountId }).pipe(
348 Stream.runCollect,
349 Effect.map((chunk) =>
350 Array.from(chunk).flatMap((page) =>
351 (page.result ?? []).map((project): ProjectAttributes => ({
352 projectId: project.id,
353 accountId,
354 name: project.name,
355 subdomain: project.subdomain ?? `${project.name}.pages.dev`,
356 domains: [...(project.domains ?? [])],
357 productionBranch: project.productionBranch,
358 createdOn: project.createdOn,
359 })),
360 ),
361 ),
362 );
363 }),
364 });
365
366 // ---------------------------------------------------------------------------
367 // Observation
368 // ---------------------------------------------------------------------------
369
370 type ObservedProject =
371 | pages.GetProjectResponse
372 | pages.CreateProjectResponse
373 | pages.PatchProjectResponse;
374
375 /**
376 * Read a project by name, mapping "gone" (`ProjectNotFound`, Cloudflare
377 * error code 8000007) to `undefined`.
378 */
379 const getProject = (accountId: string, projectName: string) =>
380 pages
381 .getProject({ accountId, projectName })
382 .pipe(Effect.catchTag("ProjectNotFound", () => Effect.undefined));
383
384 /**
385 * Pages project names form the `<name>.pages.dev` subdomain: lowercase
386 * alphanumerics and dashes, at most 58 characters.
387 */
388 const createProjectName = (id: string, name?: string) =>
389 Effect.gen(function* () {
390 return name ?? (yield* createPhysicalName({ id, lowercase: true, maxLength: 58 }));
391 });
392
393 const toAttributes = (project: ObservedProject, accountId: string): ProjectAttributes => ({
394 projectId: project.id,
395 accountId,
396 name: project.name,
397 subdomain: project.subdomain ?? `${project.name}.pages.dev`,
398 domains: [...(project.domains ?? [])],
399 productionBranch: project.productionBranch,
400 createdOn: project.createdOn,
401 });
402
403 // ---------------------------------------------------------------------------
404 // Desired-state mapping
405 // ---------------------------------------------------------------------------
406
407 type ApiBuildConfig = NonNullable<pages.CreateProjectRequest["buildConfig"]>;
408 type ApiDeploymentConfigs = NonNullable<pages.CreateProjectRequest["deploymentConfigs"]>;
409 type ApiEnvConfig = NonNullable<ApiDeploymentConfigs["production"]>;
410 type ObservedEnvConfig = pages.GetProjectResponse["deploymentConfigs"]["production"];
411
412 const toApiBuildConfig = (config: BuildConfig | undefined): ApiBuildConfig | undefined =>
413 config === undefined
414 ? undefined
415 : {
416 buildCaching: config.buildCaching,
417 buildCommand: config.buildCommand,
418 destinationDir: config.destinationDir,
419 rootDir: config.rootDir,
420 };
421
422 /**
423 * Map the desired deployment config of one environment to the API shape.
424 * When `observed` is provided, record-shaped fields include explicit
425 * `null`s for observed keys absent from the desired config — Cloudflare's
426 * PATCH endpoint deep-merges, so this is how keys are removed.
427 */
428 const toApiEnvConfig = (
429 desired: DeploymentConfig,
430 observed: ObservedEnvConfig | undefined,
431 ): ApiEnvConfig => ({
432 envVars: mergeRecord(
433 desired.envVars === undefined
434 ? undefined
435 : Object.fromEntries(
436 Object.entries(desired.envVars).map(([key, envVar]) => [
437 key,
438 {
439 type: envVar.type ?? "plain_text",
440 value: envVar.value as string,
441 },
442 ]),
443 ),
444 observed?.envVars,
445 ),
446 kvNamespaces: mergeRecord(
447 mapBindingRecord(desired.kvNamespaces, "namespace_id"),
448 observed?.kvNamespaces,
449 ),
450 d1Databases: mergeRecord(mapBindingRecord(desired.d1Databases, "id"), observed?.d1Databases),
451 r2Buckets: mergeRecord(mapBindingRecord(desired.r2Buckets, "name"), observed?.r2Buckets),
452 compatibilityDate: desired.compatibilityDate,
453 compatibilityFlags: desired.compatibilityFlags,
454 failOpen: desired.failOpen,
455 placement: desired.placement,
456 });
457
458 const mapBindingRecord = (
459 record: Record<string, Input<string>> | undefined,
460 idKey: string,
461 ): Record<string, unknown> | undefined =>
462 record === undefined
463 ? undefined
464 : Object.fromEntries(
465 Object.entries(record).map(([binding, id]) => [binding, { [idKey]: id as string }]),
466 );
467
468 /**
469 * Overlay the desired record on top of the observed one, nulling observed
470 * keys that are absent from the desired record so PATCH removes them.
471 * `undefined` desired means "unmanaged" — leave the cloud state alone.
472 */
473 const mergeRecord = (
474 desired: Record<string, unknown> | undefined,
475 observed: Record<string, unknown> | null | undefined,
476 ): Record<string, unknown> | undefined => {
477 if (desired === undefined) return undefined;
478 const removals = Object.fromEntries(
479 Object.keys(observed ?? {})
480 .filter((key) => !(key in desired))
481 .map((key) => [key, null]),
482 );
483 return { ...removals, ...desired };
484 };
485
486 const toApiDeploymentConfigs = (
487 desired: DeploymentConfigs | undefined,
488 observed: pages.GetProjectResponse["deploymentConfigs"] | undefined,
489 ): ApiDeploymentConfigs | undefined => {
490 if (desired === undefined) return undefined;
491 const configs: ApiDeploymentConfigs = {};
492 if (desired.preview !== undefined) {
493 configs.preview = toApiEnvConfig(desired.preview, observed?.preview);
494 }
495 if (desired.production !== undefined) {
496 configs.production = toApiEnvConfig(desired.production, observed?.production);
497 }
498 return configs;
499 };
500
501 // ---------------------------------------------------------------------------
502 // Drift detection
503 // ---------------------------------------------------------------------------
504
505 type ProjectPatchBody = Pick<
506 pages.PatchProjectRequest,
507 "productionBranch" | "buildConfig" | "deploymentConfigs"
508 >;
509
510 /**
511 * Compute the PATCH body needed to converge the observed project to the
512 * desired props, or `undefined` when the project is already converged.
513 * Props left `undefined` are unmanaged and never touched.
514 */
515 const buildProjectPatch = (
516 news: ProjectProps,
517 observed: ObservedProject,
518 ): ProjectPatchBody | undefined => {
519 const patch: ProjectPatchBody = {};
520 let dirty = false;
521
522 const desiredBranch = news.productionBranch ?? "main";
523 if (observed.productionBranch !== desiredBranch) {
524 patch.productionBranch = desiredBranch;
525 dirty = true;
526 }
527
528 if (news.buildConfig !== undefined && buildConfigDirty(news.buildConfig, observed.buildConfig)) {
529 patch.buildConfig = toApiBuildConfig(news.buildConfig);
530 dirty = true;
531 }
532
533 if (news.deploymentConfigs !== undefined) {
534 const desired = toApiDeploymentConfigs(
535 news.deploymentConfigs,
536 observedDeploymentConfigs(observed),
537 );
538 if (
539 desired !== undefined &&
540 deploymentConfigsDirty(desired, observedDeploymentConfigs(observed))
541 ) {
542 patch.deploymentConfigs = desired;
543 dirty = true;
544 }
545 }
546
547 return dirty ? patch : undefined;
548 };
549
550 const observedDeploymentConfigs = (
551 observed: ObservedProject,
552 ): pages.GetProjectResponse["deploymentConfigs"] => observed.deploymentConfigs;
553
554 const buildConfigDirty = (
555 desired: BuildConfig,
556 observed: ObservedProject["buildConfig"],
557 ): boolean => {
558 const fields: (keyof BuildConfig)[] = [
559 "buildCaching",
560 "buildCommand",
561 "destinationDir",
562 "rootDir",
563 ];
564 return fields.some(
565 (field) => desired[field] !== undefined && desired[field] !== (observed?.[field] ?? undefined),
566 );
567 };
568
569 const deploymentConfigsDirty = (
570 desired: ApiDeploymentConfigs,
571 observed: pages.GetProjectResponse["deploymentConfigs"] | undefined,
572 ): boolean =>
573 (desired.preview !== undefined && envConfigDirty(desired.preview, observed?.preview)) ||
574 (desired.production !== undefined && envConfigDirty(desired.production, observed?.production));
575
576 const envConfigDirty = (
577 desired: ApiEnvConfig,
578 observed: ObservedEnvConfig | undefined,
579 ): boolean => {
580 if (
581 desired.compatibilityDate !== undefined &&
582 desired.compatibilityDate !== observed?.compatibilityDate
583 ) {
584 return true;
585 }
586 if (
587 desired.compatibilityFlags !== undefined &&
588 !arrayEqualsUnordered(desired.compatibilityFlags, observed?.compatibilityFlags ?? [])
589 ) {
590 return true;
591 }
592 if (desired.failOpen !== undefined && desired.failOpen !== observed?.failOpen) {
593 return true;
594 }
595 if (desired.placement !== undefined && desired.placement.mode !== observed?.placement?.mode) {
596 return true;
597 }
598 return (
599 recordDirty(desired.envVars, observed?.envVars, envVarEquals) ||
600 recordDirty(desired.kvNamespaces, observed?.kvNamespaces, deepEquals) ||
601 recordDirty(desired.d1Databases, observed?.d1Databases, deepEquals) ||
602 recordDirty(desired.r2Buckets, observed?.r2Buckets, deepEquals)
603 );
604 };
605
606 /**
607 * A merged desired record (which already contains `null` removal markers)
608 * is dirty when any non-null entry differs from the observed value or any
609 * null marker still has an observed value to remove.
610 */
611 const recordDirty = (
612 desired: Record<string, unknown> | undefined,
613 observed: Record<string, unknown> | null | undefined,
614 equals: (a: unknown, b: unknown) => boolean,
615 ): boolean => {
616 if (desired === undefined) return false;
617 return Object.entries(desired).some(([key, value]) =>
618 value === null
619 ? observed?.[key] !== undefined && observed[key] !== null
620 : !equals(value, observed?.[key]),
621 );
622 };
623
624 /**
625 * Secrets read back as `{ type: "secret_text" }` without a value, so a
626 * desired secret with a value can never be proven converged — treat
627 * matching-type secrets as equal and rely on PATCH idempotency.
628 */
629 const envVarEquals = (desired: unknown, observed: unknown): boolean => {
630 const d = desired as { type?: string; value?: string };
631 const o = observed as { type?: string; value?: string } | undefined;
632 if (o === undefined) return false;
633 if (d.type === "secret_text") return o.type === "secret_text";
634 return (o.type ?? "plain_text") === (d.type ?? "plain_text") && o.value === d.value;
635 };
636
637 const deepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);