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

main
ts 246 lines 8.44 KB
Raw
1 import * as location from "@distilled.cloud/aws/location";
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, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as EffectStream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { toTagRecord } from "./internal.ts";
14
15 export class MapUnexpectedResponse extends Data.TaggedError("MapUnexpectedResponse")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 /**
21 * Rendering configuration for a map. `style` selects the base map style and is
22 * immutable — changing it replaces the map.
23 */
24 export interface MapConfiguration {
25 /**
26 * The map style. Selecting a style determines the map's data provider
27 * (Esri, HERE, or Grab). Immutable — changing the style replaces the map.
28 *
29 * Common values: `VectorEsriNavigation`, `VectorEsriStreets`,
30 * `VectorHereExplore`, `RasterHereExploreSatellite`,
31 * `VectorGrabStandardLight`.
32 */
33 style: string;
34 /**
35 * Political view (an ISO 3166-1 alpha-3 country code) applied to the map's
36 * disputed borders and labels.
37 */
38 politicalView?: string;
39 }
40
41 export interface MapProps {
42 /**
43 * Name of the map resource. Immutable — changing it replaces the map.
44 * @default ${app}-${stage}-${id}
45 */
46 mapName?: string;
47 /**
48 * Rendering configuration for the map (base style + political view).
49 */
50 configuration: MapConfiguration;
51 /**
52 * Optional description of the map resource.
53 */
54 description?: string;
55 /**
56 * Tags to associate with the map.
57 */
58 tags?: Record<string, string>;
59 }
60
61 export interface Map extends Resource<
62 "AWS.Location.Map",
63 MapProps,
64 {
65 /** Physical name of the map resource. */
66 mapName: string;
67 /** ARN of the map resource. */
68 mapArn: string;
69 /** The map style selected at creation. */
70 style: string;
71 /** Political view currently applied to the map, if any. */
72 politicalView: string | undefined;
73 /** Data provider backing the map, derived from the style. */
74 dataSource: string;
75 /** Description of the map resource. */
76 description: string | undefined;
77 /** Tags currently associated with the map. */
78 tags: Record<string, string>;
79 },
80 never,
81 Providers
82 > {}
83
84 /**
85 * An Amazon Location Service map resource. A map exposes vector/raster tiles,
86 * glyphs, and sprites for a chosen base style. The map style is immutable;
87 * the political view and description can be updated in place.
88 *
89 * ### Creating Maps
90 * **Example:** Basic Map
91 * ```typescript
92 * import * as Location from "@alchemy.run/aws/Location";
93 *
94 * const map = yield* Location.Map("AppMap", {
95 * configuration: { style: "VectorEsriNavigation" },
96 * });
97 * ```
98 *
99 * **Example:** Map with Political View
100 * ```typescript
101 * const map = yield* Location.Map("RegionMap", {
102 * configuration: { style: "VectorHereExplore", politicalView: "IND" },
103 * description: "Map with India political view",
104 * });
105 * ```
106 *
107 * @resource
108 */
109 export const Map = Resource<Map>("AWS.Location.Map");
110
111 const createMapName = (id: string, props: { mapName?: string | undefined }) =>
112 Effect.gen(function* () {
113 if (props.mapName) return props.mapName;
114 return yield* createPhysicalName({ id, maxLength: 100 });
115 });
116
117 const readMap = Effect.fn(function* (mapName: string) {
118 const found = yield* location
119 .describeMap({ MapName: mapName })
120 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
121 if (!found) return undefined;
122 return {
123 mapName: found.MapName,
124 mapArn: found.MapArn,
125 style: found.Configuration.Style,
126 politicalView: Redacted.isRedacted(found.Configuration.PoliticalView)
127 ? Redacted.value(found.Configuration.PoliticalView)
128 : found.Configuration.PoliticalView,
129 dataSource: found.DataSource,
130 description: found.Description ? found.Description : undefined,
131 tags: toTagRecord(found.Tags),
132 } satisfies Map["Attributes"];
133 });
134
135 export const MapProvider = () =>
136 Provider.effect(
137 Map,
138 Effect.gen(function* () {
139 return {
140 stables: ["mapName", "mapArn"],
141 list: () =>
142 Effect.gen(function* () {
143 const names = yield* location.listMaps.pages({}).pipe(
144 EffectStream.runCollect,
145 Effect.map((chunk) =>
146 Array.from(chunk).flatMap((page) =>
147 (page.Entries ?? []).map((entry) => entry.MapName),
148 ),
149 ),
150 );
151 const hydrated = yield* Effect.forEach(names, (name) => readMap(name), {
152 concurrency: 10,
153 });
154 return hydrated.filter((attrs): attrs is Map["Attributes"] => attrs !== undefined);
155 }),
156 read: Effect.fn(function* ({ id, olds, output }) {
157 const mapName = output?.mapName ?? (yield* createMapName(id, olds ?? {}));
158 const state = yield* readMap(mapName);
159 if (!state) return undefined;
160 return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state);
161 }),
162 diff: Effect.fn(function* ({ id, news, olds }) {
163 if (!isResolved(news)) return;
164 const oldName = yield* createMapName(id, olds);
165 const newName = yield* createMapName(id, news);
166 // Name and base style are immutable — either change forces a replace.
167 if (oldName !== newName || olds.configuration?.style !== news.configuration?.style) {
168 return { action: "replace" } as const;
169 }
170 }),
171 reconcile: Effect.fn(function* ({ id, news, output, session }) {
172 const mapName = output?.mapName ?? (yield* createMapName(id, news));
173 const internalTags = yield* createInternalTags(id);
174 const desiredTags = { ...internalTags, ...news.tags };
175
176 // Observe — cloud state is authoritative; output is only a name cache.
177 let state = yield* readMap(mapName);
178
179 // Ensure — create if missing; tolerate a concurrent create.
180 if (state === undefined) {
181 yield* location
182 .createMap({
183 MapName: mapName,
184 Configuration: {
185 Style: news.configuration.style,
186 PoliticalView: news.configuration.politicalView,
187 },
188 Description: news.description,
189 Tags: desiredTags,
190 })
191 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
192 state = yield* readMap(mapName);
193 if (state === undefined) {
194 return yield* new MapUnexpectedResponse({
195 message: `failed to read created map ${mapName}`,
196 });
197 }
198 }
199
200 // Sync description + political view.
201 if (
202 state.description !== (news.description ?? undefined) ||
203 state.politicalView !== (news.configuration.politicalView ?? undefined)
204 ) {
205 yield* location.updateMap({
206 MapName: mapName,
207 Description: news.description,
208 ConfigurationUpdate: {
209 PoliticalView: news.configuration.politicalView,
210 },
211 });
212 }
213
214 // Sync tags — diff against observed cloud tags.
215 const { removed, upsert } = diffTags(state.tags, desiredTags);
216 if (removed.length > 0) {
217 yield* location.untagResource({
218 ResourceArn: state.mapArn,
219 TagKeys: removed,
220 });
221 }
222 if (upsert.length > 0) {
223 yield* location.tagResource({
224 ResourceArn: state.mapArn,
225 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
226 });
227 }
228
229 yield* session.note(state.mapArn);
230
231 const final = yield* readMap(mapName);
232 if (!final) {
233 return yield* new MapUnexpectedResponse({
234 message: `failed to read reconciled map ${mapName}`,
235 });
236 }
237 return final;
238 }),
239 delete: Effect.fn(function* ({ output }) {
240 yield* location
241 .deleteMap({ MapName: output.mapName })
242 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
243 }),
244 };
245 }),
246 );