@powerhousedao/vetra 6.2.3 → 6.3.0-dev.2

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 (98) hide show
  1. package/dist/codegen/index.d.ts +19 -7
  2. package/dist/codegen/index.d.ts.map +1 -1
  3. package/dist/codegen/index.js +29 -27
  4. package/dist/codegen/index.js.map +1 -1
  5. package/dist/codegen/spec.js +1 -1
  6. package/dist/document-models/app-module/index.d.ts +3 -34
  7. package/dist/document-models/app-module/index.js +1 -1
  8. package/dist/document-models/document-editor/index.d.ts +3 -32
  9. package/dist/document-models/index.d.ts +5 -5
  10. package/dist/document-models/index.js +2 -2
  11. package/dist/document-models/processor-module/index.d.ts +3 -35
  12. package/dist/document-models/processor-module/index.js +4 -4
  13. package/dist/document-models/subgraph-module/index.d.ts +3 -30
  14. package/dist/document-models/vetra-package/index.d.ts +3 -38
  15. package/dist/{editor-CiX3Tq3g.js → editor-BDR7IYJG.js} +3 -5
  16. package/dist/{editor-CiX3Tq3g.js.map → editor-BDR7IYJG.js.map} +1 -1
  17. package/dist/{editor-C5a0rBQj.js → editor-CbT_8Z6A.js} +4 -6
  18. package/dist/{editor-C5a0rBQj.js.map → editor-CbT_8Z6A.js.map} +1 -1
  19. package/dist/{editor-DpZVlVN1.js → editor-CnfajXGg.js} +3 -5
  20. package/dist/{editor-DpZVlVN1.js.map → editor-CnfajXGg.js.map} +1 -1
  21. package/dist/{editor-DpadPeVq.js → editor-Cnk0M044.js} +46 -27
  22. package/dist/editor-Cnk0M044.js.map +1 -0
  23. package/dist/{editor-BXOEFIDj.js → editor-D5SIbFn_.js} +3 -3
  24. package/dist/{editor-BXOEFIDj.js.map → editor-D5SIbFn_.js.map} +1 -1
  25. package/dist/{editor-DFEeM_dy.js → editor-SJk7cr6k.js} +3 -5
  26. package/dist/{editor-DFEeM_dy.js.map → editor-SJk7cr6k.js.map} +1 -1
  27. package/dist/editors/index.d.ts +17 -6
  28. package/dist/editors/index.d.ts.map +1 -1
  29. package/dist/editors/index.js +1 -1
  30. package/dist/{factory-BzUAqoGU.js → factory-BUuO4fIN.js} +11 -3
  31. package/dist/factory-BUuO4fIN.js.map +1 -0
  32. package/dist/{factory-BWrWHoS5.js → factory-C-Nm-wK8.js} +15 -11
  33. package/dist/factory-C-Nm-wK8.js.map +1 -0
  34. package/dist/index-BwHVZmO6.d.ts +43 -0
  35. package/dist/index-BwHVZmO6.d.ts.map +1 -0
  36. package/dist/{index-D6Ai0OOc.d.ts → index-C56rbYzd.d.ts} +2 -1
  37. package/dist/{index-D6Ai0OOc.d.ts.map → index-C56rbYzd.d.ts.map} +1 -1
  38. package/dist/index-CDV0nUS6.d.ts +36 -0
  39. package/dist/index-CDV0nUS6.d.ts.map +1 -0
  40. package/dist/{index-DPG4u1Ym.d.ts → index-ChQj71kz.d.ts} +4 -3
  41. package/dist/{index-DPG4u1Ym.d.ts.map → index-ChQj71kz.d.ts.map} +1 -1
  42. package/dist/index-CiPX7twW.d.ts +34 -0
  43. package/dist/index-CiPX7twW.d.ts.map +1 -0
  44. package/dist/{index-B52jv-LY.d.ts → index-CqDvbSe4.d.ts} +3 -2
  45. package/dist/{index-B52jv-LY.d.ts.map → index-CqDvbSe4.d.ts.map} +1 -1
  46. package/dist/index-DGhkn3As.d.ts +40 -0
  47. package/dist/index-DGhkn3As.d.ts.map +1 -0
  48. package/dist/index-DoopUfIG.d.ts +32 -0
  49. package/dist/index-DoopUfIG.d.ts.map +1 -0
  50. package/dist/{index-DplUuZMT.d.ts → index-RAhSmsFD.d.ts} +2 -1
  51. package/dist/{index-DplUuZMT.d.ts.map → index-RAhSmsFD.d.ts.map} +1 -1
  52. package/dist/index.d.ts +10 -5
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +3 -3
  55. package/dist/{module-Caxhis1M.js → module-23VayWKe.js} +7 -7
  56. package/dist/module-23VayWKe.js.map +1 -0
  57. package/dist/{module-CdpGkPNN.js → module-B6S4QGOx.js} +7 -7
  58. package/dist/module-B6S4QGOx.js.map +1 -0
  59. package/dist/{module-Db8mmgzN.js → module-BktWa0rB.js} +11 -9
  60. package/dist/module-BktWa0rB.js.map +1 -0
  61. package/dist/{module-D4lqkHHK.d.ts → module-C-jL7yqs.d.ts} +2 -1
  62. package/dist/{module-D4lqkHHK.d.ts.map → module-C-jL7yqs.d.ts.map} +1 -1
  63. package/dist/{ph-factories-HuC7_vvF.js → ph-factories-fEke-Nr8.js} +2 -2
  64. package/dist/{ph-factories-HuC7_vvF.js.map → ph-factories-fEke-Nr8.js.map} +1 -1
  65. package/dist/{processor-CsiUWh93.js → processor-CgDcxcaa.js} +426 -325
  66. package/dist/processor-CgDcxcaa.js.map +1 -0
  67. package/dist/processors/codegen/index.d.ts +11 -2
  68. package/dist/processors/codegen/index.d.ts.map +1 -1
  69. package/dist/processors/codegen/index.js +2 -2
  70. package/dist/processors/index.js +1 -1
  71. package/dist/processors/vetra-read-model/index.d.ts.map +1 -1
  72. package/dist/processors/vetra-read-model/index.js +1 -1
  73. package/dist/{spec-api-BIJ_jsGp.js → spec-api-BGj7gcQn.js} +18 -12
  74. package/dist/{spec-api-BIJ_jsGp.js.map → spec-api-BGj7gcQn.js.map} +1 -1
  75. package/dist/subgraph-type-lint-BZuO7F-G.js +116 -0
  76. package/dist/subgraph-type-lint-BZuO7F-G.js.map +1 -0
  77. package/dist/switchboard-B17FaODm.js +8 -0
  78. package/dist/{switchboard-kgDm1UIQ.js.map → switchboard-B17FaODm.js.map} +1 -1
  79. package/dist/{utils-w_21RRK6.js → utils-BJk4_43W.js} +22 -2
  80. package/dist/utils-BJk4_43W.js.map +1 -0
  81. package/package.json +13 -11
  82. package/style.css +2 -0
  83. package/dist/document-models/app-module/index.d.ts.map +0 -1
  84. package/dist/document-models/document-editor/index.d.ts.map +0 -1
  85. package/dist/document-models/processor-module/index.d.ts.map +0 -1
  86. package/dist/document-models/subgraph-module/index.d.ts.map +0 -1
  87. package/dist/document-models/vetra-package/index.d.ts.map +0 -1
  88. package/dist/editor-DpadPeVq.js.map +0 -1
  89. package/dist/factory-BWrWHoS5.js.map +0 -1
  90. package/dist/factory-BzUAqoGU.js.map +0 -1
  91. package/dist/module-Caxhis1M.js.map +0 -1
  92. package/dist/module-CdpGkPNN.js.map +0 -1
  93. package/dist/module-Db8mmgzN.js.map +0 -1
  94. package/dist/processor-CsiUWh93.js.map +0 -1
  95. package/dist/switchboard-kgDm1UIQ.js +0 -8
  96. package/dist/useVetraDocument-B0k3gNtw.js +0 -30
  97. package/dist/useVetraDocument-B0k3gNtw.js.map +0 -1
  98. package/dist/utils-w_21RRK6.js.map +0 -1
