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

main
ts 654 lines 20.3 KB
Raw
1 import * as LocalFlagship from "@alchemy.run/cloudflare-runtime/core/bindings/flagship";
2 import * as flagship from "@distilled.cloud/cloudflare/flagship";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import * as Data from "effect/Data";
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 { localAccountId } from "../LocalAccount.ts";
14 import { isLocalId, localStorageDirectory } from "../LocalRuntime.ts";
15 import type { Providers } from "../Providers.ts";
16
17 const TypeId = "Cloudflare.Flagship.Flag" as const;
18 type TypeId = typeof TypeId;
19
20 /**
21 * Comparison operator applied to a targeting condition.
22 */
23 export type FlagConditionOperator =
24 | "equals"
25 | "not_equals"
26 | "greater_than"
27 | "less_than"
28 | "greater_than_or_equals"
29 | "less_than_or_equals"
30 | "contains"
31 | "starts_with"
32 | "ends_with"
33 | "in"
34 | "not_in"
35 | "has"
36 | "not_has";
37
38 /**
39 * A single targeting condition: either a flat attribute comparison or a
40 * nested group of clauses combined with AND/OR.
41 */
42 /**
43 * Value a flat condition compares against — a scalar, a JSON object, or a
44 * list (for `in` / `not_in`).
45 */
46 export type FlagConditionValue = string | number | boolean | { [key: string]: unknown } | unknown[];
47
48 export type FlagCondition =
49 | {
50 /**
51 * Evaluation-context attribute to match on (e.g. `country`, `userId`).
52 */
53 attribute: string;
54 /**
55 * Comparison operator.
56 */
57 operator: FlagConditionOperator;
58 /**
59 * Value to compare against.
60 */
61 value: FlagConditionValue;
62 }
63 | {
64 /**
65 * Nested conditions combined with `logicalOperator`.
66 */
67 clauses: FlagCondition[];
68 /**
69 * How the clauses combine.
70 */
71 logicalOperator: "AND" | "OR";
72 };
73
74 /**
75 * Percentage rollout applied after a rule's conditions match.
76 */
77 export type FlagRollout = {
78 /**
79 * Percentage of matching contexts served the rule's variation (0-100).
80 */
81 percentage: number;
82 /**
83 * Context attribute used for rollout bucketing.
84 * @default the context's targeting key
85 */
86 attribute?: string;
87 };
88
89 /**
90 * A targeting rule. Rules are evaluated in ascending `priority`; the first
91 * matching rule wins.
92 */
93 export type FlagRule = {
94 /**
95 * Conditions that must all match for the rule to apply.
96 */
97 conditions: FlagCondition[];
98 /**
99 * Evaluation order — lower runs first.
100 */
101 priority: number;
102 /**
103 * Variation (key in `variations`) served when the rule matches.
104 */
105 serveVariation: string;
106 /**
107 * Optional percentage rollout applied after the conditions match.
108 */
109 rollout?: FlagRollout;
110 };
111
112 /**
113 * Value type of a flag's variations.
114 */
115 export type FlagType = "boolean" | "string" | "number" | "json";
116
117 export type FlagProps = {
118 /**
119 * The Flagship app the flag belongs to. Changing the app triggers a
120 * replacement.
121 */
122 appId: string;
123 /**
124 * Unique flag key within the app — used in all evaluation and SDK calls.
125 * Changing the key triggers a replacement. If omitted, a unique key is
126 * generated from the app, stage, and logical ID.
127 * @default ${app}-${stage}-${id}
128 */
129 key?: string;
130 /**
131 * When false, the flag bypasses all rules and always serves
132 * `defaultVariation`.
133 * @default true
134 */
135 enabled?: boolean;
136 /**
137 * Variation served when no rule matches or the flag is disabled. Must be a
138 * key in `variations`.
139 */
140 defaultVariation: string;
141 /**
142 * Map of variation name to value. All values must be the same type
143 * (boolean, string, number, or JSON object/array). Each serialized value
144 * must be 10KB or smaller.
145 */
146 variations: Record<string, unknown>;
147 /**
148 * Targeting rules evaluated in ascending `priority`; the first matching
149 * rule wins. An empty array means the flag always serves
150 * `defaultVariation`.
151 * @default []
152 */
153 rules?: FlagRule[];
154 /**
155 * Human readable description of the flag.
156 */
157 description?: string;
158 /**
159 * Value type of the flag's variations. Inferred from the variation values
160 * on write, so it can usually be omitted.
161 */
162 type?: FlagType;
163 };
164
165 export type FlagAttributes = {
166 /**
167 * The Flagship app the flag belongs to.
168 */
169 appId: string;
170 /**
171 * The Cloudflare account the flag belongs to.
172 */
173 accountId: string;
174 /**
175 * Unique flag key within the app.
176 */
177 key: string;
178 /**
179 * Whether the flag's rules are evaluated.
180 */
181 enabled: boolean;
182 /**
183 * Variation served when no rule matches or the flag is disabled.
184 */
185 defaultVariation: string;
186 /**
187 * Map of variation name to value.
188 */
189 variations: Record<string, unknown>;
190 /**
191 * Targeting rules.
192 */
193 rules: FlagRule[];
194 /**
195 * Human readable description of the flag.
196 */
197 description: string | undefined;
198 /**
199 * Value type of the flag's variations, as inferred by Cloudflare.
200 */
201 type: FlagType | undefined;
202 /**
203 * When the flag was last modified.
204 */
205 updatedAt: string | undefined;
206 /**
207 * Email of the actor who last modified the flag, or `edge-gateway` for
208 * gateway-authenticated changes.
209 */
210 updatedBy: string | undefined;
211 };
212
213 export type Flag = Resource<TypeId, FlagProps, FlagAttributes, never, Providers>;
214
215 /**
216 * A feature flag in a Cloudflare Flagship app.
217 *
218 * A flag maps a key to a set of variations plus targeting rules. Workers
219 * evaluate flags through the `Flagship` binding (or the REST evaluate
220 * endpoint); changing variations, rules, enablement, or the default
221 * variation takes effect without redeploying code. Everything except the
222 * flag key and the parent app is mutable in place.
223 * ### Creating a Flag
224 * **Example:** Boolean flag
225 * ```typescript
226 * const app = yield* Cloudflare.Flagship.App("Flags", {});
227 *
228 * const flag = yield* Cloudflare.Flagship.Flag("NewCheckout", {
229 * appId: app.appId,
230 * key: "new-checkout",
231 * defaultVariation: "off",
232 * variations: { off: false, on: true },
233 * });
234 * ```
235 *
236 * **Example:** String flag with multiple variations
237 * ```typescript
238 * const flag = yield* Cloudflare.Flagship.Flag("CheckoutFlow", {
239 * appId: app.appId,
240 * key: "checkout-flow",
241 * defaultVariation: "v1",
242 * variations: { v1: "classic", v2: "express", v3: "one-click" },
243 * });
244 * ```
245 *
246 * ### Targeting Rules
247 * **Example:** Serve a variation to a specific country
248 * ```typescript
249 * const flag = yield* Cloudflare.Flagship.Flag("DarkMode", {
250 * appId: app.appId,
251 * key: "dark-mode",
252 * defaultVariation: "off",
253 * variations: { off: false, on: true },
254 * rules: [
255 * {
256 * priority: 1,
257 * conditions: [
258 * { attribute: "country", operator: "equals", value: "US" },
259 * ],
260 * serveVariation: "on",
261 * },
262 * ],
263 * });
264 * ```
265 *
266 * **Example:** Percentage rollout
267 * ```typescript
268 * const flag = yield* Cloudflare.Flagship.Flag("NewSearch", {
269 * appId: app.appId,
270 * key: "new-search",
271 * defaultVariation: "off",
272 * variations: { off: false, on: true },
273 * rules: [
274 * {
275 * priority: 1,
276 * conditions: [],
277 * serveVariation: "on",
278 * rollout: { percentage: 25 },
279 * },
280 * ],
281 * });
282 * ```
283 *
284 * ### Toggling a Flag
285 * **Example:** Disable a flag without removing its rules
286 * ```typescript
287 * const flag = yield* Cloudflare.Flagship.Flag("NewCheckout", {
288 * appId: app.appId,
289 * key: "new-checkout",
290 * enabled: false,
291 * defaultVariation: "off",
292 * variations: { off: false, on: true },
293 * });
294 * ```
295 *
296 * @see https://developers.cloudflare.com/flagship/
297 * @see https://developers.cloudflare.com/api/resources/flagship/
298 *
299 * @resource
300 * @product Flagship
301 * @category Developer Platform
302 */
303 export const Flag = Resource<Flag>(TypeId);
304
305 /**
306 * Returns true if the given value is a Flagship Flag resource.
307 */
308 export const isFlag = (value: unknown): value is Flag =>
309 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
310
311 export const FlagProviderLive = () =>
312 Provider.succeed(Flag, {
313 stables: ["appId", "accountId", "key"],
314 diff: Effect.fn(function* ({ olds, news, output }) {
315 if (!isResolved(news)) return undefined;
316 const { accountId } = yield* yield* CloudflareEnvironment;
317 if ((output?.accountId ?? accountId) !== accountId) {
318 return { action: "replace" } as const;
319 }
320 // The app is a path parameter — a flag cannot move between apps in
321 // place. By diff time both sides are resolved strings.
322 const oldAppId = output?.appId ?? olds?.appId;
323 if (
324 typeof oldAppId === "string" &&
325 typeof news.appId === "string" &&
326 oldAppId !== news.appId
327 ) {
328 return { action: "replace" } as const;
329 }
330 // The key is the flag's identity within the app.
331 const oldKey = output?.key ?? olds?.key;
332 if (typeof oldKey === "string" && typeof news.key === "string" && oldKey !== news.key) {
333 return { action: "replace" } as const;
334 }
335 return undefined;
336 }),
337 read: Effect.fn(function* ({ id, olds, output }) {
338 const { accountId } = yield* yield* CloudflareEnvironment;
339 const acct = output?.accountId ?? accountId;
340 const appId = output?.appId ?? (olds?.appId as string | undefined);
341 if (appId === undefined) return undefined;
342
343 // The key is deterministic (explicit or generated from the logical
344 // ID), so a cold read and a warm read are the same lookup.
345 const key = output?.key ?? (yield* createFlagKey(id, olds?.key));
346 const observed = yield* getFlag(acct, appId, key);
347 return observed ? toAttributes(observed, acct, appId) : undefined;
348 }),
349 reconcile: Effect.fn(function* ({ id, news, output }) {
350 const { accountId } = yield* yield* CloudflareEnvironment;
351 const appId = news.appId as string;
352 const key = yield* createFlagKey(id, news.key);
353 const desired = {
354 enabled: news.enabled ?? true,
355 defaultVariation: news.defaultVariation,
356 variations: news.variations,
357 rules: news.rules ?? [],
358 description: news.description,
359 };
360
361 // Observe — flag identity is (appId, key); a missing flag falls
362 // through and we recreate.
363 const observed = yield* getFlag(output?.accountId ?? accountId, appId, key);
364
365 if (!observed) {
366 // Ensure — greenfield (or out-of-band delete). A concurrent create
367 // of the same key surfaces as FlagshipFlagAlreadyExists; treat it
368 // as a race and converge via the update path below.
369 const created = yield* flagship
370 .createAppFlag({
371 accountId,
372 appId,
373 key,
374 ...desired,
375 type: news.type,
376 })
377 .pipe(Effect.catchTag("FlagshipFlagAlreadyExists", () => Effect.undefined));
378 if (created) {
379 return toAttributes(created, accountId, appId);
380 }
381 }
382
383 // Sync — diff observed cloud state against desired; the update API is
384 // a PUT that takes the full body, so send everything, but skip the
385 // call entirely on a no-op.
386 const live = observed ?? (yield* getFlag(accountId, appId, key));
387 if (live) {
388 const observedShape = {
389 enabled: live.enabled,
390 defaultVariation: live.defaultVariation,
391 variations: live.variations,
392 rules: normalizeRules(live.rules),
393 description: live.description ?? undefined,
394 };
395 const desiredShape = {
396 ...desired,
397 rules: normalizeRules(desired.rules),
398 };
399 if (deepEqual(observedShape, desiredShape)) {
400 return toAttributes(live, accountId, appId);
401 }
402 }
403 const updated = yield* flagship.updateAppFlag({
404 accountId,
405 appId,
406 flagKey: key,
407 key,
408 ...desired,
409 type: news.type,
410 });
411 return toAttributes(updated, accountId, appId);
412 }),
413 delete: Effect.fn(function* ({ output }) {
414 yield* flagship
415 .deleteAppFlag({
416 accountId: output.accountId,
417 appId: output.appId,
418 flagKey: output.key,
419 })
420 // A missing flag or a missing parent app both mean it's already
421 // gone.
422 .pipe(Effect.catchTag(["FlagshipFlagNotFound", "FlagshipAppNotFound"], () => Effect.void));
423 }),
424 // Flags are sub-resources keyed by (accountId, appId, key). There is no
425 // account-wide flag enumeration, so enumerate every Flagship app first,
426 // then fan out the per-app flag list and flatten.
427 list: Effect.fn(function* () {
428 const { accountId } = yield* yield* CloudflareEnvironment;
429 const apps = yield* flagship.listApps.pages({ accountId }).pipe(
430 Stream.runCollect,
431 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.result ?? [])),
432 );
433 const rows = yield* Effect.forEach(
434 apps,
435 (app) =>
436 flagship.listAppFlags.pages({ accountId, appId: app.id }).pipe(
437 Stream.runCollect,
438 Effect.map((chunk) =>
439 Array.from(chunk).flatMap((page) =>
440 (page.result ?? []).map((flag) => toAttributes(flag, accountId, app.id)),
441 ),
442 ),
443 // The parent app can be deleted between enumeration and the
444 // per-app flag list; treat a gone app as having no flags.
445 Effect.catchTag("FlagshipAppNotFound", () => Effect.succeed<FlagAttributes[]>([])),
446 ),
447 { concurrency: 10 },
448 );
449 return rows.flat();
450 }),
451 });
452
453 /**
454 * Local (dev) provider — writes the flag's definition into the local
455 * Flagship simulator's store under its (`dev:`) app, where a dev Worker's
456 * `flagship` binding evaluates it. Definitions are plain files under
457 * `.alchemy/local/flagship`, read fresh on every evaluation, so an update
458 * applies to running Workers without a restart.
459 *
460 * The flag's app must be local too: a dev Worker bound to a live app
461 * (`Alchemy.remote()`) evaluates the cloud's flags, so a local definition
462 * would never be read. Opt the flag out of emulation alongside its app.
463 */
464 export const FlagProviderLocal = () =>
465 Provider.succeed(Flag, {
466 stables: ["appId", "accountId", "key"],
467 diff: Effect.fn(function* ({ id, news, output }) {
468 if (!output) return { action: "update" } as const;
469 if (!isResolved(news)) return undefined;
470 // Mirror the live provider: a new app or key replaces the flag.
471 if (
472 output.appId !== news.appId ||
473 output.key !== (yield* createFlagKey(id, news.key)) ||
474 output.accountId !== (yield* localAccountId)
475 ) {
476 return { action: "replace" } as const;
477 }
478 // Fall through to the engine's default prop diff (variations, rules,
479 // enablement and description update in place).
480 }),
481 read: Effect.fn(function* ({ output }) {
482 // Virtual identity — the persisted state row is the source of truth
483 // (the written definition converges on every reconcile).
484 return output ?? undefined;
485 }),
486 reconcile: Effect.fn(function* ({ id, news }) {
487 const appId = news.appId as string;
488 const key = yield* createFlagKey(id, news.key);
489 if (!isLocalId(appId)) {
490 return yield* new LocalFlagError({
491 message:
492 `Flag "${key}" is emulated locally but its app ${JSON.stringify(appId)} is live. ` +
493 "A dev Worker bound to a live app evaluates the cloud's flags, so " +
494 "apply Alchemy.remote() to the flag as well as its app.",
495 });
496 }
497 const definition = {
498 enabled: news.enabled ?? true,
499 defaultVariation: news.defaultVariation,
500 variations: news.variations,
501 rules: news.rules ?? [],
502 };
503 // An atomic overwrite — idempotent, so re-running after a crash
504 // converges.
505 yield* LocalFlagship.writeFlag(yield* localFlagshipStore(appId), key, definition);
506 return {
507 appId,
508 accountId: yield* localAccountId,
509 key,
510 ...definition,
511 description: news.description,
512 type: news.type ?? inferFlagType(news.variations),
513 updatedAt: yield* Effect.sync(() => new Date().toISOString()),
514 updatedBy: "local",
515 };
516 }),
517 delete: Effect.fn(function* ({ output }) {
518 if (!isLocalId(output.appId)) return;
519 // Deleting a missing definition is a no-op. A replacement's new
520 // generation has a different app or key, so this never removes its
521 // successor's definition.
522 yield* LocalFlagship.deleteFlag(yield* localFlagshipStore(output.appId), output.key);
523 }),
524 });
525
526 export const FlagProvider = () =>
527 ProviderLayer.dual(Flag, {
528 local: () => FlagProviderLocal(),
529 live: () => FlagProviderLive(),
530 });
531
532 export class LocalFlagError extends Data.TaggedError("LocalFlagError")<{
533 message: string;
534 }> {}
535
536 /**
537 * The local Flagship simulator's store for an app — the same storage
538 * directory the local workerd runtime serves.
539 */
540 export const localFlagshipStore = (appId: string) =>
541 Effect.map(localStorageDirectory, (storageDirectory) => ({ storageDirectory, appId }));
542
543 /**
544 * Infer a flag's value type from its variations, as Cloudflare does on
545 * write.
546 */
547 const inferFlagType = (variations: Record<string, unknown>): FlagType | undefined => {
548 const first = Object.values(variations)[0];
549 switch (typeof first) {
550 case "boolean":
551 return "boolean";
552 case "string":
553 return "string";
554 case "number":
555 return "number";
556 case "object":
557 return first === null ? undefined : "json";
558 default:
559 return undefined;
560 }
561 };
562
563 /**
564 * Read a flag by key, mapping "gone" (`FlagshipFlagNotFound`, or a deleted
565 * parent app surfacing as `FlagshipAppNotFound`) to `undefined`.
566 */
567 const getFlag = (accountId: string, appId: string, flagKey: string) =>
568 flagship
569 .getAppFlag({ accountId, appId, flagKey })
570 .pipe(Effect.catchTag(["FlagshipFlagNotFound", "FlagshipAppNotFound"], () => Effect.undefined));
571
572 const createFlagKey = (id: string, key: string | undefined) =>
573 Effect.gen(function* () {
574 return key ?? (yield* createPhysicalName({ id, lowercase: true }));
575 });
576
577 /**
578 * Wire rules carry readonly markers, open-union widening, and explicit
579 * nulls; strip them so rules diff structurally against the user's props.
580 */
581 const normalizeRules = (rules: readonly WireRule[] | FlagRule[]): FlagRule[] =>
582 rules.map((rule) => ({
583 conditions: normalizeConditions(rule.conditions),
584 priority: rule.priority,
585 serveVariation: rule.serveVariation,
586 ...(rule.rollout
587 ? {
588 rollout: {
589 percentage: rule.rollout.percentage,
590 ...(rule.rollout.attribute != null ? { attribute: rule.rollout.attribute } : {}),
591 },
592 }
593 : {}),
594 }));
595
596 type WireRule = {
597 conditions: readonly unknown[];
598 priority: number;
599 serveVariation: string;
600 rollout?: { percentage: number; attribute?: string | null } | null;
601 };
602
603 const normalizeConditions = (conditions: readonly unknown[]): FlagCondition[] =>
604 conditions.flatMap((condition): FlagCondition[] => {
605 if (Predicate.hasProperty(condition, "clauses")) {
606 const group = condition as {
607 clauses: readonly unknown[];
608 logicalOperator: string;
609 };
610 return [
611 {
612 clauses: normalizeConditions(group.clauses),
613 logicalOperator: group.logicalOperator as "AND" | "OR",
614 },
615 ];
616 }
617 if (Predicate.hasProperty(condition, "attribute")) {
618 const flat = condition as {
619 attribute: string;
620 operator: string;
621 value: FlagConditionValue;
622 };
623 return [
624 {
625 attribute: flat.attribute,
626 operator: flat.operator as FlagConditionOperator,
627 value: flat.value,
628 },
629 ];
630 }
631 return [];
632 });
633
634 const toAttributes = (
635 flag:
636 | flagship.GetAppFlagResponse
637 | flagship.CreateAppFlagResponse
638 | flagship.UpdateAppFlagResponse
639 | flagship.ListAppFlagsResponse["result"][number],
640 accountId: string,
641 appId: string,
642 ): FlagAttributes => ({
643 appId,
644 accountId,
645 key: flag.key,
646 enabled: flag.enabled,
647 defaultVariation: flag.defaultVariation,
648 variations: flag.variations,
649 rules: normalizeRules(flag.rules),
650 description: flag.description ?? undefined,
651 type: (flag.type as FlagType | null | undefined) ?? undefined,
652 updatedAt: flag.updatedAt ?? undefined,
653 updatedBy: flag.updatedBy ?? undefined,
654 });