@domain-first/project-structure 8.1.1 → 8.2.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.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/graph.js ADDED
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import node_fs from "node:fs";
4
+ import node_os from "node:os";
5
+ import node_path from "node:path";
6
+ import { parseArgs } from "node:util";
7
+ import { File, ProjectRoot, outdatedConfigMessage, ConfigFile } from "./870.js";
8
+ import { readAliases, resolveSpecifier } from "./38.js";
9
+ import { namedImportFiles, wiring_layers, findWiredModules, wiredDependencyNames } from "./201.js";
10
+ const sharedKernel = 'shared-kernel';
11
+ const contextsOf = (contextsFolder)=>node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
12
+ withFileTypes: true
13
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
14
+ const projectGraph = (projectRoot, rootFolder)=>{
15
+ const root = node_path.resolve(projectRoot, rootFolder);
16
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
17
+ const owners = [
18
+ sharedKernel,
19
+ ...contextsOf(contextsFolder)
20
+ ];
21
+ const ownerPath = (owner)=>owner === sharedKernel ? node_path.join(root, sharedKernel) : node_path.join(contextsFolder, owner);
22
+ const byWireFile = new Map();
23
+ const wired = [];
24
+ for (const owner of owners)for (const module of findWiredModules(ownerPath(owner))){
25
+ const node = {
26
+ id: `${owner}:${module.typeName}`,
27
+ owner,
28
+ typeName: module.typeName,
29
+ layer: module.layer,
30
+ implementations: module.implementations.map(({ className })=>className)
31
+ };
32
+ byWireFile.set(module.wireFile, node);
33
+ wired.push([
34
+ module,
35
+ node
36
+ ]);
37
+ }
38
+ const aliases = readAliases(projectRoot);
39
+ const edges = [];
40
+ for (const [module, node] of wired){
41
+ const source = new File(module.wireFile).data;
42
+ const imported = namedImportFiles(source, module.wireFile, (specifier, file)=>resolveSpecifier(specifier, file, aliases));
43
+ for (const { className } of module.implementations)for (const name of wiredDependencyNames(source, className)){
44
+ const file = imported.get(name);
45
+ const target = file && byWireFile.get(file);
46
+ if (target) edges.push({
47
+ from: node.id,
48
+ to: target.id,
49
+ implementation: className
50
+ });
51
+ }
52
+ }
53
+ return {
54
+ owners,
55
+ modules: wired.map(([, node])=>node),
56
+ edges
57
+ };
58
+ };
59
+ const sanitize = (value)=>value.replace(/[^A-Za-z0-9]/g, '_');
60
+ const quoted = (value)=>`"${value.replace(/"/g, '#quot;')}"`;
61
+ const ownerOf = (graph, id)=>graph.modules.find((module)=>module.id === id)?.owner;
62
+ const typeOf = (graph, id)=>graph.modules.find((module)=>module.id === id)?.typeName ?? id;
63
+ const contextMap = (graph, idPrefix = '')=>{
64
+ const nodeId = (value)=>`${idPrefix}${sanitize(value)}`;
65
+ const links = new Map();
66
+ for (const edge of graph.edges){
67
+ const from = ownerOf(graph, edge.from);
68
+ const to = ownerOf(graph, edge.to);
69
+ if (!from || !to || from === to) continue;
70
+ const key = `${from}\u0000${to}`;
71
+ const set = links.get(key) ?? new Set();
72
+ set.add(to === sharedKernel ? typeOf(graph, edge.to) : `${typeOf(graph, edge.from)} → ${typeOf(graph, edge.to)}`);
73
+ links.set(key, set);
74
+ }
75
+ const lines = [
76
+ 'flowchart LR'
77
+ ];
78
+ for (const owner of graph.owners)lines.push(owner === sharedKernel ? ` ${nodeId(owner)}[(${quoted(owner)})]` : ` ${nodeId(owner)}[${quoted(owner)}]`);
79
+ for (const [key, labels] of [
80
+ ...links
81
+ ].sort(([a], [b])=>a.localeCompare(b))){
82
+ const [from, to] = key.split('\u0000');
83
+ const label = [
84
+ ...labels
85
+ ].sort().join('<br/>');
86
+ lines.push(to === sharedKernel ? ` ${nodeId(from)} -.->|${quoted(label)}| ${nodeId(to)}` : ` ${nodeId(from)} -->|${quoted(label)}| ${nodeId(to)}`);
87
+ }
88
+ return lines.join('\n');
89
+ };
90
+ const ownerGraph = (graph, owner, idPrefix = '')=>{
91
+ const nodeId = (value)=>`${idPrefix}${sanitize(value)}`;
92
+ const own = graph.modules.filter((module)=>module.owner === owner);
93
+ const ownIds = new Set(own.map((module)=>module.id));
94
+ const edges = new Map();
95
+ for (const edge of graph.edges){
96
+ if (!ownIds.has(edge.from)) continue;
97
+ const key = `${edge.from}\u0000${edge.to}`;
98
+ const set = edges.get(key) ?? new Set();
99
+ set.add(edge.implementation);
100
+ edges.set(key, set);
101
+ }
102
+ const external = [
103
+ ...new Set([
104
+ ...edges.keys()
105
+ ].map((key)=>key.split('\u0000')[1]).filter((id)=>!ownIds.has(id)))
106
+ ].sort();
107
+ const lines = [
108
+ 'flowchart TB'
109
+ ];
110
+ const node = (id)=>`${nodeId(id)}[${quoted(typeOf(graph, id))}]`;
111
+ for (const layer of wiring_layers){
112
+ const members = own.filter((module)=>module.layer === layer);
113
+ if (members.length) {
114
+ lines.push(` subgraph ${nodeId(`${owner}_${layer}`)}[${quoted(layer)}]`);
115
+ for (const module of members)lines.push(` ${node(module.id)}`);
116
+ lines.push(' end');
117
+ }
118
+ }
119
+ for (const other of [
120
+ ...new Set(external.map((id)=>ownerOf(graph, id) ?? ''))
121
+ ]){
122
+ lines.push(` subgraph ${nodeId(`owner_${other}`)}[${quoted(other)}]`);
123
+ for (const id of external.filter((x)=>ownerOf(graph, x) === other))lines.push(` ${node(id)}`);
124
+ lines.push(' end');
125
+ }
126
+ for (const [key, implementations] of [
127
+ ...edges
128
+ ].sort(([a], [b])=>a.localeCompare(b))){
129
+ const [from, to] = key.split('\u0000');
130
+ const all = graph.modules.find((module)=>module.id === from)?.implementations.length ?? 0;
131
+ const label = implementations.size < all ? `|${quoted([
132
+ ...implementations
133
+ ].sort().join(', '))}|` : '';
134
+ lines.push(` ${nodeId(from)} -->${label} ${nodeId(to)}`);
135
+ }
136
+ return lines.join('\n');
137
+ };
138
+ const formatOfFile = (file)=>({
139
+ '.md': 'markdown',
140
+ '.mmd': 'mermaid',
141
+ '.mermaid': 'mermaid',
142
+ '.json': 'json',
143
+ '.html': 'html'
144
+ })[node_path.extname(file).toLowerCase()];
145
+ const escapeHtml = (value)=>value.replace(/[&<>"]/g, (char)=>({
146
+ '&': '&amp;',
147
+ '<': '&lt;',
148
+ '>': '&gt;',
149
+ '"': '&quot;'
150
+ })[char] ?? char);
151
+ const mermaidScript = 'https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.esm.min.mjs';
152
+ const graphHtml = (graph, title, owner)=>{
153
+ const sections = owner ? [
154
+ [
155
+ owner,
156
+ ownerGraph(graph, owner, 'c0_')
157
+ ]
158
+ ] : [
159
+ [
160
+ 'Bounded contexts',
161
+ contextMap(graph, 'c0_')
162
+ ],
163
+ ...graph.owners.filter((name)=>graph.modules.some((module)=>module.owner === name)).map((name, index)=>[
164
+ name,
165
+ ownerGraph(graph, name, `c${index + 1}_`)
166
+ ])
167
+ ];
168
+ return `<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8">
172
+ <meta name="viewport" content="width=device-width, initial-scale=1">
173
+ <title>${escapeHtml(title)}</title>
174
+ <style>
175
+ body { margin: 0 auto; max-width: 1200px; padding: 24px 16px; font-family: ui-monospace, Menlo, Consolas, monospace; background: #fafaf7; color: #1d1d1b; }
176
+ h1 { font-size: 22px; } h2 { margin-top: 40px; font-size: 18px; border-bottom: 2px solid #1d1d1b; padding-bottom: 6px; }
177
+ .mermaid { overflow-x: auto; }
178
+ </style>
179
+ </head>
180
+ <body>
181
+ <h1>${escapeHtml(title)}</h1>
182
+ ${sections.map(([name, chart])=>`<h2>${escapeHtml(name)}</h2>\n<pre class="mermaid">\n${escapeHtml(chart)}\n</pre>`).join('\n')}
183
+ <script type="module">
184
+ import mermaid from '${mermaidScript}';
185
+ mermaid.initialize({ startOnLoad: false });
186
+ // One chart at a time: charts rendered together disturb each other's layout.
187
+ for (const node of document.querySelectorAll('.mermaid')) {
188
+ await mermaid.run({ nodes: [node] });
189
+ }
190
+ </script>
191
+ </body>
192
+ </html>
193
+ `;
194
+ };
195
+ const renderGraph = (graph, format, { owner, title = 'Project structure' } = {})=>{
196
+ if ('html' === format) return graphHtml(graph, title, owner);
197
+ if ('json' === format) {
198
+ const modules = owner ? graph.modules.filter((module)=>module.owner === owner) : graph.modules;
199
+ const ids = new Set(modules.map((module)=>module.id));
200
+ return JSON.stringify({
201
+ owners: owner ? [
202
+ owner
203
+ ] : graph.owners,
204
+ modules,
205
+ edges: owner ? graph.edges.filter((edge)=>ids.has(edge.from)) : graph.edges
206
+ });
207
+ }
208
+ const chart = owner ? ownerGraph(graph, owner) : contextMap(graph);
209
+ return 'markdown' === format ? `\`\`\`mermaid\n${chart}\n\`\`\`` : chart;
210
+ };
211
+ const help = `Usage: df-graph [--context <name>] [--json | --markdown | --html] [--out <file>]
212
+
213
+ Shows the project's structure as a Mermaid flowchart, read from the wiring.
214
+ Without options it prints the bounded contexts and the Shared Kernel, with
215
+ the cross-context ports that reach a neighbor's handlers (solid arrows) and
216
+ the use of the Shared Kernel (dashed arrows).
217
+
218
+ Options:
219
+ --context <name> the wired modules of one bounded context (or shared-kernel)
220
+ by layer, with their dependencies
221
+ --markdown wrap the chart in a \`\`\`mermaid block, e.g. for a README
222
+ --json the graph as JSON: owners, modules and dependencies
223
+ --html a page with the rendered charts (all contexts without
224
+ --context), opened in the browser; Mermaid loads from a CDN
225
+ --out <file> write to a file instead; the extension picks the format:
226
+ .md, .mmd/.mermaid, .json or .html
227
+ -h, --help show this help`;
228
+ const { values: values } = parseArgs({
229
+ options: {
230
+ help: {
231
+ type: 'boolean',
232
+ short: 'h',
233
+ default: false
234
+ },
235
+ context: {
236
+ type: 'string'
237
+ },
238
+ json: {
239
+ type: 'boolean',
240
+ default: false
241
+ },
242
+ markdown: {
243
+ type: 'boolean',
244
+ default: false
245
+ },
246
+ html: {
247
+ type: 'boolean',
248
+ default: false
249
+ },
250
+ out: {
251
+ type: 'string'
252
+ }
253
+ }
254
+ });
255
+ if (values.help) {
256
+ console.log(help);
257
+ process.exit(0);
258
+ }
259
+ const fail = (message)=>{
260
+ console.log(message);
261
+ process.exit(1);
262
+ };
263
+ const flagged = [
264
+ 'json',
265
+ 'markdown',
266
+ 'html'
267
+ ].filter((flag)=>values[flag]);
268
+ if (flagged.length > 1) fail('Choose one of --json, --markdown and --html.');
269
+ const fileFormat = void 0 === values.out ? void 0 : formatOfFile(values.out);
270
+ if (void 0 !== values.out && !fileFormat) fail('--out needs a .md, .mmd, .mermaid, .json or .html file.');
271
+ const flagFormat = flagged[0];
272
+ if (fileFormat && flagFormat && fileFormat !== flagFormat) fail(`--${flagFormat} doesn't match ${values.out}.`);
273
+ const graph_format = fileFormat ?? flagFormat ?? 'mermaid';
274
+ if (!ConfigFile.exists) fail('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
275
+ if (ConfigFile.outdated) fail(outdatedConfigMessage);
276
+ const config = ConfigFile.Instance.data;
277
+ if (!config.backend) fail('Backend is not configured: run df-init --section backend.');
278
+ if (!config.backend?.domainFirstPackages.includes('@domain-first/wire')) fail('df-graph reads the wiring: it needs @domain-first/wire.');
279
+ const graph_projectRoot = new ProjectRoot().path;
280
+ const graph_graph = projectGraph(graph_projectRoot, config.project.rootFolder);
281
+ const graph_owner = values.context;
282
+ if (void 0 !== graph_owner && !graph_graph.owners.includes(graph_owner)) fail(`Unknown context: ${graph_owner}. Known: ${graph_graph.owners.join(', ')}.`);
283
+ if (!graph_graph.modules.length) console.error(`No wired modules yet: generate some with df-scaffold (${sharedKernel} and bounded contexts are scanned).`);
284
+ const packageName = (()=>{
285
+ try {
286
+ return JSON.parse(node_fs.readFileSync(node_path.join(graph_projectRoot, 'package.json'), 'utf8')).name;
287
+ } catch {
288
+ return;
289
+ }
290
+ })();
291
+ const output = renderGraph(graph_graph, graph_format, {
292
+ owner: graph_owner,
293
+ title: [
294
+ packageName ?? node_path.basename(graph_projectRoot),
295
+ graph_owner
296
+ ].filter(Boolean).join(' / ')
297
+ });
298
+ const openInBrowser = (file)=>{
299
+ const [command, args] = 'darwin' === process.platform ? [
300
+ 'open',
301
+ [
302
+ file
303
+ ]
304
+ ] : 'win32' === process.platform ? [
305
+ 'cmd',
306
+ [
307
+ '/c',
308
+ 'start',
309
+ '',
310
+ file
311
+ ]
312
+ ] : [
313
+ 'xdg-open',
314
+ [
315
+ file
316
+ ]
317
+ ];
318
+ const child = spawn(command, args, {
319
+ stdio: 'ignore',
320
+ detached: true
321
+ });
322
+ child.on('error', ()=>console.log(`Open ${file} in a browser.`));
323
+ child.unref();
324
+ };
325
+ if (void 0 !== values.out) {
326
+ const file = node_path.resolve(values.out);
327
+ node_fs.mkdirSync(node_path.dirname(file), {
328
+ recursive: true
329
+ });
330
+ node_fs.writeFileSync(file, `${output}\n`);
331
+ console.log(`Wrote ${node_path.relative(process.cwd(), file) || file}.`);
332
+ } else if ('html' === graph_format) {
333
+ const file = node_path.join(node_os.tmpdir(), `df-graph-${(packageName ?? node_path.basename(graph_projectRoot)).replace(/[^\w-]+/g, '-')}${graph_owner ? `-${graph_owner}` : ''}.html`);
334
+ node_fs.writeFileSync(file, output);
335
+ console.log(`Wrote ${file}; opening it in the browser.`);
336
+ openInBrowser(file);
337
+ } else console.log(output);
package/dist/index.cjs CHANGED
@@ -1149,6 +1149,7 @@ const missing_domain_first_packages_missingPackages = (packages)=>{
1149
1149
  ] : [];
1150
1150
  };
