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

main
ts 245 lines 8.75 KB
Raw
1 import * as ag from "@distilled.cloud/aws/api-gateway";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 const normalizeBasePath = (basePath: string | undefined) =>
11 basePath === undefined || basePath === "" ? "(none)" : basePath;
12
13 export interface BasePathMappingProps {
14 /** The custom domain name to map (e.g. `api.example.com`). */
15 domainName: string;
16 /** Domain name ID, required for private custom domain names. */
17 domainNameId?: string;
18 /**
19 * Base path segment; omit or empty string for root mapping (`(none)` in API Gateway).
20 */
21 basePath?: string;
22 /** ID of the REST API the path maps to. */
23 restApiId: Input<string>;
24 /** Name of the API stage requests are routed to. */
25 stage?: string;
26 }
27
28 /** @resource */
29 export interface BasePathMapping extends Resource<
30 "AWS.ApiGateway.BasePathMapping",
31 BasePathMappingProps,
32 {
33 domainName: string;
34 domainNameId: string | undefined;
35 basePath: string;
36 restApiId: string;
37 stage: string | undefined;
38 },
39 never,
40 Providers
41 > {}
42
43 /**
44 * Maps a custom domain name path to a REST API stage.
45 *
46 * ### Custom domain
47 * **Example:** Root mapping
48 * ```typescript
49 * yield* ApiGateway.BasePathMapping("Root", {
50 * domainName: domain.domainName,
51 * restApiId: api.restApiId,
52 * stage: stage.stageName,
53 * });
54 * ```
55 */
56 const BasePathMappingResource = Resource<BasePathMapping>("AWS.ApiGateway.BasePathMapping");
57
58 export { BasePathMappingResource as BasePathMapping };
59
60 export const BasePathMappingProvider = () =>
61 Provider.effect(
62 BasePathMappingResource,
63 Effect.gen(function* () {
64 return {
65 stables: ["domainName", "domainNameId", "basePath"] as const,
66 diff: Effect.fn(function* ({ news: newsIn, olds }) {
67 if (!isResolved(newsIn)) return;
68 const news = newsIn as Input.ResolveProps<BasePathMappingProps>;
69 if (
70 news.domainName !== olds.domainName ||
71 normalizeBasePath(news.basePath) !== normalizeBasePath(olds.basePath)
72 ) {
73 return { action: "replace" } as const;
74 }
75 }),
76 read: Effect.fn(function* ({ output }) {
77 if (!output) return undefined;
78 const b = yield* ag
79 .getBasePathMapping({
80 domainName: output.domainName,
81 basePath: output.basePath,
82 domainNameId: output.domainNameId,
83 })
84 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
85 if (!b?.restApiId) return undefined;
86 return {
87 domainName: output.domainName,
88 basePath: output.basePath,
89 domainNameId: output.domainNameId,
90 restApiId: b.restApiId,
91 stage: b.stage,
92 };
93 }),
94 reconcile: Effect.fn(function* ({ news: newsIn, output, session }) {
95 if (!isResolved(newsIn)) {
96 return yield* Effect.die("BasePathMapping props were not resolved");
97 }
98 const news = newsIn as Input.ResolveProps<BasePathMappingProps>;
99 const domainName = output?.domainName ?? news.domainName;
100 const domainNameId = output?.domainNameId ?? news.domainNameId;
101 const basePath = output?.basePath ?? normalizeBasePath(news.basePath);
102
103 // Observe — basePathmappings are keyed by (domainName, basePath).
104 // We never trust `output.restApiId`/`output.stage` for diffing; we
105 // re-read the live mapping every time.
106 let observed = yield* ag
107 .getBasePathMapping({
108 domainName,
109 basePath,
110 domainNameId,
111 })
112 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
113
114 // Ensure — create the mapping if it isn't there.
115 if (!observed?.restApiId) {
116 yield* ag.createBasePathMapping({
117 domainName: news.domainName,
118 domainNameId: news.domainNameId,
119 basePath: basePath === "(none)" ? undefined : news.basePath,
120 restApiId: news.restApiId as string,
121 stage: news.stage,
122 });
123 yield* session.note(`Created base path mapping ${news.domainName} / ${basePath}`);
124 observed = yield* ag.getBasePathMapping({
125 domainName,
126 basePath,
127 domainNameId,
128 });
129 }
130
131 // Sync mutable fields — diff observed cloud state against desired.
132 const desiredRestApiId = news.restApiId as string;
133 const patches: ag.PatchOperation[] = [];
134 if (desiredRestApiId !== observed.restApiId) {
135 patches.push({
136 op: "replace" as const,
137 path: "/restApiId",
138 value: desiredRestApiId,
139 });
140 }
141 if ((news.stage ?? "") !== (observed.stage ?? "")) {
142 patches.push({
143 op: "replace" as const,
144 path: "/stage",
145 value: news.stage ?? "",
146 });
147 }
148 if (patches.length > 0) {
149 yield* ag.updateBasePathMapping({
150 domainName,
151 basePath,
152 domainNameId,
153 patchOperations: patches,
154 });
155 }
156
157 yield* session.note(`Reconciled base path mapping`);
158 const final = yield* ag.getBasePathMapping({
159 domainName,
160 basePath,
161 domainNameId,
162 });
163 return {
164 domainName,
165 domainNameId,
166 basePath,
167 restApiId: final.restApiId!,
168 stage: final.stage,
169 };
170 }),
171 // BasePathMappings are sub-resources keyed by their parent domain
172 // name. There is no account-wide list, so enumerate every custom
173 // domain name first (getDomainNames) and then list the mappings under
174 // each (getBasePathMappings), flattening to the full Attributes shape.
175 list: () =>
176 Effect.gen(function* () {
177 const domains = yield* ag.getDomainNames.pages({}).pipe(
178 Stream.runCollect,
179 Effect.map((chunk) =>
180 Array.from(chunk).flatMap((page) =>
181 (page.items ?? []).filter(
182 (d): d is ag.DomainName & { domainName: string } => d.domainName != null,
183 ),
184 ),
185 ),
186 );
187 const rows = yield* Effect.forEach(
188 domains,
189 (domain) =>
190 ag.getBasePathMappings
191 .pages({
192 domainName: domain.domainName,
193 domainNameId: domain.domainNameId,
194 })
195 .pipe(
196 Stream.runCollect,
197 Effect.map((chunk) =>
198 Array.from(chunk).flatMap((page) =>
199 (page.items ?? [])
200 .filter(
201 (
202 m,
203 ): m is ag.BasePathMapping & {
204 restApiId: string;
205 } => m.restApiId != null,
206 )
207 .map((m) => ({
208 domainName: domain.domainName,
209 domainNameId: domain.domainNameId,
210 basePath: normalizeBasePath(m.basePath),
211 restApiId: m.restApiId,
212 stage: m.stage,
213 })),
214 ),
215 ),
216 // A domain can disappear between enumeration and listing.
217 Effect.catchTag("NotFoundException", () =>
218 Effect.succeed(
219 [] as {
220 domainName: string;
221 domainNameId: string | undefined;
222 basePath: string;
223 restApiId: string;
224 stage: string | undefined;
225 }[],
226 ),
227 ),
228 ),
229 { concurrency: 10 },
230 );
231 return rows.flat();
232 }),
233 delete: Effect.fn(function* ({ output, session }) {
234 yield* ag
235 .deleteBasePathMapping({
236 domainName: output.domainName,
237 basePath: output.basePath,
238 domainNameId: output.domainNameId,
239 })
240 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
241 yield* session.note(`Deleted base path mapping`);
242 }),
243 };
244 }),
245 );