express-file-cluster 0.9.0 → 0.9.1

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.
Files changed (41) hide show
  1. package/dist/auth/index.d.cts +1 -1
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  4. package/dist/chunk-QKQZF573.js.map +1 -0
  5. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  6. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  7. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  8. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  9. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  10. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  11. package/dist/cli/db-runner.cjs +17 -17
  12. package/dist/cli/db-runner.js +2 -2
  13. package/dist/cli/index.cjs +363 -26
  14. package/dist/cli/index.cjs.map +1 -1
  15. package/dist/cli/index.js +343 -6
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/docs/api-reference/collection.md +155 -0
  18. package/dist/docs/cli/add.md +35 -6
  19. package/dist/docs/guides/authentication.md +50 -0
  20. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  21. package/dist/docs/guides/which-api.md +21 -12
  22. package/dist/docs/index.md +3 -1
  23. package/dist/docs/skills/SKILL.md +2 -2
  24. package/dist/docs/skills/api-surface.md +8 -0
  25. package/dist/docs/skills/what-not-to-invent.md +3 -2
  26. package/dist/index.cjs +11 -9
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +193 -3
  29. package/dist/index.d.ts +193 -3
  30. package/dist/index.js +4 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/registry/index.json +1 -1
  33. package/dist/tasks/index.d.cts +1 -1
  34. package/dist/tasks/index.d.ts +1 -1
  35. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.cts} +36 -7
  36. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.ts} +36 -7
  37. package/package.json +1 -1
  38. package/dist/chunk-2PBMLMO4.js.map +0 -1
  39. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  40. package/dist/chunk-6QNLN6AI.js.map +0 -1
  41. package/dist/chunk-RGTENTDN.cjs.map +0 -1
@@ -10,7 +10,7 @@ var _chunkT4OHFU5Tcjs = require('../chunk-T4OHFU5T.cjs');
10
10
  var _chunkQL6EWT4Bcjs = require('../chunk-QL6EWT4B.cjs');
11
11
 
12
12
 
13
- var _chunk66R7S7J3cjs = require('../chunk-66R7S7J3.cjs');
13
+ var _chunkX2US4RAMcjs = require('../chunk-X2US4RAM.cjs');
14
14
  require('../chunk-VQSWSYK6.cjs');
15
15
  require('../chunk-7YEX4MQV.cjs');
16
16
  require('../chunk-TI24L4XE.cjs');
@@ -879,8 +879,11 @@ var Registry = class {
879
879
  }
880
880
 
881
881
 