1151
1151
  const external_node_async_hooks_namespaceObject = require("node:async_hooks");
1152
+ const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
1152
1153
  class RequestError extends Error {
1153
1154
  code;
1154
1155
  details;
@@ -1224,7 +1225,7 @@ const interaction_confirm = async (config)=>{
1224
1225
  });
1225
1226
  return value;
1226
1227
  };
1227
- const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof prompts_namespaceObject.Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
1229
  value: choice
1229
1230
  });
1230
1231
  const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
@@ -1237,9 +1238,62 @@ const resolveChoice = (value, choices, key, id)=>{
1237
1238
  });
1238
1239
  return matches[0].value;
1239
1240
  };
1241
+ const searchThreshold = 10;
1242
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
1243
+ const filterChoices = (choices, term)=>{
1244
+ const text = (term ?? '').trim().toLowerCase();
1245
+ const words = text.split(/\s+/).filter(Boolean);
1246
+ if (!words.length) return [
1247
+ ...choices
1248
+ ];
1249
+ const groups = [
1250
+ {
1251
+ matches: []
1252
+ }
1253
+ ];
1254
+ for (const choice of choices){
1255
+ if (isSeparator(choice)) {
1256
+ groups.push({
1257
+ separator: choice,
1258
+ matches: []
1259
+ });
1260
+ continue;
1261
+ }
1262
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1263
+ value: choice
1264
+ };
1265
+ const label = choiceLabel(normalized).toLowerCase();
1266
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
1267
+ choice: normalized,
1268
+ prefix: label.startsWith(text)
1269
+ });
1270
+ }
1271
+ const byPrefix = (items, prefix)=>[
1272
+ ...items.filter(prefix),
1273
+ ...items.filter((item)=>!prefix(item))
1274
+ ];
1275
+ const [ungrouped, ...grouped] = groups;
1276
+ return [
1277
+ ungrouped,
1278
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
1279
+ ].flatMap(({ separator, matches })=>[
1280
+ ...separator ? [
1281
+ separator
1282
+ ] : [],
1283
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
1284
+ ]);
1285
+ };
1240
1286
  const interaction_select = async (config)=>{
1241
1287
  const { key, id, ...interactive } = config;
1242
- if (!isNonInteractive()) return (0, prompts_namespaceObject.select)(interactive);
1288
+ if (!isNonInteractive()) {
1289
+ if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
1290
+ return (0, prompts_namespaceObject.search)({
1291
+ message: `${config.message.trimEnd()} (type to filter)`,
1292
+ source: (term)=>filterChoices(config.choices, term),
1293
+ pageSize: config.pageSize,
1294
+ default: config.default
1295
+ });
1296
+ }
1243
1297
  const field = requireKey(key);
1244
1298
  const value = answerFor(field, config.default);
1245
1299
  if (void 0 === value) throw interaction_missing(field);
package/dist/init.cjs CHANGED
@@ -467,6 +467,7 @@ const print_next_steps_printNextSteps = (nextSteps)=>{
467
467
  };
468
468
  const external_node_async_hooks_namespaceObject = require("node:async_hooks");
469
469
  const prompts_namespaceObject = require("@inquirer/prompts");
470
+ const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
470
471
  class interaction_RequestError extends Error {
471
472
  code;
472
473
  details;
@@ -528,7 +529,7 @@ const interaction_confirm = async (config)=>{
528
529
  });
529
530
  return value;
530
531
  };
