Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions packages/astro/src/cli/create-key/core/create-key.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import type { Logger } from '../../../core/logger/core.js';
import type { KeyGenerator } from '../definitions.js';
import { defineCommand } from '../domain/command.js';

interface CreateKeyOptions {
interface Options {
logger: Logger;
keyGenerator: KeyGenerator;
}

export async function createKey({ logger, keyGenerator }: CreateKeyOptions) {
const key = await keyGenerator.generate();
export const createKeyCommand = defineCommand({
help: {
commandName: 'astro create-key',
tables: {
Flags: [['--help (-h)', 'See all available flags.']],
},
description: 'Generates a key to encrypt props passed to server islands.',
},
async run({ logger, keyGenerator }: Options) {
const key = await keyGenerator.generate();

logger.info(
'crypto',
`Generated a key to encrypt props passed to server islands. To reuse the same key across builds, set this value as ASTRO_KEY in an environment variable on your build server.

ASTRO_KEY=${key}`,
);
}
logger.info(
'crypto',
`Generated a key to encrypt props passed to server islands. To reuse the same key across builds, set this value as ASTRO_KEY in an environment variable on your build server.\n\nASTRO_KEY=${key}`,
);
},
});
25 changes: 25 additions & 0 deletions packages/astro/src/cli/create-key/definitions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
import type { AnyCommand } from './domain/command.js';
import type { HelpPayload } from './domain/help-payload.js';

export interface KeyGenerator {
generate: () => Promise<string>;
}

export interface HelpDisplay {
shouldFire: () => boolean;
show: (payload: HelpPayload) => void;
}

export interface TextStyler {
bgWhite: (msg: string) => string;
black: (msg: string) => string;
dim: (msg: string) => string;
green: (msg: string) => string;
bold: (msg: string) => string;
bgGreen: (msg: string) => string;
}

export interface AstroVersionProvider {
getVersion: () => string;
}

export interface CommandRunner {
run: <T extends AnyCommand>(command: T, ...args: Parameters<T['run']>) => ReturnType<T['run']>;
}
12 changes: 12 additions & 0 deletions packages/astro/src/cli/create-key/domain/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { HelpPayload } from './help-payload.js';

interface Command<T extends (...args: Array<any>) => any> {
help: HelpPayload;
run: T;
}

export type AnyCommand = Command<(...args: Array<any>) => any>;

export function defineCommand<T extends AnyCommand>(command: T) {
return command;
}
7 changes: 7 additions & 0 deletions packages/astro/src/cli/create-key/domain/help-payload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface HelpPayload {
commandName: string;
headline?: string;
usage?: string;
tables?: Record<string, [command: string, help: string][]>;
description?: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { AstroVersionProvider } from '../definitions.js';

export function createBuildTimeAstroVersionProvider(): AstroVersionProvider {
return {
getVersion() {
return process.env.PACKAGE_VERSION ?? '';
},
};
}
17 changes: 17 additions & 0 deletions packages/astro/src/cli/create-key/infra/cli-command-runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { CommandRunner, HelpDisplay } from '../definitions.js';

interface Options {
helpDisplay: HelpDisplay;
}

export function createCliCommandRunner({ helpDisplay }: Options): CommandRunner {
return {
run(command, ...args) {
if (helpDisplay.shouldFire()) {
helpDisplay.show(command.help);
return;
}
return command.run(...args);
},
};
}
6 changes: 6 additions & 0 deletions packages/astro/src/cli/create-key/infra/kleur-text-styler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import * as colors from 'kleur/colors';
import type { TextStyler } from '../definitions.js';

export function createKleurTextStyler(): TextStyler {
return colors;
}
76 changes: 76 additions & 0 deletions packages/astro/src/cli/create-key/infra/logger-help-display.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import type { Logger } from '../../../core/logger/core.js';
import type { Flags } from '../../flags.js';
import type { AstroVersionProvider, HelpDisplay, TextStyler } from '../definitions.js';

interface Options {
logger: Logger;
textStyler: TextStyler;
astroVersionProvider: AstroVersionProvider;
// TODO: find something better
flags: Flags;
}

export function createLoggerHelpDisplay({
logger,
flags,
textStyler,
astroVersionProvider,
}: Options): HelpDisplay {
return {
shouldFire() {
return !!(flags.help || flags.h);
},
show({ commandName, description, headline, tables, usage }) {
const linebreak = () => '';
const title = (label: string) => ` ${textStyler.bgWhite(textStyler.black(` ${label} `))}`;
const table = (rows: [string, string][], { padding }: { padding: number }) => {
const split = process.stdout.columns < 60;
let raw = '';

for (const row of rows) {
if (split) {
raw += ` ${row[0]}\n `;
} else {
raw += `${`${row[0]}`.padStart(padding)}`;
}
raw += ' ' + textStyler.dim(row[1]) + '\n';
}

return raw.slice(0, -1); // remove latest \n
};

let message = [];

if (headline) {
message.push(
linebreak(),
` ${textStyler.bgGreen(textStyler.black(` ${commandName} `))} ${textStyler.green(
`v${astroVersionProvider.getVersion()}`,
)} ${headline}`,
);
}

if (usage) {
message.push(linebreak(), ` ${textStyler.green(commandName)} ${textStyler.bold(usage)}`);
}

if (tables) {
function calculateTablePadding(rows: [string, string][]) {
return rows.reduce((val, [first]) => Math.max(val, first.length), 0) + 2;
}

const tableEntries = Object.entries(tables);
const padding = Math.max(...tableEntries.map(([, rows]) => calculateTablePadding(rows)));
for (const [tableTitle, tableRows] of tableEntries) {
message.push(linebreak(), title(tableTitle), table(tableRows, { padding }));
}
}

if (description) {
message.push(linebreak(), `${description}`);
}

logger.info('SKIP_FORMAT', message.join('\n') + '\n');
},
};
}
35 changes: 27 additions & 8 deletions packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,16 +109,35 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
return;
}
case 'create-key': {
const [{ createKey }, { createLoggerFromFlags }, { createCryptoKeyGenerator }] =
await Promise.all([
import('./create-key/core/create-key.js'),
import('./flags.js'),
import('./create-key/infra/crypto-key-generator.js'),
]);
const [
{ createLoggerFromFlags },
{ createCryptoKeyGenerator },
{ createKleurTextStyler },
{ createBuildTimeAstroVersionProvider },
{ createLoggerHelpDisplay },
{ createCliCommandRunner },
{ createKeyCommand },
] = await Promise.all([
import('./flags.js'),
import('./create-key/infra/crypto-key-generator.js'),
import('./create-key/infra/kleur-text-styler.js'),
import('./create-key/infra/build-time-astro-version-provider.js'),
import('./create-key/infra/logger-help-display.js'),
import('./create-key/infra/cli-command-runner.js'),
import('./create-key/core/create-key.js'),
]);
const logger = createLoggerFromFlags(flags);
const keyGenerator = createCryptoKeyGenerator();
await createKey({ logger, keyGenerator });
return;
const textStyler = createKleurTextStyler();
const astroVersionProvider = createBuildTimeAstroVersionProvider();
const helpDisplay = createLoggerHelpDisplay({
logger,
flags,
textStyler,
astroVersionProvider,
});
const runner = createCliCommandRunner({ helpDisplay });
return await runner.run(createKeyCommand, { logger, keyGenerator });
}
case 'docs': {
const { docs } = await import('./docs/index.js');
Expand Down
1 change: 1 addition & 0 deletions packages/astro/src/core/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ export function formatErrorMessage(err: ErrorWithMetadata, showFullStacktrace: b
return output.join('\n');
}

/** @deprecated Migrate to HelpDisplay */
export function printHelp({
commandName,
headline,
Expand Down
Loading