@nestjs/schematics
Version:
The generators behind the Nest CLI: scaffold NestJS applications, libraries, modules, controllers, services and CRUD resources.
145 lines (144 loc) • 6.13 kB
JavaScript
import { join, normalize, strings } from '@angular-devkit/core';
import { apply, chain, filter, mergeWith, move, noop, renameTemplateFiles, SchematicsException, template, url, } from '@angular-devkit/schematics';
import { basename, parse } from 'path';
import { formatFiles } from '../../utils/format-files.rule.js';
import { normalizeToKebabOrSnakeCase } from '../../utils/formatting.js';
import { DEFAULT_AUTHOR, DEFAULT_DESCRIPTION, DEFAULT_LANGUAGE, DEFAULT_VERSION, } from '../defaults.js';
export function main(options) {
options.name = normalizeToKebabOrSnakeCase(options.name.toString());
const path = !options.directory || options.directory === 'undefined'
? options.name
: options.directory;
options = transform(options);
return (host, context) => {
const existing = keepOrRefuseExistingFiles(host, context, path);
return chain([
mergeWith(apply(generate(options, path), [existing])),
options.minimal
? mergeWith(apply(generateMinimalSharedFiles(options, path), [existing]))
: noop(),
options.format === true ? formatFiles() : noop(),
]);
};
}
const KEPT_IF_PRESENT = ['README.md', '.gitignore', 'CLAUDE.md'];
function keepOrRefuseExistingFiles(host, context, path) {
const root = normalize(`/${path}`);
const kept = KEPT_IF_PRESENT.map((file) => join(root, file));
return (generated) => {
const conflicts = [];
const skipped = [];
generated.visit((file) => {
if (!host.exists(file)) {
return;
}
(kept.includes(file) ? skipped : conflicts).push(file);
});
const display = (file) => file.slice(root.length).replace(/^\//, '');
if (conflicts.length > 0) {
const where = root === '/' ? 'the current directory' : `"${path}"`;
throw new SchematicsException(`Cannot create the application in ${where}: these files already exist and would be overwritten:\n` +
conflicts
.sort()
.map((file) => ` ${display(file)}\n`)
.join('') +
'Nothing was written. Move them elsewhere (and back afterwards), or create the application in a directory without them.');
}
for (const file of skipped) {
generated.delete(file);
context.logger.info(`Kept the existing ${display(file)} (the generated one was not written).`);
if (display(file) === 'CLAUDE.md' &&
!host.readText(file).includes('@AGENTS.md')) {
context.logger.info('Add a line "@AGENTS.md" to it, so Claude Code also reads AGENTS.md.');
}
}
return generated;
};
}
function transform(options) {
const target = Object.assign({}, options);
target.author = target.author ? target.author : DEFAULT_AUTHOR;
target.description = target.description
? target.description
: DEFAULT_DESCRIPTION;
target.language = target.language ? target.language : DEFAULT_LANGUAGE;
target.name = resolvePackageName(target.name.toString());
target.version = target.version ? target.version : DEFAULT_VERSION;
target.type = target.type ?? 'esm';
target.observe = target.observe ?? false;
target.minimal = target.minimal ?? false;
const skills = target.skills ?? [];
target.skills = [
...new Set(Array.isArray(skills) ? skills : [skills]),
];
target.spec = target.spec ?? true;
if (target.minimal && target.language !== 'ts') {
throw new SchematicsException('A minimal application is TypeScript only: JavaScript needs Babel and its own entry file to run decorators, so it would not stay one file.');
}
if (target.minimal && target.type !== 'esm') {
throw new SchematicsException('A minimal application is ESM only (type "esm"): generate a standard application to use CommonJS.');
}
target.specFileSuffix = normalizeToKebabOrSnakeCase(options.specFileSuffix || 'spec');
target.packageManager =
!target.packageManager || target.packageManager === 'undefined'
? 'npm'
: target.packageManager;
target.dependencies = target.dependencies ? target.dependencies : '';
target.devDependencies = target.devDependencies ? target.devDependencies : '';
return target;
}
function resolvePackageName(path) {
const { base: baseFilename, dir: dirname } = parse(path);
if (baseFilename === '.') {
return basename(process.cwd());
}
if (dirname.match(/^@[^\s]/)) {
return `${dirname}/${baseFilename}`;
}
return baseFilename;
}
function resolveTemplateDir(options) {
if (options.minimal) {
return 'ts-minimal';
}
return options.type === 'esm' && options.language === 'ts'
? 'ts-esm'
: options.language;
}
function generate(options, path) {
const templateDir = resolveTemplateDir(options);
return apply(url(join('./files', templateDir)), [
options.spec
? noop()
: filter((path) => !isTestFile(path, options.language || 'ts')),
forClaudeCode(options) ? noop() : filter((path) => path !== '/CLAUDE.md'),
template({
...strings,
...options,
}),
renameTemplateFiles(),
move(path),
]);
}
function forClaudeCode(options) {
return (options.skills ?? []).some((target) => target === 'all' || target === 'claude');
}
function isTestFile(path, languageExtension) {
return (path.endsWith(`__specFileSuffix__.${languageExtension}`) ||
path.startsWith('/test/') ||
/^\/(jest|vitest)\.config(\.e2e)?\.(ts|js)$/.test(path));
}
function generateMinimalSharedFiles(options, path) {
return apply(url(join('./files', 'ts')), [
filter((path) => [
'/AGENTS.md',
...(forClaudeCode(options) ? ['/CLAUDE.md'] : []),
'/.gitignore',
].includes(path)),
template({
...strings,
...options,
}),
move(path),
]);
}