-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathapify-command.ts
More file actions
885 lines (718 loc) · 26.5 KB
/
apify-command.ts
File metadata and controls
885 lines (718 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
/* eslint-disable max-classes-per-file */
import type { parseArgs, ParseArgsConfig, ParseArgsOptionDescriptor } from 'node:util';
import type { Awaitable } from '@crawlee/types';
import chalk from 'chalk';
import indentString from 'indent-string';
import widestLine from 'widest-line';
import wrapAnsi from 'wrap-ansi';
import { cachedStdinInput } from '../../entrypoints/_shared.js';
import type { TrackEventMap } from '../hooks/telemetry/trackEvent.js';
import { trackEvent } from '../hooks/telemetry/trackEvent.js';
import { useCLIMetadata } from '../hooks/useCLIMetadata.js';
import { ProjectLanguage, useCwdProject } from '../hooks/useCwdProject.js';
import { error } from '../outputs.js';
import type { ArgTag, TaggedArgBuilder } from './args.js';
import { CommandError, CommandErrorCode } from './CommandError.js';
import type { FlagTag, TaggedFlagBuilder } from './flags.js';
import { registerCommandForHelpGeneration, renderHelpForCommand, selectiveRenderHelpForCommand } from './help.js';
import { getMaxLineWidth } from './help/consts.js';
export enum StdinMode {
Raw = 1,
Stringified = 2,
}
interface ArgTagToTSType {
string: string;
}
interface FlagTagToTSType {
string: string;
boolean: boolean;
integer: number;
}
type InferArgTypeFromArg<Builder extends TaggedArgBuilder<ArgTag, unknown>> =
Builder extends TaggedArgBuilder<infer ReturnedType, infer Required>
? If<Required, ArgTagToTSType[ReturnedType], ArgTagToTSType[ReturnedType] | undefined>
: unknown;
type If<T, Y, N> = T extends true ? Y : N;
type IfNotUnknown<T, Y, N> = T extends unknown ? Y : N;
type InferFlagTypeFromFlag<
Builder extends TaggedFlagBuilder<FlagTag, string[] | null, unknown, unknown>,
OptionalIfHasDefault = false,
> = Builder extends TaggedFlagBuilder<infer ReturnedType, never, infer Required, infer HasDefault> // Handle special case where there can be no choices
? If<
// If we want to mark flags as optional if they have a default
OptionalIfHasDefault,
// If the flag actually has a default value, assert on that
IfNotUnknown<
HasDefault,
FlagTagToTSType[ReturnedType] | undefined,
// Otherwise fall back to required status
If<Required, FlagTagToTSType[ReturnedType], FlagTagToTSType[ReturnedType] | undefined>
>,
// fallback to required status
If<Required, FlagTagToTSType[ReturnedType], FlagTagToTSType[ReturnedType] | undefined>
>
: // Might have choices, in which case we branch based on that
Builder extends TaggedFlagBuilder<infer ReturnedType, infer ChoiceType, infer Required, infer HasDefault>
? // If choices is a valid array
ChoiceType extends unknown[] | readonly unknown[]
? // If we want optional flags to stay as optional
If<
OptionalIfHasDefault,
ChoiceType[number] | undefined,
// fallback to required status
If<Required, ChoiceType[number], ChoiceType[number] | undefined>
>
: If<
// If we want to mark flags as optional if they have a default
OptionalIfHasDefault,
// If the flag actually has a default value, assert on that
IfNotUnknown<
HasDefault,
FlagTagToTSType[ReturnedType] | undefined,
// Fallback to required status
If<Required, FlagTagToTSType[ReturnedType], FlagTagToTSType[ReturnedType] | undefined>
>,
// fallback to required status
If<Required, FlagTagToTSType[ReturnedType], FlagTagToTSType[ReturnedType] | undefined>
>
: unknown;
// Adapted from https://gist.github.com/kuroski/9a7ae8e5e5c9e22985364d1ddbf3389d to support kebab-case and "string a"
type CamelCase<S extends string> = S extends
| `${infer P1}-${infer P2}${infer P3}`
| `${infer P1}_${infer P2}${infer P3}`
| `${infer P1} ${infer P2}${infer P3}`
? `${P1}${Uppercase<P2>}${CamelCase<P3>}`
: S;
type _InferArgsFromCommand<O extends Record<string, TaggedArgBuilder<ArgTag, unknown>>> = {
[K in keyof O as CamelCase<string & K>]: InferArgTypeFromArg<O[K]>;
};
type _InferFlagsFromCommand<
O extends Record<string, TaggedFlagBuilder<FlagTag, string[] | null, unknown, unknown>>,
OptionalIfHasDefault = false,
> = {
[K in keyof O as CamelCase<string & K>]: InferFlagTypeFromFlag<O[K], OptionalIfHasDefault>;
};
type InferArgsFromCommand<O extends Record<string, TaggedArgBuilder<ArgTag, unknown>> | undefined> = O extends undefined
? Record<string, unknown>
: _InferArgsFromCommand<Exclude<O, undefined>>;
type InferFlagsFromCommand<
O extends Record<string, TaggedFlagBuilder<FlagTag, string[] | null, unknown, unknown>> | undefined,
OptionalIfHasDefault = false,
> = (O extends undefined
? Record<string, unknown>
: _InferFlagsFromCommand<Exclude<O, undefined>, OptionalIfHasDefault>) & {
json: boolean;
};
export function camelCaseString(str: string): string {
return str.replace(/[-_\s](.)/g, (_, group1) => group1.toUpperCase());
}
export function kebabCaseString(str: string): string {
return str.replace(/[\s_]+/g, '-');
}
export function camelCaseToKebabCase(str: string): string {
return str.replace(/([A-Z])/g, '-$1').toLowerCase();
}
const helpFlagDefinition = {
type: 'boolean',
multiple: false,
short: 'h',
} as const satisfies ParseArgsOptionDescriptor;
const jsonFlagDefinition = {
type: 'boolean',
multiple: false,
} as const satisfies ParseArgsOptionDescriptor;
export const commandRegistry = new Map<string, typeof BuiltApifyCommand>();
type ParseResult = ReturnType<typeof parseArgs<ReturnType<ApifyCommand['_buildParseArgsOption']>>>;
const COMMANDS_WITHIN_ACTOR = [
'init',
'run',
'push',
'actors push',
'pull',
'actors pull',
'call',
'actors call',
'actors start',
];
export abstract class ApifyCommand<T extends typeof BuiltApifyCommand = typeof BuiltApifyCommand> {
static args?: Record<string, TaggedArgBuilder<ArgTag, unknown>> & {
json?: 'Do not use json as the key of an argument, as it will prevent the --json flag from working';
};
static flags?: Record<string, TaggedFlagBuilder<FlagTag, string[] | null, unknown, unknown>> & {
json?: 'Do not use json as the key of a flag, override the enableJsonFlag static property instead';
};
static subcommands?: (typeof BuiltApifyCommand)[];
static enableJsonFlag = false;
static name: string;
static shortDescription?: string;
static description?: string;
static aliases?: string[];
static hidden?: boolean;
static hiddenAliases?: string[];
protected telemetryData: TrackEventMap[`cli_command_${string}`] = {} as never;
protected flags!: InferFlagsFromCommand<T['flags']>;
protected args!: InferArgsFromCommand<T['args']>;
protected entrypoint: string;
protected commandString: string;
protected aliasUsed: string;
protected subcommandAliasUsed?: string;
protected skipTelemetry = false;
public constructor(entrypoint: string, commandString: string, aliasUsed: string, subcommandAliasUsed?: string) {
this.entrypoint = entrypoint;
this.commandString = commandString;
this.aliasUsed = aliasUsed;
this.subcommandAliasUsed = subcommandAliasUsed;
const metadata = useCLIMetadata();
this.telemetryData.installMethod = metadata.installMethod;
this.telemetryData.osArch = metadata.arch;
this.telemetryData.runtime = metadata.runtime.runtime;
this.telemetryData.runtimeVersion = metadata.runtime.version;
this.telemetryData.runtimeNodeVersion = metadata.runtime.nodeVersion ?? metadata.runtime.version;
this.telemetryData.commandString = commandString;
this.telemetryData.entrypoint = entrypoint;
}
abstract run(): Awaitable<void>;
protected get ctor(): typeof BuiltApifyCommand {
return this.constructor as typeof BuiltApifyCommand;
}
protected pluralString(amount: number, singular: string, plural: string): string {
return amount === 1 ? singular : plural;
}
static printHelp(): never {
console.log(renderHelpForCommand(this as typeof BuiltApifyCommand));
process.exit(0);
}
protected printHelp() {
return this.ctor.printHelp();
}
private async _run(parseResult: ParseResult) {
const { values: rawFlags, positionals: rawArgs, tokens: rawTokens } = parseResult;
if (rawFlags.help) {
this.ctor.printHelp();
}
// Cheating a bit here with the types, but its fine
this.args = {} as any;
this.flags = {} as any;
// If we have this set, we assume that the user wants only the flag
if (this.ctor.enableJsonFlag) {
if (typeof rawFlags.json === 'boolean') {
this.flags.json = rawFlags.json;
} else {
this.flags.json = false;
}
}
const missingRequiredArgs = new Map<string, TaggedArgBuilder<ArgTag, unknown>>();
if (this.ctor.args) {
let index = 0;
for (const [userArgName, builderData] of Object.entries(this.ctor.args)) {
if (typeof builderData === 'string') {
throw new RangeError('Do not provide the string for the json arg! It is a type level assertion!');
}
const camelCasedName = camelCaseString(userArgName);
const rawArg = rawArgs[index++];
if (rawArg) {
switch (builderData.argTag) {
case 'string':
default:
this.args[camelCasedName] = String(rawArg);
if (rawArg === '-' && builderData.stdin) {
this.args[camelCasedName] = this._handleStdin(builderData.stdin);
}
if (builderData.catchAll) {
this.args[camelCasedName] = rawArgs.slice(index - 1).join(' ');
}
break;
}
} else if (builderData.required) {
missingRequiredArgs.set(userArgName, builderData);
}
}
}
if (missingRequiredArgs.size) {
this._printMissingRequiredArgs(missingRequiredArgs);
return;
}
this._parseFlags(rawFlags, rawTokens);
try {
await this.run();
} catch (err: any) {
error({ message: err.message });
} finally {
// analytics
if (!this.telemetryData.actorLanguage && COMMANDS_WITHIN_ACTOR.includes(this.commandString)) {
const cwdProject = await useCwdProject();
cwdProject.inspect((project) => {
if (project.type === ProjectLanguage.JavaScript) {
this.telemetryData.actorLanguage = 'javascript';
this.telemetryData.actorRuntime = project.runtime!.runtimeShorthand || 'node';
this.telemetryData.actorRuntimeVersion = project.runtime!.version;
} else if (project.type === ProjectLanguage.Python || project.type === ProjectLanguage.Scrapy) {
this.telemetryData.actorLanguage = 'python';
this.telemetryData.actorRuntime = 'python';
this.telemetryData.actorRuntimeVersion = project.runtime!.version;
}
});
}
this.telemetryData.flagsUsed = Object.keys(this.flags);
if (!this.skipTelemetry) {
await trackEvent(
`cli_command_${this.commandString.replaceAll(' ', '_').toLowerCase()}` as const,
this.telemetryData,
);
}
}
}
private _userFlagNameToRegisteredName(
userFlagName: string,
builderData: TaggedFlagBuilder<FlagTag, string[] | null, unknown, unknown>,
) {
const rawBaseFlagName = kebabCaseString(camelCaseToKebabCase(userFlagName)).toLowerCase();
let baseFlagName = rawBaseFlagName;
if (rawBaseFlagName.startsWith('no-')) {
baseFlagName = rawBaseFlagName.slice(3);
}
const allMatchers = new Set<string>();
for (const alias of builderData.aliases ?? []) {
allMatchers.add(kebabCaseString(camelCaseToKebabCase(alias)).toLowerCase());
}
return { baseFlagName, rawBaseFlagName, allMatchers: [baseFlagName, ...allMatchers] };
}
private _commandFlagKeyToKebabCaseRegisteredName(commandFlagKey: string) {
let flagKey = kebabCaseString(camelCaseToKebabCase(commandFlagKey)).toLowerCase();
if (flagKey.startsWith('no-')) {
// node handles `no-` flags by negating the flag, so we need to handle that differently if we register a flag with a "no-" prefix
flagKey = flagKey.slice(3);
}
return flagKey;
}
private _parseFlags(rawFlags: ParseResult['values'], rawTokens: ParseResult['tokens']) {
if (!this.ctor.flags) {
return;
}
const exclusiveFlagMap = new Map<string, Set<string>>();
let flagThatUsedStdin: string | undefined;
for (const [commandFlagKey, builderData] of Object.entries(this.ctor.flags)) {
if (typeof builderData === 'string') {
throw new RangeError('Do not provide the string for the json arg! It is a type level assertion!');
}
const { allMatchers, baseFlagName, rawBaseFlagName } = this._userFlagNameToRegisteredName(
commandFlagKey,
builderData,
);
const camelCasedName = camelCaseString(rawBaseFlagName);
const usedShortFormOfTheFlag = rawTokens.some(
(token) => token.kind === 'option' && token.name === baseFlagName,
);
if (builderData.exclusive?.length) {
const existingExclusiveFlags = exclusiveFlagMap.get(baseFlagName) ?? new Set();
for (const exclusiveFlag of builderData.exclusive) {
existingExclusiveFlags.add(this._commandFlagKeyToKebabCaseRegisteredName(exclusiveFlag));
}
exclusiveFlagMap.set(baseFlagName, existingExclusiveFlags);
// Go through each exclusive flag for this one flag and also add it
for (const exclusiveFlag of builderData.exclusive) {
const exclusiveFlagKebabCasedName = this._commandFlagKeyToKebabCaseRegisteredName(exclusiveFlag);
const exclusiveFlagExisting = exclusiveFlagMap.get(exclusiveFlagKebabCasedName) ?? new Set();
exclusiveFlagExisting.add(baseFlagName);
exclusiveFlagMap.set(exclusiveFlagKebabCasedName, exclusiveFlagExisting);
}
}
// If you have a flag a, with alias b, and you pass --a and --b, it's not allowed
const matchingFlags = allMatchers.filter((matcher) => rawFlags[matcher]);
if (matchingFlags.length > 1) {
throw new CommandError({
code: CommandErrorCode.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES,
command: this.ctor,
metadata: {
flag: baseFlagName,
},
});
}
let rawFlag = rawFlags[matchingFlags[0]];
if (!rawFlag && builderData.required) {
throw new CommandError({
code: CommandErrorCode.APIFY_MISSING_FLAG,
command: this.ctor,
metadata: {
flag: baseFlagName,
matcher: matchingFlags[0],
},
});
}
// If you provide --a 1 --a 2, it's <currently> not allowed
if (Array.isArray(rawFlag)) {
if (rawFlag.length > 1) {
throw new CommandError({
code: CommandErrorCode.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES,
command: this.ctor,
metadata: {
flag: baseFlagName,
},
});
}
rawFlag = rawFlag[0]! as string | boolean;
}
// -i='{"foo":"bar"}'
if (usedShortFormOfTheFlag && typeof rawFlag === 'string' && rawFlag.startsWith('=')) {
rawFlag = rawFlag.slice(1);
}
if (typeof rawFlag !== 'undefined') {
switch (builderData.flagTag) {
case 'boolean': {
this.flags[camelCasedName] = rawBaseFlagName.startsWith('no-') ? !rawFlag : rawFlag;
break;
}
case 'integer': {
const parsed = Number(rawFlag);
if (Number.isNaN(parsed) || !Number.isInteger(parsed)) {
throw new CommandError({
code: CommandErrorCode.APIFY_INVALID_FLAG_INTEGER_VALUE,
command: this.ctor,
metadata: {
flag: baseFlagName,
value: String(rawFlag),
},
});
}
this.flags[camelCasedName] = parsed;
break;
}
case 'string':
default: {
this.flags[camelCasedName] = rawFlag;
if (rawFlag === '-' && builderData.stdin) {
if (flagThatUsedStdin) {
throw new CommandError({
code: CommandErrorCode.APIFY_TOO_MANY_REQUESTERS_OF_STDIN,
command: this.ctor,
metadata: { firstUse: flagThatUsedStdin, secondUse: baseFlagName },
});
}
flagThatUsedStdin = baseFlagName;
this.flags[camelCasedName] = this._handleStdin(builderData.stdin);
}
break;
}
}
} else if (typeof builderData.hasDefault !== 'undefined') {
this.flags[camelCasedName] = builderData.hasDefault;
}
// Validate choices
if (
// We have the flag
this.flags[camelCasedName] &&
// And we have a list of choices
builderData.choices &&
// And the flag is not one of the choices
!builderData.choices.includes(this.flags[camelCasedName] as string)
) {
throw new CommandError({
code: CommandErrorCode.APIFY_INVALID_CHOICE,
command: this.ctor,
metadata: {
flag: baseFlagName,
choices: builderData.choices.map((choice) => chalk.white.bold(choice)).join(', '),
},
});
}
// Re-validate required (we don't have the flag and it's either required or passed in)
if (this.flags[camelCasedName] == null && (builderData.required || rawFlag != null)) {
throw new CommandError({
code: CommandErrorCode.APIFY_MISSING_FLAG,
command: this.ctor,
metadata: {
flag: baseFlagName,
matcher: matchingFlags[0],
providedButReceivedNoValue: !!rawFlag,
},
});
}
}
const exclusiveErrors: [flagA: string, flagB: string][] = [];
for (const [flagA, flags] of exclusiveFlagMap) {
// If the flag is not set, or is set to null, we can skip it
if (rawFlags[flagA] == null) {
continue;
}
for (const flagB of flags) {
if (rawFlags[flagB] == null) {
continue;
}
// At this point we know both are set
const flagAValue = (rawFlags[flagA] as (string | boolean)[])[0];
const flagBValue = (rawFlags[flagB] as (string | boolean)[])[0];
const flagRepresentation = (kebabCasedFlag: string, value: unknown) => {
if (typeof value === 'boolean') {
return value ? `--${kebabCasedFlag}` : `--no-${kebabCasedFlag}`;
}
return `--${kebabCasedFlag}=${value}`;
};
exclusiveErrors.push([flagRepresentation(flagA, flagAValue), flagRepresentation(flagB, flagBValue)]);
break;
}
}
if (exclusiveErrors.length) {
throw new CommandError({
code: CommandErrorCode.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG,
command: this.ctor,
metadata: {
flagPairs: exclusiveErrors,
},
});
}
}
private _printMissingRequiredArgs(missingRequiredArgs: Map<string, TaggedArgBuilder<ArgTag, unknown>>) {
const help = selectiveRenderHelpForCommand(this.ctor, {
showUsageString: true,
});
const widestArgNameLength = widestLine([...missingRequiredArgs.keys()].join('\n'));
const missingArgsStrings: string[] = [];
for (const [argName, arg] of missingRequiredArgs) {
const fullString = `${argName.padEnd(widestArgNameLength)} ${arg.description}`;
const wrapped = wrapAnsi(fullString, getMaxLineWidth() - widestArgNameLength - 2);
const indented = indentString(wrapped, widestArgNameLength + 2 + 2).trim();
missingArgsStrings.push(` ${chalk.red('>')} ${indented}`);
}
error({
message: [
`Missing ${missingRequiredArgs.size} required ${this.pluralString(missingRequiredArgs.size, 'argument', 'arguments')}:`,
...missingArgsStrings,
chalk.gray(' See more help with --help'),
'',
help,
].join('\n'),
});
}
private _handleStdin(mode: StdinMode) {
switch (mode) {
case StdinMode.Stringified:
return (cachedStdinInput?.toString('utf8') ?? '').trim();
default:
return cachedStdinInput;
}
}
protected _buildParseArgsOption() {
const object = {
allowNegative: true,
allowPositionals: true,
strict: true,
tokens: true,
options: {
help: helpFlagDefinition,
} as {
help: typeof helpFlagDefinition;
json: typeof jsonFlagDefinition;
[k: string]: ParseArgsOptionDescriptor;
},
} satisfies ParseArgsConfig;
if (this.ctor.flags) {
for (const [key, internalBuilderData] of Object.entries(this.ctor.flags)) {
if (typeof internalBuilderData === 'string') {
throw new RangeError('Do not provide the string for the json flag! It is a type level assertion!');
}
// Skip the "json" flag, as it is set by enableJsonFlag
if (key.toLowerCase() === 'json') {
continue;
}
let flagKey = kebabCaseString(camelCaseToKebabCase(key)).toLowerCase();
// node handles `no-` flags by negating the flag, so we need to handle that differently if we register a flag with a "no-" prefix
if (flagKey.startsWith('no-')) {
flagKey = flagKey.slice(3);
}
const flagDefinitions = internalBuilderData.builder(flagKey);
for (const { flagName, option } of flagDefinitions) {
object.options![flagName] = option;
}
}
}
if (this.ctor.enableJsonFlag) {
object.options!.json = jsonFlagDefinition;
}
return object;
}
static registerCommand(entrypoint: string) {
registerCommandForHelpGeneration(entrypoint, this as typeof BuiltApifyCommand);
// Register the command itself
commandRegistry.set(this.name, this as typeof BuiltApifyCommand);
// Register all aliases
if (this.aliases?.length) {
for (const alias of this.aliases) {
commandRegistry.set(alias, this as typeof BuiltApifyCommand);
}
}
if (this.hiddenAliases?.length) {
for (const alias of this.hiddenAliases) {
commandRegistry.set(alias, this as typeof BuiltApifyCommand);
}
}
// For each subcommand, register it and all its aliases
if (this.subcommands?.length) {
for (const subcommand of this.subcommands) {
// Base name + subcommand name
commandRegistry.set(`${this.name} ${subcommand.name}`, subcommand as typeof BuiltApifyCommand);
// All aliases of the base command + subcommand name
if (this.aliases?.length) {
for (const alias of this.aliases) {
commandRegistry.set(`${alias} ${subcommand.name}`, subcommand as typeof BuiltApifyCommand);
}
}
// All hidden aliases of the base command + subcommand name
if (this.hiddenAliases?.length) {
for (const alias of this.hiddenAliases) {
commandRegistry.set(`${alias} ${subcommand.name}`, subcommand as typeof BuiltApifyCommand);
}
}
// For each subcommand, register all its aliases
if (subcommand.aliases?.length) {
for (const subcommandAlias of subcommand.aliases) {
// Base name + subcommand alias
commandRegistry.set(`${this.name} ${subcommandAlias}`, subcommand as typeof BuiltApifyCommand);
// All aliases of the base command + subcommand alias
if (this.aliases?.length) {
for (const alias of this.aliases) {
commandRegistry.set(
`${alias} ${subcommandAlias}`,
subcommand as typeof BuiltApifyCommand,
);
}
}
// All hidden aliases of the base command + subcommand alias
if (this.hiddenAliases?.length) {
for (const alias of this.hiddenAliases) {
commandRegistry.set(
`${alias} ${subcommandAlias}`,
subcommand as typeof BuiltApifyCommand,
);
}
}
}
}
// For each subcommand, register all its hidden aliases
if (subcommand.hiddenAliases?.length) {
for (const subcommandAlias of subcommand.hiddenAliases) {
// Base name + subcommand hidden alias
commandRegistry.set(`${this.name} ${subcommandAlias}`, subcommand as typeof BuiltApifyCommand);
// All aliases of the base command + subcommand hidden alias
if (this.aliases?.length) {
for (const alias of this.aliases) {
commandRegistry.set(
`${alias} ${subcommandAlias}`,
subcommand as typeof BuiltApifyCommand,
);
}
}
// All hidden aliases of the base command + subcommand hidden alias
if (this.hiddenAliases?.length) {
for (const alias of this.hiddenAliases) {
commandRegistry.set(
`${alias} ${subcommandAlias}`,
subcommand as typeof BuiltApifyCommand,
);
}
}
}
}
}
}
}
}
// Utility type to extract only the keys that are optional
type ExtractOptionalFlagKeys<Cmd extends typeof BuiltApifyCommand> = {
[K in keyof InferFlagsFromCommand<Cmd['flags'], true>]: [undefined] extends [
InferFlagsFromCommand<Cmd['flags'], true>[K],
]
? K
: never;
}[keyof InferFlagsFromCommand<Cmd['flags'], true>];
type ExtractOptionalArgKeys<Cmd extends typeof BuiltApifyCommand> = {
[K in keyof InferArgsFromCommand<Cmd['args']>]: [undefined] extends [InferArgsFromCommand<Cmd['args']>[K]]
? K
: never;
}[keyof InferArgsFromCommand<Cmd['args']>];
// Messy type...
type StaticArgsFlagsInput<Cmd extends typeof BuiltApifyCommand> = Omit<
{
// This ensures we only get the required args
[K in Exclude<
keyof InferArgsFromCommand<Cmd['args']>,
ExtractOptionalArgKeys<Cmd>
> as `args_${string & K}`]: InferArgsFromCommand<Cmd['args']>[K];
},
// Omit args_json as it is used only to throw an error if the user provides it
'args_json'
> &
Omit<
{
// Fill in the rest of the args, this will not override what the code above does
[K in keyof InferArgsFromCommand<Cmd['args']> as `args_${string & K}`]?: InferArgsFromCommand<
Cmd['args']
>[K];
},
'args_json'
> &
Omit<
{
// This ensures we only ever get the required flags into this object, as `key?: type` and `key: type | undefined` are not the same (one is optionally present, the other is mandatory)
[K in Exclude<
keyof InferFlagsFromCommand<Cmd['flags'], true>,
ExtractOptionalFlagKeys<Cmd>
> as `flags_${string & K}`]: InferFlagsFromCommand<Cmd['flags'], true>[K];
},
// Omit flags_json as it is used only to throw an error if the user provides it
'flags_json'
> &
Omit<
{
// Fill in the rest of the flags, this will not override what the code above does
[K in keyof InferFlagsFromCommand<Cmd['flags'], true> as `flags_${string & K}`]?: InferFlagsFromCommand<
Cmd['flags'],
true
>[K];
},
// Omit flags_json as it is used only to throw an error if the user provides it
'flags_json'
> & {
// Define it at the end exactly like it is
flags_json?: boolean;
};
export async function testRunCommand<Cmd extends typeof BuiltApifyCommand>(
command: Cmd,
argsFlags: StaticArgsFlagsInput<Cmd>,
) {
return internalRunCommand('test-cli', command, argsFlags);
}
export async function internalRunCommand<Cmd extends typeof BuiltApifyCommand>(
entrypoint: string,
command: Cmd,
argsFlags: StaticArgsFlagsInput<Cmd>,
) {
// This is very much yolo'd in, but its purpose is for testing only
const rawObject: ParseResult = {
positionals: [],
values: {},
tokens: [],
};
let positionalIndex = 0;
for (const [key, value] of Object.entries(argsFlags)) {
const [type, rawKey] = key.split('_');
if (type === 'args') {
rawObject.positionals[positionalIndex++] = value as unknown as string;
} else {
const yargsFlagName = kebabCaseString(camelCaseToKebabCase(rawKey)).toLowerCase();
// We handle "no-" flags differently, as yargs handles them by negating the base flag name (no-prompt -> prompt=false)
if (yargsFlagName.startsWith('no-')) {
rawObject.values[yargsFlagName.slice(3)] = !value;
} else {
rawObject.values[yargsFlagName] = value;
}
}
}
const instance = new (command as typeof BuiltApifyCommand)(entrypoint, command.name, command.name);
// eslint-disable-next-line dot-notation
instance['skipTelemetry'] = true;
// eslint-disable-next-line dot-notation
await instance['_run'](rawObject);
}
export declare class BuiltApifyCommand extends ApifyCommand {
override run(): Awaitable<void>;
}