-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli-adapter.ts
More file actions
548 lines (466 loc) · 18.5 KB
/
cli-adapter.ts
File metadata and controls
548 lines (466 loc) · 18.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
import type { InstallerAdapter, AdapterConfig } from './types.js';
import type { InstallerEventEmitter, InstallerEvents } from '../events.js';
import clack from '../../utils/clack.js';
import chalk from 'chalk';
import { getConfig } from '../settings.js';
import { ProgressTracker } from '../progress-tracker.js';
import { renderCompletionSummary } from '../../utils/summary-box.js';
/**
* CLI adapter that renders wizard events via clack.
*
* Subscribes to InstallerEventEmitter and translates events into
* clack UI operations (logs, spinners, prompts).
*/
export class CLIAdapter implements InstallerAdapter {
readonly emitter: InstallerEventEmitter;
private sendEvent: AdapterConfig['sendEvent'];
private debug: boolean;
private spinner: ReturnType<typeof clack.spinner> | null = null;
private isStarted = false;
private progress = new ProgressTracker();
// Store bound handlers for cleanup
private handlers = new Map<string, (...args: unknown[]) => void>();
// Queue for logs while prompt is active (parallel state issue)
private isPromptActive = false;
private pendingLogs: Array<() => void> = [];
// SIGINT handler for cleanup
private sigIntHandler: (() => void) | null = null;
// Long-running agent update interval
private agentUpdateInterval: NodeJS.Timeout | null = null;
private agentStartTime: number | null = null;
private lastFileOperation: string | null = null;
constructor(config: AdapterConfig) {
this.emitter = config.emitter;
this.sendEvent = config.sendEvent;
this.debug = config.debug ?? false;
}
/**
* Queue a log call if a prompt is active, otherwise execute immediately.
*/
private queueableLog(logFn: () => void): void {
if (this.isPromptActive) {
this.pendingLogs.push(logFn);
} else {
logFn();
}
}
/**
* Flush any queued logs after prompt completes.
*/
private flushPendingLogs(): void {
const logs = this.pendingLogs.splice(0);
logs.forEach((fn) => fn());
}
async start(): Promise<void> {
if (this.isStarted) return;
this.isStarted = true;
// Show intro
const config = getConfig();
if (config.branding.showAsciiArt) {
const art = config.branding.useCompact ? config.branding.compactAsciiArt : config.branding.asciiArt;
console.log(chalk.cyan(art));
console.log();
} else {
clack.intro('Welcome to the WorkOS AuthKit installer');
}
// Handle Ctrl+C gracefully
const handleSigInt = () => {
if (this.spinner) {
this.spinner.stop('Cancelled');
this.spinner = null;
}
this.stopAgentUpdates();
clack.log.warn('Installer cancelled');
clack.outro('Your project was not modified');
process.exit(0);
};
process.on('SIGINT', handleSigInt);
this.sigIntHandler = handleSigInt;
// Subscribe to state events for progress tracking
this.subscribe('state:enter', this.handleStateEnter);
this.subscribe('state:exit', this.handleStateExit);
// Subscribe to events that require UI rendering
this.subscribe('auth:success', this.handleAuthSuccess);
this.subscribe('auth:failure', this.handleAuthFailure);
this.subscribe('detection:complete', this.handleDetectionComplete);
this.subscribe('detection:none', this.handleDetectionNone);
this.subscribe('git:dirty', this.handleGitDirty);
this.subscribe('credentials:found', this.handleCredentialsFound);
this.subscribe('credentials:request', this.handleCredentialsRequest);
this.subscribe('credentials:env:prompt', this.handleEnvScanPrompt);
this.subscribe('device:started', this.handleDeviceStarted);
this.subscribe('device:success', this.handleDeviceSuccess);
this.subscribe('staging:fetching', this.handleStagingFetching);
this.subscribe('staging:success', this.handleStagingSuccess);
this.subscribe('credentials:env:found', this.handleEnvCredentialsFound);
this.subscribe('config:complete', this.handleConfigComplete);
this.subscribe('agent:start', this.handleAgentStart);
this.subscribe('agent:progress', this.handleAgentProgress);
this.subscribe('file:write', this.handleFileWrite);
this.subscribe('file:edit', this.handleFileEdit);
this.subscribe('validation:start', this.handleValidationStart);
this.subscribe('validation:issues', this.handleValidationIssues);
this.subscribe('validation:complete', this.handleValidationComplete);
this.subscribe('complete', this.handleComplete);
this.subscribe('error', this.handleError);
// Branch check events
this.subscribe('branch:prompt', this.handleBranchPrompt);
this.subscribe('branch:created', this.handleBranchCreated);
// Post-install events
this.subscribe('postinstall:changes', this.handlePostInstallChanges);
this.subscribe('postinstall:commit:prompt', this.handleCommitPrompt);
this.subscribe('postinstall:commit:generating', this.handleCommitGenerating);
this.subscribe('postinstall:commit:success', this.handleCommitSuccess);
this.subscribe('postinstall:commit:failed', this.handleCommitFailed);
this.subscribe('postinstall:pr:prompt', this.handlePrPrompt);
this.subscribe('postinstall:pr:generating', this.handlePrGenerating);
this.subscribe('postinstall:pr:pushing', this.handlePrPushing);
this.subscribe('postinstall:pr:success', this.handlePrSuccess);
this.subscribe('postinstall:pr:failed', this.handlePrFailed);
this.subscribe('postinstall:push:failed', this.handlePushFailed);
this.subscribe('postinstall:manual', this.handleManualInstructions);
}
async stop(): Promise<void> {
if (!this.isStarted) return;
// Remove SIGINT handler
if (this.sigIntHandler) {
process.off('SIGINT', this.sigIntHandler);
this.sigIntHandler = null;
}
// Stop agent updates
this.stopAgentUpdates();
// Unsubscribe from all events
for (const [event, handler] of this.handlers) {
this.emitter.off(event as keyof InstallerEvents, handler as never);
}
this.handlers.clear();
// Stop any active spinner
this.spinner?.stop();
this.spinner = null;
this.isStarted = false;
}
private stopAgentUpdates = (): void => {
if (this.agentUpdateInterval) {
clearInterval(this.agentUpdateInterval);
this.agentUpdateInterval = null;
}
this.agentStartTime = null;
this.lastFileOperation = null;
};
private stopSpinner(message: string): void {
if (this.spinner) {
this.spinner.stop(message);
this.spinner = null;
}
}
/** Debug logging - only outputs when debug mode is enabled */
private debugLog = (message: string): void => {
if (this.debug) {
console.log(chalk.dim(`[debug] ${message}`));
}
};
/**
* Helper to subscribe and track handlers for cleanup.
*/
private subscribe<K extends keyof InstallerEvents>(
event: K,
handler: (payload: InstallerEvents[K]) => void | Promise<void>,
): void {
const boundHandler = handler.bind(this);
this.handlers.set(event, boundHandler as (...args: unknown[]) => void);
this.emitter.on(event, boundHandler);
}
// ===== Event Handlers =====
private handleStateEnter = ({ state }: InstallerEvents['state:enter']): void => {
this.progress.enterPhase(state);
};
private handleStateExit = ({ state }: InstallerEvents['state:exit']): void => {
this.progress.exitPhase(state);
};
private handleAuthSuccess = (): void => {
clack.log.success('Authenticated');
};
private handleAuthFailure = ({ message }: InstallerEvents['auth:failure']): void => {
clack.log.error(`Auth failed: ${message}`);
clack.log.info('Visit https://dashboard.workos.com to verify your account');
};
private handleDetectionComplete = ({ integration }: InstallerEvents['detection:complete']): void => {
this.queueableLog(() => clack.log.success(`Detected ${chalk.bold(integration)}`));
};
private handleDetectionNone = (): void => {
this.queueableLog(() => clack.log.warn('Could not detect framework automatically'));
};
private handleCredentialsFound = (): void => {
clack.log.success('Found existing WorkOS credentials in .env.local');
};
private handleEnvScanPrompt = async ({ files }: InstallerEvents['credentials:env:prompt']): Promise<void> => {
this.isPromptActive = true;
const fileList = files.length === 1 ? files[0] : files.slice(0, 2).join(', ');
const confirmed = await clack.confirm({
message: `Found ${fileList}. Check for existing WorkOS credentials?`,
initialValue: true,
});
this.isPromptActive = false;
this.flushPendingLogs();
this.sendEvent({
type: clack.isCancel(confirmed) || !confirmed ? 'ENV_SCAN_DECLINED' : 'ENV_SCAN_APPROVED',
});
};
private handleDeviceStarted = ({ verificationUri, userCode }: InstallerEvents['device:started']): void => {
clack.log.info(`\nOpen this URL in your browser:\n`);
console.log(` ${chalk.cyan(verificationUri)}`);
console.log(`\nEnter code: ${chalk.bold(userCode)}\n`);
this.spinner = clack.spinner();
this.spinner.start('Waiting for authentication...');
};
private handleDeviceSuccess = (): void => {
// Spinner will be stopped by handleStagingFetching
};
private handleStagingFetching = (): void => {
if (this.spinner) {
this.spinner.stop('Authenticated');
}
this.spinner = clack.spinner();
this.spinner.start('Fetching your WorkOS credentials...');
};
private handleStagingSuccess = (): void => {
this.stopSpinner('Credentials fetched');
clack.log.success('WorkOS credentials retrieved automatically');
};
private handleEnvCredentialsFound = ({ sourcePath }: InstallerEvents['credentials:env:found']): void => {
clack.log.success(`Found existing WorkOS credentials in ${sourcePath}`);
};
private handleGitDirty = async ({ files }: InstallerEvents['git:dirty']): Promise<void> => {
clack.log.warn('You have uncommitted or untracked files:');
files.slice(0, 5).forEach((f) => clack.log.info(chalk.dim(` ${f}`)));
if (files.length > 5) {
clack.log.info(chalk.dim(` ... and ${files.length - 5} more`));
}
this.isPromptActive = true;
const confirmed = await clack.confirm({
message: 'Continue anyway?',
initialValue: false,
});
this.isPromptActive = false;
this.flushPendingLogs();
this.sendEvent({
type: clack.isCancel(confirmed) || !confirmed ? 'GIT_CANCELLED' : 'GIT_CONFIRMED',
});
};
private handleCredentialsRequest = async ({
requiresApiKey,
}: InstallerEvents['credentials:request']): Promise<void> => {
clack.log.step(`Get your credentials from ${chalk.cyan('https://dashboard.workos.com')}`);
const clientId = await clack.text({
message: 'Enter your WorkOS Client ID:',
placeholder: 'client_...',
validate: (value) => {
if (!value || value.trim().length === 0) {
return 'Client ID is required';
}
if (!value.startsWith('client_')) {
return 'Client ID should start with "client_"';
}
return undefined;
},
});
if (clack.isCancel(clientId)) {
this.sendEvent({ type: 'CANCEL' });
return;
}
let apiKey = '';
if (requiresApiKey) {
clack.log.info(chalk.dim('ℹ️ Your API key will be hidden for security and saved to .env.local'));
const apiKeyResult = await clack.password({
message: 'Enter your WorkOS API Key:',
validate: (value) => {
if (!value || value.trim().length === 0) {
return 'API Key is required';
}
if (!value.startsWith('sk_')) {
return 'API Key should start with "sk_"';
}
return undefined;
},
});
if (clack.isCancel(apiKeyResult)) {
this.sendEvent({ type: 'CANCEL' });
return;
}
apiKey = apiKeyResult as string;
} else {
clack.log.info(chalk.dim('ℹ️ Client-only SDK - API key not required'));
}
this.sendEvent({
type: 'CREDENTIALS_SUBMITTED',
apiKey,
clientId: clientId as string,
});
};
private handleConfigComplete = (): void => {
clack.log.success('Environment configured');
};
private handleAgentStart = (): void => {
this.agentStartTime = Date.now();
this.lastFileOperation = null;
this.spinner = clack.spinner();
this.spinner.start('Running AI agent...');
// Periodic status updates with elapsed time
this.agentUpdateInterval = setInterval(() => {
const elapsed = Math.round((Date.now() - (this.agentStartTime ?? Date.now())) / 1000);
const timeStr = elapsed >= 60 ? `${Math.floor(elapsed / 60)}m ${elapsed % 60}s` : `${elapsed}s`;
const detail = this.lastFileOperation ?? 'Working';
this.spinner?.message(`${detail} (${timeStr})`);
}, 2000);
};
private handleAgentProgress = ({ step, detail }: InstallerEvents['agent:progress']): void => {
const message = detail ? `${step}: ${detail}` : step;
this.spinner?.message(message);
};
private handleFileWrite = ({ path }: InstallerEvents['file:write']): void => {
const shortPath = path.split('/').slice(-2).join('/');
this.lastFileOperation = `Writing ${shortPath}`;
this.spinner?.message(this.lastFileOperation);
};
private handleFileEdit = ({ path }: InstallerEvents['file:edit']): void => {
const shortPath = path.split('/').slice(-2).join('/');
this.lastFileOperation = `Editing ${shortPath}`;
this.spinner?.message(this.lastFileOperation);
};
private handleValidationStart = (): void => {
this.stopAgentUpdates();
this.stopSpinner('Agent completed');
};
private handleValidationIssues = ({ issues }: InstallerEvents['validation:issues']): void => {
for (const issue of issues) {
if (issue.severity === 'error') {
clack.log.error(issue.message);
} else {
clack.log.warn(issue.message);
}
if (issue.hint) {
clack.log.info(`Hint: ${issue.hint}`);
}
}
};
private handleValidationComplete = ({ passed, issueCount }: InstallerEvents['validation:complete']): void => {
if (passed) {
clack.log.success('Validation passed');
} else {
clack.log.warn(`Validation found ${issueCount} issue(s)`);
}
};
private handleComplete = ({ success, summary }: InstallerEvents['complete']): void => {
this.stopAgentUpdates();
this.stopSpinner(success ? 'Done' : 'Failed');
console.log('');
console.log(renderCompletionSummary(success, summary));
console.log('');
};
private handleError = ({ message, stack }: InstallerEvents['error']): void => {
this.stopSpinner('Error');
this.stopAgentUpdates();
clack.log.error(message);
// Add actionable hints for common errors
if (message.includes('authentication') || message.includes('auth')) {
clack.log.info('Try running: workos auth logout && workos install');
}
if (message.includes('ENOENT') || message.includes('not found')) {
clack.log.info('Ensure you are in a project directory');
}
if (stack && this.debug) {
this.debugLog(stack);
}
};
private handleBranchPrompt = async ({ branch }: InstallerEvents['branch:prompt']): Promise<void> => {
this.isPromptActive = true;
const choice = await clack.select({
message: `You are on ${chalk.bold(branch)}. Create a feature branch?`,
options: [
{ value: 'create', label: 'Create feat/add-workos-authkit' },
{ value: 'continue', label: 'Continue on current branch' },
{ value: 'cancel', label: 'Cancel' },
],
});
this.isPromptActive = false;
this.flushPendingLogs();
if (clack.isCancel(choice) || choice === 'cancel') {
this.sendEvent({ type: 'BRANCH_CANCEL' });
} else if (choice === 'create') {
this.sendEvent({ type: 'BRANCH_CREATE' });
} else {
this.sendEvent({ type: 'BRANCH_CONTINUE' });
}
};
private handleBranchCreated = ({ branch }: InstallerEvents['branch:created']): void => {
this.queueableLog(() => clack.log.success(`Created branch ${chalk.bold(branch)}`));
};
// ===== Post-install Event Handlers =====
private handlePostInstallChanges = ({ files }: InstallerEvents['postinstall:changes']): void => {
this.debugLog(`Post-install: ${files.length} changed files detected`);
};
private handleCommitPrompt = async (): Promise<void> => {
this.isPromptActive = true;
const confirmed = await clack.confirm({
message: 'Commit the changes?',
initialValue: true,
});
this.isPromptActive = false;
this.flushPendingLogs();
this.sendEvent({
type: clack.isCancel(confirmed) || !confirmed ? 'COMMIT_DECLINED' : 'COMMIT_APPROVED',
});
};
private handleCommitGenerating = (): void => {
this.spinner = clack.spinner();
this.spinner.start('Generating commit message...');
};
private handleCommitSuccess = ({ message }: InstallerEvents['postinstall:commit:success']): void => {
this.stopSpinner('Committed');
clack.log.success(`Committed: ${chalk.dim(message)}`);
};
private handleCommitFailed = ({ error }: InstallerEvents['postinstall:commit:failed']): void => {
this.stopSpinner('Commit failed');
clack.log.error(`Commit failed: ${error}`);
};
private handlePrPrompt = async (): Promise<void> => {
this.isPromptActive = true;
const confirmed = await clack.confirm({
message: 'Create a pull request?',
initialValue: true,
});
this.isPromptActive = false;
this.flushPendingLogs();
this.sendEvent({
type: clack.isCancel(confirmed) || !confirmed ? 'PR_DECLINED' : 'PR_APPROVED',
});
};
private handlePrGenerating = (): void => {
this.spinner = clack.spinner();
this.spinner.start('Generating PR description...');
};
private handlePrPushing = (): void => {
if (this.spinner) {
this.spinner.message('Pushing to remote...');
} else {
this.spinner = clack.spinner();
this.spinner.start('Pushing to remote...');
}
};
private handlePrSuccess = ({ url }: InstallerEvents['postinstall:pr:success']): void => {
this.stopSpinner('PR created');
clack.log.success(`Pull request created: ${chalk.cyan(url)}`);
};
private handlePrFailed = ({ error }: InstallerEvents['postinstall:pr:failed']): void => {
this.stopSpinner('PR creation failed');
clack.log.error(`PR creation failed: ${error}`);
};
private handlePushFailed = ({ error }: InstallerEvents['postinstall:push:failed']): void => {
this.stopSpinner('Push failed');
clack.log.error(`Push failed: ${error}`);
};
private handleManualInstructions = ({ instructions }: InstallerEvents['postinstall:manual']): void => {
clack.log.info('GitHub CLI not found. Manual steps:');
console.log(chalk.dim(instructions));
};
}