@navios/commander 1.0.0-alpha.4 → 1.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/src/commander.factory.d.mts +59 -0
  3. package/dist/src/commander.factory.d.mts.map +1 -1
  4. package/dist/src/commands/help.command.d.mts.map +1 -1
  5. package/dist/src/decorators/command.decorator.d.mts +9 -2
  6. package/dist/src/decorators/command.decorator.d.mts.map +1 -1
  7. package/dist/src/overrides/help.command.d.mts +18 -0
  8. package/dist/src/overrides/help.command.d.mts.map +1 -0
  9. package/dist/src/tokens/help-command.token.d.mts +4 -0
  10. package/dist/src/tokens/help-command.token.d.mts.map +1 -0
  11. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  12. package/dist/tsconfig.tsbuildinfo +1 -1
  13. package/lib/help-command.token-BPEgaaxY.mjs +558 -0
  14. package/lib/help-command.token-BPEgaaxY.mjs.map +1 -0
  15. package/lib/help-command.token-DcvTjwbA.cjs +611 -0
  16. package/lib/help-command.token-DcvTjwbA.cjs.map +1 -0
  17. package/lib/help.command-D9lsIDIe.cjs +316 -0
  18. package/lib/help.command-D9lsIDIe.cjs.map +1 -0
  19. package/lib/help.command-DtokRzad.mjs +317 -0
  20. package/lib/help.command-DtokRzad.mjs.map +1 -0
  21. package/lib/index.cjs +43 -566
  22. package/lib/index.cjs.map +1 -1
  23. package/lib/index.d.cts +184 -119
  24. package/lib/index.d.cts.map +1 -1
  25. package/lib/index.d.mts +184 -119
  26. package/lib/index.d.mts.map +1 -1
  27. package/lib/index.mjs +28 -551
  28. package/lib/index.mjs.map +1 -1
  29. package/package.json +11 -4
  30. package/src/commander.factory.mts +107 -8
  31. package/src/commands/help.command.mts +4 -3
  32. package/src/decorators/command.decorator.mts +17 -8
  33. package/src/overrides/help.command.mts +40 -0
  34. package/src/tokens/help-command.token.mts +5 -0
  35. package/tsconfig.json +0 -3
  36. package/tsconfig.spec.json +1 -1
  37. package/dist/src/commander.application.d.mts +0 -147
  38. package/dist/src/commander.application.d.mts.map +0 -1
  39. package/dist/src/metadata/cli-module.metadata.d.mts +0 -60
  40. package/dist/src/metadata/cli-module.metadata.d.mts.map +0 -1
  41. package/dist/src/services/module-loader.service.d.mts +0 -74
  42. package/dist/src/services/module-loader.service.d.mts.map +0 -1
