@powerhousedao/codegen 6.0.0-dev.176 → 6.0.0-dev.178

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.
@@ -1 +1 @@
1
- {"version":3,"file":"file-builders-D4FOBUqA.mjs","names":["path","path","path","makeIndexFile","makeProcessorFile","makeFactoryFile"],"sources":["../src/file-builders/editor-common.ts","../src/file-builders/index-files.ts","../src/file-builders/module-files.ts","../src/file-builders/app.ts","../src/file-builders/boilerplate/package.json.ts","../src/file-builders/clis/generate-cli-docs.ts","../src/file-builders/document-editor.ts","../src/codegen/graphql.ts","../src/file-builders/document-model/gen-dir.ts","../src/file-builders/document-model/migrate-legacy.ts","../src/file-builders/document-model/root-dir.ts","../src/file-builders/document-model/src-dir.ts","../src/file-builders/document-model/tests-dir.ts","../src/file-builders/document-model/upgrades-dir.ts","../src/file-builders/document-model/document-model.ts","../src/file-builders/processors/analytics.ts","../src/file-builders/processors/relational-db.ts","../src/file-builders/processors/processor.ts","../src/file-builders/subgraph.ts","../src/file-builders/subgraphs.ts"],"sourcesContent":["import { pascalCase } from \"change-case\";\nimport path from \"path\";\nimport { documentEditorModuleFileTemplate } from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { getOrCreateSourceFile } from \"utils\";\n\ntype MakeEditorModuleFileArgs = {\n project: Project;\n editorName: string;\n editorId: string;\n documentModelId?: string;\n editorDirPath: string;\n legacyMultipleDocumentTypes?: string[];\n};\n/** Generates the `module.ts` file for a document editor or app */\nexport function makeEditorModuleFile({\n project,\n editorDirPath,\n editorName,\n documentModelId,\n editorId,\n legacyMultipleDocumentTypes,\n}: MakeEditorModuleFileArgs) {\n if (documentModelId && !!legacyMultipleDocumentTypes) {\n throw new Error(\n \"Cannot specify both documentModelId and legacyMultipleDocumentTypes\",\n );\n }\n const filePath = path.join(editorDirPath, \"module.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n\n const pascalCaseEditorName = pascalCase(editorName);\n const documentTypes = documentModelId\n ? `[\"${documentModelId}\"]`\n : JSON.stringify(legacyMultipleDocumentTypes);\n\n const template = documentEditorModuleFileTemplate({\n editorName,\n editorId,\n pascalCaseEditorName,\n documentTypes,\n });\n sourceFile.replaceWithText(template);\n}\n","import path from \"node:path\";\nimport type { Project } from \"ts-morph\";\n\ntype MakeLegacyIndexFileArgs = {\n /** The project to make the legacy index file for */\n project: Project;\n /** The directory containing the module.ts files to generate from */\n modulesDirPath: string;\n modules: {\n unversionedName: string;\n versionedName: string | undefined;\n moduleSpecifier: string;\n }[];\n};\n\n/**\n * Makes a legacy index.ts file for the modules file which exports the modules as individual exports instead of an array of named exports.\n */\nexport function makeLegacyIndexFile({\n project,\n modulesDirPath,\n modules,\n}: MakeLegacyIndexFileArgs) {\n const indexSourceFilePath = path.join(modulesDirPath, \"index.ts\");\n\n // get the source file for the index.ts file if it exists\n let indexSourceFile = project.getSourceFile(indexSourceFilePath);\n // if the index.ts file doesn't exist, create it\n if (!indexSourceFile) {\n indexSourceFile = project.createSourceFile(indexSourceFilePath, \"\");\n } else {\n indexSourceFile.replaceWithText(\"\");\n }\n\n indexSourceFile.addExportDeclarations(\n modules.map(({ versionedName, unversionedName, moduleSpecifier }) => ({\n namedExports: [\n versionedName\n ? `${unversionedName} as ${versionedName}`\n : unversionedName,\n ],\n moduleSpecifier,\n })),\n );\n}\n","import { camelCase, pascalCase } from \"change-case\";\nimport path from \"node:path\";\nimport type { Project } from \"ts-morph\";\nimport { SyntaxKind, VariableDeclarationKind } from \"ts-morph\";\nimport {\n ensureDirectoriesExist,\n getOrCreateDirectory,\n getOrCreateSourceFile,\n} from \"../utils/source-files.js\";\nimport { getVariableDeclarationByTypeName } from \"../utils/syntax-getters.js\";\nimport { makeLegacyIndexFile } from \"./index-files.js\";\n\ntype MakeModuleFileArgs = {\n /** The project to make the modules file for */\n project: Project;\n /** The directory containing the module.ts files to generate from */\n modulesDirPath: string;\n /** The name of the output file which exports the modules, e.g. 'document-models.ts' or 'editors.ts' */\n outputFileName: string;\n /** The type name of the modules exported by the module.ts files, e.g. 'DocumentModelModule' or 'EditorModule' */\n typeName: string;\n /** The name of the variable that exports the modules, e.g. 'documentModels' or 'editors' */\n variableName: string;\n /** The type of the variable that exports the modules, e.g. 'DocumentModelModule<any>[]' or 'EditorModule[]' */\n variableType: string;\n /** Whether to make a legacy index.ts file for the modules, to be removed in the future */\n shouldMakeLegacyIndexFile?: boolean;\n /** Name of the module file to look for\n * @default module.ts\n */\n moduleFileName?: string;\n};\n/**\n * Makes a file which exports the modules from the module.ts files in the given directory as a variable declaration.\n */\nexport async function makeModulesFile({\n project,\n modulesDirPath,\n outputFileName,\n typeName,\n variableName,\n variableType,\n shouldMakeLegacyIndexFile = true,\n moduleFileName = \"module.ts\",\n}: MakeModuleFileArgs) {\n await ensureDirectoriesExist(project, modulesDirPath);\n const modulesSourceFilesPath = path.join(modulesDirPath, \"**/*\");\n // we only need the files in the directory we're creating the modules file from\n project.addSourceFilesAtPaths(modulesSourceFilesPath);\n\n const { directory: modulesDir } = getOrCreateDirectory(\n project,\n modulesDirPath,\n );\n const moduleFiles = modulesDir\n .getDescendantSourceFiles()\n .filter((file) => file.getBaseName().includes(moduleFileName));\n\n // get the variable declaration for the module object exported by each module.ts file by the given type name\n const moduleDeclarations = moduleFiles\n .map((file) => getVariableDeclarationByTypeName(file, typeName))\n .filter((v) => v !== undefined);\n\n const modules = moduleDeclarations.map((module) => {\n const sourceFile = module.getSourceFile();\n const moduleSpecifier =\n modulesDir.getRelativePathAsModuleSpecifierTo(sourceFile.getFilePath()) +\n \".js\";\n const versionDir = getVersionDirFromModuleSpecifier(moduleSpecifier);\n const unversionedName = module.getName();\n const versionedName = versionDir\n ? `${unversionedName}${pascalCase(versionDir)}`\n : undefined;\n return { versionedName, unversionedName, moduleSpecifier };\n });\n\n const moduleExportsFilePath = path.join(modulesDirPath, outputFileName);\n\n const { sourceFile: moduleExportsSourceFile } = getOrCreateSourceFile(\n project,\n moduleExportsFilePath,\n );\n\n moduleExportsSourceFile.replaceWithText(\"\");\n\n const typeImport = {\n namedImports: [typeName],\n moduleSpecifier: \"document-model\",\n isTypeOnly: true,\n };\n const moduleImports = modules.map(\n ({ versionedName, unversionedName, moduleSpecifier }) => ({\n namedImports: [\n versionedName\n ? `${unversionedName} as ${versionedName}`\n : unversionedName,\n ],\n moduleSpecifier,\n }),\n );\n const importDeclarations = [typeImport, ...moduleImports];\n\n for (const declaration of importDeclarations) {\n if (\n !moduleExportsSourceFile.getImportDeclaration((importDeclaration) =>\n importDeclaration\n .getNamedImports()\n .some((importSpecifier) =>\n declaration.namedImports.includes(importSpecifier.getName()),\n ),\n )\n ) {\n moduleExportsSourceFile.addImportDeclaration(declaration);\n }\n }\n\n // create the variable statement for the modules file\n // start as an empty array\n const moduleExportsVariableStatementInput = {\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: variableName,\n type: variableType,\n initializer: `[]`,\n },\n ],\n };\n // get the variable statement for the modules file if it exists\n let moduleExportsVariableStatement =\n moduleExportsSourceFile.getVariableStatement(variableName);\n // if the variable statement doesn't exist, create it\n if (!moduleExportsVariableStatement) {\n moduleExportsVariableStatement =\n moduleExportsSourceFile.addVariableStatement(\n moduleExportsVariableStatementInput,\n );\n } else {\n // if the variable statement exists, set it to the new variable statement\n moduleExportsVariableStatement.set(moduleExportsVariableStatementInput);\n }\n // get the array literal expression for the variable statement\n const arrayLiteral = moduleExportsVariableStatement\n .getDeclarations()\n .at(0)\n ?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);\n\n // add the module declaration names to the array literal expression\n arrayLiteral?.addElements(\n modules.map((module) => module.versionedName ?? module.unversionedName),\n { useNewLines: true },\n );\n\n // we also need to export each module from the index.ts file for backwards compatibility\n if (shouldMakeLegacyIndexFile) {\n makeLegacyIndexFile({\n project,\n modulesDirPath,\n modules,\n });\n }\n\n await project.save();\n}\n\nexport async function makeUpgradeManifestsFile(args: {\n project: Project;\n projectDir: string;\n}) {\n const { project, projectDir } = args;\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n\n await makeModulesFile({\n project,\n modulesDirPath: documentModelsDirPath,\n outputFileName: \"upgrade-manifests.ts\",\n typeName: \"UpgradeManifest\",\n variableName: \"upgradeManifests\",\n variableType: \"UpgradeManifest<readonly number[]>[]\",\n moduleFileName: \"upgrade-manifest.ts\",\n shouldMakeLegacyIndexFile: false,\n });\n}\n\n/** Generates the `document-models.ts` file which exports the document models defined in each document model dir's `module.ts` file */\nexport async function makeDocumentModelModulesFile({\n project,\n projectDir,\n}: {\n project: Project;\n projectDir: string;\n}) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n await makeModulesFile({\n project,\n modulesDirPath: documentModelsDirPath,\n outputFileName: \"document-models.ts\",\n typeName: \"DocumentModelModule\",\n variableName: \"documentModels\",\n variableType: \"DocumentModelModule<any>[]\",\n });\n}\n\n/** Generates the `editors.ts` file which exports the editors defined in each editor dir's `module.ts` file */\nexport async function makeEditorsModulesFile(\n project: Project,\n projectDir: string,\n) {\n const modulesDirPath = path.join(projectDir, \"editors\");\n await makeModulesFile({\n project,\n modulesDirPath,\n outputFileName: \"editors.ts\",\n typeName: \"EditorModule\",\n variableName: \"editors\",\n variableType: \"EditorModule[]\",\n });\n}\n\nfunction getVersionDirFromModuleSpecifier(moduleSpecifier: string) {\n const match = moduleSpecifier.match(/\\/(v\\d+)(?=\\/)/);\n const version = match?.[1];\n return version;\n}\n\ntype MakeUpgradeManifestsExportArgs = {\n /** The project to add the export to */\n project: Project;\n /** The directory containing the document model directories (e.g., document-models/) */\n modulesDirPath: string;\n /** The path to the output file (document-models.ts) */\n outputFilePath: string;\n /** The variable name for the upgrade manifests array */\n variableName: string;\n /** The type of the upgrade manifests variable */\n variableType: string;\n /** The type name for UpgradeManifest to add to imports */\n typeName: string;\n};\n\n/**\n * Adds the upgradeManifests export to an existing document-models.ts file.\n * Searches for upgrade-manifest.ts files in each document model's upgrades directory,\n * adds imports for each, and creates the upgradeManifests array export.\n */\nexport function makeUpgradeManifestsExport({\n project,\n modulesDirPath,\n outputFilePath,\n variableName,\n variableType,\n typeName,\n}: MakeUpgradeManifestsExportArgs) {\n // Resolve to absolute path for glob pattern matching\n const absoluteModulesDirPath = path.resolve(modulesDirPath);\n const absoluteOutputFilePath = path.resolve(outputFilePath);\n\n // Add upgrade-manifest.ts files to the project\n const upgradeManifestGlob = `${absoluteModulesDirPath}/**/upgrade-manifest.ts`;\n project.addSourceFilesAtPaths(upgradeManifestGlob);\n\n // Find all upgrade-manifest.ts files\n const upgradeManifestFiles = project\n .getSourceFiles()\n .filter((file) => file.getFilePath().includes(\"upgrade-manifest.ts\"))\n .filter((file) => file.getFilePath().startsWith(absoluteModulesDirPath));\n\n if (upgradeManifestFiles.length === 0) {\n return;\n }\n\n // Get the output source file (document-models.ts)\n // Refresh from file system to ensure we have the latest content after makeModulesFile\n let outputSourceFile = project.getSourceFile(absoluteOutputFilePath);\n if (outputSourceFile) {\n outputSourceFile.refreshFromFileSystemSync();\n } else {\n // If not found in project, add it\n project.addSourceFilesAtPaths(absoluteOutputFilePath);\n outputSourceFile = project.getSourceFile(absoluteOutputFilePath);\n }\n if (!outputSourceFile) {\n return;\n }\n\n const modulesDir = project.getDirectory(absoluteModulesDirPath);\n if (!modulesDir) {\n return;\n }\n\n // Extract upgrade manifest info from each file\n const manifests = upgradeManifestFiles.map((file) => {\n const filePath = file.getFilePath();\n // Extract document model name from path (e.g., ./todo/upgrades/upgrade-manifest.ts -> todo)\n const pathParts = filePath.split(\"/\");\n const upgradesIndex = pathParts.indexOf(\"upgrades\");\n const documentModelName =\n upgradesIndex > 0 ? pathParts[upgradesIndex - 1] : \"unknown\";\n\n const moduleSpecifier =\n modulesDir.getRelativePathAsModuleSpecifierTo(filePath) + \".js\";\n\n // Create aliased name like \"upgradeManifest as todoUpgradeManifest\"\n // Convert to camelCase to ensure valid JS identifier (e.g., billing-statement -> billingStatementUpgradeManifest)\n const aliasedName = `${camelCase(documentModelName)}UpgradeManifest`;\n\n return {\n originalName: \"upgradeManifest\",\n aliasedName,\n moduleSpecifier,\n };\n });\n\n // Add UpgradeManifest to the existing type import from document-model\n const existingTypeImport = outputSourceFile\n .getImportDeclarations()\n .find(\n (imp) =>\n imp.getModuleSpecifierValue() === \"document-model\" && imp.isTypeOnly(),\n );\n\n if (existingTypeImport) {\n const namedImports = existingTypeImport.getNamedImports();\n const hasUpgradeManifest = namedImports.some(\n (ni) => ni.getName() === typeName,\n );\n if (!hasUpgradeManifest) {\n existingTypeImport.addNamedImport(typeName);\n }\n }\n\n // Add import declarations for each upgrade manifest using text insertion\n // This avoids ts-morph AST manipulation issues with the refreshed file\n const existingImports = outputSourceFile.getImportDeclarations();\n const lastImport = existingImports[existingImports.length - 1];\n\n if (lastImport) {\n const importTexts = manifests.map(\n ({ originalName, aliasedName, moduleSpecifier }) =>\n `import { ${originalName} as ${aliasedName} } from \"${moduleSpecifier}\";`,\n );\n const insertText = \"\\n\" + importTexts.join(\"\\n\");\n const insertPos = lastImport.getEnd();\n outputSourceFile.insertText(insertPos, insertText);\n }\n\n // Create the upgradeManifests variable statement\n const variableStatementInput = {\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: variableName,\n type: variableType,\n initializer: `[]`,\n },\n ],\n };\n\n // Add the variable statement\n const variableStatement = outputSourceFile.addVariableStatement(\n variableStatementInput,\n );\n\n // Get the array literal and add the manifest names\n const arrayLiteral = variableStatement\n .getDeclarations()\n .at(0)\n ?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);\n\n arrayLiteral?.addElements(\n manifests.map((m) => m.aliasedName),\n { useNewLines: true },\n );\n}\n","import type { CommonGenerateEditorArgs } from \"@powerhousedao/codegen\";\nimport path from \"path\";\nimport {\n appConfigFileTemplate,\n appDriveContentsFileTemplate,\n appEditorFileTemplate,\n appFilesFileTemplate,\n appFoldersFileTemplate,\n createDocumentFileTemplate,\n driveExplorerFileTemplate,\n driveExplorerNavigationBreadcrumbsFileTemplate,\n emptyStateFileTemplate,\n folderTreeFileTemplate,\n} from \"templates\";\nimport { type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { makeEditorModuleFile } from \"./editor-common.js\";\nimport { makeEditorsModulesFile } from \"./module-files.js\";\n\ntype GenerateAppArgs = CommonGenerateEditorArgs & {\n allowedDocumentModelIds: string[];\n isDragAndDropEnabled: boolean;\n};\n/** Generates a app with the configs for `allowedDocumentModelIds` and `isDragAndDropEnabled` */\nexport async function tsMorphGenerateApp({\n projectDir,\n editorDir,\n editorName,\n editorId,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n}: GenerateAppArgs) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const documentModelsSourceFilesPath = path.join(\n documentModelsDirPath,\n \"/**/*\",\n );\n const editorsDirPath = path.join(projectDir, \"editors\");\n const editorSourceFilesPath = path.join(editorsDirPath, \"/**/*\");\n const editorDirPath = path.join(editorsDirPath, editorDir);\n const editorComponentsDirPath = path.join(editorDirPath, \"components\");\n\n const project = buildTsMorphProject(projectDir);\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n editorsDirPath,\n editorDirPath,\n editorComponentsDirPath,\n );\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n project.addSourceFilesAtPaths(editorSourceFilesPath);\n\n await makeNavigationBreadcrumbsFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeCreateDocumentFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeEmptyStateFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFoldersFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFolderTreeFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFilesFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeDriveExplorerFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeDriveContentsFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeAppComponent({\n project,\n editorDirPath,\n });\n\n await makeAppConfigFile({\n project,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n editorDirPath,\n });\n\n makeEditorModuleFile({\n project,\n editorName,\n editorId,\n editorDirPath,\n documentModelId: \"powerhouse/document-drive\",\n });\n\n await makeEditorsModulesFile(project, projectDir);\n\n await project.save();\n}\n\ntype MakeAppComponentArgs = {\n project: Project;\n editorDirPath: string;\n};\nasync function makeAppComponent({\n project,\n editorDirPath,\n}: MakeAppComponentArgs) {\n const filePath = path.join(editorDirPath, \"editor.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) {\n const editorFunction = sourceFile.getFunction(\"Editor\");\n if (editorFunction) {\n if (!editorFunction.isDefaultExport()) {\n editorFunction.setIsDefaultExport(true);\n }\n return;\n }\n }\n const template = appEditorFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeAppConfigFileArgs = {\n project: Project;\n editorDirPath: string;\n allowedDocumentModelIds: string[];\n isDragAndDropEnabled: boolean;\n};\nasync function makeAppConfigFile({\n project,\n editorDirPath,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n}: MakeAppConfigFileArgs) {\n const filePath = path.join(editorDirPath, \"config.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n const allowedDocumentTypesString = JSON.stringify(allowedDocumentModelIds);\n const isDragAndDropEnabledString = isDragAndDropEnabled ? \"true\" : \"false\";\n\n const template = appConfigFileTemplate({\n isDragAndDropEnabledString,\n allowedDocumentTypesString,\n });\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeDriveContentsFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeDriveContentsFile({\n project,\n editorComponentsDirPath,\n}: MakeDriveContentsFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"DriveContents.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n const template = appDriveContentsFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeNavigationBreadcrumbsFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\n\nasync function makeNavigationBreadcrumbsFile({\n project,\n editorComponentsDirPath,\n}: MakeNavigationBreadcrumbsFileArgs) {\n const filePath = path.join(\n editorComponentsDirPath,\n \"NavigationBreadcrumbs.tsx\",\n );\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(driveExplorerNavigationBreadcrumbsFileTemplate());\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFoldersFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFoldersFile({\n project,\n editorComponentsDirPath,\n}: MakeFoldersFileArgs) {\n const foldersFilePath = path.join(editorComponentsDirPath, \"Folders.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n foldersFilePath,\n );\n\n if (alreadyExists) return;\n\n const template = appFoldersFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFilesFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFilesFile({\n project,\n editorComponentsDirPath,\n}: MakeFilesFileArgs) {\n const filesFilePath = path.join(editorComponentsDirPath, \"Files.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filesFilePath,\n );\n\n if (alreadyExists) return;\n\n const template = appFilesFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeDriveExplorerFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeDriveExplorerFile({\n project,\n editorComponentsDirPath,\n}: MakeDriveExplorerFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"DriveExplorer.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(driveExplorerFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFolderTreeFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFolderTreeFile({\n project,\n editorComponentsDirPath,\n}: MakeFolderTreeFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"FolderTree.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(folderTreeFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeEmptyStateFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeEmptyStateFile({\n project,\n editorComponentsDirPath,\n}: MakeEmptyStateFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"EmptyState.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(emptyStateFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeCreateDocumentFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeCreateDocumentFile({\n project,\n editorComponentsDirPath,\n}: MakeCreateDocumentFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"CreateDocument.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(createDocumentFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import {\n makeVersionedDependencies,\n VERSIONED_DEPENDENCIES,\n VERSIONED_DEV_DEPENDENCIES,\n} from \"@powerhousedao/shared/clis\";\nimport { packageJsonTemplate } from \"templates\";\n\nexport async function buildBoilerplatePackageJson(args: {\n name: string;\n tag?: string;\n version?: string;\n workspace?: boolean;\n}) {\n const { name, tag, version, workspace } = args;\n const versionedDependencies = await makeVersionedDependencies({\n names: VERSIONED_DEPENDENCIES,\n tag,\n version,\n });\n const versionedDevDependencies = await makeVersionedDependencies({\n names: VERSIONED_DEV_DEPENDENCIES,\n tag,\n version,\n });\n\n const template = packageJsonTemplate(\n name,\n versionedDependencies,\n versionedDevDependencies,\n );\n\n return template;\n}\n","import type { CommandEntry, CommandHelpInfo } from \"@powerhousedao/codegen\";\nimport { writeFile } from \"node:fs/promises\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { docsFromCliHelpTemplate } from \"templates\";\nexport function getCommandHelpInfo<TEntry extends CommandEntry>(\n entry: TEntry,\n): CommandHelpInfo {\n const name = entry.name;\n const description = entry.command.description ?? \"\";\n const helpTopics = entry.command.helpTopics?.() ?? [];\n return {\n name,\n description,\n helpTopics,\n };\n}\n\nexport function getCommandsHelpInfo<TEntry extends CommandEntry>(\n entries: TEntry[],\n) {\n return entries.map(getCommandHelpInfo);\n}\n\nexport function makeCliDocsFromHelp<TEntry extends CommandEntry>(args: {\n cliDescription: string;\n docsTitle: string;\n docsIntroduction: string;\n entries: TEntry[];\n}) {\n const { cliDescription, docsIntroduction, docsTitle, entries } = args;\n const commandsHelpInfo = getCommandsHelpInfo(entries);\n\n const template = docsFromCliHelpTemplate({\n cliDescription,\n docsIntroduction,\n docsTitle,\n commandsHelpInfo,\n });\n\n const templateWithAnsiEscapesRemoved = stripVTControlCharacters(template);\n\n return templateWithAnsiEscapesRemoved;\n}\n\nexport async function writeCliDocsMarkdownFile<\n TEntry extends CommandEntry,\n>(args: {\n filePath: string;\n cliDescription: string;\n docsTitle: string;\n docsIntroduction: string;\n entries: TEntry[];\n}) {\n const { filePath, ...restArgs } = args;\n const markdownFileContent = makeCliDocsFromHelp(restArgs);\n\n await writeFile(filePath, markdownFileContent, {\n encoding: \"utf-8\",\n });\n}\n","import type {\n CommonGenerateEditorArgs,\n EditorVariableNames,\n} from \"@powerhousedao/codegen\";\nimport { getEditorVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport { documentEditorEditorFileTemplate } from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getDocumentTypeMetadata,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { makeEditorModuleFile } from \"./editor-common.js\";\nimport { makeEditorsModulesFile } from \"./module-files.js\";\n\ntype GenerateEditorArgs = CommonGenerateEditorArgs & {\n documentModelId: string;\n};\n/** Generates a document editor for the given `documentModelId` (also called `documentType`) */\nexport async function tsMorphGenerateDocumentEditor({\n projectDir,\n editorDir,\n editorName,\n editorId,\n documentModelId,\n}: GenerateEditorArgs) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const editorsDirPath = path.join(projectDir, \"editors\");\n const editorDirPath = path.join(editorsDirPath, editorDir);\n const componentsDirPath = path.join(editorDirPath, \"components\");\n const editorSourceFilesPath = path.join(editorsDirPath, \"/**/*\");\n const documentModelsSourceFilesPath = path.join(\n documentModelsDirPath,\n \"/**/*\",\n );\n\n const project = buildTsMorphProject(projectDir);\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n editorsDirPath,\n editorDirPath,\n componentsDirPath,\n );\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n project.addSourceFilesAtPaths(editorSourceFilesPath);\n\n const documentTypeMetadata = getDocumentTypeMetadata({\n project,\n documentModelId,\n documentModelsDirPath,\n });\n\n const editorVariableNames = getEditorVariableNames(documentTypeMetadata);\n\n await makeEditorComponent({\n project,\n editorDirPath,\n ...documentTypeMetadata,\n ...editorVariableNames,\n });\n\n makeEditorModuleFile({\n project,\n editorName,\n editorId,\n documentModelId,\n editorDirPath,\n });\n\n await makeEditorsModulesFile(project, projectDir);\n\n await project.save();\n}\n\ntype MakeEditorComponentArgs = EditorVariableNames & {\n project: Project;\n editorDirPath: string;\n documentModelDocumentTypeName: string;\n documentModelImportPath: string;\n};\nasync function makeEditorComponent(args: MakeEditorComponentArgs) {\n const { project, editorDirPath } = args;\n const filePath = path.join(editorDirPath, \"editor.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) {\n const functionDeclaration = sourceFile.getFunction(\"Editor\");\n if (functionDeclaration) {\n if (!functionDeclaration.isDefaultExport()) {\n functionDeclaration.setIsDefaultExport(true);\n }\n return;\n }\n }\n\n const template = documentEditorEditorFileTemplate(args);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type { CodegenConfig } from \"@graphql-codegen/cli\";\nimport { generate } from \"@graphql-codegen/cli\";\nimport type { TypeScriptPluginConfig } from \"@graphql-codegen/typescript\";\nimport {\n generatorTypeDefs,\n validationSchema,\n} from \"@powerhousedao/document-engineering/graphql\";\nimport type {\n DocumentModelGlobalState,\n DocumentSpecification,\n ModuleSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ValidationSchemaPluginConfig } from \"graphql-codegen-typescript-validation-schema\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { format } from \"prettier\";\n\nconst getDirectories = async (source: string) => {\n const dir = await fs.readdir(source, { withFileTypes: true });\n return dir.filter((dirent) => dirent.isDirectory()).map((dirent) => dirent);\n};\n\nexport const scalars = {\n Unknown: \"unknown\",\n DateTime: \"string\",\n Attachment: \"string\",\n Address: \"`${string}:0x${string}`\",\n ...(generatorTypeDefs as Record<string, string>),\n};\n\nexport const scalarsValidation = {\n Unknown: \"z.unknown()\",\n DateTime: \"z.string().datetime()\",\n Attachment: \"z.string()\",\n Address:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n ...(validationSchema as Record<string, string>),\n};\n\nconst avoidOptionals: TypeScriptPluginConfig[\"avoidOptionals\"] = {\n field: true,\n inputValue: false,\n};\nconst maybeValue = \"T | null | undefined\";\nconst typescriptConfig: TypeScriptPluginConfig = {\n avoidOptionals,\n scalars,\n strictScalars: true,\n enumsAsTypes: true,\n skipTypename: true,\n maybeValue,\n};\n\nconst validationSchemaConfig: ValidationSchemaPluginConfig = {\n avoidOptionals,\n scalars,\n strictScalars: true,\n enumsAsTypes: true,\n skipTypename: true,\n importFrom: `./types.js`,\n schema: \"zodv4\",\n useTypeImports: true,\n scalarSchemas: scalarsValidation,\n directives: {\n equals: {\n value: [\"regex\", \"/^$1$/\"],\n },\n },\n withObjectType: true,\n maybeValue,\n};\n\nfunction buildSchemasForModules(modules: ModuleSpecification[]) {\n const schemaStrings: string[] = [];\n for (const module of modules) {\n schemaStrings.push(`# ${module.name}`);\n const operationsSchemas = module.operations\n .map((operation) => operation.schema)\n .filter((schema) => schema !== null);\n schemaStrings.push(...operationsSchemas);\n }\n return schemaStrings;\n}\n\nfunction buildGraphqlDocumentStringForSpecification(\n specification: DocumentSpecification,\n) {\n const customScalarSchemas = Object.keys(scalars)\n .map((k) => `scalar ${k}`)\n .join(\"\\n\");\n const stateSchemas = Object.values(specification.state).map(\n (state) => state.schema,\n );\n const moduleSchemas = buildSchemasForModules(specification.modules);\n\n return [customScalarSchemas, ...stateSchemas, ...moduleSchemas];\n}\n\nasync function formatContentWithPrettier(path: string, content: string) {\n const formattedContent = await format(content, {\n parser: \"typescript\",\n });\n return formattedContent;\n}\n\ntype GenerateTypesAndZodSchemasFromGraphqlArgs = {\n dirName: string;\n schema: string;\n skipFormat?: boolean;\n writeFile?: boolean;\n watch?: boolean;\n};\nexport async function generateTypesAndZodSchemasFromGraphql(\n args: GenerateTypesAndZodSchemasFromGraphqlArgs,\n) {\n const { dirName, schema, skipFormat, writeFile, watch } = args;\n const beforeOneFileWrite = skipFormat ? undefined : formatContentWithPrettier;\n\n const config: CodegenConfig = {\n overwrite: true,\n watch,\n hooks: {\n beforeOneFileWrite,\n },\n generates: {\n [`${dirName}/gen/schema/types.ts`]: {\n schema,\n config: typescriptConfig,\n plugins: [\n {\n typescript: typescriptConfig,\n },\n ],\n },\n [`${dirName}/gen/schema/zod.ts`]: {\n schema,\n config: validationSchemaConfig,\n plugins: [\n {\n add: {\n content:\n \"/* eslint-disable @typescript-eslint/no-empty-object-type */\",\n },\n },\n {\n \"graphql-codegen-typescript-validation-schema\":\n validationSchemaConfig,\n },\n ],\n },\n },\n };\n\n await generate(config, writeFile);\n}\n\nexport async function generateDocumentModelZodSchemas(args: {\n documentModelDirPath: string;\n specification: DocumentSpecification;\n writeFile?: boolean;\n skipFormat?: boolean;\n watch?: boolean;\n}) {\n const {\n documentModelDirPath,\n specification,\n writeFile = true,\n skipFormat = false,\n watch = false,\n } = args;\n const schema = buildGraphqlDocumentStringForSpecification(specification)\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n await generateTypesAndZodSchemasFromGraphql({\n dirName: documentModelDirPath,\n schema,\n writeFile,\n skipFormat,\n watch,\n });\n\n await fs.writeFile(path.join(documentModelDirPath, \"schema.graphql\"), schema);\n}\n\nexport const generateSchemas = async (\n inDir: string,\n { watch = false, skipFormat = false, writeFile = true, outDir = inDir } = {},\n) => {\n const dirs = await getDirectories(inDir);\n const inputs = await Promise.all(\n dirs.map(async (dir) => {\n const documentModelJsonFile = await fs.readFile(\n path.join(dir.parentPath, dir.name, `${dir.name}.json`),\n \"utf-8\",\n );\n const parsedJson = JSON.parse(\n documentModelJsonFile,\n ) as DocumentModelGlobalState;\n\n const latestSpecification =\n parsedJson.specifications[parsedJson.specifications.length - 1];\n\n const schema = buildGraphqlDocumentStringForSpecification(\n latestSpecification,\n )\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n return { dirName: path.join(outDir, dir.name), schema };\n }),\n );\n\n await Promise.all(\n inputs.map(async ({ schema, dirName }) => {\n await generateTypesAndZodSchemasFromGraphql({\n schema,\n dirName,\n writeFile,\n skipFormat,\n watch,\n });\n }),\n );\n};\n","import { kebabCase, pascalCase } from \"change-case\";\nimport type {\n DocumentModelFileMakerArgs,\n DocumentModelTemplateInputsWithModule,\n} from \"file-builders\";\nimport { getDocumentModelOperationsModuleVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport {\n documentModelDocumentSchemaFileTemplate,\n documentModelDocumentTypeTemplate,\n documentModelGenActionsFileTemplate,\n documentModelGenControllerFileTemplate,\n documentModelGenCreatorsFileTemplate,\n documentModelGenIndexFileTemplate,\n documentModelGenReducerFileTemplate,\n documentModelGenTypesTemplate,\n documentModelGenUtilsTemplate,\n documentModelOperationModuleActionsFileTemplate,\n documentModelOperationsModuleCreatorsFileTemplate,\n documentModelOperationsModuleErrorFileTemplate,\n documentModelOperationsModuleOperationsFileTemplate,\n documentModelPhFactoriesFileTemplate,\n documentModelSchemaIndexTemplate,\n} from \"templates\";\nimport { VariableDeclarationKind } from \"ts-morph\";\nimport {\n buildObjectLiteral,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\n\nexport async function makeGenDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelSchemaIndexFile(fileMakerArgs);\n await makeDocumentModelGenUtilsFile(fileMakerArgs);\n await makeDocumentModelGenTypesFile(fileMakerArgs);\n await makeDocumentModelGenCreatorsFile(fileMakerArgs);\n await makeDocumentModelGenActionsFile(fileMakerArgs);\n await makeDocumentModelGenDocumentSchemaFile(fileMakerArgs);\n await makeDocumentModelGenReducerFile(fileMakerArgs);\n await makeDocumentModelDocumentTypeFile(fileMakerArgs);\n await makeDocumentModelGenIndexFile(fileMakerArgs);\n await makeDocumentModelGenDocumentModelFile(fileMakerArgs);\n await makeDocumentModelGenPhFactoriesFile(fileMakerArgs);\n await makeDocumentModelGenControllerFile(fileMakerArgs);\n\n const modules = fileMakerArgs.modules;\n\n for (const module of modules) {\n const operationsModuleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n await makeGenDirOperationModuleFiles({\n module,\n ...fileMakerArgs,\n ...operationsModuleVariableNames,\n });\n }\n}\n\nasync function makeGenDirOperationModuleFiles(\n fileMakerArgs: DocumentModelTemplateInputsWithModule,\n) {\n await makeOperationModuleGenActionsFile(fileMakerArgs);\n await makeOperationModuleGenCreatorsFile(fileMakerArgs);\n await makeOperationModuleGenOperationsFile(fileMakerArgs);\n await makeOperationModuleGenErrorFile(fileMakerArgs);\n}\n\nasync function makeDocumentModelGenUtilsFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenUtilsTemplate(args);\n const { project, genDirPath } = args;\n const utilsFilePath = path.join(genDirPath, \"utils.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, utilsFilePath);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelDocumentTypeFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelDocumentTypeTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"document-type.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSchemaIndexFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelSchemaIndexTemplate;\n const { project, schemaDirPath } = args;\n const filePath = path.join(schemaDirPath, \"index.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenTypesFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenTypesTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"types.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenDocumentModelFile(\n args: DocumentModelFileMakerArgs,\n) {\n const { project, genDirPath, documentModelState } = args;\n const filePath = path.join(genDirPath, \"document-model.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n\n sourceFile.addImportDeclaration({\n namedImports: [\"DocumentModelGlobalState\"],\n moduleSpecifier: \"document-model\",\n isTypeOnly: true,\n });\n\n const documentModelStateString = buildObjectLiteral(\n documentModelState,\n sourceFile,\n );\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: \"documentModel\",\n type: \"DocumentModelGlobalState\",\n initializer: documentModelStateString,\n },\n ],\n });\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenDocumentSchemaFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelDocumentSchemaFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"document-schema.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenCreatorsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenCreatorsFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"creators.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenPhFactoriesFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelPhFactoriesFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"ph-factories.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenControllerFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenControllerFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"controller.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenIndexFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenIndexFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenActionsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenActionsFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenReducerFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenReducerFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"reducer.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenActionsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const { actions } = getDocumentModelOperationsModuleVariableNames(module);\n const pascalCaseModuleName = pascalCase(module.name);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationModuleActionsFileTemplate({\n ...args,\n actions,\n pascalCaseModuleName,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenCreatorsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleCreatorsFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"creators.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenOperationsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleOperationsFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"operations.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenErrorFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleErrorFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n\n const filePath = path.join(dirPath, \"error.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import { directoryExists, fileExists } from \"@powerhousedao/shared/clis\";\nimport { copyFile, mkdir, readdir, rename } from \"node:fs/promises\";\nimport path from \"path\";\n\n/**\n * Detects whether a document model directory has a legacy (non-versioned)\n * structure and migrates it to the versioned layout expected by `--use-versioning`.\n *\n * Detection: a directory is \"legacy\" when `src/reducers/` exists at root level\n * AND no `v1/` directory exists yet.\n *\n * Migration steps:\n * 1. Move legacy root-level items (`gen/`, `src/`, `tests/`, and known root files)\n * into a `legacy/` subfolder for reference / backup.\n * 2. Copy custom source files (reducers, tests, utils) from `legacy/` into the\n * soon-to-be-created `v1/` directory so that ts-morph picks them up during\n * generation and preserves business logic.\n *\n * This function is idempotent — calling it on an already-migrated directory is a\n * no-op.\n */\nexport async function migrateLegacyToVersioned(\n documentModelDirPath: string,\n): Promise<void> {\n const srcReducersPath = path.join(documentModelDirPath, \"src\", \"reducers\");\n const v1Path = path.join(documentModelDirPath, \"v1\");\n const legacyPath = path.join(documentModelDirPath, \"legacy\");\n\n // Detection: only migrate if legacy structure exists and v1 doesn't\n const hasSrcReducers = await directoryExists(srcReducersPath);\n const hasV1 = await directoryExists(v1Path);\n\n if (!hasSrcReducers || hasV1) {\n return;\n }\n\n console.log(\n `[migrate-legacy] Detected legacy structure in ${documentModelDirPath}`,\n );\n\n // Step 1: Create legacy directory\n await mkdir(legacyPath, { recursive: true });\n\n // Step 2: Move known root-level items into legacy/\n const dirsToMove = [\"gen\", \"src\", \"tests\"];\n const filesToMove = [\n \"module.ts\",\n \"actions.ts\",\n \"hooks.ts\",\n \"utils.ts\",\n \"index.ts\",\n \"schema.graphql\",\n ];\n\n for (const dirName of dirsToMove) {\n const srcPath = path.join(documentModelDirPath, dirName);\n if (await directoryExists(srcPath)) {\n const destPath = path.join(legacyPath, dirName);\n await rename(srcPath, destPath);\n console.log(`[migrate-legacy] Moved ${dirName}/ → legacy/${dirName}/`);\n }\n }\n\n for (const fileName of filesToMove) {\n const srcPath = path.join(documentModelDirPath, fileName);\n if (await fileExists(srcPath)) {\n const destPath = path.join(legacyPath, fileName);\n await rename(srcPath, destPath);\n console.log(`[migrate-legacy] Moved ${fileName} → legacy/${fileName}`);\n }\n }\n\n // Step 3: Copy custom source files into v1/ so ts-morph finds them\n const v1SrcReducersPath = path.join(v1Path, \"src\", \"reducers\");\n const v1SrcPath = path.join(v1Path, \"src\");\n const v1TestsPath = path.join(v1Path, \"tests\");\n\n // Copy legacy/src/reducers/*.ts → v1/src/reducers/\n const legacySrcReducersPath = path.join(legacyPath, \"src\", \"reducers\");\n if (await directoryExists(legacySrcReducersPath)) {\n await mkdir(v1SrcReducersPath, { recursive: true });\n await copyDirectoryFiles(legacySrcReducersPath, v1SrcReducersPath);\n console.log(`[migrate-legacy] Copied src/reducers/ → v1/src/reducers/`);\n }\n\n // Copy legacy/src/tests/*.ts → v1/src/tests/ (if exists)\n const legacySrcTestsPath = path.join(legacyPath, \"src\", \"tests\");\n if (await directoryExists(legacySrcTestsPath)) {\n const v1SrcTestsPath = path.join(v1SrcPath, \"tests\");\n await mkdir(v1SrcTestsPath, { recursive: true });\n await copyDirectoryFiles(legacySrcTestsPath, v1SrcTestsPath);\n console.log(`[migrate-legacy] Copied src/tests/ → v1/src/tests/`);\n }\n\n // Copy legacy/tests/*.ts → v1/tests/ (if exists)\n const legacyTestsPath = path.join(legacyPath, \"tests\");\n if (await directoryExists(legacyTestsPath)) {\n await mkdir(v1TestsPath, { recursive: true });\n await copyDirectoryFiles(legacyTestsPath, v1TestsPath);\n console.log(`[migrate-legacy] Copied tests/ → v1/tests/`);\n }\n\n // Copy legacy/src/utils.ts → v1/src/utils.ts (if exists)\n const legacyUtilsPath = path.join(legacyPath, \"src\", \"utils.ts\");\n if (await fileExists(legacyUtilsPath)) {\n await mkdir(v1SrcPath, { recursive: true });\n await copyFile(legacyUtilsPath, path.join(v1SrcPath, \"utils.ts\"));\n console.log(`[migrate-legacy] Copied src/utils.ts → v1/src/utils.ts`);\n }\n\n console.log(\n `[migrate-legacy] Migration complete for ${documentModelDirPath}`,\n );\n}\n\n/** Copy all files (non-recursive) from srcDir to destDir */\nasync function copyDirectoryFiles(\n srcDir: string,\n destDir: string,\n): Promise<void> {\n const entries = await readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n await copyFile(\n path.join(srcDir, entry.name),\n path.join(destDir, entry.name),\n );\n }\n }\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport path from \"path\";\nimport {\n documentModelHooksFileTemplate,\n documentModelIndexTemplate,\n documentModelModuleFileTemplate,\n documentModelRootActionsFileTemplate,\n documentModelUtilsTemplate,\n} from \"templates\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\n\nexport async function makeRootDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelVersionIndexFile(fileMakerArgs);\n await makeDocumentModelRootActionsFile(fileMakerArgs);\n await makeDocumentModelModuleFile(fileMakerArgs);\n await makeDocumentModelUtilsFile(fileMakerArgs);\n await makeDocumentModelHooksFile(fileMakerArgs);\n}\n\nasync function makeDocumentModelVersionIndexFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelIndexTemplate;\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelUtilsFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelUtilsTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"utils.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelRootActionsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelRootActionsFileTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelHooksFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelHooksFileTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"hooks.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelModuleFile(args: DocumentModelFileMakerArgs) {\n const { project, documentModelVersionDirPath } = args;\n const template = documentModelModuleFileTemplate(args);\n\n const moduleFilePath = path.join(documentModelVersionDirPath, \"module.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, moduleFilePath);\n\n sourceFile.replaceWithText(template);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport type { ModuleSpecification } from \"@powerhousedao/shared/document-model\";\nimport { ts } from \"@tmpl/core\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport path from \"path\";\nimport {\n documentModelSrcIndexFileTemplate,\n documentModelSrcUtilsTemplate,\n} from \"templates\";\nimport type { SourceFile } from \"ts-morph\";\nimport { VariableDeclarationKind } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getObjectLiteral,\n getOrCreateSourceFile,\n getPreviousVersionSourceFile,\n} from \"utils\";\n\nexport async function makeSrcDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelSrcIndexFile(fileMakerArgs);\n await makeDocumentModelSrcUtilsFile(fileMakerArgs);\n await makeReducerOperationHandlersForModules(fileMakerArgs);\n}\n\nasync function makeReducerOperationHandlersForModules(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n const { modules } = fileMakerArgs;\n for (const module of modules) {\n await makeReducerOperationHandlerForModule({\n ...fileMakerArgs,\n module,\n });\n }\n}\n\nasync function makeReducerOperationHandlerForModule({\n project,\n module,\n version,\n reducersDirPath,\n pascalCaseDocumentType,\n camelCaseDocumentType,\n versionedDocumentModelPackageImportPath,\n}: DocumentModelFileMakerArgs & { module: ModuleSpecification }) {\n const kebabCaseModuleName = kebabCase(module.name);\n const pascalCaseModuleName = pascalCase(module.name);\n const filePath = path.join(reducersDirPath, `${kebabCaseModuleName}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (!alreadyExists) {\n const previousVersionFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n if (previousVersionFile) {\n sourceFile.replaceWithText(previousVersionFile.getText());\n }\n }\n const operationsInterfaceTypeName = `${pascalCaseDocumentType}${pascalCaseModuleName}Operations`;\n const operationsInterfaceVariableName = `${camelCaseDocumentType}${pascalCaseModuleName}Operations`;\n\n const existingOperationsInterfaceTypeImport = sourceFile.getImportDeclaration(\n (importDeclaration) =>\n !!importDeclaration\n .getNamedImports()\n .find(\n (importSpecifier) =>\n importSpecifier.getName() === operationsInterfaceTypeName,\n ),\n );\n if (existingOperationsInterfaceTypeImport) {\n existingOperationsInterfaceTypeImport.remove();\n }\n\n const operationsInterfaceTypeImport = sourceFile.addImportDeclaration({\n namedImports: [operationsInterfaceTypeName],\n moduleSpecifier: versionedDocumentModelPackageImportPath,\n isTypeOnly: true,\n });\n\n const operationsInterfaceTypeProperties = operationsInterfaceTypeImport\n .getNamedImports()\n .find((value) => value.getName() === operationsInterfaceTypeName)\n ?.getNameNode()\n .getType()\n .getProperties()\n .map((symbol) => symbol.getName());\n\n if (!operationsInterfaceTypeProperties) {\n throw new Error(\"Failed to create operation handler object\");\n }\n\n let operationsInterfaceVariableStatement = sourceFile.getVariableStatement(\n operationsInterfaceVariableName,\n );\n\n if (!operationsInterfaceVariableStatement) {\n operationsInterfaceVariableStatement = sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: operationsInterfaceVariableName,\n type: operationsInterfaceTypeName,\n initializer: \"{}\",\n },\n ],\n });\n }\n\n const operationsInterfaceObject = getObjectLiteral(\n operationsInterfaceVariableStatement,\n );\n\n if (!operationsInterfaceObject) {\n throw new Error(\"Failed to build reducer object\");\n }\n\n // Build a lookup map from method name to operation spec to access reducer code\n const operationsByMethodName = new Map<\n string,\n (typeof module.operations)[number]\n >();\n for (const operation of module.operations) {\n if (operation.name) {\n const methodName = `${camelCase(operation.name)}Operation`;\n operationsByMethodName.set(methodName, operation);\n }\n }\n\n for (const name of operationsInterfaceTypeProperties) {\n if (operationsInterfaceObject.getProperty(name)) continue;\n\n const operationSpec = operationsByMethodName.get(name);\n const reducerCode = operationSpec?.reducer?.trim();\n\n operationsInterfaceObject.addMethod({\n name,\n parameters: [{ name: \"state\" }, { name: \"action\" }],\n statements: reducerCode\n ? [reducerCode]\n : [\n `// TODO: implement ${name} reducer`,\n ts`throw new Error(\"Reducer for '${name}' not implemented.\")`.raw,\n ],\n });\n }\n\n // Add error imports for error classes referenced in reducer code\n addErrorImportsForModule(sourceFile, module);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSrcIndexFile({\n project,\n ...variableNames\n}: DocumentModelFileMakerArgs) {\n const template = documentModelSrcIndexFileTemplate;\n const { srcDirPath } = variableNames;\n\n const filePath = path.join(srcDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSrcUtilsFile({\n project,\n srcDirPath,\n version,\n}: DocumentModelFileMakerArgs) {\n const template = documentModelSrcUtilsTemplate;\n\n const filePath = path.join(srcDirPath, \"utils.ts\");\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (!alreadyExists) {\n const previousVersionSourceFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n\n if (previousVersionSourceFile) {\n sourceFile.replaceWithText(previousVersionSourceFile.getText());\n } else {\n sourceFile.replaceWithText(template);\n }\n }\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction addErrorImportsForModule(\n sourceFile: SourceFile,\n module: ModuleSpecification,\n): void {\n // Collect all unique errors from all operations in this module\n const allErrors: { name: string }[] = [];\n for (const operation of module.operations) {\n if (Array.isArray(operation.errors)) {\n for (const error of operation.errors) {\n if (error.name && !allErrors.find((e) => e.name === error.name)) {\n allErrors.push({ name: error.name });\n }\n }\n }\n }\n\n if (allErrors.length === 0) return;\n\n // Scan the source file content to find which error classes are actually referenced\n const sourceFileContent = sourceFile.getFullText();\n const usedErrors: string[] = [];\n\n for (const error of allErrors) {\n const errorPattern = new RegExp(`\\\\b${error.name}\\\\b`, \"g\");\n if (errorPattern.test(sourceFileContent)) {\n usedErrors.push(error.name);\n }\n }\n\n if (usedErrors.length === 0) return;\n\n const errorImportPath = `../../gen/${kebabCase(module.name)}/error.js`;\n\n const existingErrorImport = sourceFile\n .getImportDeclarations()\n .find(\n (importDecl) => importDecl.getModuleSpecifierValue() === errorImportPath,\n );\n\n if (existingErrorImport) {\n const existingNamedImports = existingErrorImport\n .getNamedImports()\n .map((namedImport) => namedImport.getName());\n\n const newErrorsToImport = usedErrors.filter(\n (errorName) => !existingNamedImports.includes(errorName),\n );\n\n if (newErrorsToImport.length > 0) {\n existingErrorImport.addNamedImports(newErrorsToImport);\n }\n } else {\n sourceFile.addImportDeclaration({\n namedImports: usedErrors,\n moduleSpecifier: errorImportPath,\n });\n }\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport type { ModuleSpecification } from \"@powerhousedao/shared/document-model\";\nimport { ts } from \"@tmpl/core\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { getDocumentModelOperationsModuleVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport {\n documentModelTestFileTemplate,\n makeActionImportNames,\n makeTestCaseForAction,\n} from \"templates\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n getPreviousVersionSourceFile,\n} from \"utils\";\n\nexport async function makeTestsDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelTestFile(fileMakerArgs);\n const modules = fileMakerArgs.modules;\n\n for (const module of modules) {\n await makeOperationModuleTestFile({ ...fileMakerArgs, module });\n }\n}\n\nasync function makeOperationModuleTestFile(\n args: DocumentModelFileMakerArgs & { module: ModuleSpecification },\n) {\n const {\n project,\n module,\n version,\n testsDirPath,\n documentModelPackageImportPath,\n versionedDocumentModelPackageImportPath,\n isPhDocumentOfTypeFunctionName,\n } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const { actions } = moduleVariableNames;\n const kebabCaseModuleName = kebabCase(module.name);\n const pascalCaseModuleName = pascalCase(module.name);\n const moduleOperationsTypeName = `${pascalCaseModuleName}Operations`;\n const filePath = path.join(testsDirPath, `${kebabCaseModuleName}.test.ts`);\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (!alreadyExists) {\n const previousVersionSourceFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n\n if (previousVersionSourceFile) {\n sourceFile.replaceWithText(previousVersionSourceFile.getText());\n } else {\n sourceFile.replaceWithText(\n ts`\n import { generateMock } from \"document-model\";\n import { describe, expect, it } from \"vitest\";\n\n describe(\"${moduleOperationsTypeName}\", () => {\n\n });\n `.raw,\n );\n }\n }\n\n const importNames = makeActionImportNames({\n ...args,\n ...moduleVariableNames,\n });\n\n const namedImports = importNames.map((name) => ({ name }));\n\n let actionsImportDeclaration = sourceFile\n .getImportDeclarations()\n .filter((i) => !i.isTypeOnly())\n .find((importDeclaration) =>\n importDeclaration\n .getModuleSpecifier()\n .getText()\n .includes(documentModelPackageImportPath),\n );\n\n if (!actionsImportDeclaration) {\n actionsImportDeclaration = sourceFile.addImportDeclaration({\n namedImports,\n moduleSpecifier: versionedDocumentModelPackageImportPath,\n });\n } else {\n actionsImportDeclaration.setModuleSpecifier(\n versionedDocumentModelPackageImportPath,\n );\n const existingNamedImports = actionsImportDeclaration\n .getNamedImports()\n .map((value) => value.getName());\n\n for (const name of importNames) {\n if (!existingNamedImports.includes(name)) {\n actionsImportDeclaration.addNamedImport(name);\n }\n }\n }\n\n const describeCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((call) => {\n const expressionText = call.getExpression().getText();\n const args = call.getArguments();\n const firstArg = args[0];\n return (\n expressionText === \"describe\" &&\n pascalCase(firstArg.getText()).includes(moduleOperationsTypeName)\n );\n });\n\n if (!describeCall) {\n console.error(\n `Test file at path ${filePath} has no describe block for ${moduleOperationsTypeName}`,\n );\n return;\n }\n\n const describeCallBody = describeCall\n .getArguments()[1]\n .asKindOrThrow(SyntaxKind.ArrowFunction);\n\n const testCaseNames = describeCall\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((call) => {\n const expressionText = call.getExpression().getText();\n return expressionText === \"it\" || expressionText === \"test\";\n })\n .map((c) => c.getArguments()[0].getText());\n\n const actionsWithoutExistingTestCases = actions.filter((action) => {\n const camelCaseActionName = camelCase(action.name);\n return !testCaseNames.some((c) => c.includes(camelCaseActionName));\n });\n\n const testCasesToAdd = actionsWithoutExistingTestCases.map((action) =>\n makeTestCaseForAction(action, isPhDocumentOfTypeFunctionName),\n );\n\n describeCallBody.addStatements(testCasesToAdd);\n\n const GENERATE_MOCK_NAME = \"generateMock\";\n const GENERATE_MOCK_MODULE_SPECIFIER = \"@powerhousedao/codegen\";\n\n const generateMockImport = sourceFile.getImportDeclaration((i) =>\n i.getNamedImports().some((v) => v.getText().includes(GENERATE_MOCK_NAME)),\n );\n\n const hasGenerateMockInSourceFile = sourceFile\n .getText()\n .includes(GENERATE_MOCK_NAME);\n\n if (hasGenerateMockInSourceFile && !generateMockImport) {\n sourceFile.addImportDeclaration({\n namedImports: [GENERATE_MOCK_NAME],\n moduleSpecifier: GENERATE_MOCK_MODULE_SPECIFIER,\n });\n }\n\n sourceFile.fixUnusedIdentifiers();\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelTestFile(args: DocumentModelFileMakerArgs) {\n const { project, testsDirPath } = args;\n const template = documentModelTestFileTemplate(args);\n\n const filePath = path.join(testsDirPath, \"document-model.test.ts\");\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import path from \"path\";\nimport { upgradeManifestTemplate, upgradeTransitionTemplate } from \"templates\";\nimport { VariableDeclarationKind, type Project } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getObjectLiteral,\n getOrCreateSourceFile,\n getVariableDeclarationByTypeName,\n} from \"utils\";\n\ntype MakeUpgradeFileArgs = {\n project: Project;\n version: number;\n upgradesDirPath: string;\n documentModelPackageImportPath: string;\n phStateName: string;\n};\nexport async function makeUpgradeFile(args: MakeUpgradeFileArgs) {\n const {\n project,\n version,\n upgradesDirPath,\n documentModelPackageImportPath,\n phStateName,\n } = args;\n if (version < 2) return;\n\n const filePath = path.join(upgradesDirPath, `v${version}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n const previousVersion = version - 1;\n const template = upgradeTransitionTemplate({\n version,\n previousVersion,\n documentModelPackageImportPath,\n phStateName,\n });\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nexport async function createOrUpdateUpgradeManifestFile(args: {\n project: Project;\n specVersions: number[];\n latestVersion: number;\n upgradesDirPath: string;\n documentModelId: string;\n upgradeManifestName: string;\n}) {\n const {\n project,\n specVersions,\n upgradesDirPath,\n documentModelId,\n upgradeManifestName,\n } = args;\n const filePath = path.join(upgradesDirPath, \"upgrade-manifest.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n const template = upgradeManifestTemplate({\n documentModelId,\n upgradeManifestName,\n });\n\n sourceFile.replaceWithText(template);\n\n const upgradeTransitionImports = buildUpgradeTransitionImports(specVersions);\n\n sourceFile.addImportDeclarations(upgradeTransitionImports);\n\n const upgradeManifestStatement = getVariableDeclarationByTypeName(\n sourceFile,\n \"UpgradeManifest\",\n )?.getVariableStatementOrThrow();\n const objectLiteral = getObjectLiteral(upgradeManifestStatement);\n const upgradesProperty = objectLiteral?.getProperty(\"upgrades\");\n const upgrades = buildUpgrades(specVersions);\n upgradesProperty?.replaceWithText(upgrades);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction buildUpgrades(specVersions: number[]) {\n const upgradeStrings: string[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n upgradeStrings.push(`v${version}`);\n }\n\n return `upgrades: { ${upgradeStrings.join(\",\\n\")} }`;\n}\n\nfunction buildUpgradeTransitionImports(specVersions: number[]) {\n const imports: {\n namedImports: string[];\n moduleSpecifier: string;\n }[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n const namedImports = [`v${version}`];\n const moduleSpecifier = `./v${version}.js`;\n imports.push({\n namedImports,\n moduleSpecifier,\n });\n }\n\n return imports;\n}\n\ntype MakeVersionConstantsFileArgs = {\n project: Project;\n upgradesDirPath: string;\n specVersions: number[];\n latestVersion: number;\n};\nexport async function createOrUpdateVersionConstantsFile({\n specVersions,\n latestVersion,\n project,\n upgradesDirPath,\n}: MakeVersionConstantsFileArgs) {\n const SUPPORTED_VERSIONS = \"supportedVersions\";\n const LATEST_VERSION = \"latestVersion\";\n const filePath = path.join(upgradesDirPath, \"versions.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(\"\");\n\n const latestVersionIndex = specVersions.indexOf(latestVersion);\n const versionInitializer = `[${specVersions.join(\", \")}] as const;`;\n const latestInitializer = `${SUPPORTED_VERSIONS}[${latestVersionIndex}];`;\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: SUPPORTED_VERSIONS,\n initializer: versionInitializer,\n },\n ],\n });\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: LATEST_VERSION,\n initializer: latestInitializer,\n },\n ],\n });\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeUpgradesIndexFileArgs = {\n project: Project;\n upgradesDirPath: string;\n upgradeManifestName: string;\n specVersions: number[];\n};\nexport async function makeUpgradesIndexFile({\n project,\n upgradesDirPath,\n specVersions,\n upgradeManifestName,\n}: MakeUpgradesIndexFileArgs) {\n const filePath = path.join(upgradesDirPath, \"index.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(\"\");\n\n const upgradeReducerExports = makeUpgradeReducerExports(specVersions);\n\n sourceFile.addExportDeclarations([\n {\n namedExports: [upgradeManifestName],\n moduleSpecifier: \"./upgrade-manifest.js\",\n },\n {\n namedExports: [\"supportedVersions\", \"latestVersion\"],\n moduleSpecifier: \"./versions.js\",\n },\n ...upgradeReducerExports,\n ]);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction makeUpgradeReducerExports(specVersions: number[]) {\n const exports: {\n namedExports: string[];\n moduleSpecifier: string;\n }[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n const namedExports = [`v${version}`];\n const moduleSpecifier = `./v${version}.js`;\n exports.push({\n namedExports,\n moduleSpecifier,\n });\n }\n\n return exports;\n}\n","import type {\n DocumentModelFileMakerArgs,\n DocumentModelVariableNames,\n GenerateDocumentModelArgs,\n} from \"@powerhousedao/codegen\";\nimport { directoryExists, fileExists } from \"@powerhousedao/shared/clis\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport { kebabCase } from \"change-case\";\nimport {\n getDocumentModelDirName,\n getDocumentModelVariableNames,\n} from \"name-builders\";\nimport { copyFile, mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport path from \"path\";\nimport { type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getInitialStates,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { generateDocumentModelZodSchemas } from \"../../codegen/graphql.js\";\nimport {\n makeDocumentModelModulesFile,\n makeUpgradeManifestsFile,\n} from \"../module-files.js\";\nimport { makeGenDirFiles } from \"./gen-dir.js\";\nimport { migrateLegacyToVersioned } from \"./migrate-legacy.js\";\nimport { makeRootDirFiles } from \"./root-dir.js\";\nimport { makeSrcDirFiles } from \"./src-dir.js\";\nimport { makeTestsDirFiles } from \"./tests-dir.js\";\nimport {\n createOrUpdateUpgradeManifestFile,\n createOrUpdateVersionConstantsFile,\n makeUpgradeFile,\n makeUpgradesIndexFile,\n} from \"./upgrades-dir.js\";\n\n/** Generates a document model from the given `documentModelState`\n *\n * If `useVersioning` is set to true, it will generate versioned document model code\n * for each `specification` in the `documentModelState`\n */\nexport async function tsMorphGenerateDocumentModel({\n projectDir,\n documentModelState,\n useVersioning,\n migrateLegacy,\n}: GenerateDocumentModelArgs) {\n if (migrateLegacy) {\n const dmDirPath = path.join(\n projectDir,\n \"document-models\",\n getDocumentModelDirName(documentModelState),\n );\n await migrateLegacyToVersioned(dmDirPath);\n }\n\n const project = buildTsMorphProject(projectDir);\n const documentModelsSourceFilesPath = path.join(\n projectDir,\n \"document-models/**/*\",\n );\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const documentModelDirName = getDocumentModelDirName(documentModelState);\n const documentModelDirPath = path.join(\n documentModelsDirPath,\n documentModelDirName,\n );\n const upgradesDirPath = path.join(documentModelDirPath, \"upgrades\");\n const documentModelVariableNames = getDocumentModelVariableNames(\n documentModelState.name,\n );\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n documentModelDirPath,\n );\n if (useVersioning) {\n await ensureDirectoriesExist(project, upgradesDirPath);\n }\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n\n const documentModelPackageImportPath = path.join(\n \"document-models\",\n documentModelDirName,\n );\n\n const specVersions = [\n ...new Set([\n ...documentModelState.specifications.map((spec) => spec.version),\n ]),\n ].toSorted();\n\n if (specVersions.length !== documentModelState.specifications.length) {\n throw new Error(\n \"Document model specifications array is misconfigured. Length is not match with spec versions.\",\n );\n }\n\n const latestVersion = specVersions[specVersions.length - 1];\n if (\n documentModelState.specifications[\n documentModelState.specifications.length - 1\n ].version !== latestVersion\n ) {\n throw new Error(\n \"Document model has incorrect version at the latest version index\",\n );\n }\n\n await writeDocumentModelStateJsonFile({\n documentModelState,\n documentModelDirName,\n documentModelDirPath,\n });\n\n if (useVersioning) {\n await Promise.all(\n specVersions.map(\n async (version) =>\n await generateDocumentModelForSpec({\n project,\n version,\n useVersioning: true,\n documentModelState,\n projectDir,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n }),\n ),\n );\n\n for (const version of specVersions) {\n await makeUpgradeFile({\n version,\n upgradesDirPath,\n project,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n });\n }\n\n await makeDocumentModelIndexFile({\n project,\n documentModelDirPath,\n latestVersion,\n });\n\n await createOrUpdateVersionConstantsFile({\n project,\n specVersions,\n latestVersion,\n upgradesDirPath,\n });\n\n await createOrUpdateUpgradeManifestFile({\n project,\n specVersions,\n latestVersion,\n upgradesDirPath,\n documentModelId: documentModelState.id,\n ...documentModelVariableNames,\n });\n\n await makeUpgradesIndexFile({\n project,\n upgradesDirPath,\n specVersions,\n ...documentModelVariableNames,\n });\n } else {\n await generateDocumentModelForSpec({\n project,\n useVersioning: false,\n version: latestVersion,\n documentModelState,\n projectDir,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n });\n }\n\n await project.save();\n}\n\ntype GenerateDocumentModelFromSpecArgs = {\n project: Project;\n version: number;\n useVersioning: boolean;\n documentModelState: DocumentModelGlobalState;\n projectDir: string;\n documentModelPackageImportPath: string;\n documentModelsDirPath: string;\n documentModelDirName: string;\n documentModelDirPath: string;\n} & DocumentModelVariableNames;\n/** Generates document model code for a given `specification` from a `documentModelState` object */\nasync function generateDocumentModelForSpec({\n project,\n projectDir,\n documentModelState,\n documentModelPackageImportPath,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n useVersioning,\n version,\n ...documentModelVariableNames\n}: GenerateDocumentModelFromSpecArgs) {\n const specification = documentModelState.specifications.find(\n (spec) => spec.version === version,\n );\n\n if (!specification) {\n throw new Error(\n `Document model specifications array is misconfigured, no specification found for version: ${version}`,\n );\n }\n\n const versionDirName = useVersioning ? `v${version}` : \"\";\n\n const documentModelVersionDirName = path.join(\n documentModelDirName,\n versionDirName,\n );\n\n const documentModelVersionDirPath = path.join(\n documentModelDirPath,\n versionDirName,\n );\n\n const versionedDocumentModelPackageImportPath = path.join(\n documentModelPackageImportPath,\n versionDirName,\n );\n\n const fileExtension = documentModelState.extension;\n const documentTypeId = documentModelState.id;\n const srcDirPath = path.join(documentModelVersionDirPath, \"src\");\n const reducersDirPath = path.join(srcDirPath, \"reducers\");\n const testsDirPath = path.join(documentModelVersionDirPath, \"tests\");\n const genDirPath = path.join(documentModelVersionDirPath, \"gen\");\n const schemaDirPath = path.join(genDirPath, \"schema\");\n const { initialGlobalState, initialLocalState } = getInitialStates(\n specification.state,\n );\n const hasLocalSchema = specification.state.local.schema !== \"\";\n const modules = specification.modules;\n const moduleDirPaths = modules.map((module) =>\n path.join(genDirPath, kebabCase(module.name)),\n );\n\n await ensureDirectoriesExist(\n project,\n documentModelVersionDirPath,\n reducersDirPath,\n testsDirPath,\n schemaDirPath,\n ...moduleDirPaths,\n );\n\n const fileMakerArgs: DocumentModelFileMakerArgs = {\n project,\n projectDir,\n version,\n useVersioning,\n documentTypeId,\n documentModelState,\n initialGlobalState,\n initialLocalState,\n modules,\n hasLocalSchema,\n documentModelsDirPath,\n documentModelDirPath,\n documentModelDirName,\n documentModelVersionDirName,\n documentModelVersionDirPath,\n documentModelPackageImportPath,\n versionedDocumentModelPackageImportPath,\n srcDirPath,\n genDirPath,\n testsDirPath,\n schemaDirPath,\n reducersDirPath,\n fileExtension,\n ...documentModelVariableNames,\n };\n\n await generateDocumentModelZodSchemas({\n documentModelDirPath: documentModelVersionDirPath,\n specification,\n });\n\n await makeRootDirFiles(fileMakerArgs);\n await makeGenDirFiles(fileMakerArgs);\n await makeSrcDirFiles(fileMakerArgs);\n await makeTestsDirFiles(fileMakerArgs);\n await makeDocumentModelModulesFile(fileMakerArgs);\n\n if (!useVersioning) return;\n\n await makeUpgradeManifestsFile({\n project,\n projectDir,\n });\n\n const previousVersionDirPath = getPreviousVersionDirPath(\n documentModelDirPath,\n version,\n );\n\n if (!previousVersionDirPath) return;\n\n await persistCustomFilesFromPreviousVersion({\n currentVersionDirPath: documentModelVersionDirPath,\n previousVersionDirPath,\n });\n}\n\n/** Writes a json file derived from a `documentModelState` */\nasync function writeDocumentModelStateJsonFile({\n documentModelState,\n documentModelDirName,\n documentModelDirPath,\n}: {\n documentModelState: DocumentModelGlobalState;\n documentModelDirPath: string;\n documentModelDirName: string;\n}) {\n const filePath = path.join(\n documentModelDirPath,\n `${documentModelDirName}.json`,\n );\n const documentModelStateJson = JSON.stringify(documentModelState, null, 2);\n await writeFile(filePath, documentModelStateJson);\n}\n\nfunction getPreviousVersionDirPath(\n documentModelDirPath: string,\n version: number,\n) {\n const previousVersion = version - 1;\n if (previousVersion < 1) return;\n\n const previousVersionDirName = `v${previousVersion}`;\n\n return path.join(documentModelDirPath, previousVersionDirName);\n}\n\nasync function makeDocumentModelIndexFile(args: {\n project: Project;\n documentModelDirPath: string;\n latestVersion: number;\n}) {\n const { project, documentModelDirPath, latestVersion } = args;\n\n const filePath = path.join(documentModelDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n sourceFile.addExportDeclarations([\n { moduleSpecifier: `./v${latestVersion}/index.js` },\n { moduleSpecifier: `./upgrades/index.js` },\n ]);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype PersistCustomFilesFromPreviousVersionArgs = {\n currentVersionDirPath: string;\n previousVersionDirPath: string;\n};\nasync function persistCustomFilesFromPreviousVersion(\n args: PersistCustomFilesFromPreviousVersionArgs,\n) {\n const { currentVersionDirPath, previousVersionDirPath } = args;\n\n const previousVersionDirExists = await directoryExists(\n previousVersionDirPath,\n );\n\n if (!previousVersionDirExists) return;\n\n const previousVersionDirContents = await readdir(previousVersionDirPath, {\n withFileTypes: true,\n recursive: true,\n });\n\n const previousVersionFiles = previousVersionDirContents\n .filter((dirEnt) => dirEnt.isFile())\n .map(({ name, parentPath }) => ({\n name,\n parentPath,\n relativePath: path.relative(previousVersionDirPath, parentPath),\n }));\n\n for (const { name, relativePath } of previousVersionFiles) {\n const filePathInCurrentVersionDir = path.join(\n currentVersionDirPath,\n relativePath,\n name,\n );\n const filePathInPreviousVersionDir = path.join(\n previousVersionDirPath,\n relativePath,\n name,\n );\n const existsInPreviousVersionDir = await fileExists(\n filePathInPreviousVersionDir,\n );\n const existsInCurrentVersionDir = await fileExists(\n filePathInCurrentVersionDir,\n );\n if (existsInPreviousVersionDir && !existsInCurrentVersionDir) {\n console.log(\n `Persisting file \"${path.join(relativePath, name)}\" from previous version directory.`,\n );\n await mkdir(path.join(currentVersionDirPath, relativePath), {\n recursive: true,\n });\n await copyFile(filePathInPreviousVersionDir, filePathInCurrentVersionDir);\n }\n }\n}\n","import path from \"path\";\nimport {\n analyticsFactoryTemplate,\n analyticsIndexTemplate,\n analyticsProcessorTemplate,\n} from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\nimport type { GenerateProcessorArgs } from \"./types.js\";\n\nexport async function tsMorphGenerateAnalyticsProcessor(\n args: GenerateProcessorArgs,\n) {\n const { project, documentTypes, pascalCaseName, dirPath, camelCaseName } =\n args;\n\n await makeIndexFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeProcessorFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeFactoryFile({\n project,\n pascalCaseName,\n camelCaseName,\n dirPath,\n documentTypes,\n });\n}\n\nasync function makeIndexFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = analyticsIndexTemplate;\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"index.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeProcessorFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = analyticsProcessorTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"processor.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeFactoryFile(v: {\n project: Project;\n pascalCaseName: string;\n camelCaseName: string;\n dirPath: string;\n documentTypes: string[];\n}) {\n const template = analyticsFactoryTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"factory.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import path from \"path\";\nimport {\n relationalDbFactoryTemplate,\n relationalDbIndexTemplate,\n relationalDbMigrationsTemplate,\n relationalDbProcessorTemplate,\n relationalDbSchemaTemplate,\n} from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\nimport type { GenerateProcessorArgs } from \"./types.js\";\n\nexport async function tsMorphGenerateRelationalDbProcessor(\n args: GenerateProcessorArgs,\n) {\n const { project, documentTypes, camelCaseName, pascalCaseName, dirPath } =\n args;\n\n await makeIndexFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeProcessorFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeFactoryFile({\n project,\n pascalCaseName,\n camelCaseName,\n dirPath,\n documentTypes,\n });\n\n await makeMigrationsFile({ project, dirPath });\n\n await makeSchemaFile({ project, dirPath });\n}\n\nasync function makeIndexFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = relationalDbIndexTemplate;\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"index.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeProcessorFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = relationalDbProcessorTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"processor.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeFactoryFile(v: {\n project: Project;\n pascalCaseName: string;\n camelCaseName: string;\n dirPath: string;\n documentTypes: string[];\n}) {\n const template = relationalDbFactoryTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"factory.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeSchemaFile(v: { project: Project; dirPath: string }) {\n const template = relationalDbSchemaTemplate();\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"schema.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeMigrationsFile(v: { project: Project; dirPath: string }) {\n const template = relationalDbMigrationsTemplate();\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"migrations.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type {\n ProcessorApp,\n ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport path from \"path\";\nimport { factoryBuildersTemplate } from \"templates\";\nimport type { SourceFile } from \"ts-morph\";\nimport { ts, type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { tsMorphGenerateAnalyticsProcessor } from \"./analytics.js\";\nimport { tsMorphGenerateRelationalDbProcessor } from \"./relational-db.js\";\n\nexport async function tsMorphGenerateProcessor(args: {\n processorName: string;\n documentTypes: string[];\n rootDir: string;\n processorType: \"relationalDb\" | \"analytics\";\n processorApps: ProcessorApps;\n}) {\n const {\n processorName,\n documentTypes,\n rootDir,\n processorType,\n processorApps,\n } = args;\n const kebabCaseName = kebabCase(processorName);\n const camelCaseName = camelCase(processorName);\n const pascalCaseName = pascalCase(processorName);\n const processorsDirPath = path.join(rootDir, \"processors\");\n const dirPath = path.join(processorsDirPath, kebabCaseName);\n const sourceFilesPath = path.join(processorsDirPath, \"**/*\");\n const project = buildTsMorphProject(rootDir);\n await ensureDirectoriesExist(project, processorsDirPath, dirPath);\n project.addSourceFilesAtPaths(sourceFilesPath);\n\n if (processorType === \"analytics\") {\n await tsMorphGenerateAnalyticsProcessor({\n processorName,\n documentTypes,\n rootDir,\n camelCaseName,\n dirPath,\n kebabCaseName,\n pascalCaseName,\n processorsDirPath,\n project,\n });\n } else {\n await tsMorphGenerateRelationalDbProcessor({\n processorName,\n documentTypes,\n rootDir,\n camelCaseName,\n dirPath,\n kebabCaseName,\n pascalCaseName,\n processorsDirPath,\n project,\n });\n }\n\n for (const processorApp of processorApps) {\n await updateFactoryBuildersFile({\n processorsDirPath,\n processorApp,\n project,\n camelCaseName,\n kebabCaseName,\n });\n }\n await project.save();\n}\n\nasync function updateFactoryBuildersFile(v: {\n project: Project;\n processorsDirPath: string;\n processorApp: ProcessorApp;\n camelCaseName: string;\n kebabCaseName: string;\n}) {\n const {\n project,\n processorsDirPath,\n processorApp,\n camelCaseName,\n kebabCaseName,\n } = v;\n const template = factoryBuildersTemplate;\n const filePath = path.join(processorsDirPath, `${processorApp}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (!alreadyExists) {\n sourceFile.replaceWithText(template);\n }\n const name = `${camelCaseName}FactoryBuilder`;\n const moduleSpecifier = path.join(\"processors\", kebabCaseName);\n\n const factoriesArrayName = \"processorFactoryBuilders\";\n\n let factoryBuildersArray = getFactoryBuildersArray(\n sourceFile,\n factoriesArrayName,\n );\n\n if (!factoryBuildersArray) {\n sourceFile.replaceWithText(template);\n factoryBuildersArray = getFactoryBuildersArray(\n sourceFile,\n factoriesArrayName,\n );\n }\n\n if (!factoryBuildersArray) {\n throw new Error(\n `Could not get factory builders array in file ${processorApp}.ts`,\n );\n }\n\n const importDeclaration = sourceFile\n .getImportDeclarations()\n .flatMap((importDeclaration) =>\n importDeclaration.getNamedImports().map((n) => n.getText()),\n )\n .find((n) => n === name);\n\n if (!importDeclaration) {\n sourceFile.addImportDeclaration({\n namedImports: [name],\n moduleSpecifier,\n });\n }\n\n const arrayElements = factoryBuildersArray\n .getElements()\n .map((e) => e.getText());\n\n if (!arrayElements.includes(name)) {\n factoryBuildersArray.addElement(name);\n }\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction getFactoryBuildersArray(sourceFile: SourceFile, name: string) {\n return sourceFile\n .getDescendantsOfKind(ts.SyntaxKind.VariableStatement)\n .flatMap((d) => d.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration))\n .find((d) => d.getName() === name)\n ?.getDescendantsOfKind(ts.SyntaxKind.ArrayLiteralExpression)\n .at(0);\n}\n","import type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { existsSync } from \"fs\";\nimport path from \"path\";\nimport {\n customSubgraphResolversTemplate,\n customSubgraphSchemaTemplate,\n documentModelSubgraphResolversTemplate,\n documentModelSubgraphSchemaTemplate,\n subgraphIndexFileTemplate,\n subgraphLibFileTemplate,\n} from \"templates\";\nimport { Project } from \"ts-morph\";\nimport {\n applyGraphQLTypePrefixes,\n extractTypeNames,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\n\ntype TsMorphGenerateSubgraphArgs = {\n subgraphsDir: string;\n subgraphName: string;\n documentModel: DocumentModelGlobalState | null;\n};\n\nexport async function tsMorphGenerateSubgraph(\n args: TsMorphGenerateSubgraphArgs,\n): Promise<void> {\n const { subgraphsDir, subgraphName, documentModel } = args;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n skipLoadingLibFiles: true,\n });\n\n const kebabCaseName = kebabCase(subgraphName);\n const pascalCaseName = pascalCase(subgraphName);\n const camelCaseName = camelCase(subgraphName);\n\n const subgraphDir = path.join(subgraphsDir, kebabCaseName);\n\n // Add existing files so getOrCreateSourceFile can detect them\n if (existsSync(subgraphDir)) {\n for (const name of [\"index.ts\", \"lib.ts\", \"schema.ts\", \"resolvers.ts\"]) {\n const filePath = path.join(subgraphDir, name);\n if (existsSync(filePath)) {\n project.addSourceFileAtPath(filePath);\n }\n }\n }\n\n // Always generate base subgraph files (unless_exists)\n await makeBaseSubgraphIndexFile(project, subgraphDir, {\n pascalCaseName,\n kebabCaseName,\n });\n await makeBaseSubgraphLibFile(project, subgraphDir);\n\n if (documentModel !== null) {\n // Generate document-model-specific schema and resolvers (force overwrite)\n await makeDocumentModelSubgraphFiles(project, subgraphDir, documentModel);\n } else {\n // Generate custom subgraph scaffolds (unless_exists)\n await makeCustomSubgraphFiles(project, subgraphDir, {\n pascalCaseName,\n camelCaseName,\n });\n }\n\n await project.save();\n}\n\nasync function makeBaseSubgraphIndexFile(\n project: Project,\n dirPath: string,\n v: { pascalCaseName: string; kebabCaseName: string },\n) {\n const filePath = path.join(dirPath, \"index.ts\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(subgraphIndexFileTemplate(v));\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeBaseSubgraphLibFile(project: Project, dirPath: string) {\n const filePath = path.join(dirPath, \"lib.ts\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(subgraphLibFileTemplate());\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeCustomSubgraphFiles(\n project: Project,\n dirPath: string,\n v: { pascalCaseName: string; camelCaseName: string },\n) {\n // Schema — skip prettier, contains gql tagged template literal\n const schemaPath = path.join(dirPath, \"schema.ts\");\n const schema = getOrCreateSourceFile(project, schemaPath);\n if (!schema.alreadyExists) {\n schema.sourceFile.replaceWithText(customSubgraphSchemaTemplate(v));\n }\n\n // Resolvers\n const resolversPath = path.join(dirPath, \"resolvers.ts\");\n const resolvers = getOrCreateSourceFile(project, resolversPath);\n if (!resolvers.alreadyExists) {\n resolvers.sourceFile.replaceWithText(customSubgraphResolversTemplate(v));\n await formatSourceFileWithPrettier(resolvers.sourceFile);\n }\n}\n\nasync function makeDocumentModelSubgraphFiles(\n project: Project,\n dirPath: string,\n documentModel: DocumentModelGlobalState,\n) {\n const latestSpec =\n documentModel.specifications[documentModel.specifications.length - 1];\n const documentType = documentModel.name;\n const pascalCaseDocumentType = pascalCase(documentType);\n const camelCaseDocumentType = camelCase(documentType);\n const phDocumentTypeName = `${pascalCaseDocumentType}Document`;\n const documentTypeVariableName = `${camelCaseDocumentType}DocumentType`;\n const kebabCaseDocumentType = kebabCase(documentType);\n const documentModelDir = `document-models/${kebabCaseDocumentType}`;\n\n const stateSchema = latestSpec.state.global.schema;\n const stateTypeNames = extractTypeNames(stateSchema);\n\n const modules = latestSpec.modules\n .filter((m): m is typeof m & { name: string } => m.name !== null)\n .map((m) => ({\n name: kebabCase(m.name),\n operations: m.operations\n .filter((op): op is typeof op & { name: string } => op.name !== null)\n .map((op) => ({\n name: op.name,\n schema: applyGraphQLTypePrefixes(\n op.schema ?? \"\",\n pascalCaseDocumentType,\n stateTypeNames,\n ),\n })),\n }));\n\n // Schema (force overwrite) — skip prettier, contains gql tagged template literal\n const schemaPath = path.join(dirPath, \"schema.ts\");\n const schema = getOrCreateSourceFile(project, schemaPath);\n schema.sourceFile.replaceWithText(\n documentModelSubgraphSchemaTemplate({\n pascalCaseDocumentType,\n modules,\n }),\n );\n\n // Resolvers (force overwrite) — skip prettier, contains template literals that confuse parser\n const resolversPath = path.join(dirPath, \"resolvers.ts\");\n const resolvers = getOrCreateSourceFile(project, resolversPath);\n resolvers.sourceFile.replaceWithText(\n documentModelSubgraphResolversTemplate({\n pascalCaseDocumentType,\n camelCaseDocumentType,\n phDocumentTypeName,\n documentTypeVariableName,\n documentModelDir,\n modules,\n }),\n );\n}\n","import path from \"path\";\nimport { IndentationText, Project } from \"ts-morph\";\n\ntype MakeSubgraphsIndexFileArgs = { projectDir: string };\nexport async function makeSubgraphsIndexFile({\n projectDir,\n}: MakeSubgraphsIndexFileArgs) {\n // use the local tsconfig.json file for a given project\n const tsConfigFilePath = path.join(projectDir, \"tsconfig.json\");\n\n const project = new Project({\n tsConfigFilePath,\n // don't add files from the tsconfig.json file, only use the ones we need\n skipAddingFilesFromTsConfig: true,\n // don't load library files, we only need the files we're adding\n skipLoadingLibFiles: true,\n // use formatting rules which match prettier\n manipulationSettings: {\n useTrailingCommas: true,\n indentationText: IndentationText.TwoSpaces,\n },\n });\n\n project.addSourceFilesAtPaths(`${projectDir}/subgraphs/**/*`);\n\n const subgraphsDir = project.getDirectory(path.join(projectDir, \"subgraphs\"));\n const subgraphsSubdirs = subgraphsDir?.getDirectories() ?? [];\n\n let subgraphsIndexSourceFile = project.getSourceFile(\n path.join(projectDir, \"subgraphs/index.ts\"),\n );\n if (!subgraphsIndexSourceFile) {\n subgraphsIndexSourceFile = project.createSourceFile(\n path.join(projectDir, \"subgraphs/index.js\"),\n \"\",\n );\n }\n\n for (const subgraphSubdir of subgraphsSubdirs) {\n const subgraphIndexSourceFilePath = `${subgraphSubdir.getPath()}/index.ts`;\n const subgraphIndexSourceFile = project.getSourceFile(\n subgraphIndexSourceFilePath,\n );\n if (!subgraphIndexSourceFile) {\n continue;\n }\n const subgraphClassExport = subgraphIndexSourceFile\n .getClasses()\n .find((c) => c.getBaseClass()?.getText().includes(\"BaseSubgraph\"));\n const subgraphClassName = subgraphClassExport?.getName();\n if (!subgraphClassName) {\n continue;\n }\n const indexFileExports = subgraphsIndexSourceFile\n .getExportDeclarations()\n .map((e) => e.getNamespaceExport()?.getText())\n .filter((e) => e !== undefined)\n .join();\n if (indexFileExports.includes(subgraphClassName)) {\n continue;\n }\n subgraphsIndexSourceFile.addExportDeclaration({\n namespaceExport: subgraphClassName,\n moduleSpecifier: `./${subgraphSubdir.getBaseName()}/index.js`,\n });\n }\n\n await project.save();\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,qBAAqB,EACnC,SACA,eACA,YACA,iBACA,UACA,+BAC2B;AAC3B,KAAI,mBAAmB,CAAC,CAAC,4BACvB,OAAM,IAAI,MACR,sEACD;CAGH,MAAM,EAAE,eAAe,sBAAsB,SAD5B,KAAK,KAAK,eAAe,YAAY,CACS;AAE/D,YAAW,gBAAgB,GAAG;CAO9B,MAAM,WAAW,iCAAiC;EAChD;EACA;EACA,sBAR2B,WAAW,WAAW;EASjD,eARoB,kBAClB,KAAK,gBAAgB,MACrB,KAAK,UAAU,4BAA4B;EAO9C,CAAC;AACF,YAAW,gBAAgB,SAAS;;;;;;;AC1BtC,SAAgB,oBAAoB,EAClC,SACA,gBACA,WAC0B;CAC1B,MAAM,sBAAsBA,OAAK,KAAK,gBAAgB,WAAW;CAGjE,IAAI,kBAAkB,QAAQ,cAAc,oBAAoB;AAEhE,KAAI,CAAC,gBACH,mBAAkB,QAAQ,iBAAiB,qBAAq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MAAM,MAAM,KAAA,EAAU,CAC9B,MAAM,CACY,SAAS,kBAAkB,CAC9C;AAEF,2BAAyB,qBAAqB;GAC5C,iBAAiB;GACjB,iBAAiB,KAAK,eAAe,aAAa,CAAC;GACpD,CAAC;;AAGJ,OAAM,QAAQ,MAAM"}
1
+ {"version":3,"file":"file-builders-BV9wDPPZ.mjs","names":["path","path","path","makeIndexFile","makeProcessorFile","makeFactoryFile"],"sources":["../src/file-builders/editor-common.ts","../src/file-builders/index-files.ts","../src/file-builders/module-files.ts","../src/file-builders/app.ts","../src/file-builders/boilerplate/package.json.ts","../src/file-builders/clis/generate-cli-docs.ts","../src/file-builders/document-editor.ts","../src/codegen/graphql.ts","../src/file-builders/document-model/gen-dir.ts","../src/file-builders/document-model/migrate-legacy.ts","../src/file-builders/document-model/root-dir.ts","../src/file-builders/document-model/src-dir.ts","../src/file-builders/document-model/tests-dir.ts","../src/file-builders/document-model/upgrades-dir.ts","../src/file-builders/document-model/document-model.ts","../src/file-builders/processors/analytics.ts","../src/file-builders/processors/relational-db.ts","../src/file-builders/processors/processor.ts","../src/file-builders/subgraph.ts","../src/file-builders/subgraphs.ts"],"sourcesContent":["import { pascalCase } from \"change-case\";\nimport path from \"path\";\nimport { documentEditorModuleFileTemplate } from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { getOrCreateSourceFile } from \"utils\";\n\ntype MakeEditorModuleFileArgs = {\n project: Project;\n editorName: string;\n editorId: string;\n documentModelId?: string;\n editorDirPath: string;\n legacyMultipleDocumentTypes?: string[];\n};\n/** Generates the `module.ts` file for a document editor or app */\nexport function makeEditorModuleFile({\n project,\n editorDirPath,\n editorName,\n documentModelId,\n editorId,\n legacyMultipleDocumentTypes,\n}: MakeEditorModuleFileArgs) {\n if (documentModelId && !!legacyMultipleDocumentTypes) {\n throw new Error(\n \"Cannot specify both documentModelId and legacyMultipleDocumentTypes\",\n );\n }\n const filePath = path.join(editorDirPath, \"module.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n\n const pascalCaseEditorName = pascalCase(editorName);\n const documentTypes = documentModelId\n ? `[\"${documentModelId}\"]`\n : JSON.stringify(legacyMultipleDocumentTypes);\n\n const template = documentEditorModuleFileTemplate({\n editorName,\n editorId,\n pascalCaseEditorName,\n documentTypes,\n });\n sourceFile.replaceWithText(template);\n}\n","import path from \"node:path\";\nimport type { Project } from \"ts-morph\";\n\ntype MakeLegacyIndexFileArgs = {\n /** The project to make the legacy index file for */\n project: Project;\n /** The directory containing the module.ts files to generate from */\n modulesDirPath: string;\n modules: {\n unversionedName: string;\n versionedName: string | undefined;\n moduleSpecifier: string;\n }[];\n};\n\n/**\n * Makes a legacy index.ts file for the modules file which exports the modules as individual exports instead of an array of named exports.\n */\nexport function makeLegacyIndexFile({\n project,\n modulesDirPath,\n modules,\n}: MakeLegacyIndexFileArgs) {\n const indexSourceFilePath = path.join(modulesDirPath, \"index.ts\");\n\n // get the source file for the index.ts file if it exists\n let indexSourceFile = project.getSourceFile(indexSourceFilePath);\n // if the index.ts file doesn't exist, create it\n if (!indexSourceFile) {\n indexSourceFile = project.createSourceFile(indexSourceFilePath, \"\");\n } else {\n indexSourceFile.replaceWithText(\"\");\n }\n\n indexSourceFile.addExportDeclarations(\n modules.map(({ versionedName, unversionedName, moduleSpecifier }) => ({\n namedExports: [\n versionedName\n ? `${unversionedName} as ${versionedName}`\n : unversionedName,\n ],\n moduleSpecifier,\n })),\n );\n}\n","import { camelCase, pascalCase } from \"change-case\";\nimport path from \"node:path\";\nimport type { Project } from \"ts-morph\";\nimport { SyntaxKind, VariableDeclarationKind } from \"ts-morph\";\nimport {\n ensureDirectoriesExist,\n getOrCreateDirectory,\n getOrCreateSourceFile,\n} from \"../utils/source-files.js\";\nimport { getVariableDeclarationByTypeName } from \"../utils/syntax-getters.js\";\nimport { makeLegacyIndexFile } from \"./index-files.js\";\n\ntype MakeModuleFileArgs = {\n /** The project to make the modules file for */\n project: Project;\n /** The directory containing the module.ts files to generate from */\n modulesDirPath: string;\n /** The name of the output file which exports the modules, e.g. 'document-models.ts' or 'editors.ts' */\n outputFileName: string;\n /** The type name of the modules exported by the module.ts files, e.g. 'DocumentModelModule' or 'EditorModule' */\n typeName: string;\n /** The name of the variable that exports the modules, e.g. 'documentModels' or 'editors' */\n variableName: string;\n /** The type of the variable that exports the modules, e.g. 'DocumentModelModule<any>[]' or 'EditorModule[]' */\n variableType: string;\n /** Whether to make a legacy index.ts file for the modules, to be removed in the future */\n shouldMakeLegacyIndexFile?: boolean;\n /** Name of the module file to look for\n * @default module.ts\n */\n moduleFileName?: string;\n};\n/**\n * Makes a file which exports the modules from the module.ts files in the given directory as a variable declaration.\n */\nexport async function makeModulesFile({\n project,\n modulesDirPath,\n outputFileName,\n typeName,\n variableName,\n variableType,\n shouldMakeLegacyIndexFile = true,\n moduleFileName = \"module.ts\",\n}: MakeModuleFileArgs) {\n await ensureDirectoriesExist(project, modulesDirPath);\n const modulesSourceFilesPath = path.join(modulesDirPath, \"**/*\");\n // we only need the files in the directory we're creating the modules file from\n project.addSourceFilesAtPaths(modulesSourceFilesPath);\n\n const { directory: modulesDir } = getOrCreateDirectory(\n project,\n modulesDirPath,\n );\n const moduleFiles = modulesDir\n .getDescendantSourceFiles()\n .filter((file) => file.getBaseName().includes(moduleFileName));\n\n // get the variable declaration for the module object exported by each module.ts file by the given type name\n const moduleDeclarations = moduleFiles\n .map((file) => getVariableDeclarationByTypeName(file, typeName))\n .filter((v) => v !== undefined);\n\n const modules = moduleDeclarations.map((module) => {\n const sourceFile = module.getSourceFile();\n const moduleSpecifier =\n modulesDir.getRelativePathAsModuleSpecifierTo(sourceFile.getFilePath()) +\n \".js\";\n const versionDir = getVersionDirFromModuleSpecifier(moduleSpecifier);\n const unversionedName = module.getName();\n const versionedName = versionDir\n ? `${unversionedName}${pascalCase(versionDir)}`\n : undefined;\n return { versionedName, unversionedName, moduleSpecifier };\n });\n\n const moduleExportsFilePath = path.join(modulesDirPath, outputFileName);\n\n const { sourceFile: moduleExportsSourceFile } = getOrCreateSourceFile(\n project,\n moduleExportsFilePath,\n );\n\n moduleExportsSourceFile.replaceWithText(\"\");\n\n const typeImport = {\n namedImports: [typeName],\n moduleSpecifier: \"document-model\",\n isTypeOnly: true,\n };\n const moduleImports = modules.map(\n ({ versionedName, unversionedName, moduleSpecifier }) => ({\n namedImports: [\n versionedName\n ? `${unversionedName} as ${versionedName}`\n : unversionedName,\n ],\n moduleSpecifier,\n }),\n );\n const importDeclarations = [typeImport, ...moduleImports];\n\n for (const declaration of importDeclarations) {\n if (\n !moduleExportsSourceFile.getImportDeclaration((importDeclaration) =>\n importDeclaration\n .getNamedImports()\n .some((importSpecifier) =>\n declaration.namedImports.includes(importSpecifier.getName()),\n ),\n )\n ) {\n moduleExportsSourceFile.addImportDeclaration(declaration);\n }\n }\n\n // create the variable statement for the modules file\n // start as an empty array\n const moduleExportsVariableStatementInput = {\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: variableName,\n type: variableType,\n initializer: `[]`,\n },\n ],\n };\n // get the variable statement for the modules file if it exists\n let moduleExportsVariableStatement =\n moduleExportsSourceFile.getVariableStatement(variableName);\n // if the variable statement doesn't exist, create it\n if (!moduleExportsVariableStatement) {\n moduleExportsVariableStatement =\n moduleExportsSourceFile.addVariableStatement(\n moduleExportsVariableStatementInput,\n );\n } else {\n // if the variable statement exists, set it to the new variable statement\n moduleExportsVariableStatement.set(moduleExportsVariableStatementInput);\n }\n // get the array literal expression for the variable statement\n const arrayLiteral = moduleExportsVariableStatement\n .getDeclarations()\n .at(0)\n ?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);\n\n // add the module declaration names to the array literal expression\n arrayLiteral?.addElements(\n modules.map((module) => module.versionedName ?? module.unversionedName),\n { useNewLines: true },\n );\n\n // we also need to export each module from the index.ts file for backwards compatibility\n if (shouldMakeLegacyIndexFile) {\n makeLegacyIndexFile({\n project,\n modulesDirPath,\n modules,\n });\n }\n\n await project.save();\n}\n\nexport async function makeUpgradeManifestsFile(args: {\n project: Project;\n projectDir: string;\n}) {\n const { project, projectDir } = args;\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n\n await makeModulesFile({\n project,\n modulesDirPath: documentModelsDirPath,\n outputFileName: \"upgrade-manifests.ts\",\n typeName: \"UpgradeManifest\",\n variableName: \"upgradeManifests\",\n variableType: \"UpgradeManifest<readonly number[]>[]\",\n moduleFileName: \"upgrade-manifest.ts\",\n shouldMakeLegacyIndexFile: false,\n });\n}\n\n/** Generates the `document-models.ts` file which exports the document models defined in each document model dir's `module.ts` file */\nexport async function makeDocumentModelModulesFile({\n project,\n projectDir,\n}: {\n project: Project;\n projectDir: string;\n}) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n await makeModulesFile({\n project,\n modulesDirPath: documentModelsDirPath,\n outputFileName: \"document-models.ts\",\n typeName: \"DocumentModelModule\",\n variableName: \"documentModels\",\n variableType: \"DocumentModelModule<any>[]\",\n });\n}\n\n/** Generates the `editors.ts` file which exports the editors defined in each editor dir's `module.ts` file */\nexport async function makeEditorsModulesFile(\n project: Project,\n projectDir: string,\n) {\n const modulesDirPath = path.join(projectDir, \"editors\");\n await makeModulesFile({\n project,\n modulesDirPath,\n outputFileName: \"editors.ts\",\n typeName: \"EditorModule\",\n variableName: \"editors\",\n variableType: \"EditorModule[]\",\n });\n}\n\nfunction getVersionDirFromModuleSpecifier(moduleSpecifier: string) {\n const match = moduleSpecifier.match(/\\/(v\\d+)(?=\\/)/);\n const version = match?.[1];\n return version;\n}\n\ntype MakeUpgradeManifestsExportArgs = {\n /** The project to add the export to */\n project: Project;\n /** The directory containing the document model directories (e.g., document-models/) */\n modulesDirPath: string;\n /** The path to the output file (document-models.ts) */\n outputFilePath: string;\n /** The variable name for the upgrade manifests array */\n variableName: string;\n /** The type of the upgrade manifests variable */\n variableType: string;\n /** The type name for UpgradeManifest to add to imports */\n typeName: string;\n};\n\n/**\n * Adds the upgradeManifests export to an existing document-models.ts file.\n * Searches for upgrade-manifest.ts files in each document model's upgrades directory,\n * adds imports for each, and creates the upgradeManifests array export.\n */\nexport function makeUpgradeManifestsExport({\n project,\n modulesDirPath,\n outputFilePath,\n variableName,\n variableType,\n typeName,\n}: MakeUpgradeManifestsExportArgs) {\n // Resolve to absolute path for glob pattern matching\n const absoluteModulesDirPath = path.resolve(modulesDirPath);\n const absoluteOutputFilePath = path.resolve(outputFilePath);\n\n // Add upgrade-manifest.ts files to the project\n const upgradeManifestGlob = `${absoluteModulesDirPath}/**/upgrade-manifest.ts`;\n project.addSourceFilesAtPaths(upgradeManifestGlob);\n\n // Find all upgrade-manifest.ts files\n const upgradeManifestFiles = project\n .getSourceFiles()\n .filter((file) => file.getFilePath().includes(\"upgrade-manifest.ts\"))\n .filter((file) => file.getFilePath().startsWith(absoluteModulesDirPath));\n\n if (upgradeManifestFiles.length === 0) {\n return;\n }\n\n // Get the output source file (document-models.ts)\n // Refresh from file system to ensure we have the latest content after makeModulesFile\n let outputSourceFile = project.getSourceFile(absoluteOutputFilePath);\n if (outputSourceFile) {\n outputSourceFile.refreshFromFileSystemSync();\n } else {\n // If not found in project, add it\n project.addSourceFilesAtPaths(absoluteOutputFilePath);\n outputSourceFile = project.getSourceFile(absoluteOutputFilePath);\n }\n if (!outputSourceFile) {\n return;\n }\n\n const modulesDir = project.getDirectory(absoluteModulesDirPath);\n if (!modulesDir) {\n return;\n }\n\n // Extract upgrade manifest info from each file\n const manifests = upgradeManifestFiles.map((file) => {\n const filePath = file.getFilePath();\n // Extract document model name from path (e.g., ./todo/upgrades/upgrade-manifest.ts -> todo)\n const pathParts = filePath.split(\"/\");\n const upgradesIndex = pathParts.indexOf(\"upgrades\");\n const documentModelName =\n upgradesIndex > 0 ? pathParts[upgradesIndex - 1] : \"unknown\";\n\n const moduleSpecifier =\n modulesDir.getRelativePathAsModuleSpecifierTo(filePath) + \".js\";\n\n // Create aliased name like \"upgradeManifest as todoUpgradeManifest\"\n // Convert to camelCase to ensure valid JS identifier (e.g., billing-statement -> billingStatementUpgradeManifest)\n const aliasedName = `${camelCase(documentModelName)}UpgradeManifest`;\n\n return {\n originalName: \"upgradeManifest\",\n aliasedName,\n moduleSpecifier,\n };\n });\n\n // Add UpgradeManifest to the existing type import from document-model\n const existingTypeImport = outputSourceFile\n .getImportDeclarations()\n .find(\n (imp) =>\n imp.getModuleSpecifierValue() === \"document-model\" && imp.isTypeOnly(),\n );\n\n if (existingTypeImport) {\n const namedImports = existingTypeImport.getNamedImports();\n const hasUpgradeManifest = namedImports.some(\n (ni) => ni.getName() === typeName,\n );\n if (!hasUpgradeManifest) {\n existingTypeImport.addNamedImport(typeName);\n }\n }\n\n // Add import declarations for each upgrade manifest using text insertion\n // This avoids ts-morph AST manipulation issues with the refreshed file\n const existingImports = outputSourceFile.getImportDeclarations();\n const lastImport = existingImports[existingImports.length - 1];\n\n if (lastImport) {\n const importTexts = manifests.map(\n ({ originalName, aliasedName, moduleSpecifier }) =>\n `import { ${originalName} as ${aliasedName} } from \"${moduleSpecifier}\";`,\n );\n const insertText = \"\\n\" + importTexts.join(\"\\n\");\n const insertPos = lastImport.getEnd();\n outputSourceFile.insertText(insertPos, insertText);\n }\n\n // Create the upgradeManifests variable statement\n const variableStatementInput = {\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: variableName,\n type: variableType,\n initializer: `[]`,\n },\n ],\n };\n\n // Add the variable statement\n const variableStatement = outputSourceFile.addVariableStatement(\n variableStatementInput,\n );\n\n // Get the array literal and add the manifest names\n const arrayLiteral = variableStatement\n .getDeclarations()\n .at(0)\n ?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);\n\n arrayLiteral?.addElements(\n manifests.map((m) => m.aliasedName),\n { useNewLines: true },\n );\n}\n","import type { CommonGenerateEditorArgs } from \"@powerhousedao/codegen\";\nimport path from \"path\";\nimport {\n appConfigFileTemplate,\n appDriveContentsFileTemplate,\n appEditorFileTemplate,\n appFilesFileTemplate,\n appFoldersFileTemplate,\n createDocumentFileTemplate,\n driveExplorerFileTemplate,\n driveExplorerNavigationBreadcrumbsFileTemplate,\n emptyStateFileTemplate,\n folderTreeFileTemplate,\n} from \"templates\";\nimport { type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { makeEditorModuleFile } from \"./editor-common.js\";\nimport { makeEditorsModulesFile } from \"./module-files.js\";\n\ntype GenerateAppArgs = CommonGenerateEditorArgs & {\n allowedDocumentModelIds: string[];\n isDragAndDropEnabled: boolean;\n};\n/** Generates a app with the configs for `allowedDocumentModelIds` and `isDragAndDropEnabled` */\nexport async function tsMorphGenerateApp({\n projectDir,\n editorDir,\n editorName,\n editorId,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n}: GenerateAppArgs) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const documentModelsSourceFilesPath = path.join(\n documentModelsDirPath,\n \"/**/*\",\n );\n const editorsDirPath = path.join(projectDir, \"editors\");\n const editorSourceFilesPath = path.join(editorsDirPath, \"/**/*\");\n const editorDirPath = path.join(editorsDirPath, editorDir);\n const editorComponentsDirPath = path.join(editorDirPath, \"components\");\n\n const project = buildTsMorphProject(projectDir);\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n editorsDirPath,\n editorDirPath,\n editorComponentsDirPath,\n );\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n project.addSourceFilesAtPaths(editorSourceFilesPath);\n\n await makeNavigationBreadcrumbsFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeCreateDocumentFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeEmptyStateFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFoldersFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFolderTreeFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeFilesFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeDriveExplorerFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeDriveContentsFile({\n project,\n editorComponentsDirPath,\n });\n\n await makeAppComponent({\n project,\n editorDirPath,\n });\n\n await makeAppConfigFile({\n project,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n editorDirPath,\n });\n\n makeEditorModuleFile({\n project,\n editorName,\n editorId,\n editorDirPath,\n documentModelId: \"powerhouse/document-drive\",\n });\n\n await makeEditorsModulesFile(project, projectDir);\n\n await project.save();\n}\n\ntype MakeAppComponentArgs = {\n project: Project;\n editorDirPath: string;\n};\nasync function makeAppComponent({\n project,\n editorDirPath,\n}: MakeAppComponentArgs) {\n const filePath = path.join(editorDirPath, \"editor.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) {\n const editorFunction = sourceFile.getFunction(\"Editor\");\n if (editorFunction) {\n if (!editorFunction.isDefaultExport()) {\n editorFunction.setIsDefaultExport(true);\n }\n return;\n }\n }\n const template = appEditorFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeAppConfigFileArgs = {\n project: Project;\n editorDirPath: string;\n allowedDocumentModelIds: string[];\n isDragAndDropEnabled: boolean;\n};\nasync function makeAppConfigFile({\n project,\n editorDirPath,\n allowedDocumentModelIds,\n isDragAndDropEnabled,\n}: MakeAppConfigFileArgs) {\n const filePath = path.join(editorDirPath, \"config.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n const allowedDocumentTypesString = JSON.stringify(allowedDocumentModelIds);\n const isDragAndDropEnabledString = isDragAndDropEnabled ? \"true\" : \"false\";\n\n const template = appConfigFileTemplate({\n isDragAndDropEnabledString,\n allowedDocumentTypesString,\n });\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeDriveContentsFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeDriveContentsFile({\n project,\n editorComponentsDirPath,\n}: MakeDriveContentsFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"DriveContents.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n const template = appDriveContentsFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeNavigationBreadcrumbsFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\n\nasync function makeNavigationBreadcrumbsFile({\n project,\n editorComponentsDirPath,\n}: MakeNavigationBreadcrumbsFileArgs) {\n const filePath = path.join(\n editorComponentsDirPath,\n \"NavigationBreadcrumbs.tsx\",\n );\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(driveExplorerNavigationBreadcrumbsFileTemplate());\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFoldersFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFoldersFile({\n project,\n editorComponentsDirPath,\n}: MakeFoldersFileArgs) {\n const foldersFilePath = path.join(editorComponentsDirPath, \"Folders.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n foldersFilePath,\n );\n\n if (alreadyExists) return;\n\n const template = appFoldersFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFilesFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFilesFile({\n project,\n editorComponentsDirPath,\n}: MakeFilesFileArgs) {\n const filesFilePath = path.join(editorComponentsDirPath, \"Files.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filesFilePath,\n );\n\n if (alreadyExists) return;\n\n const template = appFilesFileTemplate();\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeDriveExplorerFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeDriveExplorerFile({\n project,\n editorComponentsDirPath,\n}: MakeDriveExplorerFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"DriveExplorer.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(driveExplorerFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeFolderTreeFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeFolderTreeFile({\n project,\n editorComponentsDirPath,\n}: MakeFolderTreeFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"FolderTree.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(folderTreeFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeEmptyStateFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeEmptyStateFile({\n project,\n editorComponentsDirPath,\n}: MakeEmptyStateFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"EmptyState.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(emptyStateFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeCreateDocumentFileArgs = {\n project: Project;\n editorComponentsDirPath: string;\n};\nasync function makeCreateDocumentFile({\n project,\n editorComponentsDirPath,\n}: MakeCreateDocumentFileArgs) {\n const filePath = path.join(editorComponentsDirPath, \"CreateDocument.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(createDocumentFileTemplate);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import {\n makeVersionedDependencies,\n VERSIONED_DEPENDENCIES,\n VERSIONED_DEV_DEPENDENCIES,\n} from \"@powerhousedao/shared/clis\";\nimport { packageJsonTemplate } from \"templates\";\n\nexport async function buildBoilerplatePackageJson(args: {\n name: string;\n tag?: string;\n version?: string;\n workspace?: boolean;\n}) {\n const { name, tag, version, workspace } = args;\n const versionedDependencies = await makeVersionedDependencies({\n names: VERSIONED_DEPENDENCIES,\n tag,\n version,\n });\n const versionedDevDependencies = await makeVersionedDependencies({\n names: VERSIONED_DEV_DEPENDENCIES,\n tag,\n version,\n });\n\n const template = packageJsonTemplate(\n name,\n versionedDependencies,\n versionedDevDependencies,\n );\n\n return template;\n}\n","import type { CommandEntry, CommandHelpInfo } from \"@powerhousedao/codegen\";\nimport { writeFile } from \"node:fs/promises\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { docsFromCliHelpTemplate } from \"templates\";\nexport function getCommandHelpInfo<TEntry extends CommandEntry>(\n entry: TEntry,\n): CommandHelpInfo {\n const name = entry.name;\n const description = entry.command.description ?? \"\";\n const helpTopics = entry.command.helpTopics?.() ?? [];\n return {\n name,\n description,\n helpTopics,\n };\n}\n\nexport function getCommandsHelpInfo<TEntry extends CommandEntry>(\n entries: TEntry[],\n) {\n return entries.map(getCommandHelpInfo);\n}\n\nexport function makeCliDocsFromHelp<TEntry extends CommandEntry>(args: {\n cliDescription: string;\n docsTitle: string;\n docsIntroduction: string;\n entries: TEntry[];\n}) {\n const { cliDescription, docsIntroduction, docsTitle, entries } = args;\n const commandsHelpInfo = getCommandsHelpInfo(entries);\n\n const template = docsFromCliHelpTemplate({\n cliDescription,\n docsIntroduction,\n docsTitle,\n commandsHelpInfo,\n });\n\n const templateWithAnsiEscapesRemoved = stripVTControlCharacters(template);\n\n return templateWithAnsiEscapesRemoved;\n}\n\nexport async function writeCliDocsMarkdownFile<\n TEntry extends CommandEntry,\n>(args: {\n filePath: string;\n cliDescription: string;\n docsTitle: string;\n docsIntroduction: string;\n entries: TEntry[];\n}) {\n const { filePath, ...restArgs } = args;\n const markdownFileContent = makeCliDocsFromHelp(restArgs);\n\n await writeFile(filePath, markdownFileContent, {\n encoding: \"utf-8\",\n });\n}\n","import type {\n CommonGenerateEditorArgs,\n EditorVariableNames,\n} from \"@powerhousedao/codegen\";\nimport { getEditorVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport { documentEditorEditorFileTemplate } from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getDocumentTypeMetadata,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { makeEditorModuleFile } from \"./editor-common.js\";\nimport { makeEditorsModulesFile } from \"./module-files.js\";\n\ntype GenerateEditorArgs = CommonGenerateEditorArgs & {\n documentModelId: string;\n};\n/** Generates a document editor for the given `documentModelId` (also called `documentType`) */\nexport async function tsMorphGenerateDocumentEditor({\n projectDir,\n editorDir,\n editorName,\n editorId,\n documentModelId,\n}: GenerateEditorArgs) {\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const editorsDirPath = path.join(projectDir, \"editors\");\n const editorDirPath = path.join(editorsDirPath, editorDir);\n const componentsDirPath = path.join(editorDirPath, \"components\");\n const editorSourceFilesPath = path.join(editorsDirPath, \"/**/*\");\n const documentModelsSourceFilesPath = path.join(\n documentModelsDirPath,\n \"/**/*\",\n );\n\n const project = buildTsMorphProject(projectDir);\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n editorsDirPath,\n editorDirPath,\n componentsDirPath,\n );\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n project.addSourceFilesAtPaths(editorSourceFilesPath);\n\n const documentTypeMetadata = getDocumentTypeMetadata({\n project,\n documentModelId,\n documentModelsDirPath,\n });\n\n const editorVariableNames = getEditorVariableNames(documentTypeMetadata);\n\n await makeEditorComponent({\n project,\n editorDirPath,\n ...documentTypeMetadata,\n ...editorVariableNames,\n });\n\n makeEditorModuleFile({\n project,\n editorName,\n editorId,\n documentModelId,\n editorDirPath,\n });\n\n await makeEditorsModulesFile(project, projectDir);\n\n await project.save();\n}\n\ntype MakeEditorComponentArgs = EditorVariableNames & {\n project: Project;\n editorDirPath: string;\n documentModelDocumentTypeName: string;\n documentModelImportPath: string;\n};\nasync function makeEditorComponent(args: MakeEditorComponentArgs) {\n const { project, editorDirPath } = args;\n const filePath = path.join(editorDirPath, \"editor.tsx\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) {\n const functionDeclaration = sourceFile.getFunction(\"Editor\");\n if (functionDeclaration) {\n if (!functionDeclaration.isDefaultExport()) {\n functionDeclaration.setIsDefaultExport(true);\n }\n return;\n }\n }\n\n const template = documentEditorEditorFileTemplate(args);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type { CodegenConfig } from \"@graphql-codegen/cli\";\nimport { generate } from \"@graphql-codegen/cli\";\nimport type { TypeScriptPluginConfig } from \"@graphql-codegen/typescript\";\nimport {\n generatorTypeDefs,\n validationSchema,\n} from \"@powerhousedao/document-engineering/graphql\";\nimport type {\n DocumentModelGlobalState,\n DocumentSpecification,\n ModuleSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ValidationSchemaPluginConfig } from \"graphql-codegen-typescript-validation-schema\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { format } from \"prettier\";\n\nconst getDirectories = async (source: string) => {\n const dir = await fs.readdir(source, { withFileTypes: true });\n return dir.filter((dirent) => dirent.isDirectory()).map((dirent) => dirent);\n};\n\nexport const scalars = {\n Unknown: \"unknown\",\n DateTime: \"string\",\n Attachment: \"string\",\n Address: \"`${string}:0x${string}`\",\n ...(generatorTypeDefs as Record<string, string>),\n};\n\nexport const scalarsValidation = {\n Unknown: \"z.unknown()\",\n DateTime: \"z.string().datetime()\",\n Attachment: \"z.string()\",\n Address:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n ...(validationSchema as Record<string, string>),\n};\n\nconst avoidOptionals: TypeScriptPluginConfig[\"avoidOptionals\"] = {\n field: true,\n inputValue: false,\n};\nconst maybeValue = \"T | null | undefined\";\nconst typescriptConfig: TypeScriptPluginConfig = {\n avoidOptionals,\n scalars,\n strictScalars: true,\n enumsAsTypes: true,\n skipTypename: true,\n maybeValue,\n};\n\nconst validationSchemaConfig: ValidationSchemaPluginConfig = {\n avoidOptionals,\n scalars,\n strictScalars: true,\n enumsAsTypes: true,\n skipTypename: true,\n importFrom: `./types.js`,\n schema: \"zodv4\",\n useTypeImports: true,\n scalarSchemas: scalarsValidation,\n directives: {\n equals: {\n value: [\"regex\", \"/^$1$/\"],\n },\n },\n withObjectType: true,\n maybeValue,\n};\n\nfunction buildSchemasForModules(modules: ModuleSpecification[]) {\n const schemaStrings: string[] = [];\n for (const module of modules) {\n schemaStrings.push(`# ${module.name}`);\n const operationsSchemas = module.operations\n .map((operation) => operation.schema)\n .filter((schema) => schema !== null);\n schemaStrings.push(...operationsSchemas);\n }\n return schemaStrings;\n}\n\nfunction buildGraphqlDocumentStringForSpecification(\n specification: DocumentSpecification,\n) {\n const customScalarSchemas = Object.keys(scalars)\n .map((k) => `scalar ${k}`)\n .join(\"\\n\");\n const stateSchemas = Object.values(specification.state).map(\n (state) => state.schema,\n );\n const moduleSchemas = buildSchemasForModules(specification.modules);\n\n return [customScalarSchemas, ...stateSchemas, ...moduleSchemas];\n}\n\nasync function formatContentWithPrettier(path: string, content: string) {\n const formattedContent = await format(content, {\n parser: \"typescript\",\n });\n return formattedContent;\n}\n\ntype GenerateTypesAndZodSchemasFromGraphqlArgs = {\n dirName: string;\n schema: string;\n skipFormat?: boolean;\n writeFile?: boolean;\n watch?: boolean;\n};\nexport async function generateTypesAndZodSchemasFromGraphql(\n args: GenerateTypesAndZodSchemasFromGraphqlArgs,\n) {\n const { dirName, schema, skipFormat, writeFile, watch } = args;\n const beforeOneFileWrite = skipFormat ? undefined : formatContentWithPrettier;\n\n const config: CodegenConfig = {\n overwrite: true,\n watch,\n hooks: {\n beforeOneFileWrite,\n },\n generates: {\n [`${dirName}/gen/schema/types.ts`]: {\n schema,\n config: typescriptConfig,\n plugins: [\n {\n typescript: typescriptConfig,\n },\n ],\n },\n [`${dirName}/gen/schema/zod.ts`]: {\n schema,\n config: validationSchemaConfig,\n plugins: [\n {\n add: {\n content:\n \"/* eslint-disable @typescript-eslint/no-empty-object-type */\",\n },\n },\n {\n \"graphql-codegen-typescript-validation-schema\":\n validationSchemaConfig,\n },\n ],\n },\n },\n };\n\n await generate(config, writeFile);\n}\n\nexport async function generateDocumentModelZodSchemas(args: {\n documentModelDirPath: string;\n specification: DocumentSpecification;\n writeFile?: boolean;\n skipFormat?: boolean;\n watch?: boolean;\n}) {\n const {\n documentModelDirPath,\n specification,\n writeFile = true,\n skipFormat = false,\n watch = false,\n } = args;\n const schema = buildGraphqlDocumentStringForSpecification(specification)\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n await generateTypesAndZodSchemasFromGraphql({\n dirName: documentModelDirPath,\n schema,\n writeFile,\n skipFormat,\n watch,\n });\n\n await fs.writeFile(path.join(documentModelDirPath, \"schema.graphql\"), schema);\n}\n\nexport const generateSchemas = async (\n inDir: string,\n { watch = false, skipFormat = false, writeFile = true, outDir = inDir } = {},\n) => {\n const dirs = await getDirectories(inDir);\n const inputs = await Promise.all(\n dirs.map(async (dir) => {\n const documentModelJsonFile = await fs.readFile(\n path.join(dir.parentPath, dir.name, `${dir.name}.json`),\n \"utf-8\",\n );\n const parsedJson = JSON.parse(\n documentModelJsonFile,\n ) as DocumentModelGlobalState;\n\n const latestSpecification =\n parsedJson.specifications[parsedJson.specifications.length - 1];\n\n const schema = buildGraphqlDocumentStringForSpecification(\n latestSpecification,\n )\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n return { dirName: path.join(outDir, dir.name), schema };\n }),\n );\n\n await Promise.all(\n inputs.map(async ({ schema, dirName }) => {\n await generateTypesAndZodSchemasFromGraphql({\n schema,\n dirName,\n writeFile,\n skipFormat,\n watch,\n });\n }),\n );\n};\n","import { kebabCase, pascalCase } from \"change-case\";\nimport type {\n DocumentModelFileMakerArgs,\n DocumentModelTemplateInputsWithModule,\n} from \"file-builders\";\nimport { getDocumentModelOperationsModuleVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport {\n documentModelDocumentSchemaFileTemplate,\n documentModelDocumentTypeTemplate,\n documentModelGenActionsFileTemplate,\n documentModelGenControllerFileTemplate,\n documentModelGenCreatorsFileTemplate,\n documentModelGenIndexFileTemplate,\n documentModelGenReducerFileTemplate,\n documentModelGenTypesTemplate,\n documentModelGenUtilsTemplate,\n documentModelOperationModuleActionsFileTemplate,\n documentModelOperationsModuleCreatorsFileTemplate,\n documentModelOperationsModuleErrorFileTemplate,\n documentModelOperationsModuleOperationsFileTemplate,\n documentModelPhFactoriesFileTemplate,\n documentModelSchemaIndexTemplate,\n} from \"templates\";\nimport { VariableDeclarationKind } from \"ts-morph\";\nimport {\n buildObjectLiteral,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\n\nexport async function makeGenDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelSchemaIndexFile(fileMakerArgs);\n await makeDocumentModelGenUtilsFile(fileMakerArgs);\n await makeDocumentModelGenTypesFile(fileMakerArgs);\n await makeDocumentModelGenCreatorsFile(fileMakerArgs);\n await makeDocumentModelGenActionsFile(fileMakerArgs);\n await makeDocumentModelGenDocumentSchemaFile(fileMakerArgs);\n await makeDocumentModelGenReducerFile(fileMakerArgs);\n await makeDocumentModelDocumentTypeFile(fileMakerArgs);\n await makeDocumentModelGenIndexFile(fileMakerArgs);\n await makeDocumentModelGenDocumentModelFile(fileMakerArgs);\n await makeDocumentModelGenPhFactoriesFile(fileMakerArgs);\n await makeDocumentModelGenControllerFile(fileMakerArgs);\n\n const modules = fileMakerArgs.modules;\n\n for (const module of modules) {\n const operationsModuleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n await makeGenDirOperationModuleFiles({\n module,\n ...fileMakerArgs,\n ...operationsModuleVariableNames,\n });\n }\n}\n\nasync function makeGenDirOperationModuleFiles(\n fileMakerArgs: DocumentModelTemplateInputsWithModule,\n) {\n await makeOperationModuleGenActionsFile(fileMakerArgs);\n await makeOperationModuleGenCreatorsFile(fileMakerArgs);\n await makeOperationModuleGenOperationsFile(fileMakerArgs);\n await makeOperationModuleGenErrorFile(fileMakerArgs);\n}\n\nasync function makeDocumentModelGenUtilsFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenUtilsTemplate(args);\n const { project, genDirPath } = args;\n const utilsFilePath = path.join(genDirPath, \"utils.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, utilsFilePath);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelDocumentTypeFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelDocumentTypeTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"document-type.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSchemaIndexFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelSchemaIndexTemplate;\n const { project, schemaDirPath } = args;\n const filePath = path.join(schemaDirPath, \"index.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenTypesFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenTypesTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"types.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenDocumentModelFile(\n args: DocumentModelFileMakerArgs,\n) {\n const { project, genDirPath, documentModelState } = args;\n const filePath = path.join(genDirPath, \"document-model.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n\n sourceFile.addImportDeclaration({\n namedImports: [\"DocumentModelGlobalState\"],\n moduleSpecifier: \"document-model\",\n isTypeOnly: true,\n });\n\n const documentModelStateString = buildObjectLiteral(\n documentModelState,\n sourceFile,\n );\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: \"documentModel\",\n type: \"DocumentModelGlobalState\",\n initializer: documentModelStateString,\n },\n ],\n });\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenDocumentSchemaFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelDocumentSchemaFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"document-schema.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenCreatorsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenCreatorsFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"creators.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenPhFactoriesFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelPhFactoriesFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"ph-factories.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenControllerFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenControllerFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"controller.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenIndexFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelGenIndexFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenActionsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenActionsFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelGenReducerFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelGenReducerFileTemplate(args);\n const { project, genDirPath } = args;\n\n const filePath = path.join(genDirPath, \"reducer.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenActionsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const { actions } = getDocumentModelOperationsModuleVariableNames(module);\n const pascalCaseModuleName = pascalCase(module.name);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationModuleActionsFileTemplate({\n ...args,\n actions,\n pascalCaseModuleName,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenCreatorsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleCreatorsFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"creators.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenOperationsFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleOperationsFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n const filePath = path.join(dirPath, \"operations.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeOperationModuleGenErrorFile(\n args: DocumentModelTemplateInputsWithModule,\n) {\n const { module } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const kebabCaseModuleName = kebabCase(module.name);\n const template = documentModelOperationsModuleErrorFileTemplate({\n ...args,\n ...moduleVariableNames,\n });\n const { project, genDirPath } = args;\n\n const dirPath = path.join(genDirPath, kebabCaseModuleName);\n\n const filePath = path.join(dirPath, \"error.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import { directoryExists, fileExists } from \"@powerhousedao/shared/clis\";\nimport { copyFile, mkdir, readdir, rename } from \"node:fs/promises\";\nimport path from \"path\";\n\n/**\n * Detects whether a document model directory has a legacy (non-versioned)\n * structure and migrates it to the versioned layout expected by `--use-versioning`.\n *\n * Detection: a directory is \"legacy\" when `src/reducers/` exists at root level\n * AND no `v1/` directory exists yet.\n *\n * Migration steps:\n * 1. Move legacy root-level items (`gen/`, `src/`, `tests/`, and known root files)\n * into a `legacy/` subfolder for reference / backup.\n * 2. Copy custom source files (reducers, tests, utils) from `legacy/` into the\n * soon-to-be-created `v1/` directory so that ts-morph picks them up during\n * generation and preserves business logic.\n *\n * This function is idempotent — calling it on an already-migrated directory is a\n * no-op.\n */\nexport async function migrateLegacyToVersioned(\n documentModelDirPath: string,\n): Promise<void> {\n const srcReducersPath = path.join(documentModelDirPath, \"src\", \"reducers\");\n const v1Path = path.join(documentModelDirPath, \"v1\");\n const legacyPath = path.join(documentModelDirPath, \"legacy\");\n\n // Detection: only migrate if legacy structure exists and v1 doesn't\n const hasSrcReducers = await directoryExists(srcReducersPath);\n const hasV1 = await directoryExists(v1Path);\n\n if (!hasSrcReducers || hasV1) {\n return;\n }\n\n console.log(\n `[migrate-legacy] Detected legacy structure in ${documentModelDirPath}`,\n );\n\n // Step 1: Create legacy directory\n await mkdir(legacyPath, { recursive: true });\n\n // Step 2: Move known root-level items into legacy/\n const dirsToMove = [\"gen\", \"src\", \"tests\"];\n const filesToMove = [\n \"module.ts\",\n \"actions.ts\",\n \"hooks.ts\",\n \"utils.ts\",\n \"index.ts\",\n \"schema.graphql\",\n ];\n\n for (const dirName of dirsToMove) {\n const srcPath = path.join(documentModelDirPath, dirName);\n if (await directoryExists(srcPath)) {\n const destPath = path.join(legacyPath, dirName);\n await rename(srcPath, destPath);\n console.log(`[migrate-legacy] Moved ${dirName}/ → legacy/${dirName}/`);\n }\n }\n\n for (const fileName of filesToMove) {\n const srcPath = path.join(documentModelDirPath, fileName);\n if (await fileExists(srcPath)) {\n const destPath = path.join(legacyPath, fileName);\n await rename(srcPath, destPath);\n console.log(`[migrate-legacy] Moved ${fileName} → legacy/${fileName}`);\n }\n }\n\n // Step 3: Copy custom source files into v1/ so ts-morph finds them\n const v1SrcReducersPath = path.join(v1Path, \"src\", \"reducers\");\n const v1SrcPath = path.join(v1Path, \"src\");\n const v1TestsPath = path.join(v1Path, \"tests\");\n\n // Copy legacy/src/reducers/*.ts → v1/src/reducers/\n const legacySrcReducersPath = path.join(legacyPath, \"src\", \"reducers\");\n if (await directoryExists(legacySrcReducersPath)) {\n await mkdir(v1SrcReducersPath, { recursive: true });\n await copyDirectoryFiles(legacySrcReducersPath, v1SrcReducersPath);\n console.log(`[migrate-legacy] Copied src/reducers/ → v1/src/reducers/`);\n }\n\n // Copy legacy/src/tests/*.ts → v1/src/tests/ (if exists)\n const legacySrcTestsPath = path.join(legacyPath, \"src\", \"tests\");\n if (await directoryExists(legacySrcTestsPath)) {\n const v1SrcTestsPath = path.join(v1SrcPath, \"tests\");\n await mkdir(v1SrcTestsPath, { recursive: true });\n await copyDirectoryFiles(legacySrcTestsPath, v1SrcTestsPath);\n console.log(`[migrate-legacy] Copied src/tests/ → v1/src/tests/`);\n }\n\n // Copy legacy/tests/*.ts → v1/tests/ (if exists)\n const legacyTestsPath = path.join(legacyPath, \"tests\");\n if (await directoryExists(legacyTestsPath)) {\n await mkdir(v1TestsPath, { recursive: true });\n await copyDirectoryFiles(legacyTestsPath, v1TestsPath);\n console.log(`[migrate-legacy] Copied tests/ → v1/tests/`);\n }\n\n // Copy legacy/src/utils.ts → v1/src/utils.ts (if exists)\n const legacyUtilsPath = path.join(legacyPath, \"src\", \"utils.ts\");\n if (await fileExists(legacyUtilsPath)) {\n await mkdir(v1SrcPath, { recursive: true });\n await copyFile(legacyUtilsPath, path.join(v1SrcPath, \"utils.ts\"));\n console.log(`[migrate-legacy] Copied src/utils.ts → v1/src/utils.ts`);\n }\n\n console.log(\n `[migrate-legacy] Migration complete for ${documentModelDirPath}`,\n );\n}\n\n/** Copy all files (non-recursive) from srcDir to destDir */\nasync function copyDirectoryFiles(\n srcDir: string,\n destDir: string,\n): Promise<void> {\n const entries = await readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n await copyFile(\n path.join(srcDir, entry.name),\n path.join(destDir, entry.name),\n );\n }\n }\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport path from \"path\";\nimport {\n documentModelHooksFileTemplate,\n documentModelIndexTemplate,\n documentModelModuleFileTemplate,\n documentModelRootActionsFileTemplate,\n documentModelUtilsTemplate,\n} from \"templates\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\n\nexport async function makeRootDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelVersionIndexFile(fileMakerArgs);\n await makeDocumentModelRootActionsFile(fileMakerArgs);\n await makeDocumentModelModuleFile(fileMakerArgs);\n await makeDocumentModelUtilsFile(fileMakerArgs);\n await makeDocumentModelHooksFile(fileMakerArgs);\n}\n\nasync function makeDocumentModelVersionIndexFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelIndexTemplate;\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelUtilsFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelUtilsTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"utils.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelRootActionsFile(\n args: DocumentModelFileMakerArgs,\n) {\n const template = documentModelRootActionsFileTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"actions.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelHooksFile(args: DocumentModelFileMakerArgs) {\n const template = documentModelHooksFileTemplate(args);\n const { project, documentModelVersionDirPath } = args;\n\n const filePath = path.join(documentModelVersionDirPath, \"hooks.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelModuleFile(args: DocumentModelFileMakerArgs) {\n const { project, documentModelVersionDirPath } = args;\n const template = documentModelModuleFileTemplate(args);\n\n const moduleFilePath = path.join(documentModelVersionDirPath, \"module.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, moduleFilePath);\n\n sourceFile.replaceWithText(template);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport type { ModuleSpecification } from \"@powerhousedao/shared/document-model\";\nimport { ts } from \"@tmpl/core\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport path from \"path\";\nimport {\n documentModelSrcIndexFileTemplate,\n documentModelSrcUtilsTemplate,\n} from \"templates\";\nimport type { SourceFile } from \"ts-morph\";\nimport { VariableDeclarationKind } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getObjectLiteral,\n getOrCreateSourceFile,\n getPreviousVersionSourceFile,\n} from \"utils\";\n\nexport async function makeSrcDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelSrcIndexFile(fileMakerArgs);\n await makeDocumentModelSrcUtilsFile(fileMakerArgs);\n await makeReducerOperationHandlersForModules(fileMakerArgs);\n}\n\nasync function makeReducerOperationHandlersForModules(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n const { modules } = fileMakerArgs;\n for (const module of modules) {\n await makeReducerOperationHandlerForModule({\n ...fileMakerArgs,\n module,\n });\n }\n}\n\nasync function makeReducerOperationHandlerForModule({\n project,\n module,\n version,\n reducersDirPath,\n pascalCaseDocumentType,\n camelCaseDocumentType,\n versionedDocumentModelPackageImportPath,\n}: DocumentModelFileMakerArgs & { module: ModuleSpecification }) {\n const kebabCaseModuleName = kebabCase(module.name);\n const pascalCaseModuleName = pascalCase(module.name);\n const filePath = path.join(reducersDirPath, `${kebabCaseModuleName}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (!alreadyExists) {\n const previousVersionFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n if (previousVersionFile) {\n sourceFile.replaceWithText(previousVersionFile.getText());\n }\n }\n const operationsInterfaceTypeName = `${pascalCaseDocumentType}${pascalCaseModuleName}Operations`;\n const operationsInterfaceVariableName = `${camelCaseDocumentType}${pascalCaseModuleName}Operations`;\n\n const existingOperationsInterfaceTypeImport = sourceFile.getImportDeclaration(\n (importDeclaration) =>\n !!importDeclaration\n .getNamedImports()\n .find(\n (importSpecifier) =>\n importSpecifier.getName() === operationsInterfaceTypeName,\n ),\n );\n if (existingOperationsInterfaceTypeImport) {\n existingOperationsInterfaceTypeImport.remove();\n }\n\n const operationsInterfaceTypeImport = sourceFile.addImportDeclaration({\n namedImports: [operationsInterfaceTypeName],\n moduleSpecifier: versionedDocumentModelPackageImportPath,\n isTypeOnly: true,\n });\n\n const operationsInterfaceTypeProperties = operationsInterfaceTypeImport\n .getNamedImports()\n .find((value) => value.getName() === operationsInterfaceTypeName)\n ?.getNameNode()\n .getType()\n .getProperties()\n .map((symbol) => symbol.getName());\n\n if (!operationsInterfaceTypeProperties) {\n throw new Error(\"Failed to create operation handler object\");\n }\n\n let operationsInterfaceVariableStatement = sourceFile.getVariableStatement(\n operationsInterfaceVariableName,\n );\n\n if (!operationsInterfaceVariableStatement) {\n operationsInterfaceVariableStatement = sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: operationsInterfaceVariableName,\n type: operationsInterfaceTypeName,\n initializer: \"{}\",\n },\n ],\n });\n }\n\n const operationsInterfaceObject = getObjectLiteral(\n operationsInterfaceVariableStatement,\n );\n\n if (!operationsInterfaceObject) {\n throw new Error(\"Failed to build reducer object\");\n }\n\n // Build a lookup map from method name to operation spec to access reducer code\n const operationsByMethodName = new Map<\n string,\n (typeof module.operations)[number]\n >();\n for (const operation of module.operations) {\n if (operation.name) {\n const methodName = `${camelCase(operation.name)}Operation`;\n operationsByMethodName.set(methodName, operation);\n }\n }\n\n for (const name of operationsInterfaceTypeProperties) {\n if (operationsInterfaceObject.getProperty(name)) continue;\n\n const operationSpec = operationsByMethodName.get(name);\n const reducerCode = operationSpec?.reducer?.trim();\n\n operationsInterfaceObject.addMethod({\n name,\n parameters: [{ name: \"state\" }, { name: \"action\" }],\n statements: reducerCode\n ? [reducerCode]\n : [\n `// TODO: implement ${name} reducer`,\n ts`throw new Error(\"Reducer for '${name}' not implemented.\")`.raw,\n ],\n });\n }\n\n // Add error imports for error classes referenced in reducer code\n addErrorImportsForModule(sourceFile, module);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSrcIndexFile({\n project,\n ...variableNames\n}: DocumentModelFileMakerArgs) {\n const template = documentModelSrcIndexFileTemplate;\n const { srcDirPath } = variableNames;\n\n const filePath = path.join(srcDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelSrcUtilsFile({\n project,\n srcDirPath,\n version,\n}: DocumentModelFileMakerArgs) {\n const template = documentModelSrcUtilsTemplate;\n\n const filePath = path.join(srcDirPath, \"utils.ts\");\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (!alreadyExists) {\n const previousVersionSourceFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n\n if (previousVersionSourceFile) {\n sourceFile.replaceWithText(previousVersionSourceFile.getText());\n } else {\n sourceFile.replaceWithText(template);\n }\n }\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction addErrorImportsForModule(\n sourceFile: SourceFile,\n module: ModuleSpecification,\n): void {\n // Collect all unique errors from all operations in this module\n const allErrors: { name: string }[] = [];\n for (const operation of module.operations) {\n if (Array.isArray(operation.errors)) {\n for (const error of operation.errors) {\n if (error.name && !allErrors.find((e) => e.name === error.name)) {\n allErrors.push({ name: error.name });\n }\n }\n }\n }\n\n if (allErrors.length === 0) return;\n\n // Scan the source file content to find which error classes are actually referenced\n const sourceFileContent = sourceFile.getFullText();\n const usedErrors: string[] = [];\n\n for (const error of allErrors) {\n const errorPattern = new RegExp(`\\\\b${error.name}\\\\b`, \"g\");\n if (errorPattern.test(sourceFileContent)) {\n usedErrors.push(error.name);\n }\n }\n\n if (usedErrors.length === 0) return;\n\n const errorImportPath = `../../gen/${kebabCase(module.name)}/error.js`;\n\n const existingErrorImport = sourceFile\n .getImportDeclarations()\n .find(\n (importDecl) => importDecl.getModuleSpecifierValue() === errorImportPath,\n );\n\n if (existingErrorImport) {\n const existingNamedImports = existingErrorImport\n .getNamedImports()\n .map((namedImport) => namedImport.getName());\n\n const newErrorsToImport = usedErrors.filter(\n (errorName) => !existingNamedImports.includes(errorName),\n );\n\n if (newErrorsToImport.length > 0) {\n existingErrorImport.addNamedImports(newErrorsToImport);\n }\n } else {\n sourceFile.addImportDeclaration({\n namedImports: usedErrors,\n moduleSpecifier: errorImportPath,\n });\n }\n}\n","import type { DocumentModelFileMakerArgs } from \"@powerhousedao/codegen\";\nimport type { ModuleSpecification } from \"@powerhousedao/shared/document-model\";\nimport { ts } from \"@tmpl/core\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { getDocumentModelOperationsModuleVariableNames } from \"name-builders\";\nimport path from \"path\";\nimport {\n documentModelTestFileTemplate,\n makeActionImportNames,\n makeTestCaseForAction,\n} from \"templates\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n getPreviousVersionSourceFile,\n} from \"utils\";\n\nexport async function makeTestsDirFiles(\n fileMakerArgs: DocumentModelFileMakerArgs,\n) {\n await makeDocumentModelTestFile(fileMakerArgs);\n const modules = fileMakerArgs.modules;\n\n for (const module of modules) {\n await makeOperationModuleTestFile({ ...fileMakerArgs, module });\n }\n}\n\nasync function makeOperationModuleTestFile(\n args: DocumentModelFileMakerArgs & { module: ModuleSpecification },\n) {\n const {\n project,\n module,\n version,\n testsDirPath,\n documentModelPackageImportPath,\n versionedDocumentModelPackageImportPath,\n isPhDocumentOfTypeFunctionName,\n } = args;\n const moduleVariableNames =\n getDocumentModelOperationsModuleVariableNames(module);\n const { actions } = moduleVariableNames;\n const kebabCaseModuleName = kebabCase(module.name);\n const pascalCaseModuleName = pascalCase(module.name);\n const moduleOperationsTypeName = `${pascalCaseModuleName}Operations`;\n const filePath = path.join(testsDirPath, `${kebabCaseModuleName}.test.ts`);\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (!alreadyExists) {\n const previousVersionSourceFile = getPreviousVersionSourceFile({\n project,\n version,\n filePath,\n });\n\n if (previousVersionSourceFile) {\n sourceFile.replaceWithText(previousVersionSourceFile.getText());\n } else {\n sourceFile.replaceWithText(\n ts`\n import { generateMock } from \"document-model\";\n import { describe, expect, it } from \"vitest\";\n\n describe(\"${moduleOperationsTypeName}\", () => {\n\n });\n `.raw,\n );\n }\n }\n\n const importNames = makeActionImportNames({\n ...args,\n ...moduleVariableNames,\n });\n\n const namedImports = importNames.map((name) => ({ name }));\n\n let actionsImportDeclaration = sourceFile\n .getImportDeclarations()\n .filter((i) => !i.isTypeOnly())\n .find((importDeclaration) =>\n importDeclaration\n .getModuleSpecifier()\n .getText()\n .includes(documentModelPackageImportPath),\n );\n\n if (!actionsImportDeclaration) {\n actionsImportDeclaration = sourceFile.addImportDeclaration({\n namedImports,\n moduleSpecifier: versionedDocumentModelPackageImportPath,\n });\n } else {\n actionsImportDeclaration.setModuleSpecifier(\n versionedDocumentModelPackageImportPath,\n );\n const existingNamedImports = actionsImportDeclaration\n .getNamedImports()\n .map((value) => value.getName());\n\n for (const name of importNames) {\n if (!existingNamedImports.includes(name)) {\n actionsImportDeclaration.addNamedImport(name);\n }\n }\n }\n\n const describeCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((call) => {\n const expressionText = call.getExpression().getText();\n const args = call.getArguments();\n const firstArg = args[0];\n return (\n expressionText === \"describe\" &&\n pascalCase(firstArg.getText()).includes(moduleOperationsTypeName)\n );\n });\n\n if (!describeCall) {\n console.error(\n `Test file at path ${filePath} has no describe block for ${moduleOperationsTypeName}`,\n );\n return;\n }\n\n const describeCallBody = describeCall\n .getArguments()[1]\n .asKindOrThrow(SyntaxKind.ArrowFunction);\n\n const testCaseNames = describeCall\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((call) => {\n const expressionText = call.getExpression().getText();\n return expressionText === \"it\" || expressionText === \"test\";\n })\n .map((c) => c.getArguments()[0].getText());\n\n const actionsWithoutExistingTestCases = actions.filter((action) => {\n const camelCaseActionName = camelCase(action.name);\n return !testCaseNames.some((c) => c.includes(camelCaseActionName));\n });\n\n const testCasesToAdd = actionsWithoutExistingTestCases.map((action) =>\n makeTestCaseForAction(action, isPhDocumentOfTypeFunctionName),\n );\n\n describeCallBody.addStatements(testCasesToAdd);\n\n const GENERATE_MOCK_NAME = \"generateMock\";\n const GENERATE_MOCK_MODULE_SPECIFIER = \"@powerhousedao/codegen\";\n\n const generateMockImport = sourceFile.getImportDeclaration((i) =>\n i.getNamedImports().some((v) => v.getText().includes(GENERATE_MOCK_NAME)),\n );\n\n const hasGenerateMockInSourceFile = sourceFile\n .getText()\n .includes(GENERATE_MOCK_NAME);\n\n if (hasGenerateMockInSourceFile && !generateMockImport) {\n sourceFile.addImportDeclaration({\n namedImports: [GENERATE_MOCK_NAME],\n moduleSpecifier: GENERATE_MOCK_MODULE_SPECIFIER,\n });\n }\n\n sourceFile.fixUnusedIdentifiers();\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeDocumentModelTestFile(args: DocumentModelFileMakerArgs) {\n const { project, testsDirPath } = args;\n const template = documentModelTestFileTemplate(args);\n\n const filePath = path.join(testsDirPath, \"document-model.test.ts\");\n\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import path from \"path\";\nimport { upgradeManifestTemplate, upgradeTransitionTemplate } from \"templates\";\nimport { VariableDeclarationKind, type Project } from \"ts-morph\";\nimport {\n formatSourceFileWithPrettier,\n getObjectLiteral,\n getOrCreateSourceFile,\n getVariableDeclarationByTypeName,\n} from \"utils\";\n\ntype MakeUpgradeFileArgs = {\n project: Project;\n version: number;\n upgradesDirPath: string;\n documentModelPackageImportPath: string;\n phStateName: string;\n};\nexport async function makeUpgradeFile(args: MakeUpgradeFileArgs) {\n const {\n project,\n version,\n upgradesDirPath,\n documentModelPackageImportPath,\n phStateName,\n } = args;\n if (version < 2) return;\n\n const filePath = path.join(upgradesDirPath, `v${version}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n\n if (alreadyExists) return;\n\n const previousVersion = version - 1;\n const template = upgradeTransitionTemplate({\n version,\n previousVersion,\n documentModelPackageImportPath,\n phStateName,\n });\n\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nexport async function createOrUpdateUpgradeManifestFile(args: {\n project: Project;\n specVersions: number[];\n latestVersion: number;\n upgradesDirPath: string;\n documentModelId: string;\n upgradeManifestName: string;\n}) {\n const {\n project,\n specVersions,\n upgradesDirPath,\n documentModelId,\n upgradeManifestName,\n } = args;\n const filePath = path.join(upgradesDirPath, \"upgrade-manifest.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n const template = upgradeManifestTemplate({\n documentModelId,\n upgradeManifestName,\n });\n\n sourceFile.replaceWithText(template);\n\n const upgradeTransitionImports = buildUpgradeTransitionImports(specVersions);\n\n sourceFile.addImportDeclarations(upgradeTransitionImports);\n\n const upgradeManifestStatement = getVariableDeclarationByTypeName(\n sourceFile,\n \"UpgradeManifest\",\n )?.getVariableStatementOrThrow();\n const objectLiteral = getObjectLiteral(upgradeManifestStatement);\n const upgradesProperty = objectLiteral?.getProperty(\"upgrades\");\n const upgrades = buildUpgrades(specVersions);\n upgradesProperty?.replaceWithText(upgrades);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction buildUpgrades(specVersions: number[]) {\n const upgradeStrings: string[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n upgradeStrings.push(`v${version}`);\n }\n\n return `upgrades: { ${upgradeStrings.join(\",\\n\")} }`;\n}\n\nfunction buildUpgradeTransitionImports(specVersions: number[]) {\n const imports: {\n namedImports: string[];\n moduleSpecifier: string;\n }[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n const namedImports = [`v${version}`];\n const moduleSpecifier = `./v${version}.js`;\n imports.push({\n namedImports,\n moduleSpecifier,\n });\n }\n\n return imports;\n}\n\ntype MakeVersionConstantsFileArgs = {\n project: Project;\n upgradesDirPath: string;\n specVersions: number[];\n latestVersion: number;\n};\nexport async function createOrUpdateVersionConstantsFile({\n specVersions,\n latestVersion,\n project,\n upgradesDirPath,\n}: MakeVersionConstantsFileArgs) {\n const SUPPORTED_VERSIONS = \"supportedVersions\";\n const LATEST_VERSION = \"latestVersion\";\n const filePath = path.join(upgradesDirPath, \"versions.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(\"\");\n\n const latestVersionIndex = specVersions.indexOf(latestVersion);\n const versionInitializer = `[${specVersions.join(\", \")}] as const;`;\n const latestInitializer = `${SUPPORTED_VERSIONS}[${latestVersionIndex}];`;\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: SUPPORTED_VERSIONS,\n initializer: versionInitializer,\n },\n ],\n });\n\n sourceFile.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n isExported: true,\n declarations: [\n {\n name: LATEST_VERSION,\n initializer: latestInitializer,\n },\n ],\n });\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype MakeUpgradesIndexFileArgs = {\n project: Project;\n upgradesDirPath: string;\n upgradeManifestName: string;\n specVersions: number[];\n};\nexport async function makeUpgradesIndexFile({\n project,\n upgradesDirPath,\n specVersions,\n upgradeManifestName,\n}: MakeUpgradesIndexFileArgs) {\n const filePath = path.join(upgradesDirPath, \"index.ts\");\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n sourceFile.replaceWithText(\"\");\n\n const upgradeReducerExports = makeUpgradeReducerExports(specVersions);\n\n sourceFile.addExportDeclarations([\n {\n namedExports: [upgradeManifestName],\n moduleSpecifier: \"./upgrade-manifest.js\",\n },\n {\n namedExports: [\"supportedVersions\", \"latestVersion\"],\n moduleSpecifier: \"./versions.js\",\n },\n ...upgradeReducerExports,\n ]);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction makeUpgradeReducerExports(specVersions: number[]) {\n const exports: {\n namedExports: string[];\n moduleSpecifier: string;\n }[] = [];\n\n for (const version of specVersions) {\n if (version < 2) continue;\n const namedExports = [`v${version}`];\n const moduleSpecifier = `./v${version}.js`;\n exports.push({\n namedExports,\n moduleSpecifier,\n });\n }\n\n return exports;\n}\n","import type {\n DocumentModelFileMakerArgs,\n DocumentModelVariableNames,\n GenerateDocumentModelArgs,\n} from \"@powerhousedao/codegen\";\nimport { directoryExists, fileExists } from \"@powerhousedao/shared/clis\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport { kebabCase } from \"change-case\";\nimport {\n getDocumentModelDirName,\n getDocumentModelVariableNames,\n} from \"name-builders\";\nimport { copyFile, mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport path from \"path\";\nimport { type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getInitialStates,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { generateDocumentModelZodSchemas } from \"../../codegen/graphql.js\";\nimport {\n makeDocumentModelModulesFile,\n makeUpgradeManifestsFile,\n} from \"../module-files.js\";\nimport { makeGenDirFiles } from \"./gen-dir.js\";\nimport { migrateLegacyToVersioned } from \"./migrate-legacy.js\";\nimport { makeRootDirFiles } from \"./root-dir.js\";\nimport { makeSrcDirFiles } from \"./src-dir.js\";\nimport { makeTestsDirFiles } from \"./tests-dir.js\";\nimport {\n createOrUpdateUpgradeManifestFile,\n createOrUpdateVersionConstantsFile,\n makeUpgradeFile,\n makeUpgradesIndexFile,\n} from \"./upgrades-dir.js\";\n\n/** Generates a document model from the given `documentModelState`\n *\n * If `useVersioning` is set to true, it will generate versioned document model code\n * for each `specification` in the `documentModelState`\n */\nexport async function tsMorphGenerateDocumentModel({\n projectDir,\n documentModelState,\n useVersioning,\n migrateLegacy,\n}: GenerateDocumentModelArgs) {\n if (migrateLegacy) {\n const dmDirPath = path.join(\n projectDir,\n \"document-models\",\n getDocumentModelDirName(documentModelState),\n );\n await migrateLegacyToVersioned(dmDirPath);\n }\n\n const project = buildTsMorphProject(projectDir);\n const documentModelsSourceFilesPath = path.join(\n projectDir,\n \"document-models/**/*\",\n );\n const documentModelsDirPath = path.join(projectDir, \"document-models\");\n const documentModelDirName = getDocumentModelDirName(documentModelState);\n const documentModelDirPath = path.join(\n documentModelsDirPath,\n documentModelDirName,\n );\n const upgradesDirPath = path.join(documentModelDirPath, \"upgrades\");\n const documentModelVariableNames = getDocumentModelVariableNames(\n documentModelState.name,\n );\n await ensureDirectoriesExist(\n project,\n documentModelsDirPath,\n documentModelDirPath,\n );\n if (useVersioning) {\n await ensureDirectoriesExist(project, upgradesDirPath);\n }\n project.addSourceFilesAtPaths(documentModelsSourceFilesPath);\n\n const documentModelPackageImportPath = path.join(\n \"document-models\",\n documentModelDirName,\n );\n\n const specVersions = [\n ...new Set([\n ...documentModelState.specifications.map((spec) => spec.version),\n ]),\n ].toSorted();\n\n if (specVersions.length !== documentModelState.specifications.length) {\n throw new Error(\n \"Document model specifications array is misconfigured. Length is not match with spec versions.\",\n );\n }\n\n const latestVersion = specVersions[specVersions.length - 1];\n if (\n documentModelState.specifications[\n documentModelState.specifications.length - 1\n ].version !== latestVersion\n ) {\n throw new Error(\n \"Document model has incorrect version at the latest version index\",\n );\n }\n\n await writeDocumentModelStateJsonFile({\n documentModelState,\n documentModelDirName,\n documentModelDirPath,\n });\n\n if (useVersioning) {\n await Promise.all(\n specVersions.map(\n async (version) =>\n await generateDocumentModelForSpec({\n project,\n version,\n useVersioning: true,\n documentModelState,\n projectDir,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n }),\n ),\n );\n\n for (const version of specVersions) {\n await makeUpgradeFile({\n version,\n upgradesDirPath,\n project,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n });\n }\n\n await makeDocumentModelIndexFile({\n project,\n documentModelDirPath,\n latestVersion,\n });\n\n await createOrUpdateVersionConstantsFile({\n project,\n specVersions,\n latestVersion,\n upgradesDirPath,\n });\n\n await createOrUpdateUpgradeManifestFile({\n project,\n specVersions,\n latestVersion,\n upgradesDirPath,\n documentModelId: documentModelState.id,\n ...documentModelVariableNames,\n });\n\n await makeUpgradesIndexFile({\n project,\n upgradesDirPath,\n specVersions,\n ...documentModelVariableNames,\n });\n } else {\n await generateDocumentModelForSpec({\n project,\n useVersioning: false,\n version: latestVersion,\n documentModelState,\n projectDir,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n documentModelPackageImportPath,\n ...documentModelVariableNames,\n });\n }\n\n await project.save();\n}\n\ntype GenerateDocumentModelFromSpecArgs = {\n project: Project;\n version: number;\n useVersioning: boolean;\n documentModelState: DocumentModelGlobalState;\n projectDir: string;\n documentModelPackageImportPath: string;\n documentModelsDirPath: string;\n documentModelDirName: string;\n documentModelDirPath: string;\n} & DocumentModelVariableNames;\n/** Generates document model code for a given `specification` from a `documentModelState` object */\nasync function generateDocumentModelForSpec({\n project,\n projectDir,\n documentModelState,\n documentModelPackageImportPath,\n documentModelsDirPath,\n documentModelDirName,\n documentModelDirPath,\n useVersioning,\n version,\n ...documentModelVariableNames\n}: GenerateDocumentModelFromSpecArgs) {\n const specification = documentModelState.specifications.find(\n (spec) => spec.version === version,\n );\n\n if (!specification) {\n throw new Error(\n `Document model specifications array is misconfigured, no specification found for version: ${version}`,\n );\n }\n\n const versionDirName = useVersioning ? `v${version}` : \"\";\n\n const documentModelVersionDirName = path.join(\n documentModelDirName,\n versionDirName,\n );\n\n const documentModelVersionDirPath = path.join(\n documentModelDirPath,\n versionDirName,\n );\n\n const versionedDocumentModelPackageImportPath = path.join(\n documentModelPackageImportPath,\n versionDirName,\n );\n\n const fileExtension = documentModelState.extension;\n const documentTypeId = documentModelState.id;\n const srcDirPath = path.join(documentModelVersionDirPath, \"src\");\n const reducersDirPath = path.join(srcDirPath, \"reducers\");\n const testsDirPath = path.join(documentModelVersionDirPath, \"tests\");\n const genDirPath = path.join(documentModelVersionDirPath, \"gen\");\n const schemaDirPath = path.join(genDirPath, \"schema\");\n const { initialGlobalState, initialLocalState } = getInitialStates(\n specification.state,\n );\n const hasLocalSchema = specification.state.local.schema !== \"\";\n const modules = specification.modules;\n const moduleDirPaths = modules.map((module) =>\n path.join(genDirPath, kebabCase(module.name)),\n );\n\n await ensureDirectoriesExist(\n project,\n documentModelVersionDirPath,\n reducersDirPath,\n testsDirPath,\n schemaDirPath,\n ...moduleDirPaths,\n );\n\n const fileMakerArgs: DocumentModelFileMakerArgs = {\n project,\n projectDir,\n version,\n useVersioning,\n documentTypeId,\n documentModelState,\n initialGlobalState,\n initialLocalState,\n modules,\n hasLocalSchema,\n documentModelsDirPath,\n documentModelDirPath,\n documentModelDirName,\n documentModelVersionDirName,\n documentModelVersionDirPath,\n documentModelPackageImportPath,\n versionedDocumentModelPackageImportPath,\n srcDirPath,\n genDirPath,\n testsDirPath,\n schemaDirPath,\n reducersDirPath,\n fileExtension,\n ...documentModelVariableNames,\n };\n\n await generateDocumentModelZodSchemas({\n documentModelDirPath: documentModelVersionDirPath,\n specification,\n });\n\n await makeRootDirFiles(fileMakerArgs);\n await makeGenDirFiles(fileMakerArgs);\n await makeSrcDirFiles(fileMakerArgs);\n await makeTestsDirFiles(fileMakerArgs);\n await makeDocumentModelModulesFile(fileMakerArgs);\n\n if (!useVersioning) return;\n\n await makeUpgradeManifestsFile({\n project,\n projectDir,\n });\n\n const previousVersionDirPath = getPreviousVersionDirPath(\n documentModelDirPath,\n version,\n );\n\n if (!previousVersionDirPath) return;\n\n await persistCustomFilesFromPreviousVersion({\n currentVersionDirPath: documentModelVersionDirPath,\n previousVersionDirPath,\n });\n}\n\n/** Writes a json file derived from a `documentModelState` */\nasync function writeDocumentModelStateJsonFile({\n documentModelState,\n documentModelDirName,\n documentModelDirPath,\n}: {\n documentModelState: DocumentModelGlobalState;\n documentModelDirPath: string;\n documentModelDirName: string;\n}) {\n const filePath = path.join(\n documentModelDirPath,\n `${documentModelDirName}.json`,\n );\n const documentModelStateJson = JSON.stringify(documentModelState, null, 2);\n await writeFile(filePath, documentModelStateJson);\n}\n\nfunction getPreviousVersionDirPath(\n documentModelDirPath: string,\n version: number,\n) {\n const previousVersion = version - 1;\n if (previousVersion < 1) return;\n\n const previousVersionDirName = `v${previousVersion}`;\n\n return path.join(documentModelDirPath, previousVersionDirName);\n}\n\nasync function makeDocumentModelIndexFile(args: {\n project: Project;\n documentModelDirPath: string;\n latestVersion: number;\n}) {\n const { project, documentModelDirPath, latestVersion } = args;\n\n const filePath = path.join(documentModelDirPath, \"index.ts\");\n\n const { sourceFile } = getOrCreateSourceFile(project, filePath);\n\n sourceFile.replaceWithText(\"\");\n sourceFile.addExportDeclarations([\n { moduleSpecifier: `./v${latestVersion}/index.js` },\n { moduleSpecifier: `./upgrades/index.js` },\n ]);\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\ntype PersistCustomFilesFromPreviousVersionArgs = {\n currentVersionDirPath: string;\n previousVersionDirPath: string;\n};\nasync function persistCustomFilesFromPreviousVersion(\n args: PersistCustomFilesFromPreviousVersionArgs,\n) {\n const { currentVersionDirPath, previousVersionDirPath } = args;\n\n const previousVersionDirExists = await directoryExists(\n previousVersionDirPath,\n );\n\n if (!previousVersionDirExists) return;\n\n const previousVersionDirContents = await readdir(previousVersionDirPath, {\n withFileTypes: true,\n recursive: true,\n });\n\n const previousVersionFiles = previousVersionDirContents\n .filter((dirEnt) => dirEnt.isFile())\n .map(({ name, parentPath }) => ({\n name,\n parentPath,\n relativePath: path.relative(previousVersionDirPath, parentPath),\n }));\n\n for (const { name, relativePath } of previousVersionFiles) {\n const filePathInCurrentVersionDir = path.join(\n currentVersionDirPath,\n relativePath,\n name,\n );\n const filePathInPreviousVersionDir = path.join(\n previousVersionDirPath,\n relativePath,\n name,\n );\n const existsInPreviousVersionDir = await fileExists(\n filePathInPreviousVersionDir,\n );\n const existsInCurrentVersionDir = await fileExists(\n filePathInCurrentVersionDir,\n );\n if (existsInPreviousVersionDir && !existsInCurrentVersionDir) {\n console.log(\n `Persisting file \"${path.join(relativePath, name)}\" from previous version directory.`,\n );\n await mkdir(path.join(currentVersionDirPath, relativePath), {\n recursive: true,\n });\n await copyFile(filePathInPreviousVersionDir, filePathInCurrentVersionDir);\n }\n }\n}\n","import path from \"path\";\nimport {\n analyticsFactoryTemplate,\n analyticsIndexTemplate,\n analyticsProcessorTemplate,\n} from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\nimport type { GenerateProcessorArgs } from \"./types.js\";\n\nexport async function tsMorphGenerateAnalyticsProcessor(\n args: GenerateProcessorArgs,\n) {\n const { project, documentTypes, pascalCaseName, dirPath, camelCaseName } =\n args;\n\n await makeIndexFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeProcessorFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeFactoryFile({\n project,\n pascalCaseName,\n camelCaseName,\n dirPath,\n documentTypes,\n });\n}\n\nasync function makeIndexFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = analyticsIndexTemplate;\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"index.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeProcessorFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = analyticsProcessorTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"processor.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeFactoryFile(v: {\n project: Project;\n pascalCaseName: string;\n camelCaseName: string;\n dirPath: string;\n documentTypes: string[];\n}) {\n const template = analyticsFactoryTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"factory.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import path from \"path\";\nimport {\n relationalDbFactoryTemplate,\n relationalDbIndexTemplate,\n relationalDbMigrationsTemplate,\n relationalDbProcessorTemplate,\n relationalDbSchemaTemplate,\n} from \"templates\";\nimport type { Project } from \"ts-morph\";\nimport { formatSourceFileWithPrettier, getOrCreateSourceFile } from \"utils\";\nimport type { GenerateProcessorArgs } from \"./types.js\";\n\nexport async function tsMorphGenerateRelationalDbProcessor(\n args: GenerateProcessorArgs,\n) {\n const { project, documentTypes, camelCaseName, pascalCaseName, dirPath } =\n args;\n\n await makeIndexFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeProcessorFile({\n project,\n pascalCaseName,\n dirPath,\n });\n\n await makeFactoryFile({\n project,\n pascalCaseName,\n camelCaseName,\n dirPath,\n documentTypes,\n });\n\n await makeMigrationsFile({ project, dirPath });\n\n await makeSchemaFile({ project, dirPath });\n}\n\nasync function makeIndexFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = relationalDbIndexTemplate;\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"index.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeProcessorFile(v: {\n project: Project;\n pascalCaseName: string;\n dirPath: string;\n}) {\n const template = relationalDbProcessorTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"processor.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeFactoryFile(v: {\n project: Project;\n pascalCaseName: string;\n camelCaseName: string;\n dirPath: string;\n documentTypes: string[];\n}) {\n const template = relationalDbFactoryTemplate(v);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"factory.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeSchemaFile(v: { project: Project; dirPath: string }) {\n const template = relationalDbSchemaTemplate();\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"schema.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeMigrationsFile(v: { project: Project; dirPath: string }) {\n const template = relationalDbMigrationsTemplate();\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n v.project,\n path.join(v.dirPath, \"migrations.ts\"),\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(template);\n await formatSourceFileWithPrettier(sourceFile);\n}\n","import type {\n ProcessorApp,\n ProcessorApps,\n} from \"@powerhousedao/shared/processors\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport path from \"path\";\nimport { factoryBuildersTemplate } from \"templates\";\nimport type { SourceFile } from \"ts-morph\";\nimport { ts, type Project } from \"ts-morph\";\nimport {\n buildTsMorphProject,\n ensureDirectoriesExist,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\nimport { tsMorphGenerateAnalyticsProcessor } from \"./analytics.js\";\nimport { tsMorphGenerateRelationalDbProcessor } from \"./relational-db.js\";\n\nexport async function tsMorphGenerateProcessor(args: {\n processorName: string;\n documentTypes: string[];\n rootDir: string;\n processorType: \"relationalDb\" | \"analytics\";\n processorApps: ProcessorApps;\n}) {\n const {\n processorName,\n documentTypes,\n rootDir,\n processorType,\n processorApps,\n } = args;\n const kebabCaseName = kebabCase(processorName);\n const camelCaseName = camelCase(processorName);\n const pascalCaseName = pascalCase(processorName);\n const processorsDirPath = path.join(rootDir, \"processors\");\n const dirPath = path.join(processorsDirPath, kebabCaseName);\n const sourceFilesPath = path.join(processorsDirPath, \"**/*\");\n const project = buildTsMorphProject(rootDir);\n await ensureDirectoriesExist(project, processorsDirPath, dirPath);\n project.addSourceFilesAtPaths(sourceFilesPath);\n\n if (processorType === \"analytics\") {\n await tsMorphGenerateAnalyticsProcessor({\n processorName,\n documentTypes,\n rootDir,\n camelCaseName,\n dirPath,\n kebabCaseName,\n pascalCaseName,\n processorsDirPath,\n project,\n });\n } else {\n await tsMorphGenerateRelationalDbProcessor({\n processorName,\n documentTypes,\n rootDir,\n camelCaseName,\n dirPath,\n kebabCaseName,\n pascalCaseName,\n processorsDirPath,\n project,\n });\n }\n\n for (const processorApp of processorApps) {\n await updateFactoryBuildersFile({\n processorsDirPath,\n processorApp,\n project,\n camelCaseName,\n kebabCaseName,\n });\n }\n await project.save();\n}\n\nasync function updateFactoryBuildersFile(v: {\n project: Project;\n processorsDirPath: string;\n processorApp: ProcessorApp;\n camelCaseName: string;\n kebabCaseName: string;\n}) {\n const {\n project,\n processorsDirPath,\n processorApp,\n camelCaseName,\n kebabCaseName,\n } = v;\n const template = factoryBuildersTemplate;\n const filePath = path.join(processorsDirPath, `${processorApp}.ts`);\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (!alreadyExists) {\n sourceFile.replaceWithText(template);\n }\n const name = `${camelCaseName}FactoryBuilder`;\n const moduleSpecifier = path.join(\"processors\", kebabCaseName);\n\n const factoriesArrayName = \"processorFactoryBuilders\";\n\n let factoryBuildersArray = getFactoryBuildersArray(\n sourceFile,\n factoriesArrayName,\n );\n\n if (!factoryBuildersArray) {\n sourceFile.replaceWithText(template);\n factoryBuildersArray = getFactoryBuildersArray(\n sourceFile,\n factoriesArrayName,\n );\n }\n\n if (!factoryBuildersArray) {\n throw new Error(\n `Could not get factory builders array in file ${processorApp}.ts`,\n );\n }\n\n const importDeclaration = sourceFile\n .getImportDeclarations()\n .flatMap((importDeclaration) =>\n importDeclaration.getNamedImports().map((n) => n.getText()),\n )\n .find((n) => n === name);\n\n if (!importDeclaration) {\n sourceFile.addImportDeclaration({\n namedImports: [name],\n moduleSpecifier,\n });\n }\n\n const arrayElements = factoryBuildersArray\n .getElements()\n .map((e) => e.getText());\n\n if (!arrayElements.includes(name)) {\n factoryBuildersArray.addElement(name);\n }\n\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nfunction getFactoryBuildersArray(sourceFile: SourceFile, name: string) {\n return sourceFile\n .getDescendantsOfKind(ts.SyntaxKind.VariableStatement)\n .flatMap((d) => d.getDescendantsOfKind(ts.SyntaxKind.VariableDeclaration))\n .find((d) => d.getName() === name)\n ?.getDescendantsOfKind(ts.SyntaxKind.ArrayLiteralExpression)\n .at(0);\n}\n","import type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { existsSync } from \"fs\";\nimport path from \"path\";\nimport {\n customSubgraphResolversTemplate,\n customSubgraphSchemaTemplate,\n documentModelSubgraphResolversTemplate,\n documentModelSubgraphSchemaTemplate,\n subgraphIndexFileTemplate,\n subgraphLibFileTemplate,\n} from \"templates\";\nimport { Project } from \"ts-morph\";\nimport {\n applyGraphQLTypePrefixes,\n extractTypeNames,\n formatSourceFileWithPrettier,\n getOrCreateSourceFile,\n} from \"utils\";\n\ntype TsMorphGenerateSubgraphArgs = {\n subgraphsDir: string;\n subgraphName: string;\n documentModel: DocumentModelGlobalState | null;\n};\n\nexport async function tsMorphGenerateSubgraph(\n args: TsMorphGenerateSubgraphArgs,\n): Promise<void> {\n const { subgraphsDir, subgraphName, documentModel } = args;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n skipLoadingLibFiles: true,\n });\n\n const kebabCaseName = kebabCase(subgraphName);\n const pascalCaseName = pascalCase(subgraphName);\n const camelCaseName = camelCase(subgraphName);\n\n const subgraphDir = path.join(subgraphsDir, kebabCaseName);\n\n // Add existing files so getOrCreateSourceFile can detect them\n if (existsSync(subgraphDir)) {\n for (const name of [\"index.ts\", \"lib.ts\", \"schema.ts\", \"resolvers.ts\"]) {\n const filePath = path.join(subgraphDir, name);\n if (existsSync(filePath)) {\n project.addSourceFileAtPath(filePath);\n }\n }\n }\n\n // Always generate base subgraph files (unless_exists)\n await makeBaseSubgraphIndexFile(project, subgraphDir, {\n pascalCaseName,\n kebabCaseName,\n });\n await makeBaseSubgraphLibFile(project, subgraphDir);\n\n if (documentModel !== null) {\n // Generate document-model-specific schema and resolvers (force overwrite)\n await makeDocumentModelSubgraphFiles(project, subgraphDir, documentModel);\n } else {\n // Generate custom subgraph scaffolds (unless_exists)\n await makeCustomSubgraphFiles(project, subgraphDir, {\n pascalCaseName,\n camelCaseName,\n });\n }\n\n await project.save();\n}\n\nasync function makeBaseSubgraphIndexFile(\n project: Project,\n dirPath: string,\n v: { pascalCaseName: string; kebabCaseName: string },\n) {\n const filePath = path.join(dirPath, \"index.ts\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(subgraphIndexFileTemplate(v));\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeBaseSubgraphLibFile(project: Project, dirPath: string) {\n const filePath = path.join(dirPath, \"lib.ts\");\n const { alreadyExists, sourceFile } = getOrCreateSourceFile(\n project,\n filePath,\n );\n if (alreadyExists) return;\n sourceFile.replaceWithText(subgraphLibFileTemplate());\n await formatSourceFileWithPrettier(sourceFile);\n}\n\nasync function makeCustomSubgraphFiles(\n project: Project,\n dirPath: string,\n v: { pascalCaseName: string; camelCaseName: string },\n) {\n // Schema — skip prettier, contains gql tagged template literal\n const schemaPath = path.join(dirPath, \"schema.ts\");\n const schema = getOrCreateSourceFile(project, schemaPath);\n if (!schema.alreadyExists) {\n schema.sourceFile.replaceWithText(customSubgraphSchemaTemplate(v));\n }\n\n // Resolvers\n const resolversPath = path.join(dirPath, \"resolvers.ts\");\n const resolvers = getOrCreateSourceFile(project, resolversPath);\n if (!resolvers.alreadyExists) {\n resolvers.sourceFile.replaceWithText(customSubgraphResolversTemplate(v));\n await formatSourceFileWithPrettier(resolvers.sourceFile);\n }\n}\n\nasync function makeDocumentModelSubgraphFiles(\n project: Project,\n dirPath: string,\n documentModel: DocumentModelGlobalState,\n) {\n const latestSpec =\n documentModel.specifications[documentModel.specifications.length - 1];\n const documentType = documentModel.name;\n const pascalCaseDocumentType = pascalCase(documentType);\n const camelCaseDocumentType = camelCase(documentType);\n const phDocumentTypeName = `${pascalCaseDocumentType}Document`;\n const documentTypeVariableName = `${camelCaseDocumentType}DocumentType`;\n const kebabCaseDocumentType = kebabCase(documentType);\n const documentModelDir = `document-models/${kebabCaseDocumentType}`;\n\n const stateSchema = latestSpec.state.global.schema;\n const stateTypeNames = extractTypeNames(stateSchema);\n\n const modules = latestSpec.modules\n .filter((m): m is typeof m & { name: string } => m.name !== null)\n .map((m) => ({\n name: kebabCase(m.name),\n operations: m.operations\n .filter((op): op is typeof op & { name: string } => op.name !== null)\n .map((op) => ({\n name: op.name,\n schema: applyGraphQLTypePrefixes(\n op.schema ?? \"\",\n pascalCaseDocumentType,\n stateTypeNames,\n ),\n })),\n }));\n\n // Schema (force overwrite) — skip prettier, contains gql tagged template literal\n const schemaPath = path.join(dirPath, \"schema.ts\");\n const schema = getOrCreateSourceFile(project, schemaPath);\n schema.sourceFile.replaceWithText(\n documentModelSubgraphSchemaTemplate({\n pascalCaseDocumentType,\n modules,\n }),\n );\n\n // Resolvers (force overwrite) — skip prettier, contains template literals that confuse parser\n const resolversPath = path.join(dirPath, \"resolvers.ts\");\n const resolvers = getOrCreateSourceFile(project, resolversPath);\n resolvers.sourceFile.replaceWithText(\n documentModelSubgraphResolversTemplate({\n pascalCaseDocumentType,\n camelCaseDocumentType,\n phDocumentTypeName,\n documentTypeVariableName,\n documentModelDir,\n modules,\n }),\n );\n}\n","import path from \"path\";\nimport { IndentationText, Project } from \"ts-morph\";\n\ntype MakeSubgraphsIndexFileArgs = { projectDir: string };\nexport async function makeSubgraphsIndexFile({\n projectDir,\n}: MakeSubgraphsIndexFileArgs) {\n // use the local tsconfig.json file for a given project\n const tsConfigFilePath = path.join(projectDir, \"tsconfig.json\");\n\n const project = new Project({\n tsConfigFilePath,\n // don't add files from the tsconfig.json file, only use the ones we need\n skipAddingFilesFromTsConfig: true,\n // don't load library files, we only need the files we're adding\n skipLoadingLibFiles: true,\n // use formatting rules which match prettier\n manipulationSettings: {\n useTrailingCommas: true,\n indentationText: IndentationText.TwoSpaces,\n },\n });\n\n project.addSourceFilesAtPaths(`${projectDir}/subgraphs/**/*`);\n\n const subgraphsDir = project.getDirectory(path.join(projectDir, \"subgraphs\"));\n const subgraphsSubdirs = subgraphsDir?.getDirectories() ?? [];\n\n let subgraphsIndexSourceFile = project.getSourceFile(\n path.join(projectDir, \"subgraphs/index.ts\"),\n );\n if (!subgraphsIndexSourceFile) {\n subgraphsIndexSourceFile = project.createSourceFile(\n path.join(projectDir, \"subgraphs/index.js\"),\n \"\",\n );\n }\n\n for (const subgraphSubdir of subgraphsSubdirs) {\n const subgraphIndexSourceFilePath = `${subgraphSubdir.getPath()}/index.ts`;\n const subgraphIndexSourceFile = project.getSourceFile(\n subgraphIndexSourceFilePath,\n );\n if (!subgraphIndexSourceFile) {\n continue;\n }\n const subgraphClassExport = subgraphIndexSourceFile\n .getClasses()\n .find((c) => c.getBaseClass()?.getText().includes(\"BaseSubgraph\"));\n const subgraphClassName = subgraphClassExport?.getName();\n if (!subgraphClassName) {\n continue;\n }\n const indexFileExports = subgraphsIndexSourceFile\n .getExportDeclarations()\n .map((e) => e.getNamespaceExport()?.getText())\n .filter((e) => e !== undefined)\n .join();\n if (indexFileExports.includes(subgraphClassName)) {\n continue;\n }\n subgraphsIndexSourceFile.addExportDeclaration({\n namespaceExport: subgraphClassName,\n moduleSpecifier: `./${subgraphSubdir.getBaseName()}/index.js`,\n });\n }\n\n await project.save();\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAAgB,qBAAqB,EACnC,SACA,eACA,YACA,iBACA,UACA,+BAC2B;AAC3B,KAAI,mBAAmB,CAAC,CAAC,4BACvB,OAAM,IAAI,MACR,sEACD;CAGH,MAAM,EAAE,eAAe,sBAAsB,SAD5B,KAAK,KAAK,eAAe,YAAY,CACS;AAE/D,YAAW,gBAAgB,GAAG;CAO9B,MAAM,WAAW,iCAAiC;EAChD;EACA;EACA,sBAR2B,WAAW,WAAW;EASjD,eARoB,kBAClB,KAAK,gBAAgB,MACrB,KAAK,UAAU,4BAA4B;EAO9C,CAAC;AACF,YAAW,gBAAgB,SAAS;;;;;;;AC1BtC,SAAgB,oBAAoB,EAClC,SACA,gBACA,WAC0B;CAC1B,MAAM,sBAAsBA,OAAK,KAAK,gBAAgB,WAAW;CAGjE,IAAI,kBAAkB,QAAQ,cAAc,oBAAoB;AAEhE,KAA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