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

main
ts 297 lines 10.7 KB
Raw
1 import * as resourceSharing from "@distilled.cloud/cloudflare/resource-sharing";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.ResourceSharing.ShareRecipient" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Association status of a share recipient. Association is eventually
17 * consistent — a new recipient transitions `associating → associated`.
18 */
19 export type ShareRecipientAssociationStatus =
20 | "associating"
21 | "associated"
22 | "disassociating"
23 | "disassociated";
24
25 export type ShareRecipientProps = {
26 /**
27 * The share the recipient is added to. Changing the share triggers a
28 * replacement.
29 */
30 shareId: string;
31 /**
32 * Recipient account identifier. Exactly one of `accountId` /
33 * `organizationId` must be set. Changing it triggers a replacement.
34 */
35 accountId?: string;
36 /**
37 * Recipient organization identifier. Exactly one of `accountId` /
38 * `organizationId` must be set. Changing it triggers a replacement.
39 */
40 organizationId?: string;
41 };
42
43 export type ShareRecipientAttributes = {
44 /**
45 * Share recipient identifier tag. Stable for the life of the recipient.
46 */
47 recipientId: string;
48 /**
49 * The Cloudflare account that owns (sends) the share.
50 */
51 accountId: string;
52 /**
53 * The share the recipient belongs to.
54 */
55 shareId: string;
56 /**
57 * The recipient account identifier reported by Cloudflare.
58 */
59 recipientAccountId: string;
60 /**
61 * Association status of the recipient. Eventually consistent —
62 * `associating` settles to `associated`.
63 */
64 associationStatus: ShareRecipientAssociationStatus;
65 /**
66 * When the recipient was created.
67 */
68 created: string;
69 /**
70 * When the recipient was last modified.
71 */
72 modified: string;
73 };
74
75 export type ShareRecipient = Resource<
76 TypeId,
77 ShareRecipientProps,
78 ShareRecipientAttributes,
79 never,
80 Providers
81 >;
82
83 /**
84 * A recipient on an existing Cloudflare share — grants another account or
85 * organization access to the share's resources.
86 *
87 * This is an existence-only resource: there is no update API, so every prop
88 * change triggers a replacement. Association is eventually consistent
89 * (`associating → associated`). Do not manage the same recipient both inline
90 * on `Share.recipients` and through this resource.
91 * ### Adding a Recipient
92 * **Example:** Share with another account
93 * ```typescript
94 * const recipient = yield* Cloudflare.ResourceSharing.ShareRecipient("Partner", {
95 * shareId: share.shareId,
96 * accountId: "<recipient-account-id>",
97 * });
98 * ```
99 *
100 * **Example:** Share with an organization
101 * ```typescript
102 * const recipient = yield* Cloudflare.ResourceSharing.ShareRecipient("Org", {
103 * shareId: share.shareId,
104 * organizationId: "<recipient-organization-id>",
105 * });
106 * ```
107 *
108 * @see https://developers.cloudflare.com/fundamentals/manage-account-resources/
109 *
110 * @resource
111 * @product Resource Sharing
112 * @category Account & Identity
113 */
114 export const ShareRecipient = Resource<ShareRecipient>(TypeId);
115
116 /**
117 * Returns true if the given value is a ShareRecipient resource.
118 */
119 export const isShareRecipient = (value: unknown): value is ShareRecipient =>
120 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
121
122 export const ShareRecipientProvider = () =>
123 Provider.succeed(ShareRecipient, {
124 stables: ["recipientId", "accountId", "shareId", "recipientAccountId", "created"],
125 diff: Effect.fn(function* ({ olds, news, output }) {
126 if (!isResolved(news)) return undefined;
127 const { accountId } = yield* yield* CloudflareEnvironment;
128 if ((output?.accountId ?? accountId) !== accountId) {
129 return { action: "replace" } as const;
130 }
131 // No update API — every identity change is a replacement. By diff
132 // time both sides are resolved strings.
133 const oldShareId = output?.shareId ?? olds?.shareId;
134 if (
135 typeof oldShareId === "string" &&
136 typeof news.shareId === "string" &&
137 oldShareId !== news.shareId
138 ) {
139 return { action: "replace" } as const;
140 }
141 const oldTarget =
142 output?.recipientAccountId ??
143 (olds?.accountId as string | undefined) ??
144 (olds?.organizationId as string | undefined);
145 const newTarget =
146 (news.accountId as string | undefined) ?? (news.organizationId as string | undefined);
147 if (
148 typeof oldTarget === "string" &&
149 typeof newTarget === "string" &&
150 oldTarget !== newTarget
151 ) {
152 return { action: "replace" } as const;
153 }
154 return undefined;
155 }),
156 read: Effect.fn(function* ({ olds, output }) {
157 const { accountId } = yield* yield* CloudflareEnvironment;
158 const acct = output?.accountId ?? accountId;
159 const shareId = output?.shareId ?? (olds?.shareId as string | undefined);
160 if (shareId === undefined) return undefined;
161
162 if (output?.recipientId) {
163 const observed = yield* getRecipient(acct, shareId, output.recipientId);
164 return observed ? toAttributes(observed, acct, shareId) : undefined;
165 }
166 // Cold read — recover from lost state by matching the recipient
167 // account/organization id among the share's recipients.
168 const target =
169 (olds?.accountId as string | undefined) ?? (olds?.organizationId as string | undefined);
170 if (target === undefined) return undefined;
171 const match = yield* findRecipient(acct, shareId, target);
172 return match ? toAttributes(match, acct, shareId) : undefined;
173 }),
174 reconcile: Effect.fn(function* ({ news, output }) {
175 const { accountId } = yield* yield* CloudflareEnvironment;
176 const acct = output?.accountId ?? accountId;
177 const shareId = news.shareId as string;
178 const targetAccountId = news.accountId as string | undefined;
179 const targetOrganizationId = news.organizationId as string | undefined;
180
181 // Observe — the recipientId cached on `output` is a hint; fall
182 // through to a natural-key lookup so an AlreadyExists race converges
183 // instead of failing, then to create. Existence-only resource: there
184 // is no sync step.
185 const observed =
186 (output?.recipientId
187 ? yield* getRecipient(acct, shareId, output.recipientId)
188 : undefined) ??
189 (yield* findRecipient(acct, shareId, targetAccountId ?? targetOrganizationId ?? ""));
190
191 if (observed) {
192 return toAttributes(observed, acct, shareId);
193 }
194
195 // Ensure — greenfield (or out-of-band delete).
196 const created = yield* resourceSharing.createRecipient({
197 accountId: acct,
198 shareId,
199 recipientAccountId: targetAccountId,
200 organizationId: targetOrganizationId,
201 });
202 return toAttributes(created, acct, shareId);
203 }),
204 delete: Effect.fn(function* ({ output }) {
205 // Disassociation is eventually consistent; the DELETE call is
206 // idempotent against a missing recipient.
207 yield* resourceSharing
208 .deleteRecipient({
209 accountId: output.accountId,
210 shareId: output.shareId,
211 recipientId: output.recipientId,
212 })
213 .pipe(Effect.catchTag("ShareRecipientNotFound", () => Effect.void));
214 }),
215 list: Effect.fn(function* () {
216 const { accountId } = yield* yield* CloudflareEnvironment;
217 // Parent fan-out: recipients are keyed by their parent Share, which is
218 // account-scoped. Enumerate the account's owned (sent) shares, then list
219 // recipients within each share with bounded concurrency.
220 const shareIds = yield* resourceSharing.listResourceSharings
221 .pages({ accountId, kind: "sent" })
222 .pipe(
223 Stream.runCollect,
224 Effect.map((chunk) =>
225 Array.from(chunk).flatMap((page) => (page.result ?? []).map((share) => share.id)),
226 ),
227 // The account cannot enumerate shares — nothing to list.
228 Effect.catchTag("Forbidden", () => Effect.succeed([] as string[])),
229 );
230
231 const rows = yield* Effect.forEach(
232 shareIds,
233 (shareId) =>
234 resourceSharing.listRecipients.pages({ accountId, shareId }).pipe(
235 Stream.runCollect,
236 Effect.map((chunk) =>
237 Array.from(chunk).flatMap((page) =>
238 (page.result ?? [])
239 // Disassociated recipients are "gone" — match `read`.
240 .filter((r) => r.associationStatus !== "disassociated")
241 .map((r) => toAttributes(r, accountId, shareId)),
242 ),
243 ),
244 // The share vanished mid-enumeration or isn't ours — skip it.
245 Effect.catchTag(["ShareNotFound", "Forbidden"], () =>
246 Effect.succeed([] as ShareRecipientAttributes[]),
247 ),
248 ),
249 { concurrency: 10 },
250 );
251 return rows.flat();
252 }),
253 });
254
255 type ObservedRecipient = resourceSharing.GetRecipientResponse;
256
257 /**
258 * Read a recipient by id, mapping "gone" (`ShareRecipientNotFound`, HTTP
259 * 404) and the terminal `disassociated` status to `undefined`.
260 */
261 const getRecipient = (accountId: string, shareId: string, recipientId: string) =>
262 resourceSharing.getRecipient({ accountId, shareId, recipientId }).pipe(
263 Effect.map((recipient): ObservedRecipient | undefined =>
264 recipient.associationStatus === "disassociated" ? undefined : recipient,
265 ),
266 Effect.catchTag("ShareRecipientNotFound", () => Effect.undefined),
267 );
268
269 /**
270 * Find a live recipient by its account/organization id. A missing share
271 * surfaces as `ShareNotFound` — treat it as "no recipient".
272 */
273 const findRecipient = (accountId: string, shareId: string, target: string) =>
274 resourceSharing.listRecipients.items({ accountId, shareId, perPage: 50 }).pipe(
275 Stream.filter((r) => r.accountId === target && r.associationStatus !== "disassociated"),
276 Stream.runHead,
277 Effect.map(Option.getOrUndefined),
278 Effect.catchTag("ShareNotFound", () => Effect.undefined),
279 );
280
281 const toAttributes = (
282 recipient:
283 | ObservedRecipient
284 | resourceSharing.CreateRecipientResponse
285 | resourceSharing.ListRecipientsResponse["result"][number],
286 accountId: string,
287 shareId: string,
288 ): ShareRecipientAttributes => ({
289 recipientId: recipient.id,
290 accountId,
291 shareId,
292 recipientAccountId: recipient.accountId,
293 // Distilled widens generated string enums to open unions (`string & {}`).
294 associationStatus: recipient.associationStatus as ShareRecipientAssociationStatus,
295 created: recipient.created,
296 modified: recipient.modified,
297 });