-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathutils.js
More file actions
792 lines (700 loc) · 23.1 KB
/
Copy pathutils.js
File metadata and controls
792 lines (700 loc) · 23.1 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
import arg from 'arg';
import chalk from 'chalk';
import fs from 'fs';
import fse from 'fs-extra';
import inquirer from 'inquirer';
import path from 'path';
import os from 'os';
import { Listr } from 'listr2'
import { fileURLToPath, pathToFileURL } from 'url';
import {ConnectionString} from 'connection-string';
import { exec } from 'child_process';
import Handlebars from 'handlebars';
import { promisify } from 'util';
import { resolveAdminforthVersionRange } from '../cli.js';
import { URL } from 'url'
import net from 'net'
const execAsync = promisify(exec);
const SUPPORTED_DB_URL_SCHEMES =['sqlite://', 'postgresql://', 'mongodb://', 'mysql://', 'clickhouse://'];
const PRISMA_MIGRATION_DB_PROTOCOLS = ['sqlite', 'postgres', 'postgresql', 'mysql'];
const DEFAULT_DB_URL = 'sqlite://.db.sqlite';
const ADMINUSER_TABLE_EXAMPLE_NOTE = 'This is only an example schema. We recommend using your favorite migration tool to create and evolve this table, and adding database indexes or constraints only when they match your project requirements.';
export function parseArgumentsIntoOptions(rawArgs) {
const args = arg(
{
'--app-name': String,
'--db': String,
'--use-npm': Boolean,
// you can add more flags here if needed
},
{
argv: rawArgs.slice(1), // skip "create-app"
}
);
return {
appName: args['--app-name'],
db: args['--db'],
useNpm: args['--use-npm'],
};
}
function generateAdminUserTableInstructions(provider) {
if (provider === 'postgresql') {
return `\`\`\`sql
CREATE TABLE adminuser (
id TEXT PRIMARY KEY,
email TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL,
created_at TIMESTAMP NOT NULL
);
\`\`\`
${ADMINUSER_TABLE_EXAMPLE_NOTE}`;
}
if (provider === 'mysql') {
return `\`\`\`sql
CREATE TABLE adminuser (
id VARCHAR(191) PRIMARY KEY,
email VARCHAR(191) NOT NULL,
password_hash TEXT NOT NULL,
role VARCHAR(191) NOT NULL,
created_at DATETIME NOT NULL
);
\`\`\`
${ADMINUSER_TABLE_EXAMPLE_NOTE}`;
}
if (provider === 'sqlite') {
return `\`\`\`sql
CREATE TABLE adminuser (
id TEXT PRIMARY KEY,
email TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL,
created_at DATETIME NOT NULL
);
\`\`\`
${ADMINUSER_TABLE_EXAMPLE_NOTE}`;
}
if (provider === 'clickhouse') {
return `\`\`\`sql
CREATE TABLE adminuser (
id String,
email String,
password_hash String,
role String,
created_at DateTime
)
ENGINE = MergeTree()
ORDER BY id;
\`\`\`
${ADMINUSER_TABLE_EXAMPLE_NOTE}`;
}
return null;
}
// Maps an AdminForth db provider to the matching `@adminforth/connector-*` package suffix.
function providerToConnectorName(provider) {
if (provider === 'postgresql') return 'postgres';
if (provider === 'mongodb') return 'mongo';
return provider;
}
// Returns the default-exported connector class for the given connector name.
// Connectors are optional peer dependencies, so they are not present during a
// fresh `npx adminforth create-app`. We first try to import an already-installed
// one (local development / monorepo), then fall back to installing it on demand.
async function loadConnectorClass(connectorName) {
const pkg = `@adminforth/connector-${connectorName}`;
try {
return (await import(pkg)).default;
} catch {
// Not installed in this context — install it on demand below.
}
console.log(chalk.dim(`\nInstalling ${pkg} to inspect the target database...`));
const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'adminforth-connector-'));
await fs.promises.writeFile(
path.join(tmpDir, 'package.json'),
JSON.stringify({ name: 'adminforth-connector-probe', version: '0.0.0', private: true, type: 'module' }),
);
// npm (>=7) installs the connector's `adminforth` peer dependency automatically,
// which is enough to import and run the connector for the emptiness probe.
await execAsync(`npm install ${pkg} --no-audit --no-fund --loglevel=error`, {
cwd: tmpDir,
env: process.env,
maxBuffer: 10 * 1024 * 1024,
});
const entry = path.join(tmpDir, 'node_modules', '@adminforth', `connector-${connectorName}`, 'dist', 'index.js');
return (await import(pathToFileURL(entry).href)).default;
}
// Decides whether the target database already contains user data and records the
// result on `options.existingDb`. When it does, AdminForth treats the database as
// "owned" by the user and skips Prisma scaffolding.
async function inspectDatabaseCleanState(options) {
const connectionString = parseConnectionString(options.db);
const provider = detectDbProvider(connectionString.protocol);
const dbConnString = connectionString.toString();
// Fast path for SQLite: a missing file is by definition a brand new database.
// Avoid connecting (which would otherwise create the file) and avoid pulling the
// connector for the common new-project case.
if (provider === 'sqlite') {
const sqliteFile = dbConnString.replace('sqlite://', '');
if (!sqliteFile || !fs.existsSync(sqliteFile)) {
options.existingDb = false;
return;
}
}
let Connector;
try {
Connector = await loadConnectorClass(providerToConnectorName(provider));
} catch (error) {
// Could not obtain the connector (e.g. offline). Treat the database as new so
// the normal Prisma flow stays available instead of failing create-app.
console.log(chalk.yellow(`\n⚠️ Could not load the database connector to inspect the database (${error.message}). Continuing as a new database.`));
options.existingDb = false;
return;
}
const connector = new Connector();
if (typeof connector.isDatabaseEmpty !== 'function') {
// Connector predates the isDatabaseEmpty() probe (version skew); cannot
// determine emptiness, so assume a new database and keep the Prisma flow.
options.existingDb = false;
return;
}
try {
await connector.setupClient(dbConnString);
} catch (error) {
if (provider === 'sqlite' && error.message?.includes('directory does not exist')) {
options.existingDb = false;
return;
}
throw error;
}
try {
options.existingDb = !(await connector.isDatabaseEmpty());
} finally {
if (typeof connector.close === 'function') {
await connector.close();
}
}
}
export async function promptForMissingOptions(options) {
const questions = [];
if (!options.appName) {
questions.push({
type: 'input',
name: 'appName',
message: 'Please specify the name of the app >',
default: 'adminforth-app',
});
};
if (!options.db) {
questions.push({
type: 'input',
name: 'db',
message: 'Please specify the database URL to use >',
default: DEFAULT_DB_URL,
});
};
if (!options.useNpm) {
questions.push({
type: 'select',
name: 'useNpm',
message: 'Select your package manager >',
choices: [
{ name: 'pnpm', value: false },
{ name: 'npm', value: true },
],
default: false,
});
}
const answers = await inquirer.prompt(questions);
const resolvedOptions = {
...options,
appName: options.appName || answers.appName,
db: options.db || answers.db,
useNpm: options.useNpm || answers.useNpm,
};
resolvedOptions.existingDb = false;
await inspectDatabaseCleanState(resolvedOptions);
if (
resolvedOptions.includePrismaMigrations === undefined &&
isPrismaMigrationDbUrl(resolvedOptions.db) &&
!resolvedOptions.existingDb
) {
const prismaAnswer = await inquirer.prompt([{
type: 'select',
name: 'includePrismaMigrations',
message: 'Include Prisma migrations? >',
choices: [
{ name: 'Yes', value: true },
{ name: 'No', value: false },
],
default: true,
}]);
resolvedOptions.includePrismaMigrations = prismaAnswer.includePrismaMigrations;
} else {
resolvedOptions.includePrismaMigrations = Boolean(resolvedOptions.includePrismaMigrations) && !resolvedOptions.existingDb;
}
return resolvedOptions;
}
function checkNodeVersion(minRequiredVersion = 20) {
const current = process.versions.node.split('.');
const major = parseInt(current[0], 10);
if (isNaN(major) || major < minRequiredVersion) {
throw new Error(
`Node.js v${minRequiredVersion}+ is required. You have ${process.versions.node}. ` +
`Please upgrade Node.js. We recommend using nvm for managing multiple Node.js versions.`
);
}
}
function parseConnectionString(dbUrl) {
return new ConnectionString(dbUrl);
}
function isPrismaMigrationDbUrl(dbUrl) {
try {
const connectionString = parseConnectionString(dbUrl);
return PRISMA_MIGRATION_DB_PROTOCOLS.includes(connectionString.protocol);
} catch {
return false;
}
}
function detectDbProvider(protocol) {
if (protocol.startsWith('sqlite')) {
return 'sqlite';
} else if (protocol.startsWith('postgres')) {
return 'postgresql';
} else if (protocol.startsWith('mongodb')) {
return 'mongodb';
} else if (protocol.startsWith('mysql')) {
return 'mysql';
} else if (protocol.startsWith('clickhouse')) {
return 'clickhouse';
}
const message = `Unknown database provider for ${protocol}. Supported database URL schemes: ${SUPPORTED_DB_URL_SCHEMES.join(', ')}.`;
throw new Error(message);
}
function generateDbUrlForPrisma(connectionString) {
if (!PRISMA_MIGRATION_DB_PROTOCOLS.includes(connectionString.protocol))
return null;
if (connectionString.protocol.startsWith('sqlite'))
return `file:${connectionString.host}`;
return connectionString.toString();
}
function generateDbUrlForPrismaProd(connectionString) {
if (!PRISMA_MIGRATION_DB_PROTOCOLS.includes(connectionString.protocol))
return null;
if (connectionString.protocol.startsWith('sqlite'))
return `file:/code/db/${connectionString.host}`;
return connectionString.toString();
}
function generateDbUrlForAfProd(connectionString) {
if (connectionString.protocol.startsWith('sqlite'))
return `sqlite:////code/db/${connectionString.host}`;
return connectionString.toString();
}
function initialChecks(options) {
return [
{
title: '👀 Checking Node.js version...',
task: () => checkNodeVersion(20)
},
{
title: '👀 Validating current working directory...',
task: () => checkForExistingPackageJson(options)
}
]
}
function checkForExistingPackageJson(options) {
const projectDir = path.join(process.cwd(), options.appName);
if (fs.existsSync(projectDir)) {
throw new Error(
`Directory "${options.appName}" already exists.\n` +
`Please remove it or use a different name.`
);
}
}
function checkIfDatabaseLocal(urlString) {
if (urlString.startsWith('sqlite')) {
return true;
}
try {
const url = new URL(urlString)
const host = url.hostname
if (!host) return false
// localhost
if (host === 'localhost') return true
// loopback ipv4
if (host === '127.0.0.1') return true
// loopback ipv6
if (host === '::1') return true
// private IP ranges
if (net.isIP(host)) {
if (
host.startsWith('10.') ||
host.startsWith('192.168.') ||
host.match(/^172\.(1[6-9]|2\d|3[0-1])\./)
) {
return true
}
}
return false
} catch {
return false
}
}
async function scaffoldProject(ctx, options, cwd) {
const projectDir = path.join(cwd, options.appName);
await fse.ensureDir(projectDir);
const connectionString = parseConnectionString(options.db);
const connectionStringProd = generateDbUrlForAfProd(connectionString);
const provider = detectDbProvider(connectionString.protocol);
const prismaDbUrl = generateDbUrlForPrisma(connectionString);
const prismaDbUrlProd = generateDbUrlForPrismaProd(connectionString);
ctx.skipPrismaSetup = !options.includePrismaMigrations || !prismaDbUrl;
const appName = options.appName;
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
// Prepare directories
ctx.customDir = path.join(projectDir, 'custom');
await fse.ensureDir(ctx.customDir);
await fse.ensureDir(path.join(projectDir, 'resources'));
// Copy static assets to `custom/assets`
const sourceAssetsDir = path.join(dirname, 'assets');
const targetAssetsDir = path.join(ctx.customDir, 'assets');
await fse.ensureDir(targetAssetsDir);
await fse.copy(sourceAssetsDir, targetAssetsDir);
// Write templated files
await writeTemplateFiles(dirname, projectDir, options.useNpm, options.includePrismaMigrations, {
dbUrl: connectionString.toString(),
dbUrlProd: connectionStringProd,
prismaDbUrl,
prismaDbUrlProd,
appName,
provider,
existingDb: options.existingDb,
nodeMajor: parseInt(process.versions.node.split('.')[0], 10),
sqliteFile: connectionString.protocol.startsWith('sqlite') ? connectionString.host : null,
});
return projectDir; // Return the new directory path
}
function getPackageManagerTemplateData(useNpm, nodeMajor) {
return {
packageManager: useNpm ? 'npm' : 'pnpm',
packageManagerRun: useNpm ? 'npm run' : 'pnpm',
packageManagerScriptArgSeparator: useNpm ? ' -- ' : ' ',
packageManagerExec: useNpm ? 'npx' : 'pnpm exec',
packageManagerEnvDev: useNpm ? 'npm run _env:dev --' : 'pnpm _env:dev',
packageManagerEnvProd: useNpm ? 'npm run _env:prod --' : 'pnpm _env:prod',
dockerBaseImage: useNpm ? `node:${nodeMajor}-slim` : 'devforth/node20-pnpm:latest',
dockerAdditionalManifestFiles: useNpm ? 'package-lock.json' : 'pnpm-lock.yaml pnpm-workspace.yaml',
dockerPackageInstallSubcommand: useNpm ? 'ci' : 'i',
};
}
async function writeTemplateFiles(dirname, cwd, useNpm, includePrismaMigrations, options) {
const {
dbUrl, prismaDbUrl, appName, provider, existingDb, nodeMajor,
dbUrlProd, prismaDbUrlProd, sqliteFile
} = options;
const packageManagerTemplateData = getPackageManagerTemplateData(useNpm, nodeMajor);
const adminforthVersion = await resolveAdminforthVersionRange();
const resolvedPrismaDbUrl = includePrismaMigrations ? prismaDbUrl : null;
const resolvedPrismaDbUrlProd = includePrismaMigrations ? prismaDbUrlProd : null;
const connectorProvider = providerToConnectorName(provider);
// Build a list of files to generate
const templateTasks = [
{
src: 'tsconfig.json.hbs',
dest: 'tsconfig.json',
data: {},
},
{
src: 'index.ts.hbs',
dest: 'index.ts',
data: { appName },
},
{
src: 'api.ts.hbs',
dest: 'api.ts',
data: {},
},
{
src: '.gitignore.hbs',
dest: '.gitignore',
data: {},
},
{
src: '.env.local.hbs',
dest: '.env.local',
data: { dbUrl: checkIfDatabaseLocal(dbUrl) ? dbUrl : null, prismaDbUrl: resolvedPrismaDbUrl },
},
{
src: '.env.prod.hbs',
dest: '.env.prod',
data: { prismaDbUrlProd: resolvedPrismaDbUrlProd, dbUrlProd },
},
{
src: 'readme.md.hbs',
dest: 'README.md',
data: {
dbUrl,
prismaDbUrl: resolvedPrismaDbUrl,
appName,
sqliteFile,
existingDb,
adminUserTableInstructions: existingDb ? generateAdminUserTableInstructions(provider) : null,
},
},
{
src: 'AGENTS.md.hbs',
dest: 'AGENTS.md',
data: { prismaDbUrl: resolvedPrismaDbUrl },
},
{
src: 'CLAUDE.md.hbs',
dest: 'CLAUDE.md',
data: {},
},
{
src: '.agents/skills/adminforth/SKILL.md.hbs',
dest: '.agents/skills/adminforth/SKILL.md',
data: { prismaDbUrl: resolvedPrismaDbUrl },
},
{
src: '.agents/skills/adminforth-permissions/SKILL.md.hbs',
dest: '.agents/skills/adminforth-permissions/SKILL.md',
data: {},
},
{
src: '.agents/skills/adminforth-hooks/SKILL.md.hbs',
dest: '.agents/skills/adminforth-hooks/SKILL.md',
data: {},
},
{
src: '.agents/skills/adminforth-custom-vue/SKILL.md.hbs',
dest: '.agents/skills/adminforth-custom-vue/SKILL.md',
data: {},
},
{
// We'll write .env using the same content as .env.sample
src: '.env.hbs',
dest: '.env',
data: { dbUrl, prismaDbUrl: resolvedPrismaDbUrl },
},
{
src: 'adminuser.ts.hbs',
dest: 'resources/adminuser.ts',
data: {},
},
{
src: 'custom/tsconfig.json.hbs',
dest: 'custom/tsconfig.json',
data: {},
},
{
src: '.dockerignore.hbs',
dest: '.dockerignore',
data: {
sqliteFile,
},
},
{
src: 'Dockerfile.hbs',
dest: 'Dockerfile',
data: {},
},
{
src: 'package.json.hbs',
dest: 'package.json',
data: {
appName,
adminforthVersion: adminforthVersion,
includePrismaMigrations: Boolean(resolvedPrismaDbUrl),
connectorProvider: connectorProvider,
},
},
{
src: 'custom/package.json.hbs',
dest: 'custom/package.json',
data: {}
},
{
src: 'globalPlugins.ts.hbs',
dest: 'globalPlugins.ts',
data: {},
}
];
if (!useNpm) {
templateTasks.push(
{
src: 'pnpm_templates/pnpm-workspace.yaml.hbs',
dest: 'pnpm-workspace.yaml',
data: {},
},
{
src: 'pnpm_templates/pnpm-lock.yaml.hbs',
dest: 'custom/pnpm-lock.yaml',
data: {},
}
)
}
if (resolvedPrismaDbUrl) {
templateTasks.push(
{
src: 'schema.prisma.hbs',
dest: 'schema.prisma',
data: { provider },
condition: Boolean(prismaDbUrl), // only create if prismaDbUrl is truthy
},
{
src: 'prisma.config.ts.hbs',
dest: 'prisma.config.ts',
data: {},
},
)
}
for (const task of templateTasks) {
// If a condition is specified and false, skip this file
if (task.condition === false) continue;
const destPath = path.join(cwd, task.dest);
await fse.ensureDir(path.dirname(destPath));
if (task.empty) {
await fs.promises.writeFile(destPath, '');
} else {
const templatePath = path.join(dirname, 'templates', task.src);
const compiled = renderHBSTemplate(templatePath, {
...packageManagerTemplateData,
...task.data,
});
await fs.promises.writeFile(destPath, compiled);
}
}
}
async function installDependenciesPnpm(ctx, cwd) {
const isWindows = process.platform === 'win32';
const nodeBinary = process.execPath;
const pnpmPath = path.join(path.dirname(nodeBinary), isWindows ? 'pnpm.cmd' : 'pnpm');
const customDir = ctx.customDir;
if (isWindows) {
const res = await Promise.all([
execAsync(`pnpm install`, { cwd, env: { PATH: process.env.PATH } }),
execAsync(`pnpm install`, { cwd: customDir, env: { PATH: process.env.PATH } }),
]);
} else {
const res = await Promise.all([
execAsync(`${nodeBinary} ${pnpmPath} install`, { cwd, env: { PATH: process.env.PATH } }),
execAsync(`${nodeBinary} ${pnpmPath} install`, { cwd: customDir, env: { PATH: process.env.PATH } }),
]);
}
}
async function installDependenciesNpm(ctx, cwd) {
const isWindows = process.platform === 'win32';
const nodeBinary = process.execPath;
const npmPath = path.join(path.dirname(nodeBinary), isWindows ? 'npm.cmd' : 'npm');
const customDir = ctx.customDir;
if (isWindows) {
const res = await Promise.all([
execAsync(`npm install`, { cwd, env: { PATH: process.env.PATH } }),
execAsync(`npm install`, { cwd: customDir, env: { PATH: process.env.PATH } }),
]);
} else {
const res = await Promise.all([
execAsync(`${nodeBinary} ${npmPath} install`, { cwd, env: { PATH: process.env.PATH } }),
execAsync(`${nodeBinary} ${npmPath} install`, { cwd: customDir, env: { PATH: process.env.PATH } }),
]);
}
}
function generateFinalInstructionsPnpm(skipPrismaSetup, options) {
let instruction = '⏭️ Run the following commands to get started:\n';
const provider = detectDbProvider(parseConnectionString(options.db).protocol);
const adminUserTableInstructions = options.existingDb ? generateAdminUserTableInstructions(provider) : null;
instruction += `
${chalk.dim('// Go to the project directory')}
${chalk.dim('$')}${chalk.cyan(` cd ${options.appName}`)}\n`;
if (!skipPrismaSetup)
instruction += `
${chalk.dim('// Generate and apply initial migration')}
${chalk.dim('$')}${chalk.cyan(' pnpm makemigration --name init && pnpm migrate:local')}\n`;
if (adminUserTableInstructions)
instruction += `
${chalk.dim('// Create the adminuser table in your database before starting the app')}
${adminUserTableInstructions}\n`;
instruction += `
${chalk.dim('// Start dev server with tsx watch for hot-reloading')}
${chalk.dim('$')}${chalk.cyan(' pnpm dev')}\n
`;
instruction += '😉 Happy coding!';
return instruction;
}
function generateFinalInstructionsNpm(skipPrismaSetup, options) {
let instruction = '⏭️ Run the following commands to get started:\n';
const provider = detectDbProvider(parseConnectionString(options.db).protocol);
const adminUserTableInstructions = options.existingDb ? generateAdminUserTableInstructions(provider) : null;
instruction += `
${chalk.dim('// Go to the project directory')}
${chalk.dim('$')}${chalk.cyan(` cd ${options.appName}`)}\n`;
if (!skipPrismaSetup)
instruction += `
${chalk.dim('// Generate and apply initial migration')}
${chalk.dim('$')}${chalk.cyan(' npm run makemigration -- --name init && npm run migrate:local')}\n`;
if (adminUserTableInstructions)
instruction += `
${chalk.dim('// Create the adminuser table in your database before starting the app')}
${adminUserTableInstructions}\n`;
instruction += `
${chalk.dim('// Start dev server with tsx watch for hot-reloading')}
${chalk.dim('$')}${chalk.cyan(' npm run dev')}\n
`;
instruction += '😉 Happy coding!';
return instruction;
}
function renderHBSTemplate(templatePath, data) {
// Example: renderHBRTemplate('path/to/template.hbs', {name: 'John Doe'})
const template = fs.readFileSync(templatePath, 'utf-8');
const compiled = Handlebars.compile(template);
return compiled(data);
}
export function prepareWorkflow(options) {
const cwd = process.cwd();
const tasks = new Listr([
{
title: '🔍 Initial checks...',
task: (_, task) =>
task.newListr(
initialChecks(options),
{ concurrent: true },
)
},
{
title: '🚀 Scaffolding your project...',
task: async (ctx) => {
ctx.projectDir = await scaffoldProject(ctx, options, cwd);
}
},
{
title: '📦 Installing dependencies...',
task: async (ctx) => {
if (options.useNpm) {
await installDependenciesNpm(ctx, ctx.projectDir);
} else {
await installDependenciesPnpm(ctx, ctx.projectDir);
}
}
},
{
title: '📝 Preparing final instructions...',
task: (ctx) => {
console.log(chalk.green(`✅ Successfully created your new Adminforth project in ${ctx.projectDir}!\n`));
if (options.useNpm) {
console.log(generateFinalInstructionsNpm(ctx.skipPrismaSetup, options));
} else {
console.log(generateFinalInstructionsPnpm(ctx.skipPrismaSetup, options));
}
console.log('\n\n');
}
}
],
{
rendererOptions: {collapseSubtasks: false},
concurrent: false,
exitOnError: true,
collectErrors: true,
});
return tasks;
}