531
- const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof prompts_namespaceObject.Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
532
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
532
533
  value: choice
533
534
  });
534
535
  const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
@@ -541,9 +542,62 @@ const resolveChoice = (value, choices, key, id)=>{
541
542
  });
542
543
  return matches[0].value;
543
544
  };
545
+ const searchThreshold = 10;
546
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
547
+ const filterChoices = (choices, term)=>{
548
+ const text = (term ?? '').trim().toLowerCase();
549
+ const words = text.split(/\s+/).filter(Boolean);
550
+ if (!words.length) return [
551
+ ...choices
552
+ ];
553
+ const groups = [
554
+ {
555
+ matches: []
556
+ }
557
+ ];
558
+ for (const choice of choices){
559
+ if (isSeparator(choice)) {
560
+ groups.push({
561
+ separator: choice,
562
+ matches: []
563
+ });
564
+ continue;
565
+ }
566
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
567
+ value: choice
568
+ };
569
+ const label = choiceLabel(normalized).toLowerCase();
570
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
571
+ choice: normalized,
572
+ prefix: label.startsWith(text)
573
+ });
574
+ }
575
+ const byPrefix = (items, prefix)=>[
576
+ ...items.filter(prefix),
577
+ ...items.filter((item)=>!prefix(item))
578
+ ];
579
+ const [ungrouped, ...grouped] = groups;
580
+ return [
581
+ ungrouped,
582
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
583
+ ].flatMap(({ separator, matches })=>[
584
+ ...separator ? [
585
+ separator
586
+ ] : [],
587
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
588
+ ]);
589
+ };
544
590
  const interaction_select = async (config)=>{
545
591
  const { key, id, ...interactive } = config;
546
- if (!interaction_isNonInteractive()) return (0, prompts_namespaceObject.select)(interactive);
592
+ if (!interaction_isNonInteractive()) {
593
+ if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
594
+ return (0, prompts_namespaceObject.search)({
595
+ message: `${config.message.trimEnd()} (type to filter)`,
596
+ source: (term)=>filterChoices(config.choices, term),
597
+ pageSize: config.pageSize,
598
+ default: config.default
599
+ });
600
+ }
547
601
  const field = requireKey(key);
548
602
  const value = interaction_answerFor(field, config.default);
549
603
  if (void 0 === value) throw interaction_missing(field);
@@ -1149,6 +1149,7 @@ const missing_domain_first_packages_missingPackages = (packages)=>{
1149
1149
  };
1150
1150
  const external_node_async_hooks_namespaceObject = require("node:async_hooks");
1151
1151
  const prompts_namespaceObject = require("@inquirer/prompts");
1152
+ const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
1152
1153
  class RequestError extends Error {
1153
1154
  code;
1154
1155
  details;
@@ -1224,7 +1225,7 @@ const interaction_confirm = async (config)=>{
1224
1225
  });
1225
1226
  return value;
1226
1227
  };
