@dudousxd/nestjs-codegen 0.11.0 → 0.12.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/index.cjs CHANGED
@@ -248,8 +248,8 @@ Run \`nestjs-codegen init\` to create a starter config.`
248
248
  }
249
249
 
250
250
  // src/generate.ts
251
- var import_promises11 = require("fs/promises");
252
- var import_node_path12 = require("path");
251
+ var import_promises12 = require("fs/promises");
252
+ var import_node_path13 = require("path");
253
253
 
254
254
  // src/discovery/pages.ts
255
255
  var import_promises2 = require("fs/promises");
@@ -2147,6 +2147,99 @@ function buildEmpty() {
2147
2147
  ].join("\n");
2148
2148
  }
2149
2149
 
2150
+ // src/generate-manifest.ts
2151
+ var import_node_crypto = require("crypto");
2152
+ var import_promises11 = require("fs/promises");
2153
+ var import_node_path12 = require("path");
2154
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
2155
+ var MANIFEST_FILE = ".codegen-manifest.json";
2156
+ var LOCK_FILE = ".watcher.lock";
2157
+ function isManifestShape(value) {
2158
+ if (typeof value !== "object" || value === null) return false;
2159
+ const candidate = value;
2160
+ if (typeof candidate.version !== "string") return false;
2161
+ if (typeof candidate.hash !== "string") return false;
2162
+ if (!Array.isArray(candidate.files)) return false;
2163
+ return candidate.files.every((entry) => typeof entry === "string");
2164
+ }
2165
+ function serializeConfig(config) {
2166
+ try {
2167
+ return JSON.stringify(config, (_key, value) => {
2168
+ if (typeof value === "function") return `[fn:${value.name}]${value.toString()}`;
2169
+ return value;
2170
+ });
2171
+ } catch {
2172
+ return `unserializable:${config.codegen.outDir}:${config.contracts.glob}`;
2173
+ }
2174
+ }
2175
+ async function discoverInputFiles(config) {
2176
+ const globs = [config.contracts.glob, config.forms.watch];
2177
+ if (config.pages) globs.push(config.pages.glob);
2178
+ const cwd = config.codegen.cwd;
2179
+ const matched = await (0, import_fast_glob2.default)(globs, { cwd, absolute: true, onlyFiles: true });
2180
+ return [...new Set(matched)].sort();
2181
+ }
2182
+ async function computeInputsHash(config) {
2183
+ const hash = (0, import_node_crypto.createHash)("sha256");
2184
+ hash.update(`version:${VERSION}
2185
+ `);
2186
+ hash.update(`config:${serializeConfig(config)}
2187
+ `);
2188
+ const inputFiles = await discoverInputFiles(config);
2189
+ const cwd = config.codegen.cwd;
2190
+ for (const file of inputFiles) {
2191
+ const contents = await (0, import_promises11.readFile)(file, "utf8");
2192
+ hash.update(`file:${(0, import_node_path12.relative)(cwd, file)}
2193
+ `);
2194
+ hash.update(contents);
2195
+ hash.update("\n");
2196
+ }
2197
+ return hash.digest("hex");
2198
+ }
2199
+ async function readManifest(outDir) {
2200
+ try {
2201
+ const raw = await (0, import_promises11.readFile)((0, import_node_path12.join)(outDir, MANIFEST_FILE), "utf8");
2202
+ const parsed = JSON.parse(raw);
2203
+ if (!isManifestShape(parsed)) return null;
2204
+ return { version: parsed.version, hash: parsed.hash, files: parsed.files };
2205
+ } catch {
2206
+ return null;
2207
+ }
2208
+ }
2209
+ async function writeManifest(outDir, manifest) {
2210
+ await (0, import_promises11.writeFile)((0, import_node_path12.join)(outDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}
2211
+ `, "utf8");
2212
+ }
2213
+ async function listOutputFiles(outDir) {
2214
+ const found = [];
2215
+ async function walk(dir) {
2216
+ const entries = await (0, import_promises11.readdir)(dir, { withFileTypes: true }).catch(() => []);
2217
+ for (const entry of entries) {
2218
+ const abs = (0, import_node_path12.join)(dir, entry.name);
2219
+ if (entry.isDirectory()) {
2220
+ await walk(abs);
2221
+ } else if (entry.isFile()) {
2222
+ const rel = (0, import_node_path12.relative)(outDir, abs);
2223
+ if (rel === MANIFEST_FILE || rel === LOCK_FILE) continue;
2224
+ found.push(rel);
2225
+ }
2226
+ }
2227
+ }
2228
+ await walk(outDir);
2229
+ return found.sort();
2230
+ }
2231
+ async function allOutputsExist(outDir, files) {
2232
+ const present = new Set(await listOutputFiles(outDir));
2233
+ return files.every((file) => present.has(file));
2234
+ }
2235
+ async function isManifestFresh(outDir, manifest, inputsHash) {
2236
+ if (manifest === null) return false;
2237
+ if (manifest.version !== VERSION) return false;
2238
+ if (manifest.hash !== inputsHash) return false;
2239
+ if (manifest.files.length === 0) return false;
2240
+ return allOutputsExist(outDir, manifest.files);
2241
+ }
2242
+
2150
2243
  // src/util/debug-log.ts
2151
2244
  var debugEnabled = false;
2152
2245
  function setCodegenDebug(enabled) {
@@ -2159,6 +2252,12 @@ function debugWarn(message) {
2159
2252
  // src/generate.ts
2160
2253
  async function generate(config, inputRoutes = []) {
2161
2254
  setCodegenDebug(config.debug);
2255
+ const inputsHash = await computeInputsHash(config);
2256
+ const manifest = await readManifest(config.codegen.outDir);
2257
+ if (await isManifestFresh(config.codegen.outDir, manifest, inputsHash)) {
2258
+ console.log(`[nestjs-codegen] ${config.codegen.outDir} up to date, skipped`);
2259
+ return;
2260
+ }
2162
2261
  const extensions = config.extensions ?? [];
2163
2262
  let routes = inputRoutes;
2164
2263
  const ctx = createExtensionContext(config, () => routes);
@@ -2215,21 +2314,27 @@ async function generate(config, inputRoutes = []) {
2215
2314
  if (extensions.length > 0) {
2216
2315
  const extraFiles = await collectEmittedFiles(extensions, ctx);
2217
2316
  for (const file of extraFiles) {
2218
- const dest = (0, import_node_path12.join)(config.codegen.outDir, file.path);
2219
- await (0, import_promises11.mkdir)((0, import_node_path12.dirname)(dest), { recursive: true });
2220
- await (0, import_promises11.writeFile)(dest, file.contents, "utf8");
2317
+ const dest = (0, import_node_path13.join)(config.codegen.outDir, file.path);
2318
+ await (0, import_promises12.mkdir)((0, import_node_path13.dirname)(dest), { recursive: true });
2319
+ await (0, import_promises12.writeFile)(dest, file.contents, "utf8");
2221
2320
  }
2222
2321
  }
2322
+ const outputFiles = await listOutputFiles(config.codegen.outDir);
2323
+ await writeManifest(config.codegen.outDir, {
2324
+ version: VERSION,
2325
+ hash: inputsHash,
2326
+ files: outputFiles
2327
+ });
2223
2328
  }
2224
2329
 
2225
2330
  // src/watch/watcher.ts
2226
- var import_promises14 = require("fs/promises");
2227
- var import_node_path16 = require("path");
2331
+ var import_promises15 = require("fs/promises");
2332
+ var import_node_path17 = require("path");
2228
2333
  var import_chokidar = __toESM(require("chokidar"), 1);
2229
2334
 
2230
2335
  // src/discovery/contracts-fast.ts
2231
- var import_node_path14 = require("path");
2232
- var import_fast_glob2 = __toESM(require("fast-glob"), 1);
2336
+ var import_node_path15 = require("path");
2337
+ var import_fast_glob3 = __toESM(require("fast-glob"), 1);
2233
2338
  var import_ts_morph9 = require("ts-morph");
2234
2339
 
2235
2340
  // src/discovery/dto-type-resolver.ts
@@ -2240,7 +2345,7 @@ var import_ts_morph4 = require("ts-morph");
2240
2345
 
2241
2346
  // src/discovery/type-ref-resolution.ts
2242
2347
  var import_node_fs = require("fs");
2243
- var import_node_path13 = require("path");
2348
+ var import_node_path14 = require("path");
2244
2349
  var import_ts_morph3 = require("ts-morph");
2245
2350
  var _EMPTY_CTX = { projectRoot: "", tsconfigPaths: null };
2246
2351
  var _ctxByProject = /* @__PURE__ */ new WeakMap();
@@ -2292,12 +2397,12 @@ function findTypeInFile(name, file) {
2292
2397
  }
2293
2398
  function resolveModuleSpecifier(moduleSpecifier, sourceFile, project) {
2294
2399
  if (moduleSpecifier.startsWith(".")) {
2295
- const dir = (0, import_node_path13.dirname)(sourceFile.getFilePath());
2400
+ const dir = (0, import_node_path14.dirname)(sourceFile.getFilePath());
2296
2401
  const noExt = moduleSpecifier.replace(/\.(js|ts)$/, "");
2297
2402
  return [
2298
- (0, import_node_path13.resolve)(dir, `${noExt}.ts`),
2299
- (0, import_node_path13.resolve)(dir, `${moduleSpecifier}.ts`),
2300
- (0, import_node_path13.resolve)(dir, moduleSpecifier, "index.ts")
2403
+ (0, import_node_path14.resolve)(dir, `${noExt}.ts`),
2404
+ (0, import_node_path14.resolve)(dir, `${moduleSpecifier}.ts`),
2405
+ (0, import_node_path14.resolve)(dir, moduleSpecifier, "index.ts")
2301
2406
  ];
2302
2407
  }
2303
2408
  const ctx = _ctxFor(project);
@@ -2318,8 +2423,8 @@ function resolveModuleSpecifier(moduleSpecifier, sourceFile, project) {
2318
2423
  const rest = moduleSpecifier.slice(prefix.length);
2319
2424
  const candidates = [];
2320
2425
  for (const mapping of mappings) {
2321
- const resolved = (0, import_node_path13.resolve)(baseUrl, mapping.replace("*", rest));
2322
- candidates.push(`${resolved}.ts`, (0, import_node_path13.resolve)(resolved, "index.ts"));
2426
+ const resolved = (0, import_node_path14.resolve)(baseUrl, mapping.replace("*", rest));
2427
+ candidates.push(`${resolved}.ts`, (0, import_node_path14.resolve)(resolved, "index.ts"));
2323
2428
  }
2324
2429
  dbg(" resolved candidates:", candidates);
2325
2430
  return candidates;
@@ -3991,7 +4096,7 @@ async function discoverContractsFast(opts) {
3991
4096
  const { cwd, glob, tsconfig } = opts;
3992
4097
  const tsconfigPath = resolveTsconfigPath(cwd, tsconfig);
3993
4098
  const project = createDiscoveryProject(tsconfigPath);
3994
- const files = await (0, import_fast_glob2.default)(glob, { cwd, absolute: true, onlyFiles: true });
4099
+ const files = await (0, import_fast_glob3.default)(glob, { cwd, absolute: true, onlyFiles: true });
3995
4100
  for (const f of files) {
3996
4101
  project.addSourceFileAtPath(f);
3997
4102
  }
@@ -3999,7 +4104,7 @@ async function discoverContractsFast(opts) {
3999
4104
  return extractAllRoutes(project);
4000
4105
  }
4001
4106
  function resolveTsconfigPath(cwd, tsconfig) {
4002
- return tsconfig ? (0, import_node_path14.resolve)(tsconfig) : (0, import_node_path14.join)(cwd, "tsconfig.json");
4107
+ return tsconfig ? (0, import_node_path15.resolve)(tsconfig) : (0, import_node_path15.join)(cwd, "tsconfig.json");
4003
4108
  }
4004
4109
  function createDiscoveryProject(tsconfigPath) {
4005
4110
  try {
@@ -4064,7 +4169,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4064
4169
  const project = createDiscoveryProject(tsconfigPath);
4065
4170
  bindDiscoveryContext(project, cwd, tsconfigPath);
4066
4171
  const instance = new _PersistentDiscovery(project, cwd, glob);
4067
- const files = await (0, import_fast_glob2.default)(glob, { cwd, absolute: true, onlyFiles: true });
4172
+ const files = await (0, import_fast_glob3.default)(glob, { cwd, absolute: true, onlyFiles: true });
4068
4173
  for (const f of files) {
4069
4174
  project.addSourceFileAtPath(f);
4070
4175
  instance.controllerPaths.add(f);
@@ -4085,7 +4190,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4085
4190
  async rediscover(changedPaths) {
4086
4191
  if (changedPaths) {
4087
4192
  for (const p of changedPaths) {
4088
- const abs = (0, import_node_path14.resolve)(p);
4193
+ const abs = (0, import_node_path15.resolve)(p);
4089
4194
  const sf = this.project.getSourceFile(abs);
4090
4195
  if (sf) {
4091
4196
  await sf.refreshFromFileSystem();
@@ -4093,7 +4198,7 @@ var PersistentDiscovery = class _PersistentDiscovery {
4093
4198
  }
4094
4199
  }
4095
4200
  const globbed = new Set(
4096
- await (0, import_fast_glob2.default)(this.glob, { cwd: this.cwd, absolute: true, onlyFiles: true })
4201
+ await (0, import_fast_glob3.default)(this.glob, { cwd: this.cwd, absolute: true, onlyFiles: true })
4097
4202
  );
4098
4203
  for (const f of globbed) {
4099
4204
  if (!this.controllerPaths.has(f)) {
@@ -4373,10 +4478,10 @@ function extractFromSourceFile(sourceFile, project) {
4373
4478
  }
4374
4479
 
4375
4480
  // src/watch/lock-file.ts
4376
- var import_promises12 = require("fs/promises");
4377
4481
  var import_promises13 = require("fs/promises");
4378
- var import_node_path15 = require("path");
4379
- var LOCK_FILE = ".watcher.lock";
4482
+ var import_promises14 = require("fs/promises");
4483
+ var import_node_path16 = require("path");
4484
+ var LOCK_FILE2 = ".watcher.lock";
4380
4485
  function isProcessAlive(pid) {
4381
4486
  try {
4382
4487
  process.kill(pid, 0);
@@ -4386,21 +4491,21 @@ function isProcessAlive(pid) {
4386
4491
  }
4387
4492
  }
4388
4493
  async function acquireLock(outDir) {
4389
- await (0, import_promises13.mkdir)(outDir, { recursive: true });
4390
- const lockPath = (0, import_node_path15.join)(outDir, LOCK_FILE);
4494
+ await (0, import_promises14.mkdir)(outDir, { recursive: true });
4495
+ const lockPath = (0, import_node_path16.join)(outDir, LOCK_FILE2);
4391
4496
  const lockData = { pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() };
4392
4497
  try {
4393
- const fd = await (0, import_promises12.open)(lockPath, "wx");
4498
+ const fd = await (0, import_promises13.open)(lockPath, "wx");
4394
4499
  await fd.writeFile(`${JSON.stringify(lockData, null, 2)}
4395
4500
  `, "utf8");
4396
4501
  await fd.close();
4397
4502
  } catch (err) {
4398
4503
  if (err.code === "EEXIST") {
4399
4504
  try {
4400
- const raw = await (0, import_promises13.readFile)(lockPath, "utf8");
4505
+ const raw = await (0, import_promises14.readFile)(lockPath, "utf8");
4401
4506
  const existing = JSON.parse(raw);
4402
4507
  if (isProcessAlive(existing.pid)) return null;
4403
- await (0, import_promises13.unlink)(lockPath);
4508
+ await (0, import_promises14.unlink)(lockPath);
4404
4509
  return acquireLock(outDir);
4405
4510
  } catch {
4406
4511
  return null;
@@ -4411,7 +4516,7 @@ async function acquireLock(outDir) {
4411
4516
  return {
4412
4517
  release: async () => {
4413
4518
  try {
4414
- await (0, import_promises13.unlink)(lockPath);
4519
+ await (0, import_promises14.unlink)(lockPath);
4415
4520
  } catch {
4416
4521
  }
4417
4522
  }
@@ -4422,12 +4527,12 @@ async function acquireLock(outDir) {
4422
4527
  var PAGES_DEBOUNCE_MS = 150;
4423
4528
  var NO_OP_WATCHER = { close: async () => {
4424
4529
  } };
4425
- async function watch(config, onChange) {
4530
+ async function watch(config, onChange, options = {}) {
4426
4531
  const lock = await acquireLock(config.codegen.outDir);
4427
4532
  if (lock === null) {
4428
4533
  let holderPid = "unknown";
4429
4534
  try {
4430
- const raw = await (0, import_promises14.readFile)((0, import_node_path16.join)(config.codegen.outDir, ".watcher.lock"), "utf8");
4535
+ const raw = await (0, import_promises15.readFile)((0, import_node_path17.join)(config.codegen.outDir, ".watcher.lock"), "utf8");
4431
4536
  const data = JSON.parse(raw);
4432
4537
  if (data.pid !== void 0) holderPid = String(data.pid);
4433
4538
  } catch {
@@ -4450,22 +4555,33 @@ async function watch(config, onChange) {
4450
4555
  }
4451
4556
  return discovery;
4452
4557
  }
4453
- try {
4454
- const initialRoutes = (await getDiscovery()).discover();
4455
- lastRoutes = initialRoutes;
4456
- await generate(config, initialRoutes);
4457
- } catch (err) {
4458
- console.warn(
4459
- `[nestjs-codegen] Initial route discovery failed, falling back to pages-only: ${err instanceof Error ? err.message : String(err)}`
4460
- );
4558
+ async function runInitialPass() {
4461
4559
  try {
4462
- await generate(config, lastRoutes);
4463
- } catch {
4560
+ const initialRoutes = (await getDiscovery()).discover();
4561
+ lastRoutes = initialRoutes;
4562
+ await generate(config, initialRoutes);
4563
+ } catch (err) {
4564
+ console.warn(
4565
+ `[nestjs-codegen] Initial route discovery failed, falling back to pages-only: ${err instanceof Error ? err.message : String(err)}`
4566
+ );
4567
+ try {
4568
+ await generate(config, lastRoutes);
4569
+ } catch {
4570
+ }
4464
4571
  }
4465
4572
  }
4573
+ if (options.deferInitialGenerate) {
4574
+ void runInitialPass().catch((err) => {
4575
+ console.warn(
4576
+ `[nestjs-codegen] Background initial generate failed: ${err instanceof Error ? err.message : String(err)}`
4577
+ );
4578
+ });
4579
+ } else {
4580
+ await runInitialPass();
4581
+ }
4466
4582
  let pagesDebounceTimer;
4467
4583
  const pagesGlob = config.pages?.glob ?? ".nestjs-codegen-no-pages";
4468
- const pagesWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, pagesGlob), {
4584
+ const pagesWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, pagesGlob), {
4469
4585
  ignoreInitial: true,
4470
4586
  persistent: true,
4471
4587
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4492,7 +4608,7 @@ async function watch(config, onChange) {
4492
4608
  pagesWatcher.on("unlink", schedulePagesRegenerate);
4493
4609
  let contractsDebounceTimer;
4494
4610
  const pendingChangedPaths = /* @__PURE__ */ new Set();
4495
- const contractsWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, config.contracts.glob), {
4611
+ const contractsWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, config.contracts.glob), {
4496
4612
  ignoreInitial: true,
4497
4613
  persistent: true,
4498
4614
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4522,7 +4638,7 @@ async function watch(config, onChange) {
4522
4638
  contractsWatcher.on("add", (p) => scheduleContractsRegenerate(p));
4523
4639
  contractsWatcher.on("change", (p) => scheduleContractsRegenerate(p));
4524
4640
  contractsWatcher.on("unlink", (p) => scheduleContractsRegenerate(p));
4525
- const formsWatcher = import_chokidar.default.watch((0, import_node_path16.join)(config.codegen.cwd, config.forms.watch), {
4641
+ const formsWatcher = import_chokidar.default.watch((0, import_node_path17.join)(config.codegen.cwd, config.forms.watch), {
4526
4642
  ignoreInitial: true,
4527
4643
  persistent: true,
4528
4644
  awaitWriteFinish: { stabilityThreshold: 80, pollInterval: 20 }
@@ -4632,7 +4748,7 @@ function createChainModuleRenderer(opts) {
4632
4748
  }
4633
4749
 
4634
4750
  // src/index.ts
4635
- var VERSION = "0.11.0";
4751
+ var VERSION = "0.12.0";
4636
4752
  // Annotate the CommonJS export names for ESM import in node:
4637
4753
  0 && (module.exports = {
4638
4754
  CodegenError,