Debian Codegraph @

generators/src/keyvalue.ts

raw symbols SCIP
1 /** Suggestions to be displayed for keys or values */
2 export type KeyValueSuggestions =
3 | string[]
4 | Fig.Suggestion[]
5 | NonNullable<Fig.Generator["custom"]>;
6
7 /** @deprecated use `KeyValueSuggestions` */
8 export type Suggestions = KeyValueSuggestions;
9
10 export type CacheValue = boolean | "keys" | "values";
11
12 export interface ValueListInit {
13 /** String to use as the separator between keys and values */
14 delimiter?: string;
15
16 /** List of suggestions */
17 values?: KeyValueSuggestions;
18
19 /** Cache key and value suggestions */
20 cache?: boolean;
21
22 /** Insert the delimiter string after accepting a suggestion (default: false) */
23 insertDelimiter?: boolean;
24
25 /** Don't filter repeated values from suggestions (default: false) */
26 allowRepeatedValues?: boolean;
27 }
28
29 export interface KeyValueInit {
30 /** String to use as the separator between keys and values */
31 separator?: string;
32
33 /** List of key suggestions */
34 keys?: KeyValueSuggestions;
35
36 /** List of value suggestions */
37 values?: KeyValueSuggestions;
38
39 /** Cache key and value suggestions */
40 cache?: CacheValue;
41
42 /** Should the separator be inserted after a key? (default: true ) */
43 insertSeparator?: boolean;
44 }
45
46 export interface KeyValueListInit {
47 /** String to use as the separator between keys and values */
48 separator?: string;
49
50 /** String to use as the separator between key-value pairs */
51 delimiter?: string;
52
53 /** List of key suggestions */
54 keys?: KeyValueSuggestions;
55
56 /** List of value suggestions */
57 values?: KeyValueSuggestions;
58
59 /** Cache key and value suggestions */
60 cache?: CacheValue;
61
62 /** Should the separator be inserted after a key? (default: true ) */
63 insertSeparator?: boolean;
64
65 /** Insert the delimiter string after accepting a value suggestion (default: false) */
66 insertDelimiter?: boolean;
67
68 /** Don't filter repeated keys from suggestions (default: false) */
69 allowRepeatedKeys?: boolean;
70
71 /** Don't filter repeated values from suggestions (default: true) */
72 allowRepeatedValues?: boolean;
73 }
74
75 /** Cache of Fig suggestions using the string[]/Suggestion[]/function as a key */
76 const suggestionCache = new Map<KeyValueSuggestions, Fig.Suggestion[]>();
77
78 function appendToInsertValue(append: string, suggestions: Fig.Suggestion[]): Fig.Suggestion[] {
79 if (append.length === 0) {
80 return suggestions;
81 }
82 return suggestions.map((item) =>
83 item.insertValue ? item : { ...item, insertValue: item.name + append }
84 );
85 }
86
87 async function kvSuggestionsToFigSuggestions(
88 suggestions: KeyValueSuggestions,
89 append: string,
90 init: Parameters<NonNullable<Fig.Generator["custom"]>>
91 ): Promise<Fig.Suggestion[]> {
92 if (typeof suggestions === "function") {
93 const out = await suggestions(...init);
94 return appendToInsertValue(append, out);
95 }
96 if (typeof suggestions[0] === "string") {
97 const out = (suggestions as string[]).map((name) => ({ name }));
98 return appendToInsertValue(append, out);
99 }
100 return appendToInsertValue(append, suggestions as Fig.Suggestion[]);
101 }
102
103 async function getSuggestions(
104 suggestions: KeyValueSuggestions,
105 append: string,
106 useSuggestionCache: boolean,
107 init: Parameters<NonNullable<Fig.Generator["custom"]>>
108 ): Promise<Fig.Suggestion[]> {
109 if (useSuggestionCache || Array.isArray(suggestions)) {
110 let value = suggestionCache.get(suggestions);
111 if (value === undefined) {
112 value = await kvSuggestionsToFigSuggestions(suggestions, append, init);
113 suggestionCache.set(suggestions, value);
114 }
115 return value;
116 }
117 return kvSuggestionsToFigSuggestions(suggestions, append, init);
118 }
119
120 function shouldUseCache(isKey: boolean, cache: CacheValue) {
121 if (typeof cache === "string") {
122 return (isKey && cache === "keys") || (!isKey && cache === "values");
123 }
124 return cache;
125 }
126
127 /** Get the final index of any of the strings */
128 function lastIndexOf(haystack: string, ...needles: readonly string[]) {
129 return Math.max(...needles.map((needle) => haystack.lastIndexOf(needle)));
130 }
131
132 function removeRepeatSuggestions(
133 alreadyUsed: string[],
134 suggestions: readonly Fig.Suggestion[]
135 ): Fig.Suggestion[] {
136 const seen = new Set(alreadyUsed);
137 return suggestions.filter((suggestion) => {
138 if (typeof suggestion.name === "string") {
139 return !seen.has(suggestion.name);
140 }
141 return !suggestion.name?.some((name) => seen.has(name));
142 });
143 }
144
145 /**
146 * Create a generator that gives suggestions for val,val,... arguments. You
147 * can use a `string[]` or `Fig.Suggestion[]` for the values.
148 *
149 * You can set `cache: true` to enable caching results. The suggestions are cached
150 * globally using the function as a key, so enabling caching for any one generator
151 * will set the cache values for the functions for the entire spec. This behavior
152 * can be used to compose expensive generators without incurring a cost every time
153 * they're used.
154 *
155 * The primary use of this is to enable the same caching behavior as `keyValue`
156 * and `keyValueList`. If your goal is to create a $PATH-like value, use a generator
157 * object literal: `{ template: "filepaths", trigger: ":", getQueryTerm: ":" }`
158 */
159 export function valueList({
160 delimiter = ",",
161 values = [],
162 cache = false,
163 insertDelimiter = false,
164 allowRepeatedValues = false,
165 }: ValueListInit): Fig.Generator {
166 return {
167 trigger: (newToken, oldToken) =>
168 newToken.lastIndexOf(delimiter) !== oldToken.lastIndexOf(delimiter),
169
170 getQueryTerm: (token) => token.slice(token.lastIndexOf(delimiter) + delimiter.length),
171
172 custom: async (...init) => {
173 const out = await getSuggestions(values, insertDelimiter ? delimiter : "", cache, init);
174 if (allowRepeatedValues) {
175 return out;
176 }
177 const [tokens] = init;
178 const valuesInList = tokens[tokens.length - 1]?.split(delimiter);
179 return removeRepeatSuggestions(valuesInList, out);
180 },
181 };
182 }
183
184 /**
185 * Create a generator that gives suggestions for key=value arguments. You
186 * can use a `string[]` or `Fig.Suggestion[]` for the keys and values, or a
187 * function with the same signature as `Fig.Generator["custom"]`.
188 *
189 * You can set `cache: true` to enable caching results. The suggestions are cached
190 * globally using the function as a key, so enabling caching for any one generator
191 * will set the cache values for the functions for the entire spec. This behavior
192 * can be used to copmpose expensive key/value generators without incurring the
193 * initial cost every time they're used.
194 *
195 * Note that you should only cache generators that produce the same output regardless
196 * of their input. You can cache either the keys or values individually using `"keys"`
197 * or `"values"` as the `cache` property value.
198 *
199 * @example
200 *
201 * ```typescript
202 * // set-values a=1 b=3 c=2
203 * const spec: Fig.Spec = {
204 * name: "set-values",
205 * args: {
206 * name: "values",
207 * isVariadic: true,
208 * generators: keyValue({
209 * keys: ["a", "b", "c"],
210 * values: ["1", "2", "3"],
211 * }),
212 * },
213 * }
214 * ```
215 *
216 * @example The separator between keys and values can be customized (default: `=`)
217 *
218 * ```typescript
219 * // key1:value
220 * keyValue({
221 * separator: ":",
222 * keys: [
223 * { name: "key1", icon: "fig://icon?type=string" },
224 * { name: "key2", icon: "fig://icon?type=string" },
225 * ],
226 * }),
227 * ```
228 */
229 export function keyValue({
230 separator = "=",
231 keys = [],
232 values = [],
233 cache = false,
234 insertSeparator = true,
235 }: KeyValueInit): Fig.Generator {
236 return {
237 trigger: (newToken, oldToken) => newToken.indexOf(separator) !== oldToken.indexOf(separator),
238 getQueryTerm: (token) => token.slice(token.indexOf(separator) + 1),
239 custom: async (...init) => {
240 const [tokens] = init;
241 const finalToken = tokens[tokens.length - 1];
242 const isKey = !finalToken.includes(separator);
243 const suggestions = isKey ? keys : values;
244 const useCache = shouldUseCache(isKey, cache);
245 const append = isKey ? (insertSeparator ? separator : "") : "";
246 return getSuggestions(suggestions, append, useCache, init);
247 },
248 };
249 }
250
251 /**
252 * Create a generator that gives suggestions for `k=v,k=v,...` arguments. You
253 * can use a `string[]` or `Fig.Suggestion[]` for the keys and values, or a
254 * function with the same signature as `Fig.Generator["custom"]`
255 *
256 * You can set `cache: true` to enable caching results. The suggestions are cached
257 * globally using the function as a key, so enabling caching for any one generator
258 * will set the cache values for the functions for the entire spec. This behavior
259 * can be used to copmpose expensive key/value generators without incurring the
260 * initial cost every time they're used.
261 *
262 * Note that you should only cache generators that produce the same output regardless
263 * of their input. You can cache either the keys or values individually using `"keys"`
264 * or `"values"` as the `cache` property value.
265 *
266 * @example
267 *
268 * ```typescript
269 * // set-values a=1,b=3,c=2
270 * const spec: Fig.Spec = {
271 * name: "set-values",
272 * args: {
273 * name: "values",
274 * generators: keyValueList({
275 * keys: ["a", "b", "c"],
276 * values: ["1", "2", "3"],
277 * }),
278 * },
279 * }
280 * ```
281 *
282 * @example
283 *
284 * The separator between keys and values can be customized. It's `=` by
285 * default. You can also change the key/value pair delimiter, which is `,`
286 * by default.
287 *
288 * ```typescript
289 * // key1:value&key2:another
290 * keyValueList({
291 * separator: ":",
292 * delimiter: "&"
293 * keys: [
294 * { name: "key1", icon: "fig://icon?type=string" },
295 * { name: "key2", icon: "fig://icon?type=string" },
296 * ],
297 * }),
298 * ```
299 */
300 export function keyValueList({
301 separator = "=",
302 delimiter = ",",
303 keys = [],
304 values = [],
305 cache = false,
306 insertSeparator = true,
307 insertDelimiter = false,
308 allowRepeatedKeys = false,
309 allowRepeatedValues = true,
310 }: KeyValueListInit): Fig.Generator {
311 return {
312 trigger: (newToken, oldToken) => {
313 const newTokenIdx = lastIndexOf(newToken, separator, delimiter);
314 const oldTokenIdx = lastIndexOf(oldToken, separator, delimiter);
315 return newTokenIdx !== oldTokenIdx;
316 },
317 getQueryTerm: (token) => {
318 const index = lastIndexOf(token, separator, delimiter);
319 return token.slice(index + 1);
320 },
321 custom: async (...init) => {
322 const [tokens] = init;
323
324 const finalToken = tokens[tokens.length - 1];
325 const index = lastIndexOf(finalToken, separator, delimiter);
326 const isKey = index === -1 || finalToken.slice(index, index + separator.length) !== separator;
327
328 const suggestions = isKey ? keys : values;
329 const useCache = shouldUseCache(isKey, cache);
330 const append = isKey ? (insertSeparator ? separator : "") : insertDelimiter ? delimiter : "";
331 const out = await getSuggestions(suggestions, append, useCache, init);
332
333 if (isKey) {
334 if (allowRepeatedKeys) {
335 return out;
336 }
337 const existingKeys = finalToken
338 .split(delimiter)
339 .map((chunk) => chunk.slice(0, chunk.indexOf(separator)));
340 return removeRepeatSuggestions(existingKeys, out);
341 }
342
343 if (allowRepeatedValues) {
344 return out;
345 }
346 const existingValues = finalToken
347 .split(delimiter)
348 .map((chunk) => chunk.slice(chunk.indexOf(separator) + separator.length));
349 return removeRepeatSuggestions(existingValues, out);
350 },
351 };
352 }