1227
- const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof prompts_namespaceObject.Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
1229
  value: choice
1229
1230
  });
1230
1231
  const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
@@ -1237,9 +1238,62 @@ const resolveChoice = (value, choices, key, id)=>{
1237
1238
  });
1238
1239
  return matches[0].value;
1239
1240
  };
1241
+ const searchThreshold = 10;
1242
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
1243
+ const filterChoices = (choices, term)=>{
1244
+ const text = (term ?? '').trim().toLowerCase();
1245
+ const words = text.split(/\s+/).filter(Boolean);
1246
+ if (!words.length) return [
1247
+ ...choices
1248
+ ];
1249
+ const groups = [
1250
+ {
1251
+ matches: []
1252
+ }
1253
+ ];
1254
+ for (const choice of choices){
1255
+ if (isSeparator(choice)) {
1256
+ groups.push({
1257
+ separator: choice,
1258
+ matches: []
1259
+ });
1260
+ continue;
1261
+ }
1262
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1263
+ value: choice
1264
+ };
1265
+ const label = choiceLabel(normalized).toLowerCase();
1266
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
1267
+ choice: normalized,
1268
+ prefix: label.startsWith(text)
1269
+ });
1270
+ }
1271
+ const byPrefix = (items, prefix)=>[
1272
+ ...items.filter(prefix),
1273
+ ...items.filter((item)=>!prefix(item))
1274
+ ];
1275
+ const [ungrouped, ...grouped] = groups;
1276
+ return [
1277
+ ungrouped,
1278
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
1279
+ ].flatMap(({ separator, matches })=>[
1280
+ ...separator ? [
1281
+ separator
1282
+ ] : [],
1283
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
1284
+ ]);
1285
+ };
1240
1286
  const interaction_select = async (config)=>{
1241
1287
  const { key, id, ...interactive } = config;
1242
- if (!isNonInteractive()) return (0, prompts_namespaceObject.select)(interactive);
1288
+ if (!isNonInteractive()) {
1289
+ if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
1290
+ return (0, prompts_namespaceObject.search)({
1291
+ message: `${config.message.trimEnd()} (type to filter)`,
1292
+ source: (term)=>filterChoices(config.choices, term),
1293
+ pageSize: config.pageSize,
1294
+ default: config.default
1295
+ });
1296
+ }
1243
1297
  const field = requireKey(key);
1244
1298
  const value = answerFor(field, config.default);
1245
1299
  if (void 0 === value) throw interaction_missing(field);
@@ -35,6 +35,15 @@ type SelectConfig<T> = {
35
35
  loop?: boolean;
36
36
  id?: (value: T) => string;
37
37
  };
38
+ /** Longer menus get a search field: typing filters the choices. */
39
+ export declare const searchThreshold = 10;
40
+ /**
41
+ * The choices whose label contains every typed word, in any case. Labels
42
+ * that start with the typed text come first, and so do their groups, so
43
+ * the highlighted choice is the one a prefix names. A group separator
44
+ * stays only when a choice of its group is left.
45
+ */
46
+ export declare const filterChoices: <T>(choices: SelectConfig<T>["choices"], term: string | undefined) => (Separator | T | Choice<T>)[];
38
47
  export declare const select: <T>(config: SelectConfig<T>) => Promise<T>;
39
48
  export declare const checkbox: <T>(config: Omit<SelectConfig<T>, "default"> & {
40
49
  required?: boolean;
@@ -0,0 +1 @@
1
+ export {};