@@ -0,0 +1,611 @@
1
+ let _navios_core = require("@navios/core");
2
+
3
+ //#region src/metadata/command.metadata.mts
4
+ /**
5
+ * @internal
6
+ * Symbol key used to store command metadata on classes.
7
+ */ const CommandMetadataKey = Symbol("CommandMetadataKey");
8
+ /**
9
+ * Gets or creates command metadata for a class.
10
+ *
11
+ * @internal
12
+ * @param target - The command class
13
+ * @param context - The decorator context
14
+ * @param path - The command path
15
+ * @param description - Optional description for help text
16
+ * @param optionsSchema - Optional Zod schema
17
+ * @returns The command metadata
18
+ */ function getCommandMetadata(target, context, path, description, optionsSchema) {
19
+ if (context.metadata) {
20
+ const metadata = context.metadata[CommandMetadataKey];
21
+ if (metadata) return metadata;
22
+ else {
23
+ const newMetadata = {
24
+ path,
25
+ description,
26
+ optionsSchema,
27
+ customAttributes: /* @__PURE__ */ new Map()
28
+ };
29
+ context.metadata[CommandMetadataKey] = newMetadata;
30
+ target[CommandMetadataKey] = newMetadata;
31
+ return newMetadata;
32
+ }
33
+ }
34
+ throw new Error("[Navios Commander] Wrong environment.");
35
+ }
36
+ /**
37
+ * Extracts command metadata from a class.
38
+ *
39
+ * @param target - The command class
40
+ * @returns The command metadata
41
+ * @throws {Error} If the class is not decorated with @Command
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const metadata = extractCommandMetadata(GreetCommand)
46
+ * console.log(metadata.path) // 'greet'
47
+ * ```
48
+ */ function extractCommandMetadata(target) {
49
+ const metadata = target[CommandMetadataKey];
50
+ if (!metadata) throw new Error("[Navios Commander] Command metadata not found. Make sure to use @Command decorator.");
51
+ return metadata;
52
+ }
53
+ /**
54
+ * Checks if a class has command metadata.
55
+ *
56
+ * @param target - The class to check
57
+ * @returns `true` if the class is decorated with @Command, `false` otherwise
58
+ */ function hasCommandMetadata(target) {
59
+ return !!target[CommandMetadataKey];
60
+ }
61
+
62
+ //#endregion
63
+ //#region src/metadata/command-entry.metadata.mts
64
+ /**
65
+ * Symbol key for storing commands in ModuleMetadata.customEntries.
66
+ * Used by @CliModule to store command classes.
67
+ *
68
+ * @public
69
+ */ const CommandEntryKey = Symbol("CommandEntryKey");
70
+ /**
71
+ * Extracts commands from a module's metadata.
72
+ * Returns empty set if no commands are defined.
73
+ *
74
+ * @param moduleClass - The module class decorated with @CliModule or @Module
75
+ * @returns Set of command classes registered in the module
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const commands = extractModuleCommands(AppModule)
80
+ * for (const command of commands) {
81
+ * console.log(command.name)
82
+ * }
83
+ * ```
84
+ */ function extractModuleCommands(moduleClass) {
85
+ return (0, _navios_core.extractModuleMetadata)(moduleClass).customEntries.get(CommandEntryKey) ?? /* @__PURE__ */ new Set();
86
+ }
87
+
88
+ //#endregion
89
+ //#region src/decorators/command.decorator.mts
90
+ /**
91
+ * Decorator that marks a class as a CLI command.
92
+ *
93
+ * The decorated class must implement the `CommandHandler` interface with an `execute` method.
94
+ * The command will be automatically registered when its module is loaded.
95
+ *
96
+ * @param options - Configuration options for the command
97
+ * @returns A class decorator function
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * import { Command, CommandHandler } from '@navios/commander'
102
+ * import { z } from 'zod'
103
+ *
104
+ * const optionsSchema = z.object({
105
+ * name: z.string(),
106
+ * greeting: z.string().optional().default('Hello')
107
+ * })
108
+ *
109
+ * @Command({
110
+ * path: 'greet',
111
+ * optionsSchema: optionsSchema
112
+ * })
113
+ * export class GreetCommand implements CommandHandler<z.infer<typeof optionsSchema>> {
114
+ * async execute(options) {
115
+ * console.log(`${options.greeting}, ${options.name}!`)
116
+ * }
117
+ * }
118
+ * ```
119
+ */ function Command({ path, description, token, optionsSchema, priority, registry }) {
120
+ return function(target, context) {
121
+ if (context.kind !== "class") throw new Error("[Navios Commander] @Command decorator can only be used on classes.");
122
+ const tokenToUse = token ?? _navios_core.InjectionToken.create(target);
123
+ if (context.metadata) getCommandMetadata(target, context, path, description, optionsSchema);
124
+ return (0, _navios_core.Injectable)({
125
+ token: tokenToUse,
126
+ scope: _navios_core.InjectableScope.Singleton,
127
+ priority,
128
+ registry
129
+ })(target, context);
130
+ };
131
+ }
132
+
133
+ //#endregion
134
+ //#region src/services/command-registry.service.mts
135
+ function applyDecs2203RFactory() {
136
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
137
+ return function addInitializer(initializer) {
138
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
139
+ assertCallable(initializer, "An initializer");
140
+ initializers.push(initializer);
141
+ };
142
+ }
143
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
144
+ var kindStr;
145
+ switch (kind) {
146
+ case 1:
147
+ kindStr = "accessor";
148
+ break;
149
+ case 2:
150
+ kindStr = "method";
151
+ break;
152
+ case 3:
153
+ kindStr = "getter";
154
+ break;
155
+ case 4:
156
+ kindStr = "setter";
157
+ break;
158
+ default: kindStr = "field";
159
+ }
160
+ var ctx = {
161
+ kind: kindStr,
162
+ name: isPrivate ? "#" + name : name,
163
+ static: isStatic,
164
+ private: isPrivate,
165
+ metadata
166
+ };
167
+ var decoratorFinishedRef = { v: false };
168
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
169
+ var get, set;
170
+ if (kind === 0) if (isPrivate) {
171
+ get = desc.get;
172
+ set = desc.set;
173
+ } else {
174
+ get = function() {
175
+ return this[name];
176
+ };
177
+ set = function(v) {
178
+ this[name] = v;
179
+ };
180
+ }
181
+ else if (kind === 2) get = function() {
182
+ return desc.value;
183
+ };
184
+ else {
185
+ if (kind === 1 || kind === 3) get = function() {
186
+ return desc.get.call(this);
187
+ };
188
+ if (kind === 1 || kind === 4) set = function(v) {
189
+ desc.set.call(this, v);
190
+ };
191
+ }
192
+ ctx.access = get && set ? {
193
+ get,
194
+ set
195
+ } : get ? { get } : { set };
196
+ try {
197
+ return dec(value, ctx);
198
+ } finally {
199
+ decoratorFinishedRef.v = true;
200
+ }
201
+ }
202
+ function assertNotFinished(decoratorFinishedRef, fnName) {
203
+ if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished");
204
+ }
205
+ function assertCallable(fn, hint) {
206
+ if (typeof fn !== "function") throw new TypeError(hint + " must be a function");
207
+ }
208
+ function assertValidReturnValue(kind, value) {
209
+ var type = typeof value;
210
+ if (kind === 1) {
211
+ if (type !== "object" || value === null) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
212
+ if (value.get !== void 0) assertCallable(value.get, "accessor.get");
213
+ if (value.set !== void 0) assertCallable(value.set, "accessor.set");
214
+ if (value.init !== void 0) assertCallable(value.init, "accessor.init");
215
+ } else if (type !== "function") {
216
+ var hint;
217
+ if (kind === 0) hint = "field";
218
+ else if (kind === 10) hint = "class";
219
+ else hint = "method";
220
+ throw new TypeError(hint + " decorators must return a function or void 0");
221
+ }
222
+ }
223
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
224
+ var decs = decInfo[0];
225
+ var desc, init, value;
226
+ if (isPrivate) if (kind === 0 || kind === 1) desc = {
227
+ get: decInfo[3],
228
+ set: decInfo[4]
229
+ };
230
+ else if (kind === 3) desc = { get: decInfo[3] };
231
+ else if (kind === 4) desc = { set: decInfo[3] };
232
+ else desc = { value: decInfo[3] };
233
+ else if (kind !== 0) desc = Object.getOwnPropertyDescriptor(base, name);
234
+ if (kind === 1) value = {
235
+ get: desc.get,
236
+ set: desc.set
237
+ };
238
+ else if (kind === 2) value = desc.value;
239
+ else if (kind === 3) value = desc.get;
240
+ else if (kind === 4) value = desc.set;
241
+ var newValue, get, set;
242
+ if (typeof decs === "function") {
243
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
244
+ if (newValue !== void 0) {
245
+ assertValidReturnValue(kind, newValue);
246
+ if (kind === 0) init = newValue;
247
+ else if (kind === 1) {
248
+ init = newValue.init;
249
+ get = newValue.get || value.get;
250
+ set = newValue.set || value.set;
251
+ value = {
252
+ get,
253
+ set
254
+ };
255
+ } else value = newValue;
256
+ }
257
+ } else for (var i = decs.length - 1; i >= 0; i--) {
258
+ var dec = decs[i];
259
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
260
+ if (newValue !== void 0) {
261
+ assertValidReturnValue(kind, newValue);
262
+ var newInit;
263
+ if (kind === 0) newInit = newValue;
264
+ else if (kind === 1) {
265
+ newInit = newValue.init;
266
+ get = newValue.get || value.get;
267
+ set = newValue.set || value.set;
268
+ value = {
269
+ get,
270
+ set
271
+ };
272
+ } else value = newValue;
273
+ if (newInit !== void 0) if (init === void 0) init = newInit;
274
+ else if (typeof init === "function") init = [init, newInit];
275
+ else init.push(newInit);
276
+ }
277
+ }
278
+ if (kind === 0 || kind === 1) {
279
+ if (init === void 0) init = function(instance, init$1) {
280
+ return init$1;
281
+ };
282
+ else if (typeof init !== "function") {
283
+ var ownInitializers = init;
284
+ init = function(instance, init$1) {
285
+ var value$1 = init$1;
286
+ for (var i$1 = 0; i$1 < ownInitializers.length; i$1++) value$1 = ownInitializers[i$1].call(instance, value$1);
287
+ return value$1;
288
+ };
289
+ } else {
290
+ var originalInitializer = init;
291
+ init = function(instance, init$1) {
292
+ return originalInitializer.call(instance, init$1);
293
+ };
294
+ }
295
+ ret.push(init);
296
+ }
297
+ if (kind !== 0) {
298
+ if (kind === 1) {
299
+ desc.get = value.get;
300
+ desc.set = value.set;
301
+ } else if (kind === 2) desc.value = value;
302
+ else if (kind === 3) desc.get = value;
303
+ else if (kind === 4) desc.set = value;
304
+ if (isPrivate) if (kind === 1) {
305
+ ret.push(function(instance, args) {
306
+ return value.get.call(instance, args);
307
+ });
308
+ ret.push(function(instance, args) {
309
+ return value.set.call(instance, args);
310
+ });
311
+ } else if (kind === 2) ret.push(value);
312
+ else ret.push(function(instance, args) {
313
+ return value.call(instance, args);
314
+ });
315
+ else Object.defineProperty(base, name, desc);
316
+ }
317
+ }
318
+ function applyMemberDecs(Class, decInfos, metadata) {
319
+ var ret = [];
320
+ var protoInitializers;
321
+ var staticInitializers;
322
+ var existingProtoNonFields = /* @__PURE__ */ new Map();
323
+ var existingStaticNonFields = /* @__PURE__ */ new Map();
324
+ for (var i = 0; i < decInfos.length; i++) {
325
+ var decInfo = decInfos[i];
326
+ if (!Array.isArray(decInfo)) continue;
327
+ var kind = decInfo[1];
328
+ var name = decInfo[2];
329
+ var isPrivate = decInfo.length > 3;
330
+ var isStatic = kind >= 5;
331
+ var base;
332
+ var initializers;
333
+ if (isStatic) {
334
+ base = Class;
335
+ kind = kind - 5;
336
+ staticInitializers = staticInitializers || [];
337
+ initializers = staticInitializers;
338
+ } else {
339
+ base = Class.prototype;
340
+ protoInitializers = protoInitializers || [];
341
+ initializers = protoInitializers;
342
+ }
343
+ if (kind !== 0 && !isPrivate) {
344
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
345
+ var existingKind = existingNonFields.get(name) || 0;
346
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
347
+ else if (!existingKind && kind > 2) existingNonFields.set(name, kind);
348
+ else existingNonFields.set(name, true);
349
+ }
350
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
351
+ }
352
+ pushInitializers(ret, protoInitializers);
353
+ pushInitializers(ret, staticInitializers);
354
+ return ret;
355
+ }
356
+ function pushInitializers(ret, initializers) {
357
+ if (initializers) ret.push(function(instance) {
358
+ for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
359
+ return instance;
360
+ });
361
+ }
362
+ function applyClassDecs(targetClass, classDecs, metadata) {
363
+ if (classDecs.length > 0) {
364
+ var initializers = [];
365
+ var newClass = targetClass;
366
+ var name = targetClass.name;
367
+ for (var i = classDecs.length - 1; i >= 0; i--) {
368
+ var decoratorFinishedRef = { v: false };
369
+ try {
370
+ var nextNewClass = classDecs[i](newClass, {
371
+ kind: "class",
372
+ name,
373
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
374
+ metadata
375
+ });
376
+ } finally {
377
+ decoratorFinishedRef.v = true;
378
+ }
379
+ if (nextNewClass !== void 0) {
380
+ assertValidReturnValue(10, nextNewClass);
381
+ newClass = nextNewClass;
382
+ }
383
+ }
384
+ return [defineMetadata(newClass, metadata), function() {
385
+ for (var i$1 = 0; i$1 < initializers.length; i$1++) initializers[i$1].call(newClass);
386
+ }];
387
+ }
388
+ }
389
+ function defineMetadata(Class, metadata) {
390
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
391
+ configurable: true,
392
+ enumerable: true,
393
+ value: metadata
394
+ });
395
+ }
396
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
397
+ if (parentClass !== void 0) var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
398
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
399
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
400
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
401
+ return {
402
+ e,
403
+ get c() {
404
+ return applyClassDecs(targetClass, classDecs, metadata);
405
+ }
406
+ };
407
+ };
408
+ }
409
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
410
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
411
+ }
412
+ var _dec, _initClass;
413
+ let _CommandRegistryService;
414
+ _dec = (0, _navios_core.Injectable)();
415
+ var CommandRegistryService = class {
416
+ static {
417
+ ({c: [_CommandRegistryService, _initClass]} = _apply_decs_2203_r(this, [], [_dec]));
418
+ }
419
+ commands = /* @__PURE__ */ new Map();
420
+ /**
421
+ * Register a command with its metadata.
422
+ *
423
+ * @param path - The command path (e.g., 'greet', 'user:create')
424
+ * @param command - The registered command data
425
+ * @throws Error if a command with the same path is already registered
426
+ */ register(path, command) {
427
+ if (this.commands.has(path)) throw new Error(`[Navios Commander] Duplicate command path: ${path}`);
428
+ this.commands.set(path, command);
429
+ }
430
+ /**
431
+ * Get a command by its path.
432
+ *
433
+ * @param path - The command path
434
+ * @returns The registered command or undefined if not found
435
+ */ getByPath(path) {
436
+ return this.commands.get(path);
437
+ }
438
+ /**
439
+ * Get all registered commands.
440
+ *
441
+ * @returns Map of path to registered command
442
+ */ getAll() {
443
+ return new Map(this.commands);
444
+ }
445
+ /**
446
+ * Get all registered commands as an array of path and class pairs.
447
+ * Useful for listing available commands.
448
+ *
449
+ * @returns Array of objects containing path and class
450
+ */ getAllAsArray() {
451
+ const result = [];
452
+ for (const [path, { class: cls }] of this.commands) result.push({
453
+ path,
454
+ class: cls
455
+ });
456
+ return result;
457
+ }
458
+ /**
459
+ * Formats help text listing all available commands with descriptions.
460
+ *
461
+ * @returns Formatted string listing all commands
462
+ */ formatCommandList() {
463
+ const lines = ["Available commands:", ""];
464
+ for (const [path, { metadata }] of this.commands) {
465
+ const description = metadata.description;
466
+ if (description) lines.push(` ${path.padEnd(20)} ${description}`);
467
+ else lines.push(` ${path}`);
468
+ }
469
+ return lines.join("\n");
470
+ }
471
+ /**
472
+ * Formats help text for a specific command.
473
+ *
474
+ * @param commandPath - The command path to show help for
475
+ * @returns Formatted string with command help
476
+ */ formatCommandHelp(commandPath) {
477
+ const command = this.commands.get(commandPath);
478
+ if (!command) return `Unknown command: ${commandPath}\n\n${this.formatCommandList()}`;
479
+ const { metadata } = command;
480
+ const lines = [];
481
+ lines.push(`Usage: ${metadata.path} [options]`);
482
+ lines.push("");
483
+ if (metadata.description) {
484
+ lines.push(metadata.description);
485
+ lines.push("");
486
+ }
487
+ if (metadata.optionsSchema) {
488
+ lines.push("Options:");
489
+ try {
490
+ const shape = metadata.optionsSchema.def.shape;
491
+ if (shape && typeof shape === "object") for (const [key, fieldSchema] of Object.entries(shape)) {
492
+ const optionFlag = `--${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`;
493
+ const fieldType = this.getSchemaTypeName(fieldSchema);
494
+ lines.push(` ${optionFlag.padEnd(20)} ${fieldType}`);
495
+ }
496
+ } catch {}
497
+ }
498
+ return lines.join("\n");
499
+ }
500
+ /**
501
+ * Gets a human-readable type name from a Zod schema.
502
+ */ getSchemaTypeName(schema) {
503
+ try {
504
+ let currentSchema = schema;
505
+ let typeName = currentSchema?.def?.type;
506
+ let isOptional = false;
507
+ let defaultValue;
508
+ while (typeName === "optional" || typeName === "default") {
509
+ if (typeName === "optional") isOptional = true;
510
+ if (typeName === "default") {
511
+ isOptional = true;
512
+ defaultValue = currentSchema?.def?.defaultValue?.();
513
+ }
514
+ currentSchema = currentSchema?.def?.innerType;
515
+ typeName = currentSchema?.def?.type;
516
+ }
517
+ let result = `<${typeName || "unknown"}>`;
518
+ if (defaultValue !== void 0) result += ` (default: ${JSON.stringify(defaultValue)})`;
519
+ else if (isOptional) result += " (optional)";
520
+ const description = this.getSchemaMeta(schema)?.description;
521
+ if (description) result += ` - ${description}`;
522
+ return result;
523
+ } catch {
524
+ return "<unknown>";
525
+ }
526
+ }
527
+ /**
528
+ * Gets metadata from a Zod schema, traversing innerType if needed.
529
+ * Zod v4 stores meta at the outermost layer when .meta() is called last,
530
+ * or in innerType when .meta() is called before .optional()/.default().
531
+ */ getSchemaMeta(schema) {
532
+ try {
533
+ const directMeta = schema.meta?.();
534
+ if (directMeta) return directMeta;
535
+ const innerType = schema.def?.innerType;
536
+ if (innerType) return this.getSchemaMeta(innerType);
537
+ return;
538
+ } catch {
539
+ return;
540
+ }
541
+ }
542
+ /**
543
+ * Clear all registered commands.
544
+ */ clear() {
545
+ this.commands.clear();
546
+ }
547
+ static {
548
+ _initClass();
549
+ }
550
+ };
551
+
552
+ //#endregion
553
+ //#region src/tokens/help-command.token.mts
554
+ const HelpCommandToken = _navios_core.InjectionToken.create("HelpCommand");
555
+
556
+ //#endregion
557
+ Object.defineProperty(exports, 'Command', {
558
+ enumerable: true,
559
+ get: function () {
560
+ return Command;
561
+ }
562
+ });
563
+ Object.defineProperty(exports, 'CommandEntryKey', {
564
+ enumerable: true,
565
+ get: function () {
566
+ return CommandEntryKey;
567
+ }
568
+ });
569
+ Object.defineProperty(exports, 'CommandMetadataKey', {
570
+ enumerable: true,
571
+ get: function () {
572
+ return CommandMetadataKey;
573
+ }
574
+ });
575
+ Object.defineProperty(exports, 'HelpCommandToken', {
576
+ enumerable: true,
577
+ get: function () {
578
+ return HelpCommandToken;
579
+ }
580
+ });
581
+ Object.defineProperty(exports, '_CommandRegistryService', {
582
+ enumerable: true,
583
+ get: function () {
584
+ return _CommandRegistryService;
585
+ }
586
+ });
587
+ Object.defineProperty(exports, 'extractCommandMetadata', {
588
+ enumerable: true,
589
+ get: function () {
590
+ return extractCommandMetadata;
591
+ }
592
+ });
593
+ Object.defineProperty(exports, 'extractModuleCommands', {
594
+ enumerable: true,
595
+ get: function () {
596
+ return extractModuleCommands;
597
+ }
598
+ });
599
+ Object.defineProperty(exports, 'getCommandMetadata', {
600
+ enumerable: true,
601
+ get: function () {
602
+ return getCommandMetadata;
603
+ }
604
+ });
605
+ Object.defineProperty(exports, 'hasCommandMetadata', {
606
+ enumerable: true,
607
+ get: function () {
608
+ return hasCommandMetadata;
609
+ }
610
+ });
611
+ //# sourceMappingURL=help-command.token-DcvTjwbA.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help-command.token-DcvTjwbA.cjs","names":["CommandMetadataKey","Symbol","getCommandMetadata","target","context","path","description","optionsSchema","metadata","newMetadata","customAttributes","Map","Error","extractCommandMetadata","hasCommandMetadata","extractModuleMetadata","CommandEntryKey","Symbol","extractModuleCommands","moduleClass","metadata","customEntries","get","Set","Injectable","InjectableScope","InjectionToken","getCommandMetadata","Command","path","description","token","optionsSchema","priority","registry","target","context","kind","Error","tokenToUse","create","metadata","scope","Singleton","Injectable","CommandRegistryService","commands","Map","register","path","command","has","Error","set","getByPath","get","getAll","getAllAsArray","result","class","cls","push","formatCommandList","lines","metadata","description","padEnd","join","formatCommandHelp","commandPath","optionsSchema","shape","def","key","fieldSchema","Object","entries","kebabKey","replace","toLowerCase","optionFlag","fieldType","getSchemaTypeName","schema","currentSchema","typeName","type","isOptional","defaultValue","innerType","undefined","JSON","stringify","getSchemaMeta","directMeta","meta","clear","InjectionToken","HelpCommandToken","create"],"sources":["../src/metadata/command.metadata.mts","../src/metadata/command-entry.metadata.mts","../src/decorators/command.decorator.mts","../src/services/command-registry.service.mts","../src/tokens/help-command.token.mts"],"sourcesContent":["import type { ClassType } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\n/**\n * @internal\n * Symbol key used to store command metadata on classes.\n */\nexport const CommandMetadataKey = Symbol('CommandMetadataKey')\n\n/**\n * Metadata associated with a command.\n *\n * @public\n */\nexport interface CommandMetadata {\n /**\n * The command path (e.g., 'greet', 'user:create').\n */\n path: string\n /**\n * Optional description of the command for help text.\n */\n description?: string\n /**\n * Optional Zod schema for validating command options.\n */\n optionsSchema?: ZodObject\n /**\n * Map of custom attributes that can be attached to the command.\n */\n customAttributes: Map<string | symbol, any>\n}\n\n/**\n * Gets or creates command metadata for a class.\n *\n * @internal\n * @param target - The command class\n * @param context - The decorator context\n * @param path - The command path\n * @param description - Optional description for help text\n * @param optionsSchema - Optional Zod schema\n * @returns The command metadata\n */\nexport function getCommandMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n path: string,\n description?: string,\n optionsSchema?: ZodObject,\n): CommandMetadata {\n if (context.metadata) {\n const metadata = context.metadata[CommandMetadataKey] as\n | CommandMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const newMetadata: CommandMetadata = {\n path,\n description,\n optionsSchema,\n customAttributes: new Map<string | symbol, any>(),\n }\n context.metadata[CommandMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[CommandMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios Commander] Wrong environment.')\n}\n\n/**\n * Extracts command metadata from a class.\n *\n * @param target - The command class\n * @returns The command metadata\n * @throws {Error} If the class is not decorated with @Command\n *\n * @example\n * ```typescript\n * const metadata = extractCommandMetadata(GreetCommand)\n * console.log(metadata.path) // 'greet'\n * ```\n */\nexport function extractCommandMetadata(target: ClassType): CommandMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios Commander] Command metadata not found. Make sure to use @Command decorator.',\n )\n }\n return metadata\n}\n\n/**\n * Checks if a class has command metadata.\n *\n * @param target - The class to check\n * @returns `true` if the class is decorated with @Command, `false` otherwise\n */\nexport function hasCommandMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[CommandMetadataKey] as CommandMetadata | undefined\n return !!metadata\n}\n","import type { ClassType } from '@navios/core'\n\nimport { extractModuleMetadata } from '@navios/core'\n\n/**\n * Symbol key for storing commands in ModuleMetadata.customEntries.\n * Used by @CliModule to store command classes.\n *\n * @public\n */\nexport const CommandEntryKey = Symbol('CommandEntryKey')\n\n/**\n * Type for the command entry value stored in customEntries.\n *\n * @public\n */\nexport type CommandEntryValue = Set<ClassType>\n\n/**\n * Extracts commands from a module's metadata.\n * Returns empty set if no commands are defined.\n *\n * @param moduleClass - The module class decorated with @CliModule or @Module\n * @returns Set of command classes registered in the module\n *\n * @example\n * ```typescript\n * const commands = extractModuleCommands(AppModule)\n * for (const command of commands) {\n * console.log(command.name)\n * }\n * ```\n */\nexport function extractModuleCommands(moduleClass: ClassType): Set<ClassType> {\n const metadata = extractModuleMetadata(moduleClass)\n return (\n (metadata.customEntries.get(CommandEntryKey) as CommandEntryValue) ??\n new Set()\n )\n}\n","import { Injectable, InjectableScope, InjectionToken } from '@navios/core'\n\nimport type { ClassType, ClassTypeWithInstance, Registry } from '@navios/core'\nimport type { ZodObject } from 'zod'\n\nimport { getCommandMetadata } from '../metadata/index.mjs'\n\nimport type { CommandHandler } from '../interfaces/index.mjs'\n\n/**\n * Options for the `@Command` decorator.\n *\n * @public\n */\nexport interface CommandOptions {\n /**\n * The token to use for the command.\n * If provided, the command will be registered with this token.\n */\n token?: InjectionToken<ClassTypeWithInstance<CommandHandler<any>>>\n /**\n * The command path that users will invoke from the CLI.\n * Can be a single word (e.g., 'greet') or multi-word with colons (e.g., 'user:create', 'db:migrate').\n */\n path: string\n /**\n * Optional description of the command for help text.\n * Displayed when users run `help` or `--help`.\n */\n description?: string\n /**\n * Optional Zod schema for validating command options.\n * If provided, options will be validated and parsed according to this schema.\n */\n optionsSchema?: ZodObject\n /**\n * Priority level for the command.\n * Higher priority commands will be loaded first.\n */\n priority?: number\n /**\n * Registry to use for the command.\n * Registry is used to store the command and its options schema.\n */\n registry?: Registry\n}\n\n/**\n * Decorator that marks a class as a CLI command.\n *\n * The decorated class must implement the `CommandHandler` interface with an `execute` method.\n * The command will be automatically registered when its module is loaded.\n *\n * @param options - Configuration options for the command\n * @returns A class decorator function\n *\n * @example\n * ```typescript\n * import { Command, CommandHandler } from '@navios/commander'\n * import { z } from 'zod'\n *\n * const optionsSchema = z.object({\n * name: z.string(),\n * greeting: z.string().optional().default('Hello')\n * })\n *\n * @Command({\n * path: 'greet',\n * optionsSchema: optionsSchema\n * })\n * export class GreetCommand implements CommandHandler<z.infer<typeof optionsSchema>> {\n * async execute(options) {\n * console.log(`${options.greeting}, ${options.name}!`)\n * }\n * }\n * ```\n */\nexport function Command({\n path,\n description,\n token,\n optionsSchema,\n priority,\n registry,\n}: CommandOptions) {\n return function (target: ClassType, context: ClassDecoratorContext) {\n if (context.kind !== 'class') {\n throw new Error('[Navios Commander] @Command decorator can only be used on classes.')\n }\n const tokenToUse =\n token ?? InjectionToken.create<ClassTypeWithInstance<CommandHandler<any>>>(target)\n\n if (context.metadata) {\n getCommandMetadata(target, context, path, description, optionsSchema)\n }\n // @ts-expect-error Injectable is callable\n return Injectable({\n token: tokenToUse,\n scope: InjectableScope.Singleton,\n priority,\n registry,\n })(target, context)\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Injectable } from '@navios/core'\n\nimport type { CommandMetadata } from '../metadata/index.mjs'\n\n/**\n * Represents a registered command with its metadata and module information.\n *\n * @public\n */\nexport interface RegisteredCommand {\n /**\n * The command class\n */\n class: ClassType\n /**\n * The command metadata from @Command decorator\n */\n metadata: CommandMetadata\n /**\n * Name of the module this command belongs to\n */\n moduleName: string\n}\n\n/**\n * Service for registering and looking up CLI commands.\n * Used internally by the CLI adapter to manage discovered commands.\n *\n * @public\n */\n@Injectable()\nexport class CommandRegistryService {\n private commands = new Map<string, RegisteredCommand>()\n\n /**\n * Register a command with its metadata.\n *\n * @param path - The command path (e.g., 'greet', 'user:create')\n * @param command - The registered command data\n * @throws Error if a command with the same path is already registered\n */\n register(path: string, command: RegisteredCommand): void {\n if (this.commands.has(path)) {\n throw new Error(`[Navios Commander] Duplicate command path: ${path}`)\n }\n this.commands.set(path, command)\n }\n\n /**\n * Get a command by its path.\n *\n * @param path - The command path\n * @returns The registered command or undefined if not found\n */\n getByPath(path: string): RegisteredCommand | undefined {\n return this.commands.get(path)\n }\n\n /**\n * Get all registered commands.\n *\n * @returns Map of path to registered command\n */\n getAll(): Map<string, RegisteredCommand> {\n return new Map(this.commands)\n }\n\n /**\n * Get all registered commands as an array of path and class pairs.\n * Useful for listing available commands.\n *\n * @returns Array of objects containing path and class\n */\n getAllAsArray(): Array<{ path: string; class: ClassType }> {\n const result: Array<{ path: string; class: ClassType }> = []\n for (const [path, { class: cls }] of this.commands) {\n result.push({ path, class: cls })\n }\n return result\n }\n\n /**\n * Formats help text listing all available commands with descriptions.\n *\n * @returns Formatted string listing all commands\n */\n formatCommandList(): string {\n const lines = ['Available commands:', '']\n for (const [path, { metadata }] of this.commands) {\n const description = metadata.description\n if (description) {\n lines.push(` ${path.padEnd(20)} ${description}`)\n } else {\n lines.push(` ${path}`)\n }\n }\n return lines.join('\\n')\n }\n\n /**\n * Formats help text for a specific command.\n *\n * @param commandPath - The command path to show help for\n * @returns Formatted string with command help\n */\n formatCommandHelp(commandPath: string): string {\n const command = this.commands.get(commandPath)\n if (!command) {\n return `Unknown command: ${commandPath}\\n\\n${this.formatCommandList()}`\n }\n\n const { metadata } = command\n const lines: string[] = []\n\n lines.push(`Usage: ${metadata.path} [options]`)\n lines.push('')\n\n if (metadata.description) {\n lines.push(metadata.description)\n lines.push('')\n }\n\n // Extract options from schema if available\n if (metadata.optionsSchema) {\n lines.push('Options:')\n try {\n const shape = metadata.optionsSchema.def.shape\n if (shape && typeof shape === 'object') {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n const kebabKey = key.replace(/([A-Z])/g, '-$1').toLowerCase()\n const optionFlag = `--${kebabKey}`\n const fieldType = this.getSchemaTypeName(fieldSchema as any)\n lines.push(` ${optionFlag.padEnd(20)} ${fieldType}`)\n }\n }\n } catch {\n // Schema introspection failed, skip options\n }\n }\n\n return lines.join('\\n')\n }\n\n /**\n * Gets a human-readable type name from a Zod schema.\n */\n private getSchemaTypeName(schema: any): string {\n try {\n let currentSchema = schema\n let typeName = currentSchema?.def?.type\n let isOptional = false\n let defaultValue: any\n\n // Unwrap optional/default wrappers\n while (typeName === 'optional' || typeName === 'default') {\n if (typeName === 'optional') {\n isOptional = true\n }\n if (typeName === 'default') {\n isOptional = true\n defaultValue = currentSchema?.def?.defaultValue?.()\n }\n currentSchema = currentSchema?.def?.innerType\n typeName = currentSchema?.def?.type\n }\n\n let result = `<${typeName || 'unknown'}>`\n if (defaultValue !== undefined) {\n result += ` (default: ${JSON.stringify(defaultValue)})`\n } else if (isOptional) {\n result += ' (optional)'\n }\n\n // Get description from meta() if available\n const description = this.getSchemaMeta(schema)?.description\n if (description) {\n result += ` - ${description}`\n }\n\n return result\n } catch {\n return '<unknown>'\n }\n }\n\n /**\n * Gets metadata from a Zod schema, traversing innerType if needed.\n * Zod v4 stores meta at the outermost layer when .meta() is called last,\n * or in innerType when .meta() is called before .optional()/.default().\n */\n private getSchemaMeta(schema: any): Record<string, unknown> | undefined {\n try {\n // First check direct meta (when .meta() is called last in chain)\n const directMeta = schema.meta?.()\n if (directMeta) return directMeta\n\n // Check innerType for wrapped schemas (optional, default, etc.)\n const innerType = schema.def?.innerType\n if (innerType) {\n return this.getSchemaMeta(innerType)\n }\n\n return undefined\n } catch {\n return undefined\n }\n }\n\n /**\n * Clear all registered commands.\n */\n clear(): void {\n this.commands.clear()\n }\n}\n","import { InjectionToken } from '@navios/core'\n\nimport type { HelpCommand } from '../overrides/help.command.mjs'\n\nexport const HelpCommandToken = InjectionToken.create<HelpCommand>('HelpCommand')\n"],"mappings":";;;;;;GAOA,MAAaA,qBAAqBC,OAAO,qBAAA;;;;;;;;;;;GAqCzC,SAAgBC,mBACdC,QACAC,SACAC,MACAC,aACAC,eAAyB;AAEzB,KAAIH,QAAQI,UAAU;EACpB,MAAMA,WAAWJ,QAAQI,SAASR;AAGlC,MAAIQ,SACF,QAAOA;OACF;GACL,MAAMC,cAA+B;IACnCJ;IACAC;IACAC;IACAG,kCAAkB,IAAIC,KAAAA;IACxB;AACAP,WAAQI,SAASR,sBAAsBS;AAEvCN,UAAOH,sBAAsBS;AAC7B,UAAOA;;;AAGX,OAAM,IAAIG,MAAM,wCAAA;;;;;;;;;;;;;;GAgBlB,SAAgBC,uBAAuBV,QAAiB;CAEtD,MAAMK,WAAWL,OAAOH;AACxB,KAAI,CAACQ,SACH,OAAM,IAAII,MACR,sFAAA;AAGJ,QAAOJ;;;;;;;GAST,SAAgBM,mBAAmBX,QAAiB;AAGlD,QAAO,CAAC,CADSA,OAAOH;;;;;;;;;;GC/F1B,MAAagB,kBAAkBC,OAAO,kBAAA;;;;;;;;;;;;;;;GAwBtC,SAAgBC,sBAAsBC,aAAsB;AAE1D,gDADu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