@vite-hub/choices 0.0.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,282 @@
1
+ import { t as choicesDiagnostics } from "./diagnostics-DTMZy54f.js";
2
+ import { readFile, readdir, stat } from "node:fs/promises";
3
+ import { relative, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ //#region ../internal/src/cli.ts
6
+ const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
7
+ const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
8
+ const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
9
+ const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
10
+ const stdoutRedirectGlobal = globalThis;
11
+ /**
12
+ * Sends `process.stdout` writes to stderr while `run` loads project config.
13
+ * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
14
+ */
15
+ async function withStdoutOnStderr(run, stderr = process.stderr) {
16
+ getStableStdoutWrite();
17
+ const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
18
+ let release;
19
+ stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
20
+ release = resolve;
21
+ });
22
+ await previous;
23
+ const write = process.stdout.write;
24
+ if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
25
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
26
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
27
+ }
28
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
29
+ process.stdout.write = ((chunk, encoding, callback) => {
30
+ const done = typeof encoding === "function" ? encoding : callback;
31
+ let called = false;
32
+ const onComplete = (error) => {
33
+ if (called) return;
34
+ called = true;
35
+ done?.(error);
36
+ };
37
+ const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
38
+ if (done && !called) {
39
+ if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
40
+ else if (stderr.write.length < 2) onComplete();
41
+ }
42
+ return result;
43
+ });
44
+ try {
45
+ return await run();
46
+ } finally {
47
+ process.stdout.write = write;
48
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
49
+ release();
50
+ }
51
+ }
52
+ /** Returns the unredirected process stdout writer for payload output. */
53
+ function getStableStdoutWrite() {
54
+ const current = process.stdout.write;
55
+ if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
56
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
57
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
58
+ }
59
+ return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
60
+ }
61
+ //#endregion
62
+ //#region ../internal/src/vite-stage.ts
63
+ /**
64
+ * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
65
+ * logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
66
+ */
67
+ function loadAllEnv(loadEnv, mode, envDir) {
68
+ const write = process.stderr.write;
69
+ process.stderr.write = () => true;
70
+ try {
71
+ return loadEnv(mode, envDir, "");
72
+ } finally {
73
+ process.stderr.write = write;
74
+ }
75
+ }
76
+ //#endregion
77
+ //#region src/cli.ts
78
+ const listUsage = "vitehub choices list [--json]";
79
+ const runUsage = "vitehub choices run <file> <text> [--export <name>] [--context <json>] [--inspect]";
80
+ const sourceExtensions = /\.(?:[cm]?[jt]s)$/;
81
+ const testFiles = /\.(?:test|spec)\.[cm]?[jt]s$/;
82
+ const skippedDirectories = /* @__PURE__ */ new Set([
83
+ "__tests__",
84
+ "build",
85
+ "coverage",
86
+ "dist",
87
+ "node_modules",
88
+ "test",
89
+ "tests"
90
+ ]);
91
+ const definesChoices = /\bdefineChoices\s*\(/;
92
+ function isChoices(value) {
93
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "resolve") === "function" && typeof Reflect.get(value, "inspect") === "function";
94
+ }
95
+ function choicesOf(module) {
96
+ return Object.entries(module).flatMap(([key, value]) => isChoices(value) ? [{
97
+ choices: value,
98
+ export: key,
99
+ name: value.name
100
+ }] : []);
101
+ }
102
+ /** Loads one file the way Vite loads server code, so TypeScript and extensionless imports work. */
103
+ async function loadModule(file, rootDir) {
104
+ const { runnerImport } = await import("vite");
105
+ const { module } = await runnerImport(file, {
106
+ configFile: false,
107
+ logLevel: "silent",
108
+ root: rootDir
109
+ });
110
+ return module;
111
+ }
112
+ /** Gateways read their keys from the environment. Add the project `.env` files without replacing set values. */
113
+ async function loadProjectEnv(context) {
114
+ const { loadEnv } = await import("vite");
115
+ const mode = context.env.NODE_ENV === "production" ? "production" : "development";
116
+ for (const [key, value] of Object.entries(loadAllEnv(loadEnv, mode, context.rootDir))) if (process.env[key] === void 0) process.env[key] = value;
117
+ }
118
+ async function findSourceFiles(directory, found = []) {
119
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
120
+ if (entry.name.startsWith(".") || skippedDirectories.has(entry.name)) continue;
121
+ const path = resolve(directory, entry.name);
122
+ if (entry.isDirectory()) await findSourceFiles(path, found);
123
+ else if (entry.isFile() && sourceExtensions.test(entry.name) && !testFiles.test(entry.name) && !entry.name.endsWith(".d.ts")) found.push(path);
124
+ }
125
+ return found;
126
+ }
127
+ /** Finds the files that name `defineChoices()`, then loads each one to read its exports. There is no registry. */
128
+ async function listChoices(rootDir) {
129
+ const listed = [];
130
+ for (const path of (await findSourceFiles(rootDir)).sort()) {
131
+ if (!definesChoices.test(await readFile(path, "utf8"))) continue;
132
+ const file = relative(rootDir, path);
133
+ try {
134
+ const choices = choicesOf(await loadModule(path, rootDir)).map(({ export: name, name: label }) => ({
135
+ export: name,
136
+ name: label
137
+ }));
138
+ if (choices.length) listed.push({
139
+ choices,
140
+ file
141
+ });
142
+ } catch (error) {
143
+ listed.push({
144
+ choices: [],
145
+ error: error instanceof Error ? error.message : String(error),
146
+ file
147
+ });
148
+ }
149
+ }
150
+ return listed;
151
+ }
152
+ function printTable(rows, stdout) {
153
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
154
+ for (const row of rows) stdout.write(`${row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()}\n`);
155
+ }
156
+ async function runList(args, context) {
157
+ const { values } = parseArgs({
158
+ args,
159
+ allowPositionals: false,
160
+ options: { json: { type: "boolean" } },
161
+ strict: true
162
+ });
163
+ const files = await withStdoutOnStderr(() => listChoices(context.rootDir), context.stderr);
164
+ if (values.json) {
165
+ context.stdout.write(`${JSON.stringify({ files }, null, 2)}\n`);
166
+ return files.some((file) => file.error) ? 1 : 0;
167
+ }
168
+ if (!files.length) {
169
+ context.stdout.write("No file exports the result of defineChoices().\n");
170
+ return 0;
171
+ }
172
+ const rows = [[
173
+ "FILE",
174
+ "EXPORT",
175
+ "NAME"
176
+ ]];
177
+ for (const file of files) if (file.error) rows.push([
178
+ file.file,
179
+ "!",
180
+ `failed to load: ${file.error.split("\n", 1)[0]}`
181
+ ]);
182
+ else for (const choices of file.choices) rows.push([
183
+ file.file,
184
+ choices.export,
185
+ choices.name ?? "-"
186
+ ]);
187
+ printTable(rows, context.stdout);
188
+ context.stdout.write(`\nRun one with: vitehub choices run ${files.find((file) => file.choices.length)?.file ?? "<file>"} "<text>"\n`);
189
+ return files.some((file) => file.error) ? 1 : 0;
190
+ }
191
+ function parseContext(value) {
192
+ if (value === void 0) return {};
193
+ try {
194
+ return { context: JSON.parse(value) };
195
+ } catch {
196
+ throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `--context must be JSON, such as '{"tenantId":"t1"}'.` });
197
+ }
198
+ }
199
+ function errorJson(error) {
200
+ return `${JSON.stringify({ error: {
201
+ code: error.code,
202
+ message: error.message
203
+ } }, null, 2)}\n`;
204
+ }
205
+ async function runOne(args, context) {
206
+ const { positionals, values } = parseArgs({
207
+ args,
208
+ allowPositionals: true,
209
+ options: {
210
+ context: { type: "string" },
211
+ export: { type: "string" },
212
+ inspect: { type: "boolean" }
213
+ },
214
+ strict: true
215
+ });
216
+ const [file, ...words] = positionals;
217
+ const text = words.join(" ");
218
+ if (!file || !text) throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `Give a file and a text. Usage: ${runUsage}` });
219
+ const request = parseContext(values.context);
220
+ const path = resolve(context.rootDir, file);
221
+ if (!(await stat(path).catch(() => void 0))?.isFile()) throw choicesDiagnostics.DECISIONS_CLI_CHOICES_NOT_FOUND({ problem: `${file} is not a file. Run vitehub choices list to find the files that call defineChoices().` });
222
+ const found = await withStdoutOnStderr(async () => {
223
+ await loadProjectEnv(context);
224
+ return choicesOf(await loadModule(path, context.rootDir));
225
+ }, context.stderr);
226
+ const names = found.map((item) => item.export).join(", ");
227
+ const chosen = values.export === void 0 ? found : found.filter((item) => item.export === values.export);
228
+ if (!found.length) throw choicesDiagnostics.DECISIONS_CLI_CHOICES_NOT_FOUND({ problem: `${file} has no export from defineChoices().` });
229
+ if (!chosen.length) throw choicesDiagnostics.DECISIONS_CLI_CHOICES_NOT_FOUND({ problem: `${file} has no export "${values.export}". Its exports from defineChoices() are: ${names}.` });
230
+ if (chosen.length > 1) throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `${file} has several exports from defineChoices(): ${names}. Pick one with --export.` });
231
+ const choices = chosen[0].choices;
232
+ const [error, data] = await withStdoutOnStderr(() => values.inspect ? choices.inspect(text, request) : choices.resolve(text, request), context.stderr);
233
+ if (error) {
234
+ context.stdout.write(errorJson(error));
235
+ return 1;
236
+ }
237
+ context.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
238
+ return 0;
239
+ }
240
+ /** The fix of a usage error of these commands, or `undefined` for another error. */
241
+ function cliFix(error) {
242
+ return choicesDiagnostics.is(error) && error.code.startsWith("DECISIONS_CLI_") ? error.fix : void 0;
243
+ }
244
+ function guard(usage, run) {
245
+ return async (args, context) => {
246
+ if (args.includes("-h") || args.includes("--help")) {
247
+ context.stdout.write(`Usage: ${usage}\n`);
248
+ return 0;
249
+ }
250
+ try {
251
+ return await run(args, context);
252
+ } catch (error) {
253
+ const fix = cliFix(error);
254
+ if (fix === void 0 && !(error instanceof TypeError && "code" in error)) throw error;
255
+ context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n${fix ? `Fix: ${fix}\n` : `Usage: ${usage}\n`}`);
256
+ return 1;
257
+ }
258
+ };
259
+ }
260
+ /**
261
+ * The `vitehub choices` commands. They load a Choices file by path and do not load the project config.
262
+ * `run` calls the gateway of the definition, so it reads the same keys as the app, from the shell or the `.env` files.
263
+ */
264
+ function createChoicesCliNamespace() {
265
+ return {
266
+ description: "List the Choices of the app and run one with a text. Does not load the project config.",
267
+ features: [{
268
+ description: "List the exports of defineChoices() results, by file.",
269
+ name: "list",
270
+ run: guard(listUsage, runList),
271
+ usage: listUsage
272
+ }, {
273
+ description: "Run one Choices definition with a text and print the selection as JSON. --inspect prints the questions without a model call.",
274
+ name: "run",
275
+ run: guard(runUsage, runOne),
276
+ usage: runUsage
277
+ }],
278
+ name: "choices"
279
+ };
280
+ }
281
+ //#endregion
282
+ export { createChoicesCliNamespace, listChoices };
@@ -0,0 +1,48 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const choicesDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: "https://vitehub.dev/docs/choices/diagnostics",
6
+ codes: {
7
+ /** A `defineChoices()` definition is invalid. It throws when you define it. */
8
+ DECISIONS_R0001: {
9
+ ...dynamicError,
10
+ fix: "Change the `defineChoices()` option that the message names: one of `gateway` with `ask()` or `model`, at least one group, a label on each group, and thresholds from 0 to 1."
11
+ },
12
+ /** The groups or options are over a limit, or an option is invalid. Nothing was asked. */
13
+ DECISIONS_R0002: {
14
+ ...dynamicError,
15
+ fix: "Use fewer options, a unique value and a label on each option, and an `options` function that does not throw. `error.cause` holds the error of a failed `options` function."
16
+ },
17
+ /** The text is empty or longer than `limits.text`. Nothing was asked. */
18
+ DECISIONS_R0003: {
19
+ ...dynamicError,
20
+ fix: "Pass `resolve()` a nonempty text no longer than `limits.text`."
21
+ },
22
+ /** The model says the options cannot express the text. The `supported` check is below its threshold. */
23
+ DECISIONS_R0004: {
24
+ ...dynamicError,
25
+ fix: "Show a message and let the person use your normal controls, or ask with a text that the options can express."
26
+ },
27
+ /** The gateway request failed. Only trusted gateway diagnostics supply a public reason and fix. */
28
+ DECISIONS_R0005: {
29
+ why: ({ reason }) => reason ? `[vitehub] The gateway request failed: ${reason}` : "[vitehub] The gateway request failed.",
30
+ fix: ({ fix }) => fix ?? "Read error.cause for the gateway error."
31
+ },
32
+ /** The model answer misses a question that was asked. */
33
+ DECISIONS_R0006: {
34
+ ...dynamicError,
35
+ fix: "Call `resolve()` again, because the model left a question without an answer. A retry often helps."
36
+ },
37
+ DECISIONS_CLI_ARGUMENTS_INVALID: {
38
+ why: ({ problem }) => problem,
39
+ fix: "Run `vitehub choices run <file> <text>`, pass `--context` as a JSON object, and pass `--export <name>` when the file has several `defineChoices()` exports."
40
+ },
41
+ DECISIONS_CLI_CHOICES_NOT_FOUND: {
42
+ why: ({ problem }) => problem,
43
+ fix: "Run `vitehub choices list` to find the files and exports that call `defineChoices()`, and pass one of them to `vitehub choices run`."
44
+ }
45
+ }
46
+ });
47
+ //#endregion
48
+ export { choicesDiagnostics as t };
@@ -0,0 +1,157 @@
1
+ import { AiGatewayAsk, AskModel } from "@vite-hub/gateways";
2
+ import { Diagnostic } from "nostics";
3
+ //#region src/types.d.ts
4
+ /** The value that you map back to your data. It must be unique within its group. */
5
+ type ChoiceValue = string | number;
6
+ /** One option of a group. `value` is yours, `label`, `aliases`, and `description` are what the model reads. */
7
+ interface ChoiceOption<TValue extends ChoiceValue = ChoiceValue> {
8
+ /** Other names for the option, such as codes, abbreviations, or translations. */
9
+ aliases?: readonly string[];
10
+ /** What the option is about. An `infer` group needs it to choose an option that the text does not name. */
11
+ description?: string;
12
+ /** What people call the option. */
13
+ label: string;
14
+ /** Your id for the option. It comes back in the selection. */
15
+ value: TValue;
16
+ }
17
+ type MaybePromise<T> = T | Promise<T>;
18
+ /** A set of options that belong to one decision, such as one filter. */
19
+ interface ChoiceGroup<TValue extends ChoiceValue = ChoiceValue> {
20
+ /** Tells the model how to read this group. Keep it short and specific to your data. */
21
+ hints?: string;
22
+ /**
23
+ * `false` (default): choose only an option that the text names. `true`: choose the option that fits the text best,
24
+ * also when the text does not name it, such as a project for a bug report. Needs `multiple: false`.
25
+ * An `infer` group has no "none" answer. Add an option for "anything else" if you need one.
26
+ */
27
+ infer?: boolean;
28
+ /** What people call the group, such as "Supplier". */
29
+ label: string;
30
+ /** `true` (default): any number of options, each included or excluded. `false`: at most one option. */
31
+ multiple?: boolean;
32
+ /** A list, or a function that loads the list for one request. Annotate the parameter of the function: its type is the `context` of `resolve()`. */
33
+ options: readonly ChoiceOption<TValue>[] | ((context: never) => MaybePromise<readonly ChoiceOption<TValue>[]>);
34
+ }
35
+ type ChoiceGroups = Record<string, ChoiceGroup>;
36
+ interface ChoicesLimits {
37
+ /** Most options in one group. Default 100. */
38
+ options: number;
39
+ /** Most groups. Default 40. */
40
+ groups: number;
41
+ /** Longest text in characters. Default 300. */
42
+ text: number;
43
+ /** Most options in all groups together. Default 100. */
44
+ totalOptions: number;
45
+ }
46
+ interface ChoicesThresholds {
47
+ /** The lowest probability that decides one option. Default 0.5. */
48
+ option?: number;
49
+ /** The lowest probability that the options can express the text. Default 0.6. Not asked when every group infers. */
50
+ supported?: number;
51
+ }
52
+ interface ChoicesDefinition<TGroups extends ChoiceGroups> {
53
+ /** Asks TypeSafe Jev, or any object with `ask()`: `typesafe()`, `vercel()`, or `cloudflare()` from `vite-hub/gateways`. Set `gateway` or `model`. */
54
+ gateway?: {
55
+ ask: AiGatewayAsk;
56
+ };
57
+ groups: TGroups;
58
+ /** Tells the model what the options are about. It is added to every question. */
59
+ hints?: string;
60
+ limits?: Partial<ChoicesLimits>;
61
+ /** Asks any AI SDK model instead of Jev, such as `openai("gpt-5.1-mini")`. It needs the `ai` package. Set `gateway` or `model`. */
62
+ model?: AskModel;
63
+ /** A label for logs and the CLI. It never connects anything. */
64
+ name?: string;
65
+ thresholds?: ChoicesThresholds;
66
+ }
67
+ type OptionValue<TOptions> = TOptions extends readonly ChoiceOption<infer TValue>[] ? TValue : TOptions extends ((context: never) => infer TResult) ? Awaited<TResult> extends readonly ChoiceOption<infer TValue>[] ? TValue : never : never;
68
+ type GroupValue<TGroup> = TGroup extends {
69
+ options: infer TOptions;
70
+ } ? OptionValue<TOptions> : never;
71
+ /** A group with `multiple` left as `true`: the options the text includes and excludes. */
72
+ interface MultipleSelection<TValue extends ChoiceValue = ChoiceValue> {
73
+ exclude: TValue[];
74
+ include: TValue[];
75
+ }
76
+ /** A group with `multiple: false`: the best option, or `null`, and every option by probability. */
77
+ interface SingleSelection<TValue extends ChoiceValue = ChoiceValue> {
78
+ /** How much the best option stands out, from 0 to 1. */
79
+ confidence: number;
80
+ /** Every option, from the most to the least likely. */
81
+ ranked: {
82
+ probability: number;
83
+ value: TValue;
84
+ }[];
85
+ /** The best option when it is above `thresholds.option`, else `null`. */
86
+ value: TValue | null;
87
+ }
88
+ /** The result for each group, typed from the options that you declared. */
89
+ type ChoicesSelection<TGroups> = { [K in keyof TGroups]: TGroups[K] extends {
90
+ multiple: false;
91
+ } ? SingleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>> : MultipleSelection<Extract<GroupValue<TGroups[K]>, ChoiceValue>>; };
92
+ /** A nostics error. Its `code` is one of `DECISIONS_R0001` to `DECISIONS_R0006`. */
93
+ type ChoicesError = Diagnostic;
94
+ type ChoicesResult<TData> = readonly [error: ChoicesError, data?: undefined] | readonly [error: undefined, data: TData];
95
+ interface ChoicesRequest<TContext> {
96
+ /** Passed to `options` functions. Put what they need here, such as the tenant. */
97
+ context: TContext;
98
+ /** Cancels the request to the gateway. */
99
+ signal?: AbortSignal;
100
+ }
101
+ /** What `resolve()` would send, without sending it. */
102
+ interface ChoicesPlan {
103
+ /** The questions for `gateway.ask()`. One per option of a multiple group, one per single group, and `supported` unless every group infers. */
104
+ questions: Record<string, unknown>;
105
+ /** The state for `gateway.ask()`. */
106
+ state: {
107
+ groups: {
108
+ hints?: string;
109
+ infer?: true;
110
+ label: string;
111
+ multiple: boolean;
112
+ options: {
113
+ aliases?: readonly string[];
114
+ label: string;
115
+ value: ChoiceValue;
116
+ }[];
117
+ }[];
118
+ query: string;
119
+ };
120
+ }
121
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
122
+ type OptionsContext<TGroup> = TGroup extends {
123
+ options: (context: infer TContext) => unknown;
124
+ } ? TContext : never;
125
+ /** The `context` that `resolve()` needs: the parameter types of the `options` functions of the groups. `unknown` when no group needs one. */
126
+ type GroupsContext<TGroups> = UnionToIntersection<{ [K in keyof TGroups]: OptionsContext<TGroups[K]>; }[keyof TGroups]>;
127
+ type ChoicesArgs<TContext> = unknown extends TContext ? [request?: {
128
+ signal?: AbortSignal;
129
+ }] : [request: ChoicesRequest<TContext> & {
130
+ context: TContext;
131
+ }];
132
+ interface Choices<TGroups extends ChoiceGroups> {
133
+ /** Shows the questions and the state that `resolve()` would send. Nothing leaves your server. */
134
+ inspect: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesPlan>>;
135
+ readonly name: string | undefined;
136
+ /** Asks the gateway which options the text names. It returns `[error, selection]` and never throws. */
137
+ resolve: (text: string, ...args: ChoicesArgs<GroupsContext<TGroups>>) => Promise<ChoicesResult<ChoicesSelection<TGroups>>>;
138
+ }
139
+ //#endregion
140
+ //#region src/choices.d.ts
141
+ /**
142
+ * Declares the options that text can choose from, and how to ask a gateway about them.
143
+ * Nothing here knows your UI, your routes, or your store. Call `resolve()` wherever you run server code.
144
+ */
145
+ export declare function defineChoices<const TGroups extends ChoiceGroups>(definition: ChoicesDefinition<TGroups>): Choices<TGroups>;
146
+ //#endregion
147
+ //#region src/options.d.ts
148
+ interface ToOptionsMap<TItem, TValue extends ChoiceValue> {
149
+ aliases?: (item: TItem) => readonly string[] | undefined;
150
+ description?: (item: TItem) => string | undefined;
151
+ label: (item: TItem) => string;
152
+ value: (item: TItem) => TValue;
153
+ }
154
+ /** Maps your own items to options. This is the bridge from your data to Choices. */
155
+ export declare function toOptions<TItem, TValue extends ChoiceValue>(items: readonly TItem[], map: ToOptionsMap<TItem, TValue>): ChoiceOption<TValue>[];
156
+ //#endregion
157
+ export type { ChoiceGroup, ChoiceGroups, ChoiceOption, ChoiceValue, Choices, ChoicesArgs, ChoicesDefinition, ChoicesError, ChoicesLimits, ChoicesPlan, ChoicesRequest, ChoicesResult, ChoicesSelection, ChoicesThresholds, GroupValue, GroupsContext, MultipleSelection, SingleSelection, ToOptionsMap };