@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 221 lines 7.27 KB
Raw
1 import type * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
3
4 export { createInternalLabels, hasAlchemyLabels };
5
6 export const lastSegment = (value: string) => {
7 const trimmed = value.replace(/\/+$/, "");
8 const parts = trimmed.split("/");
9 return parts[parts.length - 1] || trimmed;
10 };
11
12 export const orgIdOf = (value: string | undefined, project?: string) =>
13 lastSegment(value ?? project ?? "");
14
15 export const orgParent = (org: string) =>
16 org.startsWith("organizations/") ? org : `organizations/${org}`;
17
18 export const xmlEscape = (value: string) =>
19 value
20 .replaceAll("&", "&")
21 .replaceAll("<", "&lt;")
22 .replaceAll(">", "&gt;")
23 .replaceAll('"', "&quot;")
24 .replaceAll("'", "&apos;");
25
26 export const xmlUnescape = (value: string) =>
27 value
28 .replaceAll("&lt;", "<")
29 .replaceAll("&gt;", ">")
30 .replaceAll("&quot;", '"')
31 .replaceAll("&apos;", "'")
32 .replaceAll("&amp;", "&");
33
34 export const encodeOwnership = (
35 labels: Record<string, string>,
36 userText: string | undefined,
37 extra?: Record<string, string>,
38 ): string => {
39 const pairs = [
40 `${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]}`,
41 `${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]}`,
42 `${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}`,
43 ...Object.entries(extra ?? {}).map(([key, value]) => `${key}=${value}`),
44 ];
45 const marker = `[alchemy ${pairs.join(" ")}]`;
46 return userText ? `${marker}\n${userText}` : marker;
47 };
48
49 export const parseOwnership = (
50 value: string | undefined,
51 ): {
52 labels: Record<string, string>;
53 text: string | undefined;
54 } => {
55 if (!value?.startsWith("[alchemy ")) {
56 return { labels: {}, text: value };
57 }
58 const end = value.indexOf("]");
59 if (end < 0) return { labels: {}, text: value };
60 const labels: Record<string, string> = {};
61 for (const part of value.slice("[alchemy ".length, end).split(/\s+/)) {
62 const eq = part.indexOf("=");
63 if (eq > 0) {
64 labels[part.slice(0, eq)] = part.slice(eq + 1);
65 }
66 }
67 const rest = value.slice(end + 1).replace(/^\s+/, "");
68 return { labels, text: rest.length > 0 ? rest : undefined };
69 };
70
71 export const hasOwnershipMarker = (value: string | undefined) =>
72 Object.keys(parseOwnership(value).labels).some((key) => key.startsWith("alchemy-"));
73
74 export const encodeDescription = (
75 labels: Record<string, string>,
76 description: string | undefined,
77 maxLength?: number,
78 ): string => {
79 const encoded = encodeOwnership(labels, description);
80 return maxLength !== undefined ? encoded.slice(0, maxLength) : encoded;
81 };
82
83 export const parseDescription = (
84 description: string | undefined,
85 ): {
86 labels: Record<string, string>;
87 description: string | undefined;
88 } => {
89 const parsed = parseOwnership(description);
90 return { labels: parsed.labels, description: parsed.text };
91 };
92
93 export const encodeComments = (
94 labels: Record<string, string>,
95 comments: readonly string[] | undefined,
96 ): string[] => {
97 const marker = encodeOwnership(labels, undefined);
98 const rest = (comments ?? []).filter((comment) => !comment.startsWith("[alchemy "));
99 return [marker, ...rest];
100 };
101
102 export const parseComments = (
103 comments: readonly string[] | undefined,
104 ): {
105 labels: Record<string, string>;
106 comments: string[];
107 } => {
108 const list = [...(comments ?? [])];
109 const marked = list.find((comment) => comment.startsWith("[alchemy "));
110 const parsed = parseOwnership(marked);
111 return {
112 labels: parsed.labels,
113 comments: list.filter((comment) => !comment.startsWith("[alchemy ")),
114 };
115 };
116
117 export const commentsHaveOwnership = (comments: readonly string[] | undefined) =>
118 hasOwnershipMarker(comments?.find((comment) => comment.startsWith("[alchemy ")));
119
120 export type Attribute = {
121 name?: string;
122 value?: string;
123 };
124
125 const isAttributeObject = (
126 value: readonly Attribute[] | { attribute?: readonly Attribute[] },
127 ): value is { attribute?: readonly Attribute[] } => !Array.isArray(value);
128
129 const attributeList = (
130 value: readonly Attribute[] | { attribute?: readonly Attribute[] } | undefined,
131 ): Attribute[] => {
132 if (value === undefined) return [];
133 if (isAttributeObject(value)) return [...(value.attribute ?? [])];
134 return [...value];
135 };
136
137 export const fromAttributes = (
138 value: readonly Attribute[] | { attribute?: readonly Attribute[] } | undefined,
139 ): {
140 labels: Record<string, string>;
141 attributes: Record<string, string>;
142 } => {
143 const labels: Record<string, string> = {};
144 const attributes: Record<string, string> = {};
145 for (const item of attributeList(value)) {
146 if (item.name === undefined) continue;
147 const next = item.value ?? "";
148 if (item.name.startsWith("alchemy-")) labels[item.name] = next;
149 else attributes[item.name] = next;
150 }
151 return { labels, attributes };
152 };
153
154 const isAttributeArray = (
155 value: Record<string, string> | readonly Attribute[],
156 ): value is readonly Attribute[] => Array.isArray(value);
157
158 export const toAttributes = (
159 ownership: Record<string, string>,
160 user?: Record<string, string> | readonly Attribute[],
161 ): Attribute[] => {
162 const record =
163 user === undefined ? {} : isAttributeArray(user) ? fromAttributes(user).attributes : user;
164 return Object.entries({ ...record, ...ownership }).map(([name, value]) => ({
165 name,
166 value,
167 }));
168 };
169
170 export const userAttributeList = (
171 value: readonly Attribute[] | { attribute?: readonly Attribute[] } | undefined,
172 ): Attribute[] =>
173 Object.entries(fromAttributes(value).attributes).map(([name, value]) => ({
174 name,
175 value,
176 }));
177
178 const OWNERSHIP_EXTENSION = "alchown";
179
180 const sanitizeHostname = (value: string) =>
181 value.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "x";
182
183 export const withOwnershipExtension = (
184 labels: Record<string, string>,
185 extensions: readonly apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension[] | undefined,
186 ): apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension[] => [
187 {
188 name: OWNERSHIP_EXTENSION,
189 hostname: [
190 sanitizeHostname(labels[alchemyLabelKeys.stack] ?? "stack"),
191 sanitizeHostname(labels[alchemyLabelKeys.stage] ?? "stage"),
192 sanitizeHostname(labels[alchemyLabelKeys.id] ?? "id"),
193 ].join("."),
194 matchCondition: "false",
195 },
196 ...(extensions ?? []).filter((extension) => extension.name !== OWNERSHIP_EXTENSION),
197 ];
198
199 export const parseOwnershipExtension = (
200 extensions: readonly apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension[] | undefined,
201 ): Record<string, string> => {
202 const found = (extensions ?? []).find((extension) => extension.name === OWNERSHIP_EXTENSION);
203 if (found?.hostname === undefined) return {};
204 const [stack, stage, ...idParts] = found.hostname.split(".");
205 if (stack === undefined || stage === undefined || idParts.length === 0) {
206 return {};
207 }
208 return {
209 [alchemyLabelKeys.stack]: stack,
210 [alchemyLabelKeys.stage]: stage,
211 [alchemyLabelKeys.id]: idParts.join("."),
212 };
213 };
214
215 export const hasOwnershipExtension = (
216 extensions: readonly apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension[] | undefined,
217 ) => (extensions ?? []).some((extension) => extension.name === OWNERSHIP_EXTENSION);
218
219 export const stripOwnershipExtension = (
220 extensions: readonly apigee.GoogleCloudApigeeV1ApimServiceExtensionExtension[] | undefined,
221 ) => (extensions ?? []).filter((extension) => extension.name !== OWNERSHIP_EXTENSION);