nest-authme 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -762,8 +762,7 @@ var init_generator = __esm({
762
762
  } else if (config.orm === "prisma") {
763
763
  plan.push(
764
764
  { template: "prisma/prisma.service.ts.hbs", output: `${config.sourceRoot}/prisma/prisma.service.ts` },
765
- { template: "prisma/prisma.module.ts.hbs", output: `${config.sourceRoot}/prisma/prisma.module.ts` },
766
- { template: "prisma/schema.prisma.additions.hbs", output: "prisma-schema-additions.prisma" }
765
+ { template: "prisma/prisma.module.ts.hbs", output: `${config.sourceRoot}/prisma/prisma.module.ts` }
767
766
  );
768
767
  }
769
768
  if (config.features.emailService) {
@@ -1179,13 +1178,139 @@ var init_main_ts_updater = __esm({
1179
1178
  }
1180
1179
  });
1181
1180
 
1181
+ // src/installer/prisma-schema-updater.ts
1182
+ var fs6, import_execa, PrismaSchemaUpdater;
1183
+ var init_prisma_schema_updater = __esm({
1184
+ "src/installer/prisma-schema-updater.ts"() {
1185
+ "use strict";
1186
+ init_cjs_shims();
1187
+ fs6 = __toESM(require("fs-extra"));
1188
+ import_execa = require("execa");
1189
+ init_template_engine();
1190
+ init_config_builder();
1191
+ PrismaSchemaUpdater = class {
1192
+ constructor(schemaPath) {
1193
+ this.schemaPath = schemaPath;
1194
+ }
1195
+ backupPath = null;
1196
+ /**
1197
+ * Update prisma/schema.prisma with auth models
1198
+ */
1199
+ async update(config) {
1200
+ const exists = await fs6.pathExists(this.schemaPath);
1201
+ if (!exists) {
1202
+ return {
1203
+ updated: false,
1204
+ message: 'prisma/schema.prisma not found. Run "npx prisma init" first, then re-run nest-authme.',
1205
+ skippedModels: []
1206
+ };
1207
+ }
1208
+ const existingContent = await fs6.readFile(this.schemaPath, "utf-8");
1209
+ const skippedModels = [];
1210
+ const hasUser = /^\s*model\s+User\s*\{/m.test(existingContent);
1211
+ const hasRefreshToken = /^\s*model\s+RefreshToken\s*\{/m.test(existingContent);
1212
+ if (hasUser) {
1213
+ skippedModels.push("User");
1214
+ }
1215
+ if (hasRefreshToken && config.features.refreshTokens) {
1216
+ skippedModels.push("RefreshToken");
1217
+ }
1218
+ const needsUser = !hasUser;
1219
+ const needsRefreshToken = config.features.refreshTokens && !hasRefreshToken;
1220
+ if (!needsUser && !needsRefreshToken) {
1221
+ return {
1222
+ updated: false,
1223
+ message: `Models already exist in schema.prisma: ${skippedModels.join(", ")}. Please check that your existing models have all required auth fields.`,
1224
+ skippedModels
1225
+ };
1226
+ }
1227
+ const templateEngine = new TemplateEngine();
1228
+ const context = buildTemplateContext(config);
1229
+ let modelsContent = await templateEngine.render("prisma/schema.prisma.models.hbs", context);
1230
+ if (hasUser) {
1231
+ modelsContent = modelsContent.replace(/model\s+User\s*\{[^}]*\}\n?/s, "");
1232
+ }
1233
+ if (hasRefreshToken) {
1234
+ modelsContent = modelsContent.replace(/model\s+RefreshToken\s*\{[^}]*\}\n?/s, "");
1235
+ }
1236
+ modelsContent = modelsContent.replace(/\n{3,}/g, "\n\n").trim();
1237
+ if (!modelsContent) {
1238
+ return {
1239
+ updated: false,
1240
+ message: "No new models to add.",
1241
+ skippedModels
1242
+ };
1243
+ }
1244
+ await this.createBackup();
1245
+ try {
1246
+ const separator = "\n\n// === Auth models (added by nest-authme) ===\n\n";
1247
+ const updatedContent = existingContent.trimEnd() + separator + modelsContent + "\n";
1248
+ await fs6.writeFile(this.schemaPath, updatedContent, "utf-8");
1249
+ await this.tryPrismaFormat();
1250
+ const addedModels = [];
1251
+ if (needsUser) addedModels.push("User");
1252
+ if (needsRefreshToken) addedModels.push("RefreshToken");
1253
+ let message = `Added ${addedModels.join(", ")} model(s) to prisma/schema.prisma`;
1254
+ if (skippedModels.length > 0) {
1255
+ message += `. Skipped existing: ${skippedModels.join(", ")} (check for missing auth fields)`;
1256
+ }
1257
+ return {
1258
+ updated: true,
1259
+ message,
1260
+ skippedModels
1261
+ };
1262
+ } catch (error) {
1263
+ await this.restoreBackup();
1264
+ throw error;
1265
+ }
1266
+ }
1267
+ /**
1268
+ * Try to run prisma format for consistent indentation
1269
+ */
1270
+ async tryPrismaFormat() {
1271
+ try {
1272
+ await (0, import_execa.execa)("npx", ["prisma", "format"], {
1273
+ cwd: this.schemaPath.replace(/[/\\]prisma[/\\]schema\.prisma$/, ""),
1274
+ timeout: 15e3
1275
+ });
1276
+ } catch {
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Create backup of schema.prisma
1281
+ */
1282
+ async createBackup() {
1283
+ this.backupPath = `${this.schemaPath}.backup`;
1284
+ await fs6.copy(this.schemaPath, this.backupPath);
1285
+ }
1286
+ /**
1287
+ * Restore backup on failure
1288
+ */
1289
+ async restoreBackup() {
1290
+ if (this.backupPath && await fs6.pathExists(this.backupPath)) {
1291
+ await fs6.copy(this.backupPath, this.schemaPath, { overwrite: true });
1292
+ await fs6.remove(this.backupPath);
1293
+ }
1294
+ }
1295
+ /**
1296
+ * Clean up backup after success
1297
+ */
1298
+ async cleanupBackup() {
1299
+ if (this.backupPath && await fs6.pathExists(this.backupPath)) {
1300
+ await fs6.remove(this.backupPath);
1301
+ }
1302
+ }
1303
+ };
1304
+ }
1305
+ });
1306
+
1182
1307
  // src/installer/package-updater.ts
1183
- var fs6, PackageUpdater;
1308
+ var fs7, PackageUpdater;
1184
1309
  var init_package_updater = __esm({
1185
1310
  "src/installer/package-updater.ts"() {
1186
1311
  "use strict";
1187
1312
  init_cjs_shims();
1188
- fs6 = __toESM(require("fs-extra"));
1313
+ fs7 = __toESM(require("fs-extra"));
1189
1314
  PackageUpdater = class {
1190
1315
  constructor(packageJsonPath) {
1191
1316
  this.packageJsonPath = packageJsonPath;
@@ -1197,7 +1322,7 @@ var init_package_updater = __esm({
1197
1322
  async update(config) {
1198
1323
  await this.createBackup();
1199
1324
  try {
1200
- const packageJson = await fs6.readJSON(this.packageJsonPath);
1325
+ const packageJson = await fs7.readJSON(this.packageJsonPath);
1201
1326
  const deps = this.getDependencies(config);
1202
1327
  packageJson.dependencies = {
1203
1328
  ...packageJson.dependencies,
@@ -1211,7 +1336,7 @@ var init_package_updater = __esm({
1211
1336
  packageJson.devDependencies = this.sortObject(
1212
1337
  packageJson.devDependencies
1213
1338
  );
1214
- await fs6.writeJSON(this.packageJsonPath, packageJson, { spaces: 2 });
1339
+ await fs7.writeJSON(this.packageJsonPath, packageJson, { spaces: 2 });
1215
1340
  } catch (error) {
1216
1341
  await this.restoreBackup();
1217
1342
  throw error;
@@ -1293,23 +1418,23 @@ var init_package_updater = __esm({
1293
1418
  */
1294
1419
  async createBackup() {
1295
1420
  this.backupPath = `${this.packageJsonPath}.backup`;
1296
- await fs6.copy(this.packageJsonPath, this.backupPath);
1421
+ await fs7.copy(this.packageJsonPath, this.backupPath);
1297
1422
  }
1298
1423
  /**
1299
1424
  * Restore backup
1300
1425
  */
1301
1426
  async restoreBackup() {
1302
- if (this.backupPath && await fs6.pathExists(this.backupPath)) {
1303
- await fs6.copy(this.backupPath, this.packageJsonPath, { overwrite: true });
1304
- await fs6.remove(this.backupPath);
1427
+ if (this.backupPath && await fs7.pathExists(this.backupPath)) {
1428
+ await fs7.copy(this.backupPath, this.packageJsonPath, { overwrite: true });
1429
+ await fs7.remove(this.backupPath);
1305
1430
  }
1306
1431
  }
1307
1432
  /**
1308
1433
  * Clean up backup
1309
1434
  */
1310
1435
  async cleanupBackup() {
1311
- if (this.backupPath && await fs6.pathExists(this.backupPath)) {
1312
- await fs6.remove(this.backupPath);
1436
+ if (this.backupPath && await fs7.pathExists(this.backupPath)) {
1437
+ await fs7.remove(this.backupPath);
1313
1438
  }
1314
1439
  }
1315
1440
  };
@@ -1317,12 +1442,12 @@ var init_package_updater = __esm({
1317
1442
  });
1318
1443
 
1319
1444
  // src/installer/dependency-installer.ts
1320
- var import_execa, import_detect_package_manager, DependencyInstaller;
1445
+ var import_execa2, import_detect_package_manager, DependencyInstaller;
1321
1446
  var init_dependency_installer = __esm({
1322
1447
  "src/installer/dependency-installer.ts"() {
1323
1448
  "use strict";
1324
1449
  init_cjs_shims();
1325
- import_execa = require("execa");
1450
+ import_execa2 = require("execa");
1326
1451
  import_detect_package_manager = require("detect-package-manager");
1327
1452
  DependencyInstaller = class {
1328
1453
  /**
@@ -1332,7 +1457,7 @@ var init_dependency_installer = __esm({
1332
1457
  const packageManager = await this.detectPackageManager(cwd);
1333
1458
  console.log(`\u{1F4E6} Installing dependencies with ${packageManager}...`);
1334
1459
  try {
1335
- await (0, import_execa.execa)(packageManager, ["install"], {
1460
+ await (0, import_execa2.execa)(packageManager, ["install"], {
1336
1461
  cwd,
1337
1462
  stdio: "inherit"
1338
1463
  });
@@ -1349,7 +1474,7 @@ var init_dependency_installer = __esm({
1349
1474
  async installCapture(cwd) {
1350
1475
  const packageManager = await this.detectPackageManager(cwd);
1351
1476
  try {
1352
- const result = await (0, import_execa.execa)(packageManager, ["install"], {
1477
+ const result = await (0, import_execa2.execa)(packageManager, ["install"], {
1353
1478
  cwd,
1354
1479
  stdio: "pipe"
1355
1480
  });
@@ -1380,7 +1505,8 @@ __export(installer_exports, {
1380
1505
  AppModuleUpdater: () => AppModuleUpdater,
1381
1506
  DependencyInstaller: () => DependencyInstaller,
1382
1507
  MainTsUpdater: () => MainTsUpdater,
1383
- PackageUpdater: () => PackageUpdater
1508
+ PackageUpdater: () => PackageUpdater,
1509
+ PrismaSchemaUpdater: () => PrismaSchemaUpdater
1384
1510
  });
1385
1511
  var init_installer = __esm({
1386
1512
  "src/installer/index.ts"() {
@@ -1388,20 +1514,21 @@ var init_installer = __esm({
1388
1514
  init_cjs_shims();
1389
1515
  init_ast_updater();
1390
1516
  init_main_ts_updater();
1517
+ init_prisma_schema_updater();
1391
1518
  init_package_updater();
1392
1519
  init_dependency_installer();
1393
1520
  }
1394
1521
  });
1395
1522
 
1396
1523
  // src/gui/orchestrator.ts
1397
- var import_events, path5, fs7, GuiOrchestrator;
1524
+ var import_events, path5, fs8, GuiOrchestrator;
1398
1525
  var init_orchestrator = __esm({
1399
1526
  "src/gui/orchestrator.ts"() {
1400
1527
  "use strict";
1401
1528
  init_cjs_shims();
1402
1529
  import_events = require("events");
1403
1530
  path5 = __toESM(require("path"));
1404
- fs7 = __toESM(require("fs-extra"));
1531
+ fs8 = __toESM(require("fs-extra"));
1405
1532
  init_generator();
1406
1533
  init_template_engine();
1407
1534
  init_config_builder();
@@ -1425,7 +1552,7 @@ var init_orchestrator = __esm({
1425
1552
  for (const spec of plan) {
1426
1553
  const content = await templateEngine.render(spec.template, context);
1427
1554
  const fullPath = path5.join(projectInfo.root, spec.output);
1428
- const exists = await fs7.pathExists(fullPath);
1555
+ const exists = await fs8.pathExists(fullPath);
1429
1556
  files.push({
1430
1557
  path: spec.output,
1431
1558
  content,
@@ -1437,6 +1564,12 @@ var init_orchestrator = __esm({
1437
1564
  { path: `${config.sourceRoot}/main.ts`, description: "Add global JWT guard, ValidationPipe, Swagger setup" },
1438
1565
  { path: "package.json", description: "Add authentication dependencies" }
1439
1566
  ];
1567
+ if (config.orm === "prisma") {
1568
+ modifiedFiles.push({
1569
+ path: "prisma/schema.prisma",
1570
+ description: "Append User and RefreshToken models"
1571
+ });
1572
+ }
1440
1573
  return {
1441
1574
  files,
1442
1575
  modifiedFiles,
@@ -1471,6 +1604,26 @@ var init_orchestrator = __esm({
1471
1604
  errors.push(msg);
1472
1605
  return { success: false, filesCreated: result.filesCreated, filesSkipped: result.filesSkipped, errors, warnings };
1473
1606
  }
1607
+ if (config.orm === "prisma") {
1608
+ this.emitProgress("prisma-schema", "Updating prisma/schema.prisma...", "started");
1609
+ try {
1610
+ const { PrismaSchemaUpdater: PrismaSchemaUpdater2 } = await Promise.resolve().then(() => (init_installer(), installer_exports));
1611
+ const schemaPath = path5.join(projectInfo.root, "prisma", "schema.prisma");
1612
+ const prismaUpdater = new PrismaSchemaUpdater2(schemaPath);
1613
+ const prismaResult = await prismaUpdater.update(config);
1614
+ if (prismaResult.updated) {
1615
+ await prismaUpdater.cleanupBackup();
1616
+ this.emitProgress("prisma-schema", prismaResult.message, "completed");
1617
+ } else {
1618
+ this.emitProgress("prisma-schema", prismaResult.message, "warning");
1619
+ warnings.push(prismaResult.message);
1620
+ }
1621
+ } catch (error) {
1622
+ const msg = error instanceof Error ? error.message : "Unknown error";
1623
+ this.emitProgress("prisma-schema", "Could not update prisma/schema.prisma", "warning", msg);
1624
+ warnings.push("Could not update prisma/schema.prisma - add models manually");
1625
+ }
1626
+ }
1474
1627
  this.emitProgress("ast-main-ts", "Updating main.ts...", "started");
1475
1628
  try {
1476
1629
  const { MainTsUpdater: MainTsUpdater2 } = await Promise.resolve().then(() => (init_installer(), installer_exports));
@@ -1522,14 +1675,14 @@ var init_orchestrator = __esm({
1522
1675
  });
1523
1676
 
1524
1677
  // src/gui/server.ts
1525
- var http, path6, fs8, GuiServer;
1678
+ var http, path6, fs9, GuiServer;
1526
1679
  var init_server = __esm({
1527
1680
  "src/gui/server.ts"() {
1528
1681
  "use strict";
1529
1682
  init_cjs_shims();
1530
1683
  http = __toESM(require("http"));
1531
1684
  path6 = __toESM(require("path"));
1532
- fs8 = __toESM(require("fs-extra"));
1685
+ fs9 = __toESM(require("fs-extra"));
1533
1686
  init_analyzer();
1534
1687
  init_prompts();
1535
1688
  init_orchestrator();
@@ -1643,7 +1796,7 @@ data: ${JSON.stringify(data)}
1643
1796
  ];
1644
1797
  for (const candidate of candidates) {
1645
1798
  try {
1646
- const html = fs8.readFileSync(candidate, "utf-8");
1799
+ const html = fs9.readFileSync(candidate, "utf-8");
1647
1800
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1648
1801
  res.end(html);
1649
1802
  return;
@@ -1895,10 +2048,16 @@ function showSuccess(stats) {
1895
2048
  console.log(import_chalk.default.gray(" # .env.example is also provided as a git-safe reference"));
1896
2049
  console.log();
1897
2050
  if (stats.orm === "prisma") {
1898
- console.log(import_chalk.default.cyan(" 2. Add Prisma schema models (see prisma-schema-additions.prisma)"));
1899
- console.log(import_chalk.default.gray(" # Copy the models into your prisma/schema.prisma"));
1900
- console.log(import_chalk.default.gray(" npx prisma migrate dev --name add-auth-models"));
1901
- console.log(import_chalk.default.gray(" npx prisma generate"));
2051
+ if (stats.prismaSchemaUpdated) {
2052
+ console.log(import_chalk.default.cyan(" 2. Run Prisma migration"));
2053
+ console.log(import_chalk.default.gray(" npx prisma migrate dev --name add-auth-models"));
2054
+ console.log(import_chalk.default.gray(" npx prisma generate"));
2055
+ } else {
2056
+ console.log(import_chalk.default.cyan(" 2. Add Prisma schema models manually"));
2057
+ console.log(import_chalk.default.gray(" # Check src/auth/README.md for the model definitions"));
2058
+ console.log(import_chalk.default.gray(" npx prisma migrate dev --name add-auth-models"));
2059
+ console.log(import_chalk.default.gray(" npx prisma generate"));
2060
+ }
1902
2061
  } else {
1903
2062
  console.log(import_chalk.default.cyan(" 2. Create database migration (if using TypeORM)"));
1904
2063
  console.log(import_chalk.default.gray(" npm run migration:generate -- src/migrations/CreateUserTable"));
@@ -2053,6 +2212,27 @@ async function run(cwd = process.cwd(), options = {}) {
2053
2212
  );
2054
2213
  process.exit(1);
2055
2214
  }
2215
+ let prismaSchemaUpdated = false;
2216
+ if (config.orm === "prisma") {
2217
+ const prismaSpinner = createSpinner("Updating prisma/schema.prisma...").start();
2218
+ try {
2219
+ const { PrismaSchemaUpdater: PrismaSchemaUpdater2 } = await Promise.resolve().then(() => (init_installer(), installer_exports));
2220
+ const schemaPath = path7.join(projectInfo.root, "prisma", "schema.prisma");
2221
+ const prismaUpdater = new PrismaSchemaUpdater2(schemaPath);
2222
+ const prismaResult = await prismaUpdater.update(config);
2223
+ if (prismaResult.updated) {
2224
+ await prismaUpdater.cleanupBackup();
2225
+ prismaSpinner.succeed(prismaResult.message);
2226
+ prismaSchemaUpdated = true;
2227
+ } else {
2228
+ prismaSpinner.warn(prismaResult.message);
2229
+ }
2230
+ } catch (error) {
2231
+ prismaSpinner.warn(
2232
+ `Could not update prisma/schema.prisma: ${error instanceof Error ? error.message : "Unknown error"}`
2233
+ );
2234
+ }
2235
+ }
2056
2236
  const mainSpinner = createSpinner("Updating main.ts with global guards...").start();
2057
2237
  try {
2058
2238
  const { MainTsUpdater: MainTsUpdater2 } = await Promise.resolve().then(() => (init_installer(), installer_exports));
@@ -2102,16 +2282,19 @@ async function run(cwd = process.cwd(), options = {}) {
2102
2282
  orm: config.orm,
2103
2283
  swagger: config.features.swagger,
2104
2284
  emailVerification: config.features.emailVerification,
2105
- resetPassword: config.features.resetPassword
2285
+ resetPassword: config.features.resetPassword,
2286
+ prismaSchemaUpdated
2106
2287
  });
2107
2288
  console.log("\u{1F41B} Issues? https://github.com/Islamawad132/add-nest-auth/issues");
2108
2289
  console.log("\u2B50 Like it? https://www.npmjs.com/package/nest-authme");
2109
2290
  console.log();
2110
2291
  }
2292
+ var path7;
2111
2293
  var init_index = __esm({
2112
2294
  "src/index.ts"() {
2113
2295
  "use strict";
2114
2296
  init_cjs_shims();
2297
+ path7 = __toESM(require("path"));
2115
2298
  init_analyzer();
2116
2299
  init_prompts();
2117
2300
  init_ui();