diff --git a/npm/ng-packs/packages/schematics/src/utils/index.ts b/npm/ng-packs/packages/schematics/src/utils/index.ts index eeb12e6d9e..733f656ecb 100644 --- a/npm/ng-packs/packages/schematics/src/utils/index.ts +++ b/npm/ng-packs/packages/schematics/src/utils/index.ts @@ -18,3 +18,4 @@ export * from './text'; export * from './tree'; export * from './type'; export * from './workspace'; +export * from './standalone'; diff --git a/npm/ng-packs/packages/schematics/src/utils/standalone.ts b/npm/ng-packs/packages/schematics/src/utils/standalone.ts new file mode 100644 index 0000000000..2444db3185 --- /dev/null +++ b/npm/ng-packs/packages/schematics/src/utils/standalone.ts @@ -0,0 +1,59 @@ +import { Tree } from '@angular-devkit/schematics'; +import { findBootstrapApplicationCall } from './angular/standalone/util'; +import { findAppConfig } from './angular/standalone/app_config'; +import * as ts from 'typescript'; +import { normalize, Path } from '@angular-devkit/core'; +import * as path from 'path'; + +export const getAppConfigPath = (host: Tree, mainFilePath: string): string => { + const bootstrapCall = findBootstrapApplicationCall(host, mainFilePath); + const appConfig = findAppConfig(bootstrapCall, host, mainFilePath); + return appConfig?.filePath || ''; +}; + +export function findAppRoutesPath(tree: Tree, mainFilePath: string): Path | null { + const appConfigPath = getAppConfigPath(tree, mainFilePath); + if (!appConfigPath || !tree.exists(appConfigPath)) return null; + + const buffer = tree.read(appConfigPath); + if (!buffer) return null; + + const source = ts.createSourceFile( + appConfigPath, + buffer.toString('utf-8'), + ts.ScriptTarget.Latest, + true, + ); + + for (const stmt of source.statements) { + if (!ts.isImportDeclaration(stmt)) continue; + + const importClause = stmt.importClause; + if (!importClause?.namedBindings || !ts.isNamedImports(importClause.namedBindings)) continue; + + const isRoutesImport = importClause.namedBindings.elements.some( + el => el.name.getText() === 'routes', + ); + if (!isRoutesImport || !ts.isStringLiteral(stmt.moduleSpecifier)) continue; + + let importPath = stmt.moduleSpecifier.text; + + if (!importPath.endsWith('.ts')) { + importPath += '.ts'; + } + + const configDir = path.dirname(appConfigPath); + const resolvedFsPath = path.resolve(configDir, importPath); + const workspaceRelativePath = path.relative(process.cwd(), resolvedFsPath).replace(/\\/g, '/'); + + const normalizedPath = normalize(workspaceRelativePath); + + if (!tree.exists(normalizedPath)) { + throw new Error(`Cannot find routes file: ${normalizedPath}`); + } + + return normalizedPath; + } + + return null; +}