@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 363 lines 12.7 KB
Raw
1 import * as organizations from "@distilled.cloud/cloudflare/organizations";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Organization.Organization" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Business profile attached to an organization. All fields are required
17 * when a profile is present — the API stores the profile as a unit.
18 */
19 export interface Profile {
20 /**
21 * Street address of the business that owns the organization.
22 */
23 businessAddress: string;
24 /**
25 * Contact email of the business.
26 */
27 businessEmail: string;
28 /**
29 * Legal name of the business.
30 */
31 businessName: string;
32 /**
33 * Contact phone number of the business.
34 */
35 businessPhone: string;
36 /**
37 * Free-form external metadata (e.g. a CRM or billing reference).
38 */
39 externalMetadata: string;
40 }
41
42 /**
43 * Feature flags Cloudflare sets on an organization. Read-only —
44 * controlled by the organization's entitlements.
45 */
46 export interface Flags {
47 /**
48 * Whether accounts may be created under this organization.
49 */
50 accountCreation: string;
51 /**
52 * Whether accounts may be deleted under this organization.
53 */
54 accountDeletion: string;
55 /**
56 * Whether accounts may be migrated into this organization.
57 */
58 accountMigration: string;
59 /**
60 * Whether accounts may be moved between organizations.
61 */
62 accountMobility: string;
63 /**
64 * Whether sub-organizations may be created under this organization.
65 */
66 subOrgCreation: string;
67 }
68
69 export interface Props {
70 /**
71 * Display name of the organization. Mutable in place. If omitted, a
72 * unique name is generated from the app, stage, and logical ID.
73 * @default ${app}-${stage}-${id}
74 */
75 name?: string;
76 /**
77 * ID of the parent organization, for building an organization
78 * hierarchy. Changing the parent triggers a replacement — re-parenting
79 * is gated by the organization's `accountMobility`/flags and is not
80 * supported in place.
81 */
82 parent?: string;
83 /**
84 * Business profile of the organization. Mutable in place.
85 */
86 profile?: Profile;
87 }
88
89 export interface Attributes {
90 /**
91 * Cloudflare-assigned identifier of the organization.
92 */
93 organizationId: string;
94 /**
95 * Display name of the organization.
96 */
97 name: string;
98 /**
99 * ISO8601 timestamp of when the organization was created.
100 */
101 createTime: string;
102 /**
103 * Who manages this organization, if it is managed by a parent entity.
104 */
105 managedBy: string | undefined;
106 /**
107 * Feature flags controlled by the organization's entitlements.
108 */
109 flags: Flags | undefined;
110 /**
111 * Parent organization, if this organization is part of a hierarchy.
112 */
113 parent: { id: string; name: string } | undefined;
114 /**
115 * Business profile of the organization, if one is set.
116 */
117 profile: Profile | undefined;
118 }
119
120 export type Organization = Resource<TypeId, Props, Attributes, never, Providers>;
121
122 /**
123 * A Cloudflare Organization — the hierarchical container above accounts.
124 *
125 * Organizations group accounts (and sub-organizations) under a single
126 * management umbrella; an account's `managedBy.parentOrgId` points at its
127 * owning organization. The feature is entitlement-gated: only tenant /
128 * organizations-enabled customers can create organizations — on a standard
129 * account every `/organizations` call fails with the typed `Forbidden`
130 * error.
131 *
132 * `name` and `profile` are mutable in place; changing `parent` triggers a
133 * replacement.
134 *
135 * Safety: organizations carry no ownership markers. When there is no prior
136 * state, `read` scans for an existing organization with the same name
137 * (and parent) and reports it as `Unowned`, so the engine refuses to take
138 * it over unless `--adopt` (or `adopt(true)`) is set.
139 * ### Creating an Organization
140 * **Example:** Basic organization
141 * ```typescript
142 * const org = yield* Cloudflare.Organization.Organization("Platform", {
143 * name: "acme-platform",
144 * });
145 * ```
146 *
147 * **Example:** Organization with a business profile
148 * ```typescript
149 * const org = yield* Cloudflare.Organization.Organization("Platform", {
150 * name: "acme-platform",
151 * profile: {
152 * businessName: "Acme Corp",
153 * businessEmail: "ops@acme.com",
154 * businessPhone: "+1-555-0100",
155 * businessAddress: "1 Acme Way, Springfield",
156 * externalMetadata: "crm:acct-42",
157 * },
158 * });
159 * ```
160 *
161 * ### Hierarchies
162 * **Example:** Sub-organization under a parent
163 * ```typescript
164 * const parent = yield* Cloudflare.Organization.Organization("Root", {
165 * name: "acme-root",
166 * });
167 * // Changing `parent` later replaces the sub-organization.
168 * const sub = yield* Cloudflare.Organization.Organization("Emea", {
169 * name: "acme-emea",
170 * parent: parent.organizationId,
171 * });
172 * ```
173 *
174 * @see https://developers.cloudflare.com/fundamentals/setup/manage-organizations/
175 *
176 * @resource
177 * @product Organizations
178 * @category Account & Identity
179 */
180 export const Organization = Resource<Organization>(TypeId, {
181 aliases: ["Cloudflare.Organization"],
182 });
183
184 /**
185 * Returns true if the given value is an Organization resource.
186 */
187 export const isOrganization = (value: unknown): value is Organization =>
188 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
189
190 export const OrganizationProvider = () =>
191 Provider.succeed(Organization, {
192 stables: ["organizationId", "createTime"],
193
194 // Enumerate every organization reachable by the credentials. Cloudflare's
195 // `/organizations` collection is account-wide (no per-account scoping
196 // beyond the token), so there is no env scope to resolve — just paginate
197 // exhaustively and map each row to the same `Attributes` shape `read`
198 // returns. The op is entitlement-gated: on an unentitled account it
199 // rejects with the typed `Forbidden` error, which `list()` tolerates
200 // (returns `[]`) so account-wide enumeration / `nuke` never blows up.
201 list: () =>
202 organizations.listOrganizations.pages({}).pipe(
203 Stream.runCollect,
204 Effect.map((chunk) =>
205 Array.from(chunk).flatMap((page) => (page.result ?? []).map(toAttributes)),
206 ),
207 // Organizations are a Tenant/reseller feature — a regular account
208 // token gets `Forbidden` ("Authentication error"). Nothing to list.
209 Effect.catchTag("Forbidden", () => Effect.succeed([])),
210 ),
211
212 diff: Effect.fn(function* ({ olds, news, output }) {
213 // `news` may still carry unresolved plan-time expressions — defer
214 // to the engine's default update logic until everything is concrete.
215 if (!isResolved(news)) return undefined;
216 // Re-parenting is not supported in place — hierarchy moves are
217 // gated by `accountMobility`/flags, so a parent change replaces.
218 const oldParent = output?.parent?.id ?? (olds?.parent as string | undefined);
219 const newParent = news.parent;
220 // `parent` is Input<string>; only compare once both are concrete.
221 if (
222 (oldParent === undefined) !== (newParent === undefined) ||
223 (typeof oldParent === "string" && typeof newParent === "string" && oldParent !== newParent)
224 ) {
225 return { action: "replace" } as const;
226 }
227 return undefined;
228 }),
229
230 read: Effect.fn(function* ({ id, output, olds }) {
231 // Owned path: refresh by our persisted organization id.
232 if (output?.organizationId) {
233 const observed = yield* getOrganization(output.organizationId);
234 return observed ? toAttributes(observed) : undefined;
235 }
236
237 // Cold read — recover from lost state by matching the deterministic
238 // physical name (+ parent). Organization names are not guaranteed
239 // unique and carry no ownership markers, so report the match as
240 // `Unowned`: the engine refuses to take it over unless `adopt` is
241 // set.
242 const name = yield* createOrganizationName(id, olds?.name);
243 const parent = olds?.parent as string | undefined;
244 const match = yield* findByName(name, parent);
245 return match ? Unowned(toAttributes(match)) : undefined;
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const name = yield* createOrganizationName(id, news.name);
250 // Inputs have been resolved to concrete strings by Plan.
251 const parent = news.parent as string | undefined;
252
253 // Observe — the organization id cached on `output` is a hint, not
254 // a guarantee: a missing organization falls through to create.
255 const observed = output?.organizationId
256 ? yield* getOrganization(output.organizationId)
257 : undefined;
258
259 if (!observed) {
260 // Ensure — greenfield (or out-of-band delete): create with the
261 // full desired body. Names are not unique on Cloudflare's side,
262 // so there is no AlreadyExists race to tolerate.
263 const created = yield* organizations.createOrganization({
264 name,
265 parent: parent !== undefined ? { id: parent } : undefined,
266 profile: news.profile,
267 });
268 return toAttributes(created);
269 }
270
271 // Sync — diff observed cloud state against desired; the update API
272 // is a PUT requiring `name`, so send the full desired shape, but
273 // skip the call entirely on a no-op. The desired profile keeps the
274 // observed one when the props omit it (the PUT would otherwise
275 // clear it).
276 const desiredProfile = news.profile ?? observed.profile ?? undefined;
277 const dirty = observed.name !== name || !sameProfile(observed.profile, news.profile);
278
279 if (!dirty) {
280 return toAttributes(observed);
281 }
282
283 const updated = yield* organizations.updateOrganization({
284 organizationId: observed.id,
285 name,
286 parent: observed.parent != null ? { id: observed.parent.id } : undefined,
287 profile: desiredProfile,
288 });
289 return toAttributes(updated);
290 }),
291
292 delete: Effect.fn(function* ({ output }) {
293 // Deletion is refused while the organization still manages
294 // accounts or sub-organizations — that's a genuine dependency
295 // violation, so it propagates. Already-gone is success.
296 yield* organizations
297 .deleteOrganization({ organizationId: output.organizationId })
298 .pipe(Effect.catchTag("OrganizationNotFound", () => Effect.void));
299 }),
300 });
301
302 type ObservedOrganization = organizations.GetOrganizationResponse;
303
304 /**
305 * Read an organization by id, mapping "gone" (`OrganizationNotFound`,
306 * HTTP 404) to `undefined`.
307 */
308 const getOrganization = (organizationId: string) =>
309 organizations.getOrganization({ organizationId }).pipe(
310 Effect.map((org): ObservedOrganization | undefined => org),
311 Effect.catchTag("OrganizationNotFound", () => Effect.undefined),
312 );
313
314 /**
315 * Find an organization by exact name (and parent, when one is expected).
316 * Cloudflare's name filter narrows server-side; re-check exactly
317 * client-side. If several organizations carry the same name, pick the
318 * oldest for determinism.
319 */
320 const findByName = (name: string, parent: string | undefined) =>
321 organizations.listOrganizations.items({ name: { contains: name } }).pipe(
322 Stream.runCollect,
323 Effect.map((chunk) =>
324 Array.from(chunk)
325 .filter((org) => org.name === name && (parent === undefined || org.parent?.id === parent))
326 .sort((a, b) => a.createTime.localeCompare(b.createTime))
327 .at(0),
328 ),
329 );
330
331 const createOrganizationName = (id: string, name: string | undefined) =>
332 Effect.gen(function* () {
333 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
334 });
335
336 /**
337 * Compare the observed profile against the desired one. An omitted
338 * desired profile is "keep whatever is there" — never a diff.
339 */
340 const sameProfile = (observed: Profile | null | undefined, desired: Profile | undefined) =>
341 desired === undefined ||
342 (observed != null &&
343 observed.businessAddress === desired.businessAddress &&
344 observed.businessEmail === desired.businessEmail &&
345 observed.businessName === desired.businessName &&
346 observed.businessPhone === desired.businessPhone &&
347 observed.externalMetadata === desired.externalMetadata);
348
349 const toAttributes = (
350 org:
351 | organizations.GetOrganizationResponse
352 | organizations.CreateOrganizationResponse
353 | organizations.UpdateOrganizationResponse
354 | organizations.ListOrganizationsResponse["result"][number],
355 ): Attributes => ({
356 organizationId: org.id,
357 name: org.name,
358 createTime: org.createTime,
359 managedBy: org.meta.managedBy ?? undefined,
360 flags: org.meta.tenantFlags ?? undefined,
361 parent: org.parent ?? undefined,
362 profile: org.profile ?? undefined,
363 });