@powerhousedao/vetra 6.2.3-dev.100 → 6.2.3-dev.102

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.
@@ -4,6 +4,7 @@ import { et as ProcessorModuleDocument } from "../index-CqDvbSe4.js";
4
4
  import { R as SubgraphModuleDocument } from "../index-RAhSmsFD.js";
5
5
  import { _ as getDocumentModels, a as specDir, c as ActionInput, d as addActions, f as addActionsAndSave, g as getDocumentModelSchema, h as getDocument, i as saveSpec, l as ActionValidationError, m as deleteDocument, n as getSpecEntry, o as specPath, p as createDocument, r as listSpecDocumentTypes, s as stripLeadingDot, t as SPECS_DIRNAME, u as DocumentModelInfo, v as getDocuments, y as validateActions } from "../specs-DoTSfuxN.js";
6
6
  import { DocumentModelDocument } from "@powerhousedao/shared/document-model";
7
+ import { GenerateSubgraphOptions } from "@powerhousedao/codegen";
7
8
  import { Project } from "ts-morph";
8
9
  //#region codegen/extract.d.ts
9
10
  export declare function extractEditorDocuments(project: Project): DocumentEditorDocument[];
@@ -22,7 +23,7 @@ export declare function extractAllDocuments(project: Project): ExtractedDocument
22
23
  //#region codegen/generate-from-document.d.ts
23
24
  export declare function generateEditorFromDocument(doc: DocumentEditorDocument, project: Project): Promise<void>;
24
25
  export declare function generateProcessorFromDocument(doc: ProcessorModuleDocument, project: Project): Promise<void>;
25
- export declare function generateSubgraphFromDocument(doc: SubgraphModuleDocument, project: Project): Promise<void>;
26
+ export declare function generateSubgraphFromDocument(doc: SubgraphModuleDocument, project: Project, options?: GenerateSubgraphOptions): Promise<void>;
26
27
  export declare function generateAppFromDocument(doc: AppModuleDocument, project: Project): Promise<void>;
27
28
  //#endregion
28
29
  //#region codegen/schema-first/extract-document-models.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../codegen/extract.ts","../../codegen/generate-from-document.ts","../../codegen/schema-first/extract-document-models.ts","../../codegen/schema-first/generate-document-model-from-document.ts","../../codegen/subgraph-type-lint.ts"],"mappings":";;;;;;;;wBA2DgB,uBACd,SAAS,UACR;wBA2Ba,oBAAoB,SAAS,UAAU;wBAkBvC,0BACd,SAAS,UACR;wBAsBa,yBACd,SAAS,UACR;YAYS;EACV,gBAAgB;EAChB,SAAS;EACT,MAAM;EACN,YAAY;EACZ,WAAW;;wBAMG,oBAAoB,SAAS,UAAU;;;wBCpHjC,2BACpB,KAAK,wBACL,SAAS,UACR;wBAemB,8BACpB,KAAK,yBACL,SAAS,UACR;wBA+BmB,6BACpB,KAAK,wBACL,SAAS,UACR;wBAImB,wBACpB,KAAK,mBACL,SAAS,UACR;;;wBCtFa,8BACd,SAAS,UACR;;;wBCbmB,kCACpB,KAAK,uBACL,SAAS,UACR;;;;;wBC0FmB,yBACpB,oBACA,eACC;;wBAoBmB,kBAAkB,qBAAqB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../codegen/extract.ts","../../codegen/generate-from-document.ts","../../codegen/schema-first/extract-document-models.ts","../../codegen/schema-first/generate-document-model-from-document.ts","../../codegen/subgraph-type-lint.ts"],"mappings":";;;;;;;;;wBA2DgB,uBACd,SAAS,UACR;wBA2Ba,oBAAoB,SAAS,UAAU;wBAkBvC,0BACd,SAAS,UACR;wBAsBa,yBACd,SAAS,UACR;YAYS;EACV,gBAAgB;EAChB,SAAS;EACT,MAAM;EACN,YAAY;EACZ,WAAW;;wBAMG,oBAAoB,SAAS,UAAU;;;wBCnHjC,2BACpB,KAAK,wBACL,SAAS,UACR;wBAemB,8BACpB,KAAK,yBACL,SAAS,UACR;wBA+BmB,6BACpB,KAAK,wBACL,SAAS,SACT,UAAU,0BACT;wBAImB,wBACpB,KAAK,mBACL,SAAS,UACR;;;wBCxFa,8BACd,SAAS,UACR;;;wBCbmB,kCACpB,KAAK,uBACL,SAAS,UACR;;;;;wBC+FmB,yBACpB,oBACA,eACC;;wBAkCmB,kBAAkB,qBAAqB"}
@@ -3,7 +3,7 @@ import { t as createDocumentEditorDocument } from "../ph-factories-Bgnr3mK3.js";
3
3
  import { t as createProcessorModuleDocument } from "../ph-factories-fEke-Nr8.js";
4
4
  import { n as createSubgraphModuleDocument } from "../ph-factories-DhLtvC7j.js";
5
5
  import { a as getDocument, c as getDocuments, d as getSpecEntry, f as listSpecDocumentTypes, g as stripLeadingDot, h as specPath, i as deleteDocument, l as validateActions, m as specDir, n as addActionsAndSave, o as getDocumentModelSchema, p as saveSpec, r as createDocument, s as getDocumentModels, t as addActions, u as SPECS_DIRNAME } from "../spec-api-BGj7gcQn.js";
6
- import { n as lintSubgraphTypes, t as findSubgraphNameConflict } from "../subgraph-type-lint-Dr8Wu0VB.js";
6
+ import { n as lintSubgraphTypes, t as findSubgraphNameConflict } from "../subgraph-type-lint-BZuO7F-G.js";
7
7
  import { documentModelDocumentModelModule } from "document-model";
8
8
  import { PROCESSOR_APPS } from "@powerhousedao/shared/processors";
9
9
  import { generateId } from "@powerhousedao/shared/document-model";
@@ -139,8 +139,8 @@ async function generateProcessorFromDocument(doc, project) {
139
139
  processorApps
140
140
  }, project);
141
141
  }
