@vite-hub/choices 0.0.0 → 0.5.0

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,279 @@
1
+ import { t as choicesDiagnostics } from "./diagnostics-BubnKF2J.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
+ async function loadModule(file, rootDir) {
103
+ const { runnerImport } = await import("vite");
104
+ const { module } = await runnerImport(file, {
105
+ configFile: false,
106
+ logLevel: "silent",
107
+ root: rootDir
108
+ });
109
+ return module;
110
+ }
111
+ async function loadProjectEnv(context) {
112
+ const { loadEnv } = await import("vite");
113
+ const mode = context.env.NODE_ENV === "production" ? "production" : "development";
114
+ for (const [key, value] of Object.entries(loadAllEnv(loadEnv, mode, context.rootDir))) if (process.env[key] === void 0) process.env[key] = value;
115
+ }
116
+ async function findSourceFiles(directory, found = []) {
117
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
118
+ if (entry.name.startsWith(".") || skippedDirectories.has(entry.name)) continue;
119
+ const path = resolve(directory, entry.name);
120
+ if (entry.isDirectory()) await findSourceFiles(path, found);
121
+ else if (entry.isFile() && sourceExtensions.test(entry.name) && !testFiles.test(entry.name) && !entry.name.endsWith(".d.ts")) found.push(path);
122
+ }
123
+ return found;
124
+ }
125
+ /** Finds the files that name `defineChoices()`, then loads each one to read its exports. There is no registry. */
126
+ async function listChoices(rootDir) {
127
+ const listed = [];
128
+ for (const path of (await findSourceFiles(rootDir)).sort()) {
129
+ if (!definesChoices.test(await readFile(path, "utf8"))) continue;
130
+ const file = relative(rootDir, path);
131
+ try {
132
+ const choices = choicesOf(await loadModule(path, rootDir)).map(({ export: name, name: label }) => ({
133
+ export: name,
134
+ name: label
135
+ }));
136
+ if (choices.length) listed.push({
137
+ choices,
138
+ file
139
+ });
140
+ } catch (error) {
141
+ listed.push({
142
+ choices: [],
143
+ error: error instanceof Error ? error.message : String(error),
144
+ file
145
+ });
146
+ }
147
+ }
148
+ return listed;
149
+ }
150
+ function printTable(rows, stdout) {
151
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
152
+ for (const row of rows) stdout.write(`${row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()}\n`);
153
+ }
154
+ async function runList(args, context) {
155
+ const { values } = parseArgs({
156
+ args,
157
+ allowPositionals: false,
158
+ options: { json: { type: "boolean" } },
159
+ strict: true
160
+ });
161
+ const files = await withStdoutOnStderr(() => listChoices(context.rootDir), context.stderr);
162
+ if (values.json) {
163
+ context.stdout.write(`${JSON.stringify({ files }, null, 2)}\n`);
164
+ return files.some((file) => file.error) ? 1 : 0;
165
+ }
166
+ if (!files.length) {
167
+ context.stdout.write("No file exports the result of defineChoices().\n");
168
+ return 0;
169
+ }
170
+ const rows = [[
171
+ "FILE",
172
+ "EXPORT",
173
+ "NAME"
174
+ ]];
175
+ for (const file of files) if (file.error) rows.push([
176
+ file.file,
177
+ "!",
178
+ `failed to load: ${file.error.split("\n", 1)[0]}`
179
+ ]);
180
+ else for (const choices of file.choices) rows.push([
181
+ file.file,
182
+ choices.export,
183
+ choices.name ?? "-"
184
+ ]);
185
+ printTable(rows, context.stdout);
186
+ context.stdout.write(`\nRun one with: vitehub choices run ${files.find((file) => file.choices.length)?.file ?? "<file>"} "<text>"\n`);
187
+ return files.some((file) => file.error) ? 1 : 0;
188
+ }
189
+ function parseContext(value) {
190
+ if (value === void 0) return {};
191
+ try {
192
+ return { context: JSON.parse(value) };
193
+ } catch {
194
+ throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `--context must be JSON, such as '{"tenantId":"t1"}'.` });
195
+ }
196
+ }
197
+ function errorJson(error) {
198
+ return `${JSON.stringify({ error: {
199
+ code: error.code,
200
+ message: error.message
201
+ } }, null, 2)}\n`;
202
+ }
203
+ async function runOne(args, context) {
204
+ const { positionals, values } = parseArgs({
205
+ args,
206
+ allowPositionals: true,
207
+ options: {
208
+ context: { type: "string" },
209
+ export: { type: "string" },
210
+ inspect: { type: "boolean" }
211
+ },
212
+ strict: true
213
+ });
214
+ const [file, ...words] = positionals;
215
+ const text = words.join(" ");
216
+ if (!file || !text) throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `Give a file and a text. Usage: ${runUsage}` });
217
+ const request = parseContext(values.context);
218
+ const path = resolve(context.rootDir, file);
219
+ 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().` });
220
+ const found = await withStdoutOnStderr(async () => {
221
+ await loadProjectEnv(context);
222
+ return choicesOf(await loadModule(path, context.rootDir));
223
+ }, context.stderr);
224
+ const names = found.map((item) => item.export).join(", ");
225
+ const chosen = values.export === void 0 ? found : found.filter((item) => item.export === values.export);
226
+ if (!found.length) throw choicesDiagnostics.DECISIONS_CLI_CHOICES_NOT_FOUND({ problem: `${file} has no export from defineChoices().` });
227
+ if (!chosen.length) throw choicesDiagnostics.DECISIONS_CLI_CHOICES_NOT_FOUND({ problem: `${file} has no export "${values.export}". Its exports from defineChoices() are: ${names}.` });
228
+ if (chosen.length > 1) throw choicesDiagnostics.DECISIONS_CLI_ARGUMENTS_INVALID({ problem: `${file} has several exports from defineChoices(): ${names}. Pick one with --export.` });
229
+ const choices = chosen[0].choices;
230
+ const [error, data] = await withStdoutOnStderr(() => values.inspect ? choices.inspect(text, request) : choices.resolve(text, request), context.stderr);
231
+ if (error) {
232
+ context.stdout.write(errorJson(error));
233
+ return 1;
234
+ }
235
+ context.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
236
+ return 0;
237
+ }
238
+ function cliFix(error) {
239
+ return choicesDiagnostics.is(error) && error.code.startsWith("DECISIONS_CLI_") ? error.fix : void 0;
240
+ }
241
+ function guard(usage, run) {
242
+ return async (args, context) => {
243
+ if (args.includes("-h") || args.includes("--help")) {
244
+ context.stdout.write(`Usage: ${usage}\n`);
245
+ return 0;
246
+ }
247
+ try {
248
+ return await run(args, context);
249
+ } catch (error) {
250
+ const fix = cliFix(error);
251
+ if (fix === void 0 && !(error instanceof TypeError && "code" in error)) throw error;
252
+ context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n${fix ? `Fix: ${fix}\n` : `Usage: ${usage}\n`}`);
253
+ return 1;
254
+ }
255
+ };
256
+ }
257
+ /**
258
+ * The `vitehub choices` commands. They load a Choices file by path and do not load the project config.
259
+ * `run` calls the gateway of the definition, so it reads the same keys as the app, from the shell or the `.env` files.
260
+ */
261
+ function createChoicesCliNamespace() {
262
+ return {
263
+ description: "List the Choices of the app and run one with a text. Does not load the project config.",
264
+ features: [{
265
+ description: "List the exports of defineChoices() results, by file.",
266
+ name: "list",
267
+ run: guard(listUsage, runList),
268
+ usage: listUsage
269
+ }, {
270
+ description: "Run one Choices definition with a text and print the selection as JSON. --inspect prints the questions without a model call.",
271
+ name: "run",
272
+ run: guard(runUsage, runOne),
273
+ usage: runUsage
274
+ }],
275
+ name: "choices"
276
+ };
277
+ }
278
+ //#endregion
279
+ export { createChoicesCliNamespace, listChoices };
@@ -0,0 +1,46 @@
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
+ DECISIONS_R0001: {
8
+ ...dynamicError,
9
+ 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."
10
+ },
11
+ DECISIONS_R0002: {
12
+ ...dynamicError,
13
+ fix: "Use fewer options, a list of option objects with a label and a unique text or finite number value, aliases as a list of text, and an `options` function that does not throw. `error.cause` holds the error of a failed `options` function."
14
+ },
15
+ DECISIONS_R0003: {
16
+ ...dynamicError,
17
+ fix: "Pass `resolve()` a nonempty text no longer than `limits.text`."
18
+ },
19
+ DECISIONS_R0004: {
20
+ ...dynamicError,
21
+ fix: "Show a message and let the person use your normal controls, or ask with a text that the options can express."
22
+ },
23
+ DECISIONS_R0005: {
24
+ why: ({ reason }) => reason ? `[vitehub] The gateway request failed: ${reason}` : "[vitehub] The gateway request failed.",
25
+ fix: ({ fix }) => fix ?? "Read error.cause for the gateway error."
26
+ },
27
+ DECISIONS_R0006: {
28
+ ...dynamicError,
29
+ fix: "Call `resolve()` again, because the model left a question without an answer. A retry often helps."
30
+ },
31
+ DECISIONS_CLI_ARGUMENTS_INVALID: {
32
+ why: ({ problem }) => problem,
33
+ fix: "Run `vitehub choices run <file> <text>`, pass `--context` as a JSON object, and pass `--export <name>` when the file has several `defineChoices()` exports."
34
+ },
35
+ DECISIONS_CLI_CHOICES_NOT_FOUND: {
36
+ why: ({ problem }) => problem,
37
+ fix: "Run `vitehub choices list` to find the files and exports that call `defineChoices()`, and pass one of them to `vitehub choices run`."
38
+ },
39
+ DECISIONS_TESTING_SELECTION_INVALID: {
40
+ why: ({ problem }) => `[vitehub] ${problem}`,
41
+ fix: "Pass `selectionGateway()` as the `gateway` of `defineChoices()`. Name only its groups: an option value or `null` for a group with `multiple: false`, and `{ include, exclude }` with option values for the other groups."
42
+ }
43
+ }
44
+ });
45
+ //#endregion
46
+ export { choicesDiagnostics as t };
@@ -0,0 +1,19 @@
1
+ import { _ as MultipleSelection, a as Choices, c as ChoicesError, d as ChoicesRequest, f as ChoicesResult, g as GroupsContext, h as GroupValue, i as ChoiceValue, l as ChoicesLimits, m as ChoicesThresholds, n as ChoiceGroups, o as ChoicesArgs, p as ChoicesSelection, r as ChoiceOption, s as ChoicesDefinition, t as ChoiceGroup, u as ChoicesPlan, v as SingleSelection } from "./types-slPoBTpx.js";
2
+ //#region src/choices.d.ts
3
+ /**
4
+ * Declares the options that text can choose from, and how to ask a gateway about them.
5
+ * Nothing here knows your UI, your routes, or your store. Call `resolve()` wherever you run server code.
6
+ */
7
+ export declare function defineChoices<const TGroups extends ChoiceGroups>(definition: ChoicesDefinition<TGroups>): Choices<TGroups>;
8
+ //#endregion
9
+ //#region src/options.d.ts
10
+ interface ToOptionsMap<TItem, TValue extends ChoiceValue> {
11
+ aliases?: (item: TItem) => readonly string[] | undefined;
12
+ description?: (item: TItem) => string | undefined;
13
+ label: (item: TItem) => string;
14
+ value: (item: TItem) => TValue;
15
+ }
16
+ /** Maps your own items to options. This is the bridge from your data to Choices. */
17
+ export declare function toOptions<TItem, TValue extends ChoiceValue>(items: readonly TItem[], map: ToOptionsMap<TItem, TValue>): ChoiceOption<TValue>[];
18
+ //#endregion
19
+ export type { ChoiceGroup, ChoiceGroups, ChoiceOption, ChoiceValue, Choices, ChoicesArgs, ChoicesDefinition, ChoicesError, ChoicesLimits, ChoicesPlan, ChoicesRequest, ChoicesResult, ChoicesSelection, ChoicesThresholds, GroupValue, GroupsContext, MultipleSelection, SingleSelection, ToOptionsMap };