The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as zones from "@distilled.cloud/cloudflare/zones"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { stripNullFields } from "alchemy/Util/data"; |
| 7 | import * as Array from "effect/Array"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Equivalence from "effect/Equivalence"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { findZoneByName } from "./lookup.ts"; |
| 15 | |
| 16 | export class ZoneUnexpectedResponse extends Data.TaggedError("ZoneUnexpectedResponse")<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | export type Type = "full" | "partial" | "secondary" | "internal"; |
| 22 | export type Status = "initializing" | "pending" | "active" | "moved"; |
| 23 | |
| 24 | /** Metadata about the zone (Cloudflare `meta`). */ |
| 25 | export type Meta = { |
| 26 | /** @deprecated Always `false`. */ |
| 27 | cdnOnly: boolean | undefined; |
| 28 | /** Number of allowed custom certificates. */ |
| 29 | customCertificateQuota: number | undefined; |
| 30 | /** @deprecated Always `true`. */ |
| 31 | dnsOnly: boolean | undefined; |
| 32 | /** Whether the zone is on Cloudflare's Foundation DNS plan. */ |
| 33 | foundationDns: boolean | undefined; |
| 34 | /** Number of allowed Page Rules. */ |
| 35 | pageRuleQuota: number | undefined; |
| 36 | /** Whether the zone has been flagged for phishing. */ |
| 37 | phishingDetected: boolean | undefined; |
| 38 | /** Onboarding step the zone is currently on. */ |
| 39 | step: number | undefined; |
| 40 | }; |
| 41 | |
| 42 | /** The owner of the zone (Cloudflare `owner`). */ |
| 43 | export type Owner = { |
| 44 | /** Owner identifier. */ |
| 45 | id: string | undefined; |
| 46 | /** Owner name. */ |
| 47 | name: string | undefined; |
| 48 | /** Owner type (e.g. `user`, `organization`). */ |
| 49 | type: string | undefined; |
| 50 | }; |
| 51 | |
| 52 | /** An organizational unit (tenant) the zone belongs to. */ |
| 53 | export type Tenant = { |
| 54 | /** Tenant identifier. */ |
| 55 | id: string | undefined; |
| 56 | /** Tenant name. */ |
| 57 | name: string | undefined; |
| 58 | }; |
| 59 | |
| 60 | /** The immediate parent organizational unit of the zone. */ |
| 61 | export type TenantUnit = { |
| 62 | /** Tenant unit identifier. */ |
| 63 | id: string | undefined; |
| 64 | }; |
| 65 | |
| 66 | /** |
| 67 | * Common shape returned by a managed {@link Zone} resource — anything that |
| 68 | * needs to point at a Cloudflare Zone can accept this. |
| 69 | * |
| 70 | * Mirrors Cloudflare's zone object. `zoneId` and `accountId` are Alchemy's |
| 71 | * flattened identifiers (Cloudflare exposes these as `id` and `account.id`); |
| 72 | * every other field keeps Cloudflare's own (camelCased) name. |
| 73 | */ |
| 74 | export type Attributes = { |
| 75 | /** Zone identifier (Cloudflare `id`). Stable across updates. */ |
| 76 | zoneId: string; |
| 77 | /** The fully-qualified domain name (e.g. `example.com`). */ |
| 78 | name: string; |
| 79 | /** Identifier of the account the zone belongs to (Cloudflare `account.id`). */ |
| 80 | accountId: string; |
| 81 | /** Name of the account the zone belongs to (Cloudflare `account.name`). */ |
| 82 | accountName: string | undefined; |
| 83 | /** |
| 84 | * Zone type. A full zone hosts its DNS at Cloudflare; a partial zone is a |
| 85 | * partner/CNAME setup. |
| 86 | */ |
| 87 | type: Type; |
| 88 | /** The zone status on Cloudflare. */ |
| 89 | status: Status | undefined; |
| 90 | /** |
| 91 | * Whether the zone is DNS-only (Cloudflare's proxy/security features |
| 92 | * disabled). |
| 93 | */ |
| 94 | paused: boolean; |
| 95 | /** The name servers Cloudflare assigns to the zone. */ |
| 96 | nameServers: string[]; |
| 97 | /** The original name servers before the domain moved to Cloudflare. */ |
| 98 | originalNameServers: string[] | undefined; |
| 99 | /** Custom (vanity) name servers. Business/Enterprise plans only. */ |
| 100 | vanityNameServers: string[] | undefined; |
| 101 | /** The last time proof of ownership was detected and the zone activated. */ |
| 102 | activatedOn: string | undefined; |
| 103 | /** When the zone was created. */ |
| 104 | createdOn: string; |
| 105 | /** |
| 106 | * The interval (in seconds) until development mode expires (positive) or |
| 107 | * since it last expired (negative). `0` if never enabled. |
| 108 | */ |
| 109 | developmentMode: number; |
| 110 | /** When the zone was last modified. */ |
| 111 | modifiedOn: string; |
| 112 | /** The DNS host at the time of switching to Cloudflare. */ |
| 113 | originalDnshost: string | undefined; |
| 114 | /** The registrar for the domain at the time of switching to Cloudflare. */ |
| 115 | originalRegistrar: string | undefined; |
| 116 | /** Allows the customer to use a custom apex (tenants-only configuration). */ |
| 117 | cnameSuffix: string | undefined; |
| 118 | /** Verification key for partial zone setup. */ |
| 119 | verificationKey: string | undefined; |
| 120 | /** Metadata about the zone. */ |
| 121 | meta: Meta; |
| 122 | /** The owner of the zone. */ |
| 123 | owner: Owner; |
| 124 | /** The root organizational unit (tenant) the zone belongs to. */ |
| 125 | tenant: Tenant | undefined; |
| 126 | /** The immediate parent organizational unit of the zone. */ |
| 127 | tenantUnit: TenantUnit | undefined; |
| 128 | }; |
| 129 | |
| 130 | export type Props = { |
| 131 | /** |
| 132 | * The fully-qualified zone name (e.g. `example.com`). Stable — changing it |
| 133 | * triggers a replacement. |
| 134 | */ |
| 135 | name: string; |
| 136 | /** |
| 137 | * Zone type. Full zones host their own DNS at Cloudflare; partial zones are |
| 138 | * partner/CNAME setups. |
| 139 | * @default "full" |
| 140 | */ |
| 141 | type?: Type; |
| 142 | /** |
| 143 | * Pause Cloudflare's proxy on the zone (DNS-only). |
| 144 | * @default false |
| 145 | */ |
| 146 | paused?: boolean; |
| 147 | /** |
| 148 | * Custom (vanity) name servers. Business/Enterprise only. |
| 149 | */ |
| 150 | vanityNameServers?: string[]; |
| 151 | }; |
| 152 | |
| 153 | export type Zone = Resource<"Cloudflare.Zone.Zone", Props, Attributes, never, Providers>; |
| 154 | |
| 155 | /** |
| 156 | * A Cloudflare Zone (DNS domain) managed by Alchemy. |
| 157 | * |
| 158 | * Zones default to **retain** on removal — destroying the stack does NOT |
| 159 | * delete the zone in Cloudflare. Opt in to actual deletion by wrapping the |
| 160 | * resource (or the whole stack) in {@link destroy}() from |
| 161 | * `alchemy/RemovalPolicy`. |
| 162 | * ### Creating a Zone |
| 163 | * **Example:** Create a new zone |
| 164 | * ```typescript |
| 165 | * const zone = yield* Cloudflare.Zone.Zone("MyZone", { |
| 166 | * name: "example.com", |
| 167 | * }); |
| 168 | * ``` |
| 169 | * |
| 170 | * **Example:** Allow destruction |
| 171 | * ```typescript |
| 172 | * import { destroy } from "alchemy/RemovalPolicy"; |
| 173 | * yield* Cloudflare.Zone.Zone("MyZone", { name: "example.com" }).pipe(destroy()); |
| 174 | * ``` |
| 175 | * |
| 176 | * ### Adopting an existing Zone |
| 177 | * **Example:** Take over a zone that already exists in Cloudflare |
| 178 | * ```typescript |
| 179 | * import { adopt } from "alchemy/AdoptPolicy"; |
| 180 | * // A zone carries no ownership markers, so the engine refuses to take over a |
| 181 | * // pre-existing zone unless you opt in with `adopt(true)`. |
| 182 | * const zone = yield* Cloudflare.Zone.Zone("MyZone", { |
| 183 | * name: "example.com", |
| 184 | * }).pipe(adopt(true)); |
| 185 | * // zone.zoneId, zone.nameServers, zone.accountId, ... |
| 186 | * ``` |
| 187 | * |
| 188 | * @resource |
| 189 | * @product Zones |
| 190 | * @category Domains & DNS |
| 191 | */ |
| 192 | export const Zone = Resource<Zone>("Cloudflare.Zone.Zone", { |
| 193 | defaultRemovalPolicy: "retain", |
| 194 | aliases: ["Cloudflare.Zone"], |
| 195 | }); |
| 196 | |
| 197 | export const ZoneProvider = () => |
| 198 | Provider.effect( |
| 199 | Zone, |
| 200 | Effect.gen(function* () { |
| 201 | // const get = yield* zones.getZone; |
| 202 | // const create = yield* zones.createZone; |
| 203 | // const patch = yield* zones.patchZone; |
| 204 | // const del = yield* zones.deleteZone; |
| 205 | |
| 206 | return { |
| 207 | stables: ["name", "zoneId", "accountId"], |
| 208 | diff: Effect.fn(function* ({ news, output }) { |
| 209 | if (!output) return undefined; |
| 210 | if (!isResolved(news)) return undefined; |
| 211 | if (news.name !== output.name) { |
| 212 | return { action: "replace" } as const; |
| 213 | } |
| 214 | const desiredType = news.type ?? "full"; |
| 215 | const desiredPaused = news.paused ?? false; |
| 216 | const desiredVanity = news.vanityNameServers ?? []; |
| 217 | if ( |
| 218 | desiredType !== output.type || |
| 219 | desiredPaused !== output.paused || |
| 220 | !stringArrayEq(desiredVanity, output.vanityNameServers ?? []) |
| 221 | ) { |
| 222 | return { action: "update" } as const; |
| 223 | } |
| 224 | return undefined; |
| 225 | }), |
| 226 | read: Effect.fn(function* ({ output, olds }) { |
| 227 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 228 | const name = output?.name ?? olds?.name; |
| 229 | // Owned path: we have persisted state (our own zoneId) — refresh it. |
| 230 | if (output?.zoneId) { |
| 231 | const result = yield* zones |
| 232 | .getZone({ zoneId: output.zoneId }) |
| 233 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 234 | if (result) return toZoneAttributes(result, accountId); |
| 235 | } |
| 236 | // Adoption path: no state of our own, but a zone with this name |
| 237 | // already exists in the cloud. Cloudflare zones carry no ownership |
| 238 | // markers we can inspect, so we cannot prove we created it — brand |
| 239 | // it `Unowned` so the engine refuses to take over unless `adopt` is |
| 240 | // set. |
| 241 | if (name) { |
| 242 | const match = yield* findZoneByName({ accountId, name }); |
| 243 | if (!match) return undefined; |
| 244 | const result = yield* zones.getZone({ zoneId: match.id }); |
| 245 | return Unowned(toZoneAttributes(result, accountId)); |
| 246 | } |
| 247 | return undefined; |
| 248 | }), |
| 249 | reconcile: Effect.fn(function* ({ news, output }) { |
| 250 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 251 | // 1. Observe — do we have a live zone for this name? |
| 252 | let zoneId = output?.zoneId; |
| 253 | if (!zoneId) { |
| 254 | const match = yield* findZoneByName({ |
| 255 | accountId, |
| 256 | name: news.name, |
| 257 | }); |
| 258 | zoneId = match?.id; |
| 259 | } |
| 260 | |
| 261 | // 2. Ensure — create if missing. |
| 262 | if (!zoneId) { |
| 263 | zoneId = yield* zones |
| 264 | .createZone({ |
| 265 | account: { id: accountId }, |
| 266 | name: news.name, |
| 267 | type: news.type ?? "full", |
| 268 | }) |
| 269 | .pipe( |
| 270 | Effect.map((created) => created.id), |
| 271 | // A concurrent deploy (or a prior crashed run) may have created |
| 272 | // the zone between our observe and create — recover by resolving |
| 273 | // its id rather than failing the reconcile. |
| 274 | Effect.catchTag("ZoneAlreadyExists", () => |
| 275 | findZoneByName({ accountId, name: news.name }).pipe( |
| 276 | Effect.flatMap((match) => |
| 277 | match |
| 278 | ? Effect.succeed(match.id) |
| 279 | : Effect.fail( |
| 280 | new ZoneUnexpectedResponse({ |
| 281 | message: `Cloudflare reported zone ${news.name} already exists but it could not be found`, |
| 282 | }), |
| 283 | ), |
| 284 | ), |
| 285 | ), |
| 286 | ), |
| 287 | ); |
| 288 | } |
| 289 | |
| 290 | // 3. Sync — apply mutable settings (type/paused/vanity NS). |
| 291 | const observed = yield* zones.getZone({ zoneId }); |
| 292 | const desiredType = news.type ?? "full"; |
| 293 | const desiredPaused = news.paused ?? false; |
| 294 | const desiredVanity = news.vanityNameServers ?? []; |
| 295 | const needsPatch = |
| 296 | (observed.type ?? "full") !== desiredType || |
| 297 | (observed.paused ?? false) !== desiredPaused || |
| 298 | !stringArrayEq(observed.vanityNameServers ?? [], desiredVanity); |
| 299 | |
| 300 | if (needsPatch) { |
| 301 | yield* zones.patchZone({ |
| 302 | zoneId, |
| 303 | type: desiredType, |
| 304 | paused: desiredPaused, |
| 305 | vanityNameServers: desiredVanity, |
| 306 | }); |
| 307 | } |
| 308 | |
| 309 | const final = yield* zones.getZone({ zoneId }); |
| 310 | return toZoneAttributes(final, accountId); |
| 311 | }), |
| 312 | delete: Effect.fn(function* ({ output }) { |
| 313 | if (!output.zoneId) return; |
| 314 | yield* zones.deleteZone({ zoneId: output.zoneId }).pipe( |
| 315 | // Zone already gone — idempotent delete. |
| 316 | Effect.catchTag("InvalidZoneIdentifier", () => Effect.void), |
| 317 | ); |
| 318 | }), |
| 319 | list: () => |
| 320 | Effect.gen(function* () { |
| 321 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 322 | // Enumerate every zone in the account, paginating exhaustively. |
| 323 | const zoneIds = yield* zones.listZones.pages({ account: { id: accountId } }).pipe( |
| 324 | Stream.runCollect, |
| 325 | Effect.map((chunk) => |
| 326 | Array.fromIterable(chunk).flatMap((page) => |
| 327 | (page.result ?? []).map((zone) => zone.id), |
| 328 | ), |
| 329 | ), |
| 330 | ); |
| 331 | // Hydrate each into the exact `read` Attributes shape via getZone, |
| 332 | // tolerating zones that vanish mid-enumeration. |
| 333 | const rows = yield* Effect.forEach( |
| 334 | zoneIds, |
| 335 | (zoneId) => |
| 336 | zones.getZone({ zoneId }).pipe( |
| 337 | Effect.map((result) => toZoneAttributes(result, accountId)), |
| 338 | Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined), |
| 339 | ), |
| 340 | { concurrency: 10 }, |
| 341 | ); |
| 342 | return rows.filter((row): row is Attributes => row !== undefined); |
| 343 | }), |
| 344 | }; |
| 345 | }), |
| 346 | ); |
| 347 | |
| 348 | /** @internal — shape a distilled zones API result into `Attributes`. */ |
| 349 | export const toZoneAttributes = ( |
| 350 | result: zones.GetZoneResponse, |
| 351 | fallbackAccountId: string, |
| 352 | ): Attributes => { |
| 353 | // Cloudflare returns `null` for absent fields; drop them so every optional |
| 354 | // attribute is simply `undefined` (matching `Attributes`). |
| 355 | const z = stripNullFields(result); |
| 356 | return { |
| 357 | zoneId: z.id, |
| 358 | name: z.name, |
| 359 | accountId: z.account.id ?? fallbackAccountId, |
| 360 | accountName: z.account.name, |
| 361 | type: z.type ?? "full", |
| 362 | status: z.status, |
| 363 | paused: z.paused ?? false, |
| 364 | nameServers: z.nameServers, |
| 365 | originalNameServers: z.originalNameServers, |
| 366 | vanityNameServers: z.vanityNameServers, |
| 367 | activatedOn: z.activatedOn, |
| 368 | createdOn: z.createdOn, |
| 369 | developmentMode: z.developmentMode, |
| 370 | modifiedOn: z.modifiedOn, |
| 371 | originalDnshost: z.originalDnshost, |
| 372 | originalRegistrar: z.originalRegistrar, |
| 373 | cnameSuffix: z.cnameSuffix, |
| 374 | verificationKey: z.verificationKey, |
| 375 | meta: z.meta, |
| 376 | owner: z.owner, |
| 377 | tenant: z.tenant, |
| 378 | tenantUnit: z.tenantUnit, |
| 379 | } as Attributes; |
| 380 | }; |
| 381 | |
| 382 | const stringArrayEq = Array.makeEquivalence(Equivalence.String); |