142
- async function generateSubgraphFromDocument(doc, project) {
143
- await generateSubgraph(doc.state.global.name, project);
142
+ async function generateSubgraphFromDocument(doc, project, options) {
143
+ await generateSubgraph(doc.state.global.name, project, options);
144
144
  }
145
145
  async function generateAppFromDocument(doc, project) {
146
146
  const state = doc.state.global;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["isDefined"],"sources":["../../codegen/schema-first/extract-document-models.ts","../../codegen/extract.ts","../../codegen/generate-from-document.ts","../../codegen/schema-first/generate-document-model-from-document.ts"],"sourcesContent":["import type {\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n getOrCreateDirectory,\n loadDocumentModelInDir,\n} from \"@powerhousedao/codegen/utils\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { readdirSync } from \"node:fs\";\nimport type { Project } from \"ts-morph\";\n\nconst isDefined = <T>(v: T | undefined | null): v is T => v != null;\n\nexport function extractDocumentModelDocuments(\n project: Project,\n): DocumentModelDocument[] {\n const { directory: documentModelsDir } = getOrCreateDirectory(\n project,\n \"document-models\",\n );\n return readdirSync(documentModelsDir.getPath(), { withFileTypes: true })\n .map(loadDocumentModelInDir)\n .filter(isDefined)\n .map(buildDocumentModelDocument);\n}\n\nfunction buildDocumentModelDocument(\n globalState: DocumentModelGlobalState,\n): DocumentModelDocument {\n const state = documentModelDocumentModelModule.utils.createState({\n global: globalState,\n } as Partial<DocumentModelPHState>);\n const doc = documentModelDocumentModelModule.utils.createDocument(state);\n doc.header.name = globalState.name;\n return doc;\n}\n","/**\n * Inverse of the `generate*` functions in `@powerhousedao/codegen`.\n *\n * `generate*` reads source-of-truth documents and writes code into the project.\n * `extract*` reads the project's existing code/files and produces the\n * `powerhouse/*` documents that would have produced that code. Intended as a\n * one-shot migration step toward the documents-as-source-of-truth model: run\n * extraction, save the documents into `specs/`, and from then on regenerate\n * from the specs.\n */\nimport {\n generateId,\n type DocumentModelDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n getAppMetadata,\n getEditorDirNames,\n getEditorMetadata,\n getOrCreateDirectory,\n getProcessorDirNames,\n getProcessorMetadata,\n getSubgraphDirNames,\n getSubgraphMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport { readdirSync } from \"node:fs\";\nimport type { Project } from \"ts-morph\";\n\nimport { extractDocumentModelDocuments } from \"./schema-first/extract-document-models.js\";\n\nconst isDefined = <T>(v: T | undefined | null): v is T => v != null;\n\n/* Import from gen/ directly to bypass the top-level barrel's `hooks.ts`,\n * which pulls in browser-only `@powerhousedao/reactor-browser`. */\nimport {\n createAppModuleDocument,\n type AppModuleDocument,\n type AppModuleGlobalState,\n} from \"../document-models/app-module/v1/gen/index.js\";\nimport {\n createDocumentEditorDocument,\n type DocumentEditorDocument,\n type DocumentEditorGlobalState,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport {\n createProcessorModuleDocument,\n type ProcessorModuleDocument,\n type ProcessorModuleGlobalState,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport {\n createSubgraphModuleDocument,\n type SubgraphModuleDocument,\n type SubgraphModuleGlobalState,\n} from \"../document-models/subgraph-module/v1/gen/index.js\";\n\n/* Builds a `powerhouse/document-editor` document for each editor in the\n * project's `editors/` directory. Drive editors (powerhouse/document-drive)\n * are excluded — those are handled by `extractAppDocuments`, matching how\n * `generateAllEditors` / `generateAllApps` are split.\n */\nexport function extractEditorDocuments(\n project: Project,\n): DocumentEditorDocument[] {\n return getEditorDirNames(project)\n .map((dirName) => getEditorMetadata(project, dirName))\n .filter(isDefined)\n .filter(\n ({ documentTypes }) =>\n !documentTypes.includes(\"powerhouse/document-drive\"),\n )\n .map(({ name, documentTypes }) => {\n const global: DocumentEditorGlobalState = {\n name,\n documentTypes: documentTypes.map((documentType) => ({\n id: generateId(),\n documentType,\n })),\n status: \"CONFIRMED\",\n };\n const doc = createDocumentEditorDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\n/* Builds a `powerhouse/app` document for each drive editor (an editor whose\n * documentTypes include `powerhouse/document-drive`) — same selection\n * predicate used by `generateAllApps`.\n */\nexport function extractAppDocuments(project: Project): AppModuleDocument[] {\n return getEditorDirNames(project)\n .map((dirName) => getAppMetadata(project, dirName))\n .filter(isDefined)\n .map(({ name, allowedDocumentTypes, isDragAndDropEnabled }) => {\n const global: AppModuleGlobalState = {\n name,\n status: \"CONFIRMED\",\n allowedDocumentTypes:\n allowedDocumentTypes.length > 0 ? allowedDocumentTypes : null,\n isDragAndDropEnabled: isDragAndDropEnabled ?? true,\n };\n const doc = createAppModuleDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\nexport function extractProcessorDocuments(\n project: Project,\n): ProcessorModuleDocument[] {\n return getProcessorDirNames(project)\n .map((dirName) => getProcessorMetadata(project, dirName))\n .map(({ processorName, processorApps, processorType, documentTypes }) => {\n const global: ProcessorModuleGlobalState = {\n name: processorName,\n // Inverse of the mapping in processor-generator.ts: the document\n // model stores `relational`; codegen consumes `relationalDb`.\n type: processorType === \"relationalDb\" ? \"relational\" : processorType,\n documentTypes: documentTypes.map((documentType) => ({\n id: generateId(),\n documentType,\n })),\n status: \"CONFIRMED\",\n processorApps: [...processorApps],\n };\n const doc = createProcessorModuleDocument({ global });\n doc.header.name = processorName;\n return doc;\n });\n}\n\nexport function extractSubgraphDocuments(\n project: Project,\n): SubgraphModuleDocument[] {\n return getSubgraphDirNames(project)\n .map((dirName) => getSubgraphMetadata(project, dirName).subgraphName)\n .filter(isDefined)\n .map((name) => {\n const global: SubgraphModuleGlobalState = { name, status: \"CONFIRMED\" };\n const doc = createSubgraphModuleDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\nexport type ExtractedDocuments = {\n documentModels: DocumentModelDocument[];\n editors: DocumentEditorDocument[];\n apps: AppModuleDocument[];\n processors: ProcessorModuleDocument[];\n subgraphs: SubgraphModuleDocument[];\n};\n\n/* Mirrors `generateAll` — runs every extractor against the project and\n * returns the full set of documents keyed by module type.\n */\nexport function extractAllDocuments(project: Project): ExtractedDocuments {\n return {\n documentModels: extractDocumentModelDocuments(project),\n editors: extractEditorDocuments(project),\n apps: extractAppDocuments(project),\n processors: extractProcessorDocuments(project),\n subgraphs: extractSubgraphDocuments(project),\n };\n}\n","/**\n * Document-driven codegen wrappers. Each function takes a `PHDocument` of the\n * matching vetra type and dispatches to the generic generate* in\n * `@powerhousedao/codegen`. The state→args translation is lifted verbatim from\n * `packages/vetra/processors/codegen/document-handlers/generators/*-generator.ts`\n * so the agent-driven path and the reactor-driven path produce identical\n * output.\n *\n * Callers are responsible for `await project.save()` after one or more\n * `generate*FromDocument` calls — leaving it out here lets a CLI batch\n * multiple specs into a single save.\n */\nimport {\n generateApp,\n generateEditor,\n generateProcessor,\n generateSubgraph,\n} from \"@powerhousedao/codegen\";\nimport {\n PROCESSOR_APPS,\n type ProcessorApp,\n type ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport { kebabCase } from \"change-case\";\nimport type { Project } from \"ts-morph\";\n\n/* Import from gen/ directly to bypass the top-level barrel's `hooks.ts`,\n * which pulls in browser-only `@powerhousedao/reactor-browser`. */\nimport type { AppModuleDocument } from \"../document-models/app-module/v1/gen/index.js\";\nimport type {\n DocumentEditorDocument,\n DocumentTypeItem as EditorDocumentTypeItem,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport type {\n DocumentTypeItem as ProcessorDocumentTypeItem,\n ProcessorModuleDocument,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport type { SubgraphModuleDocument } from \"../document-models/subgraph-module/v1/gen/index.js\";\n\nexport async function generateEditorFromDocument(\n doc: DocumentEditorDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n const documentTypes = state.documentTypes.map(\n (dt: EditorDocumentTypeItem) => dt.documentType,\n );\n await generateEditor(\n {\n editorName: state.name,\n documentTypes,\n editorId: kebabCase(state.name),\n },\n project,\n );\n}\n\nexport async function generateProcessorFromDocument(\n doc: ProcessorModuleDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n // Mirror processor-generator.ts:99-103: document model stores `relational`,\n // codegen expects `relationalDb`.\n let processorType: \"analytics\" | \"relationalDb\";\n if (state.type === \"analytics\") {\n processorType = \"analytics\";\n } else if (state.type === \"relational\") {\n processorType = \"relationalDb\";\n } else {\n throw new Error(`Unsupported processor type: \"${state.type}\"`);\n }\n\n const documentTypes = state.documentTypes.map(\n (dt: ProcessorDocumentTypeItem) => dt.documentType,\n );\n const processorApps = state.processorApps;\n if (!isProcessorApps(processorApps)) {\n throw new Error(`Unsupported processor apps: ${processorApps.join(\", \")}`);\n }\n await generateProcessor(\n {\n processorName: state.name,\n processorType,\n documentTypes,\n processorApps,\n },\n project,\n );\n}\n\nexport async function generateSubgraphFromDocument(\n doc: SubgraphModuleDocument,\n project: Project,\n): Promise<void> {\n await generateSubgraph(doc.state.global.name, project);\n}\n\nexport async function generateAppFromDocument(\n doc: AppModuleDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n await generateApp(\n {\n appName: state.name,\n appId: kebabCase(state.name),\n allowedDocumentTypes: state.allowedDocumentTypes ?? [],\n isDragAndDropEnabled: state.isDragAndDropEnabled,\n },\n project,\n );\n}\n\nfunction isProcessorApps(input: readonly string[]): input is ProcessorApps {\n if (input.length === 0) return false;\n if (new Set(input).size !== input.length) return false;\n if (!input.every((i) => PROCESSOR_APPS.includes(i as ProcessorApp))) {\n return false;\n }\n return true;\n}\n","import { generateDocumentModel } from \"@powerhousedao/codegen\";\nimport type { DocumentModelDocument } from \"@powerhousedao/shared/document-model\";\nimport type { Project } from \"ts-morph\";\n\nexport async function generateDocumentModelFromDocument(\n doc: DocumentModelDocument,\n project: Project,\n): Promise<void> {\n await generateDocumentModel(doc.state.global, project);\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAMA,eAAgB,MAAoC,KAAK;AAE/D,SAAgB,8BACd,SACyB;CACzB,MAAM,EAAE,WAAW,sBAAsB,qBACvC,SACA,iBACF;CACA,OAAO,YAAY,kBAAkB,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC,CAAC,CACrE,IAAI,sBAAsB,CAAC,CAC3B,OAAOA,WAAS,CAAC,CACjB,IAAI,0BAA0B;AACnC;AAEA,SAAS,2BACP,aACuB;CACvB,MAAM,QAAQ,iCAAiC,MAAM,YAAY,EAC/D,QAAQ,YACV,CAAkC;CAClC,MAAM,MAAM,iCAAiC,MAAM,eAAe,KAAK;CACvE,IAAI,OAAO,OAAO,YAAY;CAC9B,OAAO;AACT;;;;;;;;;;;;;ACRA,MAAM,aAAgB,MAAoC,KAAK;AA8B/D,SAAgB,uBACd,SAC0B;CAC1B,OAAO,kBAAkB,OAAO,CAAC,CAC9B,KAAK,YAAY,kBAAkB,SAAS,OAAO,CAAC,CAAC,CACrD,OAAO,SAAS,CAAC,CACjB,QACE,EAAE,oBACD,CAAC,cAAc,SAAS,2BAA2B,CACvD,C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CAC9B,GACA,OACF;AACF;AAEA,SAAS,gBAAgB,OAAkD;CACzE,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM,QAAQ,OAAO;CACjD,IAAI,CAAC,MAAM,OAAO,MAAM,eAAe,SAAS,CAAiB,CAAC,GAChE,OAAO;CAET,OAAO;AACT;;;ACrHA,eAAsB,kCACpB,KACA,SACe;CACf,MAAM,sBAAsB,IAAI,MAAM,QAAQ,OAAO;AACvD"}
1
+ {"version":3,"file":"index.js","names":["isDefined"],"sources":["../../codegen/schema-first/extract-document-models.ts","../../codegen/extract.ts","../../codegen/generate-from-document.ts","../../codegen/schema-first/generate-document-model-from-document.ts"],"sourcesContent":["import type {\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n getOrCreateDirectory,\n loadDocumentModelInDir,\n} from \"@powerhousedao/codegen/utils\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { readdirSync } from \"node:fs\";\nimport type { Project } from \"ts-morph\";\n\nconst isDefined = <T>(v: T | undefined | null): v is T => v != null;\n\nexport function extractDocumentModelDocuments(\n project: Project,\n): DocumentModelDocument[] {\n const { directory: documentModelsDir } = getOrCreateDirectory(\n project,\n \"document-models\",\n );\n return readdirSync(documentModelsDir.getPath(), { withFileTypes: true })\n .map(loadDocumentModelInDir)\n .filter(isDefined)\n .map(buildDocumentModelDocument);\n}\n\nfunction buildDocumentModelDocument(\n globalState: DocumentModelGlobalState,\n): DocumentModelDocument {\n const state = documentModelDocumentModelModule.utils.createState({\n global: globalState,\n } as Partial<DocumentModelPHState>);\n const doc = documentModelDocumentModelModule.utils.createDocument(state);\n doc.header.name = globalState.name;\n return doc;\n}\n","/**\n * Inverse of the `generate*` functions in `@powerhousedao/codegen`.\n *\n * `generate*` reads source-of-truth documents and writes code into the project.\n * `extract*` reads the project's existing code/files and produces the\n * `powerhouse/*` documents that would have produced that code. Intended as a\n * one-shot migration step toward the documents-as-source-of-truth model: run\n * extraction, save the documents into `specs/`, and from then on regenerate\n * from the specs.\n */\nimport {\n generateId,\n type DocumentModelDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n getAppMetadata,\n getEditorDirNames,\n getEditorMetadata,\n getOrCreateDirectory,\n getProcessorDirNames,\n getProcessorMetadata,\n getSubgraphDirNames,\n getSubgraphMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport { readdirSync } from \"node:fs\";\nimport type { Project } from \"ts-morph\";\n\nimport { extractDocumentModelDocuments } from \"./schema-first/extract-document-models.js\";\n\nconst isDefined = <T>(v: T | undefined | null): v is T => v != null;\n\n/* Import from gen/ directly to bypass the top-level barrel's `hooks.ts`,\n * which pulls in browser-only `@powerhousedao/reactor-browser`. */\nimport {\n createAppModuleDocument,\n type AppModuleDocument,\n type AppModuleGlobalState,\n} from \"../document-models/app-module/v1/gen/index.js\";\nimport {\n createDocumentEditorDocument,\n type DocumentEditorDocument,\n type DocumentEditorGlobalState,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport {\n createProcessorModuleDocument,\n type ProcessorModuleDocument,\n type ProcessorModuleGlobalState,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport {\n createSubgraphModuleDocument,\n type SubgraphModuleDocument,\n type SubgraphModuleGlobalState,\n} from \"../document-models/subgraph-module/v1/gen/index.js\";\n\n/* Builds a `powerhouse/document-editor` document for each editor in the\n * project's `editors/` directory. Drive editors (powerhouse/document-drive)\n * are excluded — those are handled by `extractAppDocuments`, matching how\n * `generateAllEditors` / `generateAllApps` are split.\n */\nexport function extractEditorDocuments(\n project: Project,\n): DocumentEditorDocument[] {\n return getEditorDirNames(project)\n .map((dirName) => getEditorMetadata(project, dirName))\n .filter(isDefined)\n .filter(\n ({ documentTypes }) =>\n !documentTypes.includes(\"powerhouse/document-drive\"),\n )\n .map(({ name, documentTypes }) => {\n const global: DocumentEditorGlobalState = {\n name,\n documentTypes: documentTypes.map((documentType) => ({\n id: generateId(),\n documentType,\n })),\n status: \"CONFIRMED\",\n };\n const doc = createDocumentEditorDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\n/* Builds a `powerhouse/app` document for each drive editor (an editor whose\n * documentTypes include `powerhouse/document-drive`) — same selection\n * predicate used by `generateAllApps`.\n */\nexport function extractAppDocuments(project: Project): AppModuleDocument[] {\n return getEditorDirNames(project)\n .map((dirName) => getAppMetadata(project, dirName))\n .filter(isDefined)\n .map(({ name, allowedDocumentTypes, isDragAndDropEnabled }) => {\n const global: AppModuleGlobalState = {\n name,\n status: \"CONFIRMED\",\n allowedDocumentTypes:\n allowedDocumentTypes.length > 0 ? allowedDocumentTypes : null,\n isDragAndDropEnabled: isDragAndDropEnabled ?? true,\n };\n const doc = createAppModuleDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\nexport function extractProcessorDocuments(\n project: Project,\n): ProcessorModuleDocument[] {\n return getProcessorDirNames(project)\n .map((dirName) => getProcessorMetadata(project, dirName))\n .map(({ processorName, processorApps, processorType, documentTypes }) => {\n const global: ProcessorModuleGlobalState = {\n name: processorName,\n // Inverse of the mapping in processor-generator.ts: the document\n // model stores `relational`; codegen consumes `relationalDb`.\n type: processorType === \"relationalDb\" ? \"relational\" : processorType,\n documentTypes: documentTypes.map((documentType) => ({\n id: generateId(),\n documentType,\n })),\n status: \"CONFIRMED\",\n processorApps: [...processorApps],\n };\n const doc = createProcessorModuleDocument({ global });\n doc.header.name = processorName;\n return doc;\n });\n}\n\nexport function extractSubgraphDocuments(\n project: Project,\n): SubgraphModuleDocument[] {\n return getSubgraphDirNames(project)\n .map((dirName) => getSubgraphMetadata(project, dirName).subgraphName)\n .filter(isDefined)\n .map((name) => {\n const global: SubgraphModuleGlobalState = { name, status: \"CONFIRMED\" };\n const doc = createSubgraphModuleDocument({ global });\n doc.header.name = name;\n return doc;\n });\n}\n\nexport type ExtractedDocuments = {\n documentModels: DocumentModelDocument[];\n editors: DocumentEditorDocument[];\n apps: AppModuleDocument[];\n processors: ProcessorModuleDocument[];\n subgraphs: SubgraphModuleDocument[];\n};\n\n/* Mirrors `generateAll` — runs every extractor against the project and\n * returns the full set of documents keyed by module type.\n */\nexport function extractAllDocuments(project: Project): ExtractedDocuments {\n return {\n documentModels: extractDocumentModelDocuments(project),\n editors: extractEditorDocuments(project),\n apps: extractAppDocuments(project),\n processors: extractProcessorDocuments(project),\n subgraphs: extractSubgraphDocuments(project),\n };\n}\n","/**\n * Document-driven codegen wrappers. Each function takes a `PHDocument` of the\n * matching vetra type and dispatches to the generic generate* in\n * `@powerhousedao/codegen`. The state→args translation is lifted verbatim from\n * `packages/vetra/processors/codegen/document-handlers/generators/*-generator.ts`\n * so the agent-driven path and the reactor-driven path produce identical\n * output.\n *\n * Callers are responsible for `await project.save()` after one or more\n * `generate*FromDocument` calls — leaving it out here lets a CLI batch\n * multiple specs into a single save.\n */\nimport {\n generateApp,\n generateEditor,\n generateProcessor,\n generateSubgraph,\n type GenerateSubgraphOptions,\n} from \"@powerhousedao/codegen\";\nimport {\n PROCESSOR_APPS,\n type ProcessorApp,\n type ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport { kebabCase } from \"change-case\";\nimport type { Project } from \"ts-morph\";\n\n/* Import from gen/ directly to bypass the top-level barrel's `hooks.ts`,\n * which pulls in browser-only `@powerhousedao/reactor-browser`. */\nimport type { AppModuleDocument } from \"../document-models/app-module/v1/gen/index.js\";\nimport type {\n DocumentEditorDocument,\n DocumentTypeItem as EditorDocumentTypeItem,\n} from \"../document-models/document-editor/v1/gen/index.js\";\nimport type {\n DocumentTypeItem as ProcessorDocumentTypeItem,\n ProcessorModuleDocument,\n} from \"../document-models/processor-module/v1/gen/index.js\";\nimport type { SubgraphModuleDocument } from \"../document-models/subgraph-module/v1/gen/index.js\";\n\nexport async function generateEditorFromDocument(\n doc: DocumentEditorDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n const documentTypes = state.documentTypes.map(\n (dt: EditorDocumentTypeItem) => dt.documentType,\n );\n await generateEditor(\n {\n editorName: state.name,\n documentTypes,\n editorId: kebabCase(state.name),\n },\n project,\n );\n}\n\nexport async function generateProcessorFromDocument(\n doc: ProcessorModuleDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n // Mirror processor-generator.ts:99-103: document model stores `relational`,\n // codegen expects `relationalDb`.\n let processorType: \"analytics\" | \"relationalDb\";\n if (state.type === \"analytics\") {\n processorType = \"analytics\";\n } else if (state.type === \"relational\") {\n processorType = \"relationalDb\";\n } else {\n throw new Error(`Unsupported processor type: \"${state.type}\"`);\n }\n\n const documentTypes = state.documentTypes.map(\n (dt: ProcessorDocumentTypeItem) => dt.documentType,\n );\n const processorApps = state.processorApps;\n if (!isProcessorApps(processorApps)) {\n throw new Error(`Unsupported processor apps: ${processorApps.join(\", \")}`);\n }\n await generateProcessor(\n {\n processorName: state.name,\n processorType,\n documentTypes,\n processorApps,\n },\n project,\n );\n}\n\nexport async function generateSubgraphFromDocument(\n doc: SubgraphModuleDocument,\n project: Project,\n options?: GenerateSubgraphOptions,\n): Promise<void> {\n await generateSubgraph(doc.state.global.name, project, options);\n}\n\nexport async function generateAppFromDocument(\n doc: AppModuleDocument,\n project: Project,\n): Promise<void> {\n const state = doc.state.global;\n await generateApp(\n {\n appName: state.name,\n appId: kebabCase(state.name),\n allowedDocumentTypes: state.allowedDocumentTypes ?? [],\n isDragAndDropEnabled: state.isDragAndDropEnabled,\n },\n project,\n );\n}\n\nfunction isProcessorApps(input: readonly string[]): input is ProcessorApps {\n if (input.length === 0) return false;\n if (new Set(input).size !== input.length) return false;\n if (!input.every((i) => PROCESSOR_APPS.includes(i as ProcessorApp))) {\n return false;\n }\n return true;\n}\n","import { generateDocumentModel } from \"@powerhousedao/codegen\";\nimport type { DocumentModelDocument } from \"@powerhousedao/shared/document-model\";\nimport type { Project } from \"ts-morph\";\n\nexport async function generateDocumentModelFromDocument(\n doc: DocumentModelDocument,\n project: Project,\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AAU,MAAM,IAAI;CAChC,GACA,OACF;AACF;AAEA,eAAsB,8BACpB,KACA,SACe;CACf,MAAM,QAAQ,IAAI,MAAM;CAGxB,IAAI;CACJ,IAAI,MAAM,SAAS,aACjB,gBAAgB;MACX,IAAI,MAAM,SAAS,cACxB,gBAAgB;MAEhB,MAAM,IAAI,MAAM,gCAAgC,MAAM,KAAK,EAAE;CAG/D,MAAM,gBAAgB,MAAM,cAAc,KACvC,OAAkC,GAAG,YACxC;CACA,MAAM,gBAAgB,MAAM;CAC5B,IAAI,CAAC,gBAAgB,aAAa,GAChC,MAAM,IAAI,MAAM,+BAA+B,cAAc,KAAK,IAAI,GAAG;CAE3E,MAAM,kBACJ;EACE,eAAe,MAAM;EACrB;EACA;EACA;CACF,GACA,OACF;AACF;AAEA,eAAsB,6BACpB,KACA,SACA,SACe;CACf,MAAM,iBAAiB,IAAI,MAAM,OAAO,MAAM,SAAS,OAAO;AAChE;AAEA,eAAsB,wBACpB,KACA,SACe;CACf,MAAM,QAAQ,IAAI,MAAM;CACxB,MAAM,YACJ;EACE,SAAS,MAAM;EACf,OAAO,UAAU,MAAM,IAAI;EAC3B,sBAAsB,MAAM,wBAAwB,CAAC;EACrD,sBAAsB,MAAM;CAC9B,GACA,OACF;AACF;AAEA,SAAS,gBAAgB,OAAkD;CACzE,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM,QAAQ,OAAO;CACjD,IAAI,CAAC,MAAM,OAAO,MAAM,eAAe,SAAS,CAAiB,CAAC,GAChE,OAAO;CAET,OAAO;AACT;;;ACvHA,eAAsB,kCACpB,KACA,SACe;CACf,MAAM,sBAAsB,IAAI,MAAM,QAAQ,OAAO;AACvD"}
@@ -27,7 +27,7 @@ const codegenFactoryBuilder = (module) => {
27
27
  const [{ buildTsMorphProject }, { getConfig }, { CodegenProcessor }] = await Promise.all([
28
28
  import("@powerhousedao/codegen/utils"),
29
29
  import("@powerhousedao/config/node"),
30
- import("./processor-Cb2shrDB.js").then((n) => n.n)
30
+ import("./processor-CgDcxcaa.js").then((n) => n.n)
31
31
  ]);
32
32
  const config = getConfig();
33
33
  const cwd = process.cwd();
@@ -55,4 +55,4 @@ const codegenFactoryBuilder = (module) => {
55
55
  //#endregion
56
56
  export { codegenFactoryBuilder as t };
57
57
 
58
- //# sourceMappingURL=factory-GIkoxPdL.js.map
58
+ //# sourceMappingURL=factory-B9ent5Rs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"factory-GIkoxPdL.js","names":[],"sources":["../processors/codegen/factory.ts"],"sourcesContent":["import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type {\n IProcessorHostModule,\n ProcessorFactoryBuilder,\n ProcessorRecord,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport { getCodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport { logger } from \"./logger.js\";\n\n/**\n * Determines if a drive header matches the Vetra drive criteria.\n * @param driveHeader - The drive header to check\n * @param explicitDriveId - Optional explicit drive ID from config (if set, uses exact match)\n * @returns true if the drive is a Vetra drive, false otherwise\n */\nfunction isDriveVetra(\n driveHeader: PHDocumentHeader,\n driveIdFromConfig?: string,\n): boolean {\n // If explicit drive ID is configured, use exact match\n if (driveIdFromConfig) {\n return (\n driveHeader.slug === driveIdFromConfig ||\n driveHeader.id === driveIdFromConfig\n );\n }\n\n // Otherwise, check if slug/id matches Vetra pattern\n // Matches \"vetra\" exactly or IDs starting with \"vetra-\" (case-insensitive)\n const matchesPattern = (identifier: string): boolean => {\n const lower = identifier.toLowerCase();\n return lower === \"vetra\" || lower.startsWith(\"vetra-\");\n };\n\n return matchesPattern(driveHeader.slug) || matchesPattern(driveHeader.id);\n}\n\nexport const codegenFactoryBuilder: ProcessorFactoryBuilder = (\n module: IProcessorHostModule,\n) => {\n return async (driveHeader: PHDocumentHeader): Promise<ProcessorRecord[]> => {\n const processorsConfig = module.config ?? new Map<string, unknown>();\n const vetraConfig = processorsConfig.get(VETRA_PROCESSOR_CONFIG_KEY) as\n | VetraProcessorConfigType\n | undefined;\n\n // Exit early if it's not a vetra drive\n if (!isDriveVetra(driveHeader, vetraConfig?.driveId)) {\n logger.debug(\n `Drive ${driveHeader.slug} is not a Vetra drive, skipping codegen processor`,\n );\n return [];\n }\n\n logger.info(\n `Drive ${driveHeader.slug} is a Vetra drive, using codegen processor`,\n );\n\n // Lazy-load codegen only once a Vetra drive is confirmed.\n const [{ buildTsMorphProject }, { getConfig }, { CodegenProcessor }] =\n await Promise.all([\n import(\"@powerhousedao/codegen/utils\"),\n import(\"@powerhousedao/config/node\"),\n import(\"./processor.js\"),\n ]);\n\n const config = getConfig();\n const cwd = process.cwd();\n\n /* Use one instance of ts-morph project, which handles race conditions */\n const project = buildTsMorphProject(cwd);\n const processor = new CodegenProcessor(\n project,\n config,\n cwd,\n driveHeader.id,\n module.client,\n vetraConfig?.interactive,\n );\n const documentTypes = [\n \"powerhouse/document-model\",\n \"powerhouse/package\",\n \"powerhouse/document-editor\",\n \"powerhouse/subgraph\",\n \"powerhouse/processor\",\n \"powerhouse/app\",\n ];\n getCodegenStatusRegistry().watch(documentTypes);\n return [\n {\n processor,\n filter: {\n branch: [\"main\"],\n documentId: [\"*\"],\n documentType: documentTypes,\n scope: [\"global\"],\n },\n },\n ];\n };\n};\n"],"mappings":";;;;;;;;;;AAiBA,SAAS,aACP,aACA,mBACS;CAET,IAAI,mBACF,OACE,YAAY,SAAS,qBACrB,YAAY,OAAO;CAMvB,MAAM,kBAAkB,eAAgC;EACtD,MAAM,QAAQ,WAAW,YAAY;EACrC,OAAO,UAAU,WAAW,MAAM,WAAW,QAAQ;CACvD;CAEA,OAAO,eAAe,YAAY,IAAI,KAAK,eAAe,YAAY,EAAE;AAC1E;AAEA,MAAa,yBACX,WACG;CACH,OAAO,OAAO,gBAA8D;EAE1E,MAAM,eADmB,OAAO,0BAAU,IAAI,IAAqB,EAAA,CAC9B,IAAI,0BAA0B;EAKnE,IAAI,CAAC,aAAa,aAAa,aAAa,OAAO,GAAG;GACpD,OAAO,MACL,SAAS,YAAY,KAAK,kDAC5B;GACA,OAAO,CAAC;EACV;EAEA,OAAO,KACL,SAAS,YAAY,KAAK,2CAC5B;EAGA,MAAM,CAAC,EAAE,uBAAuB,EAAE,aAAa,EAAE,sBAC/C,MAAM,QAAQ,IAAI;GAChB,OAAO;GACP,OAAO;GACP,OAAO,0BAAiB,CAAA,MAAA,MAAA,EAAA,CAAA;EAC1B,CAAC;EAEH,MAAM,SAAS,UAAU;EACzB,MAAM,MAAM,QAAQ,IAAI;EAIxB,MAAM,YAAY,IAAI,iBADN,oBAAoB,GAE5B,GACN,QACA,KACA,YAAY,IACZ,OAAO,QACP,aAAa,WACf;EACA,MAAM,gBAAgB;GACpB;GACA;GACA;GACA;GACA;GACA;EACF;EACA,yBAAyB,CAAC,CAAC,MAAM,aAAa;EAC9C,OAAO,CACL;GACE;GACA,QAAQ;IACN,QAAQ,CAAC,MAAM;IACf,YAAY,CAAC,GAAG;IAChB,cAAc;IACd,OAAO,CAAC,QAAQ;GAClB;EACF,CACF;CACF;AACF"}
1
+ {"version":3,"file":"factory-B9ent5Rs.js","names":[],"sources":["../processors/codegen/factory.ts"],"sourcesContent":["import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type {\n IProcessorHostModule,\n ProcessorFactoryBuilder,\n ProcessorRecord,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport { getCodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport { logger } from \"./logger.js\";\n\n/**\n * Determines if a drive header matches the Vetra drive criteria.\n * @param driveHeader - The drive header to check\n * @param explicitDriveId - Optional explicit drive ID from config (if set, uses exact match)\n * @returns true if the drive is a Vetra drive, false otherwise\n */\nfunction isDriveVetra(\n driveHeader: PHDocumentHeader,\n driveIdFromConfig?: string,\n): boolean {\n // If explicit drive ID is configured, use exact match\n if (driveIdFromConfig) {\n return (\n driveHeader.slug === driveIdFromConfig ||\n driveHeader.id === driveIdFromConfig\n );\n }\n\n // Otherwise, check if slug/id matches Vetra pattern\n // Matches \"vetra\" exactly or IDs starting with \"vetra-\" (case-insensitive)\n const matchesPattern = (identifier: string): boolean => {\n const lower = identifier.toLowerCase();\n return lower === \"vetra\" || lower.startsWith(\"vetra-\");\n };\n\n return matchesPattern(driveHeader.slug) || matchesPattern(driveHeader.id);\n}\n\nexport const codegenFactoryBuilder: ProcessorFactoryBuilder = (\n module: IProcessorHostModule,\n) => {\n return async (driveHeader: PHDocumentHeader): Promise<ProcessorRecord[]> => {\n const processorsConfig = module.config ?? new Map<string, unknown>();\n const vetraConfig = processorsConfig.get(VETRA_PROCESSOR_CONFIG_KEY) as\n | VetraProcessorConfigType\n | undefined;\n\n // Exit early if it's not a vetra drive\n if (!isDriveVetra(driveHeader, vetraConfig?.driveId)) {\n logger.debug(\n `Drive ${driveHeader.slug} is not a Vetra drive, skipping codegen processor`,\n );\n return [];\n }\n\n logger.info(\n `Drive ${driveHeader.slug} is a Vetra drive, using codegen processor`,\n );\n\n // Lazy-load codegen only once a Vetra drive is confirmed.\n const [{ buildTsMorphProject }, { getConfig }, { CodegenProcessor }] =\n await Promise.all([\n import(\"@powerhousedao/codegen/utils\"),\n import(\"@powerhousedao/config/node\"),\n import(\"./processor.js\"),\n ]);\n\n const config = getConfig();\n const cwd = process.cwd();\n\n /* Use one instance of ts-morph project, which handles race conditions */\n const project = buildTsMorphProject(cwd);\n const processor = new CodegenProcessor(\n project,\n config,\n cwd,\n driveHeader.id,\n module.client,\n vetraConfig?.interactive,\n );\n const documentTypes = [\n \"powerhouse/document-model\",\n \"powerhouse/package\",\n \"powerhouse/document-editor\",\n \"powerhouse/subgraph\",\n \"powerhouse/processor\",\n \"powerhouse/app\",\n ];\n getCodegenStatusRegistry().watch(documentTypes);\n return [\n {\n processor,\n filter: {\n branch: [\"main\"],\n documentId: [\"*\"],\n documentType: documentTypes,\n scope: [\"global\"],\n },\n },\n ];\n };\n};\n"],"mappings":";;;;;;;;;;AAiBA,SAAS,aACP,aACA,mBACS;CAET,IAAI,mBACF,OACE,YAAY,SAAS,qBACrB,YAAY,OAAO;CAMvB,MAAM,kBAAkB,eAAgC;EACtD,MAAM,QAAQ,WAAW,YAAY;EACrC,OAAO,UAAU,WAAW,MAAM,WAAW,QAAQ;CACvD;CAEA,OAAO,eAAe,YAAY,IAAI,KAAK,eAAe,YAAY,EAAE;AAC1E;AAEA,MAAa,yBACX,WACG;CACH,OAAO,OAAO,gBAA8D;EAE1E,MAAM,eADmB,OAAO,0BAAU,IAAI,IAAqB,EAAA,CAC9B,IAAI,0BAA0B;EAKnE,IAAI,CAAC,aAAa,aAAa,aAAa,OAAO,GAAG;GACpD,OAAO,MACL,SAAS,YAAY,KAAK,kDAC5B;GACA,OAAO,CAAC;EACV;EAEA,OAAO,KACL,SAAS,YAAY,KAAK,2CAC5B;EAGA,MAAM,CAAC,EAAE,uBAAuB,EAAE,aAAa,EAAE,sBAC/C,MAAM,QAAQ,IAAI;GAChB,OAAO;GACP,OAAO;GACP,OAAO,0BAAiB,CAAA,MAAA,MAAA,EAAA,CAAA;EAC1B,CAAC;EAEH,MAAM,SAAS,UAAU;EACzB,MAAM,MAAM,QAAQ,IAAI;EAIxB,MAAM,YAAY,IAAI,iBADN,oBAAoB,GAE5B,GACN,QACA,KACA,YAAY,IACZ,OAAO,QACP,aAAa,WACf;EACA,MAAM,gBAAgB;GACpB;GACA;GACA;GACA;GACA;GACA;EACF;EACA,yBAAyB,CAAC,CAAC,MAAM,aAAa;EAC9C,OAAO,CACL;GACE;GACA,QAAQ;IACN,QAAQ,CAAC,MAAM;IACf,YAAY,CAAC,GAAG;IAChB,cAAc;IACd,OAAO,CAAC,QAAQ;GAClB;EACF,CACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { n as lintSubgraphTypes, t as findSubgraphNameConflict } from "./subgraph-type-lint-Dr8Wu0VB.js";
2
+ import { n as lintSubgraphTypes, t as findSubgraphNameConflict } from "./subgraph-type-lint-BZuO7F-G.js";
3
3
  import { t as logger } from "./logger-BFxMdimR.js";
4
4
  import { PROCESSOR_APPS, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
5
5
  import { afterPendingInstalls, generateApp, generateDocumentModel, generateEditor, generateProcessor, generateSubgraph, installFeatureDependencies, installsPending, validateDocumentModelState } from "@powerhousedao/codegen";
@@ -990,4 +990,4 @@ var CodegenProcessor = class {
990
990
  //#endregion
991
991
  export { processor_exports as n, CodegenProcessor as t };
992
992
 
993
- //# sourceMappingURL=processor-Cb2shrDB.js.map
993
+ //# sourceMappingURL=processor-CgDcxcaa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"processor-Cb2shrDB.js","names":["installFeatureDependencies","installForFeatures","installFeatureDependencies","installFeatureDependencies"],"sources":["../processors/codegen/document-handlers/base-document-gen.ts","../processors/codegen/interactive-manager.ts","../processors/codegen/written-files.ts","../processors/codegen/document-handlers/document-codegen-manager.ts","../processors/codegen/document-handlers/generators/utils.ts","../processors/codegen/document-handlers/generators/app-generator.ts","../processors/codegen/document-handlers/generators/document-editor-generator.ts","../processors/codegen/document-handlers/generators/schema-first/document-model-generator.ts","../processors/codegen/document-handlers/generators/package-generator.ts","../processors/codegen/document-handlers/generators/processor-generator.ts","../processors/codegen/document-handlers/generators/subgraph-generator.ts","../processors/codegen/document-handlers/document-codegen-factory.ts","../processors/codegen/processor.ts"],"sourcesContent":["import type { Project } from \"ts-morph\";\nimport type {\n CodegenInput,\n CodegenJob,\n Config,\n GenerateResult,\n} from \"./types.js\";\n\n/** The base of the generators, one per document type or set of types. */\nexport abstract class BaseDocumentGen {\n /** The document type or types this generator handles. */\n abstract readonly supportedDocumentTypes: string | string[];\n project: Project;\n\n constructor(\n protected config: Config,\n project: Project,\n ) {\n this.project = project;\n }\n\n /** Generates code for the document; throws when generation fails. */\n abstract generate(\n strand: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult>;\n\n supportsDocumentType(documentType: string): boolean {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return this.supportedDocumentTypes === documentType;\n }\n return this.supportedDocumentTypes.includes(documentType);\n }\n\n getSupportedDocumentTypes(): string[] {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return [this.supportedDocumentTypes];\n }\n return [...this.supportedDocumentTypes];\n }\n\n /** The module's name in the strand's state, for its codegen status. */\n moduleName(strand: CodegenInput): string | undefined {\n const state = strand.state as { global?: { name?: unknown } } | undefined;\n const name = state?.global?.name;\n return typeof name === \"string\" && name !== \"\" ? name : undefined;\n }\n\n /** Why this strand is not generated from; undefined when it is. */\n skipReason(strand: CodegenInput): string | undefined {\n if (!strand.documentId || !strand.documentType) {\n return \"The operation names no document\";\n }\n if (!this.supportsDocumentType(strand.documentType)) {\n return `No generator for document type ${strand.documentType}`;\n }\n return undefined;\n }\n\n shouldProcess(strand: CodegenInput): boolean {\n return this.skipReason(strand) === undefined;\n }\n}\n","import { createInterface } from \"node:readline\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport interface QueuedStrand {\n strand: CodegenInput;\n timestamp: number;\n}\n\n/**\n * InteractiveManager handles user interaction for code generation confirmation\n * Supports both individual strand processing and queue-based batch processing\n */\nexport class InteractiveManager {\n private isInteractiveMode: boolean;\n private processingConfirmation = false;\n private strandQueue = new Map<string, QueuedStrand>();\n\n constructor(interactiveMode = false) {\n this.isInteractiveMode = interactiveMode;\n }\n\n private getDocumentKey(documentType: string, documentId: string): string {\n return `${documentType}:${documentId}`;\n }\n\n /**\n * Add a strand to the queue, replacing any existing strand for the same document\n */\n public queueStrand(strand: CodegenInput): void {\n const documentKey = this.getDocumentKey(\n strand.documentType,\n strand.documentId,\n );\n\n this.strandQueue.set(documentKey, {\n strand,\n timestamp: Date.now(),\n });\n\n logger.debug(\n `>>> Queued strand for ${documentKey}, queue size: ${this.strandQueue.size}`,\n );\n }\n\n /**\n * Drop the queued strands the predicate matches\n */\n public discardWhere(predicate: (strand: CodegenInput) => boolean): void {\n for (const [key, queued] of this.strandQueue) {\n if (predicate(queued.strand)) this.strandQueue.delete(key);\n }\n }\n\n /**\n * Get all queued strands\n */\n public getQueuedStrands(): QueuedStrand[] {\n return Array.from(this.strandQueue.values());\n }\n\n /**\n * Clear and return all queued strands\n */\n public clearQueue(): QueuedStrand[] {\n const queuedStrands = Array.from(this.strandQueue.values());\n this.strandQueue.clear();\n return queuedStrands;\n }\n\n /**\n * Get the current queue size\n */\n public getQueueSize(): number {\n return this.strandQueue.size;\n }\n\n private async promptUserConfirmation(): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔄 Code generation ready to run.\");\n console.log(\"=\".repeat(50));\n\n process.stdout.write(\n \"Do you want to proceed with code generation? (y/n): \\n\\n\",\n );\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n console.log(\"\"); // Add blank line after user input\n resolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n });\n });\n }\n\n /**\n * Process generation with user confirmation (legacy single-strand method)\n * This method assumes interactive mode is already enabled (checked by caller)\n */\n public async processWithConfirmation<T>(\n documentType: string,\n generator: () => Promise<T>,\n ): Promise<T | null> {\n if (this.processingConfirmation) {\n logger.debug(\"Already processing confirmation, skipping\");\n return null;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Always prompt user since this method only called in interactive mode\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(`❌ Code generation cancelled by user for ${documentType}`);\n return null;\n }\n\n logger.info(`✅ User approved code generation for ${documentType}`);\n\n const result = await generator();\n return result;\n } catch (error) {\n logger.error(\n `❌ Error during interactive code generation for ${documentType}:`,\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n /**\n * Process all queued strands with a single user confirmation\n * This is the main method for queue-based interactive processing\n */\n public async processQueueWithConfirmation(\n processor: (strands: QueuedStrand[]) => Promise<void>,\n onCancel?: (strands: QueuedStrand[]) => void,\n ): Promise<void> {\n if (this.processingConfirmation) {\n logger.debug(\n \"Already processing confirmation, skipping queue processing\",\n );\n return;\n }\n\n // Check if there are any strands to process\n let queuedStrands = this.getQueuedStrands();\n if (queuedStrands.length === 0) {\n logger.debug(\"No strands in queue to process\");\n return;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Prompt user for confirmation\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(\"❌ Code generation cancelled by user\");\n onCancel?.(this.clearQueue());\n return;\n }\n\n // Get and clear the final queue state right before processing\n // (in case new strands were added while waiting for user input)\n queuedStrands = this.clearQueue();\n if (queuedStrands.length === 0) {\n logger.info(\"ℹ️ No documents to process\");\n return;\n }\n\n logger.info(\n `✅ User approved code generation for ${queuedStrands.length} document(s)`,\n );\n\n // Process all queued strands\n await processor(queuedStrands);\n logger.info(\"✅ Code generation completed\");\n } catch (error) {\n logger.error(\n \"❌ Error during interactive queue processing: @error\",\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n public setInteractiveMode(enabled: boolean): void {\n this.isInteractiveMode = enabled;\n logger.debug(`Interactive mode set to: ${enabled}`);\n }\n\n public isInteractive(): boolean {\n return this.isInteractiveMode;\n }\n\n public isProcessing(): boolean {\n return this.processingConfirmation;\n }\n}\n","import type { Dirent } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nconst SKIPPED_DIRS = new Set([\"node_modules\", \"dist\", \"backup-documents\"]);\nconst MAX_FILES = 500;\n\n/** The project's files modified at or after `since`, relative and sorted. */\nexport async function filesWrittenSince(\n projectDir: string,\n since: number,\n): Promise<string[]> {\n const written: string[] = [];\n const visit = async (dir: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (written.length >= MAX_FILES) return;\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || SKIPPED_DIRS.has(entry.name)) {\n continue;\n }\n await visit(path);\n } else if (entry.isFile()) {\n try {\n if ((await stat(path)).mtimeMs >= since) {\n written.push(relative(projectDir, path).replaceAll(\"\\\\\", \"/\"));\n }\n } catch {\n // Removed while listing.\n }\n }\n }\n };\n await visit(projectDir);\n return written.sort();\n}\n","import { afterPendingInstalls, installsPending } from \"@powerhousedao/codegen\";\nimport {\n type CodegenState,\n type CodegenStatusRegistry,\n getCodegenStatusRegistry,\n} from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { QueuedStrand } from \"../interactive-manager.js\";\nimport { InteractiveManager } from \"../interactive-manager.js\";\nimport { logger } from \"../logger.js\";\nimport { filesWrittenSince } from \"../written-files.js\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, Config } from \"./types.js\";\n\nconst DEFAULT_DEBOUNCE_TIME = 1000; // wait 1 second between codegen calls\nconst MODULE_NOT_FOUND_CODES = new Set([\n \"ERR_MODULE_NOT_FOUND\",\n \"MODULE_NOT_FOUND\",\n \"ERR_PACKAGE_PATH_NOT_EXPORTED\",\n]);\nconst MODULE_NOT_FOUND_MESSAGE =\n /Cannot find (module|package)|Failed to resolve (import|entry)|Failed to load url/;\n\n/** Whether a document belongs to what this manager generates from. */\nexport type DocumentScope = (documentId: string) => Promise<boolean>;\n\n/**\n * Manager class responsible for routing documents to the correct generator\n * and managing generator registration and instantiation\n */\nexport class DocumentCodegenManager {\n project: Project;\n private generators = new Map<string, BaseDocumentGen>();\n private debounceTimers = new Map<string, NodeJS.Timeout>();\n // One job at a time, so none runs while another job's install relinks node_modules.\n private jobs: Promise<void> = Promise.resolve();\n private queuedJobs = new Map<string, CodegenInput>();\n private runningJobs = 0;\n /** The wait before retrying a module-resolution failure when no install is queued. */\n retryDelayMs = 3000;\n private interactiveManager: InteractiveManager;\n private isInScope: DocumentScope = () => Promise.resolve(true);\n readonly status: CodegenStatusRegistry;\n\n constructor(\n private config: Config,\n project: Project,\n interactiveMode = false,\n status: CodegenStatusRegistry = getCodegenStatusRegistry(),\n ) {\n this.project = project;\n this.interactiveManager = new InteractiveManager(interactiveMode);\n this.status = status;\n }\n\n /**\n * Limit generation to the documents `isInScope` accepts, checked when the\n * debounce fires\n */\n setScope(isInScope: DocumentScope): void {\n this.isInScope = isInScope;\n }\n\n /**\n * Register a generator class for a specific document type\n */\n registerGenerator(\n documentType: string,\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n\n this.generators.set(\n documentType,\n new generatorClass(this.config, this.project),\n );\n logger.debug(`✅ Registered generator for document type: ${documentType}`);\n }\n\n /**\n * Register a generator class that supports multiple document types\n */\n registerMultiTypeGenerator(\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n const generator = new generatorClass(this.config, this.project);\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n this.generators.set(documentType, generator);\n }\n\n logger.debug(\n `✅ Registered multi-type generator for document types: ${supportedTypes.join(\", \")}`,\n );\n }\n\n /**\n * Get a generator instance for the given document type\n * Public method to allow external access for validation\n */\n public getGenerator(documentType: string): BaseDocumentGen | undefined {\n return this.generators.get(documentType);\n }\n\n /**\n * Get all registered document types\n */\n getRegisteredDocumentTypes(): string[] {\n return Array.from(this.generators.keys());\n }\n\n /**\n * Check if a document type is supported\n */\n isDocumentTypeSupported(documentType: string): boolean {\n return this.generators.has(documentType);\n }\n\n /**\n * Route a document to the appropriate generator and handle the generation\n * Handles both interactive and non-interactive modes with queue-based processing\n */\n routeAndGenerate(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n\n if (!documentType) {\n logger.error(\"❌ Document type is missing from strand state\");\n throw new Error(\"Document type is missing from strand state\");\n }\n\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n logger.warn(\n `ℹ️ Supported document types: ${this.getRegisteredDocumentTypes().join(\", \")}`,\n );\n throw new Error(`Unsupported document type: ${documentType}`);\n }\n\n // Scope and validation are checked when the debounce fires, on the\n // document's final state.\n this.status.set({\n documentId: strand.documentId,\n documentType,\n state: \"queued\",\n message: this.interactiveManager.isInteractive()\n ? \"Waiting for confirmation in the terminal running Vetra\"\n : \"Waiting for the document's changes to settle\",\n });\n // Different flow for interactive vs non-interactive mode\n if (this.interactiveManager.isInteractive()) {\n // Interactive mode: queue strands and use debounce timer to trigger batch processing\n logger.debug(\n `>>> Queueing strand for interactive processing: ${documentType}:${strand.documentId}`,\n );\n\n // Add strand to queue (will replace any existing strand for same document)\n this.interactiveManager.queueStrand(strand);\n\n // Clear any existing debounce timer for interactive processing\n const existingTimer = this.debounceTimers.get(\"interactive\");\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up debounce timer for batch interactive processing\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n const rejected = new Set<CodegenInput>();\n for (const { strand } of this.interactiveManager.getQueuedStrands()) {\n if (!(await this.accepts(strand))) rejected.add(strand);\n }\n this.interactiveManager.discardWhere((queued) =>\n rejected.has(queued),\n );\n await this.interactiveManager.processQueueWithConfirmation(\n async (queuedStrands: QueuedStrand[]) => {\n await this.processQueuedStrands(queuedStrands);\n },\n (cancelled) => {\n for (const { strand } of cancelled) {\n this.setStatus(strand, \"skipped\", \"Cancelled in the terminal\");\n }\n },\n );\n } catch (error) {\n logger.error(\n \"❌ Error during interactive batch processing: @error\",\n error,\n );\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(\"interactive\");\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference using 'interactive' key\n this.debounceTimers.set(\"interactive\", debounceTimer);\n } else {\n // Non-interactive mode: use debouncing per document instance\n // Create unique key for this specific document instance\n const timerKey = `${documentType}:${strand.documentId}`;\n\n // Clear any existing debounce timer for this document instance\n const existingTimer = this.debounceTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up new debounced generation (no interactive confirmation)\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n if (!(await this.accepts(strand))) return;\n logger.debug(\n `🔄 Routing document type \"${documentType}\" to generator (debounced)`,\n );\n await this.enqueueJob(strand);\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(timerKey);\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference\n this.debounceTimers.set(timerKey, debounceTimer);\n }\n return Promise.resolve();\n }\n\n /** In scope first, so documents out of scope are never validated or logged. */\n private async accepts(strand: CodegenInput): Promise<boolean> {\n const generator = this.getGenerator(strand.documentType);\n if (!generator) return false;\n if (!(await this.isInScope(strand.documentId))) {\n logger.debug(\n `Document ${strand.documentId} is not in the Vetra drive, skipping codegen`,\n );\n this.status.delete(strand.documentId);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n const reason = generator.skipReason(strand);\n if (reason !== undefined) {\n this.setStatus(strand, \"skipped\", reason);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n return true;\n }\n\n /** Queues a job; one already queued for the document runs the latest strand. */\n private enqueueJob(strand: CodegenInput): Promise<void> {\n const { documentId } = strand;\n const alreadyQueued = this.queuedJobs.has(documentId);\n this.queuedJobs.set(documentId, strand);\n if (this.runningJobs > 0) {\n this.setStatus(\n strand,\n \"queued\",\n \"Waiting for codegen of other documents to finish\",\n );\n }\n if (alreadyQueued) return this.jobs;\n this.jobs = this.jobs.then(async () => {\n const latest = this.queuedJobs.get(documentId);\n this.queuedJobs.delete(documentId);\n const generator = latest && this.getGenerator(latest.documentType);\n if (!latest || !generator) return;\n this.runningJobs++;\n try {\n await this.runJob(latest, generator);\n } finally {\n this.runningJobs--;\n }\n });\n return this.jobs;\n }\n\n /** Runs a job after pending installs, once more after a module-resolution failure. */\n private async runJob(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<void> {\n await this.afterInstalls(\n strand,\n \"Waiting for a dependency install to finish\",\n );\n const error = await this.attempt(strand, generator);\n if (error === undefined) return;\n if (!isModuleResolutionError(error)) {\n this.setStatus(strand, \"failed\", errorMessage(error));\n return;\n }\n logger.warn(\n `Codegen for ${strand.documentType} ${strand.documentId} could not resolve a module; retrying once installs finish: ${errorMessage(error)}`,\n );\n const waited = await this.afterInstalls(\n strand,\n `Retrying once dependency installs finish, after: ${errorMessage(error)}`,\n );\n if (!waited) {\n await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs));\n }\n const retryError = await this.attempt(strand, generator);\n if (retryError !== undefined) {\n this.setStatus(\n strand,\n \"failed\",\n `${errorMessage(retryError)} (also after a retry; if an install is running, run it to the end, then change the document again)`,\n );\n }\n }\n\n /** Waits for queued installs, saying so; resolves to whether any was queued. */\n private async afterInstalls(\n strand: CodegenInput,\n message: string,\n ): Promise<boolean> {\n if (!installsPending()) return false;\n this.setStatus(strand, \"waiting-for-install\", message);\n await afterPendingInstalls();\n return true;\n }\n\n /** Generates once; records done or skipped, or resolves to the error. */\n private async attempt(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<unknown> {\n const startedAt = Date.now();\n const job: CodegenJob = {\n waitingForInstall: (message) =>\n this.setStatus(strand, \"waiting-for-install\", message),\n running: () => this.setStatus(strand, \"running\"),\n };\n job.running();\n try {\n const result = await generator.generate(strand, job);\n if (result) {\n this.setStatus(strand, \"skipped\", result.skipped);\n return;\n }\n const files = await filesWrittenSince(\n this.config.CURRENT_WORKING_DIR,\n startedAt,\n );\n this.setStatus(strand, \"done\", undefined, files);\n logger.debug(\n `✅ Successfully generated code for document type: ${strand.documentType}`,\n );\n return undefined;\n } catch (error) {\n logger.error(\n `❌ Error generating code for document type \"${strand.documentType}\":`,\n error,\n );\n return error ?? new Error(\"Codegen failed\");\n }\n }\n\n private setStatus(\n strand: CodegenInput,\n state: CodegenState,\n message?: string,\n files?: string[],\n ): void {\n this.status.set({\n documentId: strand.documentId,\n documentType: strand.documentType,\n name: this.getGenerator(strand.documentType)?.moduleName(strand),\n state,\n message,\n files,\n });\n }\n\n /**\n * Process multiple strands in priority order (document-model types first)\n */\n private async processQueuedStrands(\n queuedStrands: QueuedStrand[],\n ): Promise<void> {\n logger.debug(`🔄 Processing ${queuedStrands.length} queued strand(s)`);\n\n // Sort by priority (document-model first to ensure dependencies exist)\n const documentModelStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType === \"powerhouse/document-model\",\n );\n const otherStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType !== \"powerhouse/document-model\",\n );\n\n // Process document models first\n for (const queuedStrand of documentModelStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n // Then process other document types\n for (const queuedStrand of otherStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n logger.debug(\n `✅ Successfully processed all ${queuedStrands.length} queued strand(s)`,\n );\n }\n\n /**\n * Process a single strand (used internally by processQueuedStrands)\n */\n private async processStrand(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n return;\n }\n\n logger.debug(`🔄 Generating code for document type: ${documentType}`);\n await this.enqueueJob(strand);\n }\n\n /**\n * Clear all registered generators\n */\n clearGenerators(): void {\n this.generators.clear();\n logger.debug(\"🧹 Cleared all registered generators\");\n }\n\n /**\n * Get statistics about registered generators\n */\n getStats(): { totalGenerators: number; supportedTypes: string[] } {\n return {\n totalGenerators: this.generators.size,\n supportedTypes: this.getRegisteredDocumentTypes(),\n };\n }\n\n /**\n * Set interactive mode for code generation\n */\n setInteractiveMode(enabled: boolean): void {\n this.interactiveManager.setInteractiveMode(enabled);\n }\n\n /**\n * Check if interactive mode is enabled\n */\n isInteractiveMode(): boolean {\n return this.interactiveManager.isInteractive();\n }\n\n /**\n * Check if the manager is currently processing an interactive confirmation\n */\n isProcessingInteractive(): boolean {\n return this.interactiveManager.isProcessing();\n }\n}\n\nfunction isModuleResolutionError(error: unknown): boolean {\n for (let cause = error; cause instanceof Error; cause = cause.cause) {\n const code = (cause as NodeJS.ErrnoException).code;\n if (code && MODULE_NOT_FOUND_CODES.has(code)) return true;\n if (MODULE_NOT_FOUND_MESSAGE.test(cause.message)) return true;\n }\n return false;\n}\n\nfunction errorMessage(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = error.cause instanceof Error ? `: ${error.cause.message}` : \"\";\n return `${error.message}${cause}`;\n}\n","import {\n type Feature,\n installFeatureDependencies as installForFeatures,\n} from \"@powerhousedao/codegen\";\nimport type {\n MinimalBackupData,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { baseMinimalSaveToFile, baseSaveToFile } from \"document-model/node\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { lintSubgraphTypes } from \"../../../../codegen/subgraph-type-lint.js\";\nimport { logger } from \"../../logger.js\";\nimport type { CodegenJob } from \"../types.js\";\n\nconst BACKUP_FOLDER = \"backup-documents\";\n\n/**\n * Exports a document to the backup directory.\n * Creates the backup directory if it doesn't exist.\n *\n * @param document - The document to backup\n * @param workingDir - Current working directory\n * @param extension - File extension for the document type (without dot)\n * @param name - Name of the document to use for the backup file (optional)\n * @returns Promise resolving to the backup file path, or undefined if backup failed\n */\nexport async function backupDocument(\n document: PHDocument,\n workingDir: string,\n extension: string = \"\",\n name?: string,\n): Promise<string | undefined> {\n const docName = name ?? document.header.name;\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseSaveToFile(\n document,\n backupPath,\n extension,\n docName,\n );\n\n logger.debug(`📁 Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`⚠️ Failed to backup document \"${docName}\":`, error);\n return undefined;\n }\n}\n\n/**\n * Creates a minimal backup of a document from strand data.\n * Used when the full document is not available (e.g., in onOperations handler).\n */\nexport async function minimalBackupDocument(\n data: MinimalBackupData,\n workingDir: string,\n extension?: string,\n): Promise<string | undefined> {\n // The reactor's resultingState carries the document header alongside the\n // state scopes; lift its protocol versions into the backup header.\n const { header, ...state } = data.state as PHBaseState & {\n header?: PHDocumentHeader;\n };\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseMinimalSaveToFile(\n {\n ...data,\n state,\n protocolVersions: data.protocolVersions ?? header?.protocolVersions,\n },\n backupPath,\n extension ?? \"\",\n );\n\n logger.debug(`Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`Failed to backup document \"${data.name}\":`, error);\n return undefined;\n }\n}\n\nexport async function warnSubgraphTypeConflicts(\n workingDir: string,\n): Promise<void> {\n let warnings: string[];\n try {\n warnings = await lintSubgraphTypes(workingDir);\n } catch (error) {\n logger.warn(\n `Failed to check subgraph type names: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n for (const warning of warnings) logger.warn(`⚠️ ${warning}`);\n}\n\n/** Adds and installs what `features` need before their files are written:\n * the package loader reloads on those files, so their imports must resolve. */\nexport async function installFeatureDependencies(\n features: readonly Feature[],\n projectDir: string,\n waiting?: string,\n job?: CodegenJob,\n): Promise<void> {\n const install = { ran: false };\n try {\n await installForFeatures(features, projectDir, {\n log: (message) => logger.info(message),\n warn: (message) => logger.warn(`⚠️ ${message}`),\n waiting,\n onInstall: (packages, command) => {\n install.ran = true;\n job?.waitingForInstall(\n `Installing ${packages.join(\", \")} with \\`${command}\\``,\n );\n },\n });\n } catch (error) {\n logger.warn(\n `⚠️ Could not add the dependencies of ${features.join(\", \")}: ${(error as Error).message}`,\n );\n } finally {\n if (install.ran) job?.running();\n }\n}\n","import { generateApp } from \"@powerhousedao/codegen\";\nimport type {\n AppModuleGlobalState,\n AppModulePHState,\n} from \"@powerhousedao/vetra/document-models/app-module\";\nimport { kebabCase } from \"change-case\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for app documents\n */\nexport class AppGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/app\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): AppModuleGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as AppModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The app has no state\";\n else if (!state.name) reason = \"The app has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `App \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The app has no state\" };\n }\n\n logger.info(`🔄 Starting app generation for app: ${state.name}`);\n try {\n await generateApp(\n {\n ...this.config.PH_CONFIG,\n appName: state.name,\n appId: kebabCase(state.name),\n allowedDocumentTypes: state.allowedDocumentTypes ?? [],\n isDragAndDropEnabled: state.isDragAndDropEnabled,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during app generation for app ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ App generation completed successfully for app: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as AppModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { generateEditor } from \"@powerhousedao/codegen\";\nimport { kebabCase } from \"change-case\";\nimport type {\n DocumentEditorPHState,\n DocumentEditorState,\n} from \"../../../../document-models/document-editor/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for document editor documents\n */\nexport class DocumentEditorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-editor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentEditorState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentEditorPHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The editor has no state\";\n else if (!state.name) reason = \"The editor has no name\";\n else if (state.documentTypes.length === 0) {\n reason = `Editor \"${state.name}\" has no document types`;\n } else if (state.status !== \"CONFIRMED\") {\n reason = `Editor \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n if (!state) {\n return { skipped: \"The editor has no state\" };\n }\n\n logger.info(`🔄 Starting editor generation for: ${state.name}`);\n try {\n await generateEditor(\n {\n ...this.config.PH_CONFIG,\n editorName: state.name,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n editorId: kebabCase(state.name),\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during editor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Editor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as DocumentEditorPHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import {\n generateDocumentModel,\n validateDocumentModelState,\n} from \"@powerhousedao/codegen\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"../../../logger.js\";\nimport { BaseDocumentGen } from \"../../base-document-gen.js\";\nimport type { CodegenInput } from \"../../types.js\";\nimport { minimalBackupDocument, warnSubgraphTypeConflicts } from \"../utils.js\";\n\n/**\n * Generator for document model documents\n */\nexport class DocumentModelGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-model\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentModelGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentModelPHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n logger.debug(\n `>>> No global state found for document model: ${input.documentId}`,\n );\n return \"The document model has no global state\";\n }\n\n const validationResult = validateDocumentModelState(globalState);\n if (!validationResult.isValid) {\n const errorList = validationResult.errors\n .map((error) => ` - ${error}`)\n .join(\"\\n\");\n logger.info(\n `⚠️ Skipped code generation for '${globalState.name || input.documentId}' due to validation errors:\\n${errorList}`,\n );\n return `The document model is not ready for code generation:\\n${errorList}`;\n }\n\n logger.info(\n `Document model ${globalState.name} is valid, proceeding with code generation`,\n );\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n throw new Error(\n `No global state found for document model: ${input.documentId}`,\n );\n }\n logger.debug(\n `🔄 Starting code generation for document model: ${globalState.name}`,\n );\n try {\n await generateDocumentModel(globalState, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during code generation for ${globalState.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Code generation completed successfully for: ${globalState.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n const fullState = input.state as DocumentModelPHState;\n const extension = globalState.extension?.replace(/^\\.+|\\.+$/g, \"\") || \"\";\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: globalState.name,\n },\n this.config.CURRENT_WORKING_DIR,\n extension,\n );\n }\n}\n","import { createOrUpdateManifest } from \"@powerhousedao/codegen/file-builders\";\nimport type {\n VetraPackageGlobalState,\n VetraPackagePHState,\n} from \"../../../../document-models/vetra-package/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for package documents\n */\nexport class PackageGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/package\";\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n if (!input.state) {\n logger.debug(`>>> No state found for package: ${input.documentId}`);\n return \"The package has no state\";\n }\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const fullState = input.state as VetraPackagePHState;\n const state = fullState.global as VetraPackageGlobalState;\n\n await createOrUpdateManifest(\n {\n name: state.name ?? \"\",\n category: state.category ?? \"\",\n description: state.description ?? \"\",\n publisher: {\n name: state.author?.name ?? \"\",\n url: state.author?.website ?? \"\",\n },\n },\n this.config.CURRENT_WORKING_DIR,\n );\n\n // Backup the document\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: \"vetra-package\",\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { type Feature, generateProcessor } from \"@powerhousedao/codegen\";\nimport {\n PROCESSOR_APPS,\n type ProcessorApp,\n type ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport type {\n ProcessorModulePHState,\n ProcessorModuleState,\n} from \"../../../../document-models/processor-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport { installFeatureDependencies, minimalBackupDocument } from \"./utils.js\";\n\nconst PROCESSOR_TYPES = {\n analytics: \"analytics\",\n relational: \"relationalDb\",\n} as const;\n\n/**\n * Generator for processor documents\n */\nexport class ProcessorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/processor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): ProcessorModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as ProcessorModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const reason = invalidReason(this.extractGlobalState(input));\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The processor has no state\" };\n }\n const processorType =\n PROCESSOR_TYPES[state.type as keyof typeof PROCESSOR_TYPES];\n const processorApps = state.processorApps as ProcessorApps;\n logger.info(`🔄 Starting processor generation for: ${state.name}`);\n try {\n const features: Feature[] =\n processorType === \"analytics\"\n ? [\"analyticsProcessor\"]\n : [\"relationalDbProcessor\"];\n await installFeatureDependencies(\n features,\n this.config.CURRENT_WORKING_DIR,\n `processor \"${state.name}\"`,\n job,\n );\n\n await generateProcessor(\n {\n processorName: state.name,\n processorType,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n processorApps,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during processor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Processor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as ProcessorModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n\nfunction invalidReason(\n state: ProcessorModuleState | undefined,\n): string | undefined {\n if (!state) return \"The processor has no state\";\n if (!state.name) return \"The processor has no name\";\n const processor = `Processor \"${state.name}\"`;\n if (!state.type) return `${processor} has no type`;\n if (!(state.type in PROCESSOR_TYPES)) {\n return `${processor} has the unsupported type \"${state.type}\"; use ${Object.keys(PROCESSOR_TYPES).join(\" or \")}`;\n }\n if (state.documentTypes.length === 0) {\n return `${processor} has no document types`;\n }\n if (state.processorApps.length === 0) {\n return `${processor} has no processor apps`;\n }\n if (!isProcessorApps(state.processorApps)) {\n return `${processor} has unsupported processor apps (${state.processorApps.join(\", \")}); use ${PROCESSOR_APPS.join(\", \")}, each once`;\n }\n if (state.status !== \"CONFIRMED\") {\n return `${processor} is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n return undefined;\n}\n\nfunction isProcessorApps(input: readonly string[]): input is ProcessorApps {\n if (input.length === 0) return false;\n if (new Set(input).size !== input.length) {\n return false;\n }\n if (!input.every((i) => PROCESSOR_APPS.includes(i as ProcessorApp)))\n return false;\n\n return true;\n}\n","import { generateSubgraph } from \"@powerhousedao/codegen\";\nimport { findSubgraphNameConflict } from \"../../../../codegen/subgraph-type-lint.js\";\nimport type {\n SubgraphModulePHState,\n SubgraphModuleState,\n} from \"../../../../document-models/subgraph-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport {\n installFeatureDependencies,\n minimalBackupDocument,\n warnSubgraphTypeConflicts,\n} from \"./utils.js\";\n\n/**\n * Generator for subgraph documents\n */\nexport class SubgraphGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/subgraph\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): SubgraphModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as SubgraphModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The subgraph has no state\";\n else if (!state.name) reason = \"The subgraph has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `Subgraph \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The subgraph has no state\" };\n }\n\n logger.info(`🔄 Starting subgraph generation for: ${state.name}`);\n try {\n const conflict = await findSubgraphNameConflict(\n this.config.CURRENT_WORKING_DIR,\n state.name,\n );\n if (conflict) {\n logger.error(`❌ Skipping subgraph generation: ${conflict}`);\n return { skipped: conflict };\n }\n await installFeatureDependencies(\n [\"subgraph\"],\n this.config.CURRENT_WORKING_DIR,\n `subgraph \"${state.name}\"`,\n job,\n );\n await generateSubgraph(state.name, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during subgraph generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Subgraph generation completed successfully for: ${state.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as SubgraphModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import type { CodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport { DocumentCodegenManager } from \"./document-codegen-manager.js\";\nimport {\n AppGenerator,\n DocumentEditorGenerator,\n DocumentModelGenerator,\n PackageGenerator,\n ProcessorGenerator,\n SubgraphGenerator,\n} from \"./generators/index.js\";\nimport type { Config } from \"./types.js\";\n\n/**\n * Factory class for creating and configuring DocumentCodegenManager instances\n * with all the standard generators pre-registered\n */\nexport class DocumentCodegenFactory {\n /**\n * Create a DocumentCodegenManager with all standard generators registered\n */\n static createManager(\n config: Config,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n // Register all the standard generators\n manager.registerGenerator(\n \"powerhouse/document-model\",\n DocumentModelGenerator,\n );\n manager.registerGenerator(\"powerhouse/package\", PackageGenerator);\n manager.registerGenerator(\"powerhouse/app\", AppGenerator);\n manager.registerGenerator(\n \"powerhouse/document-editor\",\n DocumentEditorGenerator,\n );\n manager.registerGenerator(\"powerhouse/subgraph\", SubgraphGenerator);\n manager.registerGenerator(\"powerhouse/processor\", ProcessorGenerator);\n\n return manager;\n }\n\n /**\n * Create a DocumentCodegenManager with only specific generators\n */\n static createManagerWithGenerators(\n config: Config,\n generators: Array<new (config: Config) => any>,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n for (const generatorClass of generators) {\n const generator = new generatorClass(config) as BaseDocumentGen;\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n manager.registerGenerator(documentType, generatorClass);\n }\n }\n\n return manager;\n }\n\n /**\n * Get all available generator classes\n */\n static getAvailableGenerators() {\n return {\n DocumentModelGenerator,\n PackageGenerator,\n AppGenerator,\n DocumentEditorGenerator,\n SubgraphGenerator,\n ProcessorGenerator,\n };\n }\n}\n","import type {\n IProcessor,\n IReactorClient,\n OperationWithContext,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PowerhouseConfig } from \"@powerhousedao/shared\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { Project } from \"ts-morph\";\nimport type { DocumentCodegenManager } from \"./document-handlers/document-codegen-manager.js\";\nimport { DocumentCodegenFactory } from \"./document-handlers/index.js\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport class CodegenProcessor implements IProcessor {\n private manager: DocumentCodegenManager;\n\n constructor(\n project: Project,\n config: PowerhouseConfig,\n cwd: string,\n private readonly driveId: string,\n private readonly client: IReactorClient,\n interactiveMode = false,\n ) {\n this.manager = DocumentCodegenFactory.createManager(\n {\n PH_CONFIG: config,\n CURRENT_WORKING_DIR: cwd,\n },\n project,\n interactiveMode,\n );\n this.manager.setScope((documentId) => this.isInDrive(documentId));\n\n if (interactiveMode) {\n logger.info(`CodegenProcessor initialized with interactive mode enabled`);\n } else {\n logger.debug(\n `CodegenProcessor initialized with interactive mode disabled`,\n );\n }\n }\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n logger.debug(\"CodegenProcessor.onOperations()\");\n\n // Only a document's final state in the batch is generated from.\n const latest = new Map<string, OperationWithContext>();\n for (const operation of operations) {\n latest.set(operation.context.documentId, operation);\n }\n\n for (const { context } of latest.values()) {\n const generator = this.manager.getGenerator(context.documentType);\n if (!generator) {\n logger.debug(\n `No generator found for document type: ${context.documentType}`,\n );\n continue;\n }\n\n const input: CodegenInput = {\n documentId: context.documentId,\n documentType: context.documentType,\n scope: context.scope,\n branch: context.branch,\n state: context.resultingState\n ? JSON.parse(context.resultingState)\n : undefined,\n };\n\n await this.manager.routeAndGenerate(input);\n }\n }\n\n async onDisconnect() {}\n\n // Utility methods for external configuration and monitoring\n public setInteractiveMode(enabled: boolean): void {\n this.manager.setInteractiveMode(enabled);\n }\n\n public isInteractive(): boolean {\n return this.manager.isInteractiveMode();\n }\n\n public isProcessingInteractive(): boolean {\n return this.manager.isProcessingInteractive();\n }\n\n /**\n * The reactor delivers every drive's operations, so membership is checked\n * here: a node of the drive (in any folder, and in drives older than\n * relationship edges), or a child edge from it (a document attached by\n * relationship alone).\n */\n private async isInDrive(documentId: string): Promise<boolean> {\n try {\n const drive = await this.client.get<DocumentDriveDocument>(this.driveId);\n if (drive.state.global.nodes.some((node) => node.id === documentId)) {\n return true;\n }\n } catch (error) {\n logger.debug(`Could not read the Vetra drive ${this.driveId}:`, error);\n }\n try {\n const parents = await this.client.getIncomingRelationshipEdges(\n documentId,\n \"child\",\n );\n return parents.results.some((edge) => edge.sourceId === this.driveId);\n } catch (error) {\n logger.debug(`Could not read the parents of ${documentId}:`, error);\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAsB,kBAAtB,MAAsC;CAMxB;CAHZ;CAEA,YACE,QACA,SACA;EAFU,KAAA,SAAA;EAGV,KAAK,UAAU;CACjB;CAQA,qBAAqB,cAA+B;EAClD,IAAI,OAAO,KAAK,2BAA2B,UACzC,OAAO,KAAK,2BAA2B;EAEzC,OAAO,KAAK,uBAAuB,SAAS,YAAY;CAC1D;CAEA,4BAAsC;EACpC,IAAI,OAAO,KAAK,2BAA2B,UACzC,OAAO,CAAC,KAAK,sBAAsB;EAErC,OAAO,CAAC,GAAG,KAAK,sBAAsB;CACxC;;CAGA,WAAW,QAA0C;EAEnD,MAAM,OADQ,OAAO,OACD,QAAQ;EAC5B,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO,KAAA;CAC1D;;CAGA,WAAW,QA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AAO,MAJe,KAAK,OAAO,6BAChC,YACA,OACF,EAAA,CACe,QAAQ,MAAM,SAAS,KAAK,aAAa,KAAK,OAAO;EACtE,SAAS,OAAO;GACd,OAAO,MAAM,iCAAiC,WAAW,IAAI,KAAK;GAClE,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"processor-CgDcxcaa.js","names":["installFeatureDependencies","installForFeatures","installFeatureDependencies","installFeatureDependencies"],"sources":["../processors/codegen/document-handlers/base-document-gen.ts","../processors/codegen/interactive-manager.ts","../processors/codegen/written-files.ts","../processors/codegen/document-handlers/document-codegen-manager.ts","../processors/codegen/document-handlers/generators/utils.ts","../processors/codegen/document-handlers/generators/app-generator.ts","../processors/codegen/document-handlers/generators/document-editor-generator.ts","../processors/codegen/document-handlers/generators/schema-first/document-model-generator.ts","../processors/codegen/document-handlers/generators/package-generator.ts","../processors/codegen/document-handlers/generators/processor-generator.ts","../processors/codegen/document-handlers/generators/subgraph-generator.ts","../processors/codegen/document-handlers/document-codegen-factory.ts","../processors/codegen/processor.ts"],"sourcesContent":["import type { Project } from \"ts-morph\";\nimport type {\n CodegenInput,\n CodegenJob,\n Config,\n GenerateResult,\n} from \"./types.js\";\n\n/** The base of the generators, one per document type or set of types. */\nexport abstract class BaseDocumentGen {\n /** The document type or types this generator handles. */\n abstract readonly supportedDocumentTypes: string | string[];\n project: Project;\n\n constructor(\n protected config: Config,\n project: Project,\n ) {\n this.project = project;\n }\n\n /** Generates code for the document; throws when generation fails. */\n abstract generate(\n strand: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult>;\n\n supportsDocumentType(documentType: string): boolean {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return this.supportedDocumentTypes === documentType;\n }\n return this.supportedDocumentTypes.includes(documentType);\n }\n\n getSupportedDocumentTypes(): string[] {\n if (typeof this.supportedDocumentTypes === \"string\") {\n return [this.supportedDocumentTypes];\n }\n return [...this.supportedDocumentTypes];\n }\n\n /** The module's name in the strand's state, for its codegen status. */\n moduleName(strand: CodegenInput): string | undefined {\n const state = strand.state as { global?: { name?: unknown } } | undefined;\n const name = state?.global?.name;\n return typeof name === \"string\" && name !== \"\" ? name : undefined;\n }\n\n /** Why this strand is not generated from; undefined when it is. */\n skipReason(strand: CodegenInput): string | undefined {\n if (!strand.documentId || !strand.documentType) {\n return \"The operation names no document\";\n }\n if (!this.supportsDocumentType(strand.documentType)) {\n return `No generator for document type ${strand.documentType}`;\n }\n return undefined;\n }\n\n shouldProcess(strand: CodegenInput): boolean {\n return this.skipReason(strand) === undefined;\n }\n}\n","import { createInterface } from \"node:readline\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport interface QueuedStrand {\n strand: CodegenInput;\n timestamp: number;\n}\n\n/**\n * InteractiveManager handles user interaction for code generation confirmation\n * Supports both individual strand processing and queue-based batch processing\n */\nexport class InteractiveManager {\n private isInteractiveMode: boolean;\n private processingConfirmation = false;\n private strandQueue = new Map<string, QueuedStrand>();\n\n constructor(interactiveMode = false) {\n this.isInteractiveMode = interactiveMode;\n }\n\n private getDocumentKey(documentType: string, documentId: string): string {\n return `${documentType}:${documentId}`;\n }\n\n /**\n * Add a strand to the queue, replacing any existing strand for the same document\n */\n public queueStrand(strand: CodegenInput): void {\n const documentKey = this.getDocumentKey(\n strand.documentType,\n strand.documentId,\n );\n\n this.strandQueue.set(documentKey, {\n strand,\n timestamp: Date.now(),\n });\n\n logger.debug(\n `>>> Queued strand for ${documentKey}, queue size: ${this.strandQueue.size}`,\n );\n }\n\n /**\n * Drop the queued strands the predicate matches\n */\n public discardWhere(predicate: (strand: CodegenInput) => boolean): void {\n for (const [key, queued] of this.strandQueue) {\n if (predicate(queued.strand)) this.strandQueue.delete(key);\n }\n }\n\n /**\n * Get all queued strands\n */\n public getQueuedStrands(): QueuedStrand[] {\n return Array.from(this.strandQueue.values());\n }\n\n /**\n * Clear and return all queued strands\n */\n public clearQueue(): QueuedStrand[] {\n const queuedStrands = Array.from(this.strandQueue.values());\n this.strandQueue.clear();\n return queuedStrands;\n }\n\n /**\n * Get the current queue size\n */\n public getQueueSize(): number {\n return this.strandQueue.size;\n }\n\n private async promptUserConfirmation(): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔄 Code generation ready to run.\");\n console.log(\"=\".repeat(50));\n\n process.stdout.write(\n \"Do you want to proceed with code generation? (y/n): \\n\\n\",\n );\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n console.log(\"\"); // Add blank line after user input\n resolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n });\n });\n }\n\n /**\n * Process generation with user confirmation (legacy single-strand method)\n * This method assumes interactive mode is already enabled (checked by caller)\n */\n public async processWithConfirmation<T>(\n documentType: string,\n generator: () => Promise<T>,\n ): Promise<T | null> {\n if (this.processingConfirmation) {\n logger.debug(\"Already processing confirmation, skipping\");\n return null;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Always prompt user since this method only called in interactive mode\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(`❌ Code generation cancelled by user for ${documentType}`);\n return null;\n }\n\n logger.info(`✅ User approved code generation for ${documentType}`);\n\n const result = await generator();\n return result;\n } catch (error) {\n logger.error(\n `❌ Error during interactive code generation for ${documentType}:`,\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n /**\n * Process all queued strands with a single user confirmation\n * This is the main method for queue-based interactive processing\n */\n public async processQueueWithConfirmation(\n processor: (strands: QueuedStrand[]) => Promise<void>,\n onCancel?: (strands: QueuedStrand[]) => void,\n ): Promise<void> {\n if (this.processingConfirmation) {\n logger.debug(\n \"Already processing confirmation, skipping queue processing\",\n );\n return;\n }\n\n // Check if there are any strands to process\n let queuedStrands = this.getQueuedStrands();\n if (queuedStrands.length === 0) {\n logger.debug(\"No strands in queue to process\");\n return;\n }\n\n this.processingConfirmation = true;\n\n try {\n // Prompt user for confirmation\n const shouldProceed = await this.promptUserConfirmation();\n\n if (!shouldProceed) {\n logger.info(\"❌ Code generation cancelled by user\");\n onCancel?.(this.clearQueue());\n return;\n }\n\n // Get and clear the final queue state right before processing\n // (in case new strands were added while waiting for user input)\n queuedStrands = this.clearQueue();\n if (queuedStrands.length === 0) {\n logger.info(\"ℹ️ No documents to process\");\n return;\n }\n\n logger.info(\n `✅ User approved code generation for ${queuedStrands.length} document(s)`,\n );\n\n // Process all queued strands\n await processor(queuedStrands);\n logger.info(\"✅ Code generation completed\");\n } catch (error) {\n logger.error(\n \"❌ Error during interactive queue processing: @error\",\n error,\n );\n throw error;\n } finally {\n this.processingConfirmation = false;\n }\n }\n\n public setInteractiveMode(enabled: boolean): void {\n this.isInteractiveMode = enabled;\n logger.debug(`Interactive mode set to: ${enabled}`);\n }\n\n public isInteractive(): boolean {\n return this.isInteractiveMode;\n }\n\n public isProcessing(): boolean {\n return this.processingConfirmation;\n }\n}\n","import type { Dirent } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nconst SKIPPED_DIRS = new Set([\"node_modules\", \"dist\", \"backup-documents\"]);\nconst MAX_FILES = 500;\n\n/** The project's files modified at or after `since`, relative and sorted. */\nexport async function filesWrittenSince(\n projectDir: string,\n since: number,\n): Promise<string[]> {\n const written: string[] = [];\n const visit = async (dir: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (written.length >= MAX_FILES) return;\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || SKIPPED_DIRS.has(entry.name)) {\n continue;\n }\n await visit(path);\n } else if (entry.isFile()) {\n try {\n if ((await stat(path)).mtimeMs >= since) {\n written.push(relative(projectDir, path).replaceAll(\"\\\\\", \"/\"));\n }\n } catch {\n // Removed while listing.\n }\n }\n }\n };\n await visit(projectDir);\n return written.sort();\n}\n","import { afterPendingInstalls, installsPending } from \"@powerhousedao/codegen\";\nimport {\n type CodegenState,\n type CodegenStatusRegistry,\n getCodegenStatusRegistry,\n} from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { QueuedStrand } from \"../interactive-manager.js\";\nimport { InteractiveManager } from \"../interactive-manager.js\";\nimport { logger } from \"../logger.js\";\nimport { filesWrittenSince } from \"../written-files.js\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, Config } from \"./types.js\";\n\nconst DEFAULT_DEBOUNCE_TIME = 1000; // wait 1 second between codegen calls\nconst MODULE_NOT_FOUND_CODES = new Set([\n \"ERR_MODULE_NOT_FOUND\",\n \"MODULE_NOT_FOUND\",\n \"ERR_PACKAGE_PATH_NOT_EXPORTED\",\n]);\nconst MODULE_NOT_FOUND_MESSAGE =\n /Cannot find (module|package)|Failed to resolve (import|entry)|Failed to load url/;\n\n/** Whether a document belongs to what this manager generates from. */\nexport type DocumentScope = (documentId: string) => Promise<boolean>;\n\n/**\n * Manager class responsible for routing documents to the correct generator\n * and managing generator registration and instantiation\n */\nexport class DocumentCodegenManager {\n project: Project;\n private generators = new Map<string, BaseDocumentGen>();\n private debounceTimers = new Map<string, NodeJS.Timeout>();\n // One job at a time, so none runs while another job's install relinks node_modules.\n private jobs: Promise<void> = Promise.resolve();\n private queuedJobs = new Map<string, CodegenInput>();\n private runningJobs = 0;\n /** The wait before retrying a module-resolution failure when no install is queued. */\n retryDelayMs = 3000;\n private interactiveManager: InteractiveManager;\n private isInScope: DocumentScope = () => Promise.resolve(true);\n readonly status: CodegenStatusRegistry;\n\n constructor(\n private config: Config,\n project: Project,\n interactiveMode = false,\n status: CodegenStatusRegistry = getCodegenStatusRegistry(),\n ) {\n this.project = project;\n this.interactiveManager = new InteractiveManager(interactiveMode);\n this.status = status;\n }\n\n /**\n * Limit generation to the documents `isInScope` accepts, checked when the\n * debounce fires\n */\n setScope(isInScope: DocumentScope): void {\n this.isInScope = isInScope;\n }\n\n /**\n * Register a generator class for a specific document type\n */\n registerGenerator(\n documentType: string,\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n\n this.generators.set(\n documentType,\n new generatorClass(this.config, this.project),\n );\n logger.debug(`✅ Registered generator for document type: ${documentType}`);\n }\n\n /**\n * Register a generator class that supports multiple document types\n */\n registerMultiTypeGenerator(\n generatorClass: new (config: Config, project: Project) => BaseDocumentGen,\n ): void {\n const generator = new generatorClass(this.config, this.project);\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n if (this.generators.has(documentType)) {\n logger.warn(\n `⚠️ Generator for document type \"${documentType}\" is already registered. Overwriting.`,\n );\n }\n this.generators.set(documentType, generator);\n }\n\n logger.debug(\n `✅ Registered multi-type generator for document types: ${supportedTypes.join(\", \")}`,\n );\n }\n\n /**\n * Get a generator instance for the given document type\n * Public method to allow external access for validation\n */\n public getGenerator(documentType: string): BaseDocumentGen | undefined {\n return this.generators.get(documentType);\n }\n\n /**\n * Get all registered document types\n */\n getRegisteredDocumentTypes(): string[] {\n return Array.from(this.generators.keys());\n }\n\n /**\n * Check if a document type is supported\n */\n isDocumentTypeSupported(documentType: string): boolean {\n return this.generators.has(documentType);\n }\n\n /**\n * Route a document to the appropriate generator and handle the generation\n * Handles both interactive and non-interactive modes with queue-based processing\n */\n routeAndGenerate(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n\n if (!documentType) {\n logger.error(\"❌ Document type is missing from strand state\");\n throw new Error(\"Document type is missing from strand state\");\n }\n\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n logger.warn(\n `ℹ️ Supported document types: ${this.getRegisteredDocumentTypes().join(\", \")}`,\n );\n throw new Error(`Unsupported document type: ${documentType}`);\n }\n\n // Scope and validation are checked when the debounce fires, on the\n // document's final state.\n this.status.set({\n documentId: strand.documentId,\n documentType,\n state: \"queued\",\n message: this.interactiveManager.isInteractive()\n ? \"Waiting for confirmation in the terminal running Vetra\"\n : \"Waiting for the document's changes to settle\",\n });\n // Different flow for interactive vs non-interactive mode\n if (this.interactiveManager.isInteractive()) {\n // Interactive mode: queue strands and use debounce timer to trigger batch processing\n logger.debug(\n `>>> Queueing strand for interactive processing: ${documentType}:${strand.documentId}`,\n );\n\n // Add strand to queue (will replace any existing strand for same document)\n this.interactiveManager.queueStrand(strand);\n\n // Clear any existing debounce timer for interactive processing\n const existingTimer = this.debounceTimers.get(\"interactive\");\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up debounce timer for batch interactive processing\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n const rejected = new Set<CodegenInput>();\n for (const { strand } of this.interactiveManager.getQueuedStrands()) {\n if (!(await this.accepts(strand))) rejected.add(strand);\n }\n this.interactiveManager.discardWhere((queued) =>\n rejected.has(queued),\n );\n await this.interactiveManager.processQueueWithConfirmation(\n async (queuedStrands: QueuedStrand[]) => {\n await this.processQueuedStrands(queuedStrands);\n },\n (cancelled) => {\n for (const { strand } of cancelled) {\n this.setStatus(strand, \"skipped\", \"Cancelled in the terminal\");\n }\n },\n );\n } catch (error) {\n logger.error(\n \"❌ Error during interactive batch processing: @error\",\n error,\n );\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(\"interactive\");\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference using 'interactive' key\n this.debounceTimers.set(\"interactive\", debounceTimer);\n } else {\n // Non-interactive mode: use debouncing per document instance\n // Create unique key for this specific document instance\n const timerKey = `${documentType}:${strand.documentId}`;\n\n // Clear any existing debounce timer for this document instance\n const existingTimer = this.debounceTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Set up new debounced generation (no interactive confirmation)\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n const debounceTimer = setTimeout(async () => {\n try {\n if (!(await this.accepts(strand))) return;\n logger.debug(\n `🔄 Routing document type \"${documentType}\" to generator (debounced)`,\n );\n await this.enqueueJob(strand);\n } finally {\n // Clean up the timer reference\n this.debounceTimers.delete(timerKey);\n }\n }, DEFAULT_DEBOUNCE_TIME);\n\n // Store the timer reference\n this.debounceTimers.set(timerKey, debounceTimer);\n }\n return Promise.resolve();\n }\n\n /** In scope first, so documents out of scope are never validated or logged. */\n private async accepts(strand: CodegenInput): Promise<boolean> {\n const generator = this.getGenerator(strand.documentType);\n if (!generator) return false;\n if (!(await this.isInScope(strand.documentId))) {\n logger.debug(\n `Document ${strand.documentId} is not in the Vetra drive, skipping codegen`,\n );\n this.status.delete(strand.documentId);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n const reason = generator.skipReason(strand);\n if (reason !== undefined) {\n this.setStatus(strand, \"skipped\", reason);\n this.queuedJobs.delete(strand.documentId);\n return false;\n }\n return true;\n }\n\n /** Queues a job; one already queued for the document runs the latest strand. */\n private enqueueJob(strand: CodegenInput): Promise<void> {\n const { documentId } = strand;\n const alreadyQueued = this.queuedJobs.has(documentId);\n this.queuedJobs.set(documentId, strand);\n if (this.runningJobs > 0) {\n this.setStatus(\n strand,\n \"queued\",\n \"Waiting for codegen of other documents to finish\",\n );\n }\n if (alreadyQueued) return this.jobs;\n this.jobs = this.jobs.then(async () => {\n const latest = this.queuedJobs.get(documentId);\n this.queuedJobs.delete(documentId);\n const generator = latest && this.getGenerator(latest.documentType);\n if (!latest || !generator) return;\n this.runningJobs++;\n try {\n await this.runJob(latest, generator);\n } finally {\n this.runningJobs--;\n }\n });\n return this.jobs;\n }\n\n /** Runs a job after pending installs, once more after a module-resolution failure. */\n private async runJob(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<void> {\n await this.afterInstalls(\n strand,\n \"Waiting for a dependency install to finish\",\n );\n const error = await this.attempt(strand, generator);\n if (error === undefined) return;\n if (!isModuleResolutionError(error)) {\n this.setStatus(strand, \"failed\", errorMessage(error));\n return;\n }\n logger.warn(\n `Codegen for ${strand.documentType} ${strand.documentId} could not resolve a module; retrying once installs finish: ${errorMessage(error)}`,\n );\n const waited = await this.afterInstalls(\n strand,\n `Retrying once dependency installs finish, after: ${errorMessage(error)}`,\n );\n if (!waited) {\n await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs));\n }\n const retryError = await this.attempt(strand, generator);\n if (retryError !== undefined) {\n this.setStatus(\n strand,\n \"failed\",\n `${errorMessage(retryError)} (also after a retry; if an install is running, run it to the end, then change the document again)`,\n );\n }\n }\n\n /** Waits for queued installs, saying so; resolves to whether any was queued. */\n private async afterInstalls(\n strand: CodegenInput,\n message: string,\n ): Promise<boolean> {\n if (!installsPending()) return false;\n this.setStatus(strand, \"waiting-for-install\", message);\n await afterPendingInstalls();\n return true;\n }\n\n /** Generates once; records done or skipped, or resolves to the error. */\n private async attempt(\n strand: CodegenInput,\n generator: BaseDocumentGen,\n ): Promise<unknown> {\n const startedAt = Date.now();\n const job: CodegenJob = {\n waitingForInstall: (message) =>\n this.setStatus(strand, \"waiting-for-install\", message),\n running: () => this.setStatus(strand, \"running\"),\n };\n job.running();\n try {\n const result = await generator.generate(strand, job);\n if (result) {\n this.setStatus(strand, \"skipped\", result.skipped);\n return;\n }\n const files = await filesWrittenSince(\n this.config.CURRENT_WORKING_DIR,\n startedAt,\n );\n this.setStatus(strand, \"done\", undefined, files);\n logger.debug(\n `✅ Successfully generated code for document type: ${strand.documentType}`,\n );\n return undefined;\n } catch (error) {\n logger.error(\n `❌ Error generating code for document type \"${strand.documentType}\":`,\n error,\n );\n return error ?? new Error(\"Codegen failed\");\n }\n }\n\n private setStatus(\n strand: CodegenInput,\n state: CodegenState,\n message?: string,\n files?: string[],\n ): void {\n this.status.set({\n documentId: strand.documentId,\n documentType: strand.documentType,\n name: this.getGenerator(strand.documentType)?.moduleName(strand),\n state,\n message,\n files,\n });\n }\n\n /**\n * Process multiple strands in priority order (document-model types first)\n */\n private async processQueuedStrands(\n queuedStrands: QueuedStrand[],\n ): Promise<void> {\n logger.debug(`🔄 Processing ${queuedStrands.length} queued strand(s)`);\n\n // Sort by priority (document-model first to ensure dependencies exist)\n const documentModelStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType === \"powerhouse/document-model\",\n );\n const otherStrands = queuedStrands.filter(\n (qs: QueuedStrand) =>\n qs.strand.documentType !== \"powerhouse/document-model\",\n );\n\n // Process document models first\n for (const queuedStrand of documentModelStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n // Then process other document types\n for (const queuedStrand of otherStrands) {\n await this.processStrand(queuedStrand.strand);\n }\n\n logger.debug(\n `✅ Successfully processed all ${queuedStrands.length} queued strand(s)`,\n );\n }\n\n /**\n * Process a single strand (used internally by processQueuedStrands)\n */\n private async processStrand(strand: CodegenInput): Promise<void> {\n const documentType = strand.documentType;\n const generator = this.getGenerator(documentType);\n\n if (!generator) {\n logger.warn(`⚠️ No generator found for document type: ${documentType}`);\n return;\n }\n\n logger.debug(`🔄 Generating code for document type: ${documentType}`);\n await this.enqueueJob(strand);\n }\n\n /**\n * Clear all registered generators\n */\n clearGenerators(): void {\n this.generators.clear();\n logger.debug(\"🧹 Cleared all registered generators\");\n }\n\n /**\n * Get statistics about registered generators\n */\n getStats(): { totalGenerators: number; supportedTypes: string[] } {\n return {\n totalGenerators: this.generators.size,\n supportedTypes: this.getRegisteredDocumentTypes(),\n };\n }\n\n /**\n * Set interactive mode for code generation\n */\n setInteractiveMode(enabled: boolean): void {\n this.interactiveManager.setInteractiveMode(enabled);\n }\n\n /**\n * Check if interactive mode is enabled\n */\n isInteractiveMode(): boolean {\n return this.interactiveManager.isInteractive();\n }\n\n /**\n * Check if the manager is currently processing an interactive confirmation\n */\n isProcessingInteractive(): boolean {\n return this.interactiveManager.isProcessing();\n }\n}\n\nfunction isModuleResolutionError(error: unknown): boolean {\n for (let cause = error; cause instanceof Error; cause = cause.cause) {\n const code = (cause as NodeJS.ErrnoException).code;\n if (code && MODULE_NOT_FOUND_CODES.has(code)) return true;\n if (MODULE_NOT_FOUND_MESSAGE.test(cause.message)) return true;\n }\n return false;\n}\n\nfunction errorMessage(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = error.cause instanceof Error ? `: ${error.cause.message}` : \"\";\n return `${error.message}${cause}`;\n}\n","import {\n type Feature,\n installFeatureDependencies as installForFeatures,\n} from \"@powerhousedao/codegen\";\nimport type {\n MinimalBackupData,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { baseMinimalSaveToFile, baseSaveToFile } from \"document-model/node\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { lintSubgraphTypes } from \"../../../../codegen/subgraph-type-lint.js\";\nimport { logger } from \"../../logger.js\";\nimport type { CodegenJob } from \"../types.js\";\n\nconst BACKUP_FOLDER = \"backup-documents\";\n\n/**\n * Exports a document to the backup directory.\n * Creates the backup directory if it doesn't exist.\n *\n * @param document - The document to backup\n * @param workingDir - Current working directory\n * @param extension - File extension for the document type (without dot)\n * @param name - Name of the document to use for the backup file (optional)\n * @returns Promise resolving to the backup file path, or undefined if backup failed\n */\nexport async function backupDocument(\n document: PHDocument,\n workingDir: string,\n extension: string = \"\",\n name?: string,\n): Promise<string | undefined> {\n const docName = name ?? document.header.name;\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseSaveToFile(\n document,\n backupPath,\n extension,\n docName,\n );\n\n logger.debug(`📁 Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`⚠️ Failed to backup document \"${docName}\":`, error);\n return undefined;\n }\n}\n\n/**\n * Creates a minimal backup of a document from strand data.\n * Used when the full document is not available (e.g., in onOperations handler).\n */\nexport async function minimalBackupDocument(\n data: MinimalBackupData,\n workingDir: string,\n extension?: string,\n): Promise<string | undefined> {\n // The reactor's resultingState carries the document header alongside the\n // state scopes; lift its protocol versions into the backup header.\n const { header, ...state } = data.state as PHBaseState & {\n header?: PHDocumentHeader;\n };\n\n try {\n const backupPath = join(workingDir, BACKUP_FOLDER);\n await mkdir(backupPath, { recursive: true });\n\n const filePath = await baseMinimalSaveToFile(\n {\n ...data,\n state,\n protocolVersions: data.protocolVersions ?? header?.protocolVersions,\n },\n backupPath,\n extension ?? \"\",\n );\n\n logger.debug(`Document backed up to: ${filePath}`);\n return filePath;\n } catch (error) {\n logger.warn(`Failed to backup document \"${data.name}\":`, error);\n return undefined;\n }\n}\n\nexport async function warnSubgraphTypeConflicts(\n workingDir: string,\n): Promise<void> {\n let warnings: string[];\n try {\n warnings = await lintSubgraphTypes(workingDir);\n } catch (error) {\n logger.warn(\n `Failed to check subgraph type names: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n for (const warning of warnings) logger.warn(`⚠️ ${warning}`);\n}\n\n/** Adds and installs what `features` need before their files are written:\n * the package loader reloads on those files, so their imports must resolve. */\nexport async function installFeatureDependencies(\n features: readonly Feature[],\n projectDir: string,\n waiting?: string,\n job?: CodegenJob,\n): Promise<void> {\n const install = { ran: false };\n try {\n await installForFeatures(features, projectDir, {\n log: (message) => logger.info(message),\n warn: (message) => logger.warn(`⚠️ ${message}`),\n waiting,\n onInstall: (packages, command) => {\n install.ran = true;\n job?.waitingForInstall(\n `Installing ${packages.join(\", \")} with \\`${command}\\``,\n );\n },\n });\n } catch (error) {\n logger.warn(\n `⚠️ Could not add the dependencies of ${features.join(\", \")}: ${(error as Error).message}`,\n );\n } finally {\n if (install.ran) job?.running();\n }\n}\n","import { generateApp } from \"@powerhousedao/codegen\";\nimport type {\n AppModuleGlobalState,\n AppModulePHState,\n} from \"@powerhousedao/vetra/document-models/app-module\";\nimport { kebabCase } from \"change-case\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for app documents\n */\nexport class AppGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/app\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): AppModuleGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as AppModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The app has no state\";\n else if (!state.name) reason = \"The app has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `App \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The app has no state\" };\n }\n\n logger.info(`🔄 Starting app generation for app: ${state.name}`);\n try {\n await generateApp(\n {\n ...this.config.PH_CONFIG,\n appName: state.name,\n appId: kebabCase(state.name),\n allowedDocumentTypes: state.allowedDocumentTypes ?? [],\n isDragAndDropEnabled: state.isDragAndDropEnabled,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during app generation for app ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ App generation completed successfully for app: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as AppModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { generateEditor } from \"@powerhousedao/codegen\";\nimport { kebabCase } from \"change-case\";\nimport type {\n DocumentEditorPHState,\n DocumentEditorState,\n} from \"../../../../document-models/document-editor/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, GenerateResult } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for document editor documents\n */\nexport class DocumentEditorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-editor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentEditorState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentEditorPHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The editor has no state\";\n else if (!state.name) reason = \"The editor has no name\";\n else if (state.documentTypes.length === 0) {\n reason = `Editor \"${state.name}\" has no document types`;\n } else if (state.status !== \"CONFIRMED\") {\n reason = `Editor \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(input: CodegenInput): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n if (!state) {\n return { skipped: \"The editor has no state\" };\n }\n\n logger.info(`🔄 Starting editor generation for: ${state.name}`);\n try {\n await generateEditor(\n {\n ...this.config.PH_CONFIG,\n editorName: state.name,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n editorId: kebabCase(state.name),\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during editor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Editor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as DocumentEditorPHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import {\n generateDocumentModel,\n validateDocumentModelState,\n} from \"@powerhousedao/codegen\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"../../../logger.js\";\nimport { BaseDocumentGen } from \"../../base-document-gen.js\";\nimport type { CodegenInput } from \"../../types.js\";\nimport { minimalBackupDocument, warnSubgraphTypeConflicts } from \"../utils.js\";\n\n/**\n * Generator for document model documents\n */\nexport class DocumentModelGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/document-model\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): DocumentModelGlobalState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as DocumentModelPHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n logger.debug(\n `>>> No global state found for document model: ${input.documentId}`,\n );\n return \"The document model has no global state\";\n }\n\n const validationResult = validateDocumentModelState(globalState);\n if (!validationResult.isValid) {\n const errorList = validationResult.errors\n .map((error) => ` - ${error}`)\n .join(\"\\n\");\n logger.info(\n `⚠️ Skipped code generation for '${globalState.name || input.documentId}' due to validation errors:\\n${errorList}`,\n );\n return `The document model is not ready for code generation:\\n${errorList}`;\n }\n\n logger.info(\n `Document model ${globalState.name} is valid, proceeding with code generation`,\n );\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const globalState = this.extractGlobalState(input);\n if (!globalState) {\n throw new Error(\n `No global state found for document model: ${input.documentId}`,\n );\n }\n logger.debug(\n `🔄 Starting code generation for document model: ${globalState.name}`,\n );\n try {\n await generateDocumentModel(globalState, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during code generation for ${globalState.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Code generation completed successfully for: ${globalState.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n const fullState = input.state as DocumentModelPHState;\n const extension = globalState.extension?.replace(/^\\.+|\\.+$/g, \"\") || \"\";\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: globalState.name,\n },\n this.config.CURRENT_WORKING_DIR,\n extension,\n );\n }\n}\n","import { createOrUpdateManifest } from \"@powerhousedao/codegen/file-builders\";\nimport type {\n VetraPackageGlobalState,\n VetraPackagePHState,\n} from \"../../../../document-models/vetra-package/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput } from \"../types.js\";\nimport { minimalBackupDocument } from \"./utils.js\";\n\n/**\n * Generator for package documents\n */\nexport class PackageGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/package\";\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n if (!input.state) {\n logger.debug(`>>> No state found for package: ${input.documentId}`);\n return \"The package has no state\";\n }\n return undefined;\n }\n\n async generate(input: CodegenInput): Promise<void> {\n const fullState = input.state as VetraPackagePHState;\n const state = fullState.global as VetraPackageGlobalState;\n\n await createOrUpdateManifest(\n {\n name: state.name ?? \"\",\n category: state.category ?? \"\",\n description: state.description ?? \"\",\n publisher: {\n name: state.author?.name ?? \"\",\n url: state.author?.website ?? \"\",\n },\n },\n this.config.CURRENT_WORKING_DIR,\n );\n\n // Backup the document\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: fullState,\n name: \"vetra-package\",\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import { type Feature, generateProcessor } from \"@powerhousedao/codegen\";\nimport {\n PROCESSOR_APPS,\n type ProcessorApp,\n type ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport type {\n ProcessorModulePHState,\n ProcessorModuleState,\n} from \"../../../../document-models/processor-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport { installFeatureDependencies, minimalBackupDocument } from \"./utils.js\";\n\nconst PROCESSOR_TYPES = {\n analytics: \"analytics\",\n relational: \"relationalDb\",\n} as const;\n\n/**\n * Generator for processor documents\n */\nexport class ProcessorGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/processor\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): ProcessorModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as ProcessorModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const reason = invalidReason(this.extractGlobalState(input));\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The processor has no state\" };\n }\n const processorType =\n PROCESSOR_TYPES[state.type as keyof typeof PROCESSOR_TYPES];\n const processorApps = state.processorApps as ProcessorApps;\n logger.info(`🔄 Starting processor generation for: ${state.name}`);\n try {\n const features: Feature[] =\n processorType === \"analytics\"\n ? [\"analyticsProcessor\"]\n : [\"relationalDbProcessor\"];\n await installFeatureDependencies(\n features,\n this.config.CURRENT_WORKING_DIR,\n `processor \"${state.name}\"`,\n job,\n );\n\n await generateProcessor(\n {\n processorName: state.name,\n processorType,\n documentTypes: state.documentTypes.map((dt) => dt.documentType),\n processorApps,\n },\n this.project,\n );\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during processor generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n\n logger.info(\n `✅ Processor generation completed successfully for: ${state.name}`,\n );\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as ProcessorModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n\nfunction invalidReason(\n state: ProcessorModuleState | undefined,\n): string | undefined {\n if (!state) return \"The processor has no state\";\n if (!state.name) return \"The processor has no name\";\n const processor = `Processor \"${state.name}\"`;\n if (!state.type) return `${processor} has no type`;\n if (!(state.type in PROCESSOR_TYPES)) {\n return `${processor} has the unsupported type \"${state.type}\"; use ${Object.keys(PROCESSOR_TYPES).join(\" or \")}`;\n }\n if (state.documentTypes.length === 0) {\n return `${processor} has no document types`;\n }\n if (state.processorApps.length === 0) {\n return `${processor} has no processor apps`;\n }\n if (!isProcessorApps(state.processorApps)) {\n return `${processor} has unsupported processor apps (${state.processorApps.join(\", \")}); use ${PROCESSOR_APPS.join(\", \")}, each once`;\n }\n if (state.status !== \"CONFIRMED\") {\n return `${processor} is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n return undefined;\n}\n\nfunction isProcessorApps(input: readonly string[]): input is ProcessorApps {\n if (input.length === 0) return false;\n if (new Set(input).size !== input.length) {\n return false;\n }\n if (!input.every((i) => PROCESSOR_APPS.includes(i as ProcessorApp)))\n return false;\n\n return true;\n}\n","import { generateSubgraph } from \"@powerhousedao/codegen\";\nimport { findSubgraphNameConflict } from \"../../../../codegen/subgraph-type-lint.js\";\nimport type {\n SubgraphModulePHState,\n SubgraphModuleState,\n} from \"../../../../document-models/subgraph-module/index.js\";\nimport { logger } from \"../../logger.js\";\nimport { BaseDocumentGen } from \"../base-document-gen.js\";\nimport type { CodegenInput, CodegenJob, GenerateResult } from \"../types.js\";\nimport {\n installFeatureDependencies,\n minimalBackupDocument,\n warnSubgraphTypeConflicts,\n} from \"./utils.js\";\n\n/**\n * Generator for subgraph documents\n */\nexport class SubgraphGenerator extends BaseDocumentGen {\n readonly supportedDocumentTypes = \"powerhouse/subgraph\";\n\n private extractGlobalState(\n input: CodegenInput,\n ): SubgraphModuleState | undefined {\n if (!input.state) {\n return undefined;\n }\n const fullState = input.state as SubgraphModulePHState;\n return fullState.global;\n }\n\n override skipReason(input: CodegenInput): string | undefined {\n const base = super.skipReason(input);\n if (base) return base;\n\n const state = this.extractGlobalState(input);\n let reason: string | undefined;\n if (!state) reason = \"The subgraph has no state\";\n else if (!state.name) reason = \"The subgraph has no name\";\n else if (state.status !== \"CONFIRMED\") {\n reason = `Subgraph \"${state.name}\" is not confirmed (status: ${state.status}); codegen runs once it is CONFIRMED`;\n }\n if (reason) logger.debug(reason);\n return reason;\n }\n\n async generate(\n input: CodegenInput,\n job?: CodegenJob,\n ): Promise<GenerateResult> {\n const state = this.extractGlobalState(input);\n const reason = this.skipReason(input);\n if (!state || reason) {\n return { skipped: reason ?? \"The subgraph has no state\" };\n }\n\n logger.info(`🔄 Starting subgraph generation for: ${state.name}`);\n try {\n const conflict = await findSubgraphNameConflict(\n this.config.CURRENT_WORKING_DIR,\n state.name,\n );\n if (conflict) {\n logger.error(`❌ Skipping subgraph generation: ${conflict}`);\n return { skipped: conflict };\n }\n await installFeatureDependencies(\n [\"subgraph\"],\n this.config.CURRENT_WORKING_DIR,\n `subgraph \"${state.name}\"`,\n job,\n );\n await generateSubgraph(state.name, this.project);\n await this.project.save();\n } catch (error) {\n logger.error(\n `❌ Error during subgraph generation for ${state.name}:`,\n error,\n );\n throw error;\n }\n logger.info(\n `✅ Subgraph generation completed successfully for: ${state.name}`,\n );\n await warnSubgraphTypeConflicts(this.config.CURRENT_WORKING_DIR);\n\n await minimalBackupDocument(\n {\n documentId: input.documentId,\n documentType: input.documentType,\n branch: input.branch,\n state: input.state as SubgraphModulePHState,\n name: state.name,\n },\n this.config.CURRENT_WORKING_DIR,\n );\n }\n}\n","import type { CodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport type { Project } from \"ts-morph\";\nimport type { BaseDocumentGen } from \"./base-document-gen.js\";\nimport { DocumentCodegenManager } from \"./document-codegen-manager.js\";\nimport {\n AppGenerator,\n DocumentEditorGenerator,\n DocumentModelGenerator,\n PackageGenerator,\n ProcessorGenerator,\n SubgraphGenerator,\n} from \"./generators/index.js\";\nimport type { Config } from \"./types.js\";\n\n/**\n * Factory class for creating and configuring DocumentCodegenManager instances\n * with all the standard generators pre-registered\n */\nexport class DocumentCodegenFactory {\n /**\n * Create a DocumentCodegenManager with all standard generators registered\n */\n static createManager(\n config: Config,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n // Register all the standard generators\n manager.registerGenerator(\n \"powerhouse/document-model\",\n DocumentModelGenerator,\n );\n manager.registerGenerator(\"powerhouse/package\", PackageGenerator);\n manager.registerGenerator(\"powerhouse/app\", AppGenerator);\n manager.registerGenerator(\n \"powerhouse/document-editor\",\n DocumentEditorGenerator,\n );\n manager.registerGenerator(\"powerhouse/subgraph\", SubgraphGenerator);\n manager.registerGenerator(\"powerhouse/processor\", ProcessorGenerator);\n\n return manager;\n }\n\n /**\n * Create a DocumentCodegenManager with only specific generators\n */\n static createManagerWithGenerators(\n config: Config,\n generators: Array<new (config: Config) => any>,\n project: Project,\n interactiveMode: boolean = false,\n status?: CodegenStatusRegistry,\n ): DocumentCodegenManager {\n const manager = new DocumentCodegenManager(\n config,\n project,\n interactiveMode,\n status,\n );\n\n for (const generatorClass of generators) {\n const generator = new generatorClass(config) as BaseDocumentGen;\n const supportedTypes = generator.getSupportedDocumentTypes();\n\n for (const documentType of supportedTypes) {\n manager.registerGenerator(documentType, generatorClass);\n }\n }\n\n return manager;\n }\n\n /**\n * Get all available generator classes\n */\n static getAvailableGenerators() {\n return {\n DocumentModelGenerator,\n PackageGenerator,\n AppGenerator,\n DocumentEditorGenerator,\n SubgraphGenerator,\n ProcessorGenerator,\n };\n }\n}\n","import type {\n IProcessor,\n IReactorClient,\n OperationWithContext,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PowerhouseConfig } from \"@powerhousedao/shared\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { Project } from \"ts-morph\";\nimport type { DocumentCodegenManager } from \"./document-handlers/document-codegen-manager.js\";\nimport { DocumentCodegenFactory } from \"./document-handlers/index.js\";\nimport type { CodegenInput } from \"./document-handlers/types.js\";\nimport { logger } from \"./logger.js\";\n\nexport class CodegenProcessor implements IProcessor {\n private manager: DocumentCodegenManager;\n\n constructor(\n project: Project,\n config: PowerhouseConfig,\n cwd: string,\n private readonly driveId: string,\n private readonly client: IReactorClient,\n interactiveMode = false,\n ) {\n this.manager = DocumentCodegenFactory.createManager(\n {\n PH_CONFIG: config,\n CURRENT_WORKING_DIR: cwd,\n },\n project,\n interactiveMode,\n );\n this.manager.setScope((documentId) => this.isInDrive(documentId));\n\n if (interactiveMode) {\n logger.info(`CodegenProcessor initialized with interactive mode enabled`);\n } else {\n logger.debug(\n `CodegenProcessor initialized with interactive mode disabled`,\n );\n }\n }\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n logger.debug(\"CodegenProcessor.onOperations()\");\n\n // Only a document's final state in the batch is generated from.\n const latest = new Map<string, OperationWithContext>();\n for (const operation of operations) {\n latest.set(operation.context.documentId, operation);\n }\n\n for (const { context } of latest.values()) {\n const generator = this.manager.getGenerator(context.documentType);\n if (!generator) {\n logger.debug(\n `No generator found for document type: ${context.documentType}`,\n );\n continue;\n }\n\n const input: CodegenInput = {\n documentId: context.documentId,\n documentType: context.documentType,\n scope: context.scope,\n branch: context.branch,\n state: context.resultingState\n ? JSON.parse(context.resultingState)\n : undefined,\n };\n\n await this.manager.routeAndGenerate(input);\n }\n }\n\n async onDisconnect() {}\n\n // Utility methods for external configuration and monitoring\n public setInteractiveMode(enabled: boolean): void {\n this.manager.setInteractiveMode(enabled);\n }\n\n public isInteractive(): boolean {\n return this.manager.isInteractiveMode();\n }\n\n public isProcessingInteractive(): boolean {\n return this.manager.isProcessingInteractive();\n }\n\n /**\n * The reactor delivers every drive's operations, so membership is checked\n * here: a node of the drive (in any folder, and in drives older than\n * relationship edges), or a child edge from it (a document attached by\n * relationship alone).\n */\n private async isInDrive(documentId: string): Promise<boolean> {\n try {\n const drive = await this.client.get<DocumentDriveDocument>(this.driveId);\n if (drive.state.global.nodes.some((node) => node.id === documentId)) {\n return true;\n }\n } catch (error) {\n logger.debug(`Could not read the Vetra drive ${this.driveId}:`, error);\n }\n try {\n const parents = await this.client.getIncomingRelationshipEdges(\n documentId,\n \"child\",\n );\n return parents.results.some((edge) => edge.sourceId === this.driveId);\n } catch (error) {\n logger.debug(`Could not read the parents of ${documentId}:`, error);\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAsB,kBAAtB,MAAsC;CAMxB;CAHZ;CAEA,YACE,QACA,SACA;EAFU,KAAA,SAAA;EAGV,KAAK,UAAU;CACjB;CAQA,qBAAqB,cAA+B;EAClD,IAAI,OAAO,KAAK,2BAA2B,UACzC,OAAO,KAAK,2BAA2B;EAEzC,OAAO,KAAK,uBAAuB,SAAS,YAAY;CAC1D;CAEA,4BAAsC;EACpC,IAAI,OAAO,KAAK,2BAA2B,UACzC,OAAO,CAAC,KAAK,sBAAsB;EAErC,OAAO,CAAC,GAAG,KAAK,sBAAsB;CACxC;;CAGA,WAAW,QAA0C;EAEnD,MAAM,OADQ,OAAO,OACD,QAAQ;EAC5B,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO,KAAA;CAC1D;;CAGA,WAAW,QAA0C;EACnD,IAAI,CAAC,OAAO,cAAc,CAAC,OAAO,cAChC,OAAO;EAET,IAAI,CAAC,KAAK,qBAAqB,OAAO,YAAY,GAChD,OAAO,kCAAkC,OAAO;CAGpD;CAEA,cAAc,QAA+B;EAC3C,OAAO,KAAK,WAAW,MAAM,MAAM,KAAA;CACrC;AACF;;;;;;;ACjDA,IAAa,qBAAb,MAAgC;CAC9B;CACA,yBAAiC;CACjC,8BAAsB,IAAI,IAA0B;CAEpD,YAAY,kBAAkB,OAAO;EACnC,KAAK,oBAAoB;CAC3B;CAEA,eAAuB,cAAsB,YAA4B;EACvE,OAAO,GAAG,aAAa,GAAG;CAC5B;;;;CAKA,YAAmB,QAA4B;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AAO,OAAO,GAAG;GAEzC,IAAI,CADc,KAAK,QAAQ,aAAa,QAAQ,YACvC,GAAG;IACd,OAAO,MACL,yCAAyC,QAAQ,cACnD;IACA;GACF;GAEA,MAAM,QAAsB;IAC1B,YAAY,QAAQ;IACpB,cAAc,QAAQ;IACtB,OAAO,QAAQ;IACf,QAAQ,QAAQ;IAChB,OAAO,QAAQ,iBACX,KAAK,MAAM,QAAQ,cAAc,IACjC,KAAA;GACN;GAEA,MAAM,KAAK,QAAQ,iBAAiB,KAAK;EAC3C;CACF;CAEA,MAAM,eAAe,CAAC;CAGtB,mBAA0B,SAAwB;EAChD,KAAK,QAAQ,mBAAmB,OAAO;CACzC;CAEA,gBAAgC;EAC9B,OAAO,KAAK,QAAQ,kBAAkB;CACxC;CAEA,0BAA0C;EACxC,OAAO,KAAK,QAAQ,wBAAwB;CAC9C;;;;;;;CAQA,MAAc,UAAU,YAAsC;EAC5D,IAAI;GAEF,KAAI,MADgB,KAAK,OAAO,IAA2B,KAAK,OAAO,EAAA,CAC7D,MAAM,OAAO,MAAM,MAAM,SAAS,KAAK,OAAO,UAAU,GAChE,OAAO;EAEX,SAAS,OAAO;GACd,OAAO,MAAM,kCAAkC,KAAK,QAAQ,IAAI,KAAK;EACvE;EACA,IAAI;GAKF,QAAO,MAJe,KAAK,OAAO,6BAChC,YACA,OACF,EAAA,CACe,QAAQ,MAAM,SAAS,KAAK,aAAa,KAAK,OAAO;EACtE,SAAS,OAAO;GACd,OAAO,MAAM,iCAAiC,WAAW,IAAI,KAAK;GAClE,OAAO;EACT;CACF;AACF"}
@@ -1,3 +1,3 @@
1
- import { t as codegenFactoryBuilder } from "../../factory-GIkoxPdL.js";
2
- import { t as CodegenProcessor } from "../../processor-Cb2shrDB.js";
1
+ import { t as codegenFactoryBuilder } from "../../factory-B9ent5Rs.js";
2
+ import { t as CodegenProcessor } from "../../processor-CgDcxcaa.js";
3
3
  export { CodegenProcessor, codegenFactoryBuilder };
@@ -1,6 +1,6 @@
1
1
  //#region processors/factory.ts
2
2
  const processorFactory = async (module) => {
3
- const { processorFactoryBuilders } = module.processorApp === "connect" ? await import("../connect-EqImHuZ2.js") : await import("../switchboard-DUSh_ScZ.js");
3
+ const { processorFactoryBuilders } = module.processorApp === "connect" ? await import("../connect-EqImHuZ2.js") : await import("../switchboard-D70bg3-8.js");
4
4
  const factories = await Promise.all(processorFactoryBuilders.map(async (buildFactory) => await buildFactory(module)));
5
5
  return async (driveHeader) => {
6
6
  const processors = [];
@@ -1,4 +1,4 @@
1
- import { loadDocumentModelInDir } from "@powerhousedao/codegen/utils";
1
+ import { loadDocumentModelInDir, subgraphDirStyle } from "@powerhousedao/codegen/utils";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { kebabCase } from "change-case";
4
4
  import { join } from "node:path";
@@ -7,6 +7,7 @@ import { Kind, parse } from "graphql";
7
7
  //#region codegen/subgraph-type-lint.ts
8
8
  const GQL_TEMPLATE = /\bgql\s*`([^`]*)`/g;
9
9
  const SUBGRAPH_NAME = /\bname\s*=\s*["'`]([^"'`]+)["'`]/;
10
+ const CODE_FIRST_NAME = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?subgraphName(?:\s*:\s*string)?\s*=\s*["'`]([^"'`$]+)["'`]/;
10
11
  const SUBGRAPH_EXPORT = /from\s+["']\.\/([^/"']+)\/index\.js["']/g;
11
12
  function directories(path) {
12
13
  try {
@@ -70,12 +71,33 @@ async function findSubgraphNameConflict(projectDir, name) {
70
71
  if (!holder || holder === "package") return void 0;
71
72
  return `Subgraph name "${subgraphName}" is taken by a ${holder} subgraph, so the server would refuse this one. Choose another name, such as "${subgraphName}-api".`;
72
73
  }
74
+ function codeFirstName(dir) {
75
+ const files = ["index.ts", ...readdirSync(dir, {
76
+ recursive: true,
77
+ encoding: "utf8"
78
+ }).filter((file) => file.endsWith(".ts") && file !== "index.ts").sort()];
79
+ for (const file of files) {
80
+ const name = CODE_FIRST_NAME.exec(read(join(dir, file)) ?? "")?.[1];
81
+ if (name !== void 0) return name;
82
+ }
83
+ }
73
84
  /** A warning per model or subgraph the server would refuse or leave out. */
74
85
  async function lintSubgraphTypes(projectDir) {
75
86
  const models = loadModels(projectDir);
76
87
  const subgraphsDir = join(projectDir, "subgraphs");
77
88
  const subgraphs = [];
78
89
  for (const dir of subgraphDirs(subgraphsDir)) {
90
+ if (subgraphDirStyle(subgraphsDir, dir) === "code-first") {
91
+ const name = codeFirstName(join(subgraphsDir, dir));
92
+ if (name !== void 0) subgraphs.push({
93
+ name,
94
+ typeDefs: {
95
+ kind: Kind.DOCUMENT,
96
+ definitions: []
97
+ }
98
+ });
99
+ continue;
100
+ }
79
101
  const typeDefs = readSchema(join(subgraphsDir, dir, "schema.ts"));
80
102
  if (!typeDefs) continue;
81
103
  const index = read(join(subgraphsDir, dir, "index.ts")) ?? "";
@@ -91,4 +113,4 @@ async function lintSubgraphTypes(projectDir) {
91
113
  //#endregion
92
114
  export { lintSubgraphTypes as n, findSubgraphNameConflict as t };
93
115
 
94
- //# sourceMappingURL=subgraph-type-lint-Dr8Wu0VB.js.map
116
+ //# sourceMappingURL=subgraph-type-lint-BZuO7F-G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subgraph-type-lint-BZuO7F-G.js","names":[],"sources":["../codegen/subgraph-type-lint.ts"],"sourcesContent":["import {\n loadDocumentModelInDir,\n subgraphDirStyle,\n} from \"@powerhousedao/codegen/utils\";\nimport {\n findPackageSubgraphConflicts,\n type PackageSubgraph,\n type PackageSubgraphConflicts,\n type RefusedDocumentModel,\n} from \"@powerhousedao/reactor-api/subgraph-types\";\nimport { kebabCase } from \"change-case\";\nimport { type DocumentNode, Kind, parse } from \"graphql\";\nimport { type Dirent, existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// Templates with substitutions are skipped: their SDL is only known at runtime.\nconst GQL_TEMPLATE = /\\bgql\\s*`([^`]*)`/g;\nconst SUBGRAPH_NAME = /\\bname\\s*=\\s*[\"'`]([^\"'`]+)[\"'`]/;\nconst CODE_FIRST_NAME =\n /\\bstatic\\s+(?:override\\s+)?(?:readonly\\s+)?subgraphName(?:\\s*:\\s*string)?\\s*=\\s*[\"'`]([^\"'`$]+)[\"'`]/;\nconst SUBGRAPH_EXPORT = /from\\s+[\"']\\.\\/([^/\"']+)\\/index\\.js[\"']/g;\n\nfunction directories(path: string): Dirent[] {\n try {\n return readdirSync(path, { withFileTypes: true }).filter((entry) =>\n entry.isDirectory(),\n );\n } catch {\n return [];\n }\n}\n\nfunction read(path: string): string | undefined {\n try {\n return readFileSync(path, \"utf-8\");\n } catch {\n return undefined;\n }\n}\n\nfunction readSchema(path: string): DocumentNode | undefined {\n const source = read(path);\n if (source === undefined) return undefined;\n const blocks = Array.from(source.matchAll(GQL_TEMPLATE), ([, sdl]) => sdl);\n if (blocks.length === 0 || blocks.some((sdl) => sdl.includes(\"${\"))) {\n return undefined;\n }\n try {\n return parse(blocks.join(\"\\n\"));\n } catch {\n // Invalid SDL fails where the subgraph loads, and is reported there.\n return undefined;\n }\n}\n\n/** Subgraph directories in the order `subgraphs/index.ts` registers them. */\nfunction subgraphDirs(subgraphsDir: string): string[] {\n const exported = Array.from(\n (read(join(subgraphsDir, \"index.ts\")) ?? \"\").matchAll(SUBGRAPH_EXPORT),\n ([, dir]) => dir,\n );\n const position = (dir: string) => {\n const index = exported.indexOf(dir);\n return index === -1 ? exported.length : index;\n };\n return directories(subgraphsDir)\n .map((entry) => entry.name)\n .sort((a, b) => position(a) - position(b));\n}\n\nfunction describeRefusal({\n name,\n reason,\n subgraphOnly,\n}: RefusedDocumentModel): string {\n const detail = reason.split(\"\\n\")[0].replace(/\\.$/, \"\");\n return subgraphOnly\n ? `The subgraph of document model \"${name}\" is refused by the server: ${detail}.`\n : `Document model \"${name}\" is refused by the server: ${detail}.`;\n}\n\nfunction describe(name: string, conflict: PackageSubgraphConflicts): string {\n if (conflict.nameHeldBy === \"package\") {\n return `Subgraph \"${name}\" is defined more than once, so the server serves only the last. Rename the others.`;\n }\n if (conflict.nameHeldBy) {\n return `Subgraph \"${name}\" has the name of a ${conflict.nameHeldBy} subgraph, so the server refuses it. Rename the subgraph.`;\n }\n const claims = conflict.claims\n .map(({ claim, owner }) => `${claim} (owned by \"${owner}\")`)\n .join(\", \");\n return `Subgraph \"${name}\" defines ${claims}, so the supergraph leaves it out. Rename them in its schema.ts.`;\n}\n\nfunction loadModels(projectDir: string) {\n return directories(join(projectDir, \"document-models\"))\n .map(loadDocumentModelInDir)\n .filter((model) => model !== undefined);\n}\n\n/** Why the server would refuse a new subgraph scaffolded as `name`, if it\n * would; an existing one is left to {@link lintSubgraphTypes}. */\nexport async function findSubgraphNameConflict(\n projectDir: string,\n name: string,\n): Promise<string | undefined> {\n const subgraphName = kebabCase(name);\n if (existsSync(join(projectDir, \"subgraphs\", subgraphName, \"index.ts\"))) {\n return undefined;\n }\n const { conflicts } = await findPackageSubgraphConflicts(\n [\n {\n name: subgraphName,\n typeDefs: { kind: Kind.DOCUMENT, definitions: [] },\n },\n ],\n loadModels(projectDir),\n );\n const holder = conflicts.get(subgraphName)?.nameHeldBy;\n if (!holder || holder === \"package\") return undefined;\n return `Subgraph name \"${subgraphName}\" is taken by a ${holder} subgraph, so the server would refuse this one. Choose another name, such as \"${subgraphName}-api\".`;\n}\n\nfunction codeFirstName(dir: string): string | undefined {\n const files = [\n \"index.ts\",\n ...readdirSync(dir, { recursive: true, encoding: \"utf8\" })\n .filter((file) => file.endsWith(\".ts\") && file !== \"index.ts\")\n .sort(),\n ];\n for (const file of files) {\n const name = CODE_FIRST_NAME.exec(read(join(dir, file)) ?? \"\")?.[1];\n if (name !== undefined) return name;\n }\n return undefined;\n}\n\n/** A warning per model or subgraph the server would refuse or leave out. */\nexport async function lintSubgraphTypes(projectDir: string): Promise<string[]> {\n const models = loadModels(projectDir);\n const subgraphsDir = join(projectDir, \"subgraphs\");\n const subgraphs: PackageSubgraph[] = [];\n for (const dir of subgraphDirs(subgraphsDir)) {\n if (subgraphDirStyle(subgraphsDir, dir) === \"code-first\") {\n // Its schema is `ph` descriptors, which `ph model check` reads; this\n // lint checks only its name, in index.ts or a module of its directory.\n const name = codeFirstName(join(subgraphsDir, dir));\n if (name !== undefined) {\n subgraphs.push({\n name,\n typeDefs: { kind: Kind.DOCUMENT, definitions: [] },\n });\n }\n continue;\n }\n const typeDefs = readSchema(join(subgraphsDir, dir, \"schema.ts\"));\n if (!typeDefs) continue;\n const index = read(join(subgraphsDir, dir, \"index.ts\")) ?? \"\";\n subgraphs.push({ name: SUBGRAPH_NAME.exec(index)?.[1] ?? dir, typeDefs });\n }\n if (subgraphs.length === 0 && models.length === 0) return [];\n\n const { conflicts, refusedModels } = await findPackageSubgraphConflicts(\n subgraphs,\n models,\n );\n return [\n ...refusedModels.map(describeRefusal),\n ...Array.from(conflicts, ([name, conflict]) => describe(name, conflict)),\n ];\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBACJ;AACF,MAAM,kBAAkB;AAExB,SAAS,YAAY,MAAwB;CAC3C,IAAI;EACF,OAAO,YAAY,MAAM,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,QAAQ,UACxD,MAAM,YAAY,CACpB;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,SAAS,KAAK,MAAkC;CAC9C,IAAI;EACF,OAAO,aAAa,MAAM,OAAO;CACnC,QAAQ;EACN;CACF;AACF;AAEA,SAAS,WAAW,MAAwC;CAC1D,MAAM,SAAS,KAAK,IAAI;CACxB,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,MAAM,SAAS,MAAM,KAAK,OAAO,SAAS,YAAY,IAAI,GAAG,SAAS,GAAG;CACzE,IAAI,OAAO,WAAW,KAAK,OAAO,MAAM,QAAQ,IAAI,SAAS,IAAI,CAAC,GAChE;CAEF,IAAI;EACF,OAAO,MAAM,OAAO,KAAK,IAAI,CAAC;CAChC,QAAQ;E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AAO,WAAW,GAAG,OAAO,CAAC;CAE3D,MAAM,EAAE,WAAW,kBAAkB,MAAM,6BACzC,WACA,MACF;CACA,OAAO,CACL,GAAG,cAAc,IAAI,eAAe,GACpC,GAAG,MAAM,KAAK,YAAY,CAAC,MAAM,cAAc,SAAS,MAAM,QAAQ,CAAC,CACzE;AACF"}
@@ -1,8 +1,8 @@
1
- import { t as codegenFactoryBuilder } from "./factory-GIkoxPdL.js";
1
+ import { t as codegenFactoryBuilder } from "./factory-B9ent5Rs.js";
2
2
  import { t as vetraReadModelFactoryBuilder } from "./factory-BUuO4fIN.js";
3
3
  //#region processors/switchboard.ts
4
4
  const processorFactoryBuilders = [vetraReadModelFactoryBuilder, codegenFactoryBuilder];
5
5
  //#endregion
6
6
  export { processorFactoryBuilders };
7
7
 
8
- //# sourceMappingURL=switchboard-DUSh_ScZ.js.map
8
+ //# sourceMappingURL=switchboard-D70bg3-8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard-DUSh_ScZ.js","names":[],"sources":["../processors/switchboard.ts"],"sourcesContent":["/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { ProcessorFactoryBuilder } from \"@powerhousedao/reactor-browser\";\nimport { codegenFactoryBuilder } from \"./codegen/factory.js\";\nimport { vetraReadModelFactoryBuilder } from \"./vetra-read-model/factory.js\";\n\nexport const processorFactoryBuilders: ProcessorFactoryBuilder[] = [\n vetraReadModelFactoryBuilder,\n codegenFactoryBuilder,\n];\n"],"mappings":";;;AAQA,MAAa,2BAAsD,CACjE,8BACA,qBACF"}
1
+ {"version":3,"file":"switchboard-D70bg3-8.js","names":[],"sources":["../processors/switchboard.ts"],"sourcesContent":["/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { ProcessorFactoryBuilder } from \"@powerhousedao/reactor-browser\";\nimport { codegenFactoryBuilder } from \"./codegen/factory.js\";\nimport { vetraReadModelFactoryBuilder } from \"./vetra-read-model/factory.js\";\n\nexport const processorFactoryBuilders: ProcessorFactoryBuilder[] = [\n vetraReadModelFactoryBuilder,\n codegenFactoryBuilder,\n];\n"],"mappings":";;;AAQA,MAAa,2BAAsD,CACjE,8BACA,qBACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/vetra",
3
- "version": "6.2.3-dev.100",
3
+ "version": "6.2.3-dev.102",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -61,21 +61,21 @@
61
61
  "./package.json": "./package.json"
62
62
  },
63
63
  "dependencies": {
64
- "@powerhousedao/codegen": "6.2.3-dev.100",
65
- "@powerhousedao/config": "6.2.3-dev.100",
66
- "@powerhousedao/design-system": "6.2.3-dev.100",
67
- "@powerhousedao/reactor-api": "6.2.3-dev.100",
68
- "@powerhousedao/reactor-browser": "6.2.3-dev.100",
69
- "@powerhousedao/shared": "6.2.3-dev.100",
64
+ "@powerhousedao/codegen": "6.2.3-dev.102",
65
+ "@powerhousedao/config": "6.2.3-dev.102",
66
+ "@powerhousedao/design-system": "6.2.3-dev.102",
67
+ "@powerhousedao/reactor-api": "6.2.3-dev.102",
68
+ "@powerhousedao/reactor-browser": "6.2.3-dev.102",
69
+ "@powerhousedao/shared": "6.2.3-dev.102",
70
70
  "change-case": "5.4.4",
71
- "document-model": "6.2.3-dev.100",
71
+ "document-model": "6.2.3-dev.102",
72
72
  "graphql": "^16",
73
73
  "react": "19.2.6",
74
74
  "zod": "^4.5.4",
75
75
  "tailwind-merge": "3.4.0"
76
76
  },
77
77
  "devDependencies": {
78
- "@powerhousedao/builder-tools": "6.2.3-dev.100",
78
+ "@powerhousedao/builder-tools": "6.2.3-dev.102",
79
79
  "@tailwindcss/cli": "4.2.2",
80
80
  "@testing-library/jest-dom": "^6.9.1",
81
81
  "@testing-library/react": "^16.3.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"subgraph-type-lint-Dr8Wu0VB.js","names":[],"sources":["../codegen/subgraph-type-lint.ts"],"sourcesContent":["import { loadDocumentModelInDir } from \"@powerhousedao/codegen/utils\";\nimport {\n findPackageSubgraphConflicts,\n type PackageSubgraph,\n type PackageSubgraphConflicts,\n type RefusedDocumentModel,\n} from \"@powerhousedao/reactor-api/subgraph-types\";\nimport { kebabCase } from \"change-case\";\nimport { type DocumentNode, Kind, parse } from \"graphql\";\nimport { type Dirent, existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// Templates with substitutions are skipped: their SDL is only known at runtime.\nconst GQL_TEMPLATE = /\\bgql\\s*`([^`]*)`/g;\nconst SUBGRAPH_NAME = /\\bname\\s*=\\s*[\"'`]([^\"'`]+)[\"'`]/;\nconst SUBGRAPH_EXPORT = /from\\s+[\"']\\.\\/([^/\"']+)\\/index\\.js[\"']/g;\n\nfunction directories(path: string): Dirent[] {\n try {\n return readdirSync(path, { withFileTypes: true }).filter((entry) =>\n entry.isDirectory(),\n );\n } catch {\n return [];\n }\n}\n\nfunction read(path: string): string | undefined {\n try {\n return readFileSync(path, \"utf-8\");\n } catch {\n return undefined;\n }\n}\n\nfunction readSchema(path: string): DocumentNode | undefined {\n const source = read(path);\n if (source === undefined) return undefined;\n const blocks = Array.from(source.matchAll(GQL_TEMPLATE), ([, sdl]) => sdl);\n if (blocks.length === 0 || blocks.some((sdl) => sdl.includes(\"${\"))) {\n return undefined;\n }\n try {\n return parse(blocks.join(\"\\n\"));\n } catch {\n // Invalid SDL fails where the subgraph loads, and is reported there.\n return undefined;\n }\n}\n\n/** Subgraph directories in the order `subgraphs/index.ts` registers them. */\nfunction subgraphDirs(subgraphsDir: string): string[] {\n const exported = Array.from(\n (read(join(subgraphsDir, \"index.ts\")) ?? \"\").matchAll(SUBGRAPH_EXPORT),\n ([, dir]) => dir,\n );\n const position = (dir: string) => {\n const index = exported.indexOf(dir);\n return index === -1 ? exported.length : index;\n };\n return directories(subgraphsDir)\n .map((entry) => entry.name)\n .sort((a, b) => position(a) - position(b));\n}\n\nfunction describeRefusal({\n name,\n reason,\n subgraphOnly,\n}: RefusedDocumentModel): string {\n const detail = reason.split(\"\\n\")[0].replace(/\\.$/, \"\");\n return subgraphOnly\n ? `The subgraph of document model \"${name}\" is refused by the server: ${detail}.`\n : `Document model \"${name}\" is refused by the server: ${detail}.`;\n}\n\nfunction describe(name: string, conflict: PackageSubgraphConflicts): string {\n if (conflict.nameHeldBy === \"package\") {\n return `Subgraph \"${name}\" is defined more than once, so the server serves only the last. Rename the others.`;\n }\n if (conflict.nameHeldBy) {\n return `Subgraph \"${name}\" has the name of a ${conflict.nameHeldBy} subgraph, so the server refuses it. Rename the subgraph.`;\n }\n const claims = conflict.claims\n .map(({ claim, owner }) => `${claim} (owned by \"${owner}\")`)\n .join(\", \");\n return `Subgraph \"${name}\" defines ${claims}, so the supergraph leaves it out. Rename them in its schema.ts.`;\n}\n\nfunction loadModels(projectDir: string) {\n return directories(join(projectDir, \"document-models\"))\n .map(loadDocumentModelInDir)\n .filter((model) => model !== undefined);\n}\n\n/** Why the server would refuse a new subgraph scaffolded as `name`, if it\n * would; an existing one is left to {@link lintSubgraphTypes}. */\nexport async function findSubgraphNameConflict(\n projectDir: string,\n name: string,\n): Promise<string | undefined> {\n const subgraphName = kebabCase(name);\n if (existsSync(join(projectDir, \"subgraphs\", subgraphName, \"index.ts\"))) {\n return undefined;\n }\n const { conflicts } = await findPackageSubgraphConflicts(\n [\n {\n name: subgraphName,\n typeDefs: { kind: Kind.DOCUMENT, definitions: [] },\n },\n ],\n loadModels(projectDir),\n );\n const holder = conflicts.get(subgraphName)?.nameHeldBy;\n if (!holder || holder === \"package\") return undefined;\n return `Subgraph name \"${subgraphName}\" is taken by a ${holder} subgraph, so the server would refuse this one. Choose another name, such as \"${subgraphName}-api\".`;\n}\n\n/** A warning per model or subgraph the server would refuse or leave out. */\nexport async function lintSubgraphTypes(projectDir: string): Promise<string[]> {\n const models = loadModels(projectDir);\n const subgraphsDir = join(projectDir, \"subgraphs\");\n const subgraphs: PackageSubgraph[] = [];\n for (const dir of subgraphDirs(subgraphsDir)) {\n const typeDefs = readSchema(join(subgraphsDir, dir, \"schema.ts\"));\n if (!typeDefs) continue;\n const index = read(join(subgraphsDir, dir, \"index.ts\")) ?? \"\";\n subgraphs.push({ name: SUBGRAPH_NAME.exec(index)?.[1] ?? dir, typeDefs });\n }\n if (subgraphs.length === 0 && models.length === 0) return [];\n\n const { conflicts, refusedModels } = await findPackageSubgraphConflicts(\n subgraphs,\n models,\n );\n return [\n ...refusedModels.map(describeRefusal),\n ...Array.from(conflicts, ([name, conflict]) => describe(name, conflict)),\n ];\n}\n"],"mappings":";;;;;;;AAaA,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AAExB,SAAS,YAAY,MAAwB;CAC3C,IAAI;EACF,OAAO,YAAY,MAAM,EAAE,eAAe,KAAK,CAAC,CAAC,CAAC,QAAQ,UACxD,MAAM,YAAY,CACpB;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,SAAS,KAAK,MAAkC;CAC9C,IAAI;EACF,OAAO,aAAa,MAAM,OAAO;CACnC,QAAQ;EACN;CACF;AACF;AAEA,SAAS,WAAW,MAAwC;CAC1D,MAAM,SAAS,KAAK,IAAI;CACxB,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,MAAM,SAAS,MAAM,KAAK,OAAO,SAAS,YAAY,IAAI,GAAG,SAAS,GAAG;CACzE,IAAI,OAAO,WAAW,KAAK,OAAO,MAAM,QAAQ,IAAI,SAAS,IAAI,CAAC,GAChE;CAEF,IAAI;EACF,OAAO,MAAM,OAAO,KAAK,IAAI,CAAC;CAChC,QAAQ;EAEN;CACF;AACF;;AAGA,SAAS,aAAa,cAAgC;CACpD,MAAM,WAAW,MAAM,MACpB,KAAK,KAAK,cAAc,UAAU,CAAC,KAAK,GAAA,CAAI,SAAS,eAAe,IACpE,GAAG,SAAS,GACf;CACA,MAAM,YAAY,QAAgB;EAChC,MA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