@baselineos/lang 0.1.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/index.js ADDED
@@ -0,0 +1,1082 @@
1
+ // src/system.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { join } from "path";
4
+
5
+ // src/config/lang-system-config.json
6
+ var lang_system_config_default = {
7
+ system: {
8
+ name: "Baseline Lang System",
9
+ version: "1.0.0",
10
+ description: "Natural language processing and command interpretation for Baseline Protocol",
11
+ language: "en",
12
+ encoding: "utf-8"
13
+ },
14
+ syntax: {
15
+ commandPrefix: "--",
16
+ optionPrefix: "-",
17
+ separator: " ",
18
+ quoteChar: '"',
19
+ escapeChar: "\\",
20
+ wildcard: "*",
21
+ range: ".."
22
+ },
23
+ patterns: {
24
+ intent: {
25
+ question: "^(what|how|when|where|why|who|which|can|should|will|do|does|is|are|was|were)",
26
+ action: "^(create|make|build|generate|start|begin|init|initialize|launch|establish|found|set|put)",
27
+ query: "^(show|display|list|find|search|get|fetch|retrieve|look|see|view|examine|inspect)",
28
+ modification: "^(update|modify|edit|change|alter|adjust|transform|convert|adapt|revise|amend)",
29
+ deletion: "^(delete|remove|destroy|eliminate|clear|wipe|erase|purge|drop|uninstall)",
30
+ status: "^(status|info|details|state|condition|health|check|verify|validate|test)",
31
+ navigation: "^(go|navigate|move|jump|switch|change|enter|exit|open|close)",
32
+ configuration: "^(config|configure|setup|install|deploy|arrange|organize|structure)"
33
+ },
34
+ command: {
35
+ basic: "^[a-z][a-z0-9-]*$",
36
+ compound: "^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$",
37
+ nested: "^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$",
38
+ namespaced: "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$"
39
+ },
40
+ option: {
41
+ short: "^-[a-zA-Z]$",
42
+ long: "^--[a-z][a-z0-9-]*$",
43
+ withValue: "^--[a-z][a-z0-9-]*=",
44
+ flag: "^--[a-z][a-z0-9-]*$"
45
+ },
46
+ value: {
47
+ text: "^[a-zA-Z0-9\\s\\-_\\.,/\\\\]+$",
48
+ number: "^[0-9]+(\\.[0-9]+)?$",
49
+ identifier: "^[a-zA-Z_][a-zA-Z0-9_]*$",
50
+ path: "^[a-zA-Z0-9\\-_/\\\\\\.]+$",
51
+ url: "^https?://[a-zA-Z0-9\\-_./]+$",
52
+ email: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
53
+ }
54
+ },
55
+ commands: {
56
+ help: {
57
+ aliases: ["h", "?", "--help", "help"],
58
+ description: "Show help information and command reference",
59
+ usage: "help [command] [options]",
60
+ examples: [
61
+ "help",
62
+ "help create",
63
+ "help --verbose",
64
+ "help create project"
65
+ ],
66
+ options: {
67
+ verbose: {
68
+ type: "boolean",
69
+ description: "Show detailed help information",
70
+ default: false
71
+ },
72
+ format: {
73
+ type: "string",
74
+ description: "Output format (text, json, markdown)",
75
+ default: "text",
76
+ values: ["text", "json", "markdown"]
77
+ }
78
+ }
79
+ },
80
+ create: {
81
+ aliases: ["c", "new", "make", "build", "generate"],
82
+ description: "Create a new resource or entity",
83
+ usage: "create <type> [name] [options]",
84
+ examples: [
85
+ "create project",
86
+ "create project myproject",
87
+ 'create --type=project --name=myproject --description="A new project"',
88
+ "create project myproject --template=web --framework=react"
89
+ ],
90
+ options: {
91
+ type: {
92
+ type: "string",
93
+ description: "Type of resource to create",
94
+ required: true,
95
+ values: ["project", "service", "component", "document", "user", "team"]
96
+ },
97
+ name: {
98
+ type: "string",
99
+ description: "Name of the resource",
100
+ required: false
101
+ },
102
+ description: {
103
+ type: "string",
104
+ description: "Description of the resource",
105
+ required: false
106
+ },
107
+ template: {
108
+ type: "string",
109
+ description: "Template to use for creation",
110
+ required: false
111
+ },
112
+ framework: {
113
+ type: "string",
114
+ description: "Framework to use",
115
+ required: false
116
+ },
117
+ force: {
118
+ type: "boolean",
119
+ description: "Force creation even if resource exists",
120
+ default: false
121
+ }
122
+ }
123
+ },
124
+ list: {
125
+ aliases: ["ls", "show", "display", "view"],
126
+ description: "List resources or entities",
127
+ usage: "list [type] [options]",
128
+ examples: [
129
+ "list",
130
+ "list projects",
131
+ "list --type=project --format=json",
132
+ "list projects --filter=active --sort=name"
133
+ ],
134
+ options: {
135
+ type: {
136
+ type: "string",
137
+ description: "Type of resources to list",
138
+ required: false
139
+ },
140
+ format: {
141
+ type: "string",
142
+ description: "Output format (text, json, table, csv)",
143
+ default: "text",
144
+ values: ["text", "json", "table", "csv"]
145
+ },
146
+ filter: {
147
+ type: "string",
148
+ description: "Filter criteria",
149
+ required: false
150
+ },
151
+ sort: {
152
+ type: "string",
153
+ description: "Sort field",
154
+ required: false
155
+ },
156
+ limit: {
157
+ type: "number",
158
+ description: "Maximum number of results",
159
+ default: 50
160
+ }
161
+ }
162
+ },
163
+ update: {
164
+ aliases: ["u", "modify", "edit", "change", "alter"],
165
+ description: "Update an existing resource or entity",
166
+ usage: "update <type> <id> [options]",
167
+ examples: [
168
+ "update project 123",
169
+ "update project 123 --name=newName",
170
+ 'update --type=project --id=123 --description="Updated description"'
171
+ ],
172
+ options: {
173
+ type: {
174
+ type: "string",
175
+ description: "Type of resource to update",
176
+ required: true
177
+ },
178
+ id: {
179
+ type: "string",
180
+ description: "ID of the resource",
181
+ required: true
182
+ },
183
+ name: {
184
+ type: "string",
185
+ description: "New name for the resource",
186
+ required: false
187
+ },
188
+ description: {
189
+ type: "string",
190
+ description: "New description for the resource",
191
+ required: false
192
+ },
193
+ force: {
194
+ type: "boolean",
195
+ description: "Force update even if validation fails",
196
+ default: false
197
+ }
198
+ }
199
+ },
200
+ delete: {
201
+ aliases: ["d", "remove", "rm", "del", "destroy"],
202
+ description: "Delete a resource or entity",
203
+ usage: "delete <type> <id> [options]",
204
+ examples: [
205
+ "delete project 123",
206
+ "delete project 123 --force",
207
+ "delete --type=project --id=123 --confirm"
208
+ ],
209
+ options: {
210
+ type: {
211
+ type: "string",
212
+ description: "Type of resource to delete",
213
+ required: true
214
+ },
215
+ id: {
216
+ type: "string",
217
+ description: "ID of the resource",
218
+ required: true
219
+ },
220
+ force: {
221
+ type: "boolean",
222
+ description: "Force deletion without confirmation",
223
+ default: false
224
+ },
225
+ confirm: {
226
+ type: "boolean",
227
+ description: "Confirm deletion",
228
+ default: false
229
+ }
230
+ }
231
+ },
232
+ status: {
233
+ aliases: ["s", "info", "details", "health"],
234
+ description: "Show status information about resources or system",
235
+ usage: "status [type] [id] [options]",
236
+ examples: [
237
+ "status",
238
+ "status project 123",
239
+ "status system",
240
+ "status --type=project --id=123 --verbose"
241
+ ],
242
+ options: {
243
+ type: {
244
+ type: "string",
245
+ description: "Type of resource to check status",
246
+ required: false
247
+ },
248
+ id: {
249
+ type: "string",
250
+ description: "ID of the resource",
251
+ required: false
252
+ },
253
+ verbose: {
254
+ type: "boolean",
255
+ description: "Show detailed status information",
256
+ default: false
257
+ },
258
+ format: {
259
+ type: "string",
260
+ description: "Output format (text, json, table)",
261
+ default: "text",
262
+ values: ["text", "json", "table"]
263
+ }
264
+ }
265
+ },
266
+ config: {
267
+ aliases: ["cfg", "settings", "configure"],
268
+ description: "Manage system configuration and settings",
269
+ usage: "config [action] [key] [value] [options]",
270
+ examples: [
271
+ "config show",
272
+ "config get database.url",
273
+ "config set database.url localhost:5432",
274
+ "config list --format=json"
275
+ ],
276
+ options: {
277
+ action: {
278
+ type: "string",
279
+ description: "Action to perform (show, get, set, list, reset)",
280
+ required: false,
281
+ values: ["show", "get", "set", "list", "reset", "export", "import"]
282
+ },
283
+ key: {
284
+ type: "string",
285
+ description: "Configuration key",
286
+ required: false
287
+ },
288
+ value: {
289
+ type: "string",
290
+ description: "Configuration value",
291
+ required: false
292
+ },
293
+ format: {
294
+ type: "string",
295
+ description: "Output format (text, json, yaml)",
296
+ default: "text",
297
+ values: ["text", "json", "yaml"]
298
+ }
299
+ }
300
+ },
301
+ test: {
302
+ aliases: ["t", "validate", "check", "verify"],
303
+ description: "Run tests or validation checks",
304
+ usage: "test [type] [options]",
305
+ examples: [
306
+ "test",
307
+ "test unit",
308
+ "test integration --verbose",
309
+ "test --type=system --format=json"
310
+ ],
311
+ options: {
312
+ type: {
313
+ type: "string",
314
+ description: "Type of tests to run",
315
+ required: false,
316
+ values: ["unit", "integration", "system", "all"]
317
+ },
318
+ verbose: {
319
+ type: "boolean",
320
+ description: "Show detailed test output",
321
+ default: false
322
+ },
323
+ format: {
324
+ type: "string",
325
+ description: "Output format (text, json, junit)",
326
+ default: "text",
327
+ values: ["text", "json", "junit"]
328
+ }
329
+ }
330
+ }
331
+ },
332
+ validation: {
333
+ strict: false,
334
+ allowUnknown: true,
335
+ maxTokens: 100,
336
+ maxOptions: 20,
337
+ maxArguments: 10
338
+ },
339
+ errorHandling: {
340
+ suggestions: true,
341
+ fuzzyMatching: true,
342
+ maxSuggestions: 5,
343
+ levenshteinThreshold: 2
344
+ },
345
+ performance: {
346
+ cacheSize: 1e3,
347
+ maxCacheAge: 3e5,
348
+ enableProfiling: false,
349
+ logPerformance: false
350
+ }
351
+ };
352
+
353
+ // src/system.ts
354
+ var IntentRecognizer = class {
355
+ patterns = /* @__PURE__ */ new Map();
356
+ initialize(patterns) {
357
+ for (const [key, value] of Object.entries(patterns)) {
358
+ if (value instanceof RegExp) {
359
+ this.patterns.set(key, { default: value });
360
+ } else if (typeof value === "object" && value !== null) {
361
+ this.patterns.set(key, value);
362
+ }
363
+ }
364
+ }
365
+ recognize(parsed) {
366
+ const intent = {
367
+ type: "unknown",
368
+ confidence: 0,
369
+ patterns: []
370
+ };
371
+ if (parsed.command) {
372
+ const commandIntent = this.analyzeCommand(parsed.command);
373
+ if (commandIntent.confidence > intent.confidence) {
374
+ intent.type = commandIntent.type;
375
+ intent.confidence = commandIntent.confidence;
376
+ intent.patterns = commandIntent.patterns;
377
+ }
378
+ }
379
+ if (parsed.arguments.length > 0) {
380
+ const argIntent = this.analyzeArguments(parsed.arguments);
381
+ if (argIntent.confidence > intent.confidence) {
382
+ intent.type = argIntent.type;
383
+ intent.confidence = argIntent.confidence;
384
+ intent.patterns = argIntent.patterns;
385
+ }
386
+ }
387
+ return intent;
388
+ }
389
+ analyzeCommand(command) {
390
+ const patterns = this.patterns.get("intent") || {};
391
+ let bestMatch = { type: "unknown", confidence: 0, patterns: [] };
392
+ for (const [type, pattern] of Object.entries(patterns)) {
393
+ if (pattern.test(command)) {
394
+ bestMatch = { type, confidence: 0.8, patterns: [pattern] };
395
+ break;
396
+ }
397
+ }
398
+ return bestMatch;
399
+ }
400
+ analyzeArguments(args) {
401
+ const patterns = this.patterns.get("intent") || {};
402
+ let bestMatch = { type: "unknown", confidence: 0, patterns: [] };
403
+ for (const arg of args) {
404
+ for (const [type, pattern] of Object.entries(patterns)) {
405
+ if (pattern.test(arg)) {
406
+ bestMatch = { type, confidence: 0.6, patterns: [pattern] };
407
+ break;
408
+ }
409
+ }
410
+ if (bestMatch.type !== "unknown") break;
411
+ }
412
+ return bestMatch;
413
+ }
414
+ };
415
+ var CommandProcessor = class {
416
+ commandRegistry = null;
417
+ process(parsed, _intent) {
418
+ const command = this.findCommand(parsed.command);
419
+ if (!command) {
420
+ return {
421
+ success: false,
422
+ error: `Command "${parsed.command}" not found`,
423
+ suggestions: ['Use "help" to see available commands']
424
+ };
425
+ }
426
+ try {
427
+ const result = command.handler(parsed.command, parsed.options, parsed.arguments);
428
+ return { ...result };
429
+ } catch (error) {
430
+ const msg = error instanceof Error ? error.message : String(error);
431
+ return {
432
+ success: false,
433
+ error: `Command execution failed: ${msg}`
434
+ };
435
+ }
436
+ }
437
+ findCommand(commandName) {
438
+ if (!commandName || !this.commandRegistry) return null;
439
+ if (this.commandRegistry.has(commandName)) {
440
+ return this.commandRegistry.get(commandName);
441
+ }
442
+ for (const [, command] of this.commandRegistry) {
443
+ if (command.aliases.includes(commandName)) {
444
+ return command;
445
+ }
446
+ }
447
+ return null;
448
+ }
449
+ };
450
+ var SyntaxValidator = class {
451
+ validate(parsed) {
452
+ const errors = [];
453
+ if (!parsed.command) {
454
+ errors.push("No command specified");
455
+ }
456
+ if (parsed.options.size > 0) {
457
+ for (const [option] of parsed.options) {
458
+ if (!this.isValidOption(option)) {
459
+ errors.push(`Invalid option: ${option}`);
460
+ }
461
+ }
462
+ }
463
+ return { valid: errors.length === 0, errors };
464
+ }
465
+ isValidOption(option) {
466
+ return /^[a-z][a-z0-9-]*$/i.test(option);
467
+ }
468
+ };
469
+ var BaselineLangSystem = class {
470
+ config;
471
+ commandRegistry = /* @__PURE__ */ new Map();
472
+ languagePatterns = /* @__PURE__ */ new Map();
473
+ intentRecognizer = new IntentRecognizer();
474
+ commandProcessor = new CommandProcessor();
475
+ syntaxValidator = new SyntaxValidator();
476
+ lexicon = /* @__PURE__ */ new Map();
477
+ validationDefaults = {
478
+ allowUnknownOptions: true
479
+ };
480
+ constructor(options = {}) {
481
+ this.config = this.loadConfiguration();
482
+ this.initializeSystem();
483
+ if (options.projectLexicon) {
484
+ this.mergeLexicon(options.projectLexicon, "project");
485
+ }
486
+ if (options.projectRoot) {
487
+ this.loadProjectLexicon(options.projectRoot);
488
+ }
489
+ }
490
+ loadConfiguration() {
491
+ const cfg = lang_system_config_default;
492
+ const syntaxCfg = cfg.syntax ?? {};
493
+ const patternsCfg = cfg.patterns ?? {};
494
+ const commandsCfg = cfg.commands ?? {};
495
+ const intentPatterns = patternsCfg.intent ?? {};
496
+ const intentSources = Object.values(intentPatterns);
497
+ const combinedIntent = intentSources.length > 0 ? new RegExp(intentSources.map((p) => `(${p})`).join("|"), "i") : /^(what|how|when|where|why|who|which|can|should|will|do|does|is|are|was|were)/i;
498
+ return {
499
+ language: cfg.system?.language ?? "en",
500
+ syntax: {
501
+ commandPrefix: syntaxCfg.commandPrefix ?? "--",
502
+ optionPrefix: syntaxCfg.optionPrefix ?? "-",
503
+ separator: syntaxCfg.separator ?? " ",
504
+ quoteChar: syntaxCfg.quoteChar ?? '"'
505
+ },
506
+ patterns: {
507
+ intent: combinedIntent,
508
+ command: new RegExp(patternsCfg.command?.basic ?? "^[a-z][a-z0-9-]*$", "i"),
509
+ option: new RegExp(patternsCfg.option?.long ?? "^[a-z][a-z0-9-]*$", "i"),
510
+ value: new RegExp(patternsCfg.value?.text ?? "^[a-zA-Z0-9\\s\\-_./\\\\]+$")
511
+ },
512
+ commands: Object.fromEntries(
513
+ Object.entries(commandsCfg).map(([name, cmd]) => [
514
+ name,
515
+ {
516
+ aliases: cmd.aliases ?? [],
517
+ description: cmd.description ?? "",
518
+ usage: cmd.usage ?? "",
519
+ examples: cmd.examples ?? [],
520
+ options: cmd.options ?? {},
521
+ validation: cmd.validation ?? {}
522
+ }
523
+ ])
524
+ ),
525
+ lexicon: cfg.lexicon ?? {},
526
+ validation: {
527
+ allowUnknownOptions: cfg.validation?.allowUnknownOptions ?? this.validationDefaults.allowUnknownOptions
528
+ }
529
+ };
530
+ }
531
+ initializeSystem() {
532
+ this.registerBuiltInCommands();
533
+ this.loadLexicon();
534
+ this.loadLanguagePatterns();
535
+ this.intentRecognizer.initialize(this.config.patterns);
536
+ this.commandProcessor.commandRegistry = this.commandRegistry;
537
+ }
538
+ registerBuiltInCommands() {
539
+ for (const [command, config] of Object.entries(this.config.commands)) {
540
+ const handler = command === "help" ? this.helpCommandHandler.bind(this) : config.handler;
541
+ this.registerCommand(command, { ...config, handler });
542
+ }
543
+ }
544
+ registerCommand(name, config) {
545
+ const registered = {
546
+ name,
547
+ aliases: config.aliases || [],
548
+ description: config.description || "",
549
+ usage: config.usage || "",
550
+ examples: config.examples || [],
551
+ handler: config.handler || this.defaultCommandHandler.bind(this),
552
+ options: config.options || {},
553
+ validation: config.validation || {}
554
+ };
555
+ this.commandRegistry.set(name, registered);
556
+ if (config.aliases) {
557
+ for (const alias of config.aliases) {
558
+ this.commandRegistry.set(alias, registered);
559
+ }
560
+ }
561
+ }
562
+ loadLanguagePatterns() {
563
+ this.languagePatterns.set("intent", {
564
+ question: /^(what|how|when|where|why|who|which)/i,
565
+ action: /^(create|make|build|generate|start|begin|init|initialize)/i,
566
+ query: /^(show|display|list|find|search|get|fetch|retrieve)/i,
567
+ modification: /^(update|modify|edit|change|alter|adjust)/i,
568
+ deletion: /^(delete|remove|destroy|eliminate|clear|wipe)/i,
569
+ status: /^(status|info|details|state|condition|health)/i
570
+ });
571
+ this.languagePatterns.set("command", {
572
+ basic: /^[a-z][a-z0-9-]*$/i,
573
+ compound: /^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,
574
+ nested: /^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i
575
+ });
576
+ this.languagePatterns.set("option", {
577
+ short: /^-[a-zA-Z]$/,
578
+ long: /^--[a-z][a-z0-9-]*$/i,
579
+ withValue: /^--[a-z][a-z0-9-]*=/i
580
+ });
581
+ }
582
+ resolveCommand(commandName) {
583
+ if (!commandName) return null;
584
+ if (this.commandRegistry.has(commandName)) {
585
+ return this.commandRegistry.get(commandName) ?? null;
586
+ }
587
+ const normalized = commandName.startsWith("--") ? commandName.slice(2) : commandName;
588
+ if (this.commandRegistry.has(normalized)) {
589
+ return this.commandRegistry.get(normalized) ?? null;
590
+ }
591
+ return null;
592
+ }
593
+ validateCommand(parsed, command) {
594
+ const errors = [];
595
+ if (!command) {
596
+ errors.push(`Command "${parsed.command ?? ""}" not found`);
597
+ return { valid: false, errors };
598
+ }
599
+ const minArgs = command.validation?.minArgs;
600
+ const maxArgs = command.validation?.maxArgs;
601
+ if (typeof minArgs === "number" && parsed.arguments.length < minArgs) {
602
+ errors.push(`Expected at least ${minArgs} arguments`);
603
+ }
604
+ if (typeof maxArgs === "number" && parsed.arguments.length > maxArgs) {
605
+ errors.push(`Expected no more than ${maxArgs} arguments`);
606
+ }
607
+ const allowUnknownOptions = command.validation?.allowUnknownOptions ?? this.config.validation?.allowUnknownOptions ?? this.validationDefaults.allowUnknownOptions;
608
+ if (!allowUnknownOptions) {
609
+ for (const optionName of parsed.options.keys()) {
610
+ if (!command.options?.[optionName]) {
611
+ errors.push(`Unknown option: ${optionName}`);
612
+ }
613
+ }
614
+ }
615
+ const optionSpecs = command.options ?? {};
616
+ for (const [optionName, spec] of Object.entries(optionSpecs)) {
617
+ if (spec.required && !parsed.options.has(optionName)) {
618
+ errors.push(`Missing required option: ${optionName}`);
619
+ continue;
620
+ }
621
+ if (!parsed.options.has(optionName)) continue;
622
+ const value = parsed.options.get(optionName);
623
+ const coerced = this.coerceOptionValue(value, spec);
624
+ if (!coerced.valid) {
625
+ errors.push(`Invalid value for option: ${optionName}`);
626
+ continue;
627
+ }
628
+ if (spec.values && coerced.value !== void 0) {
629
+ const stringValue = String(coerced.value);
630
+ if (!spec.values.includes(stringValue)) {
631
+ errors.push(`Invalid value for option: ${optionName}`);
632
+ continue;
633
+ }
634
+ }
635
+ }
636
+ return { valid: errors.length === 0, errors };
637
+ }
638
+ normalizeOptions(parsed, command) {
639
+ const optionSpecs = command.options ?? {};
640
+ for (const [name, spec] of Object.entries(optionSpecs)) {
641
+ if (!parsed.options.has(name) && spec.default !== void 0) {
642
+ parsed.options.set(name, spec.default);
643
+ }
644
+ if (!parsed.options.has(name)) continue;
645
+ const value = parsed.options.get(name);
646
+ const coerced = this.coerceOptionValue(value, spec);
647
+ if (coerced.valid) {
648
+ parsed.options.set(name, coerced.value);
649
+ }
650
+ }
651
+ }
652
+ listCommands() {
653
+ const seen = /* @__PURE__ */ new Set();
654
+ const commands = [];
655
+ for (const command of this.commandRegistry.values()) {
656
+ if (seen.has(command.name)) continue;
657
+ seen.add(command.name);
658
+ commands.push(command);
659
+ }
660
+ return commands.sort((a, b) => a.name.localeCompare(b.name));
661
+ }
662
+ helpCommandHandler(_command, options, args) {
663
+ const format = options.get("format") ?? "text";
664
+ const verbose = Boolean(options.get("verbose"));
665
+ const target = args[0];
666
+ if (target) {
667
+ const command = this.resolveCommand(target);
668
+ if (!command) {
669
+ return {
670
+ success: false,
671
+ error: `Unknown command "${target}"`,
672
+ suggestions: this.findSimilarCommands(target)
673
+ };
674
+ }
675
+ const payload2 = {
676
+ name: command.name,
677
+ description: command.description,
678
+ usage: command.usage,
679
+ aliases: command.aliases,
680
+ examples: command.examples,
681
+ options: command.options
682
+ };
683
+ return {
684
+ success: true,
685
+ message: this.formatHelpPayload(payload2, format, verbose),
686
+ options,
687
+ arguments: args,
688
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
689
+ };
690
+ }
691
+ const commands = this.listCommands();
692
+ const payload = commands.map((command) => ({
693
+ name: command.name,
694
+ description: command.description,
695
+ usage: command.usage,
696
+ aliases: command.aliases,
697
+ examples: command.examples,
698
+ options: command.options
699
+ }));
700
+ return {
701
+ success: true,
702
+ message: this.formatHelpPayload(payload, format, verbose),
703
+ options,
704
+ arguments: args,
705
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
706
+ };
707
+ }
708
+ formatHelpPayload(payload, format, verbose) {
709
+ if (format === "json") {
710
+ return JSON.stringify(payload, null, 2);
711
+ }
712
+ if (Array.isArray(payload)) {
713
+ const lines2 = payload.map((entry2) => {
714
+ const item = entry2;
715
+ return `${item.name ?? ""} \u2014 ${item.description ?? ""}`.trim();
716
+ });
717
+ return lines2.join("\n");
718
+ }
719
+ const entry = payload;
720
+ const lines = [];
721
+ if (entry.name) {
722
+ lines.push(`${entry.name} \u2014 ${entry.description ?? ""}`.trim());
723
+ }
724
+ if (entry.usage) {
725
+ lines.push(`Usage: ${entry.usage}`);
726
+ }
727
+ if (verbose && entry.aliases && entry.aliases.length > 0) {
728
+ lines.push(`Aliases: ${entry.aliases.join(", ")}`);
729
+ }
730
+ if (verbose && entry.examples && entry.examples.length > 0) {
731
+ lines.push(`Examples: ${entry.examples.join(" | ")}`);
732
+ }
733
+ if (verbose && entry.options && Object.keys(entry.options).length > 0) {
734
+ lines.push(`Options: ${Object.keys(entry.options).join(", ")}`);
735
+ }
736
+ return lines.join("\n");
737
+ }
738
+ coerceOptionValue(value, spec) {
739
+ if (spec.type === "boolean") {
740
+ if (typeof value === "boolean") return { valid: true, value };
741
+ if (typeof value === "string") {
742
+ const normalized = value.trim().toLowerCase();
743
+ if (["true", "1", "yes", "y", "on"].includes(normalized)) {
744
+ return { valid: true, value: true };
745
+ }
746
+ if (["false", "0", "no", "n", "off"].includes(normalized)) {
747
+ return { valid: true, value: false };
748
+ }
749
+ }
750
+ if (value === null || value === void 0) {
751
+ return { valid: true, value: true };
752
+ }
753
+ return { valid: false, value };
754
+ }
755
+ if (spec.type === "number") {
756
+ if (typeof value === "number" && !Number.isNaN(value)) {
757
+ return { valid: true, value };
758
+ }
759
+ if (typeof value === "string" && value.trim() !== "") {
760
+ const parsed = Number(value);
761
+ if (!Number.isNaN(parsed)) {
762
+ return { valid: true, value: parsed };
763
+ }
764
+ }
765
+ return { valid: false, value };
766
+ }
767
+ if (spec.type === "string") {
768
+ if (typeof value === "string") {
769
+ return { valid: true, value };
770
+ }
771
+ if (value === null || value === void 0) {
772
+ return { valid: false, value };
773
+ }
774
+ return { valid: true, value: String(value) };
775
+ }
776
+ return { valid: true, value };
777
+ }
778
+ loadLexicon() {
779
+ const entries = this.config.lexicon ?? {};
780
+ if (Object.keys(entries).length === 0) {
781
+ for (const [name, command] of Object.entries(this.config.commands)) {
782
+ this.lexicon.set(name, {
783
+ description: command.description || "",
784
+ aliases: command.aliases ?? [],
785
+ examples: command.examples ?? [],
786
+ source: "built-in"
787
+ });
788
+ }
789
+ return;
790
+ }
791
+ this.mergeLexicon(entries, "config");
792
+ }
793
+ loadProjectLexicon(projectRoot) {
794
+ const candidates = [
795
+ join(projectRoot, ".baseline", "lang.json"),
796
+ join(projectRoot, ".baseline", "lexicon.json"),
797
+ join(projectRoot, "baseline.lang.json")
798
+ ];
799
+ for (const path of candidates) {
800
+ if (!existsSync(path)) continue;
801
+ const raw = readFileSync(path, "utf8");
802
+ const parsed = JSON.parse(raw);
803
+ const lexicon = this.extractLexicon(parsed);
804
+ if (lexicon) {
805
+ this.mergeLexicon(lexicon, "project");
806
+ }
807
+ }
808
+ }
809
+ extractLexicon(input) {
810
+ if (!input || typeof input !== "object") return null;
811
+ const candidate = input;
812
+ const fromContainer = candidate.lexicon;
813
+ if (fromContainer && typeof fromContainer === "object") {
814
+ return this.sanitizeLexicon(fromContainer);
815
+ }
816
+ return this.sanitizeLexicon(candidate);
817
+ }
818
+ sanitizeLexicon(entries) {
819
+ const sanitized = {};
820
+ for (const [term, entry] of Object.entries(entries)) {
821
+ if (!term.trim()) continue;
822
+ const description = entry?.description ?? "";
823
+ sanitized[term.trim()] = {
824
+ description,
825
+ aliases: entry?.aliases ?? [],
826
+ tags: entry?.tags ?? [],
827
+ examples: entry?.examples ?? [],
828
+ source: entry?.source
829
+ };
830
+ }
831
+ return sanitized;
832
+ }
833
+ mergeLexicon(entries, source) {
834
+ for (const [term, entry] of Object.entries(entries)) {
835
+ const normalized = term.trim();
836
+ if (!normalized) continue;
837
+ const existing = this.lexicon.get(normalized);
838
+ const merged = {
839
+ description: entry.description || existing?.description || "",
840
+ aliases: this.mergeStringArrays(existing?.aliases, entry.aliases),
841
+ tags: this.mergeStringArrays(existing?.tags, entry.tags),
842
+ examples: this.mergeStringArrays(existing?.examples, entry.examples),
843
+ source: source ?? entry.source ?? existing?.source
844
+ };
845
+ this.lexicon.set(normalized, merged);
846
+ }
847
+ }
848
+ mergeStringArrays(left, right) {
849
+ const combined = [...left ?? [], ...right ?? []].map((value) => value.trim()).filter(Boolean);
850
+ return Array.from(new Set(combined));
851
+ }
852
+ processInput(input) {
853
+ try {
854
+ const parsed = this.parseInput(input);
855
+ const intent = this.intentRecognizer.recognize(parsed);
856
+ const validation = this.syntaxValidator.validate(parsed);
857
+ if (!validation.valid) {
858
+ return {
859
+ success: false,
860
+ error: "Syntax validation failed",
861
+ details: validation.errors,
862
+ suggestions: this.generateSuggestions(input)
863
+ };
864
+ }
865
+ const command = this.resolveCommand(parsed.command);
866
+ const commandValidation = this.validateCommand(parsed, command);
867
+ if (!commandValidation.valid) {
868
+ return {
869
+ success: false,
870
+ error: "Command validation failed",
871
+ details: commandValidation.errors,
872
+ suggestions: this.generateSuggestions(input)
873
+ };
874
+ }
875
+ if (command) {
876
+ this.normalizeOptions(parsed, command);
877
+ }
878
+ const result = this.commandProcessor.process(parsed, intent);
879
+ return {
880
+ success: true,
881
+ input,
882
+ parsed,
883
+ intent,
884
+ result,
885
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
886
+ };
887
+ } catch (error) {
888
+ const msg = error instanceof Error ? error.message : String(error);
889
+ return {
890
+ success: false,
891
+ error: "Processing failed",
892
+ details: msg,
893
+ suggestions: this.generateSuggestions(input)
894
+ };
895
+ }
896
+ }
897
+ parseInput(input) {
898
+ const tokens = this.tokenize(input);
899
+ const parsed = {
900
+ original: input,
901
+ tokens: [...tokens],
902
+ command: null,
903
+ options: /* @__PURE__ */ new Map(),
904
+ arguments: [],
905
+ intent: null
906
+ };
907
+ if (tokens.length > 0) {
908
+ const firstToken = tokens[0];
909
+ if (this.isCommand(firstToken)) {
910
+ parsed.command = firstToken;
911
+ tokens.splice(0, 1);
912
+ }
913
+ }
914
+ for (let i = 0; i < tokens.length; i++) {
915
+ const token = tokens[i];
916
+ if (this.isOption(token)) {
917
+ const option = this.parseOption(token);
918
+ if (option.value) {
919
+ parsed.options.set(option.name, option.value);
920
+ } else if (i + 1 < tokens.length && !this.isOption(tokens[i + 1])) {
921
+ parsed.options.set(option.name, tokens[i + 1]);
922
+ i++;
923
+ } else {
924
+ parsed.options.set(option.name, true);
925
+ }
926
+ } else {
927
+ parsed.arguments.push(token);
928
+ }
929
+ }
930
+ return parsed;
931
+ }
932
+ tokenize(input) {
933
+ const tokens = [];
934
+ let current = "";
935
+ let inQuotes = false;
936
+ let quoteChar = "";
937
+ for (let i = 0; i < input.length; i++) {
938
+ const char = input[i];
939
+ if ((char === '"' || char === "'") && !inQuotes) {
940
+ inQuotes = true;
941
+ quoteChar = char;
942
+ continue;
943
+ }
944
+ if (char === quoteChar && inQuotes) {
945
+ inQuotes = false;
946
+ quoteChar = "";
947
+ if (current.trim()) {
948
+ tokens.push(current.trim());
949
+ current = "";
950
+ }
951
+ continue;
952
+ }
953
+ if (char === " " && !inQuotes) {
954
+ if (current.trim()) {
955
+ tokens.push(current.trim());
956
+ current = "";
957
+ }
958
+ continue;
959
+ }
960
+ current += char;
961
+ }
962
+ if (current.trim()) {
963
+ tokens.push(current.trim());
964
+ }
965
+ return tokens.filter((token) => token.length > 0);
966
+ }
967
+ isCommand(token) {
968
+ if (this.commandRegistry.has(token)) return true;
969
+ if (this.commandRegistry.has(token.replace(/^--/, ""))) return true;
970
+ if (/^[a-z][a-z0-9-]*$/i.test(token)) return true;
971
+ return false;
972
+ }
973
+ isOption(token) {
974
+ return token.startsWith("-") || token.startsWith("--");
975
+ }
976
+ parseOption(token) {
977
+ if (token.startsWith("--")) {
978
+ const [name, value] = token.split("=");
979
+ return { name: name.substring(2), value: value || null, type: "long" };
980
+ } else if (token.startsWith("-")) {
981
+ return { name: token.substring(1), value: null, type: "short" };
982
+ }
983
+ return { name: token, value: null, type: "unknown" };
984
+ }
985
+ generateSuggestions(input) {
986
+ const suggestions = [];
987
+ const tokens = this.tokenize(input);
988
+ if (tokens.length === 0) {
989
+ suggestions.push('Try starting with a command like "help" or "create"');
990
+ return suggestions;
991
+ }
992
+ const firstToken = tokens[0];
993
+ if (!this.isCommand(firstToken)) {
994
+ const similarCommands = this.findSimilarCommands(firstToken);
995
+ if (similarCommands.length > 0) {
996
+ suggestions.push(`Did you mean: ${similarCommands.join(", ")}?`);
997
+ }
998
+ }
999
+ suggestions.push('Use "help" to see available commands');
1000
+ suggestions.push('Use "help <command>" for specific command help');
1001
+ return suggestions;
1002
+ }
1003
+ getSuggestionTerms() {
1004
+ const terms = /* @__PURE__ */ new Set();
1005
+ for (const key of this.commandRegistry.keys()) {
1006
+ terms.add(key);
1007
+ }
1008
+ for (const [term, entry] of this.lexicon.entries()) {
1009
+ terms.add(term);
1010
+ for (const alias of entry.aliases ?? []) {
1011
+ if (alias.trim()) terms.add(alias.trim());
1012
+ }
1013
+ }
1014
+ return Array.from(terms);
1015
+ }
1016
+ findSimilarCommands(input, maxResults = 3) {
1017
+ const commands = this.getSuggestionTerms();
1018
+ const similar = [];
1019
+ for (const command of commands) {
1020
+ const distance = this.levenshteinDistance(input.toLowerCase(), command.toLowerCase());
1021
+ if (distance <= 2) {
1022
+ similar.push(command);
1023
+ }
1024
+ }
1025
+ return similar.slice(0, maxResults);
1026
+ }
1027
+ levenshteinDistance(str1, str2) {
1028
+ const matrix = [];
1029
+ for (let i = 0; i <= str2.length; i++) {
1030
+ matrix[i] = [i];
1031
+ }
1032
+ for (let j = 0; j <= str1.length; j++) {
1033
+ matrix[0][j] = j;
1034
+ }
1035
+ for (let i = 1; i <= str2.length; i++) {
1036
+ for (let j = 1; j <= str1.length; j++) {
1037
+ if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
1038
+ matrix[i][j] = matrix[i - 1][j - 1];
1039
+ } else {
1040
+ matrix[i][j] = Math.min(
1041
+ matrix[i - 1][j - 1] + 1,
1042
+ matrix[i][j - 1] + 1,
1043
+ matrix[i - 1][j] + 1
1044
+ );
1045
+ }
1046
+ }
1047
+ }
1048
+ return matrix[str2.length][str1.length];
1049
+ }
1050
+ defaultCommandHandler(command, options, args) {
1051
+ return {
1052
+ success: true,
1053
+ message: `Command "${command}" executed successfully`,
1054
+ options,
1055
+ arguments: args,
1056
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1057
+ };
1058
+ }
1059
+ getCommandRegistry() {
1060
+ return this.commandRegistry;
1061
+ }
1062
+ getLanguagePatterns() {
1063
+ return this.languagePatterns;
1064
+ }
1065
+ getLexicon() {
1066
+ return this.lexicon;
1067
+ }
1068
+ };
1069
+ export {
1070
+ BaselineLangSystem,
1071
+ CommandProcessor,
1072
+ IntentRecognizer,
1073
+ SyntaxValidator
1074
+ };
1075
+ /**
1076
+ * Baseline Lang System
1077
+ *
1078
+ * The foundation layer of the Baseline Protocol that handles natural language
1079
+ * processing, command interpretation, and language syntax management.
1080
+ *
1081
+ * @license Apache-2.0
1082
+ */