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

main
ts 781 lines 26.5 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
2 import * as zones from "@distilled.cloud/cloudflare/zones";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { arrayEqualsUnordered } from "alchemy/Util/equal";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 export class RecordUnexpectedResponse extends Data.TaggedError("RecordUnexpectedResponse")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 /**
20 * DNS record type literal — every value Cloudflare recognises. Stable
21 * across reconciles; changing it triggers a replacement because record
22 * type is part of a record's identity.
23 */
24 export type RecordType =
25 | "A"
26 | "AAAA"
27 | "CNAME"
28 | "MX"
29 | "NS"
30 | "OPENPGPKEY"
31 | "PTR"
32 | "TXT"
33 | "CAA"
34 | "CERT"
35 | "DNSKEY"
36 | "DS"
37 | "HTTPS"
38 | "LOC"
39 | "NAPTR"
40 | "SMIMEA"
41 | "SRV"
42 | "SSHFP"
43 | "SVCB"
44 | "TLSA"
45 | "URI"
46 | (string & {});
47
48 /**
49 * Cloudflare's structured DNS record components, keyed by record type.
50 */
51 export interface RecordDataByType {
52 CAA: dns.RecordsCreateRequestDataCAARecord;
53 CERT: dns.RecordsCreateRequestDataCERTRecord;
54 DNSKEY: dns.RecordsCreateRequestDataDNSKEYRecord;
55 DS: dns.RecordsCreateRequestDataDSRecord;
56 HTTPS: dns.RecordsCreateRequestDataHTTPSRecord;
57 LOC: dns.RecordsCreateRequestDataLOCRecord;
58 NAPTR: dns.RecordsCreateRequestDataNAPTRRecord;
59 SMIMEA: dns.RecordsCreateRequestDataSMIMEARecord;
60 SRV: dns.RecordsCreateRequestDataSRVRecord;
61 SSHFP: dns.RecordsCreateRequestDataSSHFPRecord;
62 SVCB: dns.RecordsCreateRequestDataHTTPSRecord;
63 TLSA: dns.RecordsCreateRequestDataSMIMEARecord;
64 URI: dns.RecordsCreateRequestDataURIRecord;
65 }
66
67 /** Structured DNS record components accepted by Cloudflare. */
68 export type RecordData = RecordDataByType[keyof RecordDataByType];
69
70 export interface RecordCommonProps {
71 /**
72 * Zone the record lives in. Stable — changing the zone triggers
73 * replacement.
74 */
75 zoneId: string;
76 /**
77 * Fully-qualified or zone-relative record name (e.g.
78 * `cluster-admin.microtrack.ai`, `_dmarc`, or `@` for the zone apex).
79 * Cloudflare normalizes relative names to their fully-qualified form.
80 *
81 * Stable — Cloudflare treats `(name, type)` as the record's identity,
82 * so a rename is a delete + create. Declared as plain `string` (not
83 * `string`) so it is statically knowable inside `diff`.
84 */
85 name: string;
86 /**
87 * TTL in seconds (`60`–`86400`), or `"1"` for Cloudflare's "automatic"
88 * setting. Must be `"1"` when `proxied` is `true`.
89 *
90 * @default "1"
91 */
92 ttl?: number | "1";
93 /**
94 * Whether to send the record through Cloudflare's proxy (orange-clouded
95 * in the dashboard). Only valid for proxiable record types
96 * (`A`, `AAAA`, `CNAME`).
97 *
98 * @default false
99 */
100 proxied?: boolean;
101 /**
102 * Free-form comment shown in the dashboard. No effect on DNS responses.
103 */
104 comment?: string;
105 /**
106 * Custom tags shown in the dashboard. No effect on DNS responses.
107 */
108 tags?: ReadonlyArray<string>;
109 }
110
111 type StringRecordType = Exclude<RecordType, keyof RecordDataByType | "MX">;
112
113 type StringRecordProps = {
114 /** Record type. Stable — changing triggers replacement. */
115 type: StringRecordType;
116 /** Formatted record value. Mutable — patched in place. */
117 content: string;
118 priority?: never;
119 };
120
121 interface MxRecordProps {
122 /** Record type. Stable — changing triggers replacement. */
123 type: "MX";
124 /** Mail server hostname. Mutable — patched in place. */
125 content: string;
126 /** Mail server priority; lower values are preferred. */
127 priority?: number;
128 }
129
130 type StructuredRecordProps = {
131 [Type in keyof RecordDataByType]: {
132 /** Record type. Stable — changing triggers replacement. */
133 type: Type;
134 /**
135 * Record value as formatted DNS content or typed Cloudflare components.
136 * Mutable — patched in place.
137 */
138 content: string | RecordDataByType[Type];
139 /**
140 * Top-level priority, used by URI records. SRV, SVCB, and HTTPS put their
141 * priority inside structured `content`.
142 */
143 priority?: Type extends "URI" ? number : never;
144 };
145 }[keyof RecordDataByType];
146
147 /** Input properties for a Cloudflare DNS record. */
148 export type RecordProps = RecordCommonProps &
149 (StringRecordProps | MxRecordProps | StructuredRecordProps);
150
151 export interface RecordAttributes {
152 /** Cloudflare-assigned DNS record UUID. */
153 recordId: string;
154 /** Zone that owns this record. */
155 zoneId: string;
156 /** Record name (FQDN, as Cloudflare returns it). */
157 name: string;
158 /** Record type. */
159 type: RecordType;
160 /** Formatted record value returned by Cloudflare. */
161 content: string;
162 /** Structured record components, when Cloudflare returns them. */
163 data?: RecordData;
164 /** Resolved TTL (Cloudflare echoes `1` for "automatic"). */
165 ttl: number;
166 /** Whether the record is proxied. */
167 proxied: boolean;
168 /** ISO8601 creation timestamp. */
169 createdOn: string | undefined;
170 /** ISO8601 last-modified timestamp. */
171 modifiedOn: string | undefined;
172 }
173
174 export type Record = Resource<
175 "Cloudflare.DNS.Record",
176 RecordProps,
177 RecordAttributes,
178 never,
179 Providers
180 >;
181
182 /**
183 * A single DNS record on a Cloudflare-managed zone.
184 *
185 * Safety: when there is no prior state, `read` scans the zone for an
186 * existing `(name, type)` match. DNS records carry no ownership markers
187 * we can inspect, so an existing match is reported as `Unowned` and the
188 * engine refuses to take it over unless `--adopt` (or `adopt(true)`) is
189 * set. This protects hand-edited records (especially the apex `A`/`AAAA`
190 * and email DKIM/SPF records that the dashboard often manages) from
191 * being clobbered.
192 *
193 * Several records may legitimately share `(name, type)` — MX fallbacks,
194 * multiple TXT records, round-robin A records. When the scan finds more
195 * than one candidate, the declared `content` (and `priority`) must match
196 * exactly one record; a record with no exact match is treated as missing
197 * (a new sibling record is created), and a still-ambiguous match fails
198 * with an error listing the candidates. To adopt one record out of such
199 * a set, declare its current `content`/`priority` verbatim first, then
200 * change them in a follow-up deploy.
201 * ### Proxied CNAME pointing at a tunnel
202 * **Example:** Route a subdomain through a Cloudflare Tunnel
203 * ```typescript
204 * yield* Cloudflare.DNS.Record("AdminCname", {
205 * zoneId: zone.zoneId,
206 * name: "cluster-admin.example.com",
207 * type: "CNAME",
208 * content: `${tunnel.tunnelId}.cfargotunnel.com`,
209 * proxied: true,
210 * comment: "research admin UI",
211 * });
212 * ```
213 *
214 * ### Plain A record
215 * **Example:** Direct A record (not proxied)
216 * ```typescript
217 * yield* Cloudflare.DNS.Record("ApiA", {
218 * zoneId: zone.zoneId,
219 * name: "api.example.com",
220 * type: "A",
221 * content: "203.0.113.42",
222 * ttl: 300,
223 * });
224 * ```
225 *
226 * ### Structured service binding records
227 * **Example:** SVCB record
228 * ```typescript
229 * yield* Cloudflare.DNS.Record("McpSvcb", {
230 * zoneId: zone.zoneId,
231 * name: "_mcp._agents.example.com",
232 * type: "SVCB",
233 * content: {
234 * priority: 1,
235 * target: "mcp.example.com.",
236 * value: 'mandatory="alpn,port" alpn="h2,h3" port="443"',
237 * },
238 * });
239 * ```
240 *
241 * **Example:** HTTPS record
242 * ```typescript
243 * yield* Cloudflare.DNS.Record("WebsiteHttps", {
244 * zoneId: zone.zoneId,
245 * name: "example.com",
246 * type: "HTTPS",
247 * content: {
248 * priority: 1,
249 * target: ".",
250 * value: 'alpn="h2,h3"',
251 * },
252 * });
253 * ```
254 *
255 * @resource
256 * @product DNS
257 * @category Domains & DNS
258 */
259 export const Record = Resource<Record>("Cloudflare.DNS.Record", {
260 aliases: ["Cloudflare.Dns.Record"],
261 });
262
263 export const RecordProvider = () =>
264 Provider.succeed(Record, {
265 stables: ["recordId", "zoneId", "type", "name"],
266
267 // Zone-scoped collection: DNS records live under `/zones/{id}/dns_records`
268 // with no account-wide enumeration API. Fan out over every zone in the
269 // account, exhaustively paginate each zone's records, and hydrate each into
270 // the same `Attributes` shape `read` produces. A fresh scoped token can 403
271 // a zone (eventual consistency) or a zone may be partially provisioned —
272 // skip those zones (-> []) rather than failing the whole enumeration.
273 list: Effect.fn(function* () {
274 const { accountId } = yield* yield* CloudflareEnvironment;
275 const zones = yield* listAllZones(accountId);
276 const rows = yield* Effect.forEach(
277 zones,
278 (zone) =>
279 dns.listRecords.pages({ zoneId: zone.id }).pipe(
280 Stream.runCollect,
281 Effect.map((chunk) =>
282 Array.from(chunk).flatMap((page) =>
283 (page.result ?? []).flatMap((r) => {
284 const attrs = toAttributes(
285 narrowRecord(r as Parameters<typeof narrowRecord>[0]),
286 zone.id,
287 );
288 return attrs ? [attrs] : [];
289 }),
290 ),
291 ),
292 Effect.catchTag("Forbidden", () => Effect.succeed([] as RecordAttributes[])),
293 ),
294 { concurrency: 10 },
295 );
296 return rows.flat();
297 }),
298
299 diff: Effect.fn(function* ({ olds = {}, news }) {
300 const o = olds as RecordProps;
301 const n = news as RecordProps;
302 if (o.type !== undefined && o.type !== n.type) {
303 return { action: "replace" } as const;
304 }
305 if (o.name !== undefined && o.name !== n.name) {
306 return { action: "replace" } as const;
307 }
308 // zoneId is Input<string>; by reconcile time both sides are
309 // concrete strings.
310 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
311 return { action: "replace" } as const;
312 }
313 }),
314
315 reconcile: Effect.fn(function* ({ news, output }) {
316 // Inputs have been resolved to concrete strings by Plan.
317 const zoneId = news.zoneId as string;
318 const body = buildMutableBody(news);
319
320 // 1. Observe by cached id first.
321 let observed: ObservedRecord | undefined;
322 if (output?.recordId) {
323 observed = yield* observeById(zoneId, output.recordId);
324 }
325
326 // 2. Fall back to scanning the zone for a (name, type) match.
327 // Ownership has already been verified upstream — `read` reports
328 // existing records as `Unowned` and the engine gates takeover
329 // behind the adopt policy before reconcile ever runs.
330 // Adoption already arrives with `output` set, so a scan hit here
331 // is a leftover or a sibling: only an exact match is this record.
332 // A lone non-matching NS/TXT/A/... is a sibling of a multi-value
333 // set (e.g. four NS records created together) and must not be
334 // overwritten. A CNAME is exclusive at its name, so any hit is it.
335 let foundByScan = false;
336 if (!observed) {
337 const existing = yield* findByNameType(
338 zoneId,
339 news.name,
340 news.type,
341 {
342 content: body.content,
343 data: body.data,
344 priority: news.priority,
345 },
346 { exact: news.type !== "CNAME" },
347 );
348 if (existing) {
349 foundByScan = true;
350 observed = existing;
351 }
352 }
353
354 // 3. Ensure.
355 if (!observed) {
356 const created = yield* dns.createRecord({ zoneId, ...body }).pipe(
357 Effect.map(
358 (r) =>
359 ({
360 record: narrowRecord(r as Parameters<typeof narrowRecord>[0]),
361 raced: false,
362 }) as const,
363 ),
364 // A record with this `(name, type)` can already exist that the
365 // scan above missed — a leftover from an interrupted run, or a
366 // concurrent reconcile that won the create race. Cloudflare
367 // answers `An identical record already exists.`
368 // (`DnsRecordAlreadyExists`). Self-heal: re-scan and adopt the
369 // existing record instead of failing the deploy. Ownership was
370 // already gated by `read`/the adopt policy upstream.
371 Effect.catchTag("DnsRecordAlreadyExists", () =>
372 findByNameType(zoneId, news.name, news.type, {
373 content: body.content,
374 data: body.data,
375 priority: news.priority,
376 }).pipe(
377 Effect.flatMap((existing) =>
378 existing
379 ? Effect.succeed({ record: existing, raced: true } as const)
380 : Effect.fail(
381 new RecordUnexpectedResponse({
382 message:
383 `Cloudflare reported an identical DNS record for ` +
384 `(${news.name}, ${news.type}) but it could not be found`,
385 }),
386 ),
387 ),
388 ),
389 ),
390 );
391 observed = created.record;
392 // A raced/adopted record is treated like a scanned-existing one so
393 // the sync step converges its mutable fields; a genuine fresh create
394 // keeps `foundByScan` false so the no-op first-reconcile suppression
395 // below still applies.
396 if (created.raced) foundByScan = true;
397 }
398
399 // 4. Sync — Cloudflare's update endpoint is PUT-style; resend
400 // the full desired body when any mutable field differs.
401 if (!observed.id) {
402 return yield* new RecordUnexpectedResponse({
403 message: "Cloudflare did not return a record id for DNS record",
404 });
405 }
406 if (!bodyEqualsObserved(body, observed)) {
407 // Suppress noise when we just created the record above — the
408 // server echo already matches and any diff is a CF-side
409 // normalisation we shouldn't fight on the very first reconcile.
410 const justCreated = !output?.recordId && !foundByScan;
411 if (!justCreated) {
412 const updated = yield* dns.updateRecord({
413 zoneId,
414 dnsRecordId: observed.id,
415 ...body,
416 });
417 observed = narrowRecord(updated as Parameters<typeof narrowRecord>[0]);
418 }
419 }
420
421 // 5. Return.
422 if (
423 !observed.id ||
424 !observed.type ||
425 observed.content === undefined ||
426 observed.ttl === undefined
427 ) {
428 return yield* new RecordUnexpectedResponse({
429 message: "Cloudflare returned a DNS record without id/type/value/ttl",
430 });
431 }
432 return {
433 recordId: observed.id,
434 zoneId,
435 name: observed.name ?? body.name,
436 type: observed.type,
437 content: observed.content,
438 data: observed.data,
439 ttl: observed.ttl,
440 proxied: observed.proxied ?? false,
441 createdOn: observed.createdOn,
442 modifiedOn: observed.modifiedOn,
443 } satisfies RecordAttributes;
444 }),
445
446 delete: Effect.fn(function* ({ output }) {
447 yield* dns
448 .deleteRecord({
449 zoneId: output.zoneId,
450 dnsRecordId: output.recordId,
451 })
452 .pipe(Effect.catchTag("RecordNotFound", () => Effect.void));
453 }),
454
455 read: Effect.fn(function* ({ output, olds }) {
456 // Owned path: we have persisted state (our own recordId) — refresh it.
457 if (output?.recordId) {
458 const observed = yield* observeById(output.zoneId, output.recordId);
459 const attrs = toAttributes(observed, output.zoneId);
460 if (attrs) return attrs;
461 }
462 // Adoption path: no state of our own, but a record with this
463 // `(zoneId, name, type)` may already exist. DNS records carry no
464 // ownership markers we can inspect, so we cannot prove we created
465 // it — brand it `Unowned` so the engine refuses to take over
466 // unless `adopt` is set. Several records may legitimately share
467 // `(name, type)` (MX fallbacks, multiple TXT/A records) — the
468 // declared `content`/`priority` disambiguate which one this
469 // resource corresponds to.
470 const zoneId = output?.zoneId ?? olds?.zoneId;
471 const name = output?.name ?? olds?.name;
472 const type = output?.type ?? olds?.type;
473 if (zoneId && name && type) {
474 const observed = yield* findByNameType(zoneId, name, type, {
475 content:
476 typeof olds?.content === "string"
477 ? olds.content
478 : olds?.content === undefined
479 ? output?.content
480 : undefined,
481 data: typeof olds?.content === "object" ? olds.content : output?.data,
482 priority: olds?.priority,
483 });
484 const attrs = toAttributes(observed, zoneId);
485 if (attrs) return Unowned(attrs);
486 }
487 return undefined;
488 }),
489 });
490
491 const observeById = (zoneId: string, dnsRecordId: string) =>
492 Effect.gen(function* () {
493 const r = yield* dns.getRecord({ zoneId, dnsRecordId }).pipe(
494 // Only a missing record should fall through to the find-by-name path.
495 Effect.catchTag("RecordNotFound", () => Effect.undefined),
496 );
497 if (r === undefined) return undefined;
498 return narrowRecord(r as Parameters<typeof narrowRecord>[0]);
499 });
500
501 /**
502 * Property match used to disambiguate between several records sharing
503 * `(name, type)` — MX fallbacks, multiple TXT records, round-robin A
504 * records are all legitimate Cloudflare configurations.
505 */
506 interface RecordMatch {
507 readonly content?: string;
508 readonly data?: RecordData;
509 readonly priority?: number;
510 }
511
512 /**
513 * Raised when several DNS records share `(name, type)` and the declared
514 * `content`/`data`/`priority` do not select exactly one of them — adoption must
515 * never pick a record arbitrarily.
516 */
517 export class AmbiguousDnsRecordError extends Data.TaggedError("AmbiguousDnsRecordError")<{
518 readonly zoneId: string;
519 readonly recordName: string;
520 readonly type: RecordType;
521 readonly candidates: ReadonlyArray<{
522 readonly id?: string;
523 readonly content?: string;
524 readonly data?: RecordData;
525 readonly priority?: number;
526 }>;
527 readonly message: string;
528 }> {}
529
530 // Locate an existing record by `(zoneId, name, type)`. Cloudflare accepts
531 // relative names on writes but returns FQDNs on reads, so check the supplied
532 // name first and then its zone-qualified form. Used both for the adoption path
533 // and to surface a conflict when the caller hasn't opted into adoption.
534 //
535 // `(name, type)` alone is NOT a unique identity — several records may share
536 // it. A single candidate is returned as-is (preserving the adopt-then-modify
537 // flow where the desired content differs from the live record). With multiple
538 // candidates, the desired record value/priority must select exactly one:
539 // - exactly one exact match -> that record
540 // - no exact match -> `undefined` (a new sibling record is created)
541 // - several exact matches -> fail with an actionable error
542 const findByNameType = (
543 zoneId: string,
544 name: string,
545 type: RecordType,
546 match: RecordMatch,
547 options?: { readonly exact?: boolean },
548 ) =>
549 listExactByNameType(zoneId, name, type).pipe(
550 Effect.flatMap((found) => {
551 if (found.length > 0) return Effect.succeed(found);
552
553 return zones.getZone({ zoneId }).pipe(
554 Effect.flatMap((zone) => {
555 const normalizedName = normalizeRecordName(name, zone.name);
556 return normalizedName === name
557 ? Effect.succeed([] as ObservedRecord[])
558 : listExactByNameType(zoneId, normalizedName, type);
559 }),
560 );
561 }),
562 Effect.flatMap(
563 Effect.fn(function* (candidates) {
564 if (candidates.length === 0) return undefined;
565 if (candidates.length === 1 && !options?.exact) return candidates[0];
566 const narrowed = candidates.filter(
567 (r) =>
568 (match.content === undefined || r.content === match.content) &&
569 (match.data === undefined || recordDataEquals(match.data, r.data)) &&
570 (match.priority === undefined || r.priority === match.priority),
571 );
572 if (narrowed.length === 1) return narrowed[0];
573 if (narrowed.length === 0) return undefined;
574 return yield* new AmbiguousDnsRecordError({
575 zoneId,
576 recordName: name,
577 type,
578 candidates: candidates.map((r) => ({
579 id: r.id,
580 content: r.content,
581 data: r.data,
582 priority: r.priority,
583 })),
584 message:
585 `Multiple DNS records in zone ${zoneId} match (name=${name}, ` +
586 `type=${type}) and the desired record value/priority does not ` +
587 `select exactly one. Set \`content\`` +
588 (type === "MX" || type === "URI" ? " and `priority`" : "") +
589 ` to exactly match the record this resource should adopt ` +
590 `(you can change it afterwards). Candidates:\n` +
591 candidates
592 .map(
593 (r) =>
594 ` - id=${r.id} content=${JSON.stringify(r.content)}` +
595 (r.data === undefined ? "" : ` data=${JSON.stringify(r.data)}`) +
596 (r.priority === undefined ? "" : ` priority=${r.priority}`),
597 )
598 .join("\n"),
599 });
600 }),
601 ),
602 );
603
604 const listExactByNameType = (zoneId: string, name: string, type: RecordType) =>
605 dns.listRecords
606 .items({
607 zoneId,
608 name: { exact: name },
609 type: type as dns.ListRecordsRequest["type"],
610 })
611 .pipe(
612 Stream.runCollect,
613 Effect.map((chunk) =>
614 Array.from(chunk)
615 .filter((r) => r.name === name && r.type === type)
616 .map((r) => narrowRecord(r as Parameters<typeof narrowRecord>[0])),
617 ),
618 );
619
620 const normalizeRecordName = (name: string, zoneName: string): string => {
621 if (name === "@") return zoneName;
622 if (name === zoneName || name.endsWith(`.${zoneName}`)) return name;
623 return `${name}.${zoneName}`;
624 };
625
626 interface ObservedRecord {
627 readonly id?: string;
628 readonly name?: string;
629 readonly type?: RecordType;
630 readonly content?: string;
631 readonly ttl?: number;
632 readonly proxied?: boolean;
633 readonly comment?: string;
634 readonly tags?: ReadonlyArray<string>;
635 readonly priority?: number;
636 readonly data?: RecordData;
637 readonly createdOn?: string;
638 readonly modifiedOn?: string;
639 }
640
641 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
642
643 const narrowRecord = (raw: {
644 id?: string | null;
645 name?: string | null;
646 type?: string | null;
647 content?: string | null;
648 ttl?: number | null;
649 proxied?: boolean | null;
650 comment?: string | null;
651 tags?: ReadonlyArray<string> | null;
652 priority?: number | null;
653 data?: Readonly<{ [key: string]: unknown }> | null;
654 createdOn?: string | null;
655 modifiedOn?: string | null;
656 }): ObservedRecord => ({
657 id: undef(raw.id),
658 name: undef(raw.name),
659 type: raw.type == null ? undefined : (raw.type as RecordType),
660 content: undef(raw.content),
661 ttl: undef(raw.ttl),
662 proxied: undef(raw.proxied),
663 comment: undef(raw.comment),
664 tags: raw.tags == null ? undefined : (raw.tags as ReadonlyArray<string>),
665 priority: undef(raw.priority),
666 data: normalizeRecordData(raw.data),
667 createdOn: undef(raw.createdOn),
668 modifiedOn: undef(raw.modifiedOn),
669 });
670
671 const toAttributes = (
672 observed: ObservedRecord | undefined,
673 zoneId: string,
674 ): RecordAttributes | undefined => {
675 if (
676 !observed?.id ||
677 !observed.name ||
678 !observed.type ||
679 observed.content === undefined ||
680 observed.ttl === undefined
681 ) {
682 return undefined;
683 }
684 return {
685 recordId: observed.id,
686 zoneId,
687 name: observed.name,
688 type: observed.type,
689 content: observed.content,
690 data: observed.data,
691 ttl: observed.ttl,
692 proxied: observed.proxied ?? false,
693 createdOn: observed.createdOn,
694 modifiedOn: observed.modifiedOn,
695 };
696 };
697
698 // ---------------------------------------------------------------------------
699 // Body construction
700 // ---------------------------------------------------------------------------
701
702 interface RecordMutableBodyCommon {
703 name: string;
704 type: RecordType;
705 ttl: number;
706 proxied?: boolean;
707 comment?: string;
708 tags?: string[];
709 priority?: number;
710 }
711
712 type RecordMutableBody = RecordMutableBodyCommon &
713 ({ content: string; data?: never } | { content?: never; data: RecordData });
714
715 const buildMutableBody = (news: RecordProps): RecordMutableBody => {
716 const common: RecordMutableBodyCommon = {
717 name: news.name,
718 type: news.type,
719 // Cloudflare rejects the string `"1"` even though distilled types
720 // it as `number | "1"`; the API wants numeric 1 for "automatic".
721 ttl: news.ttl === undefined ? 1 : news.ttl === ("1" as unknown) ? 1 : (news.ttl as number),
722 proxied: news.proxied,
723 comment: news.comment,
724 tags: news.tags === undefined ? undefined : Array.from(news.tags),
725 priority: news.priority,
726 };
727 return typeof news.content === "string"
728 ? { ...common, content: news.content }
729 : { ...common, data: news.content };
730 };
731
732 // ---------------------------------------------------------------------------
733 // Drift detection
734 // ---------------------------------------------------------------------------
735
736 const bodyEqualsObserved = (desired: RecordMutableBody, observed: ObservedRecord): boolean => {
737 if (desired.content !== undefined && desired.content !== observed.content) {
738 return false;
739 }
740 if (desired.data !== undefined && !recordDataEquals(desired.data, observed.data)) {
741 return false;
742 }
743 // CF echoes ttl=1 for "automatic".
744 if (desired.ttl !== observed.ttl) return false;
745 if (desired.proxied !== undefined && desired.proxied !== (observed.proxied ?? false)) {
746 return false;
747 }
748 if (desired.comment !== undefined && desired.comment !== (observed.comment ?? "")) {
749 return false;
750 }
751 if (desired.tags !== undefined && !arrayEqualsUnordered(desired.tags, observed.tags)) {
752 return false;
753 }
754 if (desired.priority !== undefined && desired.priority !== observed.priority) {
755 return false;
756 }
757 return true;
758 };
759
760 const normalizeRecordData = (
761 data: Readonly<{ [key: string]: unknown }> | null | undefined,
762 ): RecordData | undefined => {
763 if (data == null) return undefined;
764 return Object.fromEntries(
765 Object.entries(data).filter(([, value]) => value != null),
766 ) as RecordData;
767 };
768
769 const recordDataEquals = (desired: RecordData, observed: RecordData | undefined): boolean => {
770 if (observed === undefined) return false;
771 const desiredEntries = Object.entries(desired).filter(([, value]) => value != null);
772 const observedEntries = Object.entries(observed).filter(([, value]) => value != null);
773 return (
774 desiredEntries.length === observedEntries.length &&
775 desiredEntries.every(([key, value]) =>
776 observedEntries.some(
777 ([observedKey, observedValue]) => observedKey === key && observedValue === value,
778 ),
779 )
780 );
781 };