882
+ has(name) {
883
+ return this.index.items.some((i) => i.name === name || _optionalChain([i, 'access', _8 => _8.aliases, 'optionalAccess', _9 => _9.includes, 'call', _10 => _10(name)]));
884
+ }
882
885
  meta(name) {
883
- const item = this.index.items.find((i) => i.name === name || _optionalChain([i, 'access', _8 => _8.aliases, 'optionalAccess', _9 => _9.includes, 'call', _10 => _10(name)]));
886
+ const item = this.index.items.find((i) => i.name === name || _optionalChain([i, 'access', _11 => _11.aliases, 'optionalAccess', _12 => _12.includes, 'call', _13 => _13(name)]));
884
887
  if (!item) {
885
888
  const names = this.index.items.map((i) => i.name).join(", ");
886
889
  throw new Error(`Unknown item "${name}". Available: ${names}`);
@@ -1017,10 +1020,10 @@ function planAdd(cwd, registry, names, opts = {}, cfg = _nullishCoalesce(readEfc
1017
1020
  const item = registry.item(variant, name);
1018
1021
  for (const file of item.files) addFile(file, name);
1019
1022
  for (const [dep, range] of Object.entries(item.dependencies)) {
1020
- if (!_optionalChain([pkg, 'access', _11 => _11.dependencies, 'optionalAccess', _12 => _12[dep]])) plan.dependencies[dep] = range;
1023
+ if (!_optionalChain([pkg, 'access', _14 => _14.dependencies, 'optionalAccess', _15 => _15[dep]])) plan.dependencies[dep] = range;
1021
1024
  }
1022
1025
  for (const [dep, range] of Object.entries(item.devDependencies)) {
1023
- if (!_optionalChain([pkg, 'access', _13 => _13.devDependencies, 'optionalAccess', _14 => _14[dep]]) && !_optionalChain([pkg, 'access', _15 => _15.dependencies, 'optionalAccess', _16 => _16[dep]]))
1026
+ if (!_optionalChain([pkg, 'access', _16 => _16.devDependencies, 'optionalAccess', _17 => _17[dep]]) && !_optionalChain([pkg, 'access', _18 => _18.dependencies, 'optionalAccess', _19 => _19[dep]]))
1024
1027
  plan.devDependencies[dep] = range;
1025
1028
  }
1026
1029
  for (const v of item.env) {
@@ -1032,7 +1035,7 @@ function planAdd(cwd, registry, names, opts = {}, cfg = _nullishCoalesce(readEfc
1032
1035
  for (const name of items) {
1033
1036
  const prompts = _nullishCoalesce(registry.meta(name).prompts, () => ( []));
1034
1037
  const sets = (p) => isEnvName(p.name) ? adding.has(p.name) : (_nullishCoalesce(p.options, () => ( []))).some((o) => Object.keys(_nullishCoalesce(o.env, () => ( {}))).some((k) => adding.has(k))) || prompts.some(
1035
- (q) => isEnvName(q.name) && adding.has(q.name) && _optionalChain([q, 'access', _17 => _17.when, 'optionalAccess', _18 => _18[p.name]]) !== void 0
1038
+ (q) => isEnvName(q.name) && adding.has(q.name) && _optionalChain([q, 'access', _20 => _20.when, 'optionalAccess', _21 => _21[p.name]]) !== void 0
1036
1039
  );
1037
1040
  for (const p of prompts) {
1038
1041
  const dup = plan.prompts.some(
@@ -1045,7 +1048,7 @@ function planAdd(cwd, registry, names, opts = {}, cfg = _nullishCoalesce(readEfc
1045
1048
  }
1046
1049
  function readEnvKeys(file) {
1047
1050
  if (!_fs2.default.existsSync(file)) return [];
1048
- return _fs2.default.readFileSync(file, "utf8").split("\n").map((l) => _optionalChain([/^([A-Za-z0-9_]+)=/, 'access', _19 => _19.exec, 'call', _20 => _20(l), 'optionalAccess', _21 => _21[1]])).filter((k) => !!k);
1051
+ return _fs2.default.readFileSync(file, "utf8").split("\n").map((l) => _optionalChain([/^([A-Za-z0-9_]+)=/, 'access', _22 => _22.exec, 'call', _23 => _23(l), 'optionalAccess', _24 => _24[1]])).filter((k) => !!k);
1049
1052
  }
1050
1053
  function appendEnv(file, lines) {
1051
1054
  if (lines.length === 0) return;
@@ -1058,7 +1061,7 @@ function promptApplies(p, answers) {
1058
1061
  return Object.entries(_nullishCoalesce(p.when, () => ( {}))).every(([k, v]) => answers[k] === v);
1059
1062
  }
1060
1063
  function promptDefault(p, answers) {
1061
- return _optionalChain([p, 'access', _22 => _22.default, 'optionalAccess', _23 => _23.replace, 'call', _24 => _24(/\{\{(\w+)\}\}/g, (_, k) => _nullishCoalesce(answers[k], () => ( "")))]);
1064
+ return _optionalChain([p, 'access', _25 => _25.default, 'optionalAccess', _26 => _26.replace, 'call', _27 => _27(/\{\{(\w+)\}\}/g, (_, k) => _nullishCoalesce(answers[k], () => ( "")))]);
1062
1065
  }
1063
1066
  function normalizeAnswer(p, raw, cwd) {
1064
1067
  let value = p.stripSpaces ? raw.replace(/\s/g, "") : raw.trim();
@@ -1079,8 +1082,8 @@ function envFromAnswers(prompts, answers) {
1079
1082
  for (const p of prompts) {
1080
1083
  if (!(p.name in answers) || !promptApplies(p, answers)) continue;
1081
1084
  if (isEnvName(p.name)) env[p.name] = answers[p.name];
1082
- const chosen = _optionalChain([p, 'access', _25 => _25.options, 'optionalAccess', _26 => _26.find, 'call', _27 => _27((o) => o.value === answers[p.name])]);
1083
- Object.assign(env, _nullishCoalesce(_optionalChain([chosen, 'optionalAccess', _28 => _28.env]), () => ( {})));
1085
+ const chosen = _optionalChain([p, 'access', _28 => _28.options, 'optionalAccess', _29 => _29.find, 'call', _30 => _30((o) => o.value === answers[p.name])]);
1086
+ Object.assign(env, _nullishCoalesce(_optionalChain([chosen, 'optionalAccess', _31 => _31.env]), () => ( {})));
1084
1087
  }
1085
1088
  return env;
1086
1089
  }
@@ -1111,7 +1114,7 @@ function applyAdd(cwd, plan, registry, env = {}) {
1111
1114
  _fs2.default.mkdirSync(_path2.default.dirname(abs), { recursive: true });
1112
1115
  _fs2.default.writeFileSync(abs, f.content);
1113
1116
  result.written.push(f.path);
1114
- const model = _optionalChain([/^src\/model\/([A-Za-z0-9_]+)\.[jt]s$/, 'access', _29 => _29.exec, 'call', _30 => _30(f.path), 'optionalAccess', _31 => _31[1]]);
1117
+ const model = _optionalChain([/^src\/model\/([A-Za-z0-9_]+)\.[jt]s$/, 'access', _32 => _32.exec, 'call', _33 => _33(f.path), 'optionalAccess', _34 => _34[1]]);
1115
1118
  if (model && model !== "index" && !existed) newModels.push(model);
1116
1119
  }
1117
1120
  cfg.files[f.path] = sha256(f.content);
@@ -1264,6 +1267,231 @@ function lineDiff(a, b) {
1264
1267
  });
1265
1268
  return shown;
1266
1269
  }
1270
+ var RESERVED_ENTITIES = /* @__PURE__ */ new Set(["user", "admin"]);
1271
+ function toPascal(s) {
1272
+ const parts = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[-_]+/g, " ").trim().split(/\s+/);
1273
+ return parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
1274
+ }
1275
+ function toCamel(s) {
1276
+ const p = toPascal(s);
1277
+ return p.charAt(0).toLowerCase() + p.slice(1);
1278
+ }
1279
+ function toSlug(s) {
1280
+ return s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[-_\s]+/g, "-").toLowerCase();
1281
+ }
1282
+ function validateEntityName(name) {
1283
+ const raw = name.trim();
1284
+ if (!raw) return { error: "Entity name cannot be empty" };
1285
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(raw))
1286
+ return { error: `Entity name must be alphanumeric and start with a letter: "${raw}"` };
1287
+ const pascal = toPascal(raw);
1288
+ const camel = toCamel(raw);
1289
+ const slug = toSlug(raw);
1290
+ if (RESERVED_ENTITIES.has(slug) || RESERVED_ENTITIES.has(pascal.toLowerCase()))
1291
+ return { error: `"${pascal}" is a built-in entity \u2014 use \`efc add auth\` for User/Admin` };
1292
+ return { pascal, camel, slug };
1293
+ }
1294
+ function entityUsesTables(cfg) {
1295
+ return cfg.database === "postgresql" && cfg.modelApi === "defineTable";
1296
+ }
1297
+ function entityOrm(cfg) {
1298
+ const t = entityUsesTables(cfg);
1299
+ return {
1300
+ findOne: (model, filter) => t ? `${model}.findFirst({ where: ${filter} })` : `${model}.findOne(${filter})`,
1301
+ create: (model, data) => t ? `${model}.create({ data: ${data} })` : `${model}.create(${data})`
1302
+ };
1303
+ }
1304
+ function entityModelContent(pascal, slug, cfg) {
1305
+ const api = entityUsesTables(cfg) ? "defineTable" : "defineModel";
1306
+ return `import { ${api} } from 'express-file-cluster';
1307
+
1308
+ export const ${pascal} = ${api}('${pascal}', {
1309
+ name: { type: 'string', required: true },
1310
+ email: { type: 'string', required: true, unique: true },
1311
+ password: { type: 'string', required: true },
1312
+ role: { type: 'string', required: true, default: '${slug}' },
1313
+ avatar: { type: 'string' },
1314
+ isVerified: { type: 'boolean', default: false },
1315
+ isActive: { type: 'boolean', default: true },
1316
+ verifyToken: { type: 'string' },
1317
+ resetToken: { type: 'string' },
1318
+ resetTokenExpiry: { type: 'date' },
1319
+ refreshToken: { type: 'string' },
1320
+ refreshTokenExpiry: { type: 'date' },
1321
+ });
1322
+ `;
1323
+ }
1324
+ function entityRegisterContent(pascal, camel, cfg) {
1325
+ const ts = cfg.language === "typescript";
1326
+ const db = entityOrm(cfg);
1327
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1328
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1329
+ return `${typeImport}import bcrypt from 'bcrypt';
1330
+ import { ${pascal} } from '../../../model/${pascal}.js';
1331
+
1332
+ export const POST = async ${typedArgs} => {
1333
+ const { name, email, password } = req.body;
1334
+ if (!name || !email || !password) {
1335
+ return res.status(400).json({ error: 'name, email and password are required' });
1336
+ }
1337
+ const existing = await ${db.findOne(pascal, "{ email }")};
1338
+ if (existing) return res.status(409).json({ error: 'Email already in use' });
1339
+ const hashed = await bcrypt.hash(password, 10);
1340
+ const record = await ${db.create(pascal, "{ name, email, password: hashed }")};
1341
+ const { password: _, ...safe } = record;
1342
+ res.status(201).json({ message: '${pascal} account created', ${camel}: safe });
1343
+ };
1344
+ `;
1345
+ }
1346
+ function entityLoginContent(pascal, slug, cfg) {
1347
+ const ts = cfg.language === "typescript";
1348
+ const db = entityOrm(cfg);
1349
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1350
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1351
+ return `${typeImport}import bcrypt from 'bcrypt';
1352
+ import { issueToken } from 'express-file-cluster/auth';
1353
+ import { ${pascal} } from '../../../model/${pascal}.js';
1354
+
1355
+ export const POST = async ${typedArgs} => {
1356
+ const { email, password } = req.body;
1357
+ if (!email || !password) return res.status(400).json({ error: 'email and password are required' });
1358
+
1359
+ const record = await ${db.findOne(pascal, "{ email }")};
1360
+ if (!record) return res.status(401).json({ error: 'Invalid credentials' });
1361
+ const match = await bcrypt.compare(password, record.password);
1362
+ if (!match) return res.status(401).json({ error: 'Invalid credentials' });
1363
+ if (!record.isActive) return res.status(403).json({ error: 'Account suspended' });
1364
+ await issueToken(res, { id: record.id, role: record.role, email: record.email });
1365
+ res.json({ message: 'Logged in as ${slug}' });
1366
+ };
1367
+ `;
1368
+ }
1369
+ function entityLogoutContent(cfg) {
1370
+ const ts = cfg.language === "typescript";
1371
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1372
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1373
+ return `${typeImport}import { requireAuth, revokeSession } from 'express-file-cluster/auth';
1374
+
1375
+ export const middlewares = [requireAuth];
1376
+
1377
+ export const POST = async ${typedArgs} => {
1378
+ try {
1379
+ await revokeSession(req, res);
1380
+ } catch {
1381
+ res.clearCookie('efc_token');
1382
+ }
1383
+ res.json({ message: 'Logged out successfully' });
1384
+ };
1385
+ `;
1386
+ }
1387
+ function entityMeContent(slug, cfg) {
1388
+ const ts = cfg.language === "typescript";
1389
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1390
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1391
+ return `${typeImport}import { requireAuth } from 'express-file-cluster/auth';
1392
+
1393
+ export const middlewares = [requireAuth('${slug}')];
1394
+
1395
+ export const GET = async ${typedArgs} => {
1396
+ res.json((req${ts ? " as any" : ""}).user);
1397
+ };
1398
+ `;
1399
+ }
1400
+ function generateEntityAuth(cwd, entityName, cfg, options) {
1401
+ const validated = validateEntityName(entityName);
1402
+ if ("error" in validated) throw new Error(`[EFC] ${validated.error}`);
1403
+ const { pascal, camel, slug } = validated;
1404
+ const ext = cfg.language === "typescript" ? "ts" : "js";
1405
+ const result = { written: [], manual: [], conflicts: [] };
1406
+ const files = [
1407
+ { rel: `src/model/${pascal}.${ext}`, content: entityModelContent(pascal, slug, cfg) },
1408
+ {
1409
+ rel: `src/api/auth/${slug}/register.${ext}`,
1410
+ content: entityRegisterContent(pascal, camel, cfg)
1411
+ },
1412
+ {
1413
+ rel: `src/api/auth/${slug}/login.${ext}`,
1414
+ content: entityLoginContent(pascal, slug, cfg)
1415
+ },
1416
+ {
1417
+ rel: `src/api/auth/${slug}/logout.${ext}`,
1418
+ content: entityLogoutContent(cfg)
1419
+ },
1420
+ {
1421
+ rel: `src/api/auth/${slug}/me.${ext}`,
1422
+ content: entityMeContent(slug, cfg)
1423
+ }
1424
+ ];
1425
+ for (const f of files) {
1426
+ const abs = _path2.default.join(cwd, f.rel);
1427
+ const exists = _fs2.default.existsSync(abs);
1428
+ if (exists && !_optionalChain([options, 'optionalAccess', _35 => _35.overwrite])) {
1429
+ result.conflicts.push(f.rel);
1430
+ result.manual.push(`${f.rel} already exists \u2014 skipped (pass --overwrite to replace)`);
1431
+ continue;
1432
+ }
1433
+ result.written.push(f.rel);
1434
+ if (!_optionalChain([options, 'optionalAccess', _36 => _36.dryRun])) {
1435
+ _fs2.default.mkdirSync(_path2.default.dirname(abs), { recursive: true });
1436
+ _fs2.default.writeFileSync(abs, f.content);
1437
+ cfg.files[f.rel] = sha256(f.content);
1438
+ }
1439
+ }
1440
+ if (entityUsesTables(cfg) && !_optionalChain([options, 'optionalAccess', _37 => _37.dryRun])) {
1441
+ result.manual.push(...registerModels(cwd, cfg.language, [pascal]));
1442
+ }
1443
+ const pkgFile = _path2.default.join(cwd, "package.json");
1444
+ if (_fs2.default.existsSync(pkgFile)) {
1445
+ try {
1446
+ const pkg = JSON.parse(_fs2.default.readFileSync(pkgFile, "utf8"));
1447
+ let pkgChanged = false;
1448
+ const deps = _nullishCoalesce(pkg["dependencies"], () => ( {}));
1449
+ const devDeps = _nullishCoalesce(pkg["devDependencies"], () => ( {}));
1450
+ if (!deps["bcrypt"]) {
1451
+ deps["bcrypt"] = "^5.1.0";
1452
+ pkg["dependencies"] = Object.fromEntries(
1453
+ Object.entries(deps).sort(([a], [b]) => a.localeCompare(b))
1454
+ );
1455
+ pkgChanged = true;
1456
+ }
1457
+ if (cfg.language === "typescript" && !devDeps["@types/bcrypt"]) {
1458
+ devDeps["@types/bcrypt"] = "^5.0.0";
1459
+ pkg["devDependencies"] = Object.fromEntries(
1460
+ Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1461
+ );
1462
+ pkgChanged = true;
1463
+ }
1464
+ if (pkgChanged) {
1465
+ result.installNeeded = true;
1466
+ if (!_optionalChain([options, 'optionalAccess', _38 => _38.dryRun])) {
1467
+ _fs2.default.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
1468
+ }
1469
+ }
1470
+ } catch (e3) {
1471
+ }
1472
+ }
1473
+ const envFile = _path2.default.join(cwd, ".env");
1474
+ if (_fs2.default.existsSync(envFile)) {
1475
+ const envKeys = readEnvKeys(envFile);
1476
+ if (!envKeys.includes("JWT_SECRET")) {
1477
+ const secret = _crypto2.default.randomBytes(64).toString("hex");
1478
+ if (!_optionalChain([options, 'optionalAccess', _39 => _39.dryRun])) {
1479
+ appendEnv(envFile, [`JWT_SECRET=${secret}`]);
1480
+ const exampleFile = _path2.default.join(cwd, ".env.example");
1481
+ if (_fs2.default.existsSync(exampleFile) && !readEnvKeys(exampleFile).includes("JWT_SECRET")) {
1482
+ appendEnv(exampleFile, ["JWT_SECRET=<generate with: openssl rand -hex 64>"]);
1483
+ }
1484
+ }
1485
+ result.manual.push("Added JWT_SECRET to .env");
1486
+ }
1487
+ }
1488
+ const itemName = `auth:${slug}`;
1489
+ if (!cfg.items.includes(itemName)) cfg.items.push(itemName);
1490
+ if (!_optionalChain([options, 'optionalAccess', _40 => _40.dryRun])) {
1491
+ writeEfcJson(cwd, cfg);
1492
+ }
1493
+ return result;
1494
+ }
1267
1495
 
1268
1496
  // src/cli/commands/registry.ts
1269
1497
  function registryCommands() {
@@ -1442,16 +1670,102 @@ function packageManager(cwd) {
1442
1670
  }
1443
1671
  function addCommand() {
1444
1672
  return new (0, _commander.Command)("add").description("Add features to the app from the registry (copies their source into src/)").argument(
1445
- "<items...>",
1446
- "registry items, e.g. auth forgot-password admin-users \u2014 `efc list` shows them"
1447
- ).option("-y, --yes", "skip the confirmation").option("--overwrite", "replace files that were changed in this app").option("--dry-run", "show what would change without writing anything").option("--no-install", "don't run the package manager afterwards").option("--no-prompt", "don't ask for credentials \u2014 write placeholders to .env instead").action(
1673
+ "[items...]",
1674
+ "registry items (auth forgot-password admin-users) or custom auth entities (auth:merchant, auth --entity merchant)"
1675
+ ).option("-y, --yes", "skip the confirmation").option("--overwrite", "replace files that were changed in this app").option("--dry-run", "show what would change without writing anything").option("--no-install", "don't run the package manager afterwards").option("--no-prompt", "don't ask for credentials \u2014 write placeholders to .env instead").option("--entity <name>", "scaffold a custom auth entity (model + auth routes)").action(
1448
1676
  async (names, opts) => {
1449
1677
  try {
1678
+ const rawNames = _nullishCoalesce(names, () => ( []));
1679
+ const entityNames = [];
1680
+ const registryNames = [];
1681
+ let i = 0;
1682
+ if (rawNames[0] === "auth" && rawNames[1] === "new" && rawNames.length >= 3) {
1683
+ for (let j = 2; j < rawNames.length; j++) {
1684
+ entityNames.push(rawNames[j]);
1685
+ }
1686
+ i = rawNames.length;
1687
+ }
1688
+ for (; i < rawNames.length; i++) {
1689
+ const n = rawNames[i];
1690
+ const colonMatch = /^auth:([A-Za-z][A-Za-z0-9_-]*)$/.exec(n);
1691
+ if (colonMatch) {
1692
+ entityNames.push(colonMatch[1]);
1693
+ } else if (opts.entity && n === "auth") {
1694
+ continue;
1695
+ } else {
1696
+ registryNames.push(n);
1697
+ }
1698
+ }
1699
+ if (opts.entity && !entityNames.includes(opts.entity)) {
1700
+ entityNames.push(opts.entity);
1701
+ }
1702
+ if (entityNames.length === 0 && registryNames.length === 0) {
1703
+ fail(
1704
+ "Specify at least one item or entity to add \u2014 e.g. `efc add auth` or `efc add auth:merchant`. Run `efc list` to see available features."
1705
+ );
1706
+ }
1707
+ let anyInstallNeeded = false;
1708
+ if (entityNames.length > 0) {
1709
+ const { cwd: cwd2, cfg: cfg2, detected: detected2 } = load();
1710
+ if (detected2) {
1711
+ console.log(
1712
+ _picocolors2.default.dim(`
1713
+ No ${EFC_JSON} yet \u2014 detected ${describe(cfg2)}; it'll be created.`)
1714
+ );
1715
+ }
1716
+ for (const eName of entityNames) {
1717
+ const validated = validateEntityName(eName);
1718
+ if ("error" in validated) fail(validated.error);
1719
+ const { pascal, slug } = validated;
1720
+ console.log(_picocolors2.default.bold(`
1721
+ Adding auth entity: ${pascal}
1722
+ `));
1723
+ const result2 = generateEntityAuth(cwd2, eName, cfg2, {
1724
+ dryRun: opts.dryRun,
1725
+ overwrite: opts.overwrite
1726
+ });
1727
+ if (result2.written.length) {
1728
+ for (const f of result2.written) console.log(` ${_picocolors2.default.green("create ")} ${f}`);
1729
+ const actionVerb = opts.dryRun ? "would be written (dry run)" : "written";
1730
+ console.log(_picocolors2.default.green(`
1731
+ \u2713 ${result2.written.length} file(s) ${actionVerb}`));
1732
+ }
1733
+ for (const m of result2.manual) console.log(_picocolors2.default.yellow(` ! ${m}`));
1734
+ console.log(
1735
+ _picocolors2.default.dim(
1736
+ `
1737
+ Routes: POST /auth/${slug}/register, /login, /logout; GET /me`
1738
+ )
1739
+ );
1740
+ console.log(
1741
+ _picocolors2.default.dim(` Protect routes with: requireAuth('${slug}')`)
1742
+ );
1743
+ if (result2.installNeeded) anyInstallNeeded = true;
1744
+ }
1745
+ console.log();
1746
+ if (anyInstallNeeded && !opts.dryRun) {
1747
+ const pm = packageManager(cwd2);
1748
+ if (opts.install) {
1749
+ console.log(_picocolors2.default.dim(` $ ${pm} install`));
1750
+ const r = _child_process.spawnSync.call(void 0, pm, ["install"], {
1751
+ cwd: cwd2,
1752
+ stdio: "inherit",
1753
+ shell: process.platform === "win32"
1754
+ });
1755
+ if (r.status !== 0)
1756
+ console.log(_picocolors2.default.yellow(` ${pm} install failed \u2014 run it yourself.`));
1757
+ } else {
1758
+ console.log(_picocolors2.default.yellow(` Run \`${pm} install\` for the new packages.`));
1759
+ }
1760
+ }
1761
+ if (registryNames.length === 0) return;
1762
+ }
1450
1763
  const { cwd, registry, cfg, detected } = load();
1451
- const plan = planAdd(cwd, registry, names, { overwrite: !!opts.overwrite }, cfg);
1764
+ const itemsToAdd = registryNames;
1765
+ const plan = planAdd(cwd, registry, itemsToAdd, { overwrite: !!opts.overwrite }, cfg);
1452
1766
  if (plan.problems.length) fail(plan.problems.join("\n"));
1453
1767
  if (plan.items.length === 0) {
1454
- console.log(_picocolors2.default.dim(`Already installed: ${names.join(", ")}`));
1768
+ console.log(_picocolors2.default.dim(`Already installed: ${itemsToAdd.join(", ")}`));
1455
1769
  return;
1456
1770
  }
1457
1771
  if (detected) {
@@ -1530,7 +1844,7 @@ function listCommand() {
1530
1844
  try {
1531
1845
  const cwd = process.cwd();
1532
1846
  const registry = new Registry();
1533
- const installed = new Set(_nullishCoalesce(_optionalChain([readEfcJson, 'call', _32 => _32(cwd), 'optionalAccess', _33 => _33.items]), () => ( [])));
1847
+ const installed = new Set(_nullishCoalesce(_optionalChain([readEfcJson, 'call', _41 => _41(cwd), 'optionalAccess', _42 => _42.items]), () => ( [])));
1534
1848
  const groups = [...new Set(registry.index.items.map((i) => i.group))];
1535
1849
  for (const group of groups) {
1536
1850
  console.log(_picocolors2.default.bold(`
@@ -1541,6 +1855,13 @@ function listCommand() {
1541
1855
  console.log(` ${mark} ${_picocolors2.default.cyan(item.name.padEnd(20))} ${item.description}${deps}`);
1542
1856
  }
1543
1857
  }
1858
+ const entities = (_nullishCoalesce(_optionalChain([readEfcJson, 'call', _43 => _43(cwd), 'optionalAccess', _44 => _44.items]), () => ( []))).filter((i) => i.startsWith("auth:")).map((i) => i.slice(5));
1859
+ if (entities.length > 0) {
1860
+ console.log(_picocolors2.default.bold("\n custom auth entities"));
1861
+ for (const e of entities) {
1862
+ console.log(` ${_picocolors2.default.green("\u2713")} ${_picocolors2.default.cyan(e.padEnd(20))} model + auth routes for ${e}`);
1863
+ }
1864
+ }
1544
1865
  console.log(_picocolors2.default.dim("\n efc add <item...> \xB7 efc view <item>\n"));
1545
1866
  } catch (err) {
1546
1867
  fail(err);
@@ -1585,6 +1906,22 @@ function diffCommand() {
1585
1906
  const names = name ? [name] : cfg.items;
1586
1907
  let clean = true;
1587
1908
  for (const n of names) {
1909
+ if (!registry.has(n)) {
1910
+ if (n.startsWith("auth:")) {
1911
+ if (name) {
1912
+ console.log(
1913
+ _picocolors2.default.dim(
1914
+ `
1915
+ ${n} is a custom auth entity (files are owned by your project, no upstream registry item to diff).`
1916
+ )
1917
+ );
1918
+ }
1919
+ } else {
1920
+ console.log(_picocolors2.default.dim(`
1921
+ ${n} is not a registry item.`));
1922
+ }
1923
+ continue;
1924
+ }
1588
1925
  for (const f of itemStatus(cwd, registry, cfg, n)) {
1589
1926
  if (f.status === "unchanged") continue;
1590
1927
  clean = false;
@@ -1676,15 +2013,15 @@ function parseAttrs(s) {
1676
2013
  return out;
1677
2014
  }
1678
2015
  function arg(a, name) {
1679
- if (!_optionalChain([a, 'optionalAccess', _34 => _34.args])) return void 0;
2016
+ if (!_optionalChain([a, 'optionalAccess', _45 => _45.args])) return void 0;
1680
2017
  const parts = splitTop(a.args, ",");
1681
2018
  if (name) {
1682
2019
  const p = parts.find((x) => x.startsWith(`${name}:`));
1683
- return _optionalChain([p, 'optionalAccess', _35 => _35.slice, 'call', _36 => _36(name.length + 1), 'access', _37 => _37.trim, 'call', _38 => _38()]);
2020
+ return _optionalChain([p, 'optionalAccess', _46 => _46.slice, 'call', _47 => _47(name.length + 1), 'access', _48 => _48.trim, 'call', _49 => _49()]);
1684
2021
  }
1685
2022
  return parts.find((x) => !/^\w+\s*:/.test(x));
1686
2023
  }
1687
- var unquote = (s) => _optionalChain([s, 'optionalAccess', _39 => _39.replace, 'call', _40 => _40(/^"(.*)"$/, "$1")]);
2024
+ var unquote = (s) => _optionalChain([s, 'optionalAccess', _50 => _50.replace, 'call', _51 => _51(/^"(.*)"$/, "$1")]);
1688
2025
  var list = (s) => s ? splitTop(s.replace(/^\[|\]$/g, ""), ",").map((x) => x.trim()).filter(Boolean) : [];
1689
2026
  function parsePrisma(source) {
1690
2027
  const text = source.replace(/\/\/.*$/gm, "");
@@ -1697,7 +2034,7 @@ function parsePrisma(source) {
1697
2034
  const [, kind, name, body] = block;
1698
2035
  const lines = body.split("\n").map((l) => l.trim()).filter(Boolean);
1699
2036
  if (kind === "datasource") {
1700
- provider = unquote(_optionalChain([/provider\s*=\s*("[^"]*")/, 'access', _41 => _41.exec, 'call', _42 => _42(body), 'optionalAccess', _43 => _43[1]]));
2037
+ provider = unquote(_optionalChain([/provider\s*=\s*("[^"]*")/, 'access', _52 => _52.exec, 'call', _53 => _53(body), 'optionalAccess', _54 => _54[1]]));
1701
2038
  } else if (kind === "enum") {
1702
2039
  const values = [];
1703
2040
  const names = [];
@@ -1759,7 +2096,7 @@ function importPrisma(source) {
1759
2096
  const def = _nullishCoalesce(arg(attr(_nullishCoalesce(id, () => ( { attrs: [] })), "@default")), () => ( ""));
1760
2097
  idKind.set(
1761
2098
  m.name,
1762
- _optionalChain([id, 'optionalAccess', _44 => _44.type]) === "Int" && /autoincrement/.test(def) ? "serial" : _optionalChain([id, 'optionalAccess', _45 => _45.type]) === "BigInt" && /autoincrement/.test(def) ? "bigserial" : "uuid"
2099
+ _optionalChain([id, 'optionalAccess', _55 => _55.type]) === "Int" && /autoincrement/.test(def) ? "serial" : _optionalChain([id, 'optionalAccess', _56 => _56.type]) === "BigInt" && /autoincrement/.test(def) ? "bigserial" : "uuid"
1763
2100
  );
1764
2101
  }
1765
2102
  const rels = [];
@@ -1789,7 +2126,7 @@ function importPrisma(source) {
1789
2126
  const fields = [];
1790
2127
  const relations = {};
1791
2128
  const table = _nullishCoalesce(unquote(arg(blocks(m, "@@map")[0])), () => ( m.name));
1792
- if (table !== _chunk66R7S7J3cjs.tableNameFor.call(void 0, m.name)) options["collection"] = table;
2129
+ if (table !== _chunkX2US4RAMcjs.tableNameFor.call(void 0, m.name)) options["collection"] = table;
1793
2130
  const kind = idKind.get(m.name);
1794
2131
  if (kind !== "uuid") options["id"] = kind;
1795
2132
  if (blocks(m, "@@id").length) {
@@ -1845,7 +2182,7 @@ function importPrisma(source) {
1845
2182
  continue;
1846
2183
  }
1847
2184
  const other = partner(r);
1848
- if (r.list && _optionalChain([other, 'optionalAccess', _46 => _46.list])) {
2185
+ if (r.list && _optionalChain([other, 'optionalAccess', _57 => _57.list])) {
1849
2186
  if (m.name < r.target || m.name === r.target && f.name < other.field) {
1850
2187
  fields.push([
1851
2188
  f.name,
@@ -1915,7 +2252,7 @@ function importPrisma(source) {
1915
2252
  }
1916
2253
  function scalarDef(f, enums, notes) {
1917
2254
  const db = f.attrs.find((a) => a.name.startsWith("@db."));
1918
- const dbType = _optionalChain([db, 'optionalAccess', _47 => _47.name, 'access', _48 => _48.slice, 'call', _49 => _49(4)]);
2255
+ const dbType = _optionalChain([db, 'optionalAccess', _58 => _58.name, 'access', _59 => _59.slice, 'call', _60 => _60(4)]);
1919
2256
  let def;
1920
2257
  const e = enums.get(f.type);
1921
2258
  if (e) def = { type: "string", enum: e.values, nativeEnum: true };
@@ -1923,7 +2260,7 @@ function scalarDef(f, enums, notes) {
1923
2260
  switch (f.type) {
1924
2261
  case "String":
1925
2262
  if (dbType === "Uuid") def = { type: "uuid" };
1926
- else if (dbType === "VarChar" && _optionalChain([db, 'optionalAccess', _50 => _50.args]))
2263
+ else if (dbType === "VarChar" && _optionalChain([db, 'optionalAccess', _61 => _61.args]))
1927
2264
  def = { type: "string", maxLength: Number(db.args) };
1928
2265
  else def = { type: "string" };
1929
2266
  break;
@@ -1937,7 +2274,7 @@ function scalarDef(f, enums, notes) {
1937
2274
  def = { type: "number" };
1938
2275
  break;
1939
2276
  case "Decimal": {
1940
- const [p, s] = (_nullishCoalesce(_optionalChain([db, 'optionalAccess', _51 => _51.args]), () => ( ""))).split(",").map((x) => Number(x.trim()));
2277
+ const [p, s] = (_nullishCoalesce(_optionalChain([db, 'optionalAccess', _62 => _62.args]), () => ( ""))).split(",").map((x) => Number(x.trim()));
1941
2278
  def = p ? { type: "decimal", precision: p, scale: _nullishCoalesce(s, () => ( 0)) } : { type: "decimal" };
1942
2279
  break;
1943
2280
  }