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

main
ts 318 lines 11.7 KB
Raw
1 import * as appintegrations from "@distilled.cloud/aws/appintegrations";
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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { definedTags } from "./internal.ts";
13
14 export interface ApplicationProps {
15 /**
16 * Name of the application. If omitted, a unique name is generated from
17 * the app, stage, and logical ID. The name can be updated in place.
18 */
19 name?: string;
20 /**
21 * The unique namespace of the application, e.g. `com.example.myapp`.
22 * Changing the namespace replaces the application.
23 */
24 namespace: string;
25 /**
26 * Description of the application (1-1000 characters).
27 */
28 description?: string;
29 /**
30 * The URL where the application is hosted and rendered from, e.g.
31 * `https://example.com`.
32 */
33 accessUrl: string;
34 /**
35 * Additional origins the application is allowed to be loaded from.
36 */
37 approvedOrigins?: string[];
38 /**
39 * The configuration of events or requests that the application has access
40 * to, e.g. `["User.Details.View"]`.
41 */
42 permissions?: string[];
43 /**
44 * Tags to apply to the application. Merged with internal Alchemy tags.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface Application extends Resource<
50 "AWS.AppIntegrations.Application",
51 ApplicationProps,
52 {
53 applicationId: string;
54 applicationArn: string;
55 applicationName: string;
56 namespace: string;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * An Amazon AppIntegrations application. Applications register external
64 * (iframe-hosted) apps — most commonly Amazon Connect agent workspace
65 * third-party applications — with a name, namespace, and the URL they are
66 * served from.
67 *
68 * The namespace is immutable; changing it replaces the application. The
69 * name, description, access URL, approved origins, and permissions can all
70 * be updated in place.
71 * ### Creating an Application
72 * **Example:** Basic Application
73 * ```typescript
74 * import * as AppIntegrations from "@alchemy.run/aws/AppIntegrations";
75 *
76 * const app = yield* AppIntegrations.Application("AgentApp", {
77 * namespace: "com.example.agentapp",
78 * accessUrl: "https://example.com",
79 * });
80 * ```
81 *
82 * **Example:** Application with Permissions and Tags
83 * ```typescript
84 * const app = yield* AppIntegrations.Application("AgentApp", {
85 * namespace: "com.example.agentapp",
86 * accessUrl: "https://example.com",
87 * description: "Agent workspace application",
88 * permissions: ["User.Details.View"],
89 * tags: { team: "contact-center" },
90 * });
91 * ```
92 *
93 * @resource
94 */
95 export const Application = Resource<Application>("AWS.AppIntegrations.Application");
96
97 /**
98 * Raised when the AppIntegrations API returns an application without the
99 * fields required to build the resource attributes.
100 */
101 export class ApplicationIncomplete extends Data.TaggedError(
102 "AppIntegrationsApplicationIncomplete",
103 )<{ message: string }> {}
104
105 export const ApplicationProvider = () =>
106 Provider.effect(
107 Application,
108 Effect.gen(function* () {
109 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
110 return props.name ?? (yield* createPhysicalName({ id, maxLength: 255 }));
111 });
112
113 /** Get a single application by ARN or ID; undefined if absent. */
114 const observe = (arnOrId: string) =>
115 appintegrations
116 .getApplication({ Arn: arnOrId })
117 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
118
119 /**
120 * Find an application ARN by namespace via list enumeration. The
121 * namespace is the account-unique key; the name is a generated
122 * physical name whose instance-id suffix changes across lost-state
123 * re-runs, so matching on it would miss the existing application and
124 * `createApplication` would then fail with "Namespace already in use".
125 */
126 const findByNamespace = (namespace: string) =>
127 appintegrations.listApplications.items({}).pipe(
128 Stream.filter((item) => item.Namespace === namespace),
129 Stream.take(1),
130 Stream.runCollect,
131 Effect.map((chunk) => Array.from(chunk)[0]?.Arn),
132 );
133
134 const toAttrs = Effect.fn(function* (live: appintegrations.GetApplicationResponse) {
135 if (
136 live.Arn === undefined ||
137 live.Id === undefined ||
138 live.Name === undefined ||
139 live.Namespace === undefined
140 ) {
141 return yield* new ApplicationIncomplete({
142 message: `application '${live.Name}' is missing Arn, Id, Name, or Namespace`,
143 });
144 }
145 return {
146 applicationId: live.Id,
147 applicationArn: live.Arn,
148 applicationName: live.Name,
149 namespace: live.Namespace,
150 };
151 });
152
153 return Application.Provider.of({
154 stables: ["applicationId", "applicationArn", "namespace"],
155
156 list: () =>
157 appintegrations.listApplications.items({}).pipe(
158 Stream.runCollect,
159 Effect.map((chunk) =>
160 Array.from(chunk).flatMap((item) =>
161 item.Arn !== undefined &&
162 item.Id !== undefined &&
163 item.Name !== undefined &&
164 item.Namespace !== undefined
165 ? [
166 {
167 applicationId: item.Id,
168 applicationArn: item.Arn,
169 applicationName: item.Name,
170 namespace: item.Namespace,
171 },
172 ]
173 : [],
174 ),
175 ),
176 ),
177
178 read: Effect.fn(function* ({ id, olds, output }) {
179 let arn = output?.applicationArn;
180 if (arn === undefined) {
181 if (olds === undefined) return undefined;
182 arn = yield* findByNamespace(olds.namespace);
183 }
184 if (arn === undefined) return undefined;
185 const live = yield* observe(arn);
186 if (live === undefined) return undefined;
187 const attrs = yield* toAttrs(live);
188 const tags = definedTags(live.Tags);
189 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
190 }),
191
192 diff: Effect.fn(function* ({ news, olds }) {
193 if (!isResolved(news)) return undefined;
194 if (olds === undefined) return undefined;
195 if (olds.namespace !== news.namespace) {
196 return { action: "replace" } as const;
197 }
198 // fall through: default update path (name, description, source
199 // config, permissions, tags are all mutable in place)
200 }),
201
202 reconcile: Effect.fn(function* ({ id, news, output, session }) {
203 const name = yield* createName(id, news);
204 const internalTags = yield* createInternalTags(id);
205 const desiredTags = { ...news.tags, ...internalTags };
206 const desiredSourceConfig: appintegrations.ApplicationSourceConfig = {
207 ExternalUrlConfig: {
208 AccessUrl: news.accessUrl,
209 ...(news.approvedOrigins ? { ApprovedOrigins: news.approvedOrigins } : {}),
210 },
211 };
212
213 // 1. Observe — prefer the cached ARN; fall back to enumerating by
214 // the unique namespace so a lost-state re-run converges even
215 // though the generated physical name changed.
216 let arn = output?.applicationArn;
217 let live = arn === undefined ? undefined : yield* observe(arn);
218 if (live === undefined) {
219 arn = yield* findByNamespace(news.namespace);
220 live = arn === undefined ? undefined : yield* observe(arn);
221 }
222
223 // 2. Ensure — create if missing. A concurrent create can win the
224 // unique namespace between observe and create ("Namespace
225 // already in use" InvalidRequestException) — treat it as a race
226 // and re-observe; rethrow if the namespace holder still can't
227 // be found.
228 if (live === undefined) {
229 const created = yield* appintegrations
230 .createApplication({
231 Name: name,
232 Namespace: news.namespace,
233 Description: news.description,
234 ApplicationSourceConfig: desiredSourceConfig,
235 Permissions: news.permissions,
236 Tags: desiredTags,
237 })
238 .pipe(
239 Effect.catchTag("InvalidRequestException", (error) =>
240 Effect.gen(function* () {
241 const existing = yield* findByNamespace(news.namespace);
242 if (existing === undefined) {
243 return yield* error;
244 }
245 return { Arn: existing };
246 }),
247 ),
248 );
249 if (created.Arn === undefined) {
250 return yield* new ApplicationIncomplete({
251 message: `createApplication for '${name}' returned no Arn`,
252 });
253 }
254 arn = created.Arn;
255 live = yield* appintegrations.getApplication({ Arn: arn });
256 }
257 const attrs = yield* toAttrs(live);
258
259 // 3. Sync mutable aspects — compare observed cloud state against
260 // desired and push a single update with only the changed fields.
261 const update: Omit<appintegrations.UpdateApplicationRequest, "Arn"> = {};
262 if (live.Name !== name) {
263 update.Name = name;
264 }
265 if (news.description !== undefined && news.description !== live.Description) {
266 update.Description = news.description;
267 }
268 const observedUrlConfig = live.ApplicationSourceConfig?.ExternalUrlConfig;
269 if (
270 observedUrlConfig?.AccessUrl !== news.accessUrl ||
271 JSON.stringify(observedUrlConfig?.ApprovedOrigins ?? []) !==
272 JSON.stringify(news.approvedOrigins ?? [])
273 ) {
274 update.ApplicationSourceConfig = desiredSourceConfig;
275 }
276 if (
277 news.permissions !== undefined &&
278 JSON.stringify([...(live.Permissions ?? [])].sort()) !==
279 JSON.stringify([...news.permissions].sort())
280 ) {
281 update.Permissions = news.permissions;
282 }
283 if (Object.keys(update).length > 0) {
284 yield* appintegrations.updateApplication({
285 Arn: attrs.applicationArn,
286 ...update,
287 });
288 }
289
290 // 4. Sync tags — diff against OBSERVED cloud tags so adoption
291 // converges.
292 const observedTags = definedTags(live.Tags);
293 const { upsert, removed } = diffTags(observedTags, desiredTags);
294 if (upsert.length > 0) {
295 yield* appintegrations.tagResource({
296 resourceArn: attrs.applicationArn,
297 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
298 });
299 }
300 if (removed.length > 0) {
301 yield* appintegrations.untagResource({
302 resourceArn: attrs.applicationArn,
303 tagKeys: removed,
304 });
305 }
306
307 yield* session.note(name);
308 return { ...attrs, applicationName: name };
309 }),
310
311 delete: Effect.fn(function* ({ output }) {
312 yield* appintegrations
313 .deleteApplication({ Arn: output.applicationArn })
314 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
315 }),
316 });
317 }),
318 );