@@ -1,18 +1,16 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { n as lintSubgraphTypes, t as findSubgraphNameConflict } from "./subgraph-type-lint-BZuO7F-G.js";
2
3
  import { t as logger } from "./logger-BFxMdimR.js";
3
- import { PROCESSOR_APPS } from "@powerhousedao/shared/processors";
4
- import { generateApp, generateDocumentModel, generateEditor, generateProcessor, generateSubgraph, validateDocumentModelState } from "@powerhousedao/codegen";
4
+ import { PROCESSOR_APPS, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
5
+ import { afterPendingInstalls, generateApp, generateDocumentModel, generateEditor, generateProcessor, generateSubgraph, installFeatureDependencies, installsPending, validateDocumentModelState } from "@powerhousedao/codegen";
5
6
  import { kebabCase } from "change-case";
6
7
  import { baseMinimalSaveToFile } from "document-model/node";
7
- import { mkdir } from "node:fs/promises";
8
- import { join } from "node:path";
8
+ import { mkdir, readdir, stat } from "node:fs/promises";
9
+ import { join, relative } from "node:path";
9
10
  import { createInterface } from "node:readline";
10
11
  import { createOrUpdateManifest } from "@powerhousedao/codegen/file-builders";
11
12
  //#region processors/codegen/document-handlers/base-document-gen.ts
12
- /**
13
- * Abstract base class for document generators
14
- * Defines the interface that all document-type handlers must implement
15
- */
13
+ /** The base of the generators, one per document type or set of types. */
16
14
  var BaseDocumentGen = class {
17
15
  config;
18
16
  project;
@@ -20,28 +18,26 @@ var BaseDocumentGen = class {
20
18
  this.config = config;
21
19
  this.project = project;
22
20
  }
23
- /**
24
- * Check if this generator supports the given document type
25
- */
26
21
  supportsDocumentType(documentType) {
27
22
  if (typeof this.supportedDocumentTypes === "string") return this.supportedDocumentTypes === documentType;
28
23
  return this.supportedDocumentTypes.includes(documentType);
29
24
  }
30
- /**
31
- * Get all supported document types as an array
32
- */
33
25
  getSupportedDocumentTypes() {
34
26
  if (typeof this.supportedDocumentTypes === "string") return [this.supportedDocumentTypes];
35
27
  return [...this.supportedDocumentTypes];
36
28
  }
37
- /**
38
- * Validate if this strand should be processed
39
- * Override this method in specific generators to add custom validation logic
40
- */
29
+ /** The module's name in the strand's state, for its codegen status. */
30
+ moduleName(strand) {
31
+ const name = strand.state?.global?.name;
32
+ return typeof name === "string" && name !== "" ? name : void 0;
33
+ }
34
+ /** Why this strand is not generated from; undefined when it is. */
35
+ skipReason(strand) {
36
+ if (!strand.documentId || !strand.documentType) return "The operation names no document";
37
+ if (!this.supportsDocumentType(strand.documentType)) return `No generator for document type ${strand.documentType}`;
38
+ }
41
39
  shouldProcess(strand) {
42
- if (!strand.documentId || !strand.documentType) return false;
43
- if (!this.supportsDocumentType(strand.documentType)) return false;
44
- return true;
40
+ return this.skipReason(strand) === void 0;
45
41
  }
46
42
  };
47
43
  //#endregion
@@ -72,6 +68,12 @@ var InteractiveManager = class {
72
68
  logger.debug(`>>> Queued strand for ${documentKey}, queue size: ${this.strandQueue.size}`);
73
69
  }
74
70
  /**
71
+ * Drop the queued strands the predicate matches
72
+ */
73
+ discardWhere(predicate) {
74
+ for (const [key, queued] of this.strandQueue) if (predicate(queued.strand)) this.strandQueue.delete(key);
75
+ }
76
+ /**
75
77
  * Get all queued strands
76
78
  */
77
79
  getQueuedStrands() {
@@ -136,7 +138,7 @@ var InteractiveManager = class {
136
138
  * Process all queued strands with a single user confirmation
137
139
  * This is the main method for queue-based interactive processing
138
140
  */
139
- async processQueueWithConfirmation(processor) {
141
+ async processQueueWithConfirmation(processor, onCancel) {
140
142
  if (this.processingConfirmation) {
141
143
  logger.debug("Already processing confirmation, skipping queue processing");
142
144
  return;
@@ -150,7 +152,7 @@ var InteractiveManager = class {
150
152
  try {
151
153
  if (!await this.promptUserConfirmation()) {
152
154
  logger.info("❌ Code generation cancelled by user");
153
- this.clearQueue();
155
+ onCancel?.(this.clearQueue());
154
156
  return;
155
157
  }
156
158
  queuedStrands = this.clearQueue();
@@ -180,8 +182,46 @@ var InteractiveManager = class {
180
182
  }
181
183
  };
182
184
  //#endregion
185
+ //#region processors/codegen/written-files.ts
186
+ const SKIPPED_DIRS = /* @__PURE__ */ new Set([
187
+ "node_modules",
188
+ "dist",
189
+ "backup-documents"
190
+ ]);
191
+ const MAX_FILES = 500;
192
+ /** The project's files modified at or after `since`, relative and sorted. */
193
+ async function filesWrittenSince(projectDir, since) {
194
+ const written = [];
195
+ const visit = async (dir) => {
196
+ let entries;
197
+ try {
198
+ entries = await readdir(dir, { withFileTypes: true });
199
+ } catch {
200
+ return;
201
+ }
202
+ for (const entry of entries) {
203
+ if (written.length >= MAX_FILES) return;
204
+ const path = join(dir, entry.name);
205
+ if (entry.isDirectory()) {
206
+ if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
207
+ await visit(path);
208
+ } else if (entry.isFile()) try {
209
+ if ((await stat(path)).mtimeMs >= since) written.push(relative(projectDir, path).replaceAll("\\", "/"));
210
+ } catch {}
211
+ }
212
+ };
213
+ await visit(projectDir);
214
+ return written.sort();
215
+ }
216
+ //#endregion
183
217
  //#region processors/codegen/document-handlers/document-codegen-manager.ts
184
218
  const DEFAULT_DEBOUNCE_TIME = 1e3;
219
+ const MODULE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
220
+ "ERR_MODULE_NOT_FOUND",
221
+ "MODULE_NOT_FOUND",
222
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
223
+ ]);
224
+ const MODULE_NOT_FOUND_MESSAGE = /Cannot find (module|package)|Failed to resolve (import|entry)|Failed to load url/;
185
225
  /**
186
226
  * Manager class responsible for routing documents to the correct generator
187
227
  * and managing generator registration and instantiation
@@ -191,12 +231,26 @@ var DocumentCodegenManager = class {
191
231
  project;
192
232
  generators = /* @__PURE__ */ new Map();
193
233
  debounceTimers = /* @__PURE__ */ new Map();
194
- processingQueue = Promise.resolve();
234
+ jobs = Promise.resolve();
235
+ queuedJobs = /* @__PURE__ */ new Map();
236
+ runningJobs = 0;
237
+ /** The wait before retrying a module-resolution failure when no install is queued. */
238
+ retryDelayMs = 3e3;
195
239
  interactiveManager;
196
- constructor(config, project, interactiveMode = false) {
240
+ isInScope = () => Promise.resolve(true);
241
+ status;
242
+ constructor(config, project, interactiveMode = false, status = getCodegenStatusRegistry()) {
197
243
  this.config = config;
198
244
  this.project = project;
199
245
  this.interactiveManager = new InteractiveManager(interactiveMode);
246
+ this.status = status;
247
+ }
248
+ /**
249
+ * Limit generation to the documents `isInScope` accepts, checked when the
250
+ * debounce fires
251
+ */
252
+ setScope(isInScope) {
253
+ this.isInScope = isInScope;
200
254
  }
201
255
  /**
202
256
  * Register a generator class for a specific document type
@@ -247,16 +301,17 @@ var DocumentCodegenManager = class {
247
301
  logger.error("❌ Document type is missing from strand state");
248
302
  throw new Error("Document type is missing from strand state");
249
303
  }
250
- const generator = this.getGenerator(documentType);
251
- if (!generator) {
304
+ if (!this.getGenerator(documentType)) {
252
305
  logger.warn(`⚠️ No generator found for document type: ${documentType}`);
253
306
  logger.warn(`ℹ️ Supported document types: ${this.getRegisteredDocumentTypes().join(", ")}`);
254
307
  throw new Error(`Unsupported document type: ${documentType}`);
255
308
  }
256
- if (!generator.shouldProcess(strand)) {
257
- logger.debug(`>>> Generator validation failed for ${documentType}:${strand.documentId}, skipping processing`);
258
- return Promise.resolve();
259
- }
309
+ this.status.set({
310
+ documentId: strand.documentId,
311
+ documentType,
312
+ state: "queued",
313
+ message: this.interactiveManager.isInteractive() ? "Waiting for confirmation in the terminal running Vetra" : "Waiting for the document's changes to settle"
314
+ });
260
315
  if (this.interactiveManager.isInteractive()) {
261
316
  logger.debug(`>>> Queueing strand for interactive processing: ${documentType}:${strand.documentId}`);
262
317
  this.interactiveManager.queueStrand(strand);
@@ -264,8 +319,13 @@ var DocumentCodegenManager = class {
264
319
  if (existingTimer) clearTimeout(existingTimer);
265
320
  const debounceTimer = setTimeout(async () => {
266
321
  try {
322
+ const rejected = /* @__PURE__ */ new Set();
323
+ for (const { strand } of this.interactiveManager.getQueuedStrands()) if (!await this.accepts(strand)) rejected.add(strand);
324
+ this.interactiveManager.discardWhere((queued) => rejected.has(queued));
267
325
  await this.interactiveManager.processQueueWithConfirmation(async (queuedStrands) => {
268
326
  await this.processQueuedStrands(queuedStrands);
327
+ }, (cancelled) => {
328
+ for (const { strand } of cancelled) this.setStatus(strand, "skipped", "Cancelled in the terminal");
269
329
  });
270
330
  } catch (error) {
271
331
  logger.error("❌ Error during interactive batch processing: @error", error);
@@ -280,11 +340,9 @@ var DocumentCodegenManager = class {
280
340
  if (existingTimer) clearTimeout(existingTimer);
281
341
  const debounceTimer = setTimeout(async () => {
282
342
  try {
343
+ if (!await this.accepts(strand)) return;
283
344
  logger.debug(`🔄 Routing document type "${documentType}" to generator (debounced)`);
284
- await generator.generate(strand);
285
- logger.debug(`✅ Successfully generated code for document type: ${documentType}`);
286
- } catch (error) {
287
- logger.error(`❌ Error generating code for document type "${documentType}":`, error);
345
+ await this.enqueueJob(strand);
288
346
  } finally {
289
347
  this.debounceTimers.delete(timerKey);
290
348
  }
@@ -293,6 +351,99 @@ var DocumentCodegenManager = class {
293
351
  }
294
352
  return Promise.resolve();
295
353
  }
354
+ /** In scope first, so documents out of scope are never validated or logged. */
355
+ async accepts(strand) {
356
+ const generator = this.getGenerator(strand.documentType);
357
+ if (!generator) return false;
358
+ if (!await this.isInScope(strand.documentId)) {
359
+ logger.debug(`Document ${strand.documentId} is not in the Vetra drive, skipping codegen`);
360
+ this.status.delete(strand.documentId);
361
+ this.queuedJobs.delete(strand.documentId);
362
+ return false;
363
+ }
364
+ const reason = generator.skipReason(strand);
365
+ if (reason !== void 0) {
366
+ this.setStatus(strand, "skipped", reason);
367
+ this.queuedJobs.delete(strand.documentId);
368
+ return false;
369
+ }
370
+ return true;
371
+ }
372
+ /** Queues a job; one already queued for the document runs the latest strand. */
373
+ enqueueJob(strand) {
374
+ const { documentId } = strand;
375
+ const alreadyQueued = this.queuedJobs.has(documentId);
376
+ this.queuedJobs.set(documentId, strand);
377
+ if (this.runningJobs > 0) this.setStatus(strand, "queued", "Waiting for codegen of other documents to finish");
378
+ if (alreadyQueued) return this.jobs;
379
+ this.jobs = this.jobs.then(async () => {
380
+ const latest = this.queuedJobs.get(documentId);
381
+ this.queuedJobs.delete(documentId);
382
+ const generator = latest && this.getGenerator(latest.documentType);
383
+ if (!latest || !generator) return;
384
+ this.runningJobs++;
385
+ try {
386
+ await this.runJob(latest, generator);
387
+ } finally {
388
+ this.runningJobs--;
389
+ }
390
+ });
391
+ return this.jobs;
392
+ }
393
+ /** Runs a job after pending installs, once more after a module-resolution failure. */
394
+ async runJob(strand, generator) {
395
+ await this.afterInstalls(strand, "Waiting for a dependency install to finish");
396
+ const error = await this.attempt(strand, generator);
397
+ if (error === void 0) return;
398
+ if (!isModuleResolutionError(error)) {
399
+ this.setStatus(strand, "failed", errorMessage(error));
400
+ return;
401
+ }
402
+ logger.warn(`Codegen for ${strand.documentType} ${strand.documentId} could not resolve a module; retrying once installs finish: ${errorMessage(error)}`);
403
+ if (!await this.afterInstalls(strand, `Retrying once dependency installs finish, after: ${errorMessage(error)}`)) await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs));
404
+ const retryError = await this.attempt(strand, generator);
405
+ if (retryError !== void 0) this.setStatus(strand, "failed", `${errorMessage(retryError)} (also after a retry; if an install is running, run it to the end, then change the document again)`);
406
+ }
407
+ /** Waits for queued installs, saying so; resolves to whether any was queued. */
408
+ async afterInstalls(strand, message) {
409
+ if (!installsPending()) return false;
410
+ this.setStatus(strand, "waiting-for-install", message);
411
+ await afterPendingInstalls();
412
+ return true;
413
+ }
414
+ /** Generates once; records done or skipped, or resolves to the error. */
415
+ async attempt(strand, generator) {
416
+ const startedAt = Date.now();
417
+ const job = {
418
+ waitingForInstall: (message) => this.setStatus(strand, "waiting-for-install", message),
419
+ running: () => this.setStatus(strand, "running")
420
+ };
421
+ job.running();
422
+ try {
423
+ const result = await generator.generate(strand, job);
424
+ if (result) {
425
+ this.setStatus(strand, "skipped", result.skipped);
426
+ return;
427
+ }
428
+ const files = await filesWrittenSince(this.config.CURRENT_WORKING_DIR, startedAt);
429
+ this.setStatus(strand, "done", void 0, files);
430
+ logger.debug(`✅ Successfully generated code for document type: ${strand.documentType}`);
431
+ return;
432
+ } catch (error) {
433
+ logger.error(`❌ Error generating code for document type "${strand.documentType}":`, error);
434
+ return error ?? /* @__PURE__ */ new Error("Codegen failed");
435
+ }
436
+ }
437
+ setStatus(strand, state, message, files) {
438
+ this.status.set({
439
+ documentId: strand.documentId,
440
+ documentType: strand.documentType,
441
+ name: this.getGenerator(strand.documentType)?.moduleName(strand),
442
+ state,
443
+ message,
444
+ files
445
+ });
446
+ }
296
447
  /**
297
448
  * Process multiple strands in priority order (document-model types first)
298
449
  */
@@ -309,18 +460,12 @@ var DocumentCodegenManager = class {
309
460
  */
310
461
  async processStrand(strand) {
311
462
  const documentType = strand.documentType;
312
- const generator = this.getGenerator(documentType);
313
- if (!generator) {
463
+ if (!this.getGenerator(documentType)) {
314
464
  logger.warn(`⚠️ No generator found for document type: ${documentType}`);
315
465
  return;
316
466
  }
317
- try {
318
- logger.debug(`🔄 Generating code for document type: ${documentType}`);
319
- await generator.generate(strand);
320
- logger.debug(`✅ Successfully generated code for document type: ${documentType}`);
321
- } catch (error) {
322
- logger.error(`❌ Error generating code for document type "${documentType}":`, error);
323
- }
467
+ logger.debug(`🔄 Generating code for document type: ${documentType}`);
468
+ await this.enqueueJob(strand);
324
469
  }
325
470
  /**
326
471
  * Clear all registered generators
@@ -357,6 +502,19 @@ var DocumentCodegenManager = class {
357
502
  return this.interactiveManager.isProcessing();
358
503
  }
359
504
  };
505
+ function isModuleResolutionError(error) {
506
+ for (let cause = error; cause instanceof Error; cause = cause.cause) {
507
+ const code = cause.code;
508
+ if (code && MODULE_NOT_FOUND_CODES.has(code)) return true;
509
+ if (MODULE_NOT_FOUND_MESSAGE.test(cause.message)) return true;
510
+ }
511
+ return false;
512
+ }
513
+ function errorMessage(error) {
514
+ if (!(error instanceof Error)) return String(error);
515
+ const cause = error.cause instanceof Error ? `: ${error.cause.message}` : "";
516
+ return `${error.message}${cause}`;
517
+ }
360
518
  //#endregion
361
519
  //#region processors/codegen/document-handlers/generators/utils.ts
362
520
  const BACKUP_FOLDER = "backup-documents";
@@ -381,6 +539,36 @@ async function minimalBackupDocument(data, workingDir, extension) {
381
539
  return;
382
540
  }
383
541
  }
542
+ async function warnSubgraphTypeConflicts(workingDir) {
543
+ let warnings;
544
+ try {
545
+ warnings = await lintSubgraphTypes(workingDir);
546
+ } catch (error) {
547
+ logger.warn(`Failed to check subgraph type names: ${error instanceof Error ? error.message : String(error)}`);
548
+ return;
549
+ }
550
+ for (const warning of warnings) logger.warn(`⚠️ ${warning}`);
551
+ }
552
+ /** Adds and installs what `features` need before their files are written:
553
+ * the package loader reloads on those files, so their imports must resolve. */
554
+ async function installFeatureDependencies$1(features, projectDir, waiting, job) {
555
+ const install = { ran: false };
556
+ try {
557
+ await installFeatureDependencies(features, projectDir, {
558
+ log: (message) => logger.info(message),
559
+ warn: (message) => logger.warn(`⚠️ ${message}`),
560
+ waiting,
561
+ onInstall: (packages, command) => {
562
+ install.ran = true;
563
+ job?.waitingForInstall(`Installing ${packages.join(", ")} with \`${command}\``);
564
+ }
565
+ });
566
+ } catch (error) {
567
+ logger.warn(`⚠️ Could not add the dependencies of ${features.join(", ")}: ${error.message}`);
568
+ } finally {
569
+ if (install.ran) job?.running();
570
+ }
571
+ }
384
572
  //#endregion
385
573
  //#region processors/codegen/document-handlers/generators/app-generator.ts
386
574
  /**
@@ -388,71 +576,47 @@ async function minimalBackupDocument(data, workingDir, extension) {
388
576
  */
389
577
  var AppGenerator = class extends BaseDocumentGen {
390
578
  supportedDocumentTypes = "powerhouse/app";
391
- /**
392
- * Parse and extract the global state from the serialized state string
393
- */
394
579
  extractGlobalState(input) {
395
580
  if (!input.state) return;
396
581
  return input.state.global;
397
582
  }
398
- /**
399
- * Validate if this app strand should be processed
400
- */
401
- shouldProcess(input) {
402
- if (!super.shouldProcess(input)) return false;
583
+ skipReason(input) {
584
+ const base = super.skipReason(input);
585
+ if (base) return base;
403
586
  const state = this.extractGlobalState(input);
404
- if (!state) {
405
- logger.debug(`No state found for app: ${input.documentId}`);
406
- return false;
407
- }
408
- if (!state.name) {
409
- logger.debug(`No name found for app: ${input.documentId}`);
410
- return false;
411
- }
412
- if (state.status !== "CONFIRMED") {
413
- logger.debug(`App not confirmed: ${state.name} (status: ${state.status})`);
414
- return false;
415
- }
416
- return true;
587
+ let reason;
588
+ if (!state) reason = "The app has no state";
589
+ else if (!state.name) reason = "The app has no name";
590
+ else if (state.status !== "CONFIRMED") reason = `App "${state.name}" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;
591
+ if (reason) logger.debug(reason);
592
+ return reason;
417
593
  }
418
594
  async generate(input) {
419
595
  const state = this.extractGlobalState(input);
420
- if (!state) {
421
- logger.error(`No state found for app: ${input.documentId}`);
422
- return;
423
- }
424
- if (state.name && state.status === "CONFIRMED") {
425
- logger.info(`🔄 Starting app generation for app: ${state.name}`);
426
- try {
427
- const appId = kebabCase(state.name);
428
- await generateApp({
429
- ...this.config.PH_CONFIG,
430
- appName: state.name,
431
- appId,
432
- allowedDocumentTypes: state.allowedDocumentTypes ?? [],
433
- isDragAndDropEnabled: state.isDragAndDropEnabled
434
- }, this.project);
435
- await this.project.save();
436
- logger.info(`✅ App generation completed successfully for app: ${state.name}`);
437
- const fullState = input.state;
438
- await minimalBackupDocument({
439
- documentId: input.documentId,
440
- documentType: input.documentType,
441
- branch: input.branch,
442
- state: fullState,
443
- name: state.name
444
- }, this.config.CURRENT_WORKING_DIR);
445
- } catch (error) {
446
- logger.error(`❌ Error during app generation for app ${state.name}:`, error);
447
- if (error instanceof Error) logger.error(`❌ Error message: ${error.message}`);
448
- }
449
- } else if (!state.name) {
450
- logger.error(`❌ Skipping app generation - missing name for app`);
451
- return;
452
- } else if (state.status !== "CONFIRMED") {
453
- logger.error(`❌ Skipping app generation - app "${state.name}" is not confirmed (status: ${state.status})`);
454
- return;
596
+ const reason = this.skipReason(input);
597
+ if (!state || reason) return { skipped: reason ?? "The app has no state" };
598
+ logger.info(`🔄 Starting app generation for app: ${state.name}`);
599
+ try {
600
+ await generateApp({
601
+ ...this.config.PH_CONFIG,
602
+ appName: state.name,
603
+ appId: kebabCase(state.name),
604
+ allowedDocumentTypes: state.allowedDocumentTypes ?? [],
605
+ isDragAndDropEnabled: state.isDragAndDropEnabled
606
+ }, this.project);
607
+ await this.project.save();
608
+ } catch (error) {
609
+ logger.error(`❌ Error during app generation for app ${state.name}:`, error);
610
+ throw error;
455
611
  }
612
+ logger.info(`✅ App generation completed successfully for app: ${state.name}`);
613
+ await minimalBackupDocument({
614
+ documentId: input.documentId,
615
+ documentType: input.documentType,
616
+ branch: input.branch,
617
+ state: input.state,
618
+ name: state.name
619
+ }, this.config.CURRENT_WORKING_DIR);
456
620
  }
457
621
  };
458
622
  //#endregion
@@ -462,127 +626,97 @@ var AppGenerator = class extends BaseDocumentGen {
462
626
  */
463
627
  var DocumentEditorGenerator = class extends BaseDocumentGen {
464
628
  supportedDocumentTypes = "powerhouse/document-editor";
465
- /**
466
- * Parse and extract the global state from the serialized state string
467
- */
468
629
  extractGlobalState(input) {
469
630
  if (!input.state) return;
470
631
  return input.state.global;
471
632
  }
472
- /**
473
- * Validate if this document editor strand should be processed
474
- */
475
- shouldProcess(input) {
476
- if (!super.shouldProcess(input)) return false;
633
+ skipReason(input) {
634
+ const base = super.skipReason(input);
635
+ if (base) return base;
477
636
  const state = this.extractGlobalState(input);
478
- if (!state) {
479
- logger.debug(`No state found for document editor: ${input.documentId}`);
480
- return false;
481
- }
482
- if (!state.name) {
483
- logger.debug(`No name found for document editor: ${input.documentId}`);
484
- return false;
485
- }
486
- if (!state.documentTypes || state.documentTypes.length === 0) {
487
- logger.debug(`No document types found for document editor: ${state.name}`);
488
- return false;
489
- }
490
- if (state.status !== "CONFIRMED") {
491
- logger.debug(`Document editor not confirmed: ${state.name} (status: ${state.status})`);
492
- return false;
493
- }
494
- return true;
637
+ let reason;
638
+ if (!state) reason = "The editor has no state";
639
+ else if (!state.name) reason = "The editor has no name";
640
+ else if (state.documentTypes.length === 0) reason = `Editor "${state.name}" has no document types`;
641
+ else if (state.status !== "CONFIRMED") reason = `Editor "${state.name}" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;
642
+ if (reason) logger.debug(reason);
643
+ return reason;
495
644
  }
496
645
  async generate(input) {
497
646
  const state = this.extractGlobalState(input);
498
- if (!state) {
499
- logger.error(`No state found for document editor: ${input.documentId}`);
500
- return;
501
- }
647
+ if (!state) return { skipped: "The editor has no state" };
502
648
  logger.info(`🔄 Starting editor generation for: ${state.name}`);
503
649
  try {
504
- const documentTypes = state.documentTypes.map((dt) => dt.documentType);
505
- const editorId = kebabCase(state.name);
506
650
  await generateEditor({
507
651
  ...this.config.PH_CONFIG,
508
652
  editorName: state.name,
509
- documentTypes,
510
- editorId
653
+ documentTypes: state.documentTypes.map((dt) => dt.documentType),
654
+ editorId: kebabCase(state.name)
511
655
  }, this.project);
512
656
  await this.project.save();
513
- logger.info(`✅ Editor generation completed successfully for: ${state.name}`);
514
- const fullState = input.state;
515
- await minimalBackupDocument({
516
- documentId: input.documentId,
517
- documentType: input.documentType,
518
- branch: input.branch,
519
- state: fullState,
520
- name: state.name
521
- }, this.config.CURRENT_WORKING_DIR);
522
657
  } catch (error) {
523
658
  logger.error(`❌ Error during editor generation for ${state.name}:`, error);
524
- if (error instanceof Error) logger.error(`❌ Error message: ${error.message}`);
525
- return;
659
+ throw error;
526
660
  }
661
+ logger.info(`✅ Editor generation completed successfully for: ${state.name}`);
662
+ await minimalBackupDocument({
663
+ documentId: input.documentId,
664
+ documentType: input.documentType,
665
+ branch: input.branch,
666
+ state: input.state,
667
+ name: state.name
668
+ }, this.config.CURRENT_WORKING_DIR);
527
669
  }
528
670
  };
529
671
  //#endregion
530
- //#region processors/codegen/document-handlers/generators/document-model-generator.ts
672
+ //#region processors/codegen/document-handlers/generators/schema-first/document-model-generator.ts
531
673
  /**
532
674
  * Generator for document model documents
533
675
  */
534
676
  var DocumentModelGenerator = class extends BaseDocumentGen {
535
677
  supportedDocumentTypes = "powerhouse/document-model";
536
- /**
537
- * Parse and extract the global state from the serialized state string
538
- */
539
678
  extractGlobalState(input) {
540
679
  if (!input.state) return;
541
680
  return input.state.global;
542
681
  }
543
- /**
544
- * Validate if this document model strand should be processed
545
- */
546
- shouldProcess(input) {
547
- if (!super.shouldProcess(input)) return false;
682
+ skipReason(input) {
683
+ const base = super.skipReason(input);
684
+ if (base) return base;
548
685
  const globalState = this.extractGlobalState(input);
549
686
  if (!globalState) {
550
687
  logger.debug(`>>> No global state found for document model: ${input.documentId}`);
551
- return false;
688
+ return "The document model has no global state";
552
689
  }
553
690
  const validationResult = validateDocumentModelState(globalState);
554
691
  if (!validationResult.isValid) {
555
692
  const errorList = validationResult.errors.map((error) => ` - ${error}`).join("\n");
556
693
  logger.info(`⚠️ Skipped code generation for '${globalState.name || input.documentId}' due to validation errors:\n${errorList}`);
557
- return false;
694
+ return `The document model is not ready for code generation:\n${errorList}`;
558
695
  }
559
696
  logger.info(`Document model ${globalState.name} is valid, proceeding with code generation`);
560
- return true;
561
697
  }
562
698
  async generate(input) {
563
699
  const globalState = this.extractGlobalState(input);
564
- if (!globalState) {
565
- logger.error(`❌ No global state found for document model: ${input.documentId}`);
566
- return;
567
- }
700
+ if (!globalState) throw new Error(`No global state found for document model: ${input.documentId}`);
568
701
  logger.debug(`🔄 Starting code generation for document model: ${globalState.name}`);
569
702
  try {
570
703
  await generateDocumentModel(globalState, this.project);
571
704
  await this.project.save();
572
- logger.info(`✅ Code generation completed successfully for: ${globalState.name}`);
573
- const fullState = input.state;
574
- const extension = globalState.extension?.replace(/^\.+|\.+$/g, "") || "";
575
- await minimalBackupDocument({
576
- documentId: input.documentId,
577
- documentType: input.documentType,
578
- branch: input.branch,
579
- state: fullState,
580
- name: globalState.name
581
- }, this.config.CURRENT_WORKING_DIR, extension);
582
705
  } catch (error) {
583
706
  logger.error(`❌ Error during code generation for ${globalState.name}:`, error);
584
- return;
707
+ throw error;
585
708
  }
709
+ logger.info(`✅ Code generation completed successfully for: ${globalState.name}`);
710
+ await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);
711
+ const fullState = input.state;
712
+ const extension = globalState.extension?.replace(/^\.+|\.+$/g, "") || "";
713
+ await minimalBackupDocument({
714
+ documentId: input.documentId,
715
+ documentType: input.documentType,
716
+ branch: input.branch,
717
+ state: fullState,
718
+ name: globalState.name
719
+ }, this.config.CURRENT_WORKING_DIR, extension);
586
720
  }
587
721
  };
588
722
  //#endregion
@@ -592,16 +726,13 @@ var DocumentModelGenerator = class extends BaseDocumentGen {
592
726
  */
593
727
  var PackageGenerator = class extends BaseDocumentGen {
594
728
  supportedDocumentTypes = "powerhouse/package";
595
- /**
596
- * Validate if this package strand should be processed
597
- */
598
- shouldProcess(input) {
599
- if (!super.shouldProcess(input)) return false;
729
+ skipReason(input) {
730
+ const base = super.skipReason(input);
731
+ if (base) return base;
600
732
  if (!input.state) {
601
733
  logger.debug(`>>> No state found for package: ${input.documentId}`);
602
- return false;
734
+ return "The package has no state";
603
735
  }
604
- return true;
605
736
  }
606
737
  async generate(input) {
607
738
  const fullState = input.state;
@@ -626,107 +757,67 @@ var PackageGenerator = class extends BaseDocumentGen {
626
757
  };
627
758
  //#endregion
628
759
  //#region processors/codegen/document-handlers/generators/processor-generator.ts
760
+ const PROCESSOR_TYPES = {
761
+ analytics: "analytics",
762
+ relational: "relationalDb"
763
+ };
629
764
  /**
630
765
  * Generator for processor documents
631
766
  */
632
767
  var ProcessorGenerator = class extends BaseDocumentGen {
633
768
  supportedDocumentTypes = "powerhouse/processor";
634
- /**
635
- * Parse and extract the global state from the serialized state string
636
- */
637
769
  extractGlobalState(input) {
638
770
  if (!input.state) return;
639
771
  return input.state.global;
640
772
  }
641
- /**
642
- * Validate if this processor strand should be processed
643
- */
644
- shouldProcess(input) {
645
- if (!super.shouldProcess(input)) return false;
646
- const state = this.extractGlobalState(input);
647
- if (!state) {
648
- logger.debug(`No state found for processor: ${input.documentId}`);
649
- return false;
650
- }
651
- if (!state.name) {
652
- logger.debug(`No name found for processor: ${input.documentId}`);
653
- return false;
654
- }
655
- if (!state.type) {
656
- logger.debug(`No type found for processor: ${state.name}`);
657
- return false;
658
- }
659
- if (!state.documentTypes || state.documentTypes.length === 0) {
660
- logger.debug(`No document types found for processor: ${state.name}`);
661
- return false;
662
- }
663
- if (!state.processorApps || state.processorApps.length === 0) {
664
- logger.debug(`No processor apps found for processor: ${state.name}`);
665
- return false;
666
- }
667
- if (state.status !== "CONFIRMED") {
668
- logger.debug(`Processor not confirmed: ${state.name} (status: ${state.status})`);
669
- return false;
670
- }
671
- return true;
773
+ skipReason(input) {
774
+ const base = super.skipReason(input);
775
+ if (base) return base;
776
+ const reason = invalidReason(this.extractGlobalState(input));
777
+ if (reason) logger.debug(reason);
778
+ return reason;
672
779
  }
673
- async generate(input) {
780
+ async generate(input, job) {
674
781
  const state = this.extractGlobalState(input);
675
- if (!state) {
676
- logger.error(`No state found for processor: ${input.documentId}`);
677
- return;
678
- }
679
- if (state.name && state.type && state.documentTypes.length > 0 && state.processorApps.length > 0 && state.status === "CONFIRMED") {
680
- logger.info(`🔄 Starting processor generation for: ${state.name}`);
681
- try {
682
- let processorType;
683
- if (state.type === "analytics") processorType = "analytics";
684
- else if (state.type === "relational") processorType = "relationalDb";
685
- else {
686
- logger.error(`❌ Unsupported processor type: ${state.type}`);
687
- return;
688
- }
689
- const documentTypes = state.documentTypes.map((dt) => dt.documentType);
690
- const processorApps = state.processorApps;
691
- if (!isProcessorApps(processorApps)) {
692
- logger.error(`❌ Unsupported processor apps: ${processorApps.join(", ")}`);
693
- return;
694
- }
695
- await generateProcessor({
696
- processorName: state.name,
697
- processorType,
698
- documentTypes,
699
- processorApps
700
- }, this.project);
701
- await this.project.save();
702
- logger.info(`✅ Processor generation completed successfully for: ${state.name}`);
703
- const fullState = input.state;
704
- await minimalBackupDocument({
705
- documentId: input.documentId,
706
- documentType: input.documentType,
707
- branch: input.branch,
708
- state: fullState,
709
- name: state.name
710
- }, this.config.CURRENT_WORKING_DIR);
711
- } catch (error) {
712
- logger.error(`❌ Error during processor generation for ${state.name}:`, error);
713
- if (error instanceof Error) logger.error(`❌ Error message: ${error.message}`);
714
- }
715
- } else if (!state.name) {
716
- logger.error(`❌ Skipping processor generation - missing name for processor`);
717
- return;
718
- } else if (!state.type) {
719
- logger.error(`❌ Skipping processor generation - missing type for processor "${state.name}"`);
720
- return;
721
- } else if (state.documentTypes.length === 0) {
722
- logger.error(`❌ Skipping processor generation - missing document types for processor "${state.name}"`);
723
- return;
724
- } else if (state.status !== "CONFIRMED") {
725
- logger.error(`❌ Skipping processor generation - processor "${state.name}" is not confirmed (status: ${state.status})`);
726
- return;
782
+ const reason = this.skipReason(input);
783
+ if (!state || reason) return { skipped: reason ?? "The processor has no state" };
784
+ const processorType = PROCESSOR_TYPES[state.type];
785
+ const processorApps = state.processorApps;
786
+ logger.info(`🔄 Starting processor generation for: ${state.name}`);
787
+ try {
788
+ await installFeatureDependencies$1(processorType === "analytics" ? ["analyticsProcessor"] : ["relationalDbProcessor"], this.config.CURRENT_WORKING_DIR, `processor "${state.name}"`, job);
789
+ await generateProcessor({
790
+ processorName: state.name,
791
+ processorType,
792
+ documentTypes: state.documentTypes.map((dt) => dt.documentType),
793
+ processorApps
794
+ }, this.project);
795
+ await this.project.save();
796
+ } catch (error) {
797
+ logger.error(`❌ Error during processor generation for ${state.name}:`, error);
798
+ throw error;
727
799
  }
800
+ logger.info(`✅ Processor generation completed successfully for: ${state.name}`);
801
+ await minimalBackupDocument({
802
+ documentId: input.documentId,
803
+ documentType: input.documentType,
804
+ branch: input.branch,
805
+ state: input.state,
806
+ name: state.name
807
+ }, this.config.CURRENT_WORKING_DIR);
728
808
  }
729
809
  };
810
+ function invalidReason(state) {
811
+ if (!state) return "The processor has no state";
812
+ if (!state.name) return "The processor has no name";
813
+ const processor = `Processor "${state.name}"`;
814
+ if (!state.type) return `${processor} has no type`;
815
+ if (!(state.type in PROCESSOR_TYPES)) return `${processor} has the unsupported type "${state.type}"; use ${Object.keys(PROCESSOR_TYPES).join(" or ")}`;
816
+ if (state.documentTypes.length === 0) return `${processor} has no document types`;
817
+ if (state.processorApps.length === 0) return `${processor} has no processor apps`;
818
+ if (!isProcessorApps(state.processorApps)) return `${processor} has unsupported processor apps (${state.processorApps.join(", ")}); use ${PROCESSOR_APPS.join(", ")}, each once`;
819
+ if (state.status !== "CONFIRMED") return `${processor} is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;
820
+ }
730
821
  function isProcessorApps(input) {
731
822
  if (input.length === 0) return false;
732
823
  if (new Set(input).size !== input.length) return false;
@@ -740,63 +831,48 @@ function isProcessorApps(input) {
740
831
  */
741
832
  var SubgraphGenerator = class extends BaseDocumentGen {
742
833
  supportedDocumentTypes = "powerhouse/subgraph";
743
- /**
744
- * Parse and extract the global state from the serialized state string
745
- */
746
834
  extractGlobalState(input) {
747
835
  if (!input.state) return;
748
836
  return input.state.global;
749
837
  }
750
- /**
751
- * Validate if this subgraph strand should be processed
752
- */
753
- shouldProcess(input) {
754
- if (!super.shouldProcess(input)) return false;
838
+ skipReason(input) {
839
+ const base = super.skipReason(input);
840
+ if (base) return base;
755
841
  const state = this.extractGlobalState(input);
756
- if (!state) {
757
- logger.debug(`No state found for subgraph: ${input.documentId}`);
758
- return false;
759
- }
760
- if (!state.name) {
761
- logger.debug(`No name found for subgraph: ${input.documentId}`);
762
- return false;
763
- }
764
- if (state.status !== "CONFIRMED") {
765
- logger.debug(`Subgraph not confirmed: ${state.name} (status: ${state.status})`);
766
- return false;
767
- }
768
- return true;
769
- }
770
- async generate(input) {
842
+ let reason;
843
+ if (!state) reason = "The subgraph has no state";
844
+ else if (!state.name) reason = "The subgraph has no name";
845
+ else if (state.status !== "CONFIRMED") reason = `Subgraph "${state.name}" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;
846
+ if (reason) logger.debug(reason);
847
+ return reason;
848
+ }
849
+ async generate(input, job) {
771
850
  const state = this.extractGlobalState(input);
772
- if (!state) {
773
- logger.error(`No state found for subgraph: ${input.documentId}`);
774
- return;
775
- }
776
- if (state.name && state.status === "CONFIRMED") {
777
- logger.info(`🔄 Starting subgraph generation for: ${state.name}`);
778
- try {
779
- await generateSubgraph(state.name, this.project);
780
- await this.project.save();
781
- logger.info(`✅ Subgraph generation completed successfully for: ${state.name}`);
782
- const fullState = input.state;
783
- await minimalBackupDocument({
784
- documentId: input.documentId,
785
- documentType: input.documentType,
786
- branch: input.branch,
787
- state: fullState,
788
- name: state.name
789
- }, this.config.CURRENT_WORKING_DIR);
790
- } catch (error) {
791
- logger.error(`❌ Error during subgraph generation for ${state.name}:`, error);
851
+ const reason = this.skipReason(input);
852
+ if (!state || reason) return { skipped: reason ?? "The subgraph has no state" };
853
+ logger.info(`🔄 Starting subgraph generation for: ${state.name}`);
854
+ try {
855
+ const conflict = await findSubgraphNameConflict(this.config.CURRENT_WORKING_DIR, state.name);
856
+ if (conflict) {
857
+ logger.error(`❌ Skipping subgraph generation: ${conflict}`);
858
+ return { skipped: conflict };
792
859
  }
793
- } else if (!state.name) {
794
- logger.error(`❌ Skipping subgraph generation - missing name for subgraph`);
795
- return;
796
- } else if (state.status !== "CONFIRMED") {
797
- logger.error(`❌ Skipping subgraph generation - subgraph "${state.name}" is not confirmed (status: ${state.status})`);
798
- return;
860
+ await installFeatureDependencies$1(["subgraph"], this.config.CURRENT_WORKING_DIR, `subgraph "${state.name}"`, job);
861
+ await generateSubgraph(state.name, this.project);
862
+ await this.project.save();
863
+ } catch (error) {
864
+ logger.error(`❌ Error during subgraph generation for ${state.name}:`, error);
865
+ throw error;
799
866
  }
867
+ logger.info(`✅ Subgraph generation completed successfully for: ${state.name}`);
868
+ await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);
869
+ await minimalBackupDocument({
870
+ documentId: input.documentId,
871
+ documentType: input.documentType,
872
+ branch: input.branch,
873
+ state: input.state,
874
+ name: state.name
875
+ }, this.config.CURRENT_WORKING_DIR);
800
876
  }
801
877
  };
802
878
  //#endregion
@@ -809,8 +885,8 @@ var DocumentCodegenFactory = class {
809
885
  /**
810
886
  * Create a DocumentCodegenManager with all standard generators registered
811
887
  */
812
- static createManager(config, project, interactiveMode = false) {
813
- const manager = new DocumentCodegenManager(config, project, interactiveMode);
888
+ static createManager(config, project, interactiveMode = false, status) {
889
+ const manager = new DocumentCodegenManager(config, project, interactiveMode, status);
814
890
  manager.registerGenerator("powerhouse/document-model", DocumentModelGenerator);
815
891
  manager.registerGenerator("powerhouse/package", PackageGenerator);
816
892
  manager.registerGenerator("powerhouse/app", AppGenerator);
@@ -822,8 +898,8 @@ var DocumentCodegenFactory = class {
822
898
  /**
823
899
  * Create a DocumentCodegenManager with only specific generators
824
900
  */
825
- static createManagerWithGenerators(config, generators, project, interactiveMode = false) {
826
- const manager = new DocumentCodegenManager(config, project, interactiveMode);
901
+ static createManagerWithGenerators(config, generators, project, interactiveMode = false, status) {
902
+ const manager = new DocumentCodegenManager(config, project, interactiveMode, status);
827
903
  for (const generatorClass of generators) {
828
904
  const supportedTypes = new generatorClass(config).getSupportedDocumentTypes();
829
905
  for (const documentType of supportedTypes) manager.registerGenerator(documentType, generatorClass);
@@ -848,20 +924,26 @@ var DocumentCodegenFactory = class {
848
924
  //#region processors/codegen/processor.ts
849
925
  var processor_exports = /* @__PURE__ */ __exportAll({ CodegenProcessor: () => CodegenProcessor });
850
926
  var CodegenProcessor = class {
927
+ driveId;
928
+ client;
851
929
  manager;
852
- constructor(project, config, cwd, interactiveMode = false) {
930
+ constructor(project, config, cwd, driveId, client, interactiveMode = false) {
931
+ this.driveId = driveId;
932
+ this.client = client;
853
933
  this.manager = DocumentCodegenFactory.createManager({
854
934
  PH_CONFIG: config,
855
935
  CURRENT_WORKING_DIR: cwd
856
936
  }, project, interactiveMode);
937
+ this.manager.setScope((documentId) => this.isInDrive(documentId));
857
938
  if (interactiveMode) logger.info(`CodegenProcessor initialized with interactive mode enabled`);
858
939
  else logger.debug(`CodegenProcessor initialized with interactive mode disabled`);
859
940
  }
860
941
  async onOperations(operations) {
861
- logger.info("CodegenProcessor.onOperations()");
862
- for (const { context } of operations) {
863
- const generator = this.manager.getGenerator(context.documentType);
864
- if (!generator) {
942
+ logger.debug("CodegenProcessor.onOperations()");
943
+ const latest = /* @__PURE__ */ new Map();
944
+ for (const operation of operations) latest.set(operation.context.documentId, operation);
945
+ for (const { context } of latest.values()) {
946
+ if (!this.manager.getGenerator(context.documentType)) {
865
947
  logger.debug(`No generator found for document type: ${context.documentType}`);
866
948
  continue;
867
949
  }
@@ -872,7 +954,7 @@ var CodegenProcessor = class {
872
954
  branch: context.branch,
873
955
  state: context.resultingState ? JSON.parse(context.resultingState) : void 0
874
956
  };
875
- if (generator.shouldProcess(input)) await this.manager.routeAndGenerate(input);
957
+ await this.manager.routeAndGenerate(input);
876
958
  }
877
959
  }
878
960
  async onDisconnect() {}
@@ -885,8 +967,27 @@ var CodegenProcessor = class {
885
967
  isProcessingInteractive() {
886
968
  return this.manager.isProcessingInteractive();
887
969
  }
970
+ /**
971
+ * The reactor delivers every drive's operations, so membership is checked
972
+ * here: a node of the drive (in any folder, and in drives older than
973
+ * relationship edges), or a child edge from it (a document attached by
974
+ * relationship alone).
975
+ */
976
+ async isInDrive(documentId) {
977
+ try {
978
+ if ((await this.client.get(this.driveId)).state.global.nodes.some((node) => node.id === documentId)) return true;
979
+ } catch (error) {
980
+ logger.debug(`Could not read the Vetra drive ${this.driveId}:`, error);
981
+ }
982
+ try {
983
+ return (await this.client.getIncomingRelationshipEdges(documentId, "child")).results.some((edge) => edge.sourceId === this.driveId);
984
+ } catch (error) {
985
+ logger.debug(`Could not read the parents of ${documentId}:`, error);
986
+ return false;
987
+ }
988
+ }
888
989
  };
889
990
  //#endregion
890
991
  export { processor_exports as n, CodegenProcessor as t };
891
992
 
892
- //# sourceMappingURL=processor-CsiUWh93.js.map
993
+ //# sourceMappingURL=processor-CgDcxcaa.js.map