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

main
ts 400 lines 14 KB
Raw
1 import * as pageRules from "@distilled.cloud/cloudflare/page-rules";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.PageRule.PageRule" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * A single Page Rule action — a discriminated union over every setting a
16 * Page Rule can override (e.g. `{ id: "always_use_https" }`,
17 * `{ id: "cache_level", value: "cache_everything" }`,
18 * `{ id: "forwarding_url", value: { url, statusCode: "301" | "302" } }`).
19 *
20 * Note: `forwarding_url` cannot be combined with most other actions —
21 * a rule either redirects or overrides settings, not both.
22 */
23 export type Action = pageRules.CreatePageRuleRequest["actions"][number];
24
25 /**
26 * Whether the rule is evaluated (`active`) or kept but ignored
27 * (`disabled`).
28 */
29 export type Status = "active" | "disabled";
30
31 export interface Props {
32 /**
33 * Zone the Page Rule applies to. Stable — moving a rule between zones
34 * triggers a replacement.
35 */
36 zoneId: string;
37 /**
38 * The URL pattern the rule matches, e.g. `*.example.com/images/*`.
39 *
40 * Mutable — the API accepts a new target via PUT. Declared as plain
41 * `string` (not `string`) so it is statically knowable inside
42 * `diff` and usable as the rule's identity for stateless recovery.
43 */
44 target: string;
45 /**
46 * The set of actions to perform when the target matches. Actions can
47 * redirect to another URL (`forwarding_url`) or override settings,
48 * but not both. Mutable — synced in place via PUT.
49 */
50 actions: ReadonlyArray<Action>;
51 /**
52 * The priority of the rule relative to other Page Rules on the zone.
53 * A higher number indicates a higher priority. Mutable.
54 *
55 * Note: priority is positional — Cloudflare clamps it to the number of
56 * Page Rules on the zone (a lone rule is always priority `1`), so the
57 * echoed priority may be lower than requested.
58 *
59 * @default 1
60 */
61 priority?: number;
62 /**
63 * Whether the rule is evaluated. Mutable.
64 *
65 * Note: the raw Cloudflare API defaults to `"disabled"`; Alchemy
66 * defaults to `"active"` so a deployed rule takes effect immediately.
67 *
68 * @default "active"
69 */
70 status?: Status;
71 }
72
73 export interface Attributes {
74 /** Cloudflare-assigned identifier of the Page Rule. */
75 pageRuleId: string;
76 /** Zone the rule belongs to. */
77 zoneId: string;
78 /** The URL pattern the rule matches. */
79 target: string;
80 /** The actions the rule performs, as echoed by Cloudflare. */
81 actions: ReadonlyArray<Action>;
82 /** The rule's priority relative to other Page Rules on the zone. */
83 priority: number;
84 /** Whether the rule is evaluated (`active`) or ignored (`disabled`). */
85 status: Status;
86 /** ISO8601 creation timestamp. */
87 createdOn: string;
88 /** ISO8601 last-modified timestamp. */
89 modifiedOn: string;
90 }
91
92 export type PageRule = Resource<TypeId, Props, Attributes, never, Providers>;
93
94 /**
95 * A Cloudflare **Page Rule** — a legacy zone-level rule that matches a URL
96 * pattern (`target`) and applies a set of `actions` (cache settings, SSL
97 * mode, redirects, etc.) at a given `priority`.
98 *
99 * :::caution[Legacy]
100 * Page Rules are a legacy product superseded by Cloudflare's modern Rules
101 * platform (Rulesets — Cache Rules, Redirect Rules, Configuration Rules,
102 * Origin Rules, Transform Rules). Prefer `Cloudflare.Ruleset.Ruleset` for new
103 * projects; use `Cloudflare.PageRule.PageRule` only for existing setups or
104 * migrations. Page Rules are also plan-limited (Free 3, Pro 20,
105 * Business 50, Enterprise 125).
106 * :::
107 *
108 * A rule's recoverable identity is its `target` URL pattern within the
109 * zone. Page Rules carry no ownership markers, so when there is no prior
110 * state `read` scans the zone for a rule with the same target and reports
111 * it as `Unowned` — the engine refuses to take it over unless `--adopt`
112 * (or `adopt(true)`) is set.
113 * ### Caching
114 * **Example:** Cache everything under a path
115 * ```typescript
116 * yield* Cloudflare.PageRule.PageRule("CacheImages", {
117 * zoneId: zone.zoneId,
118 * target: `${zone.name}/images/*`,
119 * actions: [
120 * { id: "cache_level", value: "cache_everything" },
121 * { id: "edge_cache_ttl", value: 7200 },
122 * ],
123 * });
124 * ```
125 *
126 * ### Redirects
127 * **Example:** Permanent redirect with forwarding_url
128 * ```typescript
129 * // forwarding_url cannot be combined with most other actions.
130 * yield* Cloudflare.PageRule.PageRule("RedirectOldBlog", {
131 * zoneId: zone.zoneId,
132 * target: `${zone.name}/blog/*`,
133 * actions: [
134 * {
135 * id: "forwarding_url",
136 * value: { url: "https://new.example.com/blog/$1", statusCode: "301" },
137 * },
138 * ],
139 * });
140 * ```
141 *
142 * ### Security
143 * **Example:** Force HTTPS and raise the security level
144 * ```typescript
145 * yield* Cloudflare.PageRule.PageRule("SecureAdmin", {
146 * zoneId: zone.zoneId,
147 * target: `${zone.name}/admin/*`,
148 * actions: [
149 * { id: "always_use_https" },
150 * { id: "security_level", value: "high" },
151 * ],
152 * priority: 2,
153 * });
154 * ```
155 *
156 * ### Staged rollout
157 * **Example:** Create the rule disabled, flip to active later
158 * ```typescript
159 * yield* Cloudflare.PageRule.PageRule("BypassCacheBeta", {
160 * zoneId: zone.zoneId,
161 * target: `${zone.name}/beta/*`,
162 * actions: [{ id: "cache_level", value: "bypass" }],
163 * status: "disabled",
164 * });
165 * ```
166 *
167 * @see https://developers.cloudflare.com/rules/page-rules/
168 *
169 * @resource
170 * @product Page Rules
171 * @category Rules & Configuration
172 */
173 export const PageRule = Resource<PageRule>(TypeId, {
174 aliases: ["Cloudflare.PageRule"],
175 });
176
177 /**
178 * Returns true if the given value is a PageRule resource.
179 */
180 export const isPageRule = (value: unknown): value is PageRule =>
181 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
182
183 export const PageRuleProvider = () =>
184 Provider.succeed(PageRule, {
185 stables: ["pageRuleId", "zoneId", "createdOn"],
186
187 list: Effect.fn(function* () {
188 const { accountId } = yield* yield* CloudflareEnvironment;
189 // Page Rules live inside a zone (`/zones/{id}/pagerules`) with no
190 // account-wide enumeration API. Fan out over every zone and list
191 // its rules; `listPageRules` is non-paginated (returns the whole
192 // array in one response). Skip plan-gated zones with the typed
193 // `Forbidden` tag.
194 const zones = yield* listAllZones(accountId);
195 const rows = yield* Effect.forEach(
196 zones,
197 (zone) =>
198 pageRules.listPageRules({ zoneId: zone.id }).pipe(
199 Effect.map((rules) => rules.map((rule) => toAttributes(rule as ObservedRule, zone.id))),
200 // Skip plan-gated zones (`Forbidden`) and zones Cloudflare rejects
201 // with "Invalid zone identifier" (e.g. pending/partial-setup zones
202 // that don't accept the page-rules endpoint) — they contribute no
203 // rules and shouldn't fail the whole account enumeration.
204 Effect.catchTag(["Forbidden", "InvalidZoneIdentifier"], () => Effect.succeed([])),
205 ),
206 { concurrency: 10 },
207 );
208 return rows.flat();
209 }),
210
211 diff: Effect.fn(function* ({ olds = {}, news }) {
212 const o = olds as Props;
213 const n = news as Props;
214 // zoneId is Input<string>; compare only once both are concrete.
215 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
216 return { action: "replace" } as const;
217 }
218 // Everything else (target, actions, priority, status) is mutable
219 // via PUT — let the engine apply the default update logic.
220 return undefined;
221 }),
222
223 read: Effect.fn(function* ({ output, olds }) {
224 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
225 if (!zoneId) return undefined;
226
227 // Owned path: refresh by our persisted rule id.
228 if (output?.pageRuleId) {
229 const observed = yield* getRule(zoneId, output.pageRuleId);
230 if (observed) return toAttributes(observed, zoneId);
231 }
232
233 // Adoption path: a rule with this target may already exist on the
234 // zone. Page Rules carry no ownership markers, so we cannot prove
235 // we created it — brand it `Unowned` so the engine refuses to take
236 // over unless `adopt` is set.
237 const target = output?.target ?? olds?.target;
238 if (target) {
239 const observed = yield* findByTarget(zoneId, target);
240 if (observed) return Unowned(toAttributes(observed, zoneId));
241 }
242 return undefined;
243 }),
244
245 reconcile: Effect.fn(function* ({ news, output }) {
246 // Inputs have been resolved to concrete strings by Plan.
247 const zoneId = news.zoneId as string;
248 const desired = desiredBody(news);
249
250 // 1. Observe — the rule id cached on `output` is a hint, not a
251 // guarantee: a missing rule falls through to the target scan
252 // and then to create.
253 let observed = output?.pageRuleId ? yield* getRule(zoneId, output.pageRuleId) : undefined;
254
255 // 2. Fall back to scanning the zone for a rule with the same
256 // target. Ownership has already been verified upstream — `read`
257 // reports existing rules as `Unowned` and the engine gates
258 // takeover behind the adopt policy before reconcile ever runs.
259 if (!observed) {
260 observed = yield* findByTarget(zoneId, news.target);
261 }
262
263 // 3. Ensure — create when missing. Pass the desired status
264 // explicitly because the raw API defaults to "disabled".
265 if (!observed) {
266 observed = yield* pageRules.createPageRule({
267 zoneId,
268 ...desired,
269 });
270 }
271
272 // 4. Sync — diff observed against desired; the update endpoint is
273 // a PUT-style full replace, so resend the whole desired body
274 // when any mutable aspect differs. Skip the call on a no-op.
275 // A rule deleted between observe and update surfaces as the
276 // typed `PageRuleNotFound` — converge by re-creating.
277 if (!ruleMatchesDesired(observed, news)) {
278 observed = yield* pageRules
279 .updatePageRule({
280 zoneId,
281 pageruleId: observed.id,
282 ...desired,
283 })
284 .pipe(
285 Effect.catchTag("PageRuleNotFound", () =>
286 pageRules.createPageRule({ zoneId, ...desired }),
287 ),
288 );
289 }
290
291 // 5. Return the fresh attributes shape.
292 return toAttributes(observed, zoneId);
293 }),
294
295 delete: Effect.fn(function* ({ output }) {
296 yield* pageRules
297 .deletePageRule({
298 zoneId: output.zoneId,
299 pageruleId: output.pageRuleId,
300 })
301 .pipe(
302 // Already gone — deletion is idempotent.
303 Effect.catchTag("PageRuleNotFound", () => Effect.void),
304 );
305 }),
306 });
307
308 // ---------------------------------------------------------------------------
309 // API helpers
310 // ---------------------------------------------------------------------------
311
312 type ObservedRule = pageRules.GetPageRuleResponse;
313
314 /**
315 * Read a rule by id, mapping "gone" (typed `PageRuleNotFound`, HTTP 404)
316 * to `undefined`.
317 */
318 const getRule = (zoneId: string, pageruleId: string) =>
319 pageRules.getPageRule({ zoneId, pageruleId }).pipe(
320 Effect.map((rule): ObservedRule | undefined => rule),
321 Effect.catchTag("PageRuleNotFound", () => Effect.undefined),
322 );
323
324 /**
325 * Find a rule on the zone whose URL-pattern target matches. The target is
326 * the rule's only recoverable identity — Cloudflare rejects a second rule
327 * with the same target, so at most one rule can match.
328 */
329 const findByTarget = (zoneId: string, target: string) =>
330 pageRules
331 .listPageRules({ zoneId })
332 .pipe(
333 Effect.map(
334 (rules) => rules.find((rule) => targetOf(rule) === target) as ObservedRule | undefined,
335 ),
336 );
337
338 /** The desired request body (everything except path params). */
339 const desiredBody = (news: Props) => ({
340 targets: [
341 {
342 target: "url" as const,
343 constraint: { operator: "matches" as const, value: news.target },
344 },
345 ],
346 actions: Array.from(news.actions),
347 priority: news.priority ?? 1,
348 status: news.status ?? ("active" as const),
349 });
350
351 /** Extract the URL pattern from a rule's targets. */
352 const targetOf = (rule: {
353 targets: ReadonlyArray<{
354 constraint?: { value: string } | null;
355 }>;
356 }): string | undefined => rule.targets[0]?.constraint?.value;
357
358 /**
359 * Deep-canonicalise a JSON-ish value for comparison: drop `null` /
360 * `undefined` members and sort object keys. Action arrays are compared
361 * order-insensitively (sorted by action id) because Cloudflare reorders
362 * them on echo.
363 */
364 const canonical = (v: unknown): unknown => {
365 if (Array.isArray(v)) return v.map(canonical);
366 if (v !== null && typeof v === "object") {
367 return Object.fromEntries(
368 Object.entries(v as Record<string, unknown>)
369 .filter(([, val]) => val !== undefined && val !== null)
370 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
371 .map(([k, val]) => [k, canonical(val)]),
372 );
373 }
374 return v;
375 };
376
377 const canonicalActions = (actions: ReadonlyArray<Action>): string =>
378 JSON.stringify(
379 actions
380 .map((a) => canonical(a) as { id?: string })
381 .sort((a, b) => ((a.id ?? "") < (b.id ?? "") ? -1 : (a.id ?? "") > (b.id ?? "") ? 1 : 0)),
382 );
383
384 /** True when the observed rule already matches every desired aspect. */
385 const ruleMatchesDesired = (observed: ObservedRule, news: Props): boolean =>
386 targetOf(observed) === news.target &&
387 observed.priority === (news.priority ?? 1) &&
388 observed.status === (news.status ?? "active") &&
389 canonicalActions(observed.actions as ReadonlyArray<Action>) === canonicalActions(news.actions);
390
391 const toAttributes = (rule: ObservedRule, zoneId: string): Attributes => ({
392 pageRuleId: rule.id,
393 zoneId,
394 target: targetOf(rule) ?? "",
395 actions: rule.actions as ReadonlyArray<Action>,
396 priority: rule.priority,
397 status: rule.status as Status,
398 createdOn: rule.createdOn,
399 modifiedOn: rule.modifiedOn,
400 });