@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/LICENSE +201 -0
- package/README.md +136 -1
- package/dist/cli.d.ts +148 -0
- package/dist/cli.js +282 -0
- package/dist/diagnostics-DTMZy54f.js +48 -0
- package/dist/index.d.ts +157 -0
- package/dist/index.js +321 -0
- package/dist/vue.d.ts +54 -0
- package/dist/vue.js +79 -0
- package/package.json +74 -9
package/dist/index.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { t as choicesDiagnostics } from "./diagnostics-DTMZy54f.js";
|
|
2
|
+
import { ask, askWithModel } from "@vite-hub/gateways";
|
|
3
|
+
import { getPublicAiGatewayDiagnostic } from "@vite-hub/gateways/internal";
|
|
4
|
+
//#region src/choices.ts
|
|
5
|
+
const defaultLimits = {
|
|
6
|
+
groups: 40,
|
|
7
|
+
options: 100,
|
|
8
|
+
text: 300,
|
|
9
|
+
totalOptions: 100
|
|
10
|
+
};
|
|
11
|
+
const defaultThresholds = {
|
|
12
|
+
option: .5,
|
|
13
|
+
supported: .6
|
|
14
|
+
};
|
|
15
|
+
/** The label of "no option" in a single group. Option labels cannot use it. */
|
|
16
|
+
const noneLabel = "(none)";
|
|
17
|
+
const includeCriteria = "Choose include when the text names this option or clearly refers to it by a common abbreviation, code, partial name, spelling error, synonym, prefix, or suffix. Match the closest specific option. Partial text alone is not permission to include neighboring options. Match each requested option independently.";
|
|
18
|
+
const excludeCriteria = "Choose exclude only when the text directly says to omit this option, for example with except, without, not, or exclude. A negated family, prefix, or suffix excludes every matching option.";
|
|
19
|
+
const noneCriteria = "Choose none when the text does not mention this option. Do not infer options from context or from other options. Unspecified options stay none even when another option is included or excluded.";
|
|
20
|
+
const supportedTrue = "Every constraint in the text can be expressed with the listed options, including several options in one group, constraints across groups, exclusions, and a prefix or suffix that matches several options. Accept fragments, omitted group names, shorthand, and typos when a real option matches.";
|
|
21
|
+
const supportedFalse = "The text needs a value or a capability that the options do not have, such as a numeric comparison, an unknown name, or OR between different groups. Also false when the text names no option at all. Do not reject a recognizable option because of shorthand or a minor typo.";
|
|
22
|
+
function define(message) {
|
|
23
|
+
throw choicesDiagnostics.DECISIONS_R0001({ message: `[vitehub] ${message}` });
|
|
24
|
+
}
|
|
25
|
+
function fail(code, message) {
|
|
26
|
+
return choicesDiagnostics[code]({ message: `[vitehub] ${message}` });
|
|
27
|
+
}
|
|
28
|
+
/** Exposes trusted gateway diagnostics while keeping unknown failures in `cause`. */
|
|
29
|
+
function gatewayFailed(cause) {
|
|
30
|
+
const diagnostic = getPublicAiGatewayDiagnostic(cause);
|
|
31
|
+
return choicesDiagnostics.DECISIONS_R0005({
|
|
32
|
+
cause,
|
|
33
|
+
fix: diagnostic?.fix,
|
|
34
|
+
reason: diagnostic?.message.replace(/^\[vitehub\]\s*/, "")
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function probability(value) {
|
|
38
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;
|
|
39
|
+
}
|
|
40
|
+
/** Checks the definition and returns what answers the questions: the gateway, or the model through `askWithModel()`. */
|
|
41
|
+
function checkDefinition(definition, limits, thresholds) {
|
|
42
|
+
const { gateway, model } = definition;
|
|
43
|
+
if (gateway === void 0 === (model === void 0)) define("defineChoices() needs one of gateway or model: a gateway with ask(), such as vercel() from vite-hub/gateways, or an AI SDK model.");
|
|
44
|
+
if (model === void 0 && typeof gateway?.ask !== "function") define("defineChoices() needs a gateway with ask(), such as typesafe() or vercel() from vite-hub/gateways.");
|
|
45
|
+
const entries = Object.entries(definition.groups ?? {});
|
|
46
|
+
if (!entries.length) define("defineChoices() needs at least one group.");
|
|
47
|
+
if (entries.length > limits.groups) define(`defineChoices() has ${entries.length} groups. The limit is ${limits.groups}.`);
|
|
48
|
+
for (const [key, group] of entries) {
|
|
49
|
+
if (typeof group?.label !== "string" || !group.label.trim()) define(`Group "${key}" needs a label.`);
|
|
50
|
+
if (!Array.isArray(group.options) && typeof group.options !== "function") define(`Group "${key}" options must be a list or a function.`);
|
|
51
|
+
if (group.multiple !== void 0 && typeof group.multiple !== "boolean") define(`Group "${key}" multiple must be true or false.`);
|
|
52
|
+
if (group.infer !== void 0 && typeof group.infer !== "boolean") define(`Group "${key}" infer must be true or false.`);
|
|
53
|
+
if (group.infer && group.multiple !== false) define(`Group "${key}" infers one option, so it needs multiple: false.`);
|
|
54
|
+
}
|
|
55
|
+
for (const [name, value] of Object.entries(thresholds)) if (!Number.isFinite(value) || value < 0 || value > 1) define(`thresholds.${name} must be a number from 0 to 1.`);
|
|
56
|
+
for (const [name, value] of Object.entries(limits)) if (!Number.isInteger(value) || value < 1) define(`limits.${name} must be a positive integer.`);
|
|
57
|
+
return model === void 0 ? gateway : askWithModel(model);
|
|
58
|
+
}
|
|
59
|
+
async function loadGroups(definition, limits, context) {
|
|
60
|
+
const keys = Object.keys(definition.groups);
|
|
61
|
+
const loaded = [];
|
|
62
|
+
let total = 0;
|
|
63
|
+
for (const key of keys) {
|
|
64
|
+
const group = definition.groups[key];
|
|
65
|
+
let options;
|
|
66
|
+
try {
|
|
67
|
+
options = typeof group.options === "function" ? await group.options(context) : group.options;
|
|
68
|
+
} catch (cause) {
|
|
69
|
+
return { error: choicesDiagnostics.DECISIONS_R0002({
|
|
70
|
+
message: `[vitehub] The options of group "${key}" failed to load.`,
|
|
71
|
+
cause
|
|
72
|
+
}) };
|
|
73
|
+
}
|
|
74
|
+
if (options.length > limits.options) return { error: fail("DECISIONS_R0002", `Group "${key}" has ${options.length} options. The limit is ${limits.options}. Narrow the options before you ask.`) };
|
|
75
|
+
const multiple = group.multiple !== false;
|
|
76
|
+
const values = /* @__PURE__ */ new Set();
|
|
77
|
+
const labels = /* @__PURE__ */ new Set();
|
|
78
|
+
for (const option of options) {
|
|
79
|
+
if (typeof option.label !== "string" || !option.label.trim()) return { error: fail("DECISIONS_R0002", `An option of group "${key}" has no label.`) };
|
|
80
|
+
if (option.description !== void 0 && typeof option.description !== "string") return { error: fail("DECISIONS_R0002", `The option "${option.label}" of group "${key}" has a description that is not text.`) };
|
|
81
|
+
if (values.has(option.value)) return { error: fail("DECISIONS_R0002", `Group "${key}" has the value ${JSON.stringify(option.value)} twice. Values must be unique within a group.`) };
|
|
82
|
+
values.add(option.value);
|
|
83
|
+
if (!multiple) {
|
|
84
|
+
if (option.label === noneLabel || labels.has(option.label)) return { error: fail("DECISIONS_R0002", `Group "${key}" is single-select, so labels must be unique and cannot be "${noneLabel}". Found "${option.label}".`) };
|
|
85
|
+
labels.add(option.label);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
total += options.length;
|
|
89
|
+
loaded.push({
|
|
90
|
+
group,
|
|
91
|
+
infer: group.infer === true,
|
|
92
|
+
key,
|
|
93
|
+
multiple,
|
|
94
|
+
options
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (total === 0) return { error: fail("DECISIONS_R0002", "No group has options. Nothing can be asked.") };
|
|
98
|
+
if (total > limits.totalOptions) return { error: fail("DECISIONS_R0002", `The groups have ${total} options. The limit is ${limits.totalOptions}. Narrow the options before you ask.`) };
|
|
99
|
+
return { groups: loaded };
|
|
100
|
+
}
|
|
101
|
+
function describe(option) {
|
|
102
|
+
return option.aliases?.length ? `${option.label} (also ${option.aliases.map((alias) => JSON.stringify(alias)).join(", ")})` : option.label;
|
|
103
|
+
}
|
|
104
|
+
/** What the model reads about one option of a single group: its description and its aliases. */
|
|
105
|
+
function optionCriteria(option) {
|
|
106
|
+
const parts = [option.description?.trim(), option.aliases?.length ? `Also called ${option.aliases.join(", ")}.` : void 0].filter(Boolean);
|
|
107
|
+
return parts.length ? parts.join(" ") : null;
|
|
108
|
+
}
|
|
109
|
+
function optionInstructions(group, option, hints) {
|
|
110
|
+
return [
|
|
111
|
+
`For the ${JSON.stringify(group.group.label)} group, does the text directly request or directly negate the option ${JSON.stringify(describe(option))} (value ${JSON.stringify(option.value)})?`,
|
|
112
|
+
option.description?.trim() && `The option means: ${option.description.trim()}`,
|
|
113
|
+
"Evaluate this option separately from all others. A requested prefix or suffix applies to every matching option. If the text names a different group for a phrase, do not reuse that phrase to select this option.",
|
|
114
|
+
group.group.hints,
|
|
115
|
+
hints
|
|
116
|
+
].filter(Boolean).join(" ");
|
|
117
|
+
}
|
|
118
|
+
function singleInstructions(group, hints) {
|
|
119
|
+
if (group.infer) return [
|
|
120
|
+
`For the ${JSON.stringify(group.group.label)} group, which one option fits the text best?`,
|
|
121
|
+
"The text does not have to name the option. Infer it from what the text is about, every fact in the text, and the option descriptions. Prefer the most specific option that fits.",
|
|
122
|
+
group.group.hints,
|
|
123
|
+
hints
|
|
124
|
+
].filter(Boolean).join(" ");
|
|
125
|
+
return [
|
|
126
|
+
`For the ${JSON.stringify(group.group.label)} group, which one option does the text choose?`,
|
|
127
|
+
`Choose ${JSON.stringify(noneLabel)} when the text does not name an option of this group. Do not infer an option from context or from other groups.`,
|
|
128
|
+
group.group.hints,
|
|
129
|
+
hints
|
|
130
|
+
].filter(Boolean).join(" ");
|
|
131
|
+
}
|
|
132
|
+
/** The supported check covers the groups that do not infer. It is not asked when every group infers. */
|
|
133
|
+
function needsSupported(groups) {
|
|
134
|
+
return groups.some((group) => !group.infer && group.options.length);
|
|
135
|
+
}
|
|
136
|
+
/** Asks if the options can express the text. With `infer` groups, it judges only the other groups, and text that sets none of them is supported. */
|
|
137
|
+
function supportedQuestion(groups, hints) {
|
|
138
|
+
const checked = groups.filter((group) => !group.infer).map((group) => JSON.stringify(group.group.label));
|
|
139
|
+
if (checked.length === groups.length) return ask.chance(["Can all intended constraints in the text be expressed with the supplied options? Be permissive about ordinary phrasing, shorthand, prefixes, and typos, but require a real match to supplied options.", hints].filter(Boolean).join(" "), {
|
|
140
|
+
false: supportedFalse,
|
|
141
|
+
true: supportedTrue
|
|
142
|
+
});
|
|
143
|
+
return ask.chance([
|
|
144
|
+
`Judge only the ${checked.join(", ")} ${checked.length === 1 ? "group" : "groups"}. Ignore every group with infer: true.`,
|
|
145
|
+
"Can every constraint that the text sets for these groups be expressed with their options? Be permissive about ordinary phrasing, shorthand, prefixes, and typos, but require a real match to supplied options.",
|
|
146
|
+
hints
|
|
147
|
+
].filter(Boolean).join(" "), {
|
|
148
|
+
false: "The text needs a value or a capability that the options of these groups do not have, such as a numeric comparison, an unknown name, or OR between different groups. Do not reject a recognizable option because of shorthand or a minor typo.",
|
|
149
|
+
true: `${supportedTrue} Also true when the text sets no constraint for these groups.`
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
function buildPlan(text, groups, hints) {
|
|
153
|
+
const questions = {};
|
|
154
|
+
if (needsSupported(groups)) questions.supported = supportedQuestion(groups, hints);
|
|
155
|
+
groups.forEach((group, groupIndex) => {
|
|
156
|
+
if (!group.options.length) return;
|
|
157
|
+
if (group.infer && group.options.length === 1) return;
|
|
158
|
+
if (group.multiple) {
|
|
159
|
+
group.options.forEach((option, optionIndex) => {
|
|
160
|
+
questions[`g${groupIndex}_o${optionIndex}`] = ask.choice(optionInstructions(group, option, hints), {
|
|
161
|
+
exclude: excludeCriteria,
|
|
162
|
+
include: includeCriteria,
|
|
163
|
+
none: noneCriteria
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const criteria = Object.fromEntries(group.options.map((option) => [option.label, optionCriteria(option)]));
|
|
169
|
+
questions[`g${groupIndex}`] = ask.choice(singleInstructions(group, hints), group.infer ? criteria : {
|
|
170
|
+
...criteria,
|
|
171
|
+
[noneLabel]: "The text does not name an option of this group."
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
return {
|
|
175
|
+
questions,
|
|
176
|
+
state: {
|
|
177
|
+
groups: groups.map((group) => ({
|
|
178
|
+
...group.group.hints ? { hints: group.group.hints } : {},
|
|
179
|
+
...group.infer ? { infer: true } : {},
|
|
180
|
+
label: group.group.label,
|
|
181
|
+
multiple: group.multiple,
|
|
182
|
+
options: group.options.map((option) => ({
|
|
183
|
+
...option.aliases?.length ? { aliases: option.aliases } : {},
|
|
184
|
+
label: option.label,
|
|
185
|
+
value: option.value
|
|
186
|
+
}))
|
|
187
|
+
})),
|
|
188
|
+
query: text
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function readSelection(answers, groups, threshold) {
|
|
193
|
+
const selection = {};
|
|
194
|
+
for (const [groupIndex, group] of groups.entries()) {
|
|
195
|
+
if (!group.multiple) {
|
|
196
|
+
const answer = answers[`g${groupIndex}`];
|
|
197
|
+
if (!group.options.length) {
|
|
198
|
+
selection[group.key] = {
|
|
199
|
+
confidence: 0,
|
|
200
|
+
ranked: [],
|
|
201
|
+
value: null
|
|
202
|
+
};
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const [only] = group.options;
|
|
206
|
+
if (group.infer && only && group.options.length === 1) {
|
|
207
|
+
selection[group.key] = {
|
|
208
|
+
confidence: 1,
|
|
209
|
+
ranked: [{
|
|
210
|
+
probability: 1,
|
|
211
|
+
value: only.value
|
|
212
|
+
}],
|
|
213
|
+
value: only.value
|
|
214
|
+
};
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (typeof answer !== "object" || answer.type !== "choice") return [fail("DECISIONS_R0006", `The model did not answer the group "${group.key}".`)];
|
|
218
|
+
const byLabel = new Map(group.options.map((option) => [option.label, option.value]));
|
|
219
|
+
const ranked = [...byLabel].map(([label, value]) => ({
|
|
220
|
+
probability: probability(Reflect.get(answer.probabilities, label)),
|
|
221
|
+
value
|
|
222
|
+
})).sort((a, b) => b.probability - a.probability);
|
|
223
|
+
const best = ranked[0];
|
|
224
|
+
const chosen = answer.choice === noneLabel ? void 0 : byLabel.get(answer.choice);
|
|
225
|
+
selection[group.key] = {
|
|
226
|
+
confidence: probability(answer.confidence),
|
|
227
|
+
ranked,
|
|
228
|
+
value: chosen !== void 0 && best && probability(Reflect.get(answer.probabilities, answer.choice)) >= threshold ? chosen : null
|
|
229
|
+
};
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const include = [];
|
|
233
|
+
const exclude = [];
|
|
234
|
+
for (const [optionIndex, option] of group.options.entries()) {
|
|
235
|
+
const answer = answers[`g${groupIndex}_o${optionIndex}`];
|
|
236
|
+
if (typeof answer !== "object" || answer.type !== "choice") return [fail("DECISIONS_R0006", `The model did not answer the option "${option.label}" of group "${group.key}".`)];
|
|
237
|
+
if (answer.choice === "none" || probability(Reflect.get(answer.probabilities, answer.choice)) < threshold) continue;
|
|
238
|
+
if (answer.choice === "include") include.push(option.value);
|
|
239
|
+
else exclude.push(option.value);
|
|
240
|
+
}
|
|
241
|
+
selection[group.key] = {
|
|
242
|
+
exclude,
|
|
243
|
+
include
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
return [void 0, selection];
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Declares the options that text can choose from, and how to ask a gateway about them.
|
|
250
|
+
* Nothing here knows your UI, your routes, or your store. Call `resolve()` wherever you run server code.
|
|
251
|
+
*/
|
|
252
|
+
function defineChoices(definition) {
|
|
253
|
+
const limits = {
|
|
254
|
+
...defaultLimits,
|
|
255
|
+
...definition.limits
|
|
256
|
+
};
|
|
257
|
+
const thresholds = {
|
|
258
|
+
...defaultThresholds,
|
|
259
|
+
...definition.thresholds
|
|
260
|
+
};
|
|
261
|
+
const base = definition;
|
|
262
|
+
const asker = checkDefinition(base, limits, thresholds);
|
|
263
|
+
const hints = definition.hints?.trim() ?? "";
|
|
264
|
+
async function prepare(text, request) {
|
|
265
|
+
const trimmed = typeof text === "string" ? text.trim() : "";
|
|
266
|
+
if (!trimmed) return [fail("DECISIONS_R0003", "The text is empty. Nothing was asked.")];
|
|
267
|
+
if (trimmed.length > limits.text) return [fail("DECISIONS_R0003", `The text has ${trimmed.length} characters. The limit is ${limits.text}.`)];
|
|
268
|
+
const loaded = await loadGroups(base, limits, request?.context);
|
|
269
|
+
if ("error" in loaded) return [loaded.error];
|
|
270
|
+
return [void 0, {
|
|
271
|
+
groups: loaded.groups,
|
|
272
|
+
plan: buildPlan(trimmed, loaded.groups, hints),
|
|
273
|
+
text: trimmed
|
|
274
|
+
}];
|
|
275
|
+
}
|
|
276
|
+
return {
|
|
277
|
+
async inspect(text, ...args) {
|
|
278
|
+
const [error, prepared] = await prepare(text, args[0]);
|
|
279
|
+
return error ? [error] : [void 0, prepared.plan];
|
|
280
|
+
},
|
|
281
|
+
name: definition.name,
|
|
282
|
+
async resolve(text, ...args) {
|
|
283
|
+
const request = args[0];
|
|
284
|
+
const [error, prepared] = await prepare(text, request);
|
|
285
|
+
if (error) return [error];
|
|
286
|
+
let answers = {};
|
|
287
|
+
if (Object.keys(prepared.plan.questions).length) try {
|
|
288
|
+
const [askError, asked] = await asker.ask(prepared.plan.state, prepared.plan.questions, { signal: request?.signal });
|
|
289
|
+
if (askError) return [gatewayFailed(askError)];
|
|
290
|
+
answers = asked;
|
|
291
|
+
} catch (cause) {
|
|
292
|
+
return [gatewayFailed(cause)];
|
|
293
|
+
}
|
|
294
|
+
if (needsSupported(prepared.groups)) {
|
|
295
|
+
const supported = answers.supported;
|
|
296
|
+
if (typeof supported !== "object" || supported.type !== "chance") return [fail("DECISIONS_R0006", "The model did not answer the supported check.")];
|
|
297
|
+
if (probability(supported.chance) < thresholds.supported) return [fail("DECISIONS_R0004", "The options cannot express that text. Try another name, or use the options directly.")];
|
|
298
|
+
}
|
|
299
|
+
const [readError, selection] = readSelection(answers, prepared.groups, thresholds.option);
|
|
300
|
+
if (readError) return [readError];
|
|
301
|
+
return [void 0, selection];
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/options.ts
|
|
307
|
+
/** Maps your own items to options. This is the bridge from your data to Choices. */
|
|
308
|
+
function toOptions(items, map) {
|
|
309
|
+
return items.map((item) => {
|
|
310
|
+
const aliases = map.aliases?.(item);
|
|
311
|
+
const description = map.description?.(item)?.trim();
|
|
312
|
+
return {
|
|
313
|
+
label: map.label(item),
|
|
314
|
+
value: map.value(item),
|
|
315
|
+
...aliases?.length ? { aliases } : {},
|
|
316
|
+
...description ? { description } : {}
|
|
317
|
+
};
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
//#endregion
|
|
321
|
+
export { defineChoices, toOptions };
|
package/dist/vue.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Ref } from "vue";
|
|
2
|
+
//#region src/vue.d.ts
|
|
3
|
+
/** Any Choices object. Its `resolve()` parameters do not matter here. */
|
|
4
|
+
export interface ChoicesLike {
|
|
5
|
+
resolve: (text: never, ...args: never[]) => Promise<unknown>;
|
|
6
|
+
}
|
|
7
|
+
/** The selection that `resolve()` of a Choices object returns on success. Use it with `typeof yourChoices`. */
|
|
8
|
+
export type ChoicesSelectionOf<TChoices extends ChoicesLike> = Extract<Awaited<ReturnType<TChoices["resolve"]>>, readonly [undefined, unknown]>[1];
|
|
9
|
+
export type ChoicesStatus = "error" | "idle" | "ready" | "thinking";
|
|
10
|
+
export interface UseChoicesOptions<TSelection> {
|
|
11
|
+
/**
|
|
12
|
+
* Wait this many milliseconds after the last keystroke, then resolve. Leave it out to resolve only when you call
|
|
13
|
+
* `submit()`.
|
|
14
|
+
*/
|
|
15
|
+
debounce?: number;
|
|
16
|
+
/** The text must be at least this long before a debounced resolve runs. Defaults to `3`. */
|
|
17
|
+
minLength?: number;
|
|
18
|
+
/** Called by `clear()`, so you can reset your own state, such as the filters that the last selection set. */
|
|
19
|
+
onClear?: () => void;
|
|
20
|
+
/** Called with each new selection. Apply it to your own state here. */
|
|
21
|
+
onSelect?: (selection: TSelection) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Your bridge to the server: send the text, return the selection. Throw when the request fails.
|
|
24
|
+
* Pass `signal` to your request so a newer text can cancel an older one.
|
|
25
|
+
*/
|
|
26
|
+
resolve: (text: string, context: {
|
|
27
|
+
signal: AbortSignal;
|
|
28
|
+
}) => Promise<TSelection>;
|
|
29
|
+
}
|
|
30
|
+
export interface UseChoicesResult<TSelection> {
|
|
31
|
+
/** Cancels the pending request and goes back to `idle`. */
|
|
32
|
+
abort: () => void;
|
|
33
|
+
/** Clears the text, the selection, and the error. */
|
|
34
|
+
clear: () => void;
|
|
35
|
+
/** The error of the last request, or `undefined`. */
|
|
36
|
+
error: Readonly<Ref<Error | undefined>>;
|
|
37
|
+
/** The latest selection, or `undefined`. A newer request keeps it until it finishes. */
|
|
38
|
+
selection: Readonly<Ref<TSelection | undefined>>;
|
|
39
|
+
status: Readonly<Ref<ChoicesStatus>>;
|
|
40
|
+
/** Resolves the current text now. */
|
|
41
|
+
submit: () => Promise<void>;
|
|
42
|
+
/** Bind this to your input. */
|
|
43
|
+
text: Ref<string>;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Turns the text of an input into a selection through a function that you write. It owns the status, the debounce, and
|
|
47
|
+
* the cancelation of older requests. It does not know your server, your store, or your UI.
|
|
48
|
+
*
|
|
49
|
+
* Give the type of your Choices as the generic, for example `useChoices<typeof forecast>({ ... })`. Import it with
|
|
50
|
+
* `import type`, so no server code reaches the browser.
|
|
51
|
+
*/
|
|
52
|
+
export declare function useChoices<TChoices extends ChoicesLike>(options: UseChoicesOptions<ChoicesSelectionOf<TChoices>>): UseChoicesResult<ChoicesSelectionOf<TChoices>>;
|
|
53
|
+
export declare function useChoices<TSelection>(options: UseChoicesOptions<TSelection>): UseChoicesResult<TSelection>;
|
|
54
|
+
//#endregion
|
package/dist/vue.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { onScopeDispose, readonly, ref, watch } from "vue";
|
|
2
|
+
//#region src/vue.ts
|
|
3
|
+
function toError(value) {
|
|
4
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
5
|
+
}
|
|
6
|
+
function useChoices(options) {
|
|
7
|
+
const text = ref("");
|
|
8
|
+
const status = ref("idle");
|
|
9
|
+
const selection = ref();
|
|
10
|
+
const error = ref();
|
|
11
|
+
const minLength = options.minLength ?? 3;
|
|
12
|
+
let controller;
|
|
13
|
+
let timer;
|
|
14
|
+
function cancel() {
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
timer = void 0;
|
|
17
|
+
controller?.abort();
|
|
18
|
+
controller = void 0;
|
|
19
|
+
}
|
|
20
|
+
async function submit() {
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
timer = void 0;
|
|
23
|
+
const value = text.value.trim();
|
|
24
|
+
controller?.abort();
|
|
25
|
+
if (!value) {
|
|
26
|
+
controller = void 0;
|
|
27
|
+
status.value = "idle";
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const current = new AbortController();
|
|
31
|
+
controller = current;
|
|
32
|
+
status.value = "thinking";
|
|
33
|
+
error.value = void 0;
|
|
34
|
+
try {
|
|
35
|
+
const result = await options.resolve(value, { signal: current.signal });
|
|
36
|
+
if (current.signal.aborted) return;
|
|
37
|
+
selection.value = result;
|
|
38
|
+
status.value = "ready";
|
|
39
|
+
options.onSelect?.(result);
|
|
40
|
+
} catch (cause) {
|
|
41
|
+
if (current.signal.aborted) return;
|
|
42
|
+
error.value = toError(cause);
|
|
43
|
+
status.value = "error";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function abort() {
|
|
47
|
+
cancel();
|
|
48
|
+
status.value = "idle";
|
|
49
|
+
}
|
|
50
|
+
function clear() {
|
|
51
|
+
cancel();
|
|
52
|
+
text.value = "";
|
|
53
|
+
selection.value = void 0;
|
|
54
|
+
error.value = void 0;
|
|
55
|
+
status.value = "idle";
|
|
56
|
+
options.onClear?.();
|
|
57
|
+
}
|
|
58
|
+
if (options.debounce !== void 0) {
|
|
59
|
+
const delay = options.debounce;
|
|
60
|
+
watch(text, (value) => {
|
|
61
|
+
cancel();
|
|
62
|
+
if (status.value === "thinking") status.value = "idle";
|
|
63
|
+
if (value.trim().length < minLength) return;
|
|
64
|
+
timer = setTimeout(() => void submit(), delay);
|
|
65
|
+
}, { flush: "sync" });
|
|
66
|
+
}
|
|
67
|
+
onScopeDispose(cancel);
|
|
68
|
+
return {
|
|
69
|
+
abort,
|
|
70
|
+
clear,
|
|
71
|
+
error: readonly(error),
|
|
72
|
+
selection: readonly(selection),
|
|
73
|
+
status: readonly(status),
|
|
74
|
+
submit,
|
|
75
|
+
text
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { useChoices };
|
package/package.json
CHANGED
|
@@ -1,19 +1,84 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/choices",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Turn text into
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Turn text into choices over options that you declare: filters, search facets, command palettes, and builders on a TypeSafe Jev decision model.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ai",
|
|
7
|
+
"choices",
|
|
8
|
+
"filters",
|
|
9
|
+
"jev",
|
|
10
|
+
"search",
|
|
11
|
+
"typescript",
|
|
12
|
+
"vitehub"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://vitehub.dev",
|
|
15
|
+
"bugs": "https://github.com/vite-hub/vitehub/issues",
|
|
5
16
|
"license": "Apache-2.0",
|
|
6
17
|
"author": "onmax <maximogarciamtnez@gmail.com>",
|
|
7
|
-
"homepage": "https://vitehub.dev",
|
|
8
18
|
"repository": {
|
|
9
19
|
"type": "git",
|
|
10
20
|
"url": "git+https://github.com/vite-hub/vitehub.git",
|
|
11
21
|
"directory": "packages/choices"
|
|
12
22
|
},
|
|
13
|
-
"publishConfig": {
|
|
14
|
-
"access": "public"
|
|
15
|
-
},
|
|
16
23
|
"files": [
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
24
|
+
"dist",
|
|
25
|
+
"package.json"
|
|
26
|
+
],
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./cli": {
|
|
37
|
+
"types": "./dist/cli.d.ts",
|
|
38
|
+
"import": "./dist/cli.js",
|
|
39
|
+
"default": "./dist/cli.js"
|
|
40
|
+
},
|
|
41
|
+
"./vue": {
|
|
42
|
+
"types": "./dist/vue.d.ts",
|
|
43
|
+
"import": "./dist/vue.js",
|
|
44
|
+
"default": "./dist/vue.js"
|
|
45
|
+
},
|
|
46
|
+
"./package.json": "./package.json"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@vite-hub/gateways": "0.4.1",
|
|
50
|
+
"nostics": "1.4.0"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/node": "^24.19.1",
|
|
54
|
+
"@vite-hub/internal": "0.0.1",
|
|
55
|
+
"ai": "7.0.130",
|
|
56
|
+
"publint": "^0.3.25",
|
|
57
|
+
"typescript": "^6.0.3",
|
|
58
|
+
"vite": "^8.2.2",
|
|
59
|
+
"vite-plus": "^0.3.3",
|
|
60
|
+
"vitest": "^4.1.11",
|
|
61
|
+
"vue": "3.5.44"
|
|
62
|
+
},
|
|
63
|
+
"peerDependencies": {
|
|
64
|
+
"vite": ">=8.0.0",
|
|
65
|
+
"vue": "^3.5.0"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"vite": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"vue": {
|
|
72
|
+
"optional": true
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"engines": {
|
|
76
|
+
"node": ">=24.15.0"
|
|
77
|
+
},
|
|
78
|
+
"scripts": {
|
|
79
|
+
"build": "vp pack",
|
|
80
|
+
"dev": "vp pack --watch",
|
|
81
|
+
"typecheck": "vp run --cache -t @vite-hub/choices#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
|
|
82
|
+
"test": "vp run --cache -t @vite-hub/choices#build && vp test"
|
|
83
|
+
}
|
|
84
|
+
}
|