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

main
ts 302 lines 10.7 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5 import { createInternalLabels } from "../Labels.ts";
6
7 export const DEFAULT_LOCATION = "global";
8 export const DEFAULT_COLLECTION = "default_collection";
9 export const DEFAULT_BRANCH = "default_branch";
10 export const LIST_LOCATIONS = ["global"] as const;
11 export const MAX_ID_LENGTH = 63;
12 export const MAX_NAME_LENGTH = MAX_ID_LENGTH;
13 export const MAX_DOCUMENT_ID_LENGTH = 128;
14 export const MAX_DISPLAY_NAME_LENGTH = 128;
15
16 export const lastSegment = (value: string) => {
17 const trimmed = value.replace(/\/+$/, "");
18 const parts = trimmed.split("/");
19 return parts[parts.length - 1] || trimmed;
20 };
21
22 export const normalizeLocation = (location: string | undefined) =>
23 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
24
25 export const locationParent = (project: string, location: string) =>
26 `projects/${project}/locations/${location}`;
27
28 export const parentOf = (name: string, collection?: string) => {
29 if (collection !== undefined) {
30 const marker = `/${collection}/`;
31 const index = name.lastIndexOf(marker);
32 return index >= 0 ? name.slice(0, index) : name;
33 }
34 const parts = name.split("/").filter((part) => part.length > 0);
35 return parts.slice(0, -2).join("/");
36 };
37
38 export const parentBefore = parentOf;
39
40 export const parseResourceName = (name: string, collection: string) => {
41 const parts = name.split("/").filter((part) => part.length > 0);
42 const collectionAt = parts.lastIndexOf(collection);
43 const locationsAt = parts.lastIndexOf("locations");
44 const projectsAt = parts.lastIndexOf("projects");
45 const dataStoresAt = parts.lastIndexOf("dataStores");
46 const collectionsAt = parts.lastIndexOf("collections");
47 const collectionId =
48 collectionsAt >= 0 && parts[collectionsAt + 1] ? parts[collectionsAt + 1]! : DEFAULT_COLLECTION;
49 return {
50 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
51 location:
52 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
53 collection: collectionId,
54 collectionId,
55 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
56 dataStoreId: dataStoresAt >= 0 && parts[dataStoresAt + 1] ? parts[dataStoresAt + 1]! : "",
57 dataStore: dataStoresAt >= 0 ? parts.slice(0, dataStoresAt + 2).join("/") : parentOf(name),
58 parent:
59 collectionAt > 0
60 ? parts.slice(0, collectionAt).join("/")
61 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
62 };
63 };
64
65 export const expandDataStore = (value: string, project: string, location: string) =>
66 value.includes("/")
67 ? value
68 : `projects/${project}/locations/${location}/collections/${DEFAULT_COLLECTION}/dataStores/${value}`;
69
70 export const rfc1035 = (name: string, maxLength = MAX_ID_LENGTH): string => {
71 let next = name
72 .toLowerCase()
73 .replace(/[^a-z0-9-]/g, "-")
74 .replace(/-+/g, "-")
75 .replace(/^-+|-+$/g, "");
76 if (!/^[a-z]/.test(next)) next = `a${next}`;
77 next = next.slice(0, maxLength).replace(/-+$/g, "");
78 if (next.length === 0) return "resource";
79 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, maxLength - 1)}0`;
80 return next.slice(0, maxLength);
81 };
82
83 export const controlIdOf = (name: string, maxLength = MAX_ID_LENGTH): string => {
84 let next = name
85 .toLowerCase()
86 .replace(/[0-9]/g, (digit) => "abcdefghij"[Number(digit)]!)
87 .replace(/[^a-z_-]/g, "-")
88 .replace(/-+/g, "-")
89 .replace(/^-+|-+$/g, "");
90 if (!/^[a-z]/.test(next)) next = `c${next}`;
91 next = next.slice(0, maxLength).replace(/[-_]+$/g, "");
92 return next.length > 0 ? next : "control";
93 };
94
95 export const servingConfigIdOf = (name: string, maxLength = MAX_ID_LENGTH): string => {
96 let next = name.toLowerCase().replace(/[^a-z0-9]/g, "");
97 if (!/^[a-z]/.test(next)) next = `s${next}`;
98 next = next.slice(0, maxLength);
99 if (next.length < 4) next = `${next}xxxx`.slice(0, 4);
100 return next.length > 0 ? next : "scfg";
101 };
102
103 export const sessionIdOf = (name: string, maxLength = MAX_ID_LENGTH): string => {
104 let next = name.toLowerCase().replace(/[^a-z0-9]/g, "");
105 if (!/^[a-z]/.test(next)) next = `s${next}`;
106 next = next.slice(0, maxLength);
107 return next.length > 0 ? next : "session";
108 };
109
110 export const identityMappingStoreIdOf = (name: string): string => {
111 const body = rfc1035(name, 59);
112 const prefixed = body.startsWith("alch") ? body : `alch${body}`;
113 return prefixed.slice(0, MAX_ID_LENGTH);
114 };
115
116 export const toPhysical = (
117 id: string,
118 explicit: string | undefined,
119 existing: string | undefined,
120 format: (name: string) => string,
121 maxLength = MAX_ID_LENGTH,
122 ) =>
123 Effect.gen(function* () {
124 if (explicit !== undefined) return explicit;
125 if (existing !== undefined) return existing;
126 return format(
127 yield* createPhysicalName({
128 id,
129 maxLength,
130 lowercase: true,
131 }),
132 );
133 });
134
135 export const internalLabels = (id: string) => createInternalLabels(id);
136
137 export const canonical = (value: unknown): unknown => {
138 if (value === undefined || value === null) return undefined;
139 if (typeof value === "boolean" || typeof value === "number") return value;
140 if (typeof value === "string") {
141 return value.length === 0 ? undefined : value;
142 }
143 if (Array.isArray(value)) {
144 const items = value.map(canonical).filter((item) => item !== undefined);
145 return items.length === 0 ? undefined : items;
146 }
147 if (typeof value === "object") {
148 const entries = Object.entries(value as Record<string, unknown>)
149 .map(([key, item]) => [key, canonical(item)] as const)
150 .filter(([, item]) => item !== undefined)
151 .sort(([left], [right]) => left.localeCompare(right));
152 if (entries.length === 0) return undefined;
153 return Object.fromEntries(entries);
154 }
155 return undefined;
156 };
157
158 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
159
160 export const sameStringList = (
161 left: readonly string[] | undefined,
162 right: readonly string[] | undefined,
163 ) => fingerprint([...(left ?? [])].sort()) === fingerprint([...(right ?? [])].sort());
164
165 export const parseJsonObject = (json: string | undefined): Record<string, unknown> | undefined => {
166 if (json === undefined || json.length === 0) return undefined;
167 try {
168 const parsed: unknown = JSON.parse(json);
169 if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
170 return parsed as Record<string, unknown>;
171 }
172 } catch {
173 return undefined;
174 }
175 return undefined;
176 };
177
178 /** Parse a JSON Schema document and default its `$schema` version. */
179 export const withSchemaVersion = (jsonSchema: string | undefined): string => {
180 const obj = parseJsonObject(jsonSchema) ?? {
181 type: "object",
182 properties: {
183 title: { type: "string" },
184 description: { type: "string" },
185 },
186 };
187 if (obj.$schema === undefined) {
188 obj.$schema = "https://json-schema.org/draft/2020-12/schema";
189 }
190 return JSON.stringify(obj);
191 };
192
193 export const listDataStores = (project: string) =>
194 Effect.forEach(
195 LIST_LOCATIONS,
196 (location) =>
197 discoveryengine.listProjectsLocationsDataStores
198 .pages({
199 parent: locationParent(project, location),
200 pageSize: 50,
201 })
202 .pipe(
203 Stream.flatMap((page) => Stream.fromIterable(page.dataStores ?? [])),
204 Stream.runCollect,
205 Effect.map((chunk) => Array.from(chunk)),
206 Effect.catchTag("NotFound", () => Effect.succeed([])),
207 ),
208 { concurrency: 2 },
209 ).pipe(Effect.map((groups) => groups.flat()));
210
211 export const normalizeCollection = (collection: string | undefined) =>
212 lastSegment(collection ?? DEFAULT_COLLECTION);
213
214 export const collectionParent = (project: string, location: string, collectionId: string) =>
215 `${locationParent(project, location)}/collections/${collectionId}`;
216
217 export const dataStoreName = (
218 project: string,
219 location: string,
220 collectionId: string,
221 dataStoreId: string,
222 ) => `${collectionParent(project, location, collectionId)}/dataStores/${dataStoreId}`;
223
224 export const dataStoreIdOf = (value: string) => lastSegment(value);
225
226 export const servingConfigId = servingConfigIdOf;
227
228 export const toResourceId = (
229 id: string,
230 explicit: string | undefined,
231 existing: string | undefined,
232 ) =>
233 Effect.gen(function* () {
234 if (explicit !== undefined) return rfc1035(explicit);
235 if (existing !== undefined) return existing;
236 return rfc1035(
237 yield* createPhysicalName({
238 id,
239 maxLength: MAX_ID_LENGTH,
240 lowercase: true,
241 }),
242 );
243 });
244
245 export const ownershipLabels = (id: string) => createInternalLabels(id);
246
247 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
248
249 export const listProjectDataStores = (project: string) =>
250 Effect.gen(function* () {
251 const seen = new Set<string>();
252 const stores: discoveryengine.GoogleCloudDiscoveryengineV1DataStore[] = [];
253 const locationStores = yield* listDataStores(project);
254 const collectionStores = yield* listCollectionDataStores(project);
255 for (const store of [...locationStores, ...collectionStores]) {
256 const name = store.name ?? "";
257 if (name.length === 0 || seen.has(name)) continue;
258 seen.add(name);
259 stores.push(store);
260 }
261 return stores;
262 });
263
264 export const branchParent = (dataStore: string, branchId = DEFAULT_BRANCH) =>
265 `${dataStore}/branches/${branchId}`;
266
267 export const siteSearchEngineParent = (dataStore: string) => `${dataStore}/siteSearchEngine`;
268
269 export const listCollectionDataStores = (project: string) =>
270 Effect.forEach(
271 LIST_LOCATIONS,
272 (location) =>
273 discoveryengine.listProjectsLocationsCollectionsDataStores
274 .pages({
275 parent: collectionParent(project, location, DEFAULT_COLLECTION),
276 pageSize: 50,
277 })
278 .pipe(
279 Stream.flatMap((page) => Stream.fromIterable(page.dataStores ?? [])),
280 Stream.runCollect,
281 Effect.map((chunk) => Array.from(chunk)),
282 Effect.catchTag("NotFound", () => Effect.succeed([])),
283 ),
284 { concurrency: 2 },
285 ).pipe(Effect.map((groups) => groups.flat()));
286
287 /**
288 * Target sites echo only `generatedUriPattern` (scheme stripped, directory
289 * patterns suffixed with `*`), so compare against that normalized form.
290 */
291 const normalizeUriPattern = (pattern: string) => {
292 const bare = pattern.replace(/^https?:\/\//, "");
293 return bare.endsWith("/") ? `${bare}*` : bare;
294 };
295
296 export const matchesUriPattern = (
297 site: { providedUriPattern?: string; generatedUriPattern?: string },
298 pattern: string,
299 ) => {
300 const observed = site.providedUriPattern ?? site.generatedUriPattern ?? "";
301 return observed === pattern || normalizeUriPattern(observed) === normalizeUriPattern(pattern);
302 };