@eui/core 22.0.0-alpha.89 → 22.0.0-alpha.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/docs/changelog.html +10 -0
- package/docs/interfaces/Edit-20.html +1 -1
- package/docs/interfaces/Edit-21.html +52 -1
- package/docs/interfaces/Edit-22.html +1 -52
- package/docs/interfaces/Schema-17.html +1 -1
- package/docs/interfaces/Schema-18.html +1 -1
- package/docs/interfaces/Schema-40.html +13 -1
- package/docs/interfaces/Schema-41.html +1 -13
- package/docs/interfaces/Schema-42.html +1 -1
- package/docs/interfaces/Schema-43.html +1 -1
- package/docs/js/search/search_index.js +2 -2
- package/docs/json/documentation.json +126 -126
- package/docs/llms.txt +33 -33
- package/docs/miscellaneous/functions.html +991 -991
- package/docs/properties.html +1 -1
- package/package.json +2 -2
|
@@ -2083,12 +2083,12 @@
|
|
|
2083
2083
|
},
|
|
2084
2084
|
{
|
|
2085
2085
|
"name": "Edit",
|
|
2086
|
-
"id": "interface-Edit-
|
|
2087
|
-
"file": "packages/core/schematics/migrate-
|
|
2086
|
+
"id": "interface-Edit-e82ad5d05a8363ecab95140e3f129427949eb3d53d4272814efdb8f6458ebc01b92b07c76d5e15e5491679d59f5b9b723c3f191c3c12257261a751583757f3fe-20",
|
|
2087
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
2088
2088
|
"deprecated": false,
|
|
2089
2089
|
"deprecationMessage": "",
|
|
2090
2090
|
"type": "interface",
|
|
2091
|
-
"sourceCode": "import {\n Binary,\n BindingPipe,\n BindingType,\n CombinedRecursiveAstVisitor,\n ImplicitReceiver,\n parseTemplate,\n PropertyRead,\n SafePropertyRead,\n TmplAstElement,\n TmplAstText,\n} from '@angular/compiler';\nimport { dirname, join, normalize } from '@angular-devkit/core';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit, TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * Migrates @ngx-translate/core v17 -> v18 breaking changes.\n *\n * No type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\n * file (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\n * templates, from the component class that owns the template.\n * shortcut: receivers that are aliased, destructured, passed through other types or declared in another\n * file are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst CORE = '@ngx-translate/core';\nconst HTTP_LOADER = '@ngx-translate/http-loader';\n\nconst TOKEN_PROVIDERS: Record<string, string> = {\n TranslateLoader: 'provideTranslateLoader',\n TranslateCompiler: 'provideTranslateCompiler',\n TranslateParser: 'provideTranslateParser',\n MissingTranslationHandler: 'provideMissingTranslationHandler',\n};\nconst PLUGIN_KEYS = ['loader', 'compiler', 'parser', 'missingTranslationHandler'];\nconst MEMBER_RENAMES: Record<string, string> = {\n setDefaultLang: 'setFallbackLang',\n getDefaultLang: 'getFallbackLang',\n onDefaultLangChange: 'onFallbackLangChange',\n};\nconst ASSIGN_OPS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.EqualsToken,\n ts.SyntaxKind.PlusEqualsToken,\n ts.SyntaxKind.MinusEqualsToken,\n ts.SyntaxKind.QuestionQuestionEqualsToken,\n ts.SyntaxKind.BarBarEqualsToken,\n ts.SyntaxKind.AmpersandAmpersandEqualsToken,\n]);\n\nexport function migrateNgxTranslate18(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const tsFiles: string[] = [];\n const htmlFiles: string[] = [];\n visitDir(tree.getDir(scanPath || '/'), (path) => (path.endsWith('.html') ? htmlFiles : tsFiles).push(path));\n\n const projectUsesNgx = tsFiles.some((f) => tree.read(f)?.toString('utf-8').includes(CORE));\n const read = (p: string): string | undefined => tree.read(p)?.toString('utf-8');\n // forChild({ extend: true }) services merge translations; setTranslation(lang, t) callers need a review then.\n const projectHasExtend = tsFiles.some((f) => {\n const s = read(f);\n return !!s && s.includes('forChild') && /extend\\s*:\\s*true/.test(s);\n });\n\n let fileCount = 0;\n const write = (path: string, original: string, result: string): void => {\n if (result === original) return;\n if (options.dryRun) logDryRun(context, `Would migrate @ngx-translate/core usages in ${path}`);\n else tree.overwrite(path, result);\n fileCount++;\n };\n\n for (const path of tsFiles) {\n const original = read(path);\n if (!original) continue;\n const hasCore = original.includes(CORE) || original.includes(HTTP_LOADER);\n if (!hasCore && !(original.includes('template') && original.includes('translate'))) continue;\n write(path, original, migrateTypeScript(original, path, context, { projectHasExtend, projectUsesNgx, read }));\n }\n\n for (const path of htmlFiles) {\n const original = read(path);\n if (!original || !/translate|currentLang/.test(original)) continue;\n const members = membersForExternalTemplate(path, tsFiles, read);\n const scan = scanTemplate(original, path, context, {\n members,\n allowKeyRewrite: true,\n checkAttributes: projectUsesNgx,\n where: (o) => `${path}:${lineOf(original, o)}`,\n });\n write(path, original, applyEdits(original, scan.edits));\n }\n\n context.logger.info(`Migrated @ngx-translate/core usages in ${fileCount} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TemplateScan {\n edits: Edit[];\n usage: { pipe: boolean; directive: boolean };\n}\n\nfunction scanTemplate(\n source: string,\n filePath: string,\n context: SchematicContext,\n opts: {\n members: Set<string>;\n allowKeyRewrite: boolean;\n checkAttributes?: boolean;\n where: (offset: number) => string;\n quiet?: boolean\n }\n): TemplateScan {\n const result: TemplateScan = { edits: [], usage: { pipe: false, directive: false } };\n let parsed;\n try {\n parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n } catch {\n return result;\n }\n if (parsed.errors && parsed.errors.length > 0) return result;\n\n const seenWarnings = new Set<string>();\n const warn = (offset: number, message: string): void => {\n const text = `${opts.where(offset)} - Manual action needed: ${message}`;\n if (opts.quiet || seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const writes = new Set<unknown>();\n const isSvc = (r: unknown): boolean =>\n r instanceof PropertyRead && r.receiver instanceof ImplicitReceiver && opts.members.has(r.name);\n\n const visitor = new (class extends CombinedRecursiveAstVisitor {\n override visitBinary(ast: Binary, context: unknown): void {\n if (ast.operation.endsWith('=') && !['==', '===', '!=', '!==', '<=', '>='].includes(ast.operation)) {\n const left = ast.left;\n if ((left instanceof PropertyRead || left instanceof SafePropertyRead) && left.name === 'currentLang' && isSvc(left.receiver)) {\n writes.add(left);\n warn(left.sourceSpan.start, 'TranslateService.currentLang is a read-only Signal in @ngx-translate/core v18; use translate.use(lang) instead of assigning it.');\n }\n }\n super.visitBinary(ast, context);\n }\n\n override visitPropertyRead(ast: PropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitPropertyRead(ast, context);\n }\n\n override visitSafePropertyRead(ast: SafePropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitSafePropertyRead(ast, context);\n }\n\n override visitPipe(ast: BindingPipe, context: unknown): void {\n if (ast.name === 'translate') result.usage.pipe = true;\n super.visitPipe(ast, context);\n }\n\n override visitElement(el: TmplAstElement): void {\n this.checkTranslateAttribute(el);\n super.visitElement(el);\n }\n\n override visitTemplate(t: Parameters<CombinedRecursiveAstVisitor['visitTemplate']>[0]): void {\n if (\n [...t.attributes, ...t.inputs, ...t.templateAttrs].some((a) => a.name === 'translate' || a.name === 'ngx-translate')\n ) {\n result.usage.directive = true;\n }\n super.visitTemplate(t);\n }\n\n private rewriteCurrentLang(ast: PropertyRead | SafePropertyRead): void {\n if (ast.name !== 'currentLang' || writes.has(ast) || !isSvc(ast.receiver)) return;\n const end = ast.nameSpan.end;\n if (/^\\s*\\(/.test(source.slice(end))) return; // already a call\n result.edits.push({ start: end, end, replacement: '()' });\n }\n\n private checkTranslateAttribute(el: TmplAstElement): void {\n if (opts.checkAttributes === false) return;\n const textAttr = el.attributes.find((a) => a.name === 'translate' || a.name === 'ngx-translate');\n const bound = el.inputs.find((i) => i.name === 'translate' && i.type === BindingType.Property);\n if (textAttr || bound) result.usage.directive = true;\n const at = el.startSourceSpan.start.offset;\n const todo = (message: string): void => {\n warn(at, `<${el.name}> ${message}`);\n const edit = createTodoEdit(source, at, message);\n if (edit) result.edits.push(edit);\n };\n\n // 7: [translate]=\"'KEY'\" now sets textContent: element children are overwritten.\n if (bound && el.children.some((c) => !(c instanceof TmplAstText))) {\n todo(\n 'with [translate] the element content is replaced by the translation (textContent) in @ngx-translate/core v18, child elements are lost. Restructure the markup.'\n );\n return;\n }\n\n // 8: <el translate>KEY</el> (text as key) is deprecated.\n if (!textAttr || textAttr.name !== 'translate' || textAttr.value !== '' || bound) return;\n const meaningful = el.children.filter((c) => !(c instanceof TmplAstText && c.value.trim() === ''));\n if (meaningful.length === 0) return;\n const only = meaningful[0];\n const isPlain =\n meaningful.length === 1 &&\n el.children.length === 1 &&\n only instanceof TmplAstText &&\n !!el.endSourceSpan &&\n source.slice(el.startSourceSpan.end.offset, el.endSourceSpan.start.offset) === only.value &&\n !/[\"'`&<>{}\\\\]/.test(only.value);\n if (!isPlain) {\n todo(\n 'uses its text content as translation key, which is deprecated and not safely convertible here (interpolation or nested elements). Use [translate]=\"\\'KEY\\'\", the translate pipe or *translateBlock.'\n );\n return;\n }\n if (!opts.allowKeyRewrite) {\n warn(at, `<${el.name}> text as translation key is deprecated; replace with [translate]=\"'KEY'\" (not rewritten inside a quoted inline template).`);\n return;\n }\n const key = (only as TmplAstText).value.trim();\n result.edits.push({\n start: textAttr.sourceSpan.start.offset,\n end: textAttr.sourceSpan.end.offset,\n replacement: `[translate]=\"'${key}'\"`,\n });\n result.edits.push({ start: el.startSourceSpan.end.offset, end: el.endSourceSpan!.start.offset, replacement: '' });\n }\n })();\n\n for (const node of parsed.nodes) visitor.visit(node);\n return result;\n}\n\n/** Members typed/injected as TranslateService of the component whose templateUrl points at `htmlPath`. */\nfunction membersForExternalTemplate(htmlPath: string, tsFiles: string[], read: (p: string) => string | undefined): Set<string> {\n const dir = dirOf(htmlPath);\n for (const f of tsFiles) {\n if (dirOf(f) !== dir || f.endsWith('.spec.ts')) continue;\n const src = read(f);\n if (!src || !src.includes('templateUrl') || !src.includes(CORE)) continue;\n const sf = ts.createSourceFile(f, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const helper = new ServiceResolver(sf);\n for (const stmt of sf.statements) {\n if (!ts.isClassDeclaration(stmt)) continue;\n const url = componentProp(stmt, 'templateUrl');\n if (url && ts.isStringLiteralLike(url.initializer) && resolveUrl(dir, url.initializer.text) === normalize(htmlPath)) {\n return helper.members(stmt);\n }\n }\n }\n return new Set();\n}\n\nfunction componentObject(cls: ts.ClassDeclaration): ts.ObjectLiteralExpression | undefined {\n for (const d of ts.getDecorators(cls) ?? []) {\n if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === 'Component') {\n const arg = d.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg)) return arg;\n }\n }\n return undefined;\n}\n\nfunction componentProp(cls: ts.ClassDeclaration, name: string): ts.PropertyAssignment | undefined {\n return componentObject(cls)?.properties.find(\n (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name\n );\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TranslateService receiver resolution\n// ---------------------------------------------------------------------------------------------------------------------\n\nclass ServiceResolver {\n readonly svcName: string | undefined;\n private cache = new Map<ts.Node, Set<string>>();\n\n constructor(private readonly sf: ts.SourceFile, typeName = 'TranslateService') {\n this.svcName = importedLocalName(sf, typeName);\n }\n\n isType(t: ts.TypeNode | undefined): boolean {\n return !!this.svcName && !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === this.svcName;\n }\n\n isInject(e: ts.Expression | undefined): boolean {\n if (!this.svcName || !e) return false;\n const x = unwrap(e);\n if (!ts.isCallExpression(x)) return false;\n const c = x.expression;\n const named = (ts.isIdentifier(c) && c.text === 'inject') || (ts.isPropertyAccessExpression(c) && c.name.text === 'inject');\n const a = x.arguments[0];\n return named && !!a && ts.isIdentifier(a) && a.text === this.svcName;\n }\n\n members(cls: ts.ClassLikeDeclaration): Set<string> {\n const cached = this.cache.get(cls);\n if (cached) return cached;\n const set = new Set<string>();\n for (const m of cls.members) {\n if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && (this.isType(m.type) || this.isInject(m.initializer))) set.add(m.name.text);\n if (ts.isConstructorDeclaration(m)) {\n for (const p of m.parameters) {\n const isProp = ts.getModifiers(p)?.some((x) =>\n [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(x.kind)\n );\n if (isProp && ts.isIdentifier(p.name) && this.isType(p.type)) set.add(p.name.text);\n }\n }\n }\n this.cache.set(cls, set);\n return set;\n }\n\n /** true: declared as TranslateService, false: declared as something else, undefined: not found. */\n bare(id: ts.Identifier): boolean | undefined {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if (\n (ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) &&\n cur.initializer &&\n ts.isVariableDeclarationList(cur.initializer)\n ) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return this.isType(d.type) || (ts.isVariableDeclaration(d) && this.isInject(d.initializer));\n }\n return undefined;\n }\n\n isService(expr: ts.Expression): boolean {\n const e = unwrap(expr);\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) {\n for (let cur: ts.Node | undefined = e.parent; cur; cur = cur.parent) {\n if (ts.isClassLike(cur)) return this.members(cur).has(e.name.text);\n }\n return false;\n }\n return ts.isIdentifier(e) && this.bare(e) === true;\n }\n}\n\nfunction unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n return e;\n}\n\n/** Local name of a non-type-only named import of `imported` from @ngx-translate/core. */\nfunction importedLocalName(sf: ts.SourceFile, imported: string, module = CORE): string | undefined {\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== module) continue;\n const nb = stmt.importClause?.namedBindings;\n if (!nb || !ts.isNamedImports(nb)) continue;\n for (const el of nb.elements) if ((el.propertyName ?? el.name).text === imported) return el.name.text;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TsEnv {\n projectHasExtend: boolean;\n projectUsesNgx: boolean;\n read: (p: string) => string | undefined;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext, env: TsEnv): string {\n const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const resolver = new ServiceResolver(sf);\n const edits: Edit[] = [];\n const todos = new Map<number, { anchor: ts.Node; messages: string[] }>();\n const needed = new Set<string>();\n const touched = new Set<string>();\n const handled = new Set<ts.Node>();\n const moves = new Map<ts.ObjectLiteralExpression, { calls: ts.CallExpression[]; texts: string[] }>();\n const moduleName = importedLocalName(sf, 'TranslateModule') === 'TranslateModule' ? 'TranslateModule' : undefined;\n const setValueName = importedLocalName(sf, 'setValue') === 'setValue' ? 'setValue' : undefined;\n const defaultEvent = importedLocalName(sf, 'DefaultLangChangeEvent') === 'DefaultLangChangeEvent';\n const tokenImported = (t: string): boolean => importedLocalName(sf, t) === t;\n const providerNames = new Set(['provideTranslateService'].filter((n) => importedLocalName(sf, n) === n));\n let importProvidersTouched = false;\n\n const seenWarnings = new Set<string>();\n const warnOnce = (text: string): void => {\n if (seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const storeResolver = new ServiceResolver(sf, 'TranslateStore');\n const httpNames = new Set(\n ['provideTranslateHttpLoader', 'TranslateHttpLoader'].map((n) => importedLocalName(sf, n, HTTP_LOADER)).filter((n): n is string => !!n)\n );\n const iServiceName = importedLocalName(sf, 'ITranslateService');\n const lineNo = (node: ts.Node): number => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n const flag = (node: ts.Node, message: string, comment = true): void => {\n warnOnce(`${filePath}:${lineNo(node)} - Manual action needed: ${message}`);\n if (!comment) return;\n const anchor = anchorOf(node);\n const key = anchor.getStart(sf);\n const entry = todos.get(key) ?? { anchor, messages: [] };\n const clean = sanitize(message);\n if (!entry.messages.includes(clean)) entry.messages.push(clean);\n todos.set(key, entry);\n };\n\n const nameOf = (n: ts.PropertyName | undefined): string | undefined =>\n n && (ts.isIdentifier(n) || ts.isStringLiteral(n)) ? n.text : undefined;\n const propOf = (obj: ts.ObjectLiteralExpression, name: string): ts.ObjectLiteralElementLike | undefined =>\n obj.properties.find((p) => !!p.name && nameOf(p.name) === name);\n\n // ----- config object transforms (defaultLanguage, useDefaultLang, plugin providers, extend/isolate) -----\n const CHILD_UNSUPPORTED = ['defaultLanguage', 'fallbackLang', 'lang', 'langs', 'useDefaultLang'];\n const transformConfig = (obj: ts.ObjectLiteralExpression, dropChildProps: boolean, out: Edit[], childTarget = false): number => {\n const drop = new Set<ts.ObjectLiteralElementLike>();\n for (const p of obj.properties) {\n const name = nameOf(p.name);\n if (!name) continue;\n if (childTarget && CHILD_UNSUPPORTED.includes(name) && ts.isPropertyAssignment(p)) {\n drop.add(p);\n flag(p, `${name} was removed: ChildTranslateServiceConfig has no such option, child services inherit the parent's fallbackLang and language. Set it on the root provideTranslateService() if needed.`);\n continue;\n }\n if (name === 'defaultLanguage') {\n if (ts.isPropertyAssignment(p)) out.push({\n start: p.name.getStart(sf),\n end: p.name.getEnd(),\n replacement: 'fallbackLang',\n });\n else if (ts.isShorthandPropertyAssignment(p)) out.push({\n start: p.getStart(sf),\n end: p.getEnd(),\n replacement: 'fallbackLang: defaultLanguage',\n });\n } else if (name === 'useDefaultLang' && ts.isPropertyAssignment(p)) {\n if (p.initializer.kind === ts.SyntaxKind.TrueKeyword) {\n drop.add(p);\n } else {\n flag(\n p,\n 'useDefaultLang was removed in @ngx-translate/core v18 and is kept only because its value is false: v18 always falls back to fallbackLang when it is set. Remove the leftover property manually (it does not compile as is); drop fallbackLang too if you relied on useDefaultLang: false.'\n );\n }\n } else if (dropChildProps && (name === 'extend' || name === 'isolate') && ts.isPropertyAssignment(p)) {\n drop.add(p);\n } else if (PLUGIN_KEYS.includes(name) && ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {\n const init = p.initializer;\n const provide = propOf(init, 'provide');\n const token = provide && ts.isPropertyAssignment(provide) && ts.isIdentifier(provide.initializer) ? provide.initializer.text : undefined;\n if (!token || !TOKEN_PROVIDERS[token]) continue;\n const useClass = propOf(init, 'useClass');\n if (init.properties.length === 2 && useClass && ts.isPropertyAssignment(useClass) && tokenImported(token)) {\n const fn = TOKEN_PROVIDERS[token];\n out.push({\n start: init.getStart(sf),\n end: init.getEnd(),\n replacement: `${fn}(${useClass.initializer.getText(sf)})`,\n });\n needed.add(fn);\n touched.add(token);\n } else {\n flag(\n p,\n `the ${token} provider uses a form other than { provide, useClass } (useFactory/useValue/deps). Convert it manually to ${TOKEN_PROVIDERS[token]}(...).`\n );\n }\n }\n }\n if (drop.size > 0) out.push(...removeArrayElements(obj, new Set([...drop].map((d) => obj.properties.indexOf(d))), sf));\n return drop.size;\n };\n\n // ----- TranslateModule.forRoot / forChild -----\n const convertModuleCall = (call: ts.CallExpression): void => {\n const callee = call.expression as ts.PropertyAccessExpression;\n handled.add(callee.expression);\n const method = callee.name.text;\n const args = call.arguments;\n const undecidable = (why: string): void =>\n flag(call, `TranslateModule.${method}() was left unchanged: ${why}. Use provideTranslateService() / provideChildTranslateService() manually.`);\n\n if (args.length > 1 || (args.length === 1 && !ts.isObjectLiteralExpression(args[0]))) return undecidable('its config is not an object literal');\n const obj = args[0] as ts.ObjectLiteralExpression | undefined;\n let fn = method === 'forRoot' ? 'provideTranslateService' : 'provideChildTranslateService';\n let hadExtendTrue = false;\n if (method === 'forChild' && obj) {\n for (const p of obj.properties) {\n const name = p.name ? nameOf(p.name) : undefined;\n if (ts.isSpreadAssignment(p)) return undecidable('its config contains a spread');\n if (name !== 'isolate' && name !== 'extend') continue;\n const init = ts.isPropertyAssignment(p) ? p.initializer.kind : undefined;\n if (init !== ts.SyntaxKind.TrueKeyword && init !== ts.SyntaxKind.FalseKeyword) return undecidable(`${name} is not a boolean literal`);\n if (name === 'isolate' && init === ts.SyntaxKind.TrueKeyword) fn = 'provideTranslateService';\n if (name === 'extend' && init === ts.SyntaxKind.TrueKeyword) hadExtendTrue = true;\n }\n }\n\n // the placement is decided first, so nothing is emitted for an unmovable call\n const parent = call.parent;\n let move: ts.ObjectLiteralExpression | undefined;\n let unwrapImportProviders: ts.CallExpression | undefined;\n if (ts.isArrayLiteralExpression(parent) && ts.isPropertyAssignment(parent.parent) && nameOf(parent.parent.name) === 'imports' && ts.isObjectLiteralExpression(parent.parent.parent)) {\n const owner = parent.parent.parent;\n const decorator = owner.parent;\n if (ts.isCallExpression(decorator) && ts.isIdentifier(decorator.expression) && decorator.expression.text === 'Component') {\n return undecidable('a standalone @Component cannot take environment providers; provide it in the application/route providers instead');\n }\n move = owner;\n } else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'importProvidersFrom') {\n if (parent.arguments.length !== 1) return undecidable('it is combined with other sources in importProvidersFrom()');\n unwrapImportProviders = parent;\n }\n\n const local: Edit[] = [];\n const removed = obj ? transformConfig(obj, method === 'forChild', local, fn === 'provideChildTranslateService') : 0;\n const keepConfig = !!obj && obj.properties.length - removed > 0;\n const cfgText = keepConfig ? applyEdits(source.slice(obj!.getStart(sf), obj!.getEnd()), shift(local, -obj!.getStart(sf))) : '';\n const text = `${fn}(${cfgText})`;\n needed.add(fn);\n touched.add('TranslateModule');\n if (method === 'forChild') {\n warnOnce(\n `${filePath}:${lineNo(call)} - forChild() was converted to ${fn}(): v18 child services use their own store with parent fallback, review isolation semantics.${hadExtendTrue ? ' extend: true was removed: setTranslation(lang, t) no longer merges, pass true as third argument where needed.' : ''}`\n );\n }\n\n if (move) {\n const g = moves.get(move) ?? { calls: [], texts: [] };\n g.calls.push(call);\n g.texts.push(text);\n moves.set(move, g);\n } else if (unwrapImportProviders) {\n edits.push({ start: unwrapImportProviders.getStart(sf), end: unwrapImportProviders.getEnd(), replacement: text });\n importProvidersTouched = true;\n } else {\n edits.push({ start: call.getStart(sf), end: call.getEnd(), replacement: text });\n }\n };\n\n // ----- bare TranslateModule in imports/exports -----\n const convertBareModule = (id: ts.Identifier, arr: ts.ArrayLiteralExpression, owner: ts.ObjectLiteralExpression): void => {\n handled.add(id);\n const callNode = owner.parent;\n const kind = ts.isCallExpression(callNode) && ts.isIdentifier(callNode.expression) ? callNode.expression.text : '';\n let names = ['TranslatePipe', 'TranslateDirective'];\n if (kind === 'Component') {\n const u = componentUsage(owner);\n if (u) names = [u.pipe ? 'TranslatePipe' : '', u.directive ? 'TranslateDirective' : ''].filter(Boolean);\n }\n const present = new Set(arr.elements.filter(ts.isIdentifier).map((e) => e.text));\n const add = names.filter((n) => !present.has(n));\n touched.add('TranslateModule');\n for (const n of names) needed.add(n);\n if (add.length > 0) {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: add.join(', ') });\n } else {\n edits.push(...removeArrayElements(arr, new Set([arr.elements.indexOf(id)]), sf));\n }\n };\n\n const componentUsage = (owner: ts.ObjectLiteralExpression): { pipe: boolean; directive: boolean } | null => {\n const tpl = propOf(owner, 'template');\n const url = propOf(owner, 'templateUrl');\n const quiet = { members: new Set<string>(), allowKeyRewrite: false, where: (): string => '', quiet: true };\n if (tpl && ts.isPropertyAssignment(tpl) && (ts.isNoSubstitutionTemplateLiteral(tpl.initializer) || ts.isStringLiteral(tpl.initializer))) {\n const lit = tpl.initializer;\n return scanTemplate(source.slice(lit.getStart(sf) + 1, lit.getEnd() - 1), filePath, context, quiet).usage;\n }\n if (url && ts.isPropertyAssignment(url) && ts.isStringLiteralLike(url.initializer)) {\n const target = resolveUrl(dirOf(filePath), url.initializer.text);\n const html = env.read(target);\n if (html !== undefined) return scanTemplate(html, target, context, quiet).usage;\n }\n return null;\n };\n\n // ----- visitor -----\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n\n if (ts.isCallExpression(node)) visitCall(node);\n else if (ts.isPropertyAccessExpression(node)) visitMember(node);\n else if (ts.isVariableDeclaration(node)) visitAlias(node.name, node.initializer, node);\n else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) visitAlias(undefined, node.right, node);\n else if (ts.isIdentifier(node)) visitIdentifier(node);\n else if (ts.isClassDeclaration(node)) visitInlineTemplate(node);\n\n ts.forEachChild(node, visit);\n };\n\n const visitCall = (call: ts.CallExpression): void => {\n const c = call.expression;\n if (moduleName && ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === moduleName && (c.name.text === 'forRoot' || c.name.text === 'forChild')) {\n convertModuleCall(call);\n return;\n }\n if (ts.isIdentifier(c) && providerNames.has(c.text) && call.arguments[0] && ts.isObjectLiteralExpression(call.arguments[0])) {\n transformConfig(call.arguments[0], false, edits);\n }\n if (setValueName && ts.isIdentifier(c) && c.text === setValueName) {\n const a0 = call.arguments[0];\n const assignable = !!a0 && (ts.isIdentifier(a0) || ts.isPropertyAccessExpression(a0) || ts.isElementAccessExpression(a0));\n if (ts.isExpressionStatement(call.parent) && call.arguments.length === 3 && assignable) {\n edits.push({ start: c.getStart(sf), end: c.getEnd(), replacement: `${a0.getText(sf)} = insertValue` });\n needed.add('insertValue');\n touched.add('setValue');\n } else {\n flag(call, 'setValue() was replaced by insertValue(), which returns a new object instead of mutating its argument. Use `target = insertValue(target, key, value)` manually.');\n }\n }\n if (ts.isPropertyAccessExpression(c) && resolver.isService(c.expression)) {\n if (c.name.text === 'getCurrentLang') {\n flag(call, 'getCurrentLang() returns Language | null in @ngx-translate/core v18 (null before a language is set). Handle the null case, e.g. `?? fallback`.');\n } else if (c.name.text === 'setTranslation' && call.arguments.length === 2 && env.projectHasExtend) {\n flag(call, 'setTranslation(lang, translations) no longer merges for services that used forChild({ extend: true }); pass `true` as third argument if you relied on merging.');\n }\n }\n };\n\n const visitMember = (n: ts.PropertyAccessExpression): void => {\n const member = n.name.text;\n if ((member === 'onTranslationChange' || member === 'getValue') && storeResolver.isService(n.expression)) {\n edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: member === 'getValue' ? 'getTranslationValue' : 'translationChange$',\n });\n return;\n }\n const isTracked = ['currentLang', 'langs', 'defaultLang', ...Object.keys(MEMBER_RENAMES)].includes(member);\n if (!isTracked || !resolver.isService(n.expression)) return;\n const parent = n.parent;\n if (MEMBER_RENAMES[member]) {\n edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: MEMBER_RENAMES[member] });\n return;\n }\n if (ts.isCallExpression(parent) && parent.expression === n) return; // already `currentLang()` etc.\n const isWrite =\n (ts.isBinaryExpression(parent) && parent.left === n && ASSIGN_OPS.has(parent.operatorToken.kind)) ||\n ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&\n (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) ||\n ts.isDeleteExpression(parent);\n if (isWrite) {\n flag(n, `${member} cannot be assigned in @ngx-translate/core v18 (read-only Signal / removed). Use use(), setFallbackLang() or setTranslation() instead.`);\n return;\n }\n if (member === 'currentLang') edits.push({ start: n.getEnd(), end: n.getEnd(), replacement: '()' });\n else if (member === 'langs') edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: 'getLangs()',\n });\n else edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: 'fallbackLang()' });\n };\n\n const visitAlias = (name: ts.BindingName | undefined, init: ts.Expression | undefined, at: ts.Node): void => {\n if (!init) return;\n if (!resolver.isService(init) && !(name && ts.isObjectBindingPattern(name) && resolver.isInject(init))) return;\n if (name && ts.isIdentifier(name) && ts.isVariableDeclaration(at) && resolver.isType(at.type)) return; // typed alias is tracked\n flag(\n at,\n 'TranslateService is aliased or destructured here, so currentLang/default*/langs usages through it are not migrated automatically. Review them against the v18 API (currentLang() signal, fallbackLang, getLangs()).'\n );\n };\n\n const visitIdentifier = (id: ts.Identifier): void => {\n const p = id.parent;\n if ((ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id)) return;\n if (httpNames.has(id.text)) {\n const call = ts.isCallExpression(p) && p.expression === id ? p : undefined;\n const cfg = call?.arguments[0];\n const hasFlag = !!cfg && ts.isObjectLiteralExpression(cfg) && !!propOf(cfg, 'failOnError');\n if (!hasFlag) {\n flag(id, 'the v18 http-loader no longer fails the whole language load when a translation file request fails (it logs a warning and uses {}). Pass failOnError: true to provideTranslateHttpLoader() if you rely on the v17 behaviour.');\n }\n }\n if (iServiceName && id.text === iServiceName && ts.isExpressionWithTypeArguments(p) && ts.isHeritageClause(p.parent) && p.parent.token === ts.SyntaxKind.ImplementsKeyword) {\n flag(id, 'ITranslateService gained isLoading: Signal<boolean> in @ngx-translate/core v18. Add isLoading = signal(false).asReadonly() to this class.');\n }\n if (defaultEvent && id.text === 'DefaultLangChangeEvent') {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: 'FallbackLangChangeEvent' });\n needed.add('FallbackLangChangeEvent');\n touched.add('DefaultLangChangeEvent');\n }\n if (moduleName && id.text === moduleName && !handled.has(id)) {\n // `TranslateModule` as an element of imports / exports\n if (ts.isArrayLiteralExpression(p) && ts.isPropertyAssignment(p.parent) && ['imports', 'exports'].includes(nameOf(p.parent.name) ?? '') && ts.isObjectLiteralExpression(p.parent.parent)) {\n convertBareModule(id, p, p.parent.parent);\n }\n }\n };\n\n const visitInlineTemplate = (cls: ts.ClassDeclaration): void => {\n const tpl = componentProp(cls, 'template');\n if (!tpl) return;\n const lit = tpl.initializer;\n if (!ts.isNoSubstitutionTemplateLiteral(lit) && !ts.isStringLiteral(lit)) return;\n const start = lit.getStart(sf) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (!/translate|currentLang/.test(raw)) return;\n const baseLine = sf.getLineAndCharacterOfPosition(start).line;\n const scan = scanTemplate(raw, filePath, context, {\n members: resolver.members(cls),\n allowKeyRewrite: ts.isNoSubstitutionTemplateLiteral(lit),\n checkAttributes: env.projectUsesNgx,\n where: (o) => `${filePath}:${baseLine + lineOf(raw, o)}`,\n });\n edits.push(...shift(scan.edits, start));\n };\n\n visit(sf);\n\n // moved forRoot/forChild calls: imports -> providers\n for (const [obj, g] of moves) {\n const importsProp = propOf(obj, 'imports') as ts.PropertyAssignment;\n const arr = importsProp.initializer as ts.ArrayLiteralExpression;\n const providersProp = propOf(obj, 'providers');\n if (providersProp && !(ts.isPropertyAssignment(providersProp) && ts.isArrayLiteralExpression(providersProp.initializer))) {\n for (const call of g.calls) flag(call, 'the providers property is not an array literal, so the converted provider could not be moved there. Move it manually.');\n continue;\n }\n const texts = g.texts.join(', ');\n const movedIdx = new Set(g.calls.map((c) => arr.elements.indexOf(c)));\n const keepsOthers = arr.elements.length > movedIdx.size;\n if (providersProp) {\n const parr = (providersProp as ts.PropertyAssignment).initializer as ts.ArrayLiteralExpression;\n if (parr.elements.length > 0) {\n edits.push({\n start: parr.elements[parr.elements.length - 1].getEnd(),\n end: parr.elements[parr.elements.length - 1].getEnd(),\n replacement: `, ${texts}`,\n });\n } else {\n edits.push({ start: parr.getStart(sf) + 1, end: parr.getEnd() - 1, replacement: texts });\n }\n if (keepsOthers) edits.push(...removeArrayElements(arr, movedIdx, sf));\n else removeObjectProperty(importsProp, sf, edits);\n } else if (!keepsOthers) {\n edits.push({ start: importsProp.getStart(sf), end: importsProp.getEnd(), replacement: `providers: [${texts}]` });\n } else {\n edits.push(...removeArrayElements(arr, movedIdx, sf));\n const multiline = source.slice(obj.getStart(sf), importsProp.getEnd()).includes('\\n');\n const indent = multiline ? /[ \\t]*$/.exec(source.slice(0, importsProp.getStart(sf)))![0] : '';\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({\n start: importsProp.getEnd(),\n end: importsProp.getEnd(),\n replacement: multiline ? `,${eol}${indent}providers: [${texts}]` : `, providers: [${texts}]`,\n });\n }\n }\n\n // remaining references to the removed module\n if (moduleName) {\n const mark = (n: ts.Node): void => {\n if (ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === moduleName && !handled.has(n) && !isPropertyName(n)) {\n flag(n, 'TranslateModule was removed in @ngx-translate/core v18. Use provideTranslateService() / provideChildTranslateService() and import TranslatePipe / TranslateDirective directly.');\n }\n ts.forEachChild(n, mark);\n };\n mark(sf);\n }\n\n // TODO comments, one line above the anchor, never duplicated\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n for (const { anchor, messages } of todos.values()) {\n const start = anchor.getStart(sf);\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1;\n const indent = /^[ \\t]*/.exec(source.slice(lineStart))![0];\n const above = new Set<string>();\n const lines = source.slice(0, lineStart).split(/\\r?\\n/);\n for (let i = lines.length - 2; i >= 0 && lines[i].trim().startsWith('// ' + TODO_PREFIX); i--) above.add(lines[i].trim());\n const fresh = messages.map((m) => `// ${TODO_PREFIX} ${m}`).filter((l) => !above.has(l));\n if (fresh.length > 0) edits.push({\n start: lineStart,\n end: lineStart,\n replacement: fresh.map((l) => `${indent}${l}${eol}`).join(''),\n });\n }\n\n let result = applyEdits(source, edits);\n if (result === source) return source;\n result = fixImports(result, filePath, CORE, needed, touched);\n if (importProvidersTouched) result = fixImports(result, filePath, '@angular/core', new Set(), new Set(['importProvidersFrom']));\n return result;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Imports\n// ---------------------------------------------------------------------------------------------------------------------\n\nconst RENAME_IN_PLACE: Record<string, string> = {\n DefaultLangChangeEvent: 'FallbackLangChangeEvent',\n setValue: 'insertValue',\n};\n\n/**\n * Drops `touched` specifiers that are no longer referenced (renaming in place when a rename is known) and\n * appends the `needed` names to the first named import of `moduleName`.\n */\nfunction fixImports(text: string, filePath: string, moduleName: string, needed: Set<string>, touched: Set<string>): string {\n const sf = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const referenced = (name: string): boolean => {\n let found = false;\n const walk = (n: ts.Node): void => {\n if (found || ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === name && !isPropertyName(n)) found = true;\n ts.forEachChild(n, walk);\n };\n walk(sf);\n return found;\n };\n\n const decls = sf.statements.filter(\n (s): s is ts.ImportDeclaration =>\n ts.isImportDeclaration(s) &&\n ts.isStringLiteral(s.moduleSpecifier) &&\n s.moduleSpecifier.text === moduleName &&\n !!s.importClause?.namedBindings &&\n ts.isNamedImports(s.importClause.namedBindings) &&\n !s.importClause.isTypeOnly\n );\n if (decls.length === 0) return text;\n\n const all = new Set<string>();\n for (const d of decls) for (const e of (d.importClause!.namedBindings as ts.NamedImports).elements) all.add(e.name.text);\n const placed = new Set<string>();\n const edits: Edit[] = [];\n const pendingNeeded = [...needed];\n\n decls.forEach((d, di) => {\n const named = d.importClause!.namedBindings as ts.NamedImports;\n const items: string[] = [];\n for (const e of named.elements) {\n const name = e.name.text;\n if (touched.has(name) && !e.propertyName && !referenced(name)) {\n const to = RENAME_IN_PLACE[name];\n if (to && needed.has(to) && !all.has(to) && !placed.has(to)) {\n items.push(to);\n placed.add(to);\n }\n continue;\n }\n items.push(e.getText(sf));\n }\n if (di === 0) {\n for (const n of pendingNeeded) if (!all.has(n) && !placed.has(n) && !items.includes(n)) items.push(n);\n }\n const before = named.elements.map((e) => e.getText(sf));\n if (items.length === before.length && items.every((v, i) => v === before[i])) return;\n if (items.length === 0 && !d.importClause!.name) {\n let end = d.getEnd();\n if (text[end] === '\\r') end++;\n if (text[end] === '\\n') end++;\n edits.push({ start: d.getStart(sf), end, replacement: '' });\n } else {\n const multiline = named.getText(sf).includes('\\n');\n const body = multiline ? `{\\n ${items.join(',\\n ')},\\n}` : `{ ${items.join(', ')} }`;\n edits.push({ start: named.getStart(sf), end: named.getEnd(), replacement: body });\n }\n });\n return applyEdits(text, edits);\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------------------------------------------------\n\nfunction isPropertyName(id: ts.Identifier): boolean {\n const p = id.parent;\n return (ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id);\n}\n\nfunction sanitize(message: string): string {\n return message.replace(/\\s+/g, ' ').trim();\n}\n\n/** Nearest ancestor that is a statement, class member or object property: the TODO goes on the line above it. */\nfunction anchorOf(node: ts.Node): ts.Node {\n let cur = node;\n while (cur.parent) {\n const p = cur.parent;\n if (ts.isSourceFile(p) || ts.isBlock(p) || ts.isModuleBlock(p) || ts.isClassLike(p) || ts.isObjectLiteralExpression(p) || ts.isCaseClause(p) || ts.isDefaultClause(p)) {\n return cur;\n }\n cur = p;\n }\n return cur;\n}\n\nconst dirOf = (p: string): string => dirname(normalize(p));\nconst resolveUrl = (dir: string, url: string): string => normalize(join(normalize(dir), url));\n\nfunction lineOf(source: string, offset: number): number {\n return source.slice(0, offset).split('\\n').length;\n}\n\nfunction shift(edits: Edit[], by: number): Edit[] {\n return edits.map((e) => ({ ...e, start: e.start + by, end: e.end + by }));\n}\n\n/** Removes one object property together with its separating comma. */\nfunction removeObjectProperty(prop: ts.ObjectLiteralElementLike, sf: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sf.getFullText();\n let start = prop.getStart(sf);\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getStart(sf);\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\n/** Removes the array elements at `indices`; non-overlapping ranges even for neighbouring elements. */\nfunction removeArrayElements(arr: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression, indices: Set<number>, sf: ts.SourceFile): Edit[] {\n const els: readonly ts.Node[] = ts.isArrayLiteralExpression(arr) ? arr.elements : arr.properties;\n const keptIdx = els.findIndex((_, i) => !indices.has(i));\n if (keptIdx === -1) return [{ start: arr.getStart(sf) + 1, end: arr.getEnd() - 1, replacement: '' }];\n const out: Edit[] = [];\n if (keptIdx > 0) out.push({ start: els[0].getStart(sf), end: els[keptIdx].getStart(sf), replacement: '' });\n for (let i = keptIdx + 1; i < els.length; i++) {\n if (indices.has(i)) out.push({ start: els[i - 1].getEnd(), end: els[i].getEnd(), replacement: '' });\n }\n return out;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const seen = new Map<string, Edit>();\n for (const e of edits) seen.set(`${e.start}:${e.end}:${e.replacement}`, e);\n let result = source;\n for (const e of [...seen.values()].sort((a, b) => b.start - a.start || b.end - a.end)) {\n result = result.slice(0, e.start) + e.replacement + result.slice(e.end);\n }\n return result;\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2091
|
+
"sourceCode": "import { BindingType, parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit } from '../utils/todo-comment';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst OLD_CLASS = 'EuiTooltipConfig';\nconst NEW_INTERFACE = 'EuiTooltipInterface';\nconst REMOVED_ANIMATION = 'showHide';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\n\nconst RENAMED_INPUTS: Record<string, string> = {\n isPrimary: 'euiTooltipPrimary',\n isSecondary: 'euiTooltipSecondary',\n isInfo: 'euiTooltipInfo',\n isSuccess: 'euiTooltipSuccess',\n isWarning: 'euiTooltipWarning',\n isDanger: 'euiTooltipDanger',\n isAccent: 'euiTooltipAccent',\n};\n\nexport function migrateEuiTooltip(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n let result = original;\n if (path.endsWith('.html')) {\n if (!original.includes('euiTooltip')) return;\n result = migrateTemplate(original, path, context);\n } else {\n if (\n !original.includes(OLD_CLASS) &&\n !original.includes(REMOVED_ANIMATION) &&\n !original.includes('euiTooltip') &&\n !original.includes(DIRECTIVE_CLASS)\n ) {\n return;\n }\n if (original.includes(OLD_CLASS)) result = migrateTypeScript(result, path, context);\n if (result.includes(DIRECTIVE_CLASS)) result = migrateProgrammaticUsage(result, path, context);\n if (result.includes(REMOVED_ANIMATION)) result = removeShowHideAnimation(result, path, context);\n if (result.includes('euiTooltip')) result = migrateInlineTemplates(result, path, context);\n }\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-tooltip usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n fileCount++;\n }\n });\n\n context.logger.info(`Migrated eui-tooltip usages in ${fileCount} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n\n // Track if EuiTooltipInterface is already imported\n let hasInterfaceImport = false;\n let classImportDecl: ts.ImportDeclaration | null = null;\n let classImportModuleSpecifier: string | null = null;\n\n // First pass: analyze imports\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === NEW_INTERFACE) {\n hasInterfaceImport = true;\n }\n if (specifier.name.text === OLD_CLASS) {\n classImportDecl = stmt;\n classImportModuleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n }\n }\n }\n\n // Second pass: handle import declarations\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n const specifiers = namedBindings.elements;\n const classSpecifier = specifiers.find((s) => s.name.text === OLD_CLASS);\n if (!classSpecifier) continue;\n\n if (hasInterfaceImport) {\n // EuiTooltipInterface is already imported elsewhere → remove EuiTooltipConfig from this import\n removeImportSpecifier(namedBindings, classSpecifier, sourceFile, edits);\n } else {\n // Rename EuiTooltipConfig → EuiTooltipInterface in the import\n edits.push({\n start: classSpecifier.name.getStart(sourceFile),\n end: classSpecifier.name.getEnd(),\n replacement: NEW_INTERFACE,\n });\n hasInterfaceImport = true;\n }\n }\n\n // Third pass: replace `new EuiTooltipConfig(...)` → spread/cast to interface\n const visitNewExpressions = (node: ts.Node): void => {\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) {\n const args = node.arguments;\n if (args !== undefined && args.length === 1) {\n const arg = args[0];\n // `new EuiTooltipConfig({ ... })` → `{ ... } as EuiTooltipInterface`\n // But if the argument is just a variable, we keep it: `varName as EuiTooltipInterface`\n const argText = source.slice(arg.getStart(sourceFile), arg.getEnd());\n\n if (ts.isObjectLiteralExpression(arg)) {\n // Inline object: `new EuiTooltipConfig({ x: 1 })` → `{ x: 1 }`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n } else {\n // Variable or expression: `new EuiTooltipConfig(opts)` → `opts`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n }\n } else if (args === undefined || args.length === 0) {\n // `new EuiTooltipConfig()` → `{} as EuiTooltipInterface`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: `{} as ${NEW_INTERFACE}`,\n });\n }\n return; // don't recurse into children we've already replaced\n }\n ts.forEachChild(node, visitNewExpressions);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitNewExpressions(stmt);\n }\n }\n\n // Fourth pass: rename all remaining identifier references (type annotations, etc.)\n const visitRefs = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n // Skip nodes we already covered in new expressions\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) return;\n\n if (ts.isIdentifier(node) && node.text === OLD_CLASS) {\n // Ensure this is not part of an import declaration\n if (!isPartOfImport(node)) {\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: NEW_INTERFACE,\n });\n }\n }\n ts.forEachChild(node, visitRefs);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitRefs(stmt);\n }\n }\n\n return applyEdits(source, edits);\n}\n\n/** Removes the `showHide` animation (import + `animations: [...]` entries) imported from an @eui package. */\nfunction removeShowHideAnimation(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue;\n if (!stmt.moduleSpecifier.text.startsWith('@eui/')) continue;\n const named = stmt.importClause?.namedBindings;\n if (!named || !ts.isNamedImports(named)) continue;\n const spec = named.elements.find((e) => e.name.text === REMOVED_ANIMATION && !e.propertyName);\n if (!spec) continue;\n found = true;\n removeImportSpecifier(named, spec, sourceFile, edits);\n }\n if (!found) return source;\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'animations' &&\n ts.isArrayLiteralExpression(node.initializer)\n ) {\n const arr = node.initializer;\n const kept = arr.elements.filter((e) => !(ts.isIdentifier(e) && e.text === REMOVED_ANIMATION));\n if (kept.length !== arr.elements.length) {\n if (kept.length === 0) {\n removeObjectProperty(node, sourceFile, edits);\n } else {\n edits.push({\n start: arr.getStart(sourceFile) + 1,\n end: arr.getEnd() - 1,\n replacement: kept.map((e) => e.getText(sourceFile)).join(', '),\n });\n }\n }\n } else if (ts.isIdentifier(node) && node.text === REMOVED_ANIMATION && !isPartOfImport(node) && !isInRemovedArray(node)) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n context.logger.warn(`${filePath}:${line + 1} - Manual action needed: the \"showHide\" animation has been removed from @eui/components.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction isInRemovedArray(node: ts.Node): boolean {\n const parent = node.parent;\n return (\n !!parent &&\n ts.isArrayLiteralExpression(parent) &&\n ts.isPropertyAssignment(parent.parent) &&\n ts.isIdentifier(parent.parent.name) &&\n parent.parent.name.text === 'animations'\n );\n}\n\nfunction removeObjectProperty(prop: ts.PropertyAssignment, sourceFile: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sourceFile.getFullText();\n let start = prop.getFullStart();\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getFullStart();\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\nfunction migrateInlineTemplates(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'template' &&\n (ts.isNoSubstitutionTemplateLiteral(node.initializer) || ts.isStringLiteral(node.initializer))\n ) {\n const lit = node.initializer;\n const start = lit.getStart(sourceFile) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (raw.includes('euiTooltip')) {\n const migrated = migrateTemplate(raw, filePath, context);\n if (migrated !== raw) edits.push({ start, end: lit.getEnd() - 1, replacement: migrated });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction migrateTemplate(source: string, filePath: string, context: SchematicContext): string {\n const parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n const edits: Edit[] = [];\n visitNodes(parsed.nodes, source, filePath, context, edits);\n return applyEdits(source, edits);\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n forEachElement(nodes, (node) => collectElementEdits(node, source, filePath, context, edits));\n}\n\nfunction collectElementEdits(el: TmplAstElement, source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n const tooltipAttr = el.attributes.find((a) => a.name === 'euiTooltip');\n const tooltipInput = el.inputs.find((i) => i.name === 'euiTooltip' && i.type === BindingType.Property);\n if (!tooltipAttr && !tooltipInput) return;\n\n // All messages of one element are merged into ONE comment: several TODOs would be inserted at the\n // same offset and overwrite each other.\n const messages: string[] = [];\n const warn = (offset: number, message: string): void => {\n messages.push(message);\n const { line } = lineOf(source, offset);\n context.logger.warn(`${filePath}:${line} - Manual action needed on <${el.name}>: ${message}`);\n };\n\n for (const attr of el.attributes) {\n if (RENAMED_INPUTS[attr.name]) {\n edits.push({ start: attr.keySpan!.start.offset, end: attr.keySpan!.end.offset, replacement: RENAMED_INPUTS[attr.name] });\n }\n }\n for (const input of el.inputs) {\n if (input.type === BindingType.Property && RENAMED_INPUTS[input.name]) {\n edits.push({ start: input.keySpan!.start.offset, end: input.keySpan!.end.offset, replacement: RENAMED_INPUTS[input.name] });\n }\n }\n\n // `position`: the migration guide lists it as removed, but EuiTooltipDirective still declares it\n // (model()). Deleting it would silently change behavior, so it is kept and flagged.\n const position = [\n ...el.attributes.filter((a) => a.name === 'position'),\n ...el.inputs.filter((i) => i.type === BindingType.Property && i.name === 'position'),\n ][0];\n if (position) {\n warn(\n position.sourceSpan.start.offset,\n 'input position of euiTooltip is documented as removed in eUI v22 but is still declared by EuiTooltipDirective. It was kept unchanged; verify it against the version you upgrade to.',\n );\n }\n\n const config = el.inputs.find((i) => i.type === BindingType.Property && i.name === 'config');\n if (config) {\n warn(\n config.sourceSpan.start.offset,\n 'input config of euiTooltip has been removed. Use the individual inputs (euiTooltip, euiTooltipPrimary, showDelay, hideDelay, contentAlignment, isDisabled) instead.',\n );\n }\n\n if (tooltipAttr && !tooltipAttr.value && !tooltipInput) {\n warn(tooltipAttr.sourceSpan.start.offset, 'input euiTooltip is now required and needs a value, e.g. euiTooltip=\"My tooltip\".');\n }\n\n if (messages.length > 0) {\n const todo = createTodoEdit(source, el.startSourceSpan.start.offset, messages.join(' '));\n if (todo) edits.push(todo);\n }\n}\n\n/**\n * Programmatic usage of a `EuiTooltipDirective` reference (`tt.isPrimary = true`, `tt.config`).\n * Renamed flags are renamed; `config` cannot be migrated and is flagged. Name based, scope aware for\n * parameters/variables (a differently typed parameter with the same name is left alone).\n * shortcut: only `this.x` and locals/params typed `EuiTooltipDirective` are followed; aliases are not.\n */\nfunction migrateProgrammaticUsage(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const isTyped = (t: ts.TypeNode | undefined): boolean =>\n !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === DIRECTIVE_CLASS;\n const isViewChildOf = (n: ts.PropertyDeclaration): boolean =>\n (ts.getDecorators?.(n) ?? []).some(\n (d) =>\n ts.isCallExpression(d.expression) &&\n ['ViewChild', 'ContentChild'].includes(d.expression.expression.getText(sourceFile)) &&\n d.expression.arguments[0]?.getText(sourceFile) === DIRECTIVE_CLASS,\n );\n\n const props = new Set<string>();\n const collect = (n: ts.Node): void => {\n if (ts.isPropertyDeclaration(n) && ts.isIdentifier(n.name) && (isTyped(n.type) || isViewChildOf(n))) props.add(n.name.text);\n ts.forEachChild(n, collect);\n };\n collect(sourceFile);\n\n /** Nearest declaration of a bare identifier: true = typed directive, false = something else, undefined = none found. */\n const bareIsDirective = (id: ts.Identifier): boolean | undefined => {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return isTyped(d.type);\n }\n return undefined;\n };\n\n const visit = (n: ts.Node): void => {\n if (ts.isPropertyAccessExpression(n) && (RENAMED_INPUTS[n.name.text] || n.name.text === 'config')) {\n const target = n.expression;\n const tracked =\n (ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword && props.has(target.name.text)) ||\n (ts.isIdentifier(target) && bareIsDirective(target) === true);\n if (tracked) {\n if (RENAMED_INPUTS[n.name.text]) {\n edits.push({ start: n.name.getStart(sourceFile), end: n.name.getEnd(), replacement: RENAMED_INPUTS[n.name.text] });\n } else {\n const { line } = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));\n context.logger.warn(\n `${filePath}:${line + 1} - Manual action needed: the \"config\" input of EuiTooltipDirective has been removed. Use the individual inputs instead.`,\n );\n }\n }\n }\n ts.forEachChild(n, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction lineOf(source: string, offset: number): { line: number } {\n return { line: source.slice(0, offset).split('\\n').length };\n}\n\nfunction isPartOfImport(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current) {\n if (ts.isImportDeclaration(current)) return true;\n current = current.parent;\n }\n return false;\n}\n\nfunction removeImportSpecifier(\n namedImports: ts.NamedImports,\n specifier: ts.ImportSpecifier,\n sourceFile: ts.SourceFile,\n edits: Edit[],\n): void {\n const elements = namedImports.elements;\n if (elements.length === 1) {\n // Remove the entire import declaration\n const importDecl = namedImports.parent.parent;\n let end = importDecl.getEnd();\n // Also remove trailing newline if present\n const fullText = sourceFile.getFullText();\n if (fullText[end] === '\\n') end++;\n edits.push({\n start: importDecl.getStart(sourceFile),\n end,\n replacement: '',\n });\n } else {\n // Remove just this specifier with surrounding comma/whitespace\n const idx = elements.indexOf(specifier);\n let start: number;\n let end: number;\n if (idx < elements.length - 1) {\n // Not the last → remove from this specifier start to next specifier start\n start = specifier.getStart(sourceFile);\n end = elements[idx + 1].getStart(sourceFile);\n } else {\n // Last element → remove from previous element end to this end\n start = elements[idx - 1].getEnd();\n end = specifier.getEnd();\n }\n edits.push({ start, end, replacement: '' });\n }\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n for (const edit of unique.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2092
2092
|
"displayName": "Edit",
|
|
2093
2093
|
"properties": [
|
|
2094
2094
|
{
|
|
@@ -2100,7 +2100,7 @@
|
|
|
2100
2100
|
"indexKey": "",
|
|
2101
2101
|
"optional": false,
|
|
2102
2102
|
"description": "",
|
|
2103
|
-
"line":
|
|
2103
|
+
"line": 15,
|
|
2104
2104
|
"rawdescription": "\n"
|
|
2105
2105
|
},
|
|
2106
2106
|
{
|
|
@@ -2112,7 +2112,7 @@
|
|
|
2112
2112
|
"indexKey": "",
|
|
2113
2113
|
"optional": false,
|
|
2114
2114
|
"description": "",
|
|
2115
|
-
"line":
|
|
2115
|
+
"line": 16,
|
|
2116
2116
|
"rawdescription": "\n"
|
|
2117
2117
|
},
|
|
2118
2118
|
{
|
|
@@ -2124,7 +2124,7 @@
|
|
|
2124
2124
|
"indexKey": "",
|
|
2125
2125
|
"optional": false,
|
|
2126
2126
|
"description": "",
|
|
2127
|
-
"line":
|
|
2127
|
+
"line": 14,
|
|
2128
2128
|
"rawdescription": "\n"
|
|
2129
2129
|
}
|
|
2130
2130
|
],
|
|
@@ -2142,12 +2142,12 @@
|
|
|
2142
2142
|
},
|
|
2143
2143
|
{
|
|
2144
2144
|
"name": "Edit",
|
|
2145
|
-
"id": "interface-Edit-
|
|
2146
|
-
"file": "packages/core/schematics/migrate-
|
|
2145
|
+
"id": "interface-Edit-85d506677a88d24ac5314a45baa87ebcf9819f4d8375ebff75fd7dd3eb56602606744787c8eaa07b0049a17bfeb30b2ad99fb4b760709d0c66b30365ae949899-21",
|
|
2146
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
2147
2147
|
"deprecated": false,
|
|
2148
2148
|
"deprecationMessage": "",
|
|
2149
2149
|
"type": "interface",
|
|
2150
|
-
"sourceCode": "import { BindingType, parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit } from '../utils/todo-comment';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst OLD_CLASS = 'EuiTooltipConfig';\nconst NEW_INTERFACE = 'EuiTooltipInterface';\nconst REMOVED_ANIMATION = 'showHide';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\n\nconst RENAMED_INPUTS: Record<string, string> = {\n isPrimary: 'euiTooltipPrimary',\n isSecondary: 'euiTooltipSecondary',\n isInfo: 'euiTooltipInfo',\n isSuccess: 'euiTooltipSuccess',\n isWarning: 'euiTooltipWarning',\n isDanger: 'euiTooltipDanger',\n isAccent: 'euiTooltipAccent',\n};\n\nexport function migrateEuiTooltip(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n let result = original;\n if (path.endsWith('.html')) {\n if (!original.includes('euiTooltip')) return;\n result = migrateTemplate(original, path, context);\n } else {\n if (\n !original.includes(OLD_CLASS) &&\n !original.includes(REMOVED_ANIMATION) &&\n !original.includes('euiTooltip') &&\n !original.includes(DIRECTIVE_CLASS)\n ) {\n return;\n }\n if (original.includes(OLD_CLASS)) result = migrateTypeScript(result, path, context);\n if (result.includes(DIRECTIVE_CLASS)) result = migrateProgrammaticUsage(result, path, context);\n if (result.includes(REMOVED_ANIMATION)) result = removeShowHideAnimation(result, path, context);\n if (result.includes('euiTooltip')) result = migrateInlineTemplates(result, path, context);\n }\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-tooltip usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n fileCount++;\n }\n });\n\n context.logger.info(`Migrated eui-tooltip usages in ${fileCount} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n\n // Track if EuiTooltipInterface is already imported\n let hasInterfaceImport = false;\n let classImportDecl: ts.ImportDeclaration | null = null;\n let classImportModuleSpecifier: string | null = null;\n\n // First pass: analyze imports\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === NEW_INTERFACE) {\n hasInterfaceImport = true;\n }\n if (specifier.name.text === OLD_CLASS) {\n classImportDecl = stmt;\n classImportModuleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n }\n }\n }\n\n // Second pass: handle import declarations\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n const specifiers = namedBindings.elements;\n const classSpecifier = specifiers.find((s) => s.name.text === OLD_CLASS);\n if (!classSpecifier) continue;\n\n if (hasInterfaceImport) {\n // EuiTooltipInterface is already imported elsewhere → remove EuiTooltipConfig from this import\n removeImportSpecifier(namedBindings, classSpecifier, sourceFile, edits);\n } else {\n // Rename EuiTooltipConfig → EuiTooltipInterface in the import\n edits.push({\n start: classSpecifier.name.getStart(sourceFile),\n end: classSpecifier.name.getEnd(),\n replacement: NEW_INTERFACE,\n });\n hasInterfaceImport = true;\n }\n }\n\n // Third pass: replace `new EuiTooltipConfig(...)` → spread/cast to interface\n const visitNewExpressions = (node: ts.Node): void => {\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) {\n const args = node.arguments;\n if (args !== undefined && args.length === 1) {\n const arg = args[0];\n // `new EuiTooltipConfig({ ... })` → `{ ... } as EuiTooltipInterface`\n // But if the argument is just a variable, we keep it: `varName as EuiTooltipInterface`\n const argText = source.slice(arg.getStart(sourceFile), arg.getEnd());\n\n if (ts.isObjectLiteralExpression(arg)) {\n // Inline object: `new EuiTooltipConfig({ x: 1 })` → `{ x: 1 }`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n } else {\n // Variable or expression: `new EuiTooltipConfig(opts)` → `opts`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n }\n } else if (args === undefined || args.length === 0) {\n // `new EuiTooltipConfig()` → `{} as EuiTooltipInterface`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: `{} as ${NEW_INTERFACE}`,\n });\n }\n return; // don't recurse into children we've already replaced\n }\n ts.forEachChild(node, visitNewExpressions);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitNewExpressions(stmt);\n }\n }\n\n // Fourth pass: rename all remaining identifier references (type annotations, etc.)\n const visitRefs = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n // Skip nodes we already covered in new expressions\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) return;\n\n if (ts.isIdentifier(node) && node.text === OLD_CLASS) {\n // Ensure this is not part of an import declaration\n if (!isPartOfImport(node)) {\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: NEW_INTERFACE,\n });\n }\n }\n ts.forEachChild(node, visitRefs);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitRefs(stmt);\n }\n }\n\n return applyEdits(source, edits);\n}\n\n/** Removes the `showHide` animation (import + `animations: [...]` entries) imported from an @eui package. */\nfunction removeShowHideAnimation(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue;\n if (!stmt.moduleSpecifier.text.startsWith('@eui/')) continue;\n const named = stmt.importClause?.namedBindings;\n if (!named || !ts.isNamedImports(named)) continue;\n const spec = named.elements.find((e) => e.name.text === REMOVED_ANIMATION && !e.propertyName);\n if (!spec) continue;\n found = true;\n removeImportSpecifier(named, spec, sourceFile, edits);\n }\n if (!found) return source;\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'animations' &&\n ts.isArrayLiteralExpression(node.initializer)\n ) {\n const arr = node.initializer;\n const kept = arr.elements.filter((e) => !(ts.isIdentifier(e) && e.text === REMOVED_ANIMATION));\n if (kept.length !== arr.elements.length) {\n if (kept.length === 0) {\n removeObjectProperty(node, sourceFile, edits);\n } else {\n edits.push({\n start: arr.getStart(sourceFile) + 1,\n end: arr.getEnd() - 1,\n replacement: kept.map((e) => e.getText(sourceFile)).join(', '),\n });\n }\n }\n } else if (ts.isIdentifier(node) && node.text === REMOVED_ANIMATION && !isPartOfImport(node) && !isInRemovedArray(node)) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n context.logger.warn(`${filePath}:${line + 1} - Manual action needed: the \"showHide\" animation has been removed from @eui/components.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction isInRemovedArray(node: ts.Node): boolean {\n const parent = node.parent;\n return (\n !!parent &&\n ts.isArrayLiteralExpression(parent) &&\n ts.isPropertyAssignment(parent.parent) &&\n ts.isIdentifier(parent.parent.name) &&\n parent.parent.name.text === 'animations'\n );\n}\n\nfunction removeObjectProperty(prop: ts.PropertyAssignment, sourceFile: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sourceFile.getFullText();\n let start = prop.getFullStart();\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getFullStart();\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\nfunction migrateInlineTemplates(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'template' &&\n (ts.isNoSubstitutionTemplateLiteral(node.initializer) || ts.isStringLiteral(node.initializer))\n ) {\n const lit = node.initializer;\n const start = lit.getStart(sourceFile) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (raw.includes('euiTooltip')) {\n const migrated = migrateTemplate(raw, filePath, context);\n if (migrated !== raw) edits.push({ start, end: lit.getEnd() - 1, replacement: migrated });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction migrateTemplate(source: string, filePath: string, context: SchematicContext): string {\n const parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n const edits: Edit[] = [];\n visitNodes(parsed.nodes, source, filePath, context, edits);\n return applyEdits(source, edits);\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n forEachElement(nodes, (node) => collectElementEdits(node, source, filePath, context, edits));\n}\n\nfunction collectElementEdits(el: TmplAstElement, source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n const tooltipAttr = el.attributes.find((a) => a.name === 'euiTooltip');\n const tooltipInput = el.inputs.find((i) => i.name === 'euiTooltip' && i.type === BindingType.Property);\n if (!tooltipAttr && !tooltipInput) return;\n\n // All messages of one element are merged into ONE comment: several TODOs would be inserted at the\n // same offset and overwrite each other.\n const messages: string[] = [];\n const warn = (offset: number, message: string): void => {\n messages.push(message);\n const { line } = lineOf(source, offset);\n context.logger.warn(`${filePath}:${line} - Manual action needed on <${el.name}>: ${message}`);\n };\n\n for (const attr of el.attributes) {\n if (RENAMED_INPUTS[attr.name]) {\n edits.push({ start: attr.keySpan!.start.offset, end: attr.keySpan!.end.offset, replacement: RENAMED_INPUTS[attr.name] });\n }\n }\n for (const input of el.inputs) {\n if (input.type === BindingType.Property && RENAMED_INPUTS[input.name]) {\n edits.push({ start: input.keySpan!.start.offset, end: input.keySpan!.end.offset, replacement: RENAMED_INPUTS[input.name] });\n }\n }\n\n // `position`: the migration guide lists it as removed, but EuiTooltipDirective still declares it\n // (model()). Deleting it would silently change behavior, so it is kept and flagged.\n const position = [\n ...el.attributes.filter((a) => a.name === 'position'),\n ...el.inputs.filter((i) => i.type === BindingType.Property && i.name === 'position'),\n ][0];\n if (position) {\n warn(\n position.sourceSpan.start.offset,\n 'input position of euiTooltip is documented as removed in eUI v22 but is still declared by EuiTooltipDirective. It was kept unchanged; verify it against the version you upgrade to.',\n );\n }\n\n const config = el.inputs.find((i) => i.type === BindingType.Property && i.name === 'config');\n if (config) {\n warn(\n config.sourceSpan.start.offset,\n 'input config of euiTooltip has been removed. Use the individual inputs (euiTooltip, euiTooltipPrimary, showDelay, hideDelay, contentAlignment, isDisabled) instead.',\n );\n }\n\n if (tooltipAttr && !tooltipAttr.value && !tooltipInput) {\n warn(tooltipAttr.sourceSpan.start.offset, 'input euiTooltip is now required and needs a value, e.g. euiTooltip=\"My tooltip\".');\n }\n\n if (messages.length > 0) {\n const todo = createTodoEdit(source, el.startSourceSpan.start.offset, messages.join(' '));\n if (todo) edits.push(todo);\n }\n}\n\n/**\n * Programmatic usage of a `EuiTooltipDirective` reference (`tt.isPrimary = true`, `tt.config`).\n * Renamed flags are renamed; `config` cannot be migrated and is flagged. Name based, scope aware for\n * parameters/variables (a differently typed parameter with the same name is left alone).\n * shortcut: only `this.x` and locals/params typed `EuiTooltipDirective` are followed; aliases are not.\n */\nfunction migrateProgrammaticUsage(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const isTyped = (t: ts.TypeNode | undefined): boolean =>\n !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === DIRECTIVE_CLASS;\n const isViewChildOf = (n: ts.PropertyDeclaration): boolean =>\n (ts.getDecorators?.(n) ?? []).some(\n (d) =>\n ts.isCallExpression(d.expression) &&\n ['ViewChild', 'ContentChild'].includes(d.expression.expression.getText(sourceFile)) &&\n d.expression.arguments[0]?.getText(sourceFile) === DIRECTIVE_CLASS,\n );\n\n const props = new Set<string>();\n const collect = (n: ts.Node): void => {\n if (ts.isPropertyDeclaration(n) && ts.isIdentifier(n.name) && (isTyped(n.type) || isViewChildOf(n))) props.add(n.name.text);\n ts.forEachChild(n, collect);\n };\n collect(sourceFile);\n\n /** Nearest declaration of a bare identifier: true = typed directive, false = something else, undefined = none found. */\n const bareIsDirective = (id: ts.Identifier): boolean | undefined => {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return isTyped(d.type);\n }\n return undefined;\n };\n\n const visit = (n: ts.Node): void => {\n if (ts.isPropertyAccessExpression(n) && (RENAMED_INPUTS[n.name.text] || n.name.text === 'config')) {\n const target = n.expression;\n const tracked =\n (ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword && props.has(target.name.text)) ||\n (ts.isIdentifier(target) && bareIsDirective(target) === true);\n if (tracked) {\n if (RENAMED_INPUTS[n.name.text]) {\n edits.push({ start: n.name.getStart(sourceFile), end: n.name.getEnd(), replacement: RENAMED_INPUTS[n.name.text] });\n } else {\n const { line } = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));\n context.logger.warn(\n `${filePath}:${line + 1} - Manual action needed: the \"config\" input of EuiTooltipDirective has been removed. Use the individual inputs instead.`,\n );\n }\n }\n }\n ts.forEachChild(n, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction lineOf(source: string, offset: number): { line: number } {\n return { line: source.slice(0, offset).split('\\n').length };\n}\n\nfunction isPartOfImport(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current) {\n if (ts.isImportDeclaration(current)) return true;\n current = current.parent;\n }\n return false;\n}\n\nfunction removeImportSpecifier(\n namedImports: ts.NamedImports,\n specifier: ts.ImportSpecifier,\n sourceFile: ts.SourceFile,\n edits: Edit[],\n): void {\n const elements = namedImports.elements;\n if (elements.length === 1) {\n // Remove the entire import declaration\n const importDecl = namedImports.parent.parent;\n let end = importDecl.getEnd();\n // Also remove trailing newline if present\n const fullText = sourceFile.getFullText();\n if (fullText[end] === '\\n') end++;\n edits.push({\n start: importDecl.getStart(sourceFile),\n end,\n replacement: '',\n });\n } else {\n // Remove just this specifier with surrounding comma/whitespace\n const idx = elements.indexOf(specifier);\n let start: number;\n let end: number;\n if (idx < elements.length - 1) {\n // Not the last → remove from this specifier start to next specifier start\n start = specifier.getStart(sourceFile);\n end = elements[idx + 1].getStart(sourceFile);\n } else {\n // Last element → remove from previous element end to this end\n start = elements[idx - 1].getEnd();\n end = specifier.getEnd();\n }\n edits.push({ start, end, replacement: '' });\n }\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n for (const edit of unique.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2150
|
+
"sourceCode": "import {\n Binary,\n BindingPipe,\n BindingType,\n CombinedRecursiveAstVisitor,\n ImplicitReceiver,\n parseTemplate,\n PropertyRead,\n SafePropertyRead,\n TmplAstElement,\n TmplAstText,\n} from '@angular/compiler';\nimport { dirname, join, normalize } from '@angular-devkit/core';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit, TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * Migrates @ngx-translate/core v17 -> v18 breaking changes.\n *\n * No type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\n * file (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\n * templates, from the component class that owns the template.\n * shortcut: receivers that are aliased, destructured, passed through other types or declared in another\n * file are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst CORE = '@ngx-translate/core';\nconst HTTP_LOADER = '@ngx-translate/http-loader';\n\nconst TOKEN_PROVIDERS: Record<string, string> = {\n TranslateLoader: 'provideTranslateLoader',\n TranslateCompiler: 'provideTranslateCompiler',\n TranslateParser: 'provideTranslateParser',\n MissingTranslationHandler: 'provideMissingTranslationHandler',\n};\nconst PLUGIN_KEYS = ['loader', 'compiler', 'parser', 'missingTranslationHandler'];\nconst MEMBER_RENAMES: Record<string, string> = {\n setDefaultLang: 'setFallbackLang',\n getDefaultLang: 'getFallbackLang',\n onDefaultLangChange: 'onFallbackLangChange',\n};\nconst ASSIGN_OPS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.EqualsToken,\n ts.SyntaxKind.PlusEqualsToken,\n ts.SyntaxKind.MinusEqualsToken,\n ts.SyntaxKind.QuestionQuestionEqualsToken,\n ts.SyntaxKind.BarBarEqualsToken,\n ts.SyntaxKind.AmpersandAmpersandEqualsToken,\n]);\n\nexport function migrateNgxTranslate18(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const tsFiles: string[] = [];\n const htmlFiles: string[] = [];\n visitDir(tree.getDir(scanPath || '/'), (path) => (path.endsWith('.html') ? htmlFiles : tsFiles).push(path));\n\n const projectUsesNgx = tsFiles.some((f) => tree.read(f)?.toString('utf-8').includes(CORE));\n const read = (p: string): string | undefined => tree.read(p)?.toString('utf-8');\n // forChild({ extend: true }) services merge translations; setTranslation(lang, t) callers need a review then.\n const projectHasExtend = tsFiles.some((f) => {\n const s = read(f);\n return !!s && s.includes('forChild') && /extend\\s*:\\s*true/.test(s);\n });\n\n let fileCount = 0;\n const write = (path: string, original: string, result: string): void => {\n if (result === original) return;\n if (options.dryRun) logDryRun(context, `Would migrate @ngx-translate/core usages in ${path}`);\n else tree.overwrite(path, result);\n fileCount++;\n };\n\n for (const path of tsFiles) {\n const original = read(path);\n if (!original) continue;\n const hasCore = original.includes(CORE) || original.includes(HTTP_LOADER);\n if (!hasCore && !(original.includes('template') && original.includes('translate'))) continue;\n write(path, original, migrateTypeScript(original, path, context, { projectHasExtend, projectUsesNgx, read }));\n }\n\n for (const path of htmlFiles) {\n const original = read(path);\n if (!original || !/translate|currentLang/.test(original)) continue;\n const members = membersForExternalTemplate(path, tsFiles, read);\n const scan = scanTemplate(original, path, context, {\n members,\n allowKeyRewrite: true,\n checkAttributes: projectUsesNgx,\n where: (o) => `${path}:${lineOf(original, o)}`,\n });\n write(path, original, applyEdits(original, scan.edits));\n }\n\n context.logger.info(`Migrated @ngx-translate/core usages in ${fileCount} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TemplateScan {\n edits: Edit[];\n usage: { pipe: boolean; directive: boolean };\n}\n\nfunction scanTemplate(\n source: string,\n filePath: string,\n context: SchematicContext,\n opts: {\n members: Set<string>;\n allowKeyRewrite: boolean;\n checkAttributes?: boolean;\n where: (offset: number) => string;\n quiet?: boolean\n }\n): TemplateScan {\n const result: TemplateScan = { edits: [], usage: { pipe: false, directive: false } };\n let parsed;\n try {\n parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n } catch {\n return result;\n }\n if (parsed.errors && parsed.errors.length > 0) return result;\n\n const seenWarnings = new Set<string>();\n const warn = (offset: number, message: string): void => {\n const text = `${opts.where(offset)} - Manual action needed: ${message}`;\n if (opts.quiet || seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const writes = new Set<unknown>();\n const isSvc = (r: unknown): boolean =>\n r instanceof PropertyRead && r.receiver instanceof ImplicitReceiver && opts.members.has(r.name);\n\n const visitor = new (class extends CombinedRecursiveAstVisitor {\n override visitBinary(ast: Binary, context: unknown): void {\n if (ast.operation.endsWith('=') && !['==', '===', '!=', '!==', '<=', '>='].includes(ast.operation)) {\n const left = ast.left;\n if ((left instanceof PropertyRead || left instanceof SafePropertyRead) && left.name === 'currentLang' && isSvc(left.receiver)) {\n writes.add(left);\n warn(left.sourceSpan.start, 'TranslateService.currentLang is a read-only Signal in @ngx-translate/core v18; use translate.use(lang) instead of assigning it.');\n }\n }\n super.visitBinary(ast, context);\n }\n\n override visitPropertyRead(ast: PropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitPropertyRead(ast, context);\n }\n\n override visitSafePropertyRead(ast: SafePropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitSafePropertyRead(ast, context);\n }\n\n override visitPipe(ast: BindingPipe, context: unknown): void {\n if (ast.name === 'translate') result.usage.pipe = true;\n super.visitPipe(ast, context);\n }\n\n override visitElement(el: TmplAstElement): void {\n this.checkTranslateAttribute(el);\n super.visitElement(el);\n }\n\n override visitTemplate(t: Parameters<CombinedRecursiveAstVisitor['visitTemplate']>[0]): void {\n if (\n [...t.attributes, ...t.inputs, ...t.templateAttrs].some((a) => a.name === 'translate' || a.name === 'ngx-translate')\n ) {\n result.usage.directive = true;\n }\n super.visitTemplate(t);\n }\n\n private rewriteCurrentLang(ast: PropertyRead | SafePropertyRead): void {\n if (ast.name !== 'currentLang' || writes.has(ast) || !isSvc(ast.receiver)) return;\n const end = ast.nameSpan.end;\n if (/^\\s*\\(/.test(source.slice(end))) return; // already a call\n result.edits.push({ start: end, end, replacement: '()' });\n }\n\n private checkTranslateAttribute(el: TmplAstElement): void {\n if (opts.checkAttributes === false) return;\n const textAttr = el.attributes.find((a) => a.name === 'translate' || a.name === 'ngx-translate');\n const bound = el.inputs.find((i) => i.name === 'translate' && i.type === BindingType.Property);\n if (textAttr || bound) result.usage.directive = true;\n const at = el.startSourceSpan.start.offset;\n const todo = (message: string): void => {\n warn(at, `<${el.name}> ${message}`);\n const edit = createTodoEdit(source, at, message);\n if (edit) result.edits.push(edit);\n };\n\n // 7: [translate]=\"'KEY'\" now sets textContent: element children are overwritten.\n if (bound && el.children.some((c) => !(c instanceof TmplAstText))) {\n todo(\n 'with [translate] the element content is replaced by the translation (textContent) in @ngx-translate/core v18, child elements are lost. Restructure the markup.'\n );\n return;\n }\n\n // 8: <el translate>KEY</el> (text as key) is deprecated.\n if (!textAttr || textAttr.name !== 'translate' || textAttr.value !== '' || bound) return;\n const meaningful = el.children.filter((c) => !(c instanceof TmplAstText && c.value.trim() === ''));\n if (meaningful.length === 0) return;\n const only = meaningful[0];\n const isPlain =\n meaningful.length === 1 &&\n el.children.length === 1 &&\n only instanceof TmplAstText &&\n !!el.endSourceSpan &&\n source.slice(el.startSourceSpan.end.offset, el.endSourceSpan.start.offset) === only.value &&\n !/[\"'`&<>{}\\\\]/.test(only.value);\n if (!isPlain) {\n todo(\n 'uses its text content as translation key, which is deprecated and not safely convertible here (interpolation or nested elements). Use [translate]=\"\\'KEY\\'\", the translate pipe or *translateBlock.'\n );\n return;\n }\n if (!opts.allowKeyRewrite) {\n warn(at, `<${el.name}> text as translation key is deprecated; replace with [translate]=\"'KEY'\" (not rewritten inside a quoted inline template).`);\n return;\n }\n const key = (only as TmplAstText).value.trim();\n result.edits.push({\n start: textAttr.sourceSpan.start.offset,\n end: textAttr.sourceSpan.end.offset,\n replacement: `[translate]=\"'${key}'\"`,\n });\n result.edits.push({ start: el.startSourceSpan.end.offset, end: el.endSourceSpan!.start.offset, replacement: '' });\n }\n })();\n\n for (const node of parsed.nodes) visitor.visit(node);\n return result;\n}\n\n/** Members typed/injected as TranslateService of the component whose templateUrl points at `htmlPath`. */\nfunction membersForExternalTemplate(htmlPath: string, tsFiles: string[], read: (p: string) => string | undefined): Set<string> {\n const dir = dirOf(htmlPath);\n for (const f of tsFiles) {\n if (dirOf(f) !== dir || f.endsWith('.spec.ts')) continue;\n const src = read(f);\n if (!src || !src.includes('templateUrl') || !src.includes(CORE)) continue;\n const sf = ts.createSourceFile(f, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const helper = new ServiceResolver(sf);\n for (const stmt of sf.statements) {\n if (!ts.isClassDeclaration(stmt)) continue;\n const url = componentProp(stmt, 'templateUrl');\n if (url && ts.isStringLiteralLike(url.initializer) && resolveUrl(dir, url.initializer.text) === normalize(htmlPath)) {\n return helper.members(stmt);\n }\n }\n }\n return new Set();\n}\n\nfunction componentObject(cls: ts.ClassDeclaration): ts.ObjectLiteralExpression | undefined {\n for (const d of ts.getDecorators(cls) ?? []) {\n if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === 'Component') {\n const arg = d.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg)) return arg;\n }\n }\n return undefined;\n}\n\nfunction componentProp(cls: ts.ClassDeclaration, name: string): ts.PropertyAssignment | undefined {\n return componentObject(cls)?.properties.find(\n (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name\n );\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TranslateService receiver resolution\n// ---------------------------------------------------------------------------------------------------------------------\n\nclass ServiceResolver {\n readonly svcName: string | undefined;\n private cache = new Map<ts.Node, Set<string>>();\n\n constructor(private readonly sf: ts.SourceFile, typeName = 'TranslateService') {\n this.svcName = importedLocalName(sf, typeName);\n }\n\n isType(t: ts.TypeNode | undefined): boolean {\n return !!this.svcName && !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === this.svcName;\n }\n\n isInject(e: ts.Expression | undefined): boolean {\n if (!this.svcName || !e) return false;\n const x = unwrap(e);\n if (!ts.isCallExpression(x)) return false;\n const c = x.expression;\n const named = (ts.isIdentifier(c) && c.text === 'inject') || (ts.isPropertyAccessExpression(c) && c.name.text === 'inject');\n const a = x.arguments[0];\n return named && !!a && ts.isIdentifier(a) && a.text === this.svcName;\n }\n\n members(cls: ts.ClassLikeDeclaration): Set<string> {\n const cached = this.cache.get(cls);\n if (cached) return cached;\n const set = new Set<string>();\n for (const m of cls.members) {\n if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && (this.isType(m.type) || this.isInject(m.initializer))) set.add(m.name.text);\n if (ts.isConstructorDeclaration(m)) {\n for (const p of m.parameters) {\n const isProp = ts.getModifiers(p)?.some((x) =>\n [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(x.kind)\n );\n if (isProp && ts.isIdentifier(p.name) && this.isType(p.type)) set.add(p.name.text);\n }\n }\n }\n this.cache.set(cls, set);\n return set;\n }\n\n /** true: declared as TranslateService, false: declared as something else, undefined: not found. */\n bare(id: ts.Identifier): boolean | undefined {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if (\n (ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) &&\n cur.initializer &&\n ts.isVariableDeclarationList(cur.initializer)\n ) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return this.isType(d.type) || (ts.isVariableDeclaration(d) && this.isInject(d.initializer));\n }\n return undefined;\n }\n\n isService(expr: ts.Expression): boolean {\n const e = unwrap(expr);\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) {\n for (let cur: ts.Node | undefined = e.parent; cur; cur = cur.parent) {\n if (ts.isClassLike(cur)) return this.members(cur).has(e.name.text);\n }\n return false;\n }\n return ts.isIdentifier(e) && this.bare(e) === true;\n }\n}\n\nfunction unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n return e;\n}\n\n/** Local name of a non-type-only named import of `imported` from @ngx-translate/core. */\nfunction importedLocalName(sf: ts.SourceFile, imported: string, module = CORE): string | undefined {\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== module) continue;\n const nb = stmt.importClause?.namedBindings;\n if (!nb || !ts.isNamedImports(nb)) continue;\n for (const el of nb.elements) if ((el.propertyName ?? el.name).text === imported) return el.name.text;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TsEnv {\n projectHasExtend: boolean;\n projectUsesNgx: boolean;\n read: (p: string) => string | undefined;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext, env: TsEnv): string {\n const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const resolver = new ServiceResolver(sf);\n const edits: Edit[] = [];\n const todos = new Map<number, { anchor: ts.Node; messages: string[] }>();\n const needed = new Set<string>();\n const touched = new Set<string>();\n const handled = new Set<ts.Node>();\n const moves = new Map<ts.ObjectLiteralExpression, { calls: ts.CallExpression[]; texts: string[] }>();\n const moduleName = importedLocalName(sf, 'TranslateModule') === 'TranslateModule' ? 'TranslateModule' : undefined;\n const setValueName = importedLocalName(sf, 'setValue') === 'setValue' ? 'setValue' : undefined;\n const defaultEvent = importedLocalName(sf, 'DefaultLangChangeEvent') === 'DefaultLangChangeEvent';\n const tokenImported = (t: string): boolean => importedLocalName(sf, t) === t;\n const providerNames = new Set(['provideTranslateService'].filter((n) => importedLocalName(sf, n) === n));\n let importProvidersTouched = false;\n\n const seenWarnings = new Set<string>();\n const warnOnce = (text: string): void => {\n if (seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const storeResolver = new ServiceResolver(sf, 'TranslateStore');\n const httpNames = new Set(\n ['provideTranslateHttpLoader', 'TranslateHttpLoader'].map((n) => importedLocalName(sf, n, HTTP_LOADER)).filter((n): n is string => !!n)\n );\n const iServiceName = importedLocalName(sf, 'ITranslateService');\n const lineNo = (node: ts.Node): number => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n const flag = (node: ts.Node, message: string, comment = true): void => {\n warnOnce(`${filePath}:${lineNo(node)} - Manual action needed: ${message}`);\n if (!comment) return;\n const anchor = anchorOf(node);\n const key = anchor.getStart(sf);\n const entry = todos.get(key) ?? { anchor, messages: [] };\n const clean = sanitize(message);\n if (!entry.messages.includes(clean)) entry.messages.push(clean);\n todos.set(key, entry);\n };\n\n const nameOf = (n: ts.PropertyName | undefined): string | undefined =>\n n && (ts.isIdentifier(n) || ts.isStringLiteral(n)) ? n.text : undefined;\n const propOf = (obj: ts.ObjectLiteralExpression, name: string): ts.ObjectLiteralElementLike | undefined =>\n obj.properties.find((p) => !!p.name && nameOf(p.name) === name);\n\n // ----- config object transforms (defaultLanguage, useDefaultLang, plugin providers, extend/isolate) -----\n const CHILD_UNSUPPORTED = ['defaultLanguage', 'fallbackLang', 'lang', 'langs', 'useDefaultLang'];\n const transformConfig = (obj: ts.ObjectLiteralExpression, dropChildProps: boolean, out: Edit[], childTarget = false): number => {\n const drop = new Set<ts.ObjectLiteralElementLike>();\n for (const p of obj.properties) {\n const name = nameOf(p.name);\n if (!name) continue;\n if (childTarget && CHILD_UNSUPPORTED.includes(name) && ts.isPropertyAssignment(p)) {\n drop.add(p);\n flag(p, `${name} was removed: ChildTranslateServiceConfig has no such option, child services inherit the parent's fallbackLang and language. Set it on the root provideTranslateService() if needed.`);\n continue;\n }\n if (name === 'defaultLanguage') {\n if (ts.isPropertyAssignment(p)) out.push({\n start: p.name.getStart(sf),\n end: p.name.getEnd(),\n replacement: 'fallbackLang',\n });\n else if (ts.isShorthandPropertyAssignment(p)) out.push({\n start: p.getStart(sf),\n end: p.getEnd(),\n replacement: 'fallbackLang: defaultLanguage',\n });\n } else if (name === 'useDefaultLang' && ts.isPropertyAssignment(p)) {\n if (p.initializer.kind === ts.SyntaxKind.TrueKeyword) {\n drop.add(p);\n } else {\n flag(\n p,\n 'useDefaultLang was removed in @ngx-translate/core v18 and is kept only because its value is false: v18 always falls back to fallbackLang when it is set. Remove the leftover property manually (it does not compile as is); drop fallbackLang too if you relied on useDefaultLang: false.'\n );\n }\n } else if (dropChildProps && (name === 'extend' || name === 'isolate') && ts.isPropertyAssignment(p)) {\n drop.add(p);\n } else if (PLUGIN_KEYS.includes(name) && ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {\n const init = p.initializer;\n const provide = propOf(init, 'provide');\n const token = provide && ts.isPropertyAssignment(provide) && ts.isIdentifier(provide.initializer) ? provide.initializer.text : undefined;\n if (!token || !TOKEN_PROVIDERS[token]) continue;\n const useClass = propOf(init, 'useClass');\n if (init.properties.length === 2 && useClass && ts.isPropertyAssignment(useClass) && tokenImported(token)) {\n const fn = TOKEN_PROVIDERS[token];\n out.push({\n start: init.getStart(sf),\n end: init.getEnd(),\n replacement: `${fn}(${useClass.initializer.getText(sf)})`,\n });\n needed.add(fn);\n touched.add(token);\n } else {\n flag(\n p,\n `the ${token} provider uses a form other than { provide, useClass } (useFactory/useValue/deps). Convert it manually to ${TOKEN_PROVIDERS[token]}(...).`\n );\n }\n }\n }\n if (drop.size > 0) out.push(...removeArrayElements(obj, new Set([...drop].map((d) => obj.properties.indexOf(d))), sf));\n return drop.size;\n };\n\n // ----- TranslateModule.forRoot / forChild -----\n const convertModuleCall = (call: ts.CallExpression): void => {\n const callee = call.expression as ts.PropertyAccessExpression;\n handled.add(callee.expression);\n const method = callee.name.text;\n const args = call.arguments;\n const undecidable = (why: string): void =>\n flag(call, `TranslateModule.${method}() was left unchanged: ${why}. Use provideTranslateService() / provideChildTranslateService() manually.`);\n\n if (args.length > 1 || (args.length === 1 && !ts.isObjectLiteralExpression(args[0]))) return undecidable('its config is not an object literal');\n const obj = args[0] as ts.ObjectLiteralExpression | undefined;\n let fn = method === 'forRoot' ? 'provideTranslateService' : 'provideChildTranslateService';\n let hadExtendTrue = false;\n if (method === 'forChild' && obj) {\n for (const p of obj.properties) {\n const name = p.name ? nameOf(p.name) : undefined;\n if (ts.isSpreadAssignment(p)) return undecidable('its config contains a spread');\n if (name !== 'isolate' && name !== 'extend') continue;\n const init = ts.isPropertyAssignment(p) ? p.initializer.kind : undefined;\n if (init !== ts.SyntaxKind.TrueKeyword && init !== ts.SyntaxKind.FalseKeyword) return undecidable(`${name} is not a boolean literal`);\n if (name === 'isolate' && init === ts.SyntaxKind.TrueKeyword) fn = 'provideTranslateService';\n if (name === 'extend' && init === ts.SyntaxKind.TrueKeyword) hadExtendTrue = true;\n }\n }\n\n // the placement is decided first, so nothing is emitted for an unmovable call\n const parent = call.parent;\n let move: ts.ObjectLiteralExpression | undefined;\n let unwrapImportProviders: ts.CallExpression | undefined;\n if (ts.isArrayLiteralExpression(parent) && ts.isPropertyAssignment(parent.parent) && nameOf(parent.parent.name) === 'imports' && ts.isObjectLiteralExpression(parent.parent.parent)) {\n const owner = parent.parent.parent;\n const decorator = owner.parent;\n if (ts.isCallExpression(decorator) && ts.isIdentifier(decorator.expression) && decorator.expression.text === 'Component') {\n return undecidable('a standalone @Component cannot take environment providers; provide it in the application/route providers instead');\n }\n move = owner;\n } else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'importProvidersFrom') {\n if (parent.arguments.length !== 1) return undecidable('it is combined with other sources in importProvidersFrom()');\n unwrapImportProviders = parent;\n }\n\n const local: Edit[] = [];\n const removed = obj ? transformConfig(obj, method === 'forChild', local, fn === 'provideChildTranslateService') : 0;\n const keepConfig = !!obj && obj.properties.length - removed > 0;\n const cfgText = keepConfig ? applyEdits(source.slice(obj!.getStart(sf), obj!.getEnd()), shift(local, -obj!.getStart(sf))) : '';\n const text = `${fn}(${cfgText})`;\n needed.add(fn);\n touched.add('TranslateModule');\n if (method === 'forChild') {\n warnOnce(\n `${filePath}:${lineNo(call)} - forChild() was converted to ${fn}(): v18 child services use their own store with parent fallback, review isolation semantics.${hadExtendTrue ? ' extend: true was removed: setTranslation(lang, t) no longer merges, pass true as third argument where needed.' : ''}`\n );\n }\n\n if (move) {\n const g = moves.get(move) ?? { calls: [], texts: [] };\n g.calls.push(call);\n g.texts.push(text);\n moves.set(move, g);\n } else if (unwrapImportProviders) {\n edits.push({ start: unwrapImportProviders.getStart(sf), end: unwrapImportProviders.getEnd(), replacement: text });\n importProvidersTouched = true;\n } else {\n edits.push({ start: call.getStart(sf), end: call.getEnd(), replacement: text });\n }\n };\n\n // ----- bare TranslateModule in imports/exports -----\n const convertBareModule = (id: ts.Identifier, arr: ts.ArrayLiteralExpression, owner: ts.ObjectLiteralExpression): void => {\n handled.add(id);\n const callNode = owner.parent;\n const kind = ts.isCallExpression(callNode) && ts.isIdentifier(callNode.expression) ? callNode.expression.text : '';\n let names = ['TranslatePipe', 'TranslateDirective'];\n if (kind === 'Component') {\n const u = componentUsage(owner);\n if (u) names = [u.pipe ? 'TranslatePipe' : '', u.directive ? 'TranslateDirective' : ''].filter(Boolean);\n }\n const present = new Set(arr.elements.filter(ts.isIdentifier).map((e) => e.text));\n const add = names.filter((n) => !present.has(n));\n touched.add('TranslateModule');\n for (const n of names) needed.add(n);\n if (add.length > 0) {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: add.join(', ') });\n } else {\n edits.push(...removeArrayElements(arr, new Set([arr.elements.indexOf(id)]), sf));\n }\n };\n\n const componentUsage = (owner: ts.ObjectLiteralExpression): { pipe: boolean; directive: boolean } | null => {\n const tpl = propOf(owner, 'template');\n const url = propOf(owner, 'templateUrl');\n const quiet = { members: new Set<string>(), allowKeyRewrite: false, where: (): string => '', quiet: true };\n if (tpl && ts.isPropertyAssignment(tpl) && (ts.isNoSubstitutionTemplateLiteral(tpl.initializer) || ts.isStringLiteral(tpl.initializer))) {\n const lit = tpl.initializer;\n return scanTemplate(source.slice(lit.getStart(sf) + 1, lit.getEnd() - 1), filePath, context, quiet).usage;\n }\n if (url && ts.isPropertyAssignment(url) && ts.isStringLiteralLike(url.initializer)) {\n const target = resolveUrl(dirOf(filePath), url.initializer.text);\n const html = env.read(target);\n if (html !== undefined) return scanTemplate(html, target, context, quiet).usage;\n }\n return null;\n };\n\n // ----- visitor -----\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n\n if (ts.isCallExpression(node)) visitCall(node);\n else if (ts.isPropertyAccessExpression(node)) visitMember(node);\n else if (ts.isVariableDeclaration(node)) visitAlias(node.name, node.initializer, node);\n else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) visitAlias(undefined, node.right, node);\n else if (ts.isIdentifier(node)) visitIdentifier(node);\n else if (ts.isClassDeclaration(node)) visitInlineTemplate(node);\n\n ts.forEachChild(node, visit);\n };\n\n const visitCall = (call: ts.CallExpression): void => {\n const c = call.expression;\n if (moduleName && ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === moduleName && (c.name.text === 'forRoot' || c.name.text === 'forChild')) {\n convertModuleCall(call);\n return;\n }\n if (ts.isIdentifier(c) && providerNames.has(c.text) && call.arguments[0] && ts.isObjectLiteralExpression(call.arguments[0])) {\n transformConfig(call.arguments[0], false, edits);\n }\n if (setValueName && ts.isIdentifier(c) && c.text === setValueName) {\n const a0 = call.arguments[0];\n const assignable = !!a0 && (ts.isIdentifier(a0) || ts.isPropertyAccessExpression(a0) || ts.isElementAccessExpression(a0));\n if (ts.isExpressionStatement(call.parent) && call.arguments.length === 3 && assignable) {\n edits.push({ start: c.getStart(sf), end: c.getEnd(), replacement: `${a0.getText(sf)} = insertValue` });\n needed.add('insertValue');\n touched.add('setValue');\n } else {\n flag(call, 'setValue() was replaced by insertValue(), which returns a new object instead of mutating its argument. Use `target = insertValue(target, key, value)` manually.');\n }\n }\n if (ts.isPropertyAccessExpression(c) && resolver.isService(c.expression)) {\n if (c.name.text === 'getCurrentLang') {\n flag(call, 'getCurrentLang() returns Language | null in @ngx-translate/core v18 (null before a language is set). Handle the null case, e.g. `?? fallback`.');\n } else if (c.name.text === 'setTranslation' && call.arguments.length === 2 && env.projectHasExtend) {\n flag(call, 'setTranslation(lang, translations) no longer merges for services that used forChild({ extend: true }); pass `true` as third argument if you relied on merging.');\n }\n }\n };\n\n const visitMember = (n: ts.PropertyAccessExpression): void => {\n const member = n.name.text;\n if ((member === 'onTranslationChange' || member === 'getValue') && storeResolver.isService(n.expression)) {\n edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: member === 'getValue' ? 'getTranslationValue' : 'translationChange$',\n });\n return;\n }\n const isTracked = ['currentLang', 'langs', 'defaultLang', ...Object.keys(MEMBER_RENAMES)].includes(member);\n if (!isTracked || !resolver.isService(n.expression)) return;\n const parent = n.parent;\n if (MEMBER_RENAMES[member]) {\n edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: MEMBER_RENAMES[member] });\n return;\n }\n if (ts.isCallExpression(parent) && parent.expression === n) return; // already `currentLang()` etc.\n const isWrite =\n (ts.isBinaryExpression(parent) && parent.left === n && ASSIGN_OPS.has(parent.operatorToken.kind)) ||\n ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&\n (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) ||\n ts.isDeleteExpression(parent);\n if (isWrite) {\n flag(n, `${member} cannot be assigned in @ngx-translate/core v18 (read-only Signal / removed). Use use(), setFallbackLang() or setTranslation() instead.`);\n return;\n }\n if (member === 'currentLang') edits.push({ start: n.getEnd(), end: n.getEnd(), replacement: '()' });\n else if (member === 'langs') edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: 'getLangs()',\n });\n else edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: 'fallbackLang()' });\n };\n\n const visitAlias = (name: ts.BindingName | undefined, init: ts.Expression | undefined, at: ts.Node): void => {\n if (!init) return;\n if (!resolver.isService(init) && !(name && ts.isObjectBindingPattern(name) && resolver.isInject(init))) return;\n if (name && ts.isIdentifier(name) && ts.isVariableDeclaration(at) && resolver.isType(at.type)) return; // typed alias is tracked\n flag(\n at,\n 'TranslateService is aliased or destructured here, so currentLang/default*/langs usages through it are not migrated automatically. Review them against the v18 API (currentLang() signal, fallbackLang, getLangs()).'\n );\n };\n\n const visitIdentifier = (id: ts.Identifier): void => {\n const p = id.parent;\n if ((ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id)) return;\n if (httpNames.has(id.text)) {\n const call = ts.isCallExpression(p) && p.expression === id ? p : undefined;\n const cfg = call?.arguments[0];\n const hasFlag = !!cfg && ts.isObjectLiteralExpression(cfg) && !!propOf(cfg, 'failOnError');\n if (!hasFlag) {\n flag(id, 'the v18 http-loader no longer fails the whole language load when a translation file request fails (it logs a warning and uses {}). Pass failOnError: true to provideTranslateHttpLoader() if you rely on the v17 behaviour.');\n }\n }\n if (iServiceName && id.text === iServiceName && ts.isExpressionWithTypeArguments(p) && ts.isHeritageClause(p.parent) && p.parent.token === ts.SyntaxKind.ImplementsKeyword) {\n flag(id, 'ITranslateService gained isLoading: Signal<boolean> in @ngx-translate/core v18. Add isLoading = signal(false).asReadonly() to this class.');\n }\n if (defaultEvent && id.text === 'DefaultLangChangeEvent') {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: 'FallbackLangChangeEvent' });\n needed.add('FallbackLangChangeEvent');\n touched.add('DefaultLangChangeEvent');\n }\n if (moduleName && id.text === moduleName && !handled.has(id)) {\n // `TranslateModule` as an element of imports / exports\n if (ts.isArrayLiteralExpression(p) && ts.isPropertyAssignment(p.parent) && ['imports', 'exports'].includes(nameOf(p.parent.name) ?? '') && ts.isObjectLiteralExpression(p.parent.parent)) {\n convertBareModule(id, p, p.parent.parent);\n }\n }\n };\n\n const visitInlineTemplate = (cls: ts.ClassDeclaration): void => {\n const tpl = componentProp(cls, 'template');\n if (!tpl) return;\n const lit = tpl.initializer;\n if (!ts.isNoSubstitutionTemplateLiteral(lit) && !ts.isStringLiteral(lit)) return;\n const start = lit.getStart(sf) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (!/translate|currentLang/.test(raw)) return;\n const baseLine = sf.getLineAndCharacterOfPosition(start).line;\n const scan = scanTemplate(raw, filePath, context, {\n members: resolver.members(cls),\n allowKeyRewrite: ts.isNoSubstitutionTemplateLiteral(lit),\n checkAttributes: env.projectUsesNgx,\n where: (o) => `${filePath}:${baseLine + lineOf(raw, o)}`,\n });\n edits.push(...shift(scan.edits, start));\n };\n\n visit(sf);\n\n // moved forRoot/forChild calls: imports -> providers\n for (const [obj, g] of moves) {\n const importsProp = propOf(obj, 'imports') as ts.PropertyAssignment;\n const arr = importsProp.initializer as ts.ArrayLiteralExpression;\n const providersProp = propOf(obj, 'providers');\n if (providersProp && !(ts.isPropertyAssignment(providersProp) && ts.isArrayLiteralExpression(providersProp.initializer))) {\n for (const call of g.calls) flag(call, 'the providers property is not an array literal, so the converted provider could not be moved there. Move it manually.');\n continue;\n }\n const texts = g.texts.join(', ');\n const movedIdx = new Set(g.calls.map((c) => arr.elements.indexOf(c)));\n const keepsOthers = arr.elements.length > movedIdx.size;\n if (providersProp) {\n const parr = (providersProp as ts.PropertyAssignment).initializer as ts.ArrayLiteralExpression;\n if (parr.elements.length > 0) {\n edits.push({\n start: parr.elements[parr.elements.length - 1].getEnd(),\n end: parr.elements[parr.elements.length - 1].getEnd(),\n replacement: `, ${texts}`,\n });\n } else {\n edits.push({ start: parr.getStart(sf) + 1, end: parr.getEnd() - 1, replacement: texts });\n }\n if (keepsOthers) edits.push(...removeArrayElements(arr, movedIdx, sf));\n else removeObjectProperty(importsProp, sf, edits);\n } else if (!keepsOthers) {\n edits.push({ start: importsProp.getStart(sf), end: importsProp.getEnd(), replacement: `providers: [${texts}]` });\n } else {\n edits.push(...removeArrayElements(arr, movedIdx, sf));\n const multiline = source.slice(obj.getStart(sf), importsProp.getEnd()).includes('\\n');\n const indent = multiline ? /[ \\t]*$/.exec(source.slice(0, importsProp.getStart(sf)))![0] : '';\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({\n start: importsProp.getEnd(),\n end: importsProp.getEnd(),\n replacement: multiline ? `,${eol}${indent}providers: [${texts}]` : `, providers: [${texts}]`,\n });\n }\n }\n\n // remaining references to the removed module\n if (moduleName) {\n const mark = (n: ts.Node): void => {\n if (ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === moduleName && !handled.has(n) && !isPropertyName(n)) {\n flag(n, 'TranslateModule was removed in @ngx-translate/core v18. Use provideTranslateService() / provideChildTranslateService() and import TranslatePipe / TranslateDirective directly.');\n }\n ts.forEachChild(n, mark);\n };\n mark(sf);\n }\n\n // TODO comments, one line above the anchor, never duplicated\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n for (const { anchor, messages } of todos.values()) {\n const start = anchor.getStart(sf);\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1;\n const indent = /^[ \\t]*/.exec(source.slice(lineStart))![0];\n const above = new Set<string>();\n const lines = source.slice(0, lineStart).split(/\\r?\\n/);\n for (let i = lines.length - 2; i >= 0 && lines[i].trim().startsWith('// ' + TODO_PREFIX); i--) above.add(lines[i].trim());\n const fresh = messages.map((m) => `// ${TODO_PREFIX} ${m}`).filter((l) => !above.has(l));\n if (fresh.length > 0) edits.push({\n start: lineStart,\n end: lineStart,\n replacement: fresh.map((l) => `${indent}${l}${eol}`).join(''),\n });\n }\n\n let result = applyEdits(source, edits);\n if (result === source) return source;\n result = fixImports(result, filePath, CORE, needed, touched);\n if (importProvidersTouched) result = fixImports(result, filePath, '@angular/core', new Set(), new Set(['importProvidersFrom']));\n return result;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Imports\n// ---------------------------------------------------------------------------------------------------------------------\n\nconst RENAME_IN_PLACE: Record<string, string> = {\n DefaultLangChangeEvent: 'FallbackLangChangeEvent',\n setValue: 'insertValue',\n};\n\n/**\n * Drops `touched` specifiers that are no longer referenced (renaming in place when a rename is known) and\n * appends the `needed` names to the first named import of `moduleName`.\n */\nfunction fixImports(text: string, filePath: string, moduleName: string, needed: Set<string>, touched: Set<string>): string {\n const sf = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const referenced = (name: string): boolean => {\n let found = false;\n const walk = (n: ts.Node): void => {\n if (found || ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === name && !isPropertyName(n)) found = true;\n ts.forEachChild(n, walk);\n };\n walk(sf);\n return found;\n };\n\n const decls = sf.statements.filter(\n (s): s is ts.ImportDeclaration =>\n ts.isImportDeclaration(s) &&\n ts.isStringLiteral(s.moduleSpecifier) &&\n s.moduleSpecifier.text === moduleName &&\n !!s.importClause?.namedBindings &&\n ts.isNamedImports(s.importClause.namedBindings) &&\n !s.importClause.isTypeOnly\n );\n if (decls.length === 0) return text;\n\n const all = new Set<string>();\n for (const d of decls) for (const e of (d.importClause!.namedBindings as ts.NamedImports).elements) all.add(e.name.text);\n const placed = new Set<string>();\n const edits: Edit[] = [];\n const pendingNeeded = [...needed];\n\n decls.forEach((d, di) => {\n const named = d.importClause!.namedBindings as ts.NamedImports;\n const items: string[] = [];\n for (const e of named.elements) {\n const name = e.name.text;\n if (touched.has(name) && !e.propertyName && !referenced(name)) {\n const to = RENAME_IN_PLACE[name];\n if (to && needed.has(to) && !all.has(to) && !placed.has(to)) {\n items.push(to);\n placed.add(to);\n }\n continue;\n }\n items.push(e.getText(sf));\n }\n if (di === 0) {\n for (const n of pendingNeeded) if (!all.has(n) && !placed.has(n) && !items.includes(n)) items.push(n);\n }\n const before = named.elements.map((e) => e.getText(sf));\n if (items.length === before.length && items.every((v, i) => v === before[i])) return;\n if (items.length === 0 && !d.importClause!.name) {\n let end = d.getEnd();\n if (text[end] === '\\r') end++;\n if (text[end] === '\\n') end++;\n edits.push({ start: d.getStart(sf), end, replacement: '' });\n } else {\n const multiline = named.getText(sf).includes('\\n');\n const body = multiline ? `{\\n ${items.join(',\\n ')},\\n}` : `{ ${items.join(', ')} }`;\n edits.push({ start: named.getStart(sf), end: named.getEnd(), replacement: body });\n }\n });\n return applyEdits(text, edits);\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------------------------------------------------\n\nfunction isPropertyName(id: ts.Identifier): boolean {\n const p = id.parent;\n return (ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id);\n}\n\nfunction sanitize(message: string): string {\n return message.replace(/\\s+/g, ' ').trim();\n}\n\n/** Nearest ancestor that is a statement, class member or object property: the TODO goes on the line above it. */\nfunction anchorOf(node: ts.Node): ts.Node {\n let cur = node;\n while (cur.parent) {\n const p = cur.parent;\n if (ts.isSourceFile(p) || ts.isBlock(p) || ts.isModuleBlock(p) || ts.isClassLike(p) || ts.isObjectLiteralExpression(p) || ts.isCaseClause(p) || ts.isDefaultClause(p)) {\n return cur;\n }\n cur = p;\n }\n return cur;\n}\n\nconst dirOf = (p: string): string => dirname(normalize(p));\nconst resolveUrl = (dir: string, url: string): string => normalize(join(normalize(dir), url));\n\nfunction lineOf(source: string, offset: number): number {\n return source.slice(0, offset).split('\\n').length;\n}\n\nfunction shift(edits: Edit[], by: number): Edit[] {\n return edits.map((e) => ({ ...e, start: e.start + by, end: e.end + by }));\n}\n\n/** Removes one object property together with its separating comma. */\nfunction removeObjectProperty(prop: ts.ObjectLiteralElementLike, sf: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sf.getFullText();\n let start = prop.getStart(sf);\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getStart(sf);\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\n/** Removes the array elements at `indices`; non-overlapping ranges even for neighbouring elements. */\nfunction removeArrayElements(arr: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression, indices: Set<number>, sf: ts.SourceFile): Edit[] {\n const els: readonly ts.Node[] = ts.isArrayLiteralExpression(arr) ? arr.elements : arr.properties;\n const keptIdx = els.findIndex((_, i) => !indices.has(i));\n if (keptIdx === -1) return [{ start: arr.getStart(sf) + 1, end: arr.getEnd() - 1, replacement: '' }];\n const out: Edit[] = [];\n if (keptIdx > 0) out.push({ start: els[0].getStart(sf), end: els[keptIdx].getStart(sf), replacement: '' });\n for (let i = keptIdx + 1; i < els.length; i++) {\n if (indices.has(i)) out.push({ start: els[i - 1].getEnd(), end: els[i].getEnd(), replacement: '' });\n }\n return out;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const seen = new Map<string, Edit>();\n for (const e of edits) seen.set(`${e.start}:${e.end}:${e.replacement}`, e);\n let result = source;\n for (const e of [...seen.values()].sort((a, b) => b.start - a.start || b.end - a.end)) {\n result = result.slice(0, e.start) + e.replacement + result.slice(e.end);\n }\n return result;\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2151
2151
|
"displayName": "Edit",
|
|
2152
2152
|
"properties": [
|
|
2153
2153
|
{
|
|
@@ -2159,7 +2159,7 @@
|
|
|
2159
2159
|
"indexKey": "",
|
|
2160
2160
|
"optional": false,
|
|
2161
2161
|
"description": "",
|
|
2162
|
-
"line":
|
|
2162
|
+
"line": 37,
|
|
2163
2163
|
"rawdescription": "\n"
|
|
2164
2164
|
},
|
|
2165
2165
|
{
|
|
@@ -2171,7 +2171,7 @@
|
|
|
2171
2171
|
"indexKey": "",
|
|
2172
2172
|
"optional": false,
|
|
2173
2173
|
"description": "",
|
|
2174
|
-
"line":
|
|
2174
|
+
"line": 38,
|
|
2175
2175
|
"rawdescription": "\n"
|
|
2176
2176
|
},
|
|
2177
2177
|
{
|
|
@@ -2183,7 +2183,7 @@
|
|
|
2183
2183
|
"indexKey": "",
|
|
2184
2184
|
"optional": false,
|
|
2185
2185
|
"description": "",
|
|
2186
|
-
"line":
|
|
2186
|
+
"line": 36,
|
|
2187
2187
|
"rawdescription": "\n"
|
|
2188
2188
|
}
|
|
2189
2189
|
],
|
|
@@ -2201,26 +2201,14 @@
|
|
|
2201
2201
|
},
|
|
2202
2202
|
{
|
|
2203
2203
|
"name": "Edit",
|
|
2204
|
-
"id": "interface-Edit-
|
|
2205
|
-
"file": "packages/core/schematics/
|
|
2204
|
+
"id": "interface-Edit-1f2d4cb62366aa9aa509b1306410734c135d050f21f7337a1c94e646185a2f016f4f7cb64b7d92719e26cc96bd7aaa73265b366365a145e7b2aa71476fe5202c-22",
|
|
2205
|
+
"file": "packages/core/schematics/utils/tooltip-message.ts",
|
|
2206
2206
|
"deprecated": false,
|
|
2207
2207
|
"deprecationMessage": "",
|
|
2208
2208
|
"type": "interface",
|
|
2209
|
-
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport { parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { forEachElement } from '../utils/template-walk';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport {\n EUI_SIGNAL_MAP as EUI_SIGNAL_MAP_RAW,\n EUI_SELECTOR_TO_CLASS as EUI_SELECTOR_TO_CLASS_RAW,\n EUI_OUTPUT_MAP,\n EUI_HOST_BINDING_REMOVED_MAP,\n EUI_WRITABLE_SIGNAL_MAP,\n} from './signal-map';\nimport { ECL_SIGNAL_MAP, ECL_SELECTOR_TO_CLASS } from './ecl-signal-map';\n\n/**\n * Combined EUI + ECL signal maps. The migration logic is identical for both\n * libraries (plain field → signal getter), so the maps are merged and the rest\n * of the engine treats them uniformly. EUI and ECL class names don't collide\n * (Eui* vs Ecl* prefixes), and the selector namespaces are disjoint.\n */\nconst EUI_SIGNAL_MAP: Record<string, ReadonlySet<string>> = { ...EUI_SIGNAL_MAP_RAW, ...ECL_SIGNAL_MAP };\nconst EUI_SELECTOR_TO_CLASS: Record<string, string> = { ...EUI_SELECTOR_TO_CLASS_RAW, ...ECL_SELECTOR_TO_CLASS };\n\n/** Every class the schematic knows about (signals, outputs or removed host bindings). */\nconst KNOWN_CLASSES: ReadonlySet<string> = new Set([\n ...Object.keys(EUI_SIGNAL_MAP),\n ...Object.keys(EUI_OUTPUT_MAP),\n ...Object.keys(EUI_HOST_BINDING_REMOVED_MAP),\n]);\nconst isKnownClass = (name: string | null | undefined): name is string => !!name && KNOWN_CLASSES.has(name);\n\n/**\n * Tracked references. Class members are tracked by name (reached via `this.name`); locals/parameters are\n * tracked by their DECLARATION node, so a same-named untracked parameter or variable is never confused\n * with a tracked class member (shadowing). `lists*` hold QueryList<EuiXxx> / EuiXxx[] holders.\n */\ninterface Refs {\n props: Map<string, string>;\n propLists: Map<string, string>;\n decls: Map<ts.Node, string>;\n listDecls: Map<ts.Node, string>;\n}\n\n/** rxjs functions that take Observables as (possibly array-wrapped) arguments. */\nconst OBSERVABLE_COMBINATORS = new Set([\n 'merge', 'race', 'combineLatest', 'forkJoin', 'concat', 'zip', 'firstValueFrom', 'lastValueFrom', 'raceWith', 'mergeWith', 'concatWith', 'zipWith', 'combineLatestWith',\n]);\n\n/** Observable methods that need a real Observable instead of an OutputEmitterRef. */\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n/** QueryList iteration methods whose callback parameter is an element of the list. */\nconst LIST_ITERATION_METHODS = new Set(['forEach', 'map', 'filter', 'some', 'every', 'find', 'findIndex', 'reduce']);\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n /** When several zero-width edits share a position, `after` ones end up after the others. */\n after?: boolean;\n}\n\n/**\n * Migrates consumer code that accesses EUI or ECL component instances\n * programmatically.\n *\n * When EUI/ECL migrated @Input() → input(), @ViewChild() → viewChild(), and\n * @ContentChild() → contentChild(), properties that were plain class fields\n * became signal getters. Consumers who access them via @ViewChild need to\n * change `comp.prop` to `comp.prop()`.\n *\n * This schematic:\n * 1. Finds @ViewChild / @ContentChild fields typed as EUI component classes\n * 2. Resolves untyped @ViewChild('refName') by reading the component template\n * and matching #refName to an EUI element tag/selector\n * 3. Tracks which local variable names hold EUI component references (incl. aliases)\n * 4. Rewrites property accesses on those references: `ref.prop` → `ref.prop()`\n * (only for properties listed in the signal map)\n * 5. Does NOT touch template bindings — those are unaffected by signal migrations\n */\nexport function migrateToSignals(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n let propCount = 0;\n let todoCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n if (!path.endsWith('.ts')) return;\n // Skip spec files — test code may use different patterns\n if (path.endsWith('.spec.ts')) return;\n\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n\n // Fast bail: file must mention at least one EUI class name or have\n // ViewChild/ContentChild with string refs (which might reference EUI elements)\n if (!hasEuiReference(original) && !hasStringRefQuery(original)) return;\n\n const result = migrateTypeScript(original, path, tree, context);\n if (result.source !== original) {\n if (options.dryRun) {\n if (result.editCount > 0) {\n logDryRun(context, `Would migrate ${result.editCount} signal property access(es) in ${path}`);\n }\n if (result.todoCount > 0) {\n logDryRun(\n context,\n `Would comment out ${result.todoCount} programmatic signal-input write(s) with a TODO in ${path}`,\n );\n }\n } else {\n tree.overwrite(path, result.source);\n }\n fileCount++;\n propCount += result.editCount;\n todoCount += result.todoCount;\n }\n });\n\n context.logger.info(`Migrated ${propCount} property access(es) to signal getters in ${fileCount} file(s).`);\n if (todoCount > 0) {\n context.logger.info(\n `Commented out ${todoCount} programmatic signal-input write(s) and left a TODO — these cannot be migrated automatically and need a manual fix.`,\n );\n }\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\n/** Quick check: does the file reference any EUI class name from the signal map? */\nfunction hasEuiReference(source: string): boolean {\n for (const className of KNOWN_CLASSES) {\n if (source.includes(className)) return true;\n }\n return false;\n}\n\n/** Quick check: does the file have @ViewChild('...') or @ContentChild('...') with string refs? */\nfunction hasStringRefQuery(source: string): boolean {\n return /(@ViewChild|@ContentChild|@ViewChildren|@ContentChildren)\\s*\\(\\s*['\"]/.test(source);\n}\n\ninterface MigrateResult {\n source: string;\n editCount: number;\n todoCount: number;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, tree: Tree, context: SchematicContext): MigrateResult {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const todoEdits: Edit[] = [];\n\n // Phase 0: Build template ref map (#refName → EUI class name) from the component's template\n const templateRefMap = buildTemplateRefMap(sourceFile, source, filePath, tree);\n\n // Phase 1: Collect all variables/properties typed as EUI classes\n const euiRefs = collectEuiReferences(sourceFile, source, templateRefMap);\n\n if (euiRefs.props.size === 0 && euiRefs.propLists.size === 0 && euiRefs.decls.size === 0 && euiRefs.listDecls.size === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const hostTodoEdits: Edit[] = [];\n let needsOutputImport = false;\n\n // Phase 2: Find property accesses on those references and rewrite signal props\n const visitNode = (node: ts.Node): void => {\n // Match: ref.prop (PropertyAccessExpression)\n if (ts.isPropertyAccessExpression(node)) {\n const rewrite = tryRewritePropertyAccess(node, euiRefs, sourceFile, source);\n if (rewrite) {\n edits.push(rewrite);\n }\n\n // Writable signal (model()): `ref.prop = value` -> `ref.prop.set(value)`\n edits.push(...trySetRewrite(node, euiRefs, sourceFile));\n\n // Output: `ref.out.subscribe()` -> `outputToObservable(ref.out).subscribe()`\n const wrap = tryWrapOutput(node, euiRefs, sourceFile);\n if (wrap) {\n edits.push(...wrap);\n needsOutputImport = true;\n }\n\n // Output handed to rxjs combinators / used as a value: wrap or flag\n const outputUse = tryOutputUsage(node, euiRefs, sourceFile, source);\n if (outputUse) {\n edits.push(...outputUse.edits);\n if (outputUse.todo) hostTodoEdits.push(outputUse.todo);\n if (outputUse.edits.length > 0) needsOutputImport = true;\n }\n\n // Removed @HostBinding property: flag with a TODO\n const hostTodo = tryHostBindingTodo(node, euiRefs, sourceFile, source);\n if (hostTodo) {\n hostTodoEdits.push(hostTodo);\n }\n\n // Separately: a programmatic WRITE to a now-signal input cannot be\n // migrated automatically. Flag it with a TODO instead of silently\n // leaving a line that will fail to compile against the signal API.\n const todo = tryInsertWriteTodo(node, euiRefs, sourceFile, source);\n if (todo) {\n todoEdits.push(todo);\n }\n }\n // Destructuring / aliasing of a tracked reference cannot be followed: flag it.\n const alias = tryAliasTodo(node, euiRefs, sourceFile, source);\n if (alias) hostTodoEdits.push(alias);\n ts.forEachChild(node, visitNode);\n };\n\n ts.forEachChild(sourceFile, visitNode);\n\n if (edits.length === 0 && todoEdits.length === 0 && hostTodoEdits.length === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const dedupedTodos = deduplicateEdits(todoEdits);\n const dedupedHostTodos = deduplicateEdits(hostTodoEdits);\n\n // A TODO edit comments out the whole write statement. Any read-rewrite `()`\n // edit whose position falls inside that commented-out range must be dropped,\n // otherwise we'd both edit and comment the same text (and produce overlapping\n // edits that corrupt the output).\n const keptEdits = edits.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const keptHostTodos = dedupedHostTodos.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const importEdit = needsOutputImport ? buildOutputImportEdit(sourceFile) : null;\n\n return {\n source: applyEdits(source, [...keptEdits, ...dedupedTodos, ...keptHostTodos, ...(importEdit ? [importEdit] : [])]),\n editCount: keptEdits.length,\n todoCount: dedupedTodos.length + keptHostTodos.length,\n };\n}\n\n/**\n * Scans the source file for class properties or variables typed as EUI component classes.\n * Returns a map: localName → Set of signal property names.\n *\n * Handles:\n * @ViewChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild(EuiXxxComponent) name!: EuiXxxComponent;\n * @ViewChild('ref') name: EuiXxxComponent;\n * @ContentChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild('ref') name: ElementRef; (resolved via template #ref → EUI selector)\n * someVar: EuiXxxComponent; (typed class field, even without decorator)\n * const alias = this.viewChildRef; (alias tracking)\n */\nfunction collectEuiReferences(\n sourceFile: ts.SourceFile,\n source: string,\n templateRefMap: Map<string, string>,\n): Refs {\n const tracked: Refs = { props: new Map(), propLists: new Map(), decls: new Map(), listDecls: new Map() };\n const { props, propLists, decls, listDecls } = tracked;\n\n // Pass 1: collect directly-typed references\n const visitDirect = (node: ts.Node): void => {\n // Class property declarations\n if (ts.isPropertyDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const euiClass = resolveEuiClassName(node, sourceFile, templateRefMap);\n if (isKnownClass(euiClass)) {\n (isListProperty(node) ? propLists : props).set(node.name.text, euiClass);\n }\n }\n\n // Variable (const x: EuiXxxComponent = ...) and parameter (method(ref: EuiXxxComponent)) declarations\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name)) {\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n decls.set(node, typeName);\n // constructor parameter property: also reachable as `this.name`\n if (ts.isParameter(node) && (ts.getModifiers?.(node) ?? []).length > 0) props.set(node.name.text, typeName);\n } else {\n const listClass = listElementClass(node.type);\n if (listClass) listDecls.set(node, listClass);\n }\n }\n\n ts.forEachChild(node, visitDirect);\n };\n\n ts.forEachChild(sourceFile, visitDirect);\n\n // Pass 2: aliases, QueryList/array iteration (source order)\n const visitAlias = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && !decls.has(node)) {\n const aliased = trackedClass(node.initializer, tracked);\n if (aliased) decls.set(node, aliased);\n const aliasedList = listClassOf(node.initializer, tracked);\n if (aliasedList) listDecls.set(node, aliasedList);\n }\n\n // list.forEach((el) => ...) / list.map(function (el) {...}) -> `el` is an element of the list\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n LIST_ITERATION_METHODS.has(node.expression.name.text)\n ) {\n const listClass = listClassOf(node.expression.expression, tracked);\n const callback = node.arguments[0];\n if (\n listClass &&\n callback &&\n (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&\n callback.parameters[0] &&\n ts.isIdentifier(callback.parameters[0].name) &&\n !callback.parameters[0].type\n ) {\n decls.set(callback.parameters[0], listClass);\n }\n }\n\n // for (const el of list) -> `el` is an element of the list\n if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {\n const listClass = listClassOf(node.expression, tracked);\n const decl = node.initializer.declarations[0];\n if (listClass && decl && ts.isIdentifier(decl.name) && !decls.has(decl)) decls.set(decl, listClass);\n }\n\n ts.forEachChild(node, visitAlias);\n };\n\n ts.forEachChild(sourceFile, visitAlias);\n return tracked;\n}\n\n/** `EuiXxx[]`, `Array<EuiXxx>`, `QueryList<EuiXxx>` -> the known element class. */\nfunction listElementClass(type: ts.TypeNode | undefined): string | null {\n if (!type) return null;\n if (ts.isArrayTypeNode(type)) {\n const n = getTypeAnnotationName(type.elementType);\n return isKnownClass(n) ? n : null;\n }\n if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && ['Array', 'ReadonlyArray', 'QueryList'].includes(type.typeName.text)) {\n const n = getTypeAnnotationName(type.typeArguments?.[0]);\n return isKnownClass(n) ? n : null;\n }\n return null;\n}\n\n/** Strips parentheses, `!`, `as T`, `<T>x` and `satisfies`. */\nfunction unwrap(expr: ts.Expression): ts.Expression {\n let cur = expr;\n while (\n ts.isParenthesizedExpression(cur) ||\n ts.isNonNullExpression(cur) ||\n ts.isAsExpression(cur) ||\n ts.isTypeAssertionExpression(cur) ||\n ts.isSatisfiesExpression(cur)\n ) {\n cur = cur.expression;\n }\n return cur;\n}\n\n/** Nearest declaration (parameter / variable / binding element) of a bare identifier, or null. */\nfunction findDeclaration(id: ts.Identifier): ts.Node | null {\n const name = id.text;\n const boundIn = (bn: ts.BindingName): boolean =>\n ts.isIdentifier(bn) ? bn.text === name : bn.elements.some((e) => !ts.isOmittedExpression(e) && boundIn(e.name));\n const matchDecl = (d: ts.ParameterDeclaration | ts.VariableDeclaration): ts.Node | null => (boundIn(d.name) ? d : null);\n\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n if (ts.isFunctionLike(cur)) {\n for (const p of cur.parameters) {\n const m = matchDecl(p);\n if (m) return m;\n }\n }\n if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur) || ts.isCaseClause(cur) || ts.isDefaultClause(cur)) {\n const stmts = ts.isCaseClause(cur) || ts.isDefaultClause(cur) ? cur.statements : cur.statements;\n for (const st of stmts) {\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n }\n }\n if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n for (const d of cur.initializer.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n if (ts.isCatchClause(cur) && cur.variableDeclaration) {\n const m = matchDecl(cur.variableDeclaration);\n if (m) return m;\n }\n }\n return null;\n}\n\n/** `this.name` -> name; anything else null. */\nfunction thisMemberName(expr: ts.Expression): string | null {\n return ts.isPropertyAccessExpression(expr) && expr.expression.kind === ts.SyntaxKind.ThisKeyword ? expr.name.text : null;\n}\n\n/** Element class of a tracked QueryList / array expression, or null. */\nfunction listClassOf(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.listDecls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n return member ? (tracked.propLists.get(member) ?? null) : null;\n}\n\n/**\n * Resolves the EUI class name from a property declaration.\n * Checks: type annotation → decorator class argument → template ref map.\n */\nfunction resolveEuiClassName(\n node: ts.PropertyDeclaration,\n sourceFile: ts.SourceFile,\n templateRefMap: Map<string, string>,\n): string | null {\n // Check type annotation first\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n return typeName;\n }\n\n const arrayClass = listElementClass(node.type);\n if (arrayClass) return arrayClass;\n\n // Check generic type argument: ElementRef<EuiXxxComponent> / QueryList<EuiXxxComponent>\n if (node.type && ts.isTypeReferenceNode(node.type) && node.type.typeArguments?.length) {\n const genericArg = getTypeAnnotationName(node.type.typeArguments[0]);\n if (isKnownClass(genericArg)) {\n return genericArg;\n }\n }\n\n // Check decorator arguments: @ViewChild(EuiXxxComponent) or @ViewChild('refName')\n if (node.modifiers) {\n for (const modifier of node.modifiers) {\n if (!ts.isDecorator(modifier)) continue;\n if (!ts.isCallExpression(modifier.expression)) continue;\n\n const decoratorName = getDecoratorName(modifier.expression);\n if (!decoratorName) continue;\n if (!['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'].includes(decoratorName)) continue;\n\n const args = modifier.expression.arguments;\n if (args.length > 0) {\n const firstArg = args[0];\n\n // @ViewChild(EuiXxxComponent) — class reference\n if (ts.isIdentifier(firstArg) && isKnownClass(firstArg.text)) {\n return firstArg.text;\n }\n\n // @ViewChild('refName') — string template ref, resolve via template\n if (ts.isStringLiteralLike(firstArg)) {\n const refName = firstArg.text;\n const euiClass = templateRefMap.get(refName);\n if (isKnownClass(euiClass)) {\n return euiClass;\n }\n }\n }\n }\n }\n\n return null;\n}\n\n/** True for `@ViewChildren/@ContentChildren` fields and `QueryList<...>`-typed fields. */\nfunction isListProperty(node: ts.PropertyDeclaration): boolean {\n if (listElementClass(node.type)) return true;\n if (node.type && ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === 'QueryList') {\n return true;\n }\n return (ts.getDecorators?.(node) ?? []).some(\n (d) => ts.isCallExpression(d.expression) && ['ViewChildren', 'ContentChildren'].includes(getDecoratorName(d.expression) ?? ''),\n );\n}\n\n/**\n * Resolves an expression to the tracked EUI class: `ref`, `this.ref`, `this.ref!`, `(this.ref as any)`,\n * the `.first` / `.last` element of a tracked QueryList, or `list[i]` of a tracked list/array.\n */\nfunction trackedClass(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.decls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n if (member) return tracked.props.get(member) ?? null;\n if (ts.isPropertyAccessExpression(e) && (e.name.text === 'first' || e.name.text === 'last')) {\n return listClassOf(e.expression, tracked);\n }\n if (ts.isElementAccessExpression(e)) return listClassOf(e.expression, tracked);\n return null;\n}\n\nfunction getDecoratorName(callExpr: ts.CallExpression): string | null {\n if (ts.isIdentifier(callExpr.expression)) {\n return callExpr.expression.text;\n }\n return null;\n}\n\nfunction getTypeAnnotationName(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n return typeNode.typeName.text;\n }\n return null;\n}\n\n/**\n * Checks if a property access `ref.prop` should be rewritten to `ref.prop()`.\n *\n * We rewrite if:\n * - `ref` is tracked in euiRefs\n * - `prop` is in the signal set for that EUI class\n * - The access is NOT already a call expression (not `ref.prop()` or `ref.prop(args)`)\n * - The access is NOT a write target (not `ref.prop = value`)\n * - The access is NOT a template binding argument (those are unaffected)\n */\nfunction tryRewritePropertyAccess(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n // Resolve the reference class — handle `this.ref.prop`, `ref.prop`, `list.first.prop`\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Skip if parent is already a call expression on this property: ref.prop(...)\n if (ts.isCallExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip a signal handed to toObservable(ref.prop): it needs the signal itself (e.g. written by migrate-eui-tab-signals)\n if (ts.isCallExpression(node.parent) && node.parent.arguments[0] === node &&\n ts.isIdentifier(node.parent.expression) && node.parent.expression.text === 'toObservable') {\n return null;\n }\n\n // Skip signal API access already in place: ref.prop.set(..) / .update(..) / .asReadonly()\n if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node &&\n ['set', 'update', 'asReadonly'].includes(node.parent.name.text)) {\n return null;\n }\n\n // Skip if this is the left side of an assignment: ref.prop = value\n if (ts.isBinaryExpression(node.parent) &&\n node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n node.parent.left === node) {\n return null;\n }\n\n // Skip if this is a compound assignment: ref.prop += value, ref.prop &&= value, etc.\n if (ts.isBinaryExpression(node.parent) && isAssignmentOperator(node.parent.operatorToken.kind) && node.parent.left === node) {\n return null;\n }\n\n // Skip if this is used with delete: delete ref.prop\n if (ts.isDeleteExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip if inside a typeof: typeof ref.prop\n if (ts.isTypeOfExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip property access chains that go deeper: ref.prop.something → ref.prop().something\n // This IS correct — we still want to add ()\n\n // Rewrite: insert () after the property name\n const end = node.name.getEnd();\n return {\n start: end,\n end: end,\n replacement: '()',\n };\n}\n\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;\n}\n\n/** Marker used to detect an already-inserted TODO so the schematic stays idempotent. */\nconst WRITE_TODO_MARKER = 'TODO(eui-signals):';\n\n/**\n * Detects a programmatic WRITE to a now-signal input and returns an edit that\n * comments out the offending statement and prepends an explanatory TODO.\n *\n * A signal input (`input()`) exposes a read-only getter — it cannot be assigned\n * from outside the component (`comp.prop = value` no longer compiles, and\n * `comp.prop()` is a getter, not a setter). There is no safe, mechanical\n * rewrite: the correct fix is to drive the value declaratively through a\n * template binding (`[prop]=\"...\"`) or, when a ComponentRef is genuinely\n * available, `componentRef.setInput('prop', value)`. Both require human\n * judgement, so instead of rewriting we comment the statement out (keeping the\n * build green) and leave a TODO pointing at the manual fix.\n *\n * Only acts when the assignment is the ENTIRE statement\n * (`ExpressionStatement` whose expression is exactly this assignment):\n * ref.prop = value (simple assignment)\n * ref.prop += value, etc. (compound assignment)\n * where `ref` is a tracked EUI/ECL reference and `prop` is in its signal set.\n *\n * When the write is only part of a larger statement (e.g. inside an `if`\n * without a block, or nested in another expression), commenting it out would\n * also remove unrelated logic, so we leave it untouched (it will surface as a\n * compile error the developer must resolve by hand).\n */\nfunction tryInsertWriteTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Only act on assignment targets: `ref.prop = ...` or `ref.prop <op>= ...`\n if (\n !ts.isBinaryExpression(node.parent) ||\n node.parent.left !== node ||\n !isAssignmentOperator(node.parent.operatorToken.kind)\n ) {\n return null;\n }\n\n const assignment = node.parent;\n\n // A plain `=` to a writable signal is migrated to `.set()` by trySetRewrite\n if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken && EUI_WRITABLE_SIGNAL_MAP[cls]?.has(propName)) {\n return null;\n }\n\n // Only comment out when the assignment IS the whole statement — otherwise we'd\n // delete unrelated logic from a larger statement.\n const statement = node.parent.parent;\n if (!statement || !ts.isExpressionStatement(statement) || statement.expression !== assignment) {\n return null;\n }\n\n // The statement must stand on its own (a direct child of a block/source), not\n // be the unbraced body of an `if`/`for`/`while` etc. — commenting those out by\n // line would swallow the surrounding `if (...)` and break the code.\n const parent = statement.parent;\n if (\n !parent ||\n !(ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isModuleBlock(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent))\n ) {\n return null;\n }\n\n const stmtStart = statement.getStart(sourceFile);\n const stmtEnd = statement.getEnd(); // includes the trailing semicolon\n const lineStart = getLineStartPosition(source, stmtStart);\n const indent = source.slice(lineStart, stmtStart);\n\n // Commenting works per line: the statement must be alone on its lines, otherwise\n // (e.g. `run() { ref.prop = 1; }`) we would comment out surrounding code.\n const eol = source.indexOf('\\n', stmtEnd);\n const restOfLine = source.slice(stmtEnd, eol === -1 ? source.length : eol);\n if (indent.trim() !== '' || restOfLine.trim() !== '') {\n return null;\n }\n\n // The statement text, as written (may span multiple lines).\n const statementText = source.slice(stmtStart, stmtEnd);\n\n // Comment out every line of the statement, preserving each line's own\n // indentation (insert `// ` after the leading whitespace). The first line's\n // indentation was stripped by starting the replacement at lineStart, so we\n // re-add it explicitly.\n const commentedStatement = statementText\n .split('\\n')\n .map((line, i) => {\n if (i === 0) return `${indent}// ${line}`;\n const lineIndent = line.slice(0, line.length - line.trimStart().length);\n return `${lineIndent}// ${line.trimStart()}`;\n })\n .join('\\n');\n\n const todo =\n `${indent}// ${WRITE_TODO_MARKER} '${propName}' is now a signal input and cannot be assigned directly.\\n` +\n `${indent}// Set it via a template binding ([${propName}]=\"...\") or componentRef.setInput('${propName}', ...).\\n` +\n `${indent}// The original statement is commented out below so the build does not fail:\\n`;\n\n // Replace the statement (from the start of its line, to drop the original\n // indentation we re-add) with the TODO + commented-out statement.\n return {\n start: lineStart,\n end: stmtEnd,\n replacement: todo + commentedStatement,\n };\n}\n\n/** `ref.prop = value;` on a writable signal -> `ref.prop.set(value);` (two zero-width-safe edits). */\nfunction trySetRewrite(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] {\n const assignment = node.parent;\n if (\n !ts.isBinaryExpression(assignment) ||\n assignment.left !== node ||\n assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||\n !ts.isExpressionStatement(assignment.parent)\n ) {\n return [];\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_WRITABLE_SIGNAL_MAP[cls]?.has(node.name.text)) return [];\n\n return [\n { start: node.getEnd(), end: assignment.right.getStart(sourceFile), replacement: '.set(' },\n { start: assignment.right.getEnd(), end: assignment.right.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** `ref.out.subscribe(...)` -> `outputToObservable(ref.out).subscribe(...)`. */\nfunction tryWrapOutput(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] | null {\n const parent = node.parent;\n if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || !OBSERVABLE_METHODS.has(parent.name.text)) {\n return null;\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n\n const start = node.getStart(sourceFile);\n return [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** Marker for a read of a property that was a @HostBinding and no longer exists. */\nconst HOST_TODO_MARKER = 'TODO(eui-signals):';\n\nfunction tryHostBindingTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_HOST_BINDING_REMOVED_MAP[cls]?.has(propName) || EUI_SIGNAL_MAP[cls]?.has(propName)) return null;\n return flagTodo(\n node,\n sourceFile,\n source,\n `'${propName}' was a @HostBinding`,\n `'${propName}' was a @HostBinding property of ${cls} and no longer exists on the instance ` +\n '(moved to static host metadata). Remove or replace this access.',\n );\n}\n\n/**\n * Inserts a `// TODO(eui-signals): <message>` line above the enclosing statement / class member.\n * `key` identifies the TODO for idempotency (looked for in the comment lines right above).\n */\nfunction flagTodo(node: ts.Node, sourceFile: ts.SourceFile, source: string, key: string, message: string): Edit | null {\n // Anchor on the enclosing statement / class member\n let anchor: ts.Node = node;\n while (\n anchor.parent &&\n !(\n ts.isBlock(anchor.parent) ||\n ts.isSourceFile(anchor.parent) ||\n ts.isModuleBlock(anchor.parent) ||\n ts.isCaseClause(anchor.parent) ||\n ts.isDefaultClause(anchor.parent) ||\n ts.isClassLike(anchor.parent)\n )\n ) {\n anchor = anchor.parent;\n }\n\n const lineStart = getLineStartPosition(source, anchor.getStart(sourceFile));\n const indent = source.slice(lineStart).match(/^[ \\t]*/)![0];\n const text = `${indent}// ${HOST_TODO_MARKER} ${message}\\n`;\n\n // Idempotent: look at the contiguous comment lines right above\n const above = source.slice(0, lineStart).split('\\n').slice(-8).reverse();\n for (const line of above.slice(1)) {\n if (!line.trim().startsWith('//')) break;\n if (line.includes(`${HOST_TODO_MARKER} ${key}`) || line.includes(key)) return null;\n }\n // A single-line anchor like `run() { ... }` shares its line with other code: still fine, the comment goes above the line.\n return { start: lineStart, end: lineStart, replacement: text };\n}\n\n/**\n * An output (OutputEmitterRef) used as a value:\n * - an argument of an rxjs combinator (`merge(ref.out, ...)`, also inside an array) is wrapped in `outputToObservable()`;\n * - any other use that is not `.emit()` / `.subscribe()` & co / already wrapped is flagged with a TODO.\n */\nfunction tryOutputUsage(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): { edits: Edit[]; todo?: Edit | null } | null {\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n const parent = node.parent;\n\n // handled elsewhere (tryWrapOutput) or fine as is\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return null;\n if (ts.isNonNullExpression(parent) || ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent)) return null;\n // declared / written outputs are not reads\n if (ts.isBinaryExpression(parent) && parent.left === node) return null;\n\n // argument of a combinator?\n let arg: ts.Node = node;\n if (ts.isArrayLiteralExpression(arg.parent)) arg = arg.parent;\n const call = arg.parent;\n if (ts.isCallExpression(call) && call.arguments.includes(arg as ts.Expression)) {\n const callee = ts.isIdentifier(call.expression) ? call.expression.text : null;\n if (callee === 'outputToObservable') return null; // already migrated\n if (callee && OBSERVABLE_COMBINATORS.has(callee)) {\n const start = node.getStart(sourceFile);\n return {\n edits: [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ],\n };\n }\n }\n\n return {\n edits: [],\n todo: flagTodo(\n node,\n sourceFile,\n source,\n `output '${node.name.text}'`,\n `output '${node.name.text}' of ${cls} is an OutputEmitterRef, not an Observable. Wrap it with outputToObservable() ` +\n '(@angular/core/rxjs-interop) where an Observable is needed.',\n ),\n };\n}\n\n/** Destructuring of a tracked reference, or storing it in a field/variable we cannot follow. */\nfunction tryAliasTodo(node: ts.Node, euiRefs: Refs, sourceFile: ts.SourceFile, source: string): Edit | null {\n if (ts.isVariableDeclaration(node) && node.initializer && !ts.isIdentifier(node.name)) {\n const cls = trackedClass(node.initializer, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `destructuring of ${cls}`,\n `destructuring of ${cls} cannot be migrated automatically: its signal inputs/outputs must be read as ref.prop() / outputToObservable(ref.out).`,\n );\n }\n }\n if (\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n !ts.isIdentifier(unwrap(node.left)) &&\n ts.isExpressionStatement(node.parent)\n ) {\n const cls = trackedClass(node.right, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `aliasing of ${cls}`,\n `aliasing of ${cls}: this copy is not tracked, so its signal inputs/outputs must be updated manually (ref.prop()).`,\n );\n }\n }\n return null;\n}\n\n/** Adds `outputToObservable` to the file's imports (merging into an existing rxjs-interop import). */\nfunction buildOutputImportEdit(sourceFile: ts.SourceFile): Edit | null {\n let lastImportEnd = 0;\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n lastImportEnd = stmt.getEnd();\n if (!ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== '@angular/core/rxjs-interop') continue;\n const bindings = stmt.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n if (bindings.elements.some((e) => e.name.text === 'outputToObservable')) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (last) {\n return { start: last.getEnd(), end: last.getEnd(), replacement: ', outputToObservable' };\n }\n }\n }\n const line = 'import { outputToObservable } from \\'@angular/core/rxjs-interop\\';';\n return lastImportEnd === 0\n ? { start: 0, end: 0, replacement: `${line}\\n` }\n : { start: lastImportEnd, end: lastImportEnd, replacement: `\\n${line}` };\n}\n\n/** True if `edit`'s position falls within any of the given ranges. */\nfunction isInsideAnyRange(edit: Edit, ranges: Edit[]): boolean {\n return ranges.some((range) => edit.start >= range.start && edit.end <= range.end);\n}\n\n/** Returns the index of the first character of the line containing `pos`. */\nfunction getLineStartPosition(source: string, pos: number): number {\n const newlineIndex = source.lastIndexOf('\\n', pos - 1);\n return newlineIndex === -1 ? 0 : newlineIndex + 1;\n}\n\n// ---------------------------------------------------------------------------\n// Template ref resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a map of template reference variable names (#ref) to EUI class names.\n *\n * Parses the component's template (inline or external) and finds elements like:\n * <eui-alert #myAlert> → myAlert → EuiAlertComponent\n * <input euiAutocomplete #ac> → ac → EuiAutocompleteComponent\n *\n * Returns Map<refName, euiClassName>.\n */\nfunction buildTemplateRefMap(\n sourceFile: ts.SourceFile,\n source: string,\n filePath: string,\n tree: Tree,\n): Map<string, string> {\n const refMap = new Map<string, string>();\n\n // Find @Component decorator\n const componentMeta = findComponentMetadata(sourceFile, source);\n if (!componentMeta) return refMap;\n\n let templateSource: string | null = null;\n\n if (componentMeta.inlineTemplate !== null) {\n templateSource = componentMeta.inlineTemplate;\n } else if (componentMeta.templateUrl) {\n // Resolve templateUrl relative to the TS file\n const dir = filePath.substring(0, filePath.lastIndexOf('/'));\n const templatePath = `${dir}/${componentMeta.templateUrl}`;\n const buffer = tree.read(templatePath);\n if (buffer) {\n templateSource = buffer.toString('utf-8');\n }\n }\n\n if (!templateSource) return refMap;\n\n // Parse the template and collect #refs\n try {\n const parsed = parseTemplate(templateSource, '', { preserveWhitespaces: true });\n collectTemplateRefs(parsed.nodes, refMap);\n } catch {\n // Template parse failure — silently skip (might be malformed or use third-party syntax)\n }\n\n return refMap;\n}\n\n/**\n * Extracts @Component metadata: templateUrl or inline template content.\n */\nfunction findComponentMetadata(\n sourceFile: ts.SourceFile,\n source: string,\n): { templateUrl: string | null; inlineTemplate: string | null } | null {\n let result: { templateUrl: string | null; inlineTemplate: string | null } | null = null;\n\n const visit = (node: ts.Node): void => {\n if (result) return;\n\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {\n const name = getDecoratorName(node.expression);\n if (name !== 'Component') {\n ts.forEachChild(node, visit);\n return;\n }\n\n const args = node.expression.arguments;\n if (args.length === 0 || !ts.isObjectLiteralExpression(args[0])) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const meta: { templateUrl: string | null; inlineTemplate: string | null } = {\n templateUrl: null,\n inlineTemplate: null,\n };\n\n for (const prop of args[0].properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n\n if (prop.name.text === 'templateUrl') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.templateUrl = init.text;\n }\n }\n\n if (prop.name.text === 'template') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.inlineTemplate = init.text;\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n meta.inlineTemplate = init.text;\n }\n }\n }\n\n result = meta;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n return result;\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (ts.isParenthesizedExpression(current)) current = current.expression;\n return current;\n}\n\n/**\n * Recursively walks template AST nodes, collecting #refName → EUI class name mappings.\n *\n * For each element with a template reference (#ref), we try to resolve its EUI class:\n * 1. Match element tag name against EUI_SELECTOR_TO_CLASS (e.g. 'eui-alert' → EuiAlertComponent)\n * 2. Match element attributes against attribute selectors (e.g. [euiAutocomplete] → EuiAutocompleteComponent)\n */\nfunction collectTemplateRefs(nodes: TmplAstNode[], refMap: Map<string, string>): void {\n forEachElement(nodes, (node) => {\n if (node.references === undefined || node.references.length === 0) return;\n const euiClass = resolveElementToEuiClass(node);\n if (!euiClass) return;\n for (const ref of node.references) {\n refMap.set(ref.name, euiClass);\n }\n });\n}\n\n/**\n * Given a template element, resolves it to an EUI class name by checking:\n * 1. Tag name: <eui-alert> → look up 'eui-alert' in EUI_SELECTOR_TO_CLASS\n * 2. Attribute selectors: <input euiAutocomplete> → look up 'input[euiAutocomplete]' or '[euiAutocomplete]'\n */\nfunction resolveElementToEuiClass(element: TmplAstElement): string | null {\n const tag = element.name;\n\n // Direct tag match: eui-alert, eui-dialog, etc.\n if (EUI_SELECTOR_TO_CLASS[tag]) {\n return EUI_SELECTOR_TO_CLASS[tag];\n }\n\n // Attribute selector match: check all attributes against known patterns\n const allAttrNames = [\n ...element.attributes.map((a) => a.name),\n ...element.inputs.map((i) => i.name),\n ];\n\n for (const attrName of allAttrNames) {\n // Try tag[attr] pattern first (e.g. 'button[euiButton]', 'input[euiAutocomplete]')\n const tagAttrSelector = `${tag}[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[tagAttrSelector]) {\n return EUI_SELECTOR_TO_CLASS[tagAttrSelector];\n }\n\n // Try [attr] pattern (e.g. '[euiTooltip]', '[euiLoading]')\n const attrSelector = `[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[attrSelector]) {\n return EUI_SELECTOR_TO_CLASS[attrSelector];\n }\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Edit helpers\n// ---------------------------------------------------------------------------\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n // Descending by position; at equal positions `after` edits are applied first so they land last.\n for (const edit of unique.sort((a, b) => b.start - a.start || Number(!!b.after) - Number(!!a.after))) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}:${edit.replacement}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2209
|
+
"sourceCode": "import { parseTemplate, TmplAstElement } from '@angular/compiler';\nimport { SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { forEachElement } from './template-walk';\n\nconst OLD_INPUT = 'tooltipMessage';\nconst NEW_INPUT = 'euiTooltip';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\nconst DIRECTIVE_PATH = '@eui/components/directives';\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n let result = source;\n for (const edit of [...edits].sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\n/**\n * Renames the removed `tooltipMessage` input to `euiTooltip` (static, bound and interpolated forms)\n * on the elements accepted by `isTarget`. Elements already carrying `euiTooltip` are left unchanged and reported.\n */\nexport function renameTooltipMessage(\n source: string,\n isTarget: (element: TmplAstElement) => boolean,\n warn: (message: string) => void,\n): { result: string; renamed: number } {\n const parsed = parseTemplate(source, '', { preserveWhitespaces: true });\n const edits: Edit[] = [];\n\n const collect = (element: TmplAstElement): void => {\n const candidates = [\n ...element.attributes.filter((a) => a.name === OLD_INPUT),\n ...element.inputs.filter((i) => i.name === OLD_INPUT),\n ];\n if (candidates.length === 0) return;\n\n const hasTooltip = element.attributes.some((a) => a.name === NEW_INPUT) || element.inputs.some((i) => i.name === NEW_INPUT);\n for (const attr of candidates) {\n const start = attr.sourceSpan.start.offset;\n if (hasTooltip) {\n const line = source.slice(0, start).split('\\n').length;\n warn(`line ${line} - \"${OLD_INPUT}\" was removed and \"${NEW_INPUT}\" is already set on <${element.name}>. Remove \"${OLD_INPUT}\" manually.`);\n continue;\n }\n // `sourceSpan` starts at the attribute (`tooltipMessage`, `[tooltipMessage]`, `bind-tooltipMessage`): rename only the key.\n const index = source.indexOf(OLD_INPUT, start);\n if (index === -1 || index >= attr.sourceSpan.end.offset) continue;\n edits.push({ start: index, end: index + OLD_INPUT.length, replacement: NEW_INPUT });\n }\n };\n\n forEachElement(parsed.nodes, (element) => {\n if (isTarget(element)) collect(element);\n });\n return { result: applyEdits(source, edits), renamed: edits.length };\n}\n\ntype ImportTarget = { kind: 'inline' } | { kind: 'templateUrl'; htmlFileName: string };\n\n/**\n * Collects the components that now use `euiTooltip` and adds `EuiTooltipDirective` to their `imports`.\n */\nexport class TooltipImportCollector {\n private readonly pending = new Map<string, ImportTarget[]>();\n\n /** The template is inlined in the component file `tsPath`. */\n addInline(tsPath: string): void {\n this.push(tsPath, { kind: 'inline' });\n }\n\n /** The template lives in `htmlPath`; the owning component is resolved through its `templateUrl`. */\n addExternal(tree: Tree, htmlPath: string): void {\n const slash = htmlPath.lastIndexOf('/');\n const dirPath = slash > 0 ? htmlPath.slice(0, slash) : '/';\n const htmlFileName = htmlPath.slice(slash + 1);\n const dir = tree.getDir(dirPath);\n for (const file of dir.subfiles) {\n if (!file.endsWith('.ts') || file.endsWith('.d.ts') || file.endsWith('.spec.ts')) continue;\n const content = tree.read(`${dir.path}/${file}`)?.toString('utf-8');\n if (content?.includes('templateUrl') && content.includes(htmlFileName)) {\n this.push(`${dir.path}/${file}`, { kind: 'templateUrl', htmlFileName });\n return;\n }\n }\n this.unresolved.push(htmlPath);\n }\n\n private readonly unresolved: string[] = [];\n\n private push(tsPath: string, target: ImportTarget): void {\n const list = this.pending.get(tsPath) ?? [];\n list.push(target);\n this.pending.set(tsPath, list);\n }\n\n apply(tree: Tree, context: SchematicContext): void {\n for (const html of this.unresolved) {\n context.logger.warn(`${html} - could not find the component of this template. Add ${DIRECTIVE_CLASS} to its imports manually.`);\n }\n for (const [tsPath, targets] of this.pending) {\n const original = tree.read(tsPath)?.toString('utf-8');\n if (original === undefined) continue;\n let current = original;\n for (const target of targets) {\n const outcome = addDirectiveImport(current, tsPath, target);\n if (outcome.status === 'manual') {\n context.logger.warn(`${tsPath} - add ${DIRECTIVE_CLASS} (from '${DIRECTIVE_PATH}') to the component \"imports\" manually (${outcome.reason}).`);\n }\n current = outcome.result;\n }\n if (current !== original) tree.overwrite(tsPath, current);\n }\n }\n}\n\nfunction propertyName(prop: ts.ObjectLiteralElementLike): string | null {\n if (!ts.isPropertyAssignment(prop)) return null;\n return ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;\n}\n\nfunction addDirectiveImport(\n source: string,\n filePath: string,\n target: ImportTarget,\n): { result: string; status: 'added' | 'present' | 'manual'; reason?: string } {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n\n const matches = (obj: ts.ObjectLiteralExpression): boolean =>\n obj.properties.some((prop) => {\n const name = propertyName(prop);\n if (!name || !ts.isPropertyAssignment(prop)) return false;\n const init = prop.initializer;\n const text = ts.isStringLiteralLike(init) ? init.text : '';\n if (target.kind === 'inline') return name === 'template' && text.includes(NEW_INPUT);\n return name === 'templateUrl' && text.split('/').pop() === target.htmlFileName;\n });\n\n let component: ts.ObjectLiteralExpression | undefined;\n const find = (node: ts.Node): void => {\n if (component) return;\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === 'Component') {\n const arg = node.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg) && matches(arg)) component = arg;\n }\n ts.forEachChild(node, find);\n };\n find(sourceFile);\n\n if (!component) return { result: source, status: 'manual', reason: 'no matching @Component found' };\n\n const standalone = component.properties.find((p) => propertyName(p) === 'standalone');\n if (standalone && ts.isPropertyAssignment(standalone) && standalone.initializer.kind === ts.SyntaxKind.FalseKeyword) {\n return { result: source, status: 'manual', reason: 'the component is not standalone, update its NgModule' };\n }\n\n const importsProp = component.properties.find((p) => propertyName(p) === 'imports');\n if (!importsProp || !ts.isPropertyAssignment(importsProp) || !ts.isArrayLiteralExpression(importsProp.initializer)) {\n return { result: source, status: 'manual', reason: 'the component has no inline \"imports\" array' };\n }\n\n const array = importsProp.initializer;\n if (array.elements.some((e) => ts.isIdentifier(e) && e.text === DIRECTIVE_CLASS)) {\n return { result: source, status: 'present' };\n }\n\n const edits: Edit[] = [];\n if (array.elements.length > 0) {\n const pos = array.elements[array.elements.length - 1].getEnd();\n edits.push({ start: pos, end: pos, replacement: `, ${DIRECTIVE_CLASS}` });\n } else {\n const pos = array.getStart(sourceFile) + 1;\n edits.push({ start: pos, end: pos, replacement: DIRECTIVE_CLASS });\n }\n\n const imports = sourceFile.statements.filter(ts.isImportDeclaration);\n const existing = imports.find(\n (i) => ts.isStringLiteral(i.moduleSpecifier) && i.moduleSpecifier.text === DIRECTIVE_PATH && i.importClause?.namedBindings && ts.isNamedImports(i.importClause.namedBindings),\n );\n const named = existing?.importClause?.namedBindings;\n if (named && ts.isNamedImports(named)) {\n if (!named.elements.some((e) => e.name.text === DIRECTIVE_CLASS)) {\n if (named.elements.length > 0) {\n const pos = named.elements[named.elements.length - 1].getEnd();\n edits.push({ start: pos, end: pos, replacement: `, ${DIRECTIVE_CLASS}` });\n } else {\n const pos = named.getStart(sourceFile) + 1;\n edits.push({ start: pos, end: pos, replacement: ` ${DIRECTIVE_CLASS} ` });\n }\n }\n } else if (imports.length > 0) {\n const last = imports[imports.length - 1];\n const quote = source[(last.moduleSpecifier as ts.StringLiteral).getStart(sourceFile)] === '\"' ? '\"' : '\\'';\n const pos = last.getEnd();\n edits.push({ start: pos, end: pos, replacement: `\\nimport { ${DIRECTIVE_CLASS} } from ${quote}${DIRECTIVE_PATH}${quote};` });\n } else {\n edits.push({ start: 0, end: 0, replacement: `import { ${DIRECTIVE_CLASS} } from '${DIRECTIVE_PATH}';\\n` });\n }\n\n return { result: applyEdits(source, edits), status: 'added' };\n}\n\n/**\n * Applies `renameTooltipMessage` to a whole file: the file itself for `.html`, the `template: \\`...\\`` literals for `.ts`.\n */\nexport function renameTooltipMessageInFile(\n source: string,\n filePath: string,\n isTarget: (element: TmplAstElement) => boolean,\n warn: (message: string) => void,\n): { result: string; renamed: number } {\n if (filePath.endsWith('.html')) return renameTooltipMessage(source, isTarget, warn);\n\n let renamed = 0;\n const result = source.replace(/template\\s*:\\s*`([^`]*)`/gs, (match, templateContent: string) => {\n if (!templateContent.includes(OLD_INPUT)) return match;\n const migrated = renameTooltipMessage(templateContent, isTarget, warn);\n renamed += migrated.renamed;\n return migrated.result === templateContent ? match : match.replace(templateContent, () => migrated.result);\n });\n return { result, renamed };\n}\n\n/** Reports `x.tooltipMessage` property accesses in TS files, which cannot be migrated automatically. */\nexport function warnTooltipMessageUsages(source: string, filePath: string, context: SchematicContext): void {\n if (!filePath.endsWith('.ts') || filePath.endsWith('.spec.ts') || !source.includes(OLD_INPUT)) return;\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && node.name.text === OLD_INPUT) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n context.logger.warn(`${filePath}:${line + 1} - \"${OLD_INPUT}\" is no longer an input on eui-chip. Use the \"${NEW_INPUT}\" directive instead.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n}\n",
|
|
2210
2210
|
"displayName": "Edit",
|
|
2211
2211
|
"properties": [
|
|
2212
|
-
{
|
|
2213
|
-
"name": "after",
|
|
2214
|
-
"coverageIgnore": false,
|
|
2215
|
-
"deprecated": false,
|
|
2216
|
-
"deprecationMessage": "",
|
|
2217
|
-
"type": "boolean",
|
|
2218
|
-
"indexKey": "",
|
|
2219
|
-
"optional": true,
|
|
2220
|
-
"description": "<p>When several zero-width edits share a position, <code>after</code> ones end up after the others.</p>\n",
|
|
2221
|
-
"line": 64,
|
|
2222
|
-
"rawdescription": "\nWhen several zero-width edits share a position, `after` ones end up after the others."
|
|
2223
|
-
},
|
|
2224
2212
|
{
|
|
2225
2213
|
"name": "end",
|
|
2226
2214
|
"coverageIgnore": false,
|
|
@@ -2230,7 +2218,7 @@
|
|
|
2230
2218
|
"indexKey": "",
|
|
2231
2219
|
"optional": false,
|
|
2232
2220
|
"description": "",
|
|
2233
|
-
"line":
|
|
2221
|
+
"line": 13,
|
|
2234
2222
|
"rawdescription": "\n"
|
|
2235
2223
|
},
|
|
2236
2224
|
{
|
|
@@ -2242,7 +2230,7 @@
|
|
|
2242
2230
|
"indexKey": "",
|
|
2243
2231
|
"optional": false,
|
|
2244
2232
|
"description": "",
|
|
2245
|
-
"line":
|
|
2233
|
+
"line": 14,
|
|
2246
2234
|
"rawdescription": "\n"
|
|
2247
2235
|
},
|
|
2248
2236
|
{
|
|
@@ -2254,7 +2242,7 @@
|
|
|
2254
2242
|
"indexKey": "",
|
|
2255
2243
|
"optional": false,
|
|
2256
2244
|
"description": "",
|
|
2257
|
-
"line":
|
|
2245
|
+
"line": 12,
|
|
2258
2246
|
"rawdescription": "\n"
|
|
2259
2247
|
}
|
|
2260
2248
|
],
|
|
@@ -2272,14 +2260,26 @@
|
|
|
2272
2260
|
},
|
|
2273
2261
|
{
|
|
2274
2262
|
"name": "Edit",
|
|
2275
|
-
"id": "interface-Edit-
|
|
2276
|
-
"file": "packages/core/schematics/
|
|
2263
|
+
"id": "interface-Edit-bdeb132e57974e9cf0ecc701fc740055cb5bf71469a03b748668e1c33e6365cc60701d8ed980432fc5cd62827c42a92a1166a7cfa04156ee9c1f5e504c35781c-23",
|
|
2264
|
+
"file": "packages/core/schematics/migrate-to-signals/index.ts",
|
|
2277
2265
|
"deprecated": false,
|
|
2278
2266
|
"deprecationMessage": "",
|
|
2279
2267
|
"type": "interface",
|
|
2280
|
-
"sourceCode": "import { parseTemplate, TmplAstElement } from '@angular/compiler';\nimport { SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { forEachElement } from './template-walk';\n\nconst OLD_INPUT = 'tooltipMessage';\nconst NEW_INPUT = 'euiTooltip';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\nconst DIRECTIVE_PATH = '@eui/components/directives';\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n let result = source;\n for (const edit of [...edits].sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\n/**\n * Renames the removed `tooltipMessage` input to `euiTooltip` (static, bound and interpolated forms)\n * on the elements accepted by `isTarget`. Elements already carrying `euiTooltip` are left unchanged and reported.\n */\nexport function renameTooltipMessage(\n source: string,\n isTarget: (element: TmplAstElement) => boolean,\n warn: (message: string) => void,\n): { result: string; renamed: number } {\n const parsed = parseTemplate(source, '', { preserveWhitespaces: true });\n const edits: Edit[] = [];\n\n const collect = (element: TmplAstElement): void => {\n const candidates = [\n ...element.attributes.filter((a) => a.name === OLD_INPUT),\n ...element.inputs.filter((i) => i.name === OLD_INPUT),\n ];\n if (candidates.length === 0) return;\n\n const hasTooltip = element.attributes.some((a) => a.name === NEW_INPUT) || element.inputs.some((i) => i.name === NEW_INPUT);\n for (const attr of candidates) {\n const start = attr.sourceSpan.start.offset;\n if (hasTooltip) {\n const line = source.slice(0, start).split('\\n').length;\n warn(`line ${line} - \"${OLD_INPUT}\" was removed and \"${NEW_INPUT}\" is already set on <${element.name}>. Remove \"${OLD_INPUT}\" manually.`);\n continue;\n }\n // `sourceSpan` starts at the attribute (`tooltipMessage`, `[tooltipMessage]`, `bind-tooltipMessage`): rename only the key.\n const index = source.indexOf(OLD_INPUT, start);\n if (index === -1 || index >= attr.sourceSpan.end.offset) continue;\n edits.push({ start: index, end: index + OLD_INPUT.length, replacement: NEW_INPUT });\n }\n };\n\n forEachElement(parsed.nodes, (element) => {\n if (isTarget(element)) collect(element);\n });\n return { result: applyEdits(source, edits), renamed: edits.length };\n}\n\ntype ImportTarget = { kind: 'inline' } | { kind: 'templateUrl'; htmlFileName: string };\n\n/**\n * Collects the components that now use `euiTooltip` and adds `EuiTooltipDirective` to their `imports`.\n */\nexport class TooltipImportCollector {\n private readonly pending = new Map<string, ImportTarget[]>();\n\n /** The template is inlined in the component file `tsPath`. */\n addInline(tsPath: string): void {\n this.push(tsPath, { kind: 'inline' });\n }\n\n /** The template lives in `htmlPath`; the owning component is resolved through its `templateUrl`. */\n addExternal(tree: Tree, htmlPath: string): void {\n const slash = htmlPath.lastIndexOf('/');\n const dirPath = slash > 0 ? htmlPath.slice(0, slash) : '/';\n const htmlFileName = htmlPath.slice(slash + 1);\n const dir = tree.getDir(dirPath);\n for (const file of dir.subfiles) {\n if (!file.endsWith('.ts') || file.endsWith('.d.ts') || file.endsWith('.spec.ts')) continue;\n const content = tree.read(`${dir.path}/${file}`)?.toString('utf-8');\n if (content?.includes('templateUrl') && content.includes(htmlFileName)) {\n this.push(`${dir.path}/${file}`, { kind: 'templateUrl', htmlFileName });\n return;\n }\n }\n this.unresolved.push(htmlPath);\n }\n\n private readonly unresolved: string[] = [];\n\n private push(tsPath: string, target: ImportTarget): void {\n const list = this.pending.get(tsPath) ?? [];\n list.push(target);\n this.pending.set(tsPath, list);\n }\n\n apply(tree: Tree, context: SchematicContext): void {\n for (const html of this.unresolved) {\n context.logger.warn(`${html} - could not find the component of this template. Add ${DIRECTIVE_CLASS} to its imports manually.`);\n }\n for (const [tsPath, targets] of this.pending) {\n const original = tree.read(tsPath)?.toString('utf-8');\n if (original === undefined) continue;\n let current = original;\n for (const target of targets) {\n const outcome = addDirectiveImport(current, tsPath, target);\n if (outcome.status === 'manual') {\n context.logger.warn(`${tsPath} - add ${DIRECTIVE_CLASS} (from '${DIRECTIVE_PATH}') to the component \"imports\" manually (${outcome.reason}).`);\n }\n current = outcome.result;\n }\n if (current !== original) tree.overwrite(tsPath, current);\n }\n }\n}\n\nfunction propertyName(prop: ts.ObjectLiteralElementLike): string | null {\n if (!ts.isPropertyAssignment(prop)) return null;\n return ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;\n}\n\nfunction addDirectiveImport(\n source: string,\n filePath: string,\n target: ImportTarget,\n): { result: string; status: 'added' | 'present' | 'manual'; reason?: string } {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n\n const matches = (obj: ts.ObjectLiteralExpression): boolean =>\n obj.properties.some((prop) => {\n const name = propertyName(prop);\n if (!name || !ts.isPropertyAssignment(prop)) return false;\n const init = prop.initializer;\n const text = ts.isStringLiteralLike(init) ? init.text : '';\n if (target.kind === 'inline') return name === 'template' && text.includes(NEW_INPUT);\n return name === 'templateUrl' && text.split('/').pop() === target.htmlFileName;\n });\n\n let component: ts.ObjectLiteralExpression | undefined;\n const find = (node: ts.Node): void => {\n if (component) return;\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === 'Component') {\n const arg = node.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg) && matches(arg)) component = arg;\n }\n ts.forEachChild(node, find);\n };\n find(sourceFile);\n\n if (!component) return { result: source, status: 'manual', reason: 'no matching @Component found' };\n\n const standalone = component.properties.find((p) => propertyName(p) === 'standalone');\n if (standalone && ts.isPropertyAssignment(standalone) && standalone.initializer.kind === ts.SyntaxKind.FalseKeyword) {\n return { result: source, status: 'manual', reason: 'the component is not standalone, update its NgModule' };\n }\n\n const importsProp = component.properties.find((p) => propertyName(p) === 'imports');\n if (!importsProp || !ts.isPropertyAssignment(importsProp) || !ts.isArrayLiteralExpression(importsProp.initializer)) {\n return { result: source, status: 'manual', reason: 'the component has no inline \"imports\" array' };\n }\n\n const array = importsProp.initializer;\n if (array.elements.some((e) => ts.isIdentifier(e) && e.text === DIRECTIVE_CLASS)) {\n return { result: source, status: 'present' };\n }\n\n const edits: Edit[] = [];\n if (array.elements.length > 0) {\n const pos = array.elements[array.elements.length - 1].getEnd();\n edits.push({ start: pos, end: pos, replacement: `, ${DIRECTIVE_CLASS}` });\n } else {\n const pos = array.getStart(sourceFile) + 1;\n edits.push({ start: pos, end: pos, replacement: DIRECTIVE_CLASS });\n }\n\n const imports = sourceFile.statements.filter(ts.isImportDeclaration);\n const existing = imports.find(\n (i) => ts.isStringLiteral(i.moduleSpecifier) && i.moduleSpecifier.text === DIRECTIVE_PATH && i.importClause?.namedBindings && ts.isNamedImports(i.importClause.namedBindings),\n );\n const named = existing?.importClause?.namedBindings;\n if (named && ts.isNamedImports(named)) {\n if (!named.elements.some((e) => e.name.text === DIRECTIVE_CLASS)) {\n if (named.elements.length > 0) {\n const pos = named.elements[named.elements.length - 1].getEnd();\n edits.push({ start: pos, end: pos, replacement: `, ${DIRECTIVE_CLASS}` });\n } else {\n const pos = named.getStart(sourceFile) + 1;\n edits.push({ start: pos, end: pos, replacement: ` ${DIRECTIVE_CLASS} ` });\n }\n }\n } else if (imports.length > 0) {\n const last = imports[imports.length - 1];\n const quote = source[(last.moduleSpecifier as ts.StringLiteral).getStart(sourceFile)] === '\"' ? '\"' : '\\'';\n const pos = last.getEnd();\n edits.push({ start: pos, end: pos, replacement: `\\nimport { ${DIRECTIVE_CLASS} } from ${quote}${DIRECTIVE_PATH}${quote};` });\n } else {\n edits.push({ start: 0, end: 0, replacement: `import { ${DIRECTIVE_CLASS} } from '${DIRECTIVE_PATH}';\\n` });\n }\n\n return { result: applyEdits(source, edits), status: 'added' };\n}\n\n/**\n * Applies `renameTooltipMessage` to a whole file: the file itself for `.html`, the `template: \\`...\\`` literals for `.ts`.\n */\nexport function renameTooltipMessageInFile(\n source: string,\n filePath: string,\n isTarget: (element: TmplAstElement) => boolean,\n warn: (message: string) => void,\n): { result: string; renamed: number } {\n if (filePath.endsWith('.html')) return renameTooltipMessage(source, isTarget, warn);\n\n let renamed = 0;\n const result = source.replace(/template\\s*:\\s*`([^`]*)`/gs, (match, templateContent: string) => {\n if (!templateContent.includes(OLD_INPUT)) return match;\n const migrated = renameTooltipMessage(templateContent, isTarget, warn);\n renamed += migrated.renamed;\n return migrated.result === templateContent ? match : match.replace(templateContent, () => migrated.result);\n });\n return { result, renamed };\n}\n\n/** Reports `x.tooltipMessage` property accesses in TS files, which cannot be migrated automatically. */\nexport function warnTooltipMessageUsages(source: string, filePath: string, context: SchematicContext): void {\n if (!filePath.endsWith('.ts') || filePath.endsWith('.spec.ts') || !source.includes(OLD_INPUT)) return;\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && node.name.text === OLD_INPUT) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n context.logger.warn(`${filePath}:${line + 1} - \"${OLD_INPUT}\" is no longer an input on eui-chip. Use the \"${NEW_INPUT}\" directive instead.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n}\n",
|
|
2268
|
+
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport { parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { forEachElement } from '../utils/template-walk';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport {\n EUI_SIGNAL_MAP as EUI_SIGNAL_MAP_RAW,\n EUI_SELECTOR_TO_CLASS as EUI_SELECTOR_TO_CLASS_RAW,\n EUI_OUTPUT_MAP,\n EUI_HOST_BINDING_REMOVED_MAP,\n EUI_WRITABLE_SIGNAL_MAP,\n} from './signal-map';\nimport { ECL_SIGNAL_MAP, ECL_SELECTOR_TO_CLASS } from './ecl-signal-map';\n\n/**\n * Combined EUI + ECL signal maps. The migration logic is identical for both\n * libraries (plain field → signal getter), so the maps are merged and the rest\n * of the engine treats them uniformly. EUI and ECL class names don't collide\n * (Eui* vs Ecl* prefixes), and the selector namespaces are disjoint.\n */\nconst EUI_SIGNAL_MAP: Record<string, ReadonlySet<string>> = { ...EUI_SIGNAL_MAP_RAW, ...ECL_SIGNAL_MAP };\nconst EUI_SELECTOR_TO_CLASS: Record<string, string> = { ...EUI_SELECTOR_TO_CLASS_RAW, ...ECL_SELECTOR_TO_CLASS };\n\n/** Every class the schematic knows about (signals, outputs or removed host bindings). */\nconst KNOWN_CLASSES: ReadonlySet<string> = new Set([\n ...Object.keys(EUI_SIGNAL_MAP),\n ...Object.keys(EUI_OUTPUT_MAP),\n ...Object.keys(EUI_HOST_BINDING_REMOVED_MAP),\n]);\nconst isKnownClass = (name: string | null | undefined): name is string => !!name && KNOWN_CLASSES.has(name);\n\n/**\n * Tracked references. Class members are tracked by name (reached via `this.name`); locals/parameters are\n * tracked by their DECLARATION node, so a same-named untracked parameter or variable is never confused\n * with a tracked class member (shadowing). `lists*` hold QueryList<EuiXxx> / EuiXxx[] holders.\n */\ninterface Refs {\n props: Map<string, string>;\n propLists: Map<string, string>;\n decls: Map<ts.Node, string>;\n listDecls: Map<ts.Node, string>;\n}\n\n/** rxjs functions that take Observables as (possibly array-wrapped) arguments. */\nconst OBSERVABLE_COMBINATORS = new Set([\n 'merge', 'race', 'combineLatest', 'forkJoin', 'concat', 'zip', 'firstValueFrom', 'lastValueFrom', 'raceWith', 'mergeWith', 'concatWith', 'zipWith', 'combineLatestWith',\n]);\n\n/** Observable methods that need a real Observable instead of an OutputEmitterRef. */\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n/** QueryList iteration methods whose callback parameter is an element of the list. */\nconst LIST_ITERATION_METHODS = new Set(['forEach', 'map', 'filter', 'some', 'every', 'find', 'findIndex', 'reduce']);\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n /** When several zero-width edits share a position, `after` ones end up after the others. */\n after?: boolean;\n}\n\n/**\n * Migrates consumer code that accesses EUI or ECL component instances\n * programmatically.\n *\n * When EUI/ECL migrated @Input() → input(), @ViewChild() → viewChild(), and\n * @ContentChild() → contentChild(), properties that were plain class fields\n * became signal getters. Consumers who access them via @ViewChild need to\n * change `comp.prop` to `comp.prop()`.\n *\n * This schematic:\n * 1. Finds @ViewChild / @ContentChild fields typed as EUI component classes\n * 2. Resolves untyped @ViewChild('refName') by reading the component template\n * and matching #refName to an EUI element tag/selector\n * 3. Tracks which local variable names hold EUI component references (incl. aliases)\n * 4. Rewrites property accesses on those references: `ref.prop` → `ref.prop()`\n * (only for properties listed in the signal map)\n * 5. Does NOT touch template bindings — those are unaffected by signal migrations\n */\nexport function migrateToSignals(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n let propCount = 0;\n let todoCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n if (!path.endsWith('.ts')) return;\n // Skip spec files — test code may use different patterns\n if (path.endsWith('.spec.ts')) return;\n\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n\n // Fast bail: file must mention at least one EUI class name or have\n // ViewChild/ContentChild with string refs (which might reference EUI elements)\n if (!hasEuiReference(original) && !hasStringRefQuery(original)) return;\n\n const result = migrateTypeScript(original, path, tree, context);\n if (result.source !== original) {\n if (options.dryRun) {\n if (result.editCount > 0) {\n logDryRun(context, `Would migrate ${result.editCount} signal property access(es) in ${path}`);\n }\n if (result.todoCount > 0) {\n logDryRun(\n context,\n `Would comment out ${result.todoCount} programmatic signal-input write(s) with a TODO in ${path}`,\n );\n }\n } else {\n tree.overwrite(path, result.source);\n }\n fileCount++;\n propCount += result.editCount;\n todoCount += result.todoCount;\n }\n });\n\n context.logger.info(`Migrated ${propCount} property access(es) to signal getters in ${fileCount} file(s).`);\n if (todoCount > 0) {\n context.logger.info(\n `Commented out ${todoCount} programmatic signal-input write(s) and left a TODO — these cannot be migrated automatically and need a manual fix.`,\n );\n }\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\n/** Quick check: does the file reference any EUI class name from the signal map? */\nfunction hasEuiReference(source: string): boolean {\n for (const className of KNOWN_CLASSES) {\n if (source.includes(className)) return true;\n }\n return false;\n}\n\n/** Quick check: does the file have @ViewChild('...') or @ContentChild('...') with string refs? */\nfunction hasStringRefQuery(source: string): boolean {\n return /(@ViewChild|@ContentChild|@ViewChildren|@ContentChildren)\\s*\\(\\s*['\"]/.test(source);\n}\n\ninterface MigrateResult {\n source: string;\n editCount: number;\n todoCount: number;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, tree: Tree, context: SchematicContext): MigrateResult {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const todoEdits: Edit[] = [];\n\n // Phase 0: Build template ref map (#refName → EUI class name) from the component's template\n const templateRefMap = buildTemplateRefMap(sourceFile, source, filePath, tree);\n\n // Phase 1: Collect all variables/properties typed as EUI classes\n const euiRefs = collectEuiReferences(sourceFile, source, templateRefMap);\n\n if (euiRefs.props.size === 0 && euiRefs.propLists.size === 0 && euiRefs.decls.size === 0 && euiRefs.listDecls.size === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const hostTodoEdits: Edit[] = [];\n let needsOutputImport = false;\n\n // Phase 2: Find property accesses on those references and rewrite signal props\n const visitNode = (node: ts.Node): void => {\n // Match: ref.prop (PropertyAccessExpression)\n if (ts.isPropertyAccessExpression(node)) {\n const rewrite = tryRewritePropertyAccess(node, euiRefs, sourceFile, source);\n if (rewrite) {\n edits.push(rewrite);\n }\n\n // Writable signal (model()): `ref.prop = value` -> `ref.prop.set(value)`\n edits.push(...trySetRewrite(node, euiRefs, sourceFile));\n\n // Output: `ref.out.subscribe()` -> `outputToObservable(ref.out).subscribe()`\n const wrap = tryWrapOutput(node, euiRefs, sourceFile);\n if (wrap) {\n edits.push(...wrap);\n needsOutputImport = true;\n }\n\n // Output handed to rxjs combinators / used as a value: wrap or flag\n const outputUse = tryOutputUsage(node, euiRefs, sourceFile, source);\n if (outputUse) {\n edits.push(...outputUse.edits);\n if (outputUse.todo) hostTodoEdits.push(outputUse.todo);\n if (outputUse.edits.length > 0) needsOutputImport = true;\n }\n\n // Removed @HostBinding property: flag with a TODO\n const hostTodo = tryHostBindingTodo(node, euiRefs, sourceFile, source);\n if (hostTodo) {\n hostTodoEdits.push(hostTodo);\n }\n\n // Separately: a programmatic WRITE to a now-signal input cannot be\n // migrated automatically. Flag it with a TODO instead of silently\n // leaving a line that will fail to compile against the signal API.\n const todo = tryInsertWriteTodo(node, euiRefs, sourceFile, source);\n if (todo) {\n todoEdits.push(todo);\n }\n }\n // Destructuring / aliasing of a tracked reference cannot be followed: flag it.\n const alias = tryAliasTodo(node, euiRefs, sourceFile, source);\n if (alias) hostTodoEdits.push(alias);\n ts.forEachChild(node, visitNode);\n };\n\n ts.forEachChild(sourceFile, visitNode);\n\n if (edits.length === 0 && todoEdits.length === 0 && hostTodoEdits.length === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const dedupedTodos = deduplicateEdits(todoEdits);\n const dedupedHostTodos = deduplicateEdits(hostTodoEdits);\n\n // A TODO edit comments out the whole write statement. Any read-rewrite `()`\n // edit whose position falls inside that commented-out range must be dropped,\n // otherwise we'd both edit and comment the same text (and produce overlapping\n // edits that corrupt the output).\n const keptEdits = edits.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const keptHostTodos = dedupedHostTodos.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const importEdit = needsOutputImport ? buildOutputImportEdit(sourceFile) : null;\n\n return {\n source: applyEdits(source, [...keptEdits, ...dedupedTodos, ...keptHostTodos, ...(importEdit ? [importEdit] : [])]),\n editCount: keptEdits.length,\n todoCount: dedupedTodos.length + keptHostTodos.length,\n };\n}\n\n/**\n * Scans the source file for class properties or variables typed as EUI component classes.\n * Returns a map: localName → Set of signal property names.\n *\n * Handles:\n * @ViewChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild(EuiXxxComponent) name!: EuiXxxComponent;\n * @ViewChild('ref') name: EuiXxxComponent;\n * @ContentChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild('ref') name: ElementRef; (resolved via template #ref → EUI selector)\n * someVar: EuiXxxComponent; (typed class field, even without decorator)\n * const alias = this.viewChildRef; (alias tracking)\n */\nfunction collectEuiReferences(\n sourceFile: ts.SourceFile,\n source: string,\n templateRefMap: Map<string, string>,\n): Refs {\n const tracked: Refs = { props: new Map(), propLists: new Map(), decls: new Map(), listDecls: new Map() };\n const { props, propLists, decls, listDecls } = tracked;\n\n // Pass 1: collect directly-typed references\n const visitDirect = (node: ts.Node): void => {\n // Class property declarations\n if (ts.isPropertyDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const euiClass = resolveEuiClassName(node, sourceFile, templateRefMap);\n if (isKnownClass(euiClass)) {\n (isListProperty(node) ? propLists : props).set(node.name.text, euiClass);\n }\n }\n\n // Variable (const x: EuiXxxComponent = ...) and parameter (method(ref: EuiXxxComponent)) declarations\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name)) {\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n decls.set(node, typeName);\n // constructor parameter property: also reachable as `this.name`\n if (ts.isParameter(node) && (ts.getModifiers?.(node) ?? []).length > 0) props.set(node.name.text, typeName);\n } else {\n const listClass = listElementClass(node.type);\n if (listClass) listDecls.set(node, listClass);\n }\n }\n\n ts.forEachChild(node, visitDirect);\n };\n\n ts.forEachChild(sourceFile, visitDirect);\n\n // Pass 2: aliases, QueryList/array iteration (source order)\n const visitAlias = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && !decls.has(node)) {\n const aliased = trackedClass(node.initializer, tracked);\n if (aliased) decls.set(node, aliased);\n const aliasedList = listClassOf(node.initializer, tracked);\n if (aliasedList) listDecls.set(node, aliasedList);\n }\n\n // list.forEach((el) => ...) / list.map(function (el) {...}) -> `el` is an element of the list\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n LIST_ITERATION_METHODS.has(node.expression.name.text)\n ) {\n const listClass = listClassOf(node.expression.expression, tracked);\n const callback = node.arguments[0];\n if (\n listClass &&\n callback &&\n (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&\n callback.parameters[0] &&\n ts.isIdentifier(callback.parameters[0].name) &&\n !callback.parameters[0].type\n ) {\n decls.set(callback.parameters[0], listClass);\n }\n }\n\n // for (const el of list) -> `el` is an element of the list\n if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {\n const listClass = listClassOf(node.expression, tracked);\n const decl = node.initializer.declarations[0];\n if (listClass && decl && ts.isIdentifier(decl.name) && !decls.has(decl)) decls.set(decl, listClass);\n }\n\n ts.forEachChild(node, visitAlias);\n };\n\n ts.forEachChild(sourceFile, visitAlias);\n return tracked;\n}\n\n/** `EuiXxx[]`, `Array<EuiXxx>`, `QueryList<EuiXxx>` -> the known element class. */\nfunction listElementClass(type: ts.TypeNode | undefined): string | null {\n if (!type) return null;\n if (ts.isArrayTypeNode(type)) {\n const n = getTypeAnnotationName(type.elementType);\n return isKnownClass(n) ? n : null;\n }\n if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && ['Array', 'ReadonlyArray', 'QueryList'].includes(type.typeName.text)) {\n const n = getTypeAnnotationName(type.typeArguments?.[0]);\n return isKnownClass(n) ? n : null;\n }\n return null;\n}\n\n/** Strips parentheses, `!`, `as T`, `<T>x` and `satisfies`. */\nfunction unwrap(expr: ts.Expression): ts.Expression {\n let cur = expr;\n while (\n ts.isParenthesizedExpression(cur) ||\n ts.isNonNullExpression(cur) ||\n ts.isAsExpression(cur) ||\n ts.isTypeAssertionExpression(cur) ||\n ts.isSatisfiesExpression(cur)\n ) {\n cur = cur.expression;\n }\n return cur;\n}\n\n/** Nearest declaration (parameter / variable / binding element) of a bare identifier, or null. */\nfunction findDeclaration(id: ts.Identifier): ts.Node | null {\n const name = id.text;\n const boundIn = (bn: ts.BindingName): boolean =>\n ts.isIdentifier(bn) ? bn.text === name : bn.elements.some((e) => !ts.isOmittedExpression(e) && boundIn(e.name));\n const matchDecl = (d: ts.ParameterDeclaration | ts.VariableDeclaration): ts.Node | null => (boundIn(d.name) ? d : null);\n\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n if (ts.isFunctionLike(cur)) {\n for (const p of cur.parameters) {\n const m = matchDecl(p);\n if (m) return m;\n }\n }\n if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur) || ts.isCaseClause(cur) || ts.isDefaultClause(cur)) {\n const stmts = ts.isCaseClause(cur) || ts.isDefaultClause(cur) ? cur.statements : cur.statements;\n for (const st of stmts) {\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n }\n }\n if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n for (const d of cur.initializer.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n if (ts.isCatchClause(cur) && cur.variableDeclaration) {\n const m = matchDecl(cur.variableDeclaration);\n if (m) return m;\n }\n }\n return null;\n}\n\n/** `this.name` -> name; anything else null. */\nfunction thisMemberName(expr: ts.Expression): string | null {\n return ts.isPropertyAccessExpression(expr) && expr.expression.kind === ts.SyntaxKind.ThisKeyword ? expr.name.text : null;\n}\n\n/** Element class of a tracked QueryList / array expression, or null. */\nfunction listClassOf(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.listDecls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n return member ? (tracked.propLists.get(member) ?? null) : null;\n}\n\n/**\n * Resolves the EUI class name from a property declaration.\n * Checks: type annotation → decorator class argument → template ref map.\n */\nfunction resolveEuiClassName(\n node: ts.PropertyDeclaration,\n sourceFile: ts.SourceFile,\n templateRefMap: Map<string, string>,\n): string | null {\n // Check type annotation first\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n return typeName;\n }\n\n const arrayClass = listElementClass(node.type);\n if (arrayClass) return arrayClass;\n\n // Check generic type argument: ElementRef<EuiXxxComponent> / QueryList<EuiXxxComponent>\n if (node.type && ts.isTypeReferenceNode(node.type) && node.type.typeArguments?.length) {\n const genericArg = getTypeAnnotationName(node.type.typeArguments[0]);\n if (isKnownClass(genericArg)) {\n return genericArg;\n }\n }\n\n // Check decorator arguments: @ViewChild(EuiXxxComponent) or @ViewChild('refName')\n if (node.modifiers) {\n for (const modifier of node.modifiers) {\n if (!ts.isDecorator(modifier)) continue;\n if (!ts.isCallExpression(modifier.expression)) continue;\n\n const decoratorName = getDecoratorName(modifier.expression);\n if (!decoratorName) continue;\n if (!['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'].includes(decoratorName)) continue;\n\n const args = modifier.expression.arguments;\n if (args.length > 0) {\n const firstArg = args[0];\n\n // @ViewChild(EuiXxxComponent) — class reference\n if (ts.isIdentifier(firstArg) && isKnownClass(firstArg.text)) {\n return firstArg.text;\n }\n\n // @ViewChild('refName') — string template ref, resolve via template\n if (ts.isStringLiteralLike(firstArg)) {\n const refName = firstArg.text;\n const euiClass = templateRefMap.get(refName);\n if (isKnownClass(euiClass)) {\n return euiClass;\n }\n }\n }\n }\n }\n\n return null;\n}\n\n/** True for `@ViewChildren/@ContentChildren` fields and `QueryList<...>`-typed fields. */\nfunction isListProperty(node: ts.PropertyDeclaration): boolean {\n if (listElementClass(node.type)) return true;\n if (node.type && ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === 'QueryList') {\n return true;\n }\n return (ts.getDecorators?.(node) ?? []).some(\n (d) => ts.isCallExpression(d.expression) && ['ViewChildren', 'ContentChildren'].includes(getDecoratorName(d.expression) ?? ''),\n );\n}\n\n/**\n * Resolves an expression to the tracked EUI class: `ref`, `this.ref`, `this.ref!`, `(this.ref as any)`,\n * the `.first` / `.last` element of a tracked QueryList, or `list[i]` of a tracked list/array.\n */\nfunction trackedClass(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.decls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n if (member) return tracked.props.get(member) ?? null;\n if (ts.isPropertyAccessExpression(e) && (e.name.text === 'first' || e.name.text === 'last')) {\n return listClassOf(e.expression, tracked);\n }\n if (ts.isElementAccessExpression(e)) return listClassOf(e.expression, tracked);\n return null;\n}\n\nfunction getDecoratorName(callExpr: ts.CallExpression): string | null {\n if (ts.isIdentifier(callExpr.expression)) {\n return callExpr.expression.text;\n }\n return null;\n}\n\nfunction getTypeAnnotationName(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n return typeNode.typeName.text;\n }\n return null;\n}\n\n/**\n * Checks if a property access `ref.prop` should be rewritten to `ref.prop()`.\n *\n * We rewrite if:\n * - `ref` is tracked in euiRefs\n * - `prop` is in the signal set for that EUI class\n * - The access is NOT already a call expression (not `ref.prop()` or `ref.prop(args)`)\n * - The access is NOT a write target (not `ref.prop = value`)\n * - The access is NOT a template binding argument (those are unaffected)\n */\nfunction tryRewritePropertyAccess(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n // Resolve the reference class — handle `this.ref.prop`, `ref.prop`, `list.first.prop`\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Skip if parent is already a call expression on this property: ref.prop(...)\n if (ts.isCallExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip a signal handed to toObservable(ref.prop): it needs the signal itself (e.g. written by migrate-eui-tab-signals)\n if (ts.isCallExpression(node.parent) && node.parent.arguments[0] === node &&\n ts.isIdentifier(node.parent.expression) && node.parent.expression.text === 'toObservable') {\n return null;\n }\n\n // Skip signal API access already in place: ref.prop.set(..) / .update(..) / .asReadonly()\n if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node &&\n ['set', 'update', 'asReadonly'].includes(node.parent.name.text)) {\n return null;\n }\n\n // Skip if this is the left side of an assignment: ref.prop = value\n if (ts.isBinaryExpression(node.parent) &&\n node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n node.parent.left === node) {\n return null;\n }\n\n // Skip if this is a compound assignment: ref.prop += value, ref.prop &&= value, etc.\n if (ts.isBinaryExpression(node.parent) && isAssignmentOperator(node.parent.operatorToken.kind) && node.parent.left === node) {\n return null;\n }\n\n // Skip if this is used with delete: delete ref.prop\n if (ts.isDeleteExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip if inside a typeof: typeof ref.prop\n if (ts.isTypeOfExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip property access chains that go deeper: ref.prop.something → ref.prop().something\n // This IS correct — we still want to add ()\n\n // Rewrite: insert () after the property name\n const end = node.name.getEnd();\n return {\n start: end,\n end: end,\n replacement: '()',\n };\n}\n\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;\n}\n\n/** Marker used to detect an already-inserted TODO so the schematic stays idempotent. */\nconst WRITE_TODO_MARKER = 'TODO(eui-signals):';\n\n/**\n * Detects a programmatic WRITE to a now-signal input and returns an edit that\n * comments out the offending statement and prepends an explanatory TODO.\n *\n * A signal input (`input()`) exposes a read-only getter — it cannot be assigned\n * from outside the component (`comp.prop = value` no longer compiles, and\n * `comp.prop()` is a getter, not a setter). There is no safe, mechanical\n * rewrite: the correct fix is to drive the value declaratively through a\n * template binding (`[prop]=\"...\"`) or, when a ComponentRef is genuinely\n * available, `componentRef.setInput('prop', value)`. Both require human\n * judgement, so instead of rewriting we comment the statement out (keeping the\n * build green) and leave a TODO pointing at the manual fix.\n *\n * Only acts when the assignment is the ENTIRE statement\n * (`ExpressionStatement` whose expression is exactly this assignment):\n * ref.prop = value (simple assignment)\n * ref.prop += value, etc. (compound assignment)\n * where `ref` is a tracked EUI/ECL reference and `prop` is in its signal set.\n *\n * When the write is only part of a larger statement (e.g. inside an `if`\n * without a block, or nested in another expression), commenting it out would\n * also remove unrelated logic, so we leave it untouched (it will surface as a\n * compile error the developer must resolve by hand).\n */\nfunction tryInsertWriteTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Only act on assignment targets: `ref.prop = ...` or `ref.prop <op>= ...`\n if (\n !ts.isBinaryExpression(node.parent) ||\n node.parent.left !== node ||\n !isAssignmentOperator(node.parent.operatorToken.kind)\n ) {\n return null;\n }\n\n const assignment = node.parent;\n\n // A plain `=` to a writable signal is migrated to `.set()` by trySetRewrite\n if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken && EUI_WRITABLE_SIGNAL_MAP[cls]?.has(propName)) {\n return null;\n }\n\n // Only comment out when the assignment IS the whole statement — otherwise we'd\n // delete unrelated logic from a larger statement.\n const statement = node.parent.parent;\n if (!statement || !ts.isExpressionStatement(statement) || statement.expression !== assignment) {\n return null;\n }\n\n // The statement must stand on its own (a direct child of a block/source), not\n // be the unbraced body of an `if`/`for`/`while` etc. — commenting those out by\n // line would swallow the surrounding `if (...)` and break the code.\n const parent = statement.parent;\n if (\n !parent ||\n !(ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isModuleBlock(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent))\n ) {\n return null;\n }\n\n const stmtStart = statement.getStart(sourceFile);\n const stmtEnd = statement.getEnd(); // includes the trailing semicolon\n const lineStart = getLineStartPosition(source, stmtStart);\n const indent = source.slice(lineStart, stmtStart);\n\n // Commenting works per line: the statement must be alone on its lines, otherwise\n // (e.g. `run() { ref.prop = 1; }`) we would comment out surrounding code.\n const eol = source.indexOf('\\n', stmtEnd);\n const restOfLine = source.slice(stmtEnd, eol === -1 ? source.length : eol);\n if (indent.trim() !== '' || restOfLine.trim() !== '') {\n return null;\n }\n\n // The statement text, as written (may span multiple lines).\n const statementText = source.slice(stmtStart, stmtEnd);\n\n // Comment out every line of the statement, preserving each line's own\n // indentation (insert `// ` after the leading whitespace). The first line's\n // indentation was stripped by starting the replacement at lineStart, so we\n // re-add it explicitly.\n const commentedStatement = statementText\n .split('\\n')\n .map((line, i) => {\n if (i === 0) return `${indent}// ${line}`;\n const lineIndent = line.slice(0, line.length - line.trimStart().length);\n return `${lineIndent}// ${line.trimStart()}`;\n })\n .join('\\n');\n\n const todo =\n `${indent}// ${WRITE_TODO_MARKER} '${propName}' is now a signal input and cannot be assigned directly.\\n` +\n `${indent}// Set it via a template binding ([${propName}]=\"...\") or componentRef.setInput('${propName}', ...).\\n` +\n `${indent}// The original statement is commented out below so the build does not fail:\\n`;\n\n // Replace the statement (from the start of its line, to drop the original\n // indentation we re-add) with the TODO + commented-out statement.\n return {\n start: lineStart,\n end: stmtEnd,\n replacement: todo + commentedStatement,\n };\n}\n\n/** `ref.prop = value;` on a writable signal -> `ref.prop.set(value);` (two zero-width-safe edits). */\nfunction trySetRewrite(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] {\n const assignment = node.parent;\n if (\n !ts.isBinaryExpression(assignment) ||\n assignment.left !== node ||\n assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||\n !ts.isExpressionStatement(assignment.parent)\n ) {\n return [];\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_WRITABLE_SIGNAL_MAP[cls]?.has(node.name.text)) return [];\n\n return [\n { start: node.getEnd(), end: assignment.right.getStart(sourceFile), replacement: '.set(' },\n { start: assignment.right.getEnd(), end: assignment.right.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** `ref.out.subscribe(...)` -> `outputToObservable(ref.out).subscribe(...)`. */\nfunction tryWrapOutput(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] | null {\n const parent = node.parent;\n if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || !OBSERVABLE_METHODS.has(parent.name.text)) {\n return null;\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n\n const start = node.getStart(sourceFile);\n return [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** Marker for a read of a property that was a @HostBinding and no longer exists. */\nconst HOST_TODO_MARKER = 'TODO(eui-signals):';\n\nfunction tryHostBindingTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_HOST_BINDING_REMOVED_MAP[cls]?.has(propName) || EUI_SIGNAL_MAP[cls]?.has(propName)) return null;\n return flagTodo(\n node,\n sourceFile,\n source,\n `'${propName}' was a @HostBinding`,\n `'${propName}' was a @HostBinding property of ${cls} and no longer exists on the instance ` +\n '(moved to static host metadata). Remove or replace this access.',\n );\n}\n\n/**\n * Inserts a `// TODO(eui-signals): <message>` line above the enclosing statement / class member.\n * `key` identifies the TODO for idempotency (looked for in the comment lines right above).\n */\nfunction flagTodo(node: ts.Node, sourceFile: ts.SourceFile, source: string, key: string, message: string): Edit | null {\n // Anchor on the enclosing statement / class member\n let anchor: ts.Node = node;\n while (\n anchor.parent &&\n !(\n ts.isBlock(anchor.parent) ||\n ts.isSourceFile(anchor.parent) ||\n ts.isModuleBlock(anchor.parent) ||\n ts.isCaseClause(anchor.parent) ||\n ts.isDefaultClause(anchor.parent) ||\n ts.isClassLike(anchor.parent)\n )\n ) {\n anchor = anchor.parent;\n }\n\n const lineStart = getLineStartPosition(source, anchor.getStart(sourceFile));\n const indent = source.slice(lineStart).match(/^[ \\t]*/)![0];\n const text = `${indent}// ${HOST_TODO_MARKER} ${message}\\n`;\n\n // Idempotent: look at the contiguous comment lines right above\n const above = source.slice(0, lineStart).split('\\n').slice(-8).reverse();\n for (const line of above.slice(1)) {\n if (!line.trim().startsWith('//')) break;\n if (line.includes(`${HOST_TODO_MARKER} ${key}`) || line.includes(key)) return null;\n }\n // A single-line anchor like `run() { ... }` shares its line with other code: still fine, the comment goes above the line.\n return { start: lineStart, end: lineStart, replacement: text };\n}\n\n/**\n * An output (OutputEmitterRef) used as a value:\n * - an argument of an rxjs combinator (`merge(ref.out, ...)`, also inside an array) is wrapped in `outputToObservable()`;\n * - any other use that is not `.emit()` / `.subscribe()` & co / already wrapped is flagged with a TODO.\n */\nfunction tryOutputUsage(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): { edits: Edit[]; todo?: Edit | null } | null {\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n const parent = node.parent;\n\n // handled elsewhere (tryWrapOutput) or fine as is\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return null;\n if (ts.isNonNullExpression(parent) || ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent)) return null;\n // declared / written outputs are not reads\n if (ts.isBinaryExpression(parent) && parent.left === node) return null;\n\n // argument of a combinator?\n let arg: ts.Node = node;\n if (ts.isArrayLiteralExpression(arg.parent)) arg = arg.parent;\n const call = arg.parent;\n if (ts.isCallExpression(call) && call.arguments.includes(arg as ts.Expression)) {\n const callee = ts.isIdentifier(call.expression) ? call.expression.text : null;\n if (callee === 'outputToObservable') return null; // already migrated\n if (callee && OBSERVABLE_COMBINATORS.has(callee)) {\n const start = node.getStart(sourceFile);\n return {\n edits: [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ],\n };\n }\n }\n\n return {\n edits: [],\n todo: flagTodo(\n node,\n sourceFile,\n source,\n `output '${node.name.text}'`,\n `output '${node.name.text}' of ${cls} is an OutputEmitterRef, not an Observable. Wrap it with outputToObservable() ` +\n '(@angular/core/rxjs-interop) where an Observable is needed.',\n ),\n };\n}\n\n/** Destructuring of a tracked reference, or storing it in a field/variable we cannot follow. */\nfunction tryAliasTodo(node: ts.Node, euiRefs: Refs, sourceFile: ts.SourceFile, source: string): Edit | null {\n if (ts.isVariableDeclaration(node) && node.initializer && !ts.isIdentifier(node.name)) {\n const cls = trackedClass(node.initializer, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `destructuring of ${cls}`,\n `destructuring of ${cls} cannot be migrated automatically: its signal inputs/outputs must be read as ref.prop() / outputToObservable(ref.out).`,\n );\n }\n }\n if (\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n !ts.isIdentifier(unwrap(node.left)) &&\n ts.isExpressionStatement(node.parent)\n ) {\n const cls = trackedClass(node.right, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `aliasing of ${cls}`,\n `aliasing of ${cls}: this copy is not tracked, so its signal inputs/outputs must be updated manually (ref.prop()).`,\n );\n }\n }\n return null;\n}\n\n/** Adds `outputToObservable` to the file's imports (merging into an existing rxjs-interop import). */\nfunction buildOutputImportEdit(sourceFile: ts.SourceFile): Edit | null {\n let lastImportEnd = 0;\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n lastImportEnd = stmt.getEnd();\n if (!ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== '@angular/core/rxjs-interop') continue;\n const bindings = stmt.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n if (bindings.elements.some((e) => e.name.text === 'outputToObservable')) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (last) {\n return { start: last.getEnd(), end: last.getEnd(), replacement: ', outputToObservable' };\n }\n }\n }\n const line = 'import { outputToObservable } from \\'@angular/core/rxjs-interop\\';';\n return lastImportEnd === 0\n ? { start: 0, end: 0, replacement: `${line}\\n` }\n : { start: lastImportEnd, end: lastImportEnd, replacement: `\\n${line}` };\n}\n\n/** True if `edit`'s position falls within any of the given ranges. */\nfunction isInsideAnyRange(edit: Edit, ranges: Edit[]): boolean {\n return ranges.some((range) => edit.start >= range.start && edit.end <= range.end);\n}\n\n/** Returns the index of the first character of the line containing `pos`. */\nfunction getLineStartPosition(source: string, pos: number): number {\n const newlineIndex = source.lastIndexOf('\\n', pos - 1);\n return newlineIndex === -1 ? 0 : newlineIndex + 1;\n}\n\n// ---------------------------------------------------------------------------\n// Template ref resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a map of template reference variable names (#ref) to EUI class names.\n *\n * Parses the component's template (inline or external) and finds elements like:\n * <eui-alert #myAlert> → myAlert → EuiAlertComponent\n * <input euiAutocomplete #ac> → ac → EuiAutocompleteComponent\n *\n * Returns Map<refName, euiClassName>.\n */\nfunction buildTemplateRefMap(\n sourceFile: ts.SourceFile,\n source: string,\n filePath: string,\n tree: Tree,\n): Map<string, string> {\n const refMap = new Map<string, string>();\n\n // Find @Component decorator\n const componentMeta = findComponentMetadata(sourceFile, source);\n if (!componentMeta) return refMap;\n\n let templateSource: string | null = null;\n\n if (componentMeta.inlineTemplate !== null) {\n templateSource = componentMeta.inlineTemplate;\n } else if (componentMeta.templateUrl) {\n // Resolve templateUrl relative to the TS file\n const dir = filePath.substring(0, filePath.lastIndexOf('/'));\n const templatePath = `${dir}/${componentMeta.templateUrl}`;\n const buffer = tree.read(templatePath);\n if (buffer) {\n templateSource = buffer.toString('utf-8');\n }\n }\n\n if (!templateSource) return refMap;\n\n // Parse the template and collect #refs\n try {\n const parsed = parseTemplate(templateSource, '', { preserveWhitespaces: true });\n collectTemplateRefs(parsed.nodes, refMap);\n } catch {\n // Template parse failure — silently skip (might be malformed or use third-party syntax)\n }\n\n return refMap;\n}\n\n/**\n * Extracts @Component metadata: templateUrl or inline template content.\n */\nfunction findComponentMetadata(\n sourceFile: ts.SourceFile,\n source: string,\n): { templateUrl: string | null; inlineTemplate: string | null } | null {\n let result: { templateUrl: string | null; inlineTemplate: string | null } | null = null;\n\n const visit = (node: ts.Node): void => {\n if (result) return;\n\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {\n const name = getDecoratorName(node.expression);\n if (name !== 'Component') {\n ts.forEachChild(node, visit);\n return;\n }\n\n const args = node.expression.arguments;\n if (args.length === 0 || !ts.isObjectLiteralExpression(args[0])) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const meta: { templateUrl: string | null; inlineTemplate: string | null } = {\n templateUrl: null,\n inlineTemplate: null,\n };\n\n for (const prop of args[0].properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n\n if (prop.name.text === 'templateUrl') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.templateUrl = init.text;\n }\n }\n\n if (prop.name.text === 'template') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.inlineTemplate = init.text;\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n meta.inlineTemplate = init.text;\n }\n }\n }\n\n result = meta;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n return result;\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (ts.isParenthesizedExpression(current)) current = current.expression;\n return current;\n}\n\n/**\n * Recursively walks template AST nodes, collecting #refName → EUI class name mappings.\n *\n * For each element with a template reference (#ref), we try to resolve its EUI class:\n * 1. Match element tag name against EUI_SELECTOR_TO_CLASS (e.g. 'eui-alert' → EuiAlertComponent)\n * 2. Match element attributes against attribute selectors (e.g. [euiAutocomplete] → EuiAutocompleteComponent)\n */\nfunction collectTemplateRefs(nodes: TmplAstNode[], refMap: Map<string, string>): void {\n forEachElement(nodes, (node) => {\n if (node.references === undefined || node.references.length === 0) return;\n const euiClass = resolveElementToEuiClass(node);\n if (!euiClass) return;\n for (const ref of node.references) {\n refMap.set(ref.name, euiClass);\n }\n });\n}\n\n/**\n * Given a template element, resolves it to an EUI class name by checking:\n * 1. Tag name: <eui-alert> → look up 'eui-alert' in EUI_SELECTOR_TO_CLASS\n * 2. Attribute selectors: <input euiAutocomplete> → look up 'input[euiAutocomplete]' or '[euiAutocomplete]'\n */\nfunction resolveElementToEuiClass(element: TmplAstElement): string | null {\n const tag = element.name;\n\n // Direct tag match: eui-alert, eui-dialog, etc.\n if (EUI_SELECTOR_TO_CLASS[tag]) {\n return EUI_SELECTOR_TO_CLASS[tag];\n }\n\n // Attribute selector match: check all attributes against known patterns\n const allAttrNames = [\n ...element.attributes.map((a) => a.name),\n ...element.inputs.map((i) => i.name),\n ];\n\n for (const attrName of allAttrNames) {\n // Try tag[attr] pattern first (e.g. 'button[euiButton]', 'input[euiAutocomplete]')\n const tagAttrSelector = `${tag}[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[tagAttrSelector]) {\n return EUI_SELECTOR_TO_CLASS[tagAttrSelector];\n }\n\n // Try [attr] pattern (e.g. '[euiTooltip]', '[euiLoading]')\n const attrSelector = `[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[attrSelector]) {\n return EUI_SELECTOR_TO_CLASS[attrSelector];\n }\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Edit helpers\n// ---------------------------------------------------------------------------\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n // Descending by position; at equal positions `after` edits are applied first so they land last.\n for (const edit of unique.sort((a, b) => b.start - a.start || Number(!!b.after) - Number(!!a.after))) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}:${edit.replacement}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
2281
2269
|
"displayName": "Edit",
|
|
2282
2270
|
"properties": [
|
|
2271
|
+
{
|
|
2272
|
+
"name": "after",
|
|
2273
|
+
"coverageIgnore": false,
|
|
2274
|
+
"deprecated": false,
|
|
2275
|
+
"deprecationMessage": "",
|
|
2276
|
+
"type": "boolean",
|
|
2277
|
+
"indexKey": "",
|
|
2278
|
+
"optional": true,
|
|
2279
|
+
"description": "<p>When several zero-width edits share a position, <code>after</code> ones end up after the others.</p>\n",
|
|
2280
|
+
"line": 64,
|
|
2281
|
+
"rawdescription": "\nWhen several zero-width edits share a position, `after` ones end up after the others."
|
|
2282
|
+
},
|
|
2283
2283
|
{
|
|
2284
2284
|
"name": "end",
|
|
2285
2285
|
"coverageIgnore": false,
|
|
@@ -2289,7 +2289,7 @@
|
|
|
2289
2289
|
"indexKey": "",
|
|
2290
2290
|
"optional": false,
|
|
2291
2291
|
"description": "",
|
|
2292
|
-
"line":
|
|
2292
|
+
"line": 61,
|
|
2293
2293
|
"rawdescription": "\n"
|
|
2294
2294
|
},
|
|
2295
2295
|
{
|
|
@@ -2301,7 +2301,7 @@
|
|
|
2301
2301
|
"indexKey": "",
|
|
2302
2302
|
"optional": false,
|
|
2303
2303
|
"description": "",
|
|
2304
|
-
"line":
|
|
2304
|
+
"line": 62,
|
|
2305
2305
|
"rawdescription": "\n"
|
|
2306
2306
|
},
|
|
2307
2307
|
{
|
|
@@ -2313,7 +2313,7 @@
|
|
|
2313
2313
|
"indexKey": "",
|
|
2314
2314
|
"optional": false,
|
|
2315
2315
|
"description": "",
|
|
2316
|
-
"line":
|
|
2316
|
+
"line": 60,
|
|
2317
2317
|
"rawdescription": "\n"
|
|
2318
2318
|
}
|
|
2319
2319
|
],
|
|
@@ -5206,12 +5206,12 @@
|
|
|
5206
5206
|
},
|
|
5207
5207
|
{
|
|
5208
5208
|
"name": "Schema",
|
|
5209
|
-
"id": "interface-Schema-
|
|
5210
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
5209
|
+
"id": "interface-Schema-da76a6389e783ac252181859f64808f331cae86954ea6f3639260cfddc149589d564991186034ad0940b8e37bca5da4424e4486e09b5933ac73a4b1939dbfc1b-26",
|
|
5210
|
+
"file": "packages/core/schematics/migrate-eui-dialog/index.ts",
|
|
5211
5211
|
"deprecated": false,
|
|
5212
5212
|
"deprecationMessage": "",
|
|
5213
5213
|
"type": "interface",
|
|
5214
|
-
"sourceCode": "import { parseTemplate, TmplAstBoundAttribute, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\nconst COMPONENT_TAG = 'eui-discussion-thread';\n\nexport function migrateEuiDiscussionThread(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let count = 0;\n\n const dir = tree.getDir(scanPath || '/');\n visitDir(dir, (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n if (!original.includes(COMPONENT_TAG)) return;\n\n const result = path.endsWith('.html')\n ? migrateTemplate(original)\n : migrateInlineTemplates(original);\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would remove [trackBy] binding in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n count++;\n }\n\n // Warn about TS usages inline\n if (path.endsWith('.ts') && !path.endsWith('.spec.ts') && original.includes('trackByFn')) {\n const sourceFile = ts.createSourceFile(path, original, ts.ScriptTarget.Latest, true);\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && node.name.text === 'trackByFn') {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n context.logger.warn(`${path}:${line + 1} - \"trackByFn\" has been removed from ${COMPONENT_TAG}. Remove this reference manually.`);\n }\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n }\n });\n\n context.logger.info(`Removed trackByFn-based [trackBy] bindings from ${COMPONENT_TAG} in ${count} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.html') && !file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\nfunction migrateTemplate(source: string): string {\n const parsed = parseTemplate(source, '', { preserveWhitespaces: true });\n const removals: { start: number; end: number }[] = [];\n\n visitNodes(parsed.nodes, source, removals);\n\n let result = source;\n for (const { start, end } of removals.sort((a, b) => b.start - a.start)) {\n let adjustedStart = start;\n while (adjustedStart > 0 && (result[adjustedStart - 1] === ' ' || result[adjustedStart - 1] === '\\t')) {\n adjustedStart--;\n }\n result = result.slice(0, adjustedStart) + result.slice(end);\n }\n\n return result;\n}\n\nfunction migrateInlineTemplates(source: string): string {\n const templateRegex = /template\\s*:\\s*`([^`]*)`/gs;\n return source.replace(templateRegex, (match, templateContent: string) => {\n if (!templateContent.includes(COMPONENT_TAG)) return match;\n const migrated = migrateTemplate(templateContent);\n if (migrated === templateContent) return match;\n return match.replace(templateContent, migrated);\n });\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, removals: { start: number; end: number }[]): void {\n forEachElement(nodes, (node) => {\n if (node.name === COMPONENT_TAG) collectRemovals(node, source, removals);\n });\n}\n\nfunction collectRemovals(element: TmplAstElement, source: string, removals: { start: number; end: number }[]): void {\n for (const input of element.inputs) {\n if (input.name === 'trackBy') {\n const valueSource = source.slice(input.sourceSpan.start.offset, input.sourceSpan.end.offset);\n if (valueSource.includes('trackByFn')) {\n removals.push({ start: input.sourceSpan.start.offset, end: input.sourceSpan.end.offset });\n }\n }\n }\n}\n",
|
|
5214
|
+
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * eUI v21 -> v22 migration for eui-dialog.\n *\n * - EuiDialogComponent.isOpen$ (BehaviorSubject) -> `isOpen` getter\n * - acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (`.value` -> `()`, `.next(v)` -> `.set(v)`)\n * - EuiDialogService.getOpenedDialog() Observable -> Signal -> `toObservable(...)` where an injection context is certain\n * - EuiDialogComponent outputs used as Observables (`.subscribe/.pipe`, or passed to merge(...)) -> `outputToObservable(...)`\n * - EuiDialogContainerComponent `cd` / `onScroll()` removed -> TODO + warning\n *\n * Anything that cannot be rewritten without changing behavior is left untouched and flagged with a\n * `// TODO: [eUI v22 migration] ...` comment and a logger warning.\n *\n * shortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\n * argument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\n * type in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\nconst BUTTON_PROPS = new Set(['acceptButtonDisabled$', 'dismissButtonDisabled$']);\nconst SIGNAL_INTEROP = '@angular/core/rxjs-interop';\nconst QUICK_CHECK = /isOpen\\$|ButtonDisabled\\$|getOpenedDialog|onScroll|EuiDialogContainerComponent|EuiDialogComponent/;\n/** EuiDialogComponent outputs (EventEmitter -> OutputEmitterRef): no `.pipe`/`.subscribe` anymore. */\nconst DIALOG_OUTPUTS = new Set(['accept', 'clickOutside', 'dialogClose', 'dialogOpen', 'dismiss', 'escape']);\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n\nexport function migrateEuiDialog(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let count = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n const original = buffer.toString('utf-8');\n if (!QUICK_CHECK.test(original)) return;\n\n const warn = (line: number, msg: string): void => context.logger.warn(`${path}:${line} - ${msg}`);\n const result = path.endsWith('.html')\n ? migrateTemplateText(original, original, (m) => warn(1, m))\n : migrateTs(path, original, warn);\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-dialog usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n count++;\n }\n });\n\n context.logger.info(`Migrated eui-dialog API usages in ${count} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.html') && !file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------\n\nconst REF = String.raw`[A-Za-z_$][\\w$]*(?:\\??\\.[A-Za-z_$][\\w$]*)*`;\n\n/** `context` is the full file text, used to decide whether the file deals with eui-dialog at all. */\nfunction migrateTemplateText(text: string, context: string, warn: (msg: string) => void): string {\n const hasDialog = /<eui-dialog\\b|euiDialog/.test(context);\n let out = text;\n\n if (hasDialog) {\n out = out\n .replace(new RegExp(String.raw`(${REF})\\.isOpen\\$\\s*\\|\\s*async\\b`, 'g'), '$1.isOpen')\n .replace(new RegExp(String.raw`(${REF})\\.isOpen\\$\\??\\.(?:value\\b|getValue\\(\\))`, 'g'), '$1.isOpen');\n }\n out = out\n .replace(new RegExp(String.raw`(${REF})\\.((?:accept|dismiss)ButtonDisabled\\$)\\s*\\|\\s*async\\b`, 'g'), '$1.$2()')\n .replace(new RegExp(String.raw`(${REF})\\.((?:accept|dismiss)ButtonDisabled\\$)\\??\\.(?:value\\b|getValue\\(\\))`, 'g'), '$1.$2()')\n .replace(new RegExp(String.raw`(${REF})\\.getOpenedDialog\\(\\)\\s*\\|\\s*async\\b`, 'g'), '$1.getOpenedDialog()()');\n\n const leftovers: string[] = [];\n if (hasDialog && /\\.isOpen\\$/.test(out)) leftovers.push('isOpen$');\n if (/ButtonDisabled\\$(?!\\(\\))/.test(out)) leftovers.push('acceptButtonDisabled$/dismissButtonDisabled$');\n if (/getOpenedDialog\\(\\)(?!\\s*\\()/.test(out)) leftovers.push('getOpenedDialog()');\n for (const l of leftovers) {\n warn(`Manual action needed: template still uses the removed Observable API \"${l}\". Read the signal/getter instead (see eUI 21 to 22 migration guide, eui-dialog).`);\n }\n return out;\n}\n\nfunction migrateInlineTemplates(source: string, warn: (msg: string) => void): string {\n return source.replace(/template\\s*:\\s*`([^`]*)`/gs, (match, content: string) => {\n const migrated = migrateTemplateText(content, content, warn);\n return migrated === content ? match : match.replace(content, () => migrated);\n });\n}\n\n// ---------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------\n\ntype Kind = 'dialog' | 'container' | 'service';\n\nfunction classify(text: string): Kind | null {\n if (/\\bEuiDialogContainerComponent\\b/.test(text)) return 'container';\n if (/\\bEuiDialogComponent\\b/.test(text)) return 'dialog';\n if (/\\bEuiDialogService\\b/.test(text)) return 'service';\n return null;\n}\n\nfunction migrateTs(path: string, original: string, warn: (line: number, msg: string) => void): string {\n const sf = ts.createSourceFile(path, original, ts.ScriptTarget.Latest, true);\n const names: Record<Kind, Set<string>> = { dialog: new Set(), container: new Set(), service: new Set() };\n\n collectNames(sf, names);\n\n const edits: Edit[] = [];\n const todoStatements = new Set<number>();\n let needsToObservable = false;\n let needsOutputToObservable = false;\n\n const lineOf = (n: ts.Node): number => sf.getLineAndCharacterOfPosition(n.getStart()).line + 1;\n\n const todo = (node: ts.Node, msg: string): void => {\n warn(lineOf(node), `Manual action needed: ${msg}`);\n const stmt = enclosingStatement(node);\n const start = stmt.getStart();\n if (todoStatements.has(start)) return;\n todoStatements.add(start);\n const lineStart = original.lastIndexOf('\\n', start - 1) + 1;\n const indent = original.slice(lineStart, start).match(/^\\s*/)![0];\n const comment = `// ${TODO_PREFIX} ${msg}`;\n // idempotency: skip when the same comment already precedes the statement\n if (original.slice(0, lineStart).trimEnd().endsWith(comment)) return;\n const eol = original.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({ start: lineStart, end: lineStart, text: `${indent}${comment}${eol}` });\n };\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {\n const prop = node.name.text;\n const recv = receiverKey(node.expression);\n const isDialogLike = recv !== null && (names.dialog.has(recv) || names.container.has(recv));\n const isOpen = prop === 'isOpen$';\n\n if (isDialogLike && (isOpen || BUTTON_PROPS.has(prop))) {\n if (handleSubject(node, prop, isOpen, edits, todo)) return;\n } else if (recv !== null && names.dialog.has(recv) && DIALOG_OUTPUTS.has(prop) && isObservableUse(node) && !isShadowed(node.expression, names)) {\n edits.push({ start: node.getStart(), end: node.getStart(), text: 'outputToObservable(' });\n edits.push({ start: node.getEnd(), end: node.getEnd(), text: ')' });\n needsOutputToObservable = true;\n } else if (recv !== null && names.container.has(recv) && (prop === 'cd' || prop === 'onScroll')) {\n todo(node, `\"${prop}\" was removed from EuiDialogContainerComponent; change detection and scroll handling are internal now. Remove this usage.`);\n }\n } else if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === 'getOpenedDialog'\n ) {\n const recv = receiverKey(node.expression.expression);\n if (recv !== null && names.service.has(recv) && !isAlreadyMigrated(node)) {\n if (inInjectionContext(node)) {\n edits.push({ start: node.getStart(), end: node.getStart(), text: 'toObservable(' });\n edits.push({ start: node.getEnd(), end: node.getEnd(), text: ')' });\n needsToObservable = true;\n } else {\n todo(\n node,\n 'EuiDialogService.getOpenedDialog() now returns a Signal. Read it as getOpenedDialog()() inside computed/effect, or wrap it with toObservable() from @angular/core/rxjs-interop in an injection context.',\n );\n }\n // do not return: nested getOpenedDialog() calls cannot exist inside the receiver\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n\n if (needsToObservable || needsOutputToObservable) {\n const imp = importEdit(sf, original, [\n ...(needsToObservable ? ['toObservable'] : []),\n ...(needsOutputToObservable ? ['outputToObservable'] : []),\n ]);\n if (imp) edits.push(imp);\n }\n\n let result = original;\n // Apply from the end; for equal positions keep insertion order stable by iterating in reverse.\n const ordered = edits.map((e, i) => ({ e, i })).sort((a, b) => b.e.start - a.e.start || b.i - a.i);\n for (const { e } of ordered) {\n result = result.slice(0, e.start) + e.text + result.slice(e.end);\n }\n\n if (result.includes('template')) {\n result = migrateInlineTemplates(result, (m) => warn(1, m));\n }\n return result;\n}\n\n/** Returns true when the node was fully handled and its children must not be visited. */\nfunction handleSubject(\n node: ts.PropertyAccessExpression,\n prop: string,\n isOpen: boolean,\n edits: Edit[],\n todo: (n: ts.Node, msg: string) => void,\n): boolean {\n const parent = node.parent;\n const nameStart = node.name.getStart();\n const replacement = isOpen ? 'isOpen' : `${prop}()`;\n\n // already migrated: `acceptButtonDisabled$()`\n if (!isOpen && ts.isCallExpression(parent) && parent.expression === node) return true;\n\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) {\n const member = parent.name.text;\n if (member === 'set' || member === 'update') return true; // already a signal write\n const call = ts.isCallExpression(parent.parent) && parent.parent.expression === parent ? parent.parent : null;\n\n if (member === 'value' && !isAssignmentTarget(parent)) {\n edits.push({ start: nameStart, end: parent.getEnd(), text: replacement });\n return true;\n }\n if (member === 'getValue' && call && call.arguments.length === 0) {\n edits.push({ start: nameStart, end: call.getEnd(), text: replacement });\n return true;\n }\n if (member === 'next' && call && !isOpen) {\n edits.push({ start: parent.name.getStart(), end: parent.name.getEnd(), text: 'set' });\n return false; // arguments may contain further migratable accesses\n }\n }\n\n if (isOpen) {\n todo(\n node,\n 'EuiDialogComponent.isOpen$ was removed. Read the isOpen getter (boolean) instead; it is not an Observable, so subscribe/pipe usages must be reworked manually (e.g. via computed/effect or the dialogOpen/dialogClose outputs).',\n );\n } else {\n todo(\n node,\n `${prop} is now a WritableSignal. Use ${prop}() to read and ${prop}.set(v) to write; use toObservable(${prop}) from @angular/core/rxjs-interop if an Observable is needed.`,\n );\n }\n return true;\n}\n\nfunction isAssignmentTarget(node: ts.Node): boolean {\n const p = node.parent;\n return ts.isBinaryExpression(p) && p.left === node && p.operatorToken.kind === ts.SyntaxKind.EqualsToken;\n}\n\nfunction isAlreadyMigrated(call: ts.CallExpression): boolean {\n const p = call.parent;\n if (ts.isCallExpression(p)) {\n if (p.expression === call) return true; // getOpenedDialog()()\n if (ts.isIdentifier(p.expression) && p.expression.text === 'toObservable') return true;\n }\n return false;\n}\n\nfunction inInjectionContext(node: ts.Node): boolean {\n for (let n: ts.Node | undefined = node.parent; n; n = n.parent) {\n if (ts.isConstructorDeclaration(n)) return true;\n if (ts.isPropertyDeclaration(n)) return !n.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);\n if (ts.isFunctionLike(n) || ts.isClassDeclaration(n) || ts.isClassExpression(n)) return false;\n }\n return false;\n}\n\nfunction enclosingStatement(node: ts.Node): ts.Node {\n let n: ts.Node = node;\n while (n.parent) {\n const p = n.parent;\n if (\n ts.isBlock(p) ||\n ts.isSourceFile(p) ||\n ts.isClassLike(p) ||\n ts.isModuleBlock(p) ||\n ts.isCaseClause(p) ||\n ts.isDefaultClause(p)\n ) {\n return n;\n }\n n = p;\n }\n return n;\n}\n\n/** Name of the variable/member a receiver expression refers to: `this.x`, `x`, `x()`, `x!`, `(x)`. */\nfunction receiverKey(expr: ts.Expression): string | null {\n let e: ts.Expression = expr;\n for (;;) {\n if (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n else if (ts.isCallExpression(e) && e.arguments.length === 0) e = e.expression;\n else break;\n }\n if (ts.isIdentifier(e)) return e.text;\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) return e.name.text;\n return null;\n}\n\nfunction collectNames(sf: ts.SourceFile, names: Record<Kind, Set<string>>): void {\n const add = (name: ts.Node | undefined, kind: Kind | null): void => {\n if (kind && name && ts.isIdentifier(name)) names[kind].add(name.text);\n };\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyDeclaration(node) || ts.isParameter(node) || ts.isVariableDeclaration(node)) {\n let kind: Kind | null = node.type ? classify(node.type.getText(sf)) : null;\n const init = node.initializer;\n if (!kind && init && ts.isCallExpression(init)) {\n const callee = init.expression.getText(sf);\n if (/^(inject|viewChild|viewChild\\.required|contentChild|contentChild\\.required)$/.test(callee)) {\n const typeArgs = init.typeArguments?.map((t) => t.getText(sf)).join(',') ?? '';\n const firstArg = init.arguments[0]?.getText(sf) ?? '';\n kind = classify(typeArgs) ?? classify(firstArg);\n }\n }\n if (!kind && ts.canHaveDecorators(node)) {\n for (const d of ts.getDecorators(node) ?? []) {\n if (ts.isCallExpression(d.expression) && /^(ViewChild|ContentChild)$/.test(d.expression.expression.getText(sf))) {\n kind = classify(d.expression.arguments[0]?.getText(sf) ?? '');\n }\n }\n }\n add(node.name, kind);\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n}\n\n/**\n * True when `node` (an output reference) is used as an Observable: receiver of subscribe/pipe/...,\n * or an argument (directly or inside an array literal) of another call such as merge(...).\n * Already wrapped (`outputToObservable(x.out)`) is not matched.\n */\nfunction isObservableUse(node: ts.PropertyAccessExpression): boolean {\n const p = node.parent;\n if (ts.isPropertyAccessExpression(p) && p.expression === node) {\n return OBSERVABLE_METHODS.has(p.name.text) && ts.isCallExpression(p.parent) && p.parent.expression === p;\n }\n const arg: ts.Node = ts.isArrayLiteralExpression(p) ? p : node;\n const call = arg.parent;\n if (ts.isCallExpression(call) && (call.arguments as readonly ts.Node[]).includes(arg)) {\n const callee = call.expression;\n return !(ts.isIdentifier(callee) && callee.text === 'outputToObservable');\n }\n return false;\n}\n\n/** A bare identifier receiver declared locally (parameter / variable) with a type that is not an eUI dialog. */\nfunction isShadowed(expr: ts.Expression, names: Record<Kind, Set<string>>): boolean {\n let e = expr;\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n if (!ts.isIdentifier(e)) return false;\n for (let n: ts.Node | undefined = e.parent; n; n = n.parent) {\n const decls: ts.Node[] = [];\n if (ts.isFunctionLike(n)) decls.push(...n.parameters);\n if (ts.isBlock(n)) n.statements.forEach((st) => ts.isVariableStatement(st) && decls.push(...st.declarationList.declarations));\n for (const d of decls) {\n const dd = d as ts.ParameterDeclaration | ts.VariableDeclaration;\n if (ts.isIdentifier(dd.name) && dd.name.text === e.text) {\n const t = dd.type?.getText();\n return !(t && classify(t) === 'dialog') && !(dd.initializer && classify(dd.initializer.getText()) === 'dialog');\n }\n }\n }\n return false;\n}\n\n/** Adds the given names to the rxjs-interop import, or creates the import after the last one. */\nfunction importEdit(sf: ts.SourceFile, source: string, wanted: string[]): Edit | null {\n const imports = sf.statements.filter(ts.isImportDeclaration);\n const existing = imports.find((i) => (i.moduleSpecifier as ts.StringLiteral).text === SIGNAL_INTEROP);\n const bindings = existing?.importClause?.namedBindings;\n if (existing && bindings && ts.isNamedImports(bindings)) {\n const missing = wanted.filter((w) => !bindings.elements.some((e) => e.name.text === w));\n if (!missing.length) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (!last) return { start: bindings.getStart(), end: bindings.getEnd(), text: `{ ${missing.join(', ')} }` };\n return { start: last.getEnd(), end: last.getEnd(), text: `, ${missing.join(', ')}` };\n }\n const line = `import { ${wanted.join(', ')} } from '${SIGNAL_INTEROP}';`;\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lastImport = imports[imports.length - 1];\n if (lastImport) return { start: lastImport.getEnd(), end: lastImport.getEnd(), text: `${eol}${line}` };\n return { start: 0, end: 0, text: `${line}${eol}` };\n}\n",
|
|
5215
5215
|
"displayName": "Schema",
|
|
5216
5216
|
"properties": [
|
|
5217
5217
|
{
|
|
@@ -5223,7 +5223,7 @@
|
|
|
5223
5223
|
"indexKey": "",
|
|
5224
5224
|
"optional": true,
|
|
5225
5225
|
"description": "",
|
|
5226
|
-
"line":
|
|
5226
|
+
"line": 27,
|
|
5227
5227
|
"rawdescription": "\n"
|
|
5228
5228
|
},
|
|
5229
5229
|
{
|
|
@@ -5235,12 +5235,14 @@
|
|
|
5235
5235
|
"indexKey": "",
|
|
5236
5236
|
"optional": true,
|
|
5237
5237
|
"description": "",
|
|
5238
|
-
"line":
|
|
5238
|
+
"line": 26,
|
|
5239
5239
|
"rawdescription": "\n"
|
|
5240
5240
|
}
|
|
5241
5241
|
],
|
|
5242
5242
|
"indexSignatures": [],
|
|
5243
5243
|
"kind": 172,
|
|
5244
|
+
"description": "<p>eUI v21 -> v22 migration for eui-dialog.</p>\n<ul>\n<li>EuiDialogComponent.isOpen$ (BehaviorSubject) -> <code>isOpen</code> getter</li>\n<li>acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (<code>.value</code> -> <code>()</code>, <code>.next(v)</code> -> <code>.set(v)</code>)</li>\n<li>EuiDialogService.getOpenedDialog() Observable -> Signal -> <code>toObservable(...)</code> where an injection context is certain</li>\n<li>EuiDialogComponent outputs used as Observables (<code>.subscribe/.pipe</code>, or passed to merge(...)) -> <code>outputToObservable(...)</code></li>\n<li>EuiDialogContainerComponent <code>cd</code> / <code>onScroll()</code> removed -> TODO + warning</li>\n</ul>\n<p>Anything that cannot be rewritten without changing behavior is left untouched and flagged with a\n<code>// TODO: [eUI v22 migration] ...</code> comment and a logger warning.</p>\n<p>shortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\nargument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\ntype in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.</p>\n",
|
|
5245
|
+
"rawdescription": "\n\neUI v21 -> v22 migration for eui-dialog.\n\n- EuiDialogComponent.isOpen$ (BehaviorSubject) -> `isOpen` getter\n- acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (`.value` -> `()`, `.next(v)` -> `.set(v)`)\n- EuiDialogService.getOpenedDialog() Observable -> Signal -> `toObservable(...)` where an injection context is certain\n- EuiDialogComponent outputs used as Observables (`.subscribe/.pipe`, or passed to merge(...)) -> `outputToObservable(...)`\n- EuiDialogContainerComponent `cd` / `onScroll()` removed -> TODO + warning\n\nAnything that cannot be rewritten without changing behavior is left untouched and flagged with a\n`// TODO: [eUI v22 migration] ...` comment and a logger warning.\n\nshortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\nargument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\ntype in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.\n",
|
|
5244
5246
|
"methods": [],
|
|
5245
5247
|
"extends": [],
|
|
5246
5248
|
"isDuplicate": true,
|
|
@@ -5253,12 +5255,12 @@
|
|
|
5253
5255
|
},
|
|
5254
5256
|
{
|
|
5255
5257
|
"name": "Schema",
|
|
5256
|
-
"id": "interface-Schema-
|
|
5257
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
5258
|
+
"id": "interface-Schema-4486b2ff645679826ae9eb409e089e7ca0390f03b2f6a831ab9cf027339caa7615e2946de8d5f61764ad21209c46bf3be643b9006715ab37995097b47e45f29d-27",
|
|
5259
|
+
"file": "packages/core/schematics/migrate-eui-discussion-thread/index.ts",
|
|
5258
5260
|
"deprecated": false,
|
|
5259
5261
|
"deprecationMessage": "",
|
|
5260
5262
|
"type": "interface",
|
|
5261
|
-
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * eUI v21 -> v22 migration for eui-dialog.\n *\n * - EuiDialogComponent.isOpen$ (BehaviorSubject) -> `isOpen` getter\n * - acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (`.value` -> `()`, `.next(v)` -> `.set(v)`)\n * - EuiDialogService.getOpenedDialog() Observable -> Signal -> `toObservable(...)` where an injection context is certain\n * - EuiDialogComponent outputs used as Observables (`.subscribe/.pipe`, or passed to merge(...)) -> `outputToObservable(...)`\n * - EuiDialogContainerComponent `cd` / `onScroll()` removed -> TODO + warning\n *\n * Anything that cannot be rewritten without changing behavior is left untouched and flagged with a\n * `// TODO: [eUI v22 migration] ...` comment and a logger warning.\n *\n * shortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\n * argument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\n * type in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\nconst BUTTON_PROPS = new Set(['acceptButtonDisabled$', 'dismissButtonDisabled$']);\nconst SIGNAL_INTEROP = '@angular/core/rxjs-interop';\nconst QUICK_CHECK = /isOpen\\$|ButtonDisabled\\$|getOpenedDialog|onScroll|EuiDialogContainerComponent|EuiDialogComponent/;\n/** EuiDialogComponent outputs (EventEmitter -> OutputEmitterRef): no `.pipe`/`.subscribe` anymore. */\nconst DIALOG_OUTPUTS = new Set(['accept', 'clickOutside', 'dialogClose', 'dialogOpen', 'dismiss', 'escape']);\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n\nexport function migrateEuiDialog(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let count = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n const original = buffer.toString('utf-8');\n if (!QUICK_CHECK.test(original)) return;\n\n const warn = (line: number, msg: string): void => context.logger.warn(`${path}:${line} - ${msg}`);\n const result = path.endsWith('.html')\n ? migrateTemplateText(original, original, (m) => warn(1, m))\n : migrateTs(path, original, warn);\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-dialog usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n count++;\n }\n });\n\n context.logger.info(`Migrated eui-dialog API usages in ${count} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.html') && !file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------\n\nconst REF = String.raw`[A-Za-z_$][\\w$]*(?:\\??\\.[A-Za-z_$][\\w$]*)*`;\n\n/** `context` is the full file text, used to decide whether the file deals with eui-dialog at all. */\nfunction migrateTemplateText(text: string, context: string, warn: (msg: string) => void): string {\n const hasDialog = /<eui-dialog\\b|euiDialog/.test(context);\n let out = text;\n\n if (hasDialog) {\n out = out\n .replace(new RegExp(String.raw`(${REF})\\.isOpen\\$\\s*\\|\\s*async\\b`, 'g'), '$1.isOpen')\n .replace(new RegExp(String.raw`(${REF})\\.isOpen\\$\\??\\.(?:value\\b|getValue\\(\\))`, 'g'), '$1.isOpen');\n }\n out = out\n .replace(new RegExp(String.raw`(${REF})\\.((?:accept|dismiss)ButtonDisabled\\$)\\s*\\|\\s*async\\b`, 'g'), '$1.$2()')\n .replace(new RegExp(String.raw`(${REF})\\.((?:accept|dismiss)ButtonDisabled\\$)\\??\\.(?:value\\b|getValue\\(\\))`, 'g'), '$1.$2()')\n .replace(new RegExp(String.raw`(${REF})\\.getOpenedDialog\\(\\)\\s*\\|\\s*async\\b`, 'g'), '$1.getOpenedDialog()()');\n\n const leftovers: string[] = [];\n if (hasDialog && /\\.isOpen\\$/.test(out)) leftovers.push('isOpen$');\n if (/ButtonDisabled\\$(?!\\(\\))/.test(out)) leftovers.push('acceptButtonDisabled$/dismissButtonDisabled$');\n if (/getOpenedDialog\\(\\)(?!\\s*\\()/.test(out)) leftovers.push('getOpenedDialog()');\n for (const l of leftovers) {\n warn(`Manual action needed: template still uses the removed Observable API \"${l}\". Read the signal/getter instead (see eUI 21 to 22 migration guide, eui-dialog).`);\n }\n return out;\n}\n\nfunction migrateInlineTemplates(source: string, warn: (msg: string) => void): string {\n return source.replace(/template\\s*:\\s*`([^`]*)`/gs, (match, content: string) => {\n const migrated = migrateTemplateText(content, content, warn);\n return migrated === content ? match : match.replace(content, () => migrated);\n });\n}\n\n// ---------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------\n\ntype Kind = 'dialog' | 'container' | 'service';\n\nfunction classify(text: string): Kind | null {\n if (/\\bEuiDialogContainerComponent\\b/.test(text)) return 'container';\n if (/\\bEuiDialogComponent\\b/.test(text)) return 'dialog';\n if (/\\bEuiDialogService\\b/.test(text)) return 'service';\n return null;\n}\n\nfunction migrateTs(path: string, original: string, warn: (line: number, msg: string) => void): string {\n const sf = ts.createSourceFile(path, original, ts.ScriptTarget.Latest, true);\n const names: Record<Kind, Set<string>> = { dialog: new Set(), container: new Set(), service: new Set() };\n\n collectNames(sf, names);\n\n const edits: Edit[] = [];\n const todoStatements = new Set<number>();\n let needsToObservable = false;\n let needsOutputToObservable = false;\n\n const lineOf = (n: ts.Node): number => sf.getLineAndCharacterOfPosition(n.getStart()).line + 1;\n\n const todo = (node: ts.Node, msg: string): void => {\n warn(lineOf(node), `Manual action needed: ${msg}`);\n const stmt = enclosingStatement(node);\n const start = stmt.getStart();\n if (todoStatements.has(start)) return;\n todoStatements.add(start);\n const lineStart = original.lastIndexOf('\\n', start - 1) + 1;\n const indent = original.slice(lineStart, start).match(/^\\s*/)![0];\n const comment = `// ${TODO_PREFIX} ${msg}`;\n // idempotency: skip when the same comment already precedes the statement\n if (original.slice(0, lineStart).trimEnd().endsWith(comment)) return;\n const eol = original.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({ start: lineStart, end: lineStart, text: `${indent}${comment}${eol}` });\n };\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {\n const prop = node.name.text;\n const recv = receiverKey(node.expression);\n const isDialogLike = recv !== null && (names.dialog.has(recv) || names.container.has(recv));\n const isOpen = prop === 'isOpen$';\n\n if (isDialogLike && (isOpen || BUTTON_PROPS.has(prop))) {\n if (handleSubject(node, prop, isOpen, edits, todo)) return;\n } else if (recv !== null && names.dialog.has(recv) && DIALOG_OUTPUTS.has(prop) && isObservableUse(node) && !isShadowed(node.expression, names)) {\n edits.push({ start: node.getStart(), end: node.getStart(), text: 'outputToObservable(' });\n edits.push({ start: node.getEnd(), end: node.getEnd(), text: ')' });\n needsOutputToObservable = true;\n } else if (recv !== null && names.container.has(recv) && (prop === 'cd' || prop === 'onScroll')) {\n todo(node, `\"${prop}\" was removed from EuiDialogContainerComponent; change detection and scroll handling are internal now. Remove this usage.`);\n }\n } else if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === 'getOpenedDialog'\n ) {\n const recv = receiverKey(node.expression.expression);\n if (recv !== null && names.service.has(recv) && !isAlreadyMigrated(node)) {\n if (inInjectionContext(node)) {\n edits.push({ start: node.getStart(), end: node.getStart(), text: 'toObservable(' });\n edits.push({ start: node.getEnd(), end: node.getEnd(), text: ')' });\n needsToObservable = true;\n } else {\n todo(\n node,\n 'EuiDialogService.getOpenedDialog() now returns a Signal. Read it as getOpenedDialog()() inside computed/effect, or wrap it with toObservable() from @angular/core/rxjs-interop in an injection context.',\n );\n }\n // do not return: nested getOpenedDialog() calls cannot exist inside the receiver\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n\n if (needsToObservable || needsOutputToObservable) {\n const imp = importEdit(sf, original, [\n ...(needsToObservable ? ['toObservable'] : []),\n ...(needsOutputToObservable ? ['outputToObservable'] : []),\n ]);\n if (imp) edits.push(imp);\n }\n\n let result = original;\n // Apply from the end; for equal positions keep insertion order stable by iterating in reverse.\n const ordered = edits.map((e, i) => ({ e, i })).sort((a, b) => b.e.start - a.e.start || b.i - a.i);\n for (const { e } of ordered) {\n result = result.slice(0, e.start) + e.text + result.slice(e.end);\n }\n\n if (result.includes('template')) {\n result = migrateInlineTemplates(result, (m) => warn(1, m));\n }\n return result;\n}\n\n/** Returns true when the node was fully handled and its children must not be visited. */\nfunction handleSubject(\n node: ts.PropertyAccessExpression,\n prop: string,\n isOpen: boolean,\n edits: Edit[],\n todo: (n: ts.Node, msg: string) => void,\n): boolean {\n const parent = node.parent;\n const nameStart = node.name.getStart();\n const replacement = isOpen ? 'isOpen' : `${prop}()`;\n\n // already migrated: `acceptButtonDisabled$()`\n if (!isOpen && ts.isCallExpression(parent) && parent.expression === node) return true;\n\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) {\n const member = parent.name.text;\n if (member === 'set' || member === 'update') return true; // already a signal write\n const call = ts.isCallExpression(parent.parent) && parent.parent.expression === parent ? parent.parent : null;\n\n if (member === 'value' && !isAssignmentTarget(parent)) {\n edits.push({ start: nameStart, end: parent.getEnd(), text: replacement });\n return true;\n }\n if (member === 'getValue' && call && call.arguments.length === 0) {\n edits.push({ start: nameStart, end: call.getEnd(), text: replacement });\n return true;\n }\n if (member === 'next' && call && !isOpen) {\n edits.push({ start: parent.name.getStart(), end: parent.name.getEnd(), text: 'set' });\n return false; // arguments may contain further migratable accesses\n }\n }\n\n if (isOpen) {\n todo(\n node,\n 'EuiDialogComponent.isOpen$ was removed. Read the isOpen getter (boolean) instead; it is not an Observable, so subscribe/pipe usages must be reworked manually (e.g. via computed/effect or the dialogOpen/dialogClose outputs).',\n );\n } else {\n todo(\n node,\n `${prop} is now a WritableSignal. Use ${prop}() to read and ${prop}.set(v) to write; use toObservable(${prop}) from @angular/core/rxjs-interop if an Observable is needed.`,\n );\n }\n return true;\n}\n\nfunction isAssignmentTarget(node: ts.Node): boolean {\n const p = node.parent;\n return ts.isBinaryExpression(p) && p.left === node && p.operatorToken.kind === ts.SyntaxKind.EqualsToken;\n}\n\nfunction isAlreadyMigrated(call: ts.CallExpression): boolean {\n const p = call.parent;\n if (ts.isCallExpression(p)) {\n if (p.expression === call) return true; // getOpenedDialog()()\n if (ts.isIdentifier(p.expression) && p.expression.text === 'toObservable') return true;\n }\n return false;\n}\n\nfunction inInjectionContext(node: ts.Node): boolean {\n for (let n: ts.Node | undefined = node.parent; n; n = n.parent) {\n if (ts.isConstructorDeclaration(n)) return true;\n if (ts.isPropertyDeclaration(n)) return !n.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);\n if (ts.isFunctionLike(n) || ts.isClassDeclaration(n) || ts.isClassExpression(n)) return false;\n }\n return false;\n}\n\nfunction enclosingStatement(node: ts.Node): ts.Node {\n let n: ts.Node = node;\n while (n.parent) {\n const p = n.parent;\n if (\n ts.isBlock(p) ||\n ts.isSourceFile(p) ||\n ts.isClassLike(p) ||\n ts.isModuleBlock(p) ||\n ts.isCaseClause(p) ||\n ts.isDefaultClause(p)\n ) {\n return n;\n }\n n = p;\n }\n return n;\n}\n\n/** Name of the variable/member a receiver expression refers to: `this.x`, `x`, `x()`, `x!`, `(x)`. */\nfunction receiverKey(expr: ts.Expression): string | null {\n let e: ts.Expression = expr;\n for (;;) {\n if (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n else if (ts.isCallExpression(e) && e.arguments.length === 0) e = e.expression;\n else break;\n }\n if (ts.isIdentifier(e)) return e.text;\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) return e.name.text;\n return null;\n}\n\nfunction collectNames(sf: ts.SourceFile, names: Record<Kind, Set<string>>): void {\n const add = (name: ts.Node | undefined, kind: Kind | null): void => {\n if (kind && name && ts.isIdentifier(name)) names[kind].add(name.text);\n };\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyDeclaration(node) || ts.isParameter(node) || ts.isVariableDeclaration(node)) {\n let kind: Kind | null = node.type ? classify(node.type.getText(sf)) : null;\n const init = node.initializer;\n if (!kind && init && ts.isCallExpression(init)) {\n const callee = init.expression.getText(sf);\n if (/^(inject|viewChild|viewChild\\.required|contentChild|contentChild\\.required)$/.test(callee)) {\n const typeArgs = init.typeArguments?.map((t) => t.getText(sf)).join(',') ?? '';\n const firstArg = init.arguments[0]?.getText(sf) ?? '';\n kind = classify(typeArgs) ?? classify(firstArg);\n }\n }\n if (!kind && ts.canHaveDecorators(node)) {\n for (const d of ts.getDecorators(node) ?? []) {\n if (ts.isCallExpression(d.expression) && /^(ViewChild|ContentChild)$/.test(d.expression.expression.getText(sf))) {\n kind = classify(d.expression.arguments[0]?.getText(sf) ?? '');\n }\n }\n }\n add(node.name, kind);\n }\n ts.forEachChild(node, visit);\n };\n visit(sf);\n}\n\n/**\n * True when `node` (an output reference) is used as an Observable: receiver of subscribe/pipe/...,\n * or an argument (directly or inside an array literal) of another call such as merge(...).\n * Already wrapped (`outputToObservable(x.out)`) is not matched.\n */\nfunction isObservableUse(node: ts.PropertyAccessExpression): boolean {\n const p = node.parent;\n if (ts.isPropertyAccessExpression(p) && p.expression === node) {\n return OBSERVABLE_METHODS.has(p.name.text) && ts.isCallExpression(p.parent) && p.parent.expression === p;\n }\n const arg: ts.Node = ts.isArrayLiteralExpression(p) ? p : node;\n const call = arg.parent;\n if (ts.isCallExpression(call) && (call.arguments as readonly ts.Node[]).includes(arg)) {\n const callee = call.expression;\n return !(ts.isIdentifier(callee) && callee.text === 'outputToObservable');\n }\n return false;\n}\n\n/** A bare identifier receiver declared locally (parameter / variable) with a type that is not an eUI dialog. */\nfunction isShadowed(expr: ts.Expression, names: Record<Kind, Set<string>>): boolean {\n let e = expr;\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n if (!ts.isIdentifier(e)) return false;\n for (let n: ts.Node | undefined = e.parent; n; n = n.parent) {\n const decls: ts.Node[] = [];\n if (ts.isFunctionLike(n)) decls.push(...n.parameters);\n if (ts.isBlock(n)) n.statements.forEach((st) => ts.isVariableStatement(st) && decls.push(...st.declarationList.declarations));\n for (const d of decls) {\n const dd = d as ts.ParameterDeclaration | ts.VariableDeclaration;\n if (ts.isIdentifier(dd.name) && dd.name.text === e.text) {\n const t = dd.type?.getText();\n return !(t && classify(t) === 'dialog') && !(dd.initializer && classify(dd.initializer.getText()) === 'dialog');\n }\n }\n }\n return false;\n}\n\n/** Adds the given names to the rxjs-interop import, or creates the import after the last one. */\nfunction importEdit(sf: ts.SourceFile, source: string, wanted: string[]): Edit | null {\n const imports = sf.statements.filter(ts.isImportDeclaration);\n const existing = imports.find((i) => (i.moduleSpecifier as ts.StringLiteral).text === SIGNAL_INTEROP);\n const bindings = existing?.importClause?.namedBindings;\n if (existing && bindings && ts.isNamedImports(bindings)) {\n const missing = wanted.filter((w) => !bindings.elements.some((e) => e.name.text === w));\n if (!missing.length) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (!last) return { start: bindings.getStart(), end: bindings.getEnd(), text: `{ ${missing.join(', ')} }` };\n return { start: last.getEnd(), end: last.getEnd(), text: `, ${missing.join(', ')}` };\n }\n const line = `import { ${wanted.join(', ')} } from '${SIGNAL_INTEROP}';`;\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lastImport = imports[imports.length - 1];\n if (lastImport) return { start: lastImport.getEnd(), end: lastImport.getEnd(), text: `${eol}${line}` };\n return { start: 0, end: 0, text: `${line}${eol}` };\n}\n",
|
|
5263
|
+
"sourceCode": "import { parseTemplate, TmplAstBoundAttribute, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\nconst COMPONENT_TAG = 'eui-discussion-thread';\n\nexport function migrateEuiDiscussionThread(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let count = 0;\n\n const dir = tree.getDir(scanPath || '/');\n visitDir(dir, (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n if (!original.includes(COMPONENT_TAG)) return;\n\n const result = path.endsWith('.html')\n ? migrateTemplate(original)\n : migrateInlineTemplates(original);\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would remove [trackBy] binding in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n count++;\n }\n\n // Warn about TS usages inline\n if (path.endsWith('.ts') && !path.endsWith('.spec.ts') && original.includes('trackByFn')) {\n const sourceFile = ts.createSourceFile(path, original, ts.ScriptTarget.Latest, true);\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && node.name.text === 'trackByFn') {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n context.logger.warn(`${path}:${line + 1} - \"trackByFn\" has been removed from ${COMPONENT_TAG}. Remove this reference manually.`);\n }\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n }\n });\n\n context.logger.info(`Removed trackByFn-based [trackBy] bindings from ${COMPONENT_TAG} in ${count} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.html') && !file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\nfunction migrateTemplate(source: string): string {\n const parsed = parseTemplate(source, '', { preserveWhitespaces: true });\n const removals: { start: number; end: number }[] = [];\n\n visitNodes(parsed.nodes, source, removals);\n\n let result = source;\n for (const { start, end } of removals.sort((a, b) => b.start - a.start)) {\n let adjustedStart = start;\n while (adjustedStart > 0 && (result[adjustedStart - 1] === ' ' || result[adjustedStart - 1] === '\\t')) {\n adjustedStart--;\n }\n result = result.slice(0, adjustedStart) + result.slice(end);\n }\n\n return result;\n}\n\nfunction migrateInlineTemplates(source: string): string {\n const templateRegex = /template\\s*:\\s*`([^`]*)`/gs;\n return source.replace(templateRegex, (match, templateContent: string) => {\n if (!templateContent.includes(COMPONENT_TAG)) return match;\n const migrated = migrateTemplate(templateContent);\n if (migrated === templateContent) return match;\n return match.replace(templateContent, migrated);\n });\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, removals: { start: number; end: number }[]): void {\n forEachElement(nodes, (node) => {\n if (node.name === COMPONENT_TAG) collectRemovals(node, source, removals);\n });\n}\n\nfunction collectRemovals(element: TmplAstElement, source: string, removals: { start: number; end: number }[]): void {\n for (const input of element.inputs) {\n if (input.name === 'trackBy') {\n const valueSource = source.slice(input.sourceSpan.start.offset, input.sourceSpan.end.offset);\n if (valueSource.includes('trackByFn')) {\n removals.push({ start: input.sourceSpan.start.offset, end: input.sourceSpan.end.offset });\n }\n }\n }\n}\n",
|
|
5262
5264
|
"displayName": "Schema",
|
|
5263
5265
|
"properties": [
|
|
5264
5266
|
{
|
|
@@ -5270,7 +5272,7 @@
|
|
|
5270
5272
|
"indexKey": "",
|
|
5271
5273
|
"optional": true,
|
|
5272
5274
|
"description": "",
|
|
5273
|
-
"line":
|
|
5275
|
+
"line": 9,
|
|
5274
5276
|
"rawdescription": "\n"
|
|
5275
5277
|
},
|
|
5276
5278
|
{
|
|
@@ -5282,14 +5284,12 @@
|
|
|
5282
5284
|
"indexKey": "",
|
|
5283
5285
|
"optional": true,
|
|
5284
5286
|
"description": "",
|
|
5285
|
-
"line":
|
|
5287
|
+
"line": 8,
|
|
5286
5288
|
"rawdescription": "\n"
|
|
5287
5289
|
}
|
|
5288
5290
|
],
|
|
5289
5291
|
"indexSignatures": [],
|
|
5290
5292
|
"kind": 172,
|
|
5291
|
-
"description": "<p>eUI v21 -> v22 migration for eui-dialog.</p>\n<ul>\n<li>EuiDialogComponent.isOpen$ (BehaviorSubject) -> <code>isOpen</code> getter</li>\n<li>acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (<code>.value</code> -> <code>()</code>, <code>.next(v)</code> -> <code>.set(v)</code>)</li>\n<li>EuiDialogService.getOpenedDialog() Observable -> Signal -> <code>toObservable(...)</code> where an injection context is certain</li>\n<li>EuiDialogComponent outputs used as Observables (<code>.subscribe/.pipe</code>, or passed to merge(...)) -> <code>outputToObservable(...)</code></li>\n<li>EuiDialogContainerComponent <code>cd</code> / <code>onScroll()</code> removed -> TODO + warning</li>\n</ul>\n<p>Anything that cannot be rewritten without changing behavior is left untouched and flagged with a\n<code>// TODO: [eUI v22 migration] ...</code> comment and a logger warning.</p>\n<p>shortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\nargument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\ntype in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.</p>\n",
|
|
5292
|
-
"rawdescription": "\n\neUI v21 -> v22 migration for eui-dialog.\n\n- EuiDialogComponent.isOpen$ (BehaviorSubject) -> `isOpen` getter\n- acceptButtonDisabled$ / dismissButtonDisabled$ -> WritableSignal (`.value` -> `()`, `.next(v)` -> `.set(v)`)\n- EuiDialogService.getOpenedDialog() Observable -> Signal -> `toObservable(...)` where an injection context is certain\n- EuiDialogComponent outputs used as Observables (`.subscribe/.pipe`, or passed to merge(...)) -> `outputToObservable(...)`\n- EuiDialogContainerComponent `cd` / `onScroll()` removed -> TODO + warning\n\nAnything that cannot be rewritten without changing behavior is left untouched and flagged with a\n`// TODO: [eUI v22 migration] ...` comment and a logger warning.\n\nshortcut: receivers are matched by member/variable NAME within one file (declared type, ViewChild\nargument or inject()/viewChild() argument), not via the type checker; a same-named variable of another\ntype in the same file would be mis-identified. Upgrade to a ts.Program if that shows up.\n",
|
|
5293
5293
|
"methods": [],
|
|
5294
5294
|
"extends": [],
|
|
5295
5295
|
"isDuplicate": true,
|
|
@@ -5868,12 +5868,12 @@
|
|
|
5868
5868
|
},
|
|
5869
5869
|
{
|
|
5870
5870
|
"name": "Schema",
|
|
5871
|
-
"id": "interface-Schema-
|
|
5872
|
-
"file": "packages/core/schematics/migrate-
|
|
5871
|
+
"id": "interface-Schema-e82ad5d05a8363ecab95140e3f129427949eb3d53d4272814efdb8f6458ebc01b92b07c76d5e15e5491679d59f5b9b723c3f191c3c12257261a751583757f3fe-40",
|
|
5872
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
5873
5873
|
"deprecated": false,
|
|
5874
5874
|
"deprecationMessage": "",
|
|
5875
5875
|
"type": "interface",
|
|
5876
|
-
"sourceCode": "import {\n Binary,\n BindingPipe,\n BindingType,\n CombinedRecursiveAstVisitor,\n ImplicitReceiver,\n parseTemplate,\n PropertyRead,\n SafePropertyRead,\n TmplAstElement,\n TmplAstText,\n} from '@angular/compiler';\nimport { dirname, join, normalize } from '@angular-devkit/core';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit, TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * Migrates @ngx-translate/core v17 -> v18 breaking changes.\n *\n * No type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\n * file (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\n * templates, from the component class that owns the template.\n * shortcut: receivers that are aliased, destructured, passed through other types or declared in another\n * file are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst CORE = '@ngx-translate/core';\nconst HTTP_LOADER = '@ngx-translate/http-loader';\n\nconst TOKEN_PROVIDERS: Record<string, string> = {\n TranslateLoader: 'provideTranslateLoader',\n TranslateCompiler: 'provideTranslateCompiler',\n TranslateParser: 'provideTranslateParser',\n MissingTranslationHandler: 'provideMissingTranslationHandler',\n};\nconst PLUGIN_KEYS = ['loader', 'compiler', 'parser', 'missingTranslationHandler'];\nconst MEMBER_RENAMES: Record<string, string> = {\n setDefaultLang: 'setFallbackLang',\n getDefaultLang: 'getFallbackLang',\n onDefaultLangChange: 'onFallbackLangChange',\n};\nconst ASSIGN_OPS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.EqualsToken,\n ts.SyntaxKind.PlusEqualsToken,\n ts.SyntaxKind.MinusEqualsToken,\n ts.SyntaxKind.QuestionQuestionEqualsToken,\n ts.SyntaxKind.BarBarEqualsToken,\n ts.SyntaxKind.AmpersandAmpersandEqualsToken,\n]);\n\nexport function migrateNgxTranslate18(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const tsFiles: string[] = [];\n const htmlFiles: string[] = [];\n visitDir(tree.getDir(scanPath || '/'), (path) => (path.endsWith('.html') ? htmlFiles : tsFiles).push(path));\n\n const projectUsesNgx = tsFiles.some((f) => tree.read(f)?.toString('utf-8').includes(CORE));\n const read = (p: string): string | undefined => tree.read(p)?.toString('utf-8');\n // forChild({ extend: true }) services merge translations; setTranslation(lang, t) callers need a review then.\n const projectHasExtend = tsFiles.some((f) => {\n const s = read(f);\n return !!s && s.includes('forChild') && /extend\\s*:\\s*true/.test(s);\n });\n\n let fileCount = 0;\n const write = (path: string, original: string, result: string): void => {\n if (result === original) return;\n if (options.dryRun) logDryRun(context, `Would migrate @ngx-translate/core usages in ${path}`);\n else tree.overwrite(path, result);\n fileCount++;\n };\n\n for (const path of tsFiles) {\n const original = read(path);\n if (!original) continue;\n const hasCore = original.includes(CORE) || original.includes(HTTP_LOADER);\n if (!hasCore && !(original.includes('template') && original.includes('translate'))) continue;\n write(path, original, migrateTypeScript(original, path, context, { projectHasExtend, projectUsesNgx, read }));\n }\n\n for (const path of htmlFiles) {\n const original = read(path);\n if (!original || !/translate|currentLang/.test(original)) continue;\n const members = membersForExternalTemplate(path, tsFiles, read);\n const scan = scanTemplate(original, path, context, {\n members,\n allowKeyRewrite: true,\n checkAttributes: projectUsesNgx,\n where: (o) => `${path}:${lineOf(original, o)}`,\n });\n write(path, original, applyEdits(original, scan.edits));\n }\n\n context.logger.info(`Migrated @ngx-translate/core usages in ${fileCount} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TemplateScan {\n edits: Edit[];\n usage: { pipe: boolean; directive: boolean };\n}\n\nfunction scanTemplate(\n source: string,\n filePath: string,\n context: SchematicContext,\n opts: {\n members: Set<string>;\n allowKeyRewrite: boolean;\n checkAttributes?: boolean;\n where: (offset: number) => string;\n quiet?: boolean\n }\n): TemplateScan {\n const result: TemplateScan = { edits: [], usage: { pipe: false, directive: false } };\n let parsed;\n try {\n parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n } catch {\n return result;\n }\n if (parsed.errors && parsed.errors.length > 0) return result;\n\n const seenWarnings = new Set<string>();\n const warn = (offset: number, message: string): void => {\n const text = `${opts.where(offset)} - Manual action needed: ${message}`;\n if (opts.quiet || seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const writes = new Set<unknown>();\n const isSvc = (r: unknown): boolean =>\n r instanceof PropertyRead && r.receiver instanceof ImplicitReceiver && opts.members.has(r.name);\n\n const visitor = new (class extends CombinedRecursiveAstVisitor {\n override visitBinary(ast: Binary, context: unknown): void {\n if (ast.operation.endsWith('=') && !['==', '===', '!=', '!==', '<=', '>='].includes(ast.operation)) {\n const left = ast.left;\n if ((left instanceof PropertyRead || left instanceof SafePropertyRead) && left.name === 'currentLang' && isSvc(left.receiver)) {\n writes.add(left);\n warn(left.sourceSpan.start, 'TranslateService.currentLang is a read-only Signal in @ngx-translate/core v18; use translate.use(lang) instead of assigning it.');\n }\n }\n super.visitBinary(ast, context);\n }\n\n override visitPropertyRead(ast: PropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitPropertyRead(ast, context);\n }\n\n override visitSafePropertyRead(ast: SafePropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitSafePropertyRead(ast, context);\n }\n\n override visitPipe(ast: BindingPipe, context: unknown): void {\n if (ast.name === 'translate') result.usage.pipe = true;\n super.visitPipe(ast, context);\n }\n\n override visitElement(el: TmplAstElement): void {\n this.checkTranslateAttribute(el);\n super.visitElement(el);\n }\n\n override visitTemplate(t: Parameters<CombinedRecursiveAstVisitor['visitTemplate']>[0]): void {\n if (\n [...t.attributes, ...t.inputs, ...t.templateAttrs].some((a) => a.name === 'translate' || a.name === 'ngx-translate')\n ) {\n result.usage.directive = true;\n }\n super.visitTemplate(t);\n }\n\n private rewriteCurrentLang(ast: PropertyRead | SafePropertyRead): void {\n if (ast.name !== 'currentLang' || writes.has(ast) || !isSvc(ast.receiver)) return;\n const end = ast.nameSpan.end;\n if (/^\\s*\\(/.test(source.slice(end))) return; // already a call\n result.edits.push({ start: end, end, replacement: '()' });\n }\n\n private checkTranslateAttribute(el: TmplAstElement): void {\n if (opts.checkAttributes === false) return;\n const textAttr = el.attributes.find((a) => a.name === 'translate' || a.name === 'ngx-translate');\n const bound = el.inputs.find((i) => i.name === 'translate' && i.type === BindingType.Property);\n if (textAttr || bound) result.usage.directive = true;\n const at = el.startSourceSpan.start.offset;\n const todo = (message: string): void => {\n warn(at, `<${el.name}> ${message}`);\n const edit = createTodoEdit(source, at, message);\n if (edit) result.edits.push(edit);\n };\n\n // 7: [translate]=\"'KEY'\" now sets textContent: element children are overwritten.\n if (bound && el.children.some((c) => !(c instanceof TmplAstText))) {\n todo(\n 'with [translate] the element content is replaced by the translation (textContent) in @ngx-translate/core v18, child elements are lost. Restructure the markup.'\n );\n return;\n }\n\n // 8: <el translate>KEY</el> (text as key) is deprecated.\n if (!textAttr || textAttr.name !== 'translate' || textAttr.value !== '' || bound) return;\n const meaningful = el.children.filter((c) => !(c instanceof TmplAstText && c.value.trim() === ''));\n if (meaningful.length === 0) return;\n const only = meaningful[0];\n const isPlain =\n meaningful.length === 1 &&\n el.children.length === 1 &&\n only instanceof TmplAstText &&\n !!el.endSourceSpan &&\n source.slice(el.startSourceSpan.end.offset, el.endSourceSpan.start.offset) === only.value &&\n !/[\"'`&<>{}\\\\]/.test(only.value);\n if (!isPlain) {\n todo(\n 'uses its text content as translation key, which is deprecated and not safely convertible here (interpolation or nested elements). Use [translate]=\"\\'KEY\\'\", the translate pipe or *translateBlock.'\n );\n return;\n }\n if (!opts.allowKeyRewrite) {\n warn(at, `<${el.name}> text as translation key is deprecated; replace with [translate]=\"'KEY'\" (not rewritten inside a quoted inline template).`);\n return;\n }\n const key = (only as TmplAstText).value.trim();\n result.edits.push({\n start: textAttr.sourceSpan.start.offset,\n end: textAttr.sourceSpan.end.offset,\n replacement: `[translate]=\"'${key}'\"`,\n });\n result.edits.push({ start: el.startSourceSpan.end.offset, end: el.endSourceSpan!.start.offset, replacement: '' });\n }\n })();\n\n for (const node of parsed.nodes) visitor.visit(node);\n return result;\n}\n\n/** Members typed/injected as TranslateService of the component whose templateUrl points at `htmlPath`. */\nfunction membersForExternalTemplate(htmlPath: string, tsFiles: string[], read: (p: string) => string | undefined): Set<string> {\n const dir = dirOf(htmlPath);\n for (const f of tsFiles) {\n if (dirOf(f) !== dir || f.endsWith('.spec.ts')) continue;\n const src = read(f);\n if (!src || !src.includes('templateUrl') || !src.includes(CORE)) continue;\n const sf = ts.createSourceFile(f, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const helper = new ServiceResolver(sf);\n for (const stmt of sf.statements) {\n if (!ts.isClassDeclaration(stmt)) continue;\n const url = componentProp(stmt, 'templateUrl');\n if (url && ts.isStringLiteralLike(url.initializer) && resolveUrl(dir, url.initializer.text) === normalize(htmlPath)) {\n return helper.members(stmt);\n }\n }\n }\n return new Set();\n}\n\nfunction componentObject(cls: ts.ClassDeclaration): ts.ObjectLiteralExpression | undefined {\n for (const d of ts.getDecorators(cls) ?? []) {\n if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === 'Component') {\n const arg = d.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg)) return arg;\n }\n }\n return undefined;\n}\n\nfunction componentProp(cls: ts.ClassDeclaration, name: string): ts.PropertyAssignment | undefined {\n return componentObject(cls)?.properties.find(\n (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name\n );\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TranslateService receiver resolution\n// ---------------------------------------------------------------------------------------------------------------------\n\nclass ServiceResolver {\n readonly svcName: string | undefined;\n private cache = new Map<ts.Node, Set<string>>();\n\n constructor(private readonly sf: ts.SourceFile, typeName = 'TranslateService') {\n this.svcName = importedLocalName(sf, typeName);\n }\n\n isType(t: ts.TypeNode | undefined): boolean {\n return !!this.svcName && !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === this.svcName;\n }\n\n isInject(e: ts.Expression | undefined): boolean {\n if (!this.svcName || !e) return false;\n const x = unwrap(e);\n if (!ts.isCallExpression(x)) return false;\n const c = x.expression;\n const named = (ts.isIdentifier(c) && c.text === 'inject') || (ts.isPropertyAccessExpression(c) && c.name.text === 'inject');\n const a = x.arguments[0];\n return named && !!a && ts.isIdentifier(a) && a.text === this.svcName;\n }\n\n members(cls: ts.ClassLikeDeclaration): Set<string> {\n const cached = this.cache.get(cls);\n if (cached) return cached;\n const set = new Set<string>();\n for (const m of cls.members) {\n if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && (this.isType(m.type) || this.isInject(m.initializer))) set.add(m.name.text);\n if (ts.isConstructorDeclaration(m)) {\n for (const p of m.parameters) {\n const isProp = ts.getModifiers(p)?.some((x) =>\n [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(x.kind)\n );\n if (isProp && ts.isIdentifier(p.name) && this.isType(p.type)) set.add(p.name.text);\n }\n }\n }\n this.cache.set(cls, set);\n return set;\n }\n\n /** true: declared as TranslateService, false: declared as something else, undefined: not found. */\n bare(id: ts.Identifier): boolean | undefined {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if (\n (ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) &&\n cur.initializer &&\n ts.isVariableDeclarationList(cur.initializer)\n ) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return this.isType(d.type) || (ts.isVariableDeclaration(d) && this.isInject(d.initializer));\n }\n return undefined;\n }\n\n isService(expr: ts.Expression): boolean {\n const e = unwrap(expr);\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) {\n for (let cur: ts.Node | undefined = e.parent; cur; cur = cur.parent) {\n if (ts.isClassLike(cur)) return this.members(cur).has(e.name.text);\n }\n return false;\n }\n return ts.isIdentifier(e) && this.bare(e) === true;\n }\n}\n\nfunction unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n return e;\n}\n\n/** Local name of a non-type-only named import of `imported` from @ngx-translate/core. */\nfunction importedLocalName(sf: ts.SourceFile, imported: string, module = CORE): string | undefined {\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== module) continue;\n const nb = stmt.importClause?.namedBindings;\n if (!nb || !ts.isNamedImports(nb)) continue;\n for (const el of nb.elements) if ((el.propertyName ?? el.name).text === imported) return el.name.text;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TsEnv {\n projectHasExtend: boolean;\n projectUsesNgx: boolean;\n read: (p: string) => string | undefined;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext, env: TsEnv): string {\n const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const resolver = new ServiceResolver(sf);\n const edits: Edit[] = [];\n const todos = new Map<number, { anchor: ts.Node; messages: string[] }>();\n const needed = new Set<string>();\n const touched = new Set<string>();\n const handled = new Set<ts.Node>();\n const moves = new Map<ts.ObjectLiteralExpression, { calls: ts.CallExpression[]; texts: string[] }>();\n const moduleName = importedLocalName(sf, 'TranslateModule') === 'TranslateModule' ? 'TranslateModule' : undefined;\n const setValueName = importedLocalName(sf, 'setValue') === 'setValue' ? 'setValue' : undefined;\n const defaultEvent = importedLocalName(sf, 'DefaultLangChangeEvent') === 'DefaultLangChangeEvent';\n const tokenImported = (t: string): boolean => importedLocalName(sf, t) === t;\n const providerNames = new Set(['provideTranslateService'].filter((n) => importedLocalName(sf, n) === n));\n let importProvidersTouched = false;\n\n const seenWarnings = new Set<string>();\n const warnOnce = (text: string): void => {\n if (seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const storeResolver = new ServiceResolver(sf, 'TranslateStore');\n const httpNames = new Set(\n ['provideTranslateHttpLoader', 'TranslateHttpLoader'].map((n) => importedLocalName(sf, n, HTTP_LOADER)).filter((n): n is string => !!n)\n );\n const iServiceName = importedLocalName(sf, 'ITranslateService');\n const lineNo = (node: ts.Node): number => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n const flag = (node: ts.Node, message: string, comment = true): void => {\n warnOnce(`${filePath}:${lineNo(node)} - Manual action needed: ${message}`);\n if (!comment) return;\n const anchor = anchorOf(node);\n const key = anchor.getStart(sf);\n const entry = todos.get(key) ?? { anchor, messages: [] };\n const clean = sanitize(message);\n if (!entry.messages.includes(clean)) entry.messages.push(clean);\n todos.set(key, entry);\n };\n\n const nameOf = (n: ts.PropertyName | undefined): string | undefined =>\n n && (ts.isIdentifier(n) || ts.isStringLiteral(n)) ? n.text : undefined;\n const propOf = (obj: ts.ObjectLiteralExpression, name: string): ts.ObjectLiteralElementLike | undefined =>\n obj.properties.find((p) => !!p.name && nameOf(p.name) === name);\n\n // ----- config object transforms (defaultLanguage, useDefaultLang, plugin providers, extend/isolate) -----\n const CHILD_UNSUPPORTED = ['defaultLanguage', 'fallbackLang', 'lang', 'langs', 'useDefaultLang'];\n const transformConfig = (obj: ts.ObjectLiteralExpression, dropChildProps: boolean, out: Edit[], childTarget = false): number => {\n const drop = new Set<ts.ObjectLiteralElementLike>();\n for (const p of obj.properties) {\n const name = nameOf(p.name);\n if (!name) continue;\n if (childTarget && CHILD_UNSUPPORTED.includes(name) && ts.isPropertyAssignment(p)) {\n drop.add(p);\n flag(p, `${name} was removed: ChildTranslateServiceConfig has no such option, child services inherit the parent's fallbackLang and language. Set it on the root provideTranslateService() if needed.`);\n continue;\n }\n if (name === 'defaultLanguage') {\n if (ts.isPropertyAssignment(p)) out.push({\n start: p.name.getStart(sf),\n end: p.name.getEnd(),\n replacement: 'fallbackLang',\n });\n else if (ts.isShorthandPropertyAssignment(p)) out.push({\n start: p.getStart(sf),\n end: p.getEnd(),\n replacement: 'fallbackLang: defaultLanguage',\n });\n } else if (name === 'useDefaultLang' && ts.isPropertyAssignment(p)) {\n if (p.initializer.kind === ts.SyntaxKind.TrueKeyword) {\n drop.add(p);\n } else {\n flag(\n p,\n 'useDefaultLang was removed in @ngx-translate/core v18 and is kept only because its value is false: v18 always falls back to fallbackLang when it is set. Remove the leftover property manually (it does not compile as is); drop fallbackLang too if you relied on useDefaultLang: false.'\n );\n }\n } else if (dropChildProps && (name === 'extend' || name === 'isolate') && ts.isPropertyAssignment(p)) {\n drop.add(p);\n } else if (PLUGIN_KEYS.includes(name) && ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {\n const init = p.initializer;\n const provide = propOf(init, 'provide');\n const token = provide && ts.isPropertyAssignment(provide) && ts.isIdentifier(provide.initializer) ? provide.initializer.text : undefined;\n if (!token || !TOKEN_PROVIDERS[token]) continue;\n const useClass = propOf(init, 'useClass');\n if (init.properties.length === 2 && useClass && ts.isPropertyAssignment(useClass) && tokenImported(token)) {\n const fn = TOKEN_PROVIDERS[token];\n out.push({\n start: init.getStart(sf),\n end: init.getEnd(),\n replacement: `${fn}(${useClass.initializer.getText(sf)})`,\n });\n needed.add(fn);\n touched.add(token);\n } else {\n flag(\n p,\n `the ${token} provider uses a form other than { provide, useClass } (useFactory/useValue/deps). Convert it manually to ${TOKEN_PROVIDERS[token]}(...).`\n );\n }\n }\n }\n if (drop.size > 0) out.push(...removeArrayElements(obj, new Set([...drop].map((d) => obj.properties.indexOf(d))), sf));\n return drop.size;\n };\n\n // ----- TranslateModule.forRoot / forChild -----\n const convertModuleCall = (call: ts.CallExpression): void => {\n const callee = call.expression as ts.PropertyAccessExpression;\n handled.add(callee.expression);\n const method = callee.name.text;\n const args = call.arguments;\n const undecidable = (why: string): void =>\n flag(call, `TranslateModule.${method}() was left unchanged: ${why}. Use provideTranslateService() / provideChildTranslateService() manually.`);\n\n if (args.length > 1 || (args.length === 1 && !ts.isObjectLiteralExpression(args[0]))) return undecidable('its config is not an object literal');\n const obj = args[0] as ts.ObjectLiteralExpression | undefined;\n let fn = method === 'forRoot' ? 'provideTranslateService' : 'provideChildTranslateService';\n let hadExtendTrue = false;\n if (method === 'forChild' && obj) {\n for (const p of obj.properties) {\n const name = p.name ? nameOf(p.name) : undefined;\n if (ts.isSpreadAssignment(p)) return undecidable('its config contains a spread');\n if (name !== 'isolate' && name !== 'extend') continue;\n const init = ts.isPropertyAssignment(p) ? p.initializer.kind : undefined;\n if (init !== ts.SyntaxKind.TrueKeyword && init !== ts.SyntaxKind.FalseKeyword) return undecidable(`${name} is not a boolean literal`);\n if (name === 'isolate' && init === ts.SyntaxKind.TrueKeyword) fn = 'provideTranslateService';\n if (name === 'extend' && init === ts.SyntaxKind.TrueKeyword) hadExtendTrue = true;\n }\n }\n\n // the placement is decided first, so nothing is emitted for an unmovable call\n const parent = call.parent;\n let move: ts.ObjectLiteralExpression | undefined;\n let unwrapImportProviders: ts.CallExpression | undefined;\n if (ts.isArrayLiteralExpression(parent) && ts.isPropertyAssignment(parent.parent) && nameOf(parent.parent.name) === 'imports' && ts.isObjectLiteralExpression(parent.parent.parent)) {\n const owner = parent.parent.parent;\n const decorator = owner.parent;\n if (ts.isCallExpression(decorator) && ts.isIdentifier(decorator.expression) && decorator.expression.text === 'Component') {\n return undecidable('a standalone @Component cannot take environment providers; provide it in the application/route providers instead');\n }\n move = owner;\n } else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'importProvidersFrom') {\n if (parent.arguments.length !== 1) return undecidable('it is combined with other sources in importProvidersFrom()');\n unwrapImportProviders = parent;\n }\n\n const local: Edit[] = [];\n const removed = obj ? transformConfig(obj, method === 'forChild', local, fn === 'provideChildTranslateService') : 0;\n const keepConfig = !!obj && obj.properties.length - removed > 0;\n const cfgText = keepConfig ? applyEdits(source.slice(obj!.getStart(sf), obj!.getEnd()), shift(local, -obj!.getStart(sf))) : '';\n const text = `${fn}(${cfgText})`;\n needed.add(fn);\n touched.add('TranslateModule');\n if (method === 'forChild') {\n warnOnce(\n `${filePath}:${lineNo(call)} - forChild() was converted to ${fn}(): v18 child services use their own store with parent fallback, review isolation semantics.${hadExtendTrue ? ' extend: true was removed: setTranslation(lang, t) no longer merges, pass true as third argument where needed.' : ''}`\n );\n }\n\n if (move) {\n const g = moves.get(move) ?? { calls: [], texts: [] };\n g.calls.push(call);\n g.texts.push(text);\n moves.set(move, g);\n } else if (unwrapImportProviders) {\n edits.push({ start: unwrapImportProviders.getStart(sf), end: unwrapImportProviders.getEnd(), replacement: text });\n importProvidersTouched = true;\n } else {\n edits.push({ start: call.getStart(sf), end: call.getEnd(), replacement: text });\n }\n };\n\n // ----- bare TranslateModule in imports/exports -----\n const convertBareModule = (id: ts.Identifier, arr: ts.ArrayLiteralExpression, owner: ts.ObjectLiteralExpression): void => {\n handled.add(id);\n const callNode = owner.parent;\n const kind = ts.isCallExpression(callNode) && ts.isIdentifier(callNode.expression) ? callNode.expression.text : '';\n let names = ['TranslatePipe', 'TranslateDirective'];\n if (kind === 'Component') {\n const u = componentUsage(owner);\n if (u) names = [u.pipe ? 'TranslatePipe' : '', u.directive ? 'TranslateDirective' : ''].filter(Boolean);\n }\n const present = new Set(arr.elements.filter(ts.isIdentifier).map((e) => e.text));\n const add = names.filter((n) => !present.has(n));\n touched.add('TranslateModule');\n for (const n of names) needed.add(n);\n if (add.length > 0) {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: add.join(', ') });\n } else {\n edits.push(...removeArrayElements(arr, new Set([arr.elements.indexOf(id)]), sf));\n }\n };\n\n const componentUsage = (owner: ts.ObjectLiteralExpression): { pipe: boolean; directive: boolean } | null => {\n const tpl = propOf(owner, 'template');\n const url = propOf(owner, 'templateUrl');\n const quiet = { members: new Set<string>(), allowKeyRewrite: false, where: (): string => '', quiet: true };\n if (tpl && ts.isPropertyAssignment(tpl) && (ts.isNoSubstitutionTemplateLiteral(tpl.initializer) || ts.isStringLiteral(tpl.initializer))) {\n const lit = tpl.initializer;\n return scanTemplate(source.slice(lit.getStart(sf) + 1, lit.getEnd() - 1), filePath, context, quiet).usage;\n }\n if (url && ts.isPropertyAssignment(url) && ts.isStringLiteralLike(url.initializer)) {\n const target = resolveUrl(dirOf(filePath), url.initializer.text);\n const html = env.read(target);\n if (html !== undefined) return scanTemplate(html, target, context, quiet).usage;\n }\n return null;\n };\n\n // ----- visitor -----\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n\n if (ts.isCallExpression(node)) visitCall(node);\n else if (ts.isPropertyAccessExpression(node)) visitMember(node);\n else if (ts.isVariableDeclaration(node)) visitAlias(node.name, node.initializer, node);\n else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) visitAlias(undefined, node.right, node);\n else if (ts.isIdentifier(node)) visitIdentifier(node);\n else if (ts.isClassDeclaration(node)) visitInlineTemplate(node);\n\n ts.forEachChild(node, visit);\n };\n\n const visitCall = (call: ts.CallExpression): void => {\n const c = call.expression;\n if (moduleName && ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === moduleName && (c.name.text === 'forRoot' || c.name.text === 'forChild')) {\n convertModuleCall(call);\n return;\n }\n if (ts.isIdentifier(c) && providerNames.has(c.text) && call.arguments[0] && ts.isObjectLiteralExpression(call.arguments[0])) {\n transformConfig(call.arguments[0], false, edits);\n }\n if (setValueName && ts.isIdentifier(c) && c.text === setValueName) {\n const a0 = call.arguments[0];\n const assignable = !!a0 && (ts.isIdentifier(a0) || ts.isPropertyAccessExpression(a0) || ts.isElementAccessExpression(a0));\n if (ts.isExpressionStatement(call.parent) && call.arguments.length === 3 && assignable) {\n edits.push({ start: c.getStart(sf), end: c.getEnd(), replacement: `${a0.getText(sf)} = insertValue` });\n needed.add('insertValue');\n touched.add('setValue');\n } else {\n flag(call, 'setValue() was replaced by insertValue(), which returns a new object instead of mutating its argument. Use `target = insertValue(target, key, value)` manually.');\n }\n }\n if (ts.isPropertyAccessExpression(c) && resolver.isService(c.expression)) {\n if (c.name.text === 'getCurrentLang') {\n flag(call, 'getCurrentLang() returns Language | null in @ngx-translate/core v18 (null before a language is set). Handle the null case, e.g. `?? fallback`.');\n } else if (c.name.text === 'setTranslation' && call.arguments.length === 2 && env.projectHasExtend) {\n flag(call, 'setTranslation(lang, translations) no longer merges for services that used forChild({ extend: true }); pass `true` as third argument if you relied on merging.');\n }\n }\n };\n\n const visitMember = (n: ts.PropertyAccessExpression): void => {\n const member = n.name.text;\n if ((member === 'onTranslationChange' || member === 'getValue') && storeResolver.isService(n.expression)) {\n edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: member === 'getValue' ? 'getTranslationValue' : 'translationChange$',\n });\n return;\n }\n const isTracked = ['currentLang', 'langs', 'defaultLang', ...Object.keys(MEMBER_RENAMES)].includes(member);\n if (!isTracked || !resolver.isService(n.expression)) return;\n const parent = n.parent;\n if (MEMBER_RENAMES[member]) {\n edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: MEMBER_RENAMES[member] });\n return;\n }\n if (ts.isCallExpression(parent) && parent.expression === n) return; // already `currentLang()` etc.\n const isWrite =\n (ts.isBinaryExpression(parent) && parent.left === n && ASSIGN_OPS.has(parent.operatorToken.kind)) ||\n ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&\n (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) ||\n ts.isDeleteExpression(parent);\n if (isWrite) {\n flag(n, `${member} cannot be assigned in @ngx-translate/core v18 (read-only Signal / removed). Use use(), setFallbackLang() or setTranslation() instead.`);\n return;\n }\n if (member === 'currentLang') edits.push({ start: n.getEnd(), end: n.getEnd(), replacement: '()' });\n else if (member === 'langs') edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: 'getLangs()',\n });\n else edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: 'fallbackLang()' });\n };\n\n const visitAlias = (name: ts.BindingName | undefined, init: ts.Expression | undefined, at: ts.Node): void => {\n if (!init) return;\n if (!resolver.isService(init) && !(name && ts.isObjectBindingPattern(name) && resolver.isInject(init))) return;\n if (name && ts.isIdentifier(name) && ts.isVariableDeclaration(at) && resolver.isType(at.type)) return; // typed alias is tracked\n flag(\n at,\n 'TranslateService is aliased or destructured here, so currentLang/default*/langs usages through it are not migrated automatically. Review them against the v18 API (currentLang() signal, fallbackLang, getLangs()).'\n );\n };\n\n const visitIdentifier = (id: ts.Identifier): void => {\n const p = id.parent;\n if ((ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id)) return;\n if (httpNames.has(id.text)) {\n const call = ts.isCallExpression(p) && p.expression === id ? p : undefined;\n const cfg = call?.arguments[0];\n const hasFlag = !!cfg && ts.isObjectLiteralExpression(cfg) && !!propOf(cfg, 'failOnError');\n if (!hasFlag) {\n flag(id, 'the v18 http-loader no longer fails the whole language load when a translation file request fails (it logs a warning and uses {}). Pass failOnError: true to provideTranslateHttpLoader() if you rely on the v17 behaviour.');\n }\n }\n if (iServiceName && id.text === iServiceName && ts.isExpressionWithTypeArguments(p) && ts.isHeritageClause(p.parent) && p.parent.token === ts.SyntaxKind.ImplementsKeyword) {\n flag(id, 'ITranslateService gained isLoading: Signal<boolean> in @ngx-translate/core v18. Add isLoading = signal(false).asReadonly() to this class.');\n }\n if (defaultEvent && id.text === 'DefaultLangChangeEvent') {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: 'FallbackLangChangeEvent' });\n needed.add('FallbackLangChangeEvent');\n touched.add('DefaultLangChangeEvent');\n }\n if (moduleName && id.text === moduleName && !handled.has(id)) {\n // `TranslateModule` as an element of imports / exports\n if (ts.isArrayLiteralExpression(p) && ts.isPropertyAssignment(p.parent) && ['imports', 'exports'].includes(nameOf(p.parent.name) ?? '') && ts.isObjectLiteralExpression(p.parent.parent)) {\n convertBareModule(id, p, p.parent.parent);\n }\n }\n };\n\n const visitInlineTemplate = (cls: ts.ClassDeclaration): void => {\n const tpl = componentProp(cls, 'template');\n if (!tpl) return;\n const lit = tpl.initializer;\n if (!ts.isNoSubstitutionTemplateLiteral(lit) && !ts.isStringLiteral(lit)) return;\n const start = lit.getStart(sf) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (!/translate|currentLang/.test(raw)) return;\n const baseLine = sf.getLineAndCharacterOfPosition(start).line;\n const scan = scanTemplate(raw, filePath, context, {\n members: resolver.members(cls),\n allowKeyRewrite: ts.isNoSubstitutionTemplateLiteral(lit),\n checkAttributes: env.projectUsesNgx,\n where: (o) => `${filePath}:${baseLine + lineOf(raw, o)}`,\n });\n edits.push(...shift(scan.edits, start));\n };\n\n visit(sf);\n\n // moved forRoot/forChild calls: imports -> providers\n for (const [obj, g] of moves) {\n const importsProp = propOf(obj, 'imports') as ts.PropertyAssignment;\n const arr = importsProp.initializer as ts.ArrayLiteralExpression;\n const providersProp = propOf(obj, 'providers');\n if (providersProp && !(ts.isPropertyAssignment(providersProp) && ts.isArrayLiteralExpression(providersProp.initializer))) {\n for (const call of g.calls) flag(call, 'the providers property is not an array literal, so the converted provider could not be moved there. Move it manually.');\n continue;\n }\n const texts = g.texts.join(', ');\n const movedIdx = new Set(g.calls.map((c) => arr.elements.indexOf(c)));\n const keepsOthers = arr.elements.length > movedIdx.size;\n if (providersProp) {\n const parr = (providersProp as ts.PropertyAssignment).initializer as ts.ArrayLiteralExpression;\n if (parr.elements.length > 0) {\n edits.push({\n start: parr.elements[parr.elements.length - 1].getEnd(),\n end: parr.elements[parr.elements.length - 1].getEnd(),\n replacement: `, ${texts}`,\n });\n } else {\n edits.push({ start: parr.getStart(sf) + 1, end: parr.getEnd() - 1, replacement: texts });\n }\n if (keepsOthers) edits.push(...removeArrayElements(arr, movedIdx, sf));\n else removeObjectProperty(importsProp, sf, edits);\n } else if (!keepsOthers) {\n edits.push({ start: importsProp.getStart(sf), end: importsProp.getEnd(), replacement: `providers: [${texts}]` });\n } else {\n edits.push(...removeArrayElements(arr, movedIdx, sf));\n const multiline = source.slice(obj.getStart(sf), importsProp.getEnd()).includes('\\n');\n const indent = multiline ? /[ \\t]*$/.exec(source.slice(0, importsProp.getStart(sf)))![0] : '';\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({\n start: importsProp.getEnd(),\n end: importsProp.getEnd(),\n replacement: multiline ? `,${eol}${indent}providers: [${texts}]` : `, providers: [${texts}]`,\n });\n }\n }\n\n // remaining references to the removed module\n if (moduleName) {\n const mark = (n: ts.Node): void => {\n if (ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === moduleName && !handled.has(n) && !isPropertyName(n)) {\n flag(n, 'TranslateModule was removed in @ngx-translate/core v18. Use provideTranslateService() / provideChildTranslateService() and import TranslatePipe / TranslateDirective directly.');\n }\n ts.forEachChild(n, mark);\n };\n mark(sf);\n }\n\n // TODO comments, one line above the anchor, never duplicated\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n for (const { anchor, messages } of todos.values()) {\n const start = anchor.getStart(sf);\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1;\n const indent = /^[ \\t]*/.exec(source.slice(lineStart))![0];\n const above = new Set<string>();\n const lines = source.slice(0, lineStart).split(/\\r?\\n/);\n for (let i = lines.length - 2; i >= 0 && lines[i].trim().startsWith('// ' + TODO_PREFIX); i--) above.add(lines[i].trim());\n const fresh = messages.map((m) => `// ${TODO_PREFIX} ${m}`).filter((l) => !above.has(l));\n if (fresh.length > 0) edits.push({\n start: lineStart,\n end: lineStart,\n replacement: fresh.map((l) => `${indent}${l}${eol}`).join(''),\n });\n }\n\n let result = applyEdits(source, edits);\n if (result === source) return source;\n result = fixImports(result, filePath, CORE, needed, touched);\n if (importProvidersTouched) result = fixImports(result, filePath, '@angular/core', new Set(), new Set(['importProvidersFrom']));\n return result;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Imports\n// ---------------------------------------------------------------------------------------------------------------------\n\nconst RENAME_IN_PLACE: Record<string, string> = {\n DefaultLangChangeEvent: 'FallbackLangChangeEvent',\n setValue: 'insertValue',\n};\n\n/**\n * Drops `touched` specifiers that are no longer referenced (renaming in place when a rename is known) and\n * appends the `needed` names to the first named import of `moduleName`.\n */\nfunction fixImports(text: string, filePath: string, moduleName: string, needed: Set<string>, touched: Set<string>): string {\n const sf = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const referenced = (name: string): boolean => {\n let found = false;\n const walk = (n: ts.Node): void => {\n if (found || ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === name && !isPropertyName(n)) found = true;\n ts.forEachChild(n, walk);\n };\n walk(sf);\n return found;\n };\n\n const decls = sf.statements.filter(\n (s): s is ts.ImportDeclaration =>\n ts.isImportDeclaration(s) &&\n ts.isStringLiteral(s.moduleSpecifier) &&\n s.moduleSpecifier.text === moduleName &&\n !!s.importClause?.namedBindings &&\n ts.isNamedImports(s.importClause.namedBindings) &&\n !s.importClause.isTypeOnly\n );\n if (decls.length === 0) return text;\n\n const all = new Set<string>();\n for (const d of decls) for (const e of (d.importClause!.namedBindings as ts.NamedImports).elements) all.add(e.name.text);\n const placed = new Set<string>();\n const edits: Edit[] = [];\n const pendingNeeded = [...needed];\n\n decls.forEach((d, di) => {\n const named = d.importClause!.namedBindings as ts.NamedImports;\n const items: string[] = [];\n for (const e of named.elements) {\n const name = e.name.text;\n if (touched.has(name) && !e.propertyName && !referenced(name)) {\n const to = RENAME_IN_PLACE[name];\n if (to && needed.has(to) && !all.has(to) && !placed.has(to)) {\n items.push(to);\n placed.add(to);\n }\n continue;\n }\n items.push(e.getText(sf));\n }\n if (di === 0) {\n for (const n of pendingNeeded) if (!all.has(n) && !placed.has(n) && !items.includes(n)) items.push(n);\n }\n const before = named.elements.map((e) => e.getText(sf));\n if (items.length === before.length && items.every((v, i) => v === before[i])) return;\n if (items.length === 0 && !d.importClause!.name) {\n let end = d.getEnd();\n if (text[end] === '\\r') end++;\n if (text[end] === '\\n') end++;\n edits.push({ start: d.getStart(sf), end, replacement: '' });\n } else {\n const multiline = named.getText(sf).includes('\\n');\n const body = multiline ? `{\\n ${items.join(',\\n ')},\\n}` : `{ ${items.join(', ')} }`;\n edits.push({ start: named.getStart(sf), end: named.getEnd(), replacement: body });\n }\n });\n return applyEdits(text, edits);\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------------------------------------------------\n\nfunction isPropertyName(id: ts.Identifier): boolean {\n const p = id.parent;\n return (ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id);\n}\n\nfunction sanitize(message: string): string {\n return message.replace(/\\s+/g, ' ').trim();\n}\n\n/** Nearest ancestor that is a statement, class member or object property: the TODO goes on the line above it. */\nfunction anchorOf(node: ts.Node): ts.Node {\n let cur = node;\n while (cur.parent) {\n const p = cur.parent;\n if (ts.isSourceFile(p) || ts.isBlock(p) || ts.isModuleBlock(p) || ts.isClassLike(p) || ts.isObjectLiteralExpression(p) || ts.isCaseClause(p) || ts.isDefaultClause(p)) {\n return cur;\n }\n cur = p;\n }\n return cur;\n}\n\nconst dirOf = (p: string): string => dirname(normalize(p));\nconst resolveUrl = (dir: string, url: string): string => normalize(join(normalize(dir), url));\n\nfunction lineOf(source: string, offset: number): number {\n return source.slice(0, offset).split('\\n').length;\n}\n\nfunction shift(edits: Edit[], by: number): Edit[] {\n return edits.map((e) => ({ ...e, start: e.start + by, end: e.end + by }));\n}\n\n/** Removes one object property together with its separating comma. */\nfunction removeObjectProperty(prop: ts.ObjectLiteralElementLike, sf: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sf.getFullText();\n let start = prop.getStart(sf);\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getStart(sf);\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\n/** Removes the array elements at `indices`; non-overlapping ranges even for neighbouring elements. */\nfunction removeArrayElements(arr: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression, indices: Set<number>, sf: ts.SourceFile): Edit[] {\n const els: readonly ts.Node[] = ts.isArrayLiteralExpression(arr) ? arr.elements : arr.properties;\n const keptIdx = els.findIndex((_, i) => !indices.has(i));\n if (keptIdx === -1) return [{ start: arr.getStart(sf) + 1, end: arr.getEnd() - 1, replacement: '' }];\n const out: Edit[] = [];\n if (keptIdx > 0) out.push({ start: els[0].getStart(sf), end: els[keptIdx].getStart(sf), replacement: '' });\n for (let i = keptIdx + 1; i < els.length; i++) {\n if (indices.has(i)) out.push({ start: els[i - 1].getEnd(), end: els[i].getEnd(), replacement: '' });\n }\n return out;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const seen = new Map<string, Edit>();\n for (const e of edits) seen.set(`${e.start}:${e.end}:${e.replacement}`, e);\n let result = source;\n for (const e of [...seen.values()].sort((a, b) => b.start - a.start || b.end - a.end)) {\n result = result.slice(0, e.start) + e.replacement + result.slice(e.end);\n }\n return result;\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
5876
|
+
"sourceCode": "import { BindingType, parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit } from '../utils/todo-comment';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst OLD_CLASS = 'EuiTooltipConfig';\nconst NEW_INTERFACE = 'EuiTooltipInterface';\nconst REMOVED_ANIMATION = 'showHide';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\n\nconst RENAMED_INPUTS: Record<string, string> = {\n isPrimary: 'euiTooltipPrimary',\n isSecondary: 'euiTooltipSecondary',\n isInfo: 'euiTooltipInfo',\n isSuccess: 'euiTooltipSuccess',\n isWarning: 'euiTooltipWarning',\n isDanger: 'euiTooltipDanger',\n isAccent: 'euiTooltipAccent',\n};\n\nexport function migrateEuiTooltip(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n let result = original;\n if (path.endsWith('.html')) {\n if (!original.includes('euiTooltip')) return;\n result = migrateTemplate(original, path, context);\n } else {\n if (\n !original.includes(OLD_CLASS) &&\n !original.includes(REMOVED_ANIMATION) &&\n !original.includes('euiTooltip') &&\n !original.includes(DIRECTIVE_CLASS)\n ) {\n return;\n }\n if (original.includes(OLD_CLASS)) result = migrateTypeScript(result, path, context);\n if (result.includes(DIRECTIVE_CLASS)) result = migrateProgrammaticUsage(result, path, context);\n if (result.includes(REMOVED_ANIMATION)) result = removeShowHideAnimation(result, path, context);\n if (result.includes('euiTooltip')) result = migrateInlineTemplates(result, path, context);\n }\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-tooltip usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n fileCount++;\n }\n });\n\n context.logger.info(`Migrated eui-tooltip usages in ${fileCount} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n\n // Track if EuiTooltipInterface is already imported\n let hasInterfaceImport = false;\n let classImportDecl: ts.ImportDeclaration | null = null;\n let classImportModuleSpecifier: string | null = null;\n\n // First pass: analyze imports\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === NEW_INTERFACE) {\n hasInterfaceImport = true;\n }\n if (specifier.name.text === OLD_CLASS) {\n classImportDecl = stmt;\n classImportModuleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n }\n }\n }\n\n // Second pass: handle import declarations\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n const specifiers = namedBindings.elements;\n const classSpecifier = specifiers.find((s) => s.name.text === OLD_CLASS);\n if (!classSpecifier) continue;\n\n if (hasInterfaceImport) {\n // EuiTooltipInterface is already imported elsewhere → remove EuiTooltipConfig from this import\n removeImportSpecifier(namedBindings, classSpecifier, sourceFile, edits);\n } else {\n // Rename EuiTooltipConfig → EuiTooltipInterface in the import\n edits.push({\n start: classSpecifier.name.getStart(sourceFile),\n end: classSpecifier.name.getEnd(),\n replacement: NEW_INTERFACE,\n });\n hasInterfaceImport = true;\n }\n }\n\n // Third pass: replace `new EuiTooltipConfig(...)` → spread/cast to interface\n const visitNewExpressions = (node: ts.Node): void => {\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) {\n const args = node.arguments;\n if (args !== undefined && args.length === 1) {\n const arg = args[0];\n // `new EuiTooltipConfig({ ... })` → `{ ... } as EuiTooltipInterface`\n // But if the argument is just a variable, we keep it: `varName as EuiTooltipInterface`\n const argText = source.slice(arg.getStart(sourceFile), arg.getEnd());\n\n if (ts.isObjectLiteralExpression(arg)) {\n // Inline object: `new EuiTooltipConfig({ x: 1 })` → `{ x: 1 }`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n } else {\n // Variable or expression: `new EuiTooltipConfig(opts)` → `opts`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n }\n } else if (args === undefined || args.length === 0) {\n // `new EuiTooltipConfig()` → `{} as EuiTooltipInterface`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: `{} as ${NEW_INTERFACE}`,\n });\n }\n return; // don't recurse into children we've already replaced\n }\n ts.forEachChild(node, visitNewExpressions);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitNewExpressions(stmt);\n }\n }\n\n // Fourth pass: rename all remaining identifier references (type annotations, etc.)\n const visitRefs = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n // Skip nodes we already covered in new expressions\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) return;\n\n if (ts.isIdentifier(node) && node.text === OLD_CLASS) {\n // Ensure this is not part of an import declaration\n if (!isPartOfImport(node)) {\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: NEW_INTERFACE,\n });\n }\n }\n ts.forEachChild(node, visitRefs);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitRefs(stmt);\n }\n }\n\n return applyEdits(source, edits);\n}\n\n/** Removes the `showHide` animation (import + `animations: [...]` entries) imported from an @eui package. */\nfunction removeShowHideAnimation(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue;\n if (!stmt.moduleSpecifier.text.startsWith('@eui/')) continue;\n const named = stmt.importClause?.namedBindings;\n if (!named || !ts.isNamedImports(named)) continue;\n const spec = named.elements.find((e) => e.name.text === REMOVED_ANIMATION && !e.propertyName);\n if (!spec) continue;\n found = true;\n removeImportSpecifier(named, spec, sourceFile, edits);\n }\n if (!found) return source;\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'animations' &&\n ts.isArrayLiteralExpression(node.initializer)\n ) {\n const arr = node.initializer;\n const kept = arr.elements.filter((e) => !(ts.isIdentifier(e) && e.text === REMOVED_ANIMATION));\n if (kept.length !== arr.elements.length) {\n if (kept.length === 0) {\n removeObjectProperty(node, sourceFile, edits);\n } else {\n edits.push({\n start: arr.getStart(sourceFile) + 1,\n end: arr.getEnd() - 1,\n replacement: kept.map((e) => e.getText(sourceFile)).join(', '),\n });\n }\n }\n } else if (ts.isIdentifier(node) && node.text === REMOVED_ANIMATION && !isPartOfImport(node) && !isInRemovedArray(node)) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n context.logger.warn(`${filePath}:${line + 1} - Manual action needed: the \"showHide\" animation has been removed from @eui/components.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction isInRemovedArray(node: ts.Node): boolean {\n const parent = node.parent;\n return (\n !!parent &&\n ts.isArrayLiteralExpression(parent) &&\n ts.isPropertyAssignment(parent.parent) &&\n ts.isIdentifier(parent.parent.name) &&\n parent.parent.name.text === 'animations'\n );\n}\n\nfunction removeObjectProperty(prop: ts.PropertyAssignment, sourceFile: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sourceFile.getFullText();\n let start = prop.getFullStart();\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getFullStart();\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\nfunction migrateInlineTemplates(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'template' &&\n (ts.isNoSubstitutionTemplateLiteral(node.initializer) || ts.isStringLiteral(node.initializer))\n ) {\n const lit = node.initializer;\n const start = lit.getStart(sourceFile) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (raw.includes('euiTooltip')) {\n const migrated = migrateTemplate(raw, filePath, context);\n if (migrated !== raw) edits.push({ start, end: lit.getEnd() - 1, replacement: migrated });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction migrateTemplate(source: string, filePath: string, context: SchematicContext): string {\n const parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n const edits: Edit[] = [];\n visitNodes(parsed.nodes, source, filePath, context, edits);\n return applyEdits(source, edits);\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n forEachElement(nodes, (node) => collectElementEdits(node, source, filePath, context, edits));\n}\n\nfunction collectElementEdits(el: TmplAstElement, source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n const tooltipAttr = el.attributes.find((a) => a.name === 'euiTooltip');\n const tooltipInput = el.inputs.find((i) => i.name === 'euiTooltip' && i.type === BindingType.Property);\n if (!tooltipAttr && !tooltipInput) return;\n\n // All messages of one element are merged into ONE comment: several TODOs would be inserted at the\n // same offset and overwrite each other.\n const messages: string[] = [];\n const warn = (offset: number, message: string): void => {\n messages.push(message);\n const { line } = lineOf(source, offset);\n context.logger.warn(`${filePath}:${line} - Manual action needed on <${el.name}>: ${message}`);\n };\n\n for (const attr of el.attributes) {\n if (RENAMED_INPUTS[attr.name]) {\n edits.push({ start: attr.keySpan!.start.offset, end: attr.keySpan!.end.offset, replacement: RENAMED_INPUTS[attr.name] });\n }\n }\n for (const input of el.inputs) {\n if (input.type === BindingType.Property && RENAMED_INPUTS[input.name]) {\n edits.push({ start: input.keySpan!.start.offset, end: input.keySpan!.end.offset, replacement: RENAMED_INPUTS[input.name] });\n }\n }\n\n // `position`: the migration guide lists it as removed, but EuiTooltipDirective still declares it\n // (model()). Deleting it would silently change behavior, so it is kept and flagged.\n const position = [\n ...el.attributes.filter((a) => a.name === 'position'),\n ...el.inputs.filter((i) => i.type === BindingType.Property && i.name === 'position'),\n ][0];\n if (position) {\n warn(\n position.sourceSpan.start.offset,\n 'input position of euiTooltip is documented as removed in eUI v22 but is still declared by EuiTooltipDirective. It was kept unchanged; verify it against the version you upgrade to.',\n );\n }\n\n const config = el.inputs.find((i) => i.type === BindingType.Property && i.name === 'config');\n if (config) {\n warn(\n config.sourceSpan.start.offset,\n 'input config of euiTooltip has been removed. Use the individual inputs (euiTooltip, euiTooltipPrimary, showDelay, hideDelay, contentAlignment, isDisabled) instead.',\n );\n }\n\n if (tooltipAttr && !tooltipAttr.value && !tooltipInput) {\n warn(tooltipAttr.sourceSpan.start.offset, 'input euiTooltip is now required and needs a value, e.g. euiTooltip=\"My tooltip\".');\n }\n\n if (messages.length > 0) {\n const todo = createTodoEdit(source, el.startSourceSpan.start.offset, messages.join(' '));\n if (todo) edits.push(todo);\n }\n}\n\n/**\n * Programmatic usage of a `EuiTooltipDirective` reference (`tt.isPrimary = true`, `tt.config`).\n * Renamed flags are renamed; `config` cannot be migrated and is flagged. Name based, scope aware for\n * parameters/variables (a differently typed parameter with the same name is left alone).\n * shortcut: only `this.x` and locals/params typed `EuiTooltipDirective` are followed; aliases are not.\n */\nfunction migrateProgrammaticUsage(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const isTyped = (t: ts.TypeNode | undefined): boolean =>\n !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === DIRECTIVE_CLASS;\n const isViewChildOf = (n: ts.PropertyDeclaration): boolean =>\n (ts.getDecorators?.(n) ?? []).some(\n (d) =>\n ts.isCallExpression(d.expression) &&\n ['ViewChild', 'ContentChild'].includes(d.expression.expression.getText(sourceFile)) &&\n d.expression.arguments[0]?.getText(sourceFile) === DIRECTIVE_CLASS,\n );\n\n const props = new Set<string>();\n const collect = (n: ts.Node): void => {\n if (ts.isPropertyDeclaration(n) && ts.isIdentifier(n.name) && (isTyped(n.type) || isViewChildOf(n))) props.add(n.name.text);\n ts.forEachChild(n, collect);\n };\n collect(sourceFile);\n\n /** Nearest declaration of a bare identifier: true = typed directive, false = something else, undefined = none found. */\n const bareIsDirective = (id: ts.Identifier): boolean | undefined => {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return isTyped(d.type);\n }\n return undefined;\n };\n\n const visit = (n: ts.Node): void => {\n if (ts.isPropertyAccessExpression(n) && (RENAMED_INPUTS[n.name.text] || n.name.text === 'config')) {\n const target = n.expression;\n const tracked =\n (ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword && props.has(target.name.text)) ||\n (ts.isIdentifier(target) && bareIsDirective(target) === true);\n if (tracked) {\n if (RENAMED_INPUTS[n.name.text]) {\n edits.push({ start: n.name.getStart(sourceFile), end: n.name.getEnd(), replacement: RENAMED_INPUTS[n.name.text] });\n } else {\n const { line } = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));\n context.logger.warn(\n `${filePath}:${line + 1} - Manual action needed: the \"config\" input of EuiTooltipDirective has been removed. Use the individual inputs instead.`,\n );\n }\n }\n }\n ts.forEachChild(n, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction lineOf(source: string, offset: number): { line: number } {\n return { line: source.slice(0, offset).split('\\n').length };\n}\n\nfunction isPartOfImport(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current) {\n if (ts.isImportDeclaration(current)) return true;\n current = current.parent;\n }\n return false;\n}\n\nfunction removeImportSpecifier(\n namedImports: ts.NamedImports,\n specifier: ts.ImportSpecifier,\n sourceFile: ts.SourceFile,\n edits: Edit[],\n): void {\n const elements = namedImports.elements;\n if (elements.length === 1) {\n // Remove the entire import declaration\n const importDecl = namedImports.parent.parent;\n let end = importDecl.getEnd();\n // Also remove trailing newline if present\n const fullText = sourceFile.getFullText();\n if (fullText[end] === '\\n') end++;\n edits.push({\n start: importDecl.getStart(sourceFile),\n end,\n replacement: '',\n });\n } else {\n // Remove just this specifier with surrounding comma/whitespace\n const idx = elements.indexOf(specifier);\n let start: number;\n let end: number;\n if (idx < elements.length - 1) {\n // Not the last → remove from this specifier start to next specifier start\n start = specifier.getStart(sourceFile);\n end = elements[idx + 1].getStart(sourceFile);\n } else {\n // Last element → remove from previous element end to this end\n start = elements[idx - 1].getEnd();\n end = specifier.getEnd();\n }\n edits.push({ start, end, replacement: '' });\n }\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n for (const edit of unique.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
5877
5877
|
"displayName": "Schema",
|
|
5878
5878
|
"properties": [
|
|
5879
5879
|
{
|
|
@@ -5885,7 +5885,7 @@
|
|
|
5885
5885
|
"indexKey": "",
|
|
5886
5886
|
"optional": true,
|
|
5887
5887
|
"description": "",
|
|
5888
|
-
"line":
|
|
5888
|
+
"line": 10,
|
|
5889
5889
|
"rawdescription": "\n"
|
|
5890
5890
|
},
|
|
5891
5891
|
{
|
|
@@ -5897,14 +5897,12 @@
|
|
|
5897
5897
|
"indexKey": "",
|
|
5898
5898
|
"optional": true,
|
|
5899
5899
|
"description": "",
|
|
5900
|
-
"line":
|
|
5900
|
+
"line": 9,
|
|
5901
5901
|
"rawdescription": "\n"
|
|
5902
5902
|
}
|
|
5903
5903
|
],
|
|
5904
5904
|
"indexSignatures": [],
|
|
5905
5905
|
"kind": 172,
|
|
5906
|
-
"description": "<p>Migrates @ngx-translate/core v17 -> v18 breaking changes.</p>\n<p>No type checker is used: a <code>TranslateService</code> receiver is resolved from its declaration in the same\nfile (<code>: TranslateService</code>, <code>inject(TranslateService)</code>, constructor parameter properties) and, for\ntemplates, from the component class that owns the template.\nshortcut: receivers that are aliased, destructured, passed through other types or declared in another\nfile are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.</p>\n",
|
|
5907
|
-
"rawdescription": "\n\nMigrates @ngx-translate/core v17 -> v18 breaking changes.\n\nNo type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\nfile (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\ntemplates, from the component class that owns the template.\nshortcut: receivers that are aliased, destructured, passed through other types or declared in another\nfile are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n",
|
|
5908
5906
|
"methods": [],
|
|
5909
5907
|
"extends": [],
|
|
5910
5908
|
"isDuplicate": true,
|
|
@@ -5917,12 +5915,12 @@
|
|
|
5917
5915
|
},
|
|
5918
5916
|
{
|
|
5919
5917
|
"name": "Schema",
|
|
5920
|
-
"id": "interface-Schema-
|
|
5921
|
-
"file": "packages/core/schematics/migrate-
|
|
5918
|
+
"id": "interface-Schema-85d506677a88d24ac5314a45baa87ebcf9819f4d8375ebff75fd7dd3eb56602606744787c8eaa07b0049a17bfeb30b2ad99fb4b760709d0c66b30365ae949899-41",
|
|
5919
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
5922
5920
|
"deprecated": false,
|
|
5923
5921
|
"deprecationMessage": "",
|
|
5924
5922
|
"type": "interface",
|
|
5925
|
-
"sourceCode": "import { BindingType, parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit } from '../utils/todo-comment';\nimport { forEachElement } from '../utils/template-walk';\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst OLD_CLASS = 'EuiTooltipConfig';\nconst NEW_INTERFACE = 'EuiTooltipInterface';\nconst REMOVED_ANIMATION = 'showHide';\nconst DIRECTIVE_CLASS = 'EuiTooltipDirective';\n\nconst RENAMED_INPUTS: Record<string, string> = {\n isPrimary: 'euiTooltipPrimary',\n isSecondary: 'euiTooltipSecondary',\n isInfo: 'euiTooltipInfo',\n isSuccess: 'euiTooltipSuccess',\n isWarning: 'euiTooltipWarning',\n isDanger: 'euiTooltipDanger',\n isAccent: 'euiTooltipAccent',\n};\n\nexport function migrateEuiTooltip(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n let result = original;\n if (path.endsWith('.html')) {\n if (!original.includes('euiTooltip')) return;\n result = migrateTemplate(original, path, context);\n } else {\n if (\n !original.includes(OLD_CLASS) &&\n !original.includes(REMOVED_ANIMATION) &&\n !original.includes('euiTooltip') &&\n !original.includes(DIRECTIVE_CLASS)\n ) {\n return;\n }\n if (original.includes(OLD_CLASS)) result = migrateTypeScript(result, path, context);\n if (result.includes(DIRECTIVE_CLASS)) result = migrateProgrammaticUsage(result, path, context);\n if (result.includes(REMOVED_ANIMATION)) result = removeShowHideAnimation(result, path, context);\n if (result.includes('euiTooltip')) result = migrateInlineTemplates(result, path, context);\n }\n\n if (result !== original) {\n if (options.dryRun) {\n logDryRun(context, `Would migrate eui-tooltip usages in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n fileCount++;\n }\n });\n\n context.logger.info(`Migrated eui-tooltip usages in ${fileCount} file(s).`);\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n\n // Track if EuiTooltipInterface is already imported\n let hasInterfaceImport = false;\n let classImportDecl: ts.ImportDeclaration | null = null;\n let classImportModuleSpecifier: string | null = null;\n\n // First pass: analyze imports\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n for (const specifier of namedBindings.elements) {\n if (specifier.name.text === NEW_INTERFACE) {\n hasInterfaceImport = true;\n }\n if (specifier.name.text === OLD_CLASS) {\n classImportDecl = stmt;\n classImportModuleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n }\n }\n }\n\n // Second pass: handle import declarations\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const namedBindings = stmt.importClause?.namedBindings;\n if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;\n\n const specifiers = namedBindings.elements;\n const classSpecifier = specifiers.find((s) => s.name.text === OLD_CLASS);\n if (!classSpecifier) continue;\n\n if (hasInterfaceImport) {\n // EuiTooltipInterface is already imported elsewhere → remove EuiTooltipConfig from this import\n removeImportSpecifier(namedBindings, classSpecifier, sourceFile, edits);\n } else {\n // Rename EuiTooltipConfig → EuiTooltipInterface in the import\n edits.push({\n start: classSpecifier.name.getStart(sourceFile),\n end: classSpecifier.name.getEnd(),\n replacement: NEW_INTERFACE,\n });\n hasInterfaceImport = true;\n }\n }\n\n // Third pass: replace `new EuiTooltipConfig(...)` → spread/cast to interface\n const visitNewExpressions = (node: ts.Node): void => {\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) {\n const args = node.arguments;\n if (args !== undefined && args.length === 1) {\n const arg = args[0];\n // `new EuiTooltipConfig({ ... })` → `{ ... } as EuiTooltipInterface`\n // But if the argument is just a variable, we keep it: `varName as EuiTooltipInterface`\n const argText = source.slice(arg.getStart(sourceFile), arg.getEnd());\n\n if (ts.isObjectLiteralExpression(arg)) {\n // Inline object: `new EuiTooltipConfig({ x: 1 })` → `{ x: 1 }`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n } else {\n // Variable or expression: `new EuiTooltipConfig(opts)` → `opts`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: argText,\n });\n }\n } else if (args === undefined || args.length === 0) {\n // `new EuiTooltipConfig()` → `{} as EuiTooltipInterface`\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: `{} as ${NEW_INTERFACE}`,\n });\n }\n return; // don't recurse into children we've already replaced\n }\n ts.forEachChild(node, visitNewExpressions);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitNewExpressions(stmt);\n }\n }\n\n // Fourth pass: rename all remaining identifier references (type annotations, etc.)\n const visitRefs = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n // Skip nodes we already covered in new expressions\n if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === OLD_CLASS) return;\n\n if (ts.isIdentifier(node) && node.text === OLD_CLASS) {\n // Ensure this is not part of an import declaration\n if (!isPartOfImport(node)) {\n edits.push({\n start: node.getStart(sourceFile),\n end: node.getEnd(),\n replacement: NEW_INTERFACE,\n });\n }\n }\n ts.forEachChild(node, visitRefs);\n };\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) {\n visitRefs(stmt);\n }\n }\n\n return applyEdits(source, edits);\n}\n\n/** Removes the `showHide` animation (import + `animations: [...]` entries) imported from an @eui package. */\nfunction removeShowHideAnimation(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n let found = false;\n\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue;\n if (!stmt.moduleSpecifier.text.startsWith('@eui/')) continue;\n const named = stmt.importClause?.namedBindings;\n if (!named || !ts.isNamedImports(named)) continue;\n const spec = named.elements.find((e) => e.name.text === REMOVED_ANIMATION && !e.propertyName);\n if (!spec) continue;\n found = true;\n removeImportSpecifier(named, spec, sourceFile, edits);\n }\n if (!found) return source;\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'animations' &&\n ts.isArrayLiteralExpression(node.initializer)\n ) {\n const arr = node.initializer;\n const kept = arr.elements.filter((e) => !(ts.isIdentifier(e) && e.text === REMOVED_ANIMATION));\n if (kept.length !== arr.elements.length) {\n if (kept.length === 0) {\n removeObjectProperty(node, sourceFile, edits);\n } else {\n edits.push({\n start: arr.getStart(sourceFile) + 1,\n end: arr.getEnd() - 1,\n replacement: kept.map((e) => e.getText(sourceFile)).join(', '),\n });\n }\n }\n } else if (ts.isIdentifier(node) && node.text === REMOVED_ANIMATION && !isPartOfImport(node) && !isInRemovedArray(node)) {\n const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n context.logger.warn(`${filePath}:${line + 1} - Manual action needed: the \"showHide\" animation has been removed from @eui/components.`);\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction isInRemovedArray(node: ts.Node): boolean {\n const parent = node.parent;\n return (\n !!parent &&\n ts.isArrayLiteralExpression(parent) &&\n ts.isPropertyAssignment(parent.parent) &&\n ts.isIdentifier(parent.parent.name) &&\n parent.parent.name.text === 'animations'\n );\n}\n\nfunction removeObjectProperty(prop: ts.PropertyAssignment, sourceFile: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sourceFile.getFullText();\n let start = prop.getFullStart();\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getFullStart();\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\nfunction migrateInlineTemplates(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAssignment(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === 'template' &&\n (ts.isNoSubstitutionTemplateLiteral(node.initializer) || ts.isStringLiteral(node.initializer))\n ) {\n const lit = node.initializer;\n const start = lit.getStart(sourceFile) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (raw.includes('euiTooltip')) {\n const migrated = migrateTemplate(raw, filePath, context);\n if (migrated !== raw) edits.push({ start, end: lit.getEnd() - 1, replacement: migrated });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction migrateTemplate(source: string, filePath: string, context: SchematicContext): string {\n const parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n const edits: Edit[] = [];\n visitNodes(parsed.nodes, source, filePath, context, edits);\n return applyEdits(source, edits);\n}\n\nfunction visitNodes(nodes: TmplAstNode[], source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n forEachElement(nodes, (node) => collectElementEdits(node, source, filePath, context, edits));\n}\n\nfunction collectElementEdits(el: TmplAstElement, source: string, filePath: string, context: SchematicContext, edits: Edit[]): void {\n const tooltipAttr = el.attributes.find((a) => a.name === 'euiTooltip');\n const tooltipInput = el.inputs.find((i) => i.name === 'euiTooltip' && i.type === BindingType.Property);\n if (!tooltipAttr && !tooltipInput) return;\n\n // All messages of one element are merged into ONE comment: several TODOs would be inserted at the\n // same offset and overwrite each other.\n const messages: string[] = [];\n const warn = (offset: number, message: string): void => {\n messages.push(message);\n const { line } = lineOf(source, offset);\n context.logger.warn(`${filePath}:${line} - Manual action needed on <${el.name}>: ${message}`);\n };\n\n for (const attr of el.attributes) {\n if (RENAMED_INPUTS[attr.name]) {\n edits.push({ start: attr.keySpan!.start.offset, end: attr.keySpan!.end.offset, replacement: RENAMED_INPUTS[attr.name] });\n }\n }\n for (const input of el.inputs) {\n if (input.type === BindingType.Property && RENAMED_INPUTS[input.name]) {\n edits.push({ start: input.keySpan!.start.offset, end: input.keySpan!.end.offset, replacement: RENAMED_INPUTS[input.name] });\n }\n }\n\n // `position`: the migration guide lists it as removed, but EuiTooltipDirective still declares it\n // (model()). Deleting it would silently change behavior, so it is kept and flagged.\n const position = [\n ...el.attributes.filter((a) => a.name === 'position'),\n ...el.inputs.filter((i) => i.type === BindingType.Property && i.name === 'position'),\n ][0];\n if (position) {\n warn(\n position.sourceSpan.start.offset,\n 'input position of euiTooltip is documented as removed in eUI v22 but is still declared by EuiTooltipDirective. It was kept unchanged; verify it against the version you upgrade to.',\n );\n }\n\n const config = el.inputs.find((i) => i.type === BindingType.Property && i.name === 'config');\n if (config) {\n warn(\n config.sourceSpan.start.offset,\n 'input config of euiTooltip has been removed. Use the individual inputs (euiTooltip, euiTooltipPrimary, showDelay, hideDelay, contentAlignment, isDisabled) instead.',\n );\n }\n\n if (tooltipAttr && !tooltipAttr.value && !tooltipInput) {\n warn(tooltipAttr.sourceSpan.start.offset, 'input euiTooltip is now required and needs a value, e.g. euiTooltip=\"My tooltip\".');\n }\n\n if (messages.length > 0) {\n const todo = createTodoEdit(source, el.startSourceSpan.start.offset, messages.join(' '));\n if (todo) edits.push(todo);\n }\n}\n\n/**\n * Programmatic usage of a `EuiTooltipDirective` reference (`tt.isPrimary = true`, `tt.config`).\n * Renamed flags are renamed; `config` cannot be migrated and is flagged. Name based, scope aware for\n * parameters/variables (a differently typed parameter with the same name is left alone).\n * shortcut: only `this.x` and locals/params typed `EuiTooltipDirective` are followed; aliases are not.\n */\nfunction migrateProgrammaticUsage(source: string, filePath: string, context: SchematicContext): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const isTyped = (t: ts.TypeNode | undefined): boolean =>\n !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === DIRECTIVE_CLASS;\n const isViewChildOf = (n: ts.PropertyDeclaration): boolean =>\n (ts.getDecorators?.(n) ?? []).some(\n (d) =>\n ts.isCallExpression(d.expression) &&\n ['ViewChild', 'ContentChild'].includes(d.expression.expression.getText(sourceFile)) &&\n d.expression.arguments[0]?.getText(sourceFile) === DIRECTIVE_CLASS,\n );\n\n const props = new Set<string>();\n const collect = (n: ts.Node): void => {\n if (ts.isPropertyDeclaration(n) && ts.isIdentifier(n.name) && (isTyped(n.type) || isViewChildOf(n))) props.add(n.name.text);\n ts.forEachChild(n, collect);\n };\n collect(sourceFile);\n\n /** Nearest declaration of a bare identifier: true = typed directive, false = something else, undefined = none found. */\n const bareIsDirective = (id: ts.Identifier): boolean | undefined => {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return isTyped(d.type);\n }\n return undefined;\n };\n\n const visit = (n: ts.Node): void => {\n if (ts.isPropertyAccessExpression(n) && (RENAMED_INPUTS[n.name.text] || n.name.text === 'config')) {\n const target = n.expression;\n const tracked =\n (ts.isPropertyAccessExpression(target) && target.expression.kind === ts.SyntaxKind.ThisKeyword && props.has(target.name.text)) ||\n (ts.isIdentifier(target) && bareIsDirective(target) === true);\n if (tracked) {\n if (RENAMED_INPUTS[n.name.text]) {\n edits.push({ start: n.name.getStart(sourceFile), end: n.name.getEnd(), replacement: RENAMED_INPUTS[n.name.text] });\n } else {\n const { line } = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));\n context.logger.warn(\n `${filePath}:${line + 1} - Manual action needed: the \"config\" input of EuiTooltipDirective has been removed. Use the individual inputs instead.`,\n );\n }\n }\n }\n ts.forEachChild(n, visit);\n };\n visit(sourceFile);\n return applyEdits(source, edits);\n}\n\nfunction lineOf(source: string, offset: number): { line: number } {\n return { line: source.slice(0, offset).split('\\n').length };\n}\n\nfunction isPartOfImport(node: ts.Node): boolean {\n let current: ts.Node | undefined = node.parent;\n while (current) {\n if (ts.isImportDeclaration(current)) return true;\n current = current.parent;\n }\n return false;\n}\n\nfunction removeImportSpecifier(\n namedImports: ts.NamedImports,\n specifier: ts.ImportSpecifier,\n sourceFile: ts.SourceFile,\n edits: Edit[],\n): void {\n const elements = namedImports.elements;\n if (elements.length === 1) {\n // Remove the entire import declaration\n const importDecl = namedImports.parent.parent;\n let end = importDecl.getEnd();\n // Also remove trailing newline if present\n const fullText = sourceFile.getFullText();\n if (fullText[end] === '\\n') end++;\n edits.push({\n start: importDecl.getStart(sourceFile),\n end,\n replacement: '',\n });\n } else {\n // Remove just this specifier with surrounding comma/whitespace\n const idx = elements.indexOf(specifier);\n let start: number;\n let end: number;\n if (idx < elements.length - 1) {\n // Not the last → remove from this specifier start to next specifier start\n start = specifier.getStart(sourceFile);\n end = elements[idx + 1].getStart(sourceFile);\n } else {\n // Last element → remove from previous element end to this end\n start = elements[idx - 1].getEnd();\n end = specifier.getEnd();\n }\n edits.push({ start, end, replacement: '' });\n }\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n for (const edit of unique.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
5923
|
+
"sourceCode": "import {\n Binary,\n BindingPipe,\n BindingType,\n CombinedRecursiveAstVisitor,\n ImplicitReceiver,\n parseTemplate,\n PropertyRead,\n SafePropertyRead,\n TmplAstElement,\n TmplAstText,\n} from '@angular/compiler';\nimport { dirname, join, normalize } from '@angular-devkit/core';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport { createTodoEdit, TODO_PREFIX } from '../utils/todo-comment';\n\n/**\n * Migrates @ngx-translate/core v17 -> v18 breaking changes.\n *\n * No type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\n * file (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\n * templates, from the component class that owns the template.\n * shortcut: receivers that are aliased, destructured, passed through other types or declared in another\n * file are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n */\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n}\n\nconst CORE = '@ngx-translate/core';\nconst HTTP_LOADER = '@ngx-translate/http-loader';\n\nconst TOKEN_PROVIDERS: Record<string, string> = {\n TranslateLoader: 'provideTranslateLoader',\n TranslateCompiler: 'provideTranslateCompiler',\n TranslateParser: 'provideTranslateParser',\n MissingTranslationHandler: 'provideMissingTranslationHandler',\n};\nconst PLUGIN_KEYS = ['loader', 'compiler', 'parser', 'missingTranslationHandler'];\nconst MEMBER_RENAMES: Record<string, string> = {\n setDefaultLang: 'setFallbackLang',\n getDefaultLang: 'getFallbackLang',\n onDefaultLangChange: 'onFallbackLangChange',\n};\nconst ASSIGN_OPS = new Set<ts.SyntaxKind>([\n ts.SyntaxKind.EqualsToken,\n ts.SyntaxKind.PlusEqualsToken,\n ts.SyntaxKind.MinusEqualsToken,\n ts.SyntaxKind.QuestionQuestionEqualsToken,\n ts.SyntaxKind.BarBarEqualsToken,\n ts.SyntaxKind.AmpersandAmpersandEqualsToken,\n]);\n\nexport function migrateNgxTranslate18(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const tsFiles: string[] = [];\n const htmlFiles: string[] = [];\n visitDir(tree.getDir(scanPath || '/'), (path) => (path.endsWith('.html') ? htmlFiles : tsFiles).push(path));\n\n const projectUsesNgx = tsFiles.some((f) => tree.read(f)?.toString('utf-8').includes(CORE));\n const read = (p: string): string | undefined => tree.read(p)?.toString('utf-8');\n // forChild({ extend: true }) services merge translations; setTranslation(lang, t) callers need a review then.\n const projectHasExtend = tsFiles.some((f) => {\n const s = read(f);\n return !!s && s.includes('forChild') && /extend\\s*:\\s*true/.test(s);\n });\n\n let fileCount = 0;\n const write = (path: string, original: string, result: string): void => {\n if (result === original) return;\n if (options.dryRun) logDryRun(context, `Would migrate @ngx-translate/core usages in ${path}`);\n else tree.overwrite(path, result);\n fileCount++;\n };\n\n for (const path of tsFiles) {\n const original = read(path);\n if (!original) continue;\n const hasCore = original.includes(CORE) || original.includes(HTTP_LOADER);\n if (!hasCore && !(original.includes('template') && original.includes('translate'))) continue;\n write(path, original, migrateTypeScript(original, path, context, { projectHasExtend, projectUsesNgx, read }));\n }\n\n for (const path of htmlFiles) {\n const original = read(path);\n if (!original || !/translate|currentLang/.test(original)) continue;\n const members = membersForExternalTemplate(path, tsFiles, read);\n const scan = scanTemplate(original, path, context, {\n members,\n allowKeyRewrite: true,\n checkAttributes: projectUsesNgx,\n where: (o) => `${path}:${lineOf(original, o)}`,\n });\n write(path, original, applyEdits(original, scan.edits));\n }\n\n context.logger.info(`Migrated @ngx-translate/core usages in ${fileCount} file(s).`);\n if (options.dryRun) logDryRunNote(context);\n return tree;\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Templates\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TemplateScan {\n edits: Edit[];\n usage: { pipe: boolean; directive: boolean };\n}\n\nfunction scanTemplate(\n source: string,\n filePath: string,\n context: SchematicContext,\n opts: {\n members: Set<string>;\n allowKeyRewrite: boolean;\n checkAttributes?: boolean;\n where: (offset: number) => string;\n quiet?: boolean\n }\n): TemplateScan {\n const result: TemplateScan = { edits: [], usage: { pipe: false, directive: false } };\n let parsed;\n try {\n parsed = parseTemplate(source, filePath, { preserveWhitespaces: true });\n } catch {\n return result;\n }\n if (parsed.errors && parsed.errors.length > 0) return result;\n\n const seenWarnings = new Set<string>();\n const warn = (offset: number, message: string): void => {\n const text = `${opts.where(offset)} - Manual action needed: ${message}`;\n if (opts.quiet || seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const writes = new Set<unknown>();\n const isSvc = (r: unknown): boolean =>\n r instanceof PropertyRead && r.receiver instanceof ImplicitReceiver && opts.members.has(r.name);\n\n const visitor = new (class extends CombinedRecursiveAstVisitor {\n override visitBinary(ast: Binary, context: unknown): void {\n if (ast.operation.endsWith('=') && !['==', '===', '!=', '!==', '<=', '>='].includes(ast.operation)) {\n const left = ast.left;\n if ((left instanceof PropertyRead || left instanceof SafePropertyRead) && left.name === 'currentLang' && isSvc(left.receiver)) {\n writes.add(left);\n warn(left.sourceSpan.start, 'TranslateService.currentLang is a read-only Signal in @ngx-translate/core v18; use translate.use(lang) instead of assigning it.');\n }\n }\n super.visitBinary(ast, context);\n }\n\n override visitPropertyRead(ast: PropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitPropertyRead(ast, context);\n }\n\n override visitSafePropertyRead(ast: SafePropertyRead, context: unknown): void {\n this.rewriteCurrentLang(ast);\n super.visitSafePropertyRead(ast, context);\n }\n\n override visitPipe(ast: BindingPipe, context: unknown): void {\n if (ast.name === 'translate') result.usage.pipe = true;\n super.visitPipe(ast, context);\n }\n\n override visitElement(el: TmplAstElement): void {\n this.checkTranslateAttribute(el);\n super.visitElement(el);\n }\n\n override visitTemplate(t: Parameters<CombinedRecursiveAstVisitor['visitTemplate']>[0]): void {\n if (\n [...t.attributes, ...t.inputs, ...t.templateAttrs].some((a) => a.name === 'translate' || a.name === 'ngx-translate')\n ) {\n result.usage.directive = true;\n }\n super.visitTemplate(t);\n }\n\n private rewriteCurrentLang(ast: PropertyRead | SafePropertyRead): void {\n if (ast.name !== 'currentLang' || writes.has(ast) || !isSvc(ast.receiver)) return;\n const end = ast.nameSpan.end;\n if (/^\\s*\\(/.test(source.slice(end))) return; // already a call\n result.edits.push({ start: end, end, replacement: '()' });\n }\n\n private checkTranslateAttribute(el: TmplAstElement): void {\n if (opts.checkAttributes === false) return;\n const textAttr = el.attributes.find((a) => a.name === 'translate' || a.name === 'ngx-translate');\n const bound = el.inputs.find((i) => i.name === 'translate' && i.type === BindingType.Property);\n if (textAttr || bound) result.usage.directive = true;\n const at = el.startSourceSpan.start.offset;\n const todo = (message: string): void => {\n warn(at, `<${el.name}> ${message}`);\n const edit = createTodoEdit(source, at, message);\n if (edit) result.edits.push(edit);\n };\n\n // 7: [translate]=\"'KEY'\" now sets textContent: element children are overwritten.\n if (bound && el.children.some((c) => !(c instanceof TmplAstText))) {\n todo(\n 'with [translate] the element content is replaced by the translation (textContent) in @ngx-translate/core v18, child elements are lost. Restructure the markup.'\n );\n return;\n }\n\n // 8: <el translate>KEY</el> (text as key) is deprecated.\n if (!textAttr || textAttr.name !== 'translate' || textAttr.value !== '' || bound) return;\n const meaningful = el.children.filter((c) => !(c instanceof TmplAstText && c.value.trim() === ''));\n if (meaningful.length === 0) return;\n const only = meaningful[0];\n const isPlain =\n meaningful.length === 1 &&\n el.children.length === 1 &&\n only instanceof TmplAstText &&\n !!el.endSourceSpan &&\n source.slice(el.startSourceSpan.end.offset, el.endSourceSpan.start.offset) === only.value &&\n !/[\"'`&<>{}\\\\]/.test(only.value);\n if (!isPlain) {\n todo(\n 'uses its text content as translation key, which is deprecated and not safely convertible here (interpolation or nested elements). Use [translate]=\"\\'KEY\\'\", the translate pipe or *translateBlock.'\n );\n return;\n }\n if (!opts.allowKeyRewrite) {\n warn(at, `<${el.name}> text as translation key is deprecated; replace with [translate]=\"'KEY'\" (not rewritten inside a quoted inline template).`);\n return;\n }\n const key = (only as TmplAstText).value.trim();\n result.edits.push({\n start: textAttr.sourceSpan.start.offset,\n end: textAttr.sourceSpan.end.offset,\n replacement: `[translate]=\"'${key}'\"`,\n });\n result.edits.push({ start: el.startSourceSpan.end.offset, end: el.endSourceSpan!.start.offset, replacement: '' });\n }\n })();\n\n for (const node of parsed.nodes) visitor.visit(node);\n return result;\n}\n\n/** Members typed/injected as TranslateService of the component whose templateUrl points at `htmlPath`. */\nfunction membersForExternalTemplate(htmlPath: string, tsFiles: string[], read: (p: string) => string | undefined): Set<string> {\n const dir = dirOf(htmlPath);\n for (const f of tsFiles) {\n if (dirOf(f) !== dir || f.endsWith('.spec.ts')) continue;\n const src = read(f);\n if (!src || !src.includes('templateUrl') || !src.includes(CORE)) continue;\n const sf = ts.createSourceFile(f, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const helper = new ServiceResolver(sf);\n for (const stmt of sf.statements) {\n if (!ts.isClassDeclaration(stmt)) continue;\n const url = componentProp(stmt, 'templateUrl');\n if (url && ts.isStringLiteralLike(url.initializer) && resolveUrl(dir, url.initializer.text) === normalize(htmlPath)) {\n return helper.members(stmt);\n }\n }\n }\n return new Set();\n}\n\nfunction componentObject(cls: ts.ClassDeclaration): ts.ObjectLiteralExpression | undefined {\n for (const d of ts.getDecorators(cls) ?? []) {\n if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === 'Component') {\n const arg = d.expression.arguments[0];\n if (arg && ts.isObjectLiteralExpression(arg)) return arg;\n }\n }\n return undefined;\n}\n\nfunction componentProp(cls: ts.ClassDeclaration, name: string): ts.PropertyAssignment | undefined {\n return componentObject(cls)?.properties.find(\n (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name\n );\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TranslateService receiver resolution\n// ---------------------------------------------------------------------------------------------------------------------\n\nclass ServiceResolver {\n readonly svcName: string | undefined;\n private cache = new Map<ts.Node, Set<string>>();\n\n constructor(private readonly sf: ts.SourceFile, typeName = 'TranslateService') {\n this.svcName = importedLocalName(sf, typeName);\n }\n\n isType(t: ts.TypeNode | undefined): boolean {\n return !!this.svcName && !!t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === this.svcName;\n }\n\n isInject(e: ts.Expression | undefined): boolean {\n if (!this.svcName || !e) return false;\n const x = unwrap(e);\n if (!ts.isCallExpression(x)) return false;\n const c = x.expression;\n const named = (ts.isIdentifier(c) && c.text === 'inject') || (ts.isPropertyAccessExpression(c) && c.name.text === 'inject');\n const a = x.arguments[0];\n return named && !!a && ts.isIdentifier(a) && a.text === this.svcName;\n }\n\n members(cls: ts.ClassLikeDeclaration): Set<string> {\n const cached = this.cache.get(cls);\n if (cached) return cached;\n const set = new Set<string>();\n for (const m of cls.members) {\n if (ts.isPropertyDeclaration(m) && ts.isIdentifier(m.name) && (this.isType(m.type) || this.isInject(m.initializer))) set.add(m.name.text);\n if (ts.isConstructorDeclaration(m)) {\n for (const p of m.parameters) {\n const isProp = ts.getModifiers(p)?.some((x) =>\n [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(x.kind)\n );\n if (isProp && ts.isIdentifier(p.name) && this.isType(p.type)) set.add(p.name.text);\n }\n }\n }\n this.cache.set(cls, set);\n return set;\n }\n\n /** true: declared as TranslateService, false: declared as something else, undefined: not found. */\n bare(id: ts.Identifier): boolean | undefined {\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n let decls: readonly (ts.ParameterDeclaration | ts.VariableDeclaration)[] = [];\n if (ts.isFunctionLike(cur)) decls = cur.parameters;\n else if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur)) {\n decls = cur.statements.filter(ts.isVariableStatement).flatMap((s) => [...s.declarationList.declarations]);\n } else if (ts.isCatchClause(cur) && cur.variableDeclaration) decls = [cur.variableDeclaration];\n else if (\n (ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) &&\n cur.initializer &&\n ts.isVariableDeclarationList(cur.initializer)\n ) {\n decls = cur.initializer.declarations;\n }\n const d = decls.find((x) => ts.isIdentifier(x.name) && x.name.text === id.text);\n if (d) return this.isType(d.type) || (ts.isVariableDeclaration(d) && this.isInject(d.initializer));\n }\n return undefined;\n }\n\n isService(expr: ts.Expression): boolean {\n const e = unwrap(expr);\n if (ts.isPropertyAccessExpression(e) && e.expression.kind === ts.SyntaxKind.ThisKeyword) {\n for (let cur: ts.Node | undefined = e.parent; cur; cur = cur.parent) {\n if (ts.isClassLike(cur)) return this.members(cur).has(e.name.text);\n }\n return false;\n }\n return ts.isIdentifier(e) && this.bare(e) === true;\n }\n}\n\nfunction unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e)) e = e.expression;\n return e;\n}\n\n/** Local name of a non-type-only named import of `imported` from @ngx-translate/core. */\nfunction importedLocalName(sf: ts.SourceFile, imported: string, module = CORE): string | undefined {\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== module) continue;\n const nb = stmt.importClause?.namedBindings;\n if (!nb || !ts.isNamedImports(nb)) continue;\n for (const el of nb.elements) if ((el.propertyName ?? el.name).text === imported) return el.name.text;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// TypeScript\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface TsEnv {\n projectHasExtend: boolean;\n projectUsesNgx: boolean;\n read: (p: string) => string | undefined;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, context: SchematicContext, env: TsEnv): string {\n const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const resolver = new ServiceResolver(sf);\n const edits: Edit[] = [];\n const todos = new Map<number, { anchor: ts.Node; messages: string[] }>();\n const needed = new Set<string>();\n const touched = new Set<string>();\n const handled = new Set<ts.Node>();\n const moves = new Map<ts.ObjectLiteralExpression, { calls: ts.CallExpression[]; texts: string[] }>();\n const moduleName = importedLocalName(sf, 'TranslateModule') === 'TranslateModule' ? 'TranslateModule' : undefined;\n const setValueName = importedLocalName(sf, 'setValue') === 'setValue' ? 'setValue' : undefined;\n const defaultEvent = importedLocalName(sf, 'DefaultLangChangeEvent') === 'DefaultLangChangeEvent';\n const tokenImported = (t: string): boolean => importedLocalName(sf, t) === t;\n const providerNames = new Set(['provideTranslateService'].filter((n) => importedLocalName(sf, n) === n));\n let importProvidersTouched = false;\n\n const seenWarnings = new Set<string>();\n const warnOnce = (text: string): void => {\n if (seenWarnings.has(text)) return;\n seenWarnings.add(text);\n context.logger.warn(text);\n };\n const storeResolver = new ServiceResolver(sf, 'TranslateStore');\n const httpNames = new Set(\n ['provideTranslateHttpLoader', 'TranslateHttpLoader'].map((n) => importedLocalName(sf, n, HTTP_LOADER)).filter((n): n is string => !!n)\n );\n const iServiceName = importedLocalName(sf, 'ITranslateService');\n const lineNo = (node: ts.Node): number => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n const flag = (node: ts.Node, message: string, comment = true): void => {\n warnOnce(`${filePath}:${lineNo(node)} - Manual action needed: ${message}`);\n if (!comment) return;\n const anchor = anchorOf(node);\n const key = anchor.getStart(sf);\n const entry = todos.get(key) ?? { anchor, messages: [] };\n const clean = sanitize(message);\n if (!entry.messages.includes(clean)) entry.messages.push(clean);\n todos.set(key, entry);\n };\n\n const nameOf = (n: ts.PropertyName | undefined): string | undefined =>\n n && (ts.isIdentifier(n) || ts.isStringLiteral(n)) ? n.text : undefined;\n const propOf = (obj: ts.ObjectLiteralExpression, name: string): ts.ObjectLiteralElementLike | undefined =>\n obj.properties.find((p) => !!p.name && nameOf(p.name) === name);\n\n // ----- config object transforms (defaultLanguage, useDefaultLang, plugin providers, extend/isolate) -----\n const CHILD_UNSUPPORTED = ['defaultLanguage', 'fallbackLang', 'lang', 'langs', 'useDefaultLang'];\n const transformConfig = (obj: ts.ObjectLiteralExpression, dropChildProps: boolean, out: Edit[], childTarget = false): number => {\n const drop = new Set<ts.ObjectLiteralElementLike>();\n for (const p of obj.properties) {\n const name = nameOf(p.name);\n if (!name) continue;\n if (childTarget && CHILD_UNSUPPORTED.includes(name) && ts.isPropertyAssignment(p)) {\n drop.add(p);\n flag(p, `${name} was removed: ChildTranslateServiceConfig has no such option, child services inherit the parent's fallbackLang and language. Set it on the root provideTranslateService() if needed.`);\n continue;\n }\n if (name === 'defaultLanguage') {\n if (ts.isPropertyAssignment(p)) out.push({\n start: p.name.getStart(sf),\n end: p.name.getEnd(),\n replacement: 'fallbackLang',\n });\n else if (ts.isShorthandPropertyAssignment(p)) out.push({\n start: p.getStart(sf),\n end: p.getEnd(),\n replacement: 'fallbackLang: defaultLanguage',\n });\n } else if (name === 'useDefaultLang' && ts.isPropertyAssignment(p)) {\n if (p.initializer.kind === ts.SyntaxKind.TrueKeyword) {\n drop.add(p);\n } else {\n flag(\n p,\n 'useDefaultLang was removed in @ngx-translate/core v18 and is kept only because its value is false: v18 always falls back to fallbackLang when it is set. Remove the leftover property manually (it does not compile as is); drop fallbackLang too if you relied on useDefaultLang: false.'\n );\n }\n } else if (dropChildProps && (name === 'extend' || name === 'isolate') && ts.isPropertyAssignment(p)) {\n drop.add(p);\n } else if (PLUGIN_KEYS.includes(name) && ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {\n const init = p.initializer;\n const provide = propOf(init, 'provide');\n const token = provide && ts.isPropertyAssignment(provide) && ts.isIdentifier(provide.initializer) ? provide.initializer.text : undefined;\n if (!token || !TOKEN_PROVIDERS[token]) continue;\n const useClass = propOf(init, 'useClass');\n if (init.properties.length === 2 && useClass && ts.isPropertyAssignment(useClass) && tokenImported(token)) {\n const fn = TOKEN_PROVIDERS[token];\n out.push({\n start: init.getStart(sf),\n end: init.getEnd(),\n replacement: `${fn}(${useClass.initializer.getText(sf)})`,\n });\n needed.add(fn);\n touched.add(token);\n } else {\n flag(\n p,\n `the ${token} provider uses a form other than { provide, useClass } (useFactory/useValue/deps). Convert it manually to ${TOKEN_PROVIDERS[token]}(...).`\n );\n }\n }\n }\n if (drop.size > 0) out.push(...removeArrayElements(obj, new Set([...drop].map((d) => obj.properties.indexOf(d))), sf));\n return drop.size;\n };\n\n // ----- TranslateModule.forRoot / forChild -----\n const convertModuleCall = (call: ts.CallExpression): void => {\n const callee = call.expression as ts.PropertyAccessExpression;\n handled.add(callee.expression);\n const method = callee.name.text;\n const args = call.arguments;\n const undecidable = (why: string): void =>\n flag(call, `TranslateModule.${method}() was left unchanged: ${why}. Use provideTranslateService() / provideChildTranslateService() manually.`);\n\n if (args.length > 1 || (args.length === 1 && !ts.isObjectLiteralExpression(args[0]))) return undecidable('its config is not an object literal');\n const obj = args[0] as ts.ObjectLiteralExpression | undefined;\n let fn = method === 'forRoot' ? 'provideTranslateService' : 'provideChildTranslateService';\n let hadExtendTrue = false;\n if (method === 'forChild' && obj) {\n for (const p of obj.properties) {\n const name = p.name ? nameOf(p.name) : undefined;\n if (ts.isSpreadAssignment(p)) return undecidable('its config contains a spread');\n if (name !== 'isolate' && name !== 'extend') continue;\n const init = ts.isPropertyAssignment(p) ? p.initializer.kind : undefined;\n if (init !== ts.SyntaxKind.TrueKeyword && init !== ts.SyntaxKind.FalseKeyword) return undecidable(`${name} is not a boolean literal`);\n if (name === 'isolate' && init === ts.SyntaxKind.TrueKeyword) fn = 'provideTranslateService';\n if (name === 'extend' && init === ts.SyntaxKind.TrueKeyword) hadExtendTrue = true;\n }\n }\n\n // the placement is decided first, so nothing is emitted for an unmovable call\n const parent = call.parent;\n let move: ts.ObjectLiteralExpression | undefined;\n let unwrapImportProviders: ts.CallExpression | undefined;\n if (ts.isArrayLiteralExpression(parent) && ts.isPropertyAssignment(parent.parent) && nameOf(parent.parent.name) === 'imports' && ts.isObjectLiteralExpression(parent.parent.parent)) {\n const owner = parent.parent.parent;\n const decorator = owner.parent;\n if (ts.isCallExpression(decorator) && ts.isIdentifier(decorator.expression) && decorator.expression.text === 'Component') {\n return undecidable('a standalone @Component cannot take environment providers; provide it in the application/route providers instead');\n }\n move = owner;\n } else if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'importProvidersFrom') {\n if (parent.arguments.length !== 1) return undecidable('it is combined with other sources in importProvidersFrom()');\n unwrapImportProviders = parent;\n }\n\n const local: Edit[] = [];\n const removed = obj ? transformConfig(obj, method === 'forChild', local, fn === 'provideChildTranslateService') : 0;\n const keepConfig = !!obj && obj.properties.length - removed > 0;\n const cfgText = keepConfig ? applyEdits(source.slice(obj!.getStart(sf), obj!.getEnd()), shift(local, -obj!.getStart(sf))) : '';\n const text = `${fn}(${cfgText})`;\n needed.add(fn);\n touched.add('TranslateModule');\n if (method === 'forChild') {\n warnOnce(\n `${filePath}:${lineNo(call)} - forChild() was converted to ${fn}(): v18 child services use their own store with parent fallback, review isolation semantics.${hadExtendTrue ? ' extend: true was removed: setTranslation(lang, t) no longer merges, pass true as third argument where needed.' : ''}`\n );\n }\n\n if (move) {\n const g = moves.get(move) ?? { calls: [], texts: [] };\n g.calls.push(call);\n g.texts.push(text);\n moves.set(move, g);\n } else if (unwrapImportProviders) {\n edits.push({ start: unwrapImportProviders.getStart(sf), end: unwrapImportProviders.getEnd(), replacement: text });\n importProvidersTouched = true;\n } else {\n edits.push({ start: call.getStart(sf), end: call.getEnd(), replacement: text });\n }\n };\n\n // ----- bare TranslateModule in imports/exports -----\n const convertBareModule = (id: ts.Identifier, arr: ts.ArrayLiteralExpression, owner: ts.ObjectLiteralExpression): void => {\n handled.add(id);\n const callNode = owner.parent;\n const kind = ts.isCallExpression(callNode) && ts.isIdentifier(callNode.expression) ? callNode.expression.text : '';\n let names = ['TranslatePipe', 'TranslateDirective'];\n if (kind === 'Component') {\n const u = componentUsage(owner);\n if (u) names = [u.pipe ? 'TranslatePipe' : '', u.directive ? 'TranslateDirective' : ''].filter(Boolean);\n }\n const present = new Set(arr.elements.filter(ts.isIdentifier).map((e) => e.text));\n const add = names.filter((n) => !present.has(n));\n touched.add('TranslateModule');\n for (const n of names) needed.add(n);\n if (add.length > 0) {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: add.join(', ') });\n } else {\n edits.push(...removeArrayElements(arr, new Set([arr.elements.indexOf(id)]), sf));\n }\n };\n\n const componentUsage = (owner: ts.ObjectLiteralExpression): { pipe: boolean; directive: boolean } | null => {\n const tpl = propOf(owner, 'template');\n const url = propOf(owner, 'templateUrl');\n const quiet = { members: new Set<string>(), allowKeyRewrite: false, where: (): string => '', quiet: true };\n if (tpl && ts.isPropertyAssignment(tpl) && (ts.isNoSubstitutionTemplateLiteral(tpl.initializer) || ts.isStringLiteral(tpl.initializer))) {\n const lit = tpl.initializer;\n return scanTemplate(source.slice(lit.getStart(sf) + 1, lit.getEnd() - 1), filePath, context, quiet).usage;\n }\n if (url && ts.isPropertyAssignment(url) && ts.isStringLiteralLike(url.initializer)) {\n const target = resolveUrl(dirOf(filePath), url.initializer.text);\n const html = env.read(target);\n if (html !== undefined) return scanTemplate(html, target, context, quiet).usage;\n }\n return null;\n };\n\n // ----- visitor -----\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) return;\n\n if (ts.isCallExpression(node)) visitCall(node);\n else if (ts.isPropertyAccessExpression(node)) visitMember(node);\n else if (ts.isVariableDeclaration(node)) visitAlias(node.name, node.initializer, node);\n else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) visitAlias(undefined, node.right, node);\n else if (ts.isIdentifier(node)) visitIdentifier(node);\n else if (ts.isClassDeclaration(node)) visitInlineTemplate(node);\n\n ts.forEachChild(node, visit);\n };\n\n const visitCall = (call: ts.CallExpression): void => {\n const c = call.expression;\n if (moduleName && ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === moduleName && (c.name.text === 'forRoot' || c.name.text === 'forChild')) {\n convertModuleCall(call);\n return;\n }\n if (ts.isIdentifier(c) && providerNames.has(c.text) && call.arguments[0] && ts.isObjectLiteralExpression(call.arguments[0])) {\n transformConfig(call.arguments[0], false, edits);\n }\n if (setValueName && ts.isIdentifier(c) && c.text === setValueName) {\n const a0 = call.arguments[0];\n const assignable = !!a0 && (ts.isIdentifier(a0) || ts.isPropertyAccessExpression(a0) || ts.isElementAccessExpression(a0));\n if (ts.isExpressionStatement(call.parent) && call.arguments.length === 3 && assignable) {\n edits.push({ start: c.getStart(sf), end: c.getEnd(), replacement: `${a0.getText(sf)} = insertValue` });\n needed.add('insertValue');\n touched.add('setValue');\n } else {\n flag(call, 'setValue() was replaced by insertValue(), which returns a new object instead of mutating its argument. Use `target = insertValue(target, key, value)` manually.');\n }\n }\n if (ts.isPropertyAccessExpression(c) && resolver.isService(c.expression)) {\n if (c.name.text === 'getCurrentLang') {\n flag(call, 'getCurrentLang() returns Language | null in @ngx-translate/core v18 (null before a language is set). Handle the null case, e.g. `?? fallback`.');\n } else if (c.name.text === 'setTranslation' && call.arguments.length === 2 && env.projectHasExtend) {\n flag(call, 'setTranslation(lang, translations) no longer merges for services that used forChild({ extend: true }); pass `true` as third argument if you relied on merging.');\n }\n }\n };\n\n const visitMember = (n: ts.PropertyAccessExpression): void => {\n const member = n.name.text;\n if ((member === 'onTranslationChange' || member === 'getValue') && storeResolver.isService(n.expression)) {\n edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: member === 'getValue' ? 'getTranslationValue' : 'translationChange$',\n });\n return;\n }\n const isTracked = ['currentLang', 'langs', 'defaultLang', ...Object.keys(MEMBER_RENAMES)].includes(member);\n if (!isTracked || !resolver.isService(n.expression)) return;\n const parent = n.parent;\n if (MEMBER_RENAMES[member]) {\n edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: MEMBER_RENAMES[member] });\n return;\n }\n if (ts.isCallExpression(parent) && parent.expression === n) return; // already `currentLang()` etc.\n const isWrite =\n (ts.isBinaryExpression(parent) && parent.left === n && ASSIGN_OPS.has(parent.operatorToken.kind)) ||\n ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&\n (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) ||\n ts.isDeleteExpression(parent);\n if (isWrite) {\n flag(n, `${member} cannot be assigned in @ngx-translate/core v18 (read-only Signal / removed). Use use(), setFallbackLang() or setTranslation() instead.`);\n return;\n }\n if (member === 'currentLang') edits.push({ start: n.getEnd(), end: n.getEnd(), replacement: '()' });\n else if (member === 'langs') edits.push({\n start: n.name.getStart(sf),\n end: n.name.getEnd(),\n replacement: 'getLangs()',\n });\n else edits.push({ start: n.name.getStart(sf), end: n.name.getEnd(), replacement: 'fallbackLang()' });\n };\n\n const visitAlias = (name: ts.BindingName | undefined, init: ts.Expression | undefined, at: ts.Node): void => {\n if (!init) return;\n if (!resolver.isService(init) && !(name && ts.isObjectBindingPattern(name) && resolver.isInject(init))) return;\n if (name && ts.isIdentifier(name) && ts.isVariableDeclaration(at) && resolver.isType(at.type)) return; // typed alias is tracked\n flag(\n at,\n 'TranslateService is aliased or destructured here, so currentLang/default*/langs usages through it are not migrated automatically. Review them against the v18 API (currentLang() signal, fallbackLang, getLangs()).'\n );\n };\n\n const visitIdentifier = (id: ts.Identifier): void => {\n const p = id.parent;\n if ((ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id)) return;\n if (httpNames.has(id.text)) {\n const call = ts.isCallExpression(p) && p.expression === id ? p : undefined;\n const cfg = call?.arguments[0];\n const hasFlag = !!cfg && ts.isObjectLiteralExpression(cfg) && !!propOf(cfg, 'failOnError');\n if (!hasFlag) {\n flag(id, 'the v18 http-loader no longer fails the whole language load when a translation file request fails (it logs a warning and uses {}). Pass failOnError: true to provideTranslateHttpLoader() if you rely on the v17 behaviour.');\n }\n }\n if (iServiceName && id.text === iServiceName && ts.isExpressionWithTypeArguments(p) && ts.isHeritageClause(p.parent) && p.parent.token === ts.SyntaxKind.ImplementsKeyword) {\n flag(id, 'ITranslateService gained isLoading: Signal<boolean> in @ngx-translate/core v18. Add isLoading = signal(false).asReadonly() to this class.');\n }\n if (defaultEvent && id.text === 'DefaultLangChangeEvent') {\n edits.push({ start: id.getStart(sf), end: id.getEnd(), replacement: 'FallbackLangChangeEvent' });\n needed.add('FallbackLangChangeEvent');\n touched.add('DefaultLangChangeEvent');\n }\n if (moduleName && id.text === moduleName && !handled.has(id)) {\n // `TranslateModule` as an element of imports / exports\n if (ts.isArrayLiteralExpression(p) && ts.isPropertyAssignment(p.parent) && ['imports', 'exports'].includes(nameOf(p.parent.name) ?? '') && ts.isObjectLiteralExpression(p.parent.parent)) {\n convertBareModule(id, p, p.parent.parent);\n }\n }\n };\n\n const visitInlineTemplate = (cls: ts.ClassDeclaration): void => {\n const tpl = componentProp(cls, 'template');\n if (!tpl) return;\n const lit = tpl.initializer;\n if (!ts.isNoSubstitutionTemplateLiteral(lit) && !ts.isStringLiteral(lit)) return;\n const start = lit.getStart(sf) + 1;\n const raw = source.slice(start, lit.getEnd() - 1);\n if (!/translate|currentLang/.test(raw)) return;\n const baseLine = sf.getLineAndCharacterOfPosition(start).line;\n const scan = scanTemplate(raw, filePath, context, {\n members: resolver.members(cls),\n allowKeyRewrite: ts.isNoSubstitutionTemplateLiteral(lit),\n checkAttributes: env.projectUsesNgx,\n where: (o) => `${filePath}:${baseLine + lineOf(raw, o)}`,\n });\n edits.push(...shift(scan.edits, start));\n };\n\n visit(sf);\n\n // moved forRoot/forChild calls: imports -> providers\n for (const [obj, g] of moves) {\n const importsProp = propOf(obj, 'imports') as ts.PropertyAssignment;\n const arr = importsProp.initializer as ts.ArrayLiteralExpression;\n const providersProp = propOf(obj, 'providers');\n if (providersProp && !(ts.isPropertyAssignment(providersProp) && ts.isArrayLiteralExpression(providersProp.initializer))) {\n for (const call of g.calls) flag(call, 'the providers property is not an array literal, so the converted provider could not be moved there. Move it manually.');\n continue;\n }\n const texts = g.texts.join(', ');\n const movedIdx = new Set(g.calls.map((c) => arr.elements.indexOf(c)));\n const keepsOthers = arr.elements.length > movedIdx.size;\n if (providersProp) {\n const parr = (providersProp as ts.PropertyAssignment).initializer as ts.ArrayLiteralExpression;\n if (parr.elements.length > 0) {\n edits.push({\n start: parr.elements[parr.elements.length - 1].getEnd(),\n end: parr.elements[parr.elements.length - 1].getEnd(),\n replacement: `, ${texts}`,\n });\n } else {\n edits.push({ start: parr.getStart(sf) + 1, end: parr.getEnd() - 1, replacement: texts });\n }\n if (keepsOthers) edits.push(...removeArrayElements(arr, movedIdx, sf));\n else removeObjectProperty(importsProp, sf, edits);\n } else if (!keepsOthers) {\n edits.push({ start: importsProp.getStart(sf), end: importsProp.getEnd(), replacement: `providers: [${texts}]` });\n } else {\n edits.push(...removeArrayElements(arr, movedIdx, sf));\n const multiline = source.slice(obj.getStart(sf), importsProp.getEnd()).includes('\\n');\n const indent = multiline ? /[ \\t]*$/.exec(source.slice(0, importsProp.getStart(sf)))![0] : '';\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n edits.push({\n start: importsProp.getEnd(),\n end: importsProp.getEnd(),\n replacement: multiline ? `,${eol}${indent}providers: [${texts}]` : `, providers: [${texts}]`,\n });\n }\n }\n\n // remaining references to the removed module\n if (moduleName) {\n const mark = (n: ts.Node): void => {\n if (ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === moduleName && !handled.has(n) && !isPropertyName(n)) {\n flag(n, 'TranslateModule was removed in @ngx-translate/core v18. Use provideTranslateService() / provideChildTranslateService() and import TranslatePipe / TranslateDirective directly.');\n }\n ts.forEachChild(n, mark);\n };\n mark(sf);\n }\n\n // TODO comments, one line above the anchor, never duplicated\n const eol = source.includes('\\r\\n') ? '\\r\\n' : '\\n';\n for (const { anchor, messages } of todos.values()) {\n const start = anchor.getStart(sf);\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1;\n const indent = /^[ \\t]*/.exec(source.slice(lineStart))![0];\n const above = new Set<string>();\n const lines = source.slice(0, lineStart).split(/\\r?\\n/);\n for (let i = lines.length - 2; i >= 0 && lines[i].trim().startsWith('// ' + TODO_PREFIX); i--) above.add(lines[i].trim());\n const fresh = messages.map((m) => `// ${TODO_PREFIX} ${m}`).filter((l) => !above.has(l));\n if (fresh.length > 0) edits.push({\n start: lineStart,\n end: lineStart,\n replacement: fresh.map((l) => `${indent}${l}${eol}`).join(''),\n });\n }\n\n let result = applyEdits(source, edits);\n if (result === source) return source;\n result = fixImports(result, filePath, CORE, needed, touched);\n if (importProvidersTouched) result = fixImports(result, filePath, '@angular/core', new Set(), new Set(['importProvidersFrom']));\n return result;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Imports\n// ---------------------------------------------------------------------------------------------------------------------\n\nconst RENAME_IN_PLACE: Record<string, string> = {\n DefaultLangChangeEvent: 'FallbackLangChangeEvent',\n setValue: 'insertValue',\n};\n\n/**\n * Drops `touched` specifiers that are no longer referenced (renaming in place when a rename is known) and\n * appends the `needed` names to the first named import of `moduleName`.\n */\nfunction fixImports(text: string, filePath: string, moduleName: string, needed: Set<string>, touched: Set<string>): string {\n const sf = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const referenced = (name: string): boolean => {\n let found = false;\n const walk = (n: ts.Node): void => {\n if (found || ts.isImportDeclaration(n)) return;\n if (ts.isIdentifier(n) && n.text === name && !isPropertyName(n)) found = true;\n ts.forEachChild(n, walk);\n };\n walk(sf);\n return found;\n };\n\n const decls = sf.statements.filter(\n (s): s is ts.ImportDeclaration =>\n ts.isImportDeclaration(s) &&\n ts.isStringLiteral(s.moduleSpecifier) &&\n s.moduleSpecifier.text === moduleName &&\n !!s.importClause?.namedBindings &&\n ts.isNamedImports(s.importClause.namedBindings) &&\n !s.importClause.isTypeOnly\n );\n if (decls.length === 0) return text;\n\n const all = new Set<string>();\n for (const d of decls) for (const e of (d.importClause!.namedBindings as ts.NamedImports).elements) all.add(e.name.text);\n const placed = new Set<string>();\n const edits: Edit[] = [];\n const pendingNeeded = [...needed];\n\n decls.forEach((d, di) => {\n const named = d.importClause!.namedBindings as ts.NamedImports;\n const items: string[] = [];\n for (const e of named.elements) {\n const name = e.name.text;\n if (touched.has(name) && !e.propertyName && !referenced(name)) {\n const to = RENAME_IN_PLACE[name];\n if (to && needed.has(to) && !all.has(to) && !placed.has(to)) {\n items.push(to);\n placed.add(to);\n }\n continue;\n }\n items.push(e.getText(sf));\n }\n if (di === 0) {\n for (const n of pendingNeeded) if (!all.has(n) && !placed.has(n) && !items.includes(n)) items.push(n);\n }\n const before = named.elements.map((e) => e.getText(sf));\n if (items.length === before.length && items.every((v, i) => v === before[i])) return;\n if (items.length === 0 && !d.importClause!.name) {\n let end = d.getEnd();\n if (text[end] === '\\r') end++;\n if (text[end] === '\\n') end++;\n edits.push({ start: d.getStart(sf), end, replacement: '' });\n } else {\n const multiline = named.getText(sf).includes('\\n');\n const body = multiline ? `{\\n ${items.join(',\\n ')},\\n}` : `{ ${items.join(', ')} }`;\n edits.push({ start: named.getStart(sf), end: named.getEnd(), replacement: body });\n }\n });\n return applyEdits(text, edits);\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------------------------------------------------\n\nfunction isPropertyName(id: ts.Identifier): boolean {\n const p = id.parent;\n return (ts.isPropertyAccessExpression(p) && p.name === id) || (ts.isPropertyAssignment(p) && p.name === id);\n}\n\nfunction sanitize(message: string): string {\n return message.replace(/\\s+/g, ' ').trim();\n}\n\n/** Nearest ancestor that is a statement, class member or object property: the TODO goes on the line above it. */\nfunction anchorOf(node: ts.Node): ts.Node {\n let cur = node;\n while (cur.parent) {\n const p = cur.parent;\n if (ts.isSourceFile(p) || ts.isBlock(p) || ts.isModuleBlock(p) || ts.isClassLike(p) || ts.isObjectLiteralExpression(p) || ts.isCaseClause(p) || ts.isDefaultClause(p)) {\n return cur;\n }\n cur = p;\n }\n return cur;\n}\n\nconst dirOf = (p: string): string => dirname(normalize(p));\nconst resolveUrl = (dir: string, url: string): string => normalize(join(normalize(dir), url));\n\nfunction lineOf(source: string, offset: number): number {\n return source.slice(0, offset).split('\\n').length;\n}\n\nfunction shift(edits: Edit[], by: number): Edit[] {\n return edits.map((e) => ({ ...e, start: e.start + by, end: e.end + by }));\n}\n\n/** Removes one object property together with its separating comma. */\nfunction removeObjectProperty(prop: ts.ObjectLiteralElementLike, sf: ts.SourceFile, edits: Edit[]): void {\n const obj = prop.parent as ts.ObjectLiteralExpression;\n const props = obj.properties;\n const idx = props.indexOf(prop);\n const text = sf.getFullText();\n let start = prop.getStart(sf);\n let end = prop.getEnd();\n if (idx < props.length - 1) {\n end = props[idx + 1].getStart(sf);\n } else if (idx > 0) {\n start = props[idx - 1].getEnd();\n } else if (text[end] === ',') {\n end++;\n }\n edits.push({ start, end, replacement: '' });\n}\n\n/** Removes the array elements at `indices`; non-overlapping ranges even for neighbouring elements. */\nfunction removeArrayElements(arr: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression, indices: Set<number>, sf: ts.SourceFile): Edit[] {\n const els: readonly ts.Node[] = ts.isArrayLiteralExpression(arr) ? arr.elements : arr.properties;\n const keptIdx = els.findIndex((_, i) => !indices.has(i));\n if (keptIdx === -1) return [{ start: arr.getStart(sf) + 1, end: arr.getEnd() - 1, replacement: '' }];\n const out: Edit[] = [];\n if (keptIdx > 0) out.push({ start: els[0].getStart(sf), end: els[keptIdx].getStart(sf), replacement: '' });\n for (let i = keptIdx + 1; i < els.length; i++) {\n if (indices.has(i)) out.push({ start: els[i - 1].getEnd(), end: els[i].getEnd(), replacement: '' });\n }\n return out;\n}\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const seen = new Map<string, Edit>();\n for (const e of edits) seen.set(`${e.start}:${e.end}:${e.replacement}`, e);\n let result = source;\n for (const e of [...seen.values()].sort((a, b) => b.start - a.start || b.end - a.end)) {\n result = result.slice(0, e.start) + e.replacement + result.slice(e.end);\n }\n return result;\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts') && !file.endsWith('.html')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
5926
5924
|
"displayName": "Schema",
|
|
5927
5925
|
"properties": [
|
|
5928
5926
|
{
|
|
@@ -5934,7 +5932,7 @@
|
|
|
5934
5932
|
"indexKey": "",
|
|
5935
5933
|
"optional": true,
|
|
5936
5934
|
"description": "",
|
|
5937
|
-
"line":
|
|
5935
|
+
"line": 32,
|
|
5938
5936
|
"rawdescription": "\n"
|
|
5939
5937
|
},
|
|
5940
5938
|
{
|
|
@@ -5946,12 +5944,14 @@
|
|
|
5946
5944
|
"indexKey": "",
|
|
5947
5945
|
"optional": true,
|
|
5948
5946
|
"description": "",
|
|
5949
|
-
"line":
|
|
5947
|
+
"line": 31,
|
|
5950
5948
|
"rawdescription": "\n"
|
|
5951
5949
|
}
|
|
5952
5950
|
],
|
|
5953
5951
|
"indexSignatures": [],
|
|
5954
5952
|
"kind": 172,
|
|
5953
|
+
"description": "<p>Migrates @ngx-translate/core v17 -> v18 breaking changes.</p>\n<p>No type checker is used: a <code>TranslateService</code> receiver is resolved from its declaration in the same\nfile (<code>: TranslateService</code>, <code>inject(TranslateService)</code>, constructor parameter properties) and, for\ntemplates, from the component class that owns the template.\nshortcut: receivers that are aliased, destructured, passed through other types or declared in another\nfile are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.</p>\n",
|
|
5954
|
+
"rawdescription": "\n\nMigrates @ngx-translate/core v17 -> v18 breaking changes.\n\nNo type checker is used: a `TranslateService` receiver is resolved from its declaration in the same\nfile (`: TranslateService`, `inject(TranslateService)`, constructor parameter properties) and, for\ntemplates, from the component class that owns the template.\nshortcut: receivers that are aliased, destructured, passed through other types or declared in another\nfile are not followed (they are flagged where detectable); upgrade to a ts.Program when needed.\n",
|
|
5955
5955
|
"methods": [],
|
|
5956
5956
|
"extends": [],
|
|
5957
5957
|
"isDuplicate": true,
|
|
@@ -5964,12 +5964,12 @@
|
|
|
5964
5964
|
},
|
|
5965
5965
|
{
|
|
5966
5966
|
"name": "Schema",
|
|
5967
|
-
"id": "interface-Schema-
|
|
5968
|
-
"file": "packages/core/schematics/migrate-to-
|
|
5967
|
+
"id": "interface-Schema-9ee907f6235e54dc564fd1a3f1f033debd4767715b1337e518de4f47f358dfcbff287bd8398fa3fe457784ecf36e625d57b4f9672b760879a507c1a823d51089-42",
|
|
5968
|
+
"file": "packages/core/schematics/migrate-to-standalone/index.ts",
|
|
5969
5969
|
"deprecated": false,
|
|
5970
5970
|
"deprecationMessage": "",
|
|
5971
5971
|
"type": "interface",
|
|
5972
|
-
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport { parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { forEachElement } from '../utils/template-walk';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport {\n EUI_SIGNAL_MAP as EUI_SIGNAL_MAP_RAW,\n EUI_SELECTOR_TO_CLASS as EUI_SELECTOR_TO_CLASS_RAW,\n EUI_OUTPUT_MAP,\n EUI_HOST_BINDING_REMOVED_MAP,\n EUI_WRITABLE_SIGNAL_MAP,\n} from './signal-map';\nimport { ECL_SIGNAL_MAP, ECL_SELECTOR_TO_CLASS } from './ecl-signal-map';\n\n/**\n * Combined EUI + ECL signal maps. The migration logic is identical for both\n * libraries (plain field → signal getter), so the maps are merged and the rest\n * of the engine treats them uniformly. EUI and ECL class names don't collide\n * (Eui* vs Ecl* prefixes), and the selector namespaces are disjoint.\n */\nconst EUI_SIGNAL_MAP: Record<string, ReadonlySet<string>> = { ...EUI_SIGNAL_MAP_RAW, ...ECL_SIGNAL_MAP };\nconst EUI_SELECTOR_TO_CLASS: Record<string, string> = { ...EUI_SELECTOR_TO_CLASS_RAW, ...ECL_SELECTOR_TO_CLASS };\n\n/** Every class the schematic knows about (signals, outputs or removed host bindings). */\nconst KNOWN_CLASSES: ReadonlySet<string> = new Set([\n ...Object.keys(EUI_SIGNAL_MAP),\n ...Object.keys(EUI_OUTPUT_MAP),\n ...Object.keys(EUI_HOST_BINDING_REMOVED_MAP),\n]);\nconst isKnownClass = (name: string | null | undefined): name is string => !!name && KNOWN_CLASSES.has(name);\n\n/**\n * Tracked references. Class members are tracked by name (reached via `this.name`); locals/parameters are\n * tracked by their DECLARATION node, so a same-named untracked parameter or variable is never confused\n * with a tracked class member (shadowing). `lists*` hold QueryList<EuiXxx> / EuiXxx[] holders.\n */\ninterface Refs {\n props: Map<string, string>;\n propLists: Map<string, string>;\n decls: Map<ts.Node, string>;\n listDecls: Map<ts.Node, string>;\n}\n\n/** rxjs functions that take Observables as (possibly array-wrapped) arguments. */\nconst OBSERVABLE_COMBINATORS = new Set([\n 'merge', 'race', 'combineLatest', 'forkJoin', 'concat', 'zip', 'firstValueFrom', 'lastValueFrom', 'raceWith', 'mergeWith', 'concatWith', 'zipWith', 'combineLatestWith',\n]);\n\n/** Observable methods that need a real Observable instead of an OutputEmitterRef. */\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n/** QueryList iteration methods whose callback parameter is an element of the list. */\nconst LIST_ITERATION_METHODS = new Set(['forEach', 'map', 'filter', 'some', 'every', 'find', 'findIndex', 'reduce']);\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n /** When several zero-width edits share a position, `after` ones end up after the others. */\n after?: boolean;\n}\n\n/**\n * Migrates consumer code that accesses EUI or ECL component instances\n * programmatically.\n *\n * When EUI/ECL migrated @Input() → input(), @ViewChild() → viewChild(), and\n * @ContentChild() → contentChild(), properties that were plain class fields\n * became signal getters. Consumers who access them via @ViewChild need to\n * change `comp.prop` to `comp.prop()`.\n *\n * This schematic:\n * 1. Finds @ViewChild / @ContentChild fields typed as EUI component classes\n * 2. Resolves untyped @ViewChild('refName') by reading the component template\n * and matching #refName to an EUI element tag/selector\n * 3. Tracks which local variable names hold EUI component references (incl. aliases)\n * 4. Rewrites property accesses on those references: `ref.prop` → `ref.prop()`\n * (only for properties listed in the signal map)\n * 5. Does NOT touch template bindings — those are unaffected by signal migrations\n */\nexport function migrateToSignals(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n let propCount = 0;\n let todoCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n if (!path.endsWith('.ts')) return;\n // Skip spec files — test code may use different patterns\n if (path.endsWith('.spec.ts')) return;\n\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n\n // Fast bail: file must mention at least one EUI class name or have\n // ViewChild/ContentChild with string refs (which might reference EUI elements)\n if (!hasEuiReference(original) && !hasStringRefQuery(original)) return;\n\n const result = migrateTypeScript(original, path, tree, context);\n if (result.source !== original) {\n if (options.dryRun) {\n if (result.editCount > 0) {\n logDryRun(context, `Would migrate ${result.editCount} signal property access(es) in ${path}`);\n }\n if (result.todoCount > 0) {\n logDryRun(\n context,\n `Would comment out ${result.todoCount} programmatic signal-input write(s) with a TODO in ${path}`,\n );\n }\n } else {\n tree.overwrite(path, result.source);\n }\n fileCount++;\n propCount += result.editCount;\n todoCount += result.todoCount;\n }\n });\n\n context.logger.info(`Migrated ${propCount} property access(es) to signal getters in ${fileCount} file(s).`);\n if (todoCount > 0) {\n context.logger.info(\n `Commented out ${todoCount} programmatic signal-input write(s) and left a TODO — these cannot be migrated automatically and need a manual fix.`,\n );\n }\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\n/** Quick check: does the file reference any EUI class name from the signal map? */\nfunction hasEuiReference(source: string): boolean {\n for (const className of KNOWN_CLASSES) {\n if (source.includes(className)) return true;\n }\n return false;\n}\n\n/** Quick check: does the file have @ViewChild('...') or @ContentChild('...') with string refs? */\nfunction hasStringRefQuery(source: string): boolean {\n return /(@ViewChild|@ContentChild|@ViewChildren|@ContentChildren)\\s*\\(\\s*['\"]/.test(source);\n}\n\ninterface MigrateResult {\n source: string;\n editCount: number;\n todoCount: number;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, tree: Tree, context: SchematicContext): MigrateResult {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const todoEdits: Edit[] = [];\n\n // Phase 0: Build template ref map (#refName → EUI class name) from the component's template\n const templateRefMap = buildTemplateRefMap(sourceFile, source, filePath, tree);\n\n // Phase 1: Collect all variables/properties typed as EUI classes\n const euiRefs = collectEuiReferences(sourceFile, source, templateRefMap);\n\n if (euiRefs.props.size === 0 && euiRefs.propLists.size === 0 && euiRefs.decls.size === 0 && euiRefs.listDecls.size === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const hostTodoEdits: Edit[] = [];\n let needsOutputImport = false;\n\n // Phase 2: Find property accesses on those references and rewrite signal props\n const visitNode = (node: ts.Node): void => {\n // Match: ref.prop (PropertyAccessExpression)\n if (ts.isPropertyAccessExpression(node)) {\n const rewrite = tryRewritePropertyAccess(node, euiRefs, sourceFile, source);\n if (rewrite) {\n edits.push(rewrite);\n }\n\n // Writable signal (model()): `ref.prop = value` -> `ref.prop.set(value)`\n edits.push(...trySetRewrite(node, euiRefs, sourceFile));\n\n // Output: `ref.out.subscribe()` -> `outputToObservable(ref.out).subscribe()`\n const wrap = tryWrapOutput(node, euiRefs, sourceFile);\n if (wrap) {\n edits.push(...wrap);\n needsOutputImport = true;\n }\n\n // Output handed to rxjs combinators / used as a value: wrap or flag\n const outputUse = tryOutputUsage(node, euiRefs, sourceFile, source);\n if (outputUse) {\n edits.push(...outputUse.edits);\n if (outputUse.todo) hostTodoEdits.push(outputUse.todo);\n if (outputUse.edits.length > 0) needsOutputImport = true;\n }\n\n // Removed @HostBinding property: flag with a TODO\n const hostTodo = tryHostBindingTodo(node, euiRefs, sourceFile, source);\n if (hostTodo) {\n hostTodoEdits.push(hostTodo);\n }\n\n // Separately: a programmatic WRITE to a now-signal input cannot be\n // migrated automatically. Flag it with a TODO instead of silently\n // leaving a line that will fail to compile against the signal API.\n const todo = tryInsertWriteTodo(node, euiRefs, sourceFile, source);\n if (todo) {\n todoEdits.push(todo);\n }\n }\n // Destructuring / aliasing of a tracked reference cannot be followed: flag it.\n const alias = tryAliasTodo(node, euiRefs, sourceFile, source);\n if (alias) hostTodoEdits.push(alias);\n ts.forEachChild(node, visitNode);\n };\n\n ts.forEachChild(sourceFile, visitNode);\n\n if (edits.length === 0 && todoEdits.length === 0 && hostTodoEdits.length === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const dedupedTodos = deduplicateEdits(todoEdits);\n const dedupedHostTodos = deduplicateEdits(hostTodoEdits);\n\n // A TODO edit comments out the whole write statement. Any read-rewrite `()`\n // edit whose position falls inside that commented-out range must be dropped,\n // otherwise we'd both edit and comment the same text (and produce overlapping\n // edits that corrupt the output).\n const keptEdits = edits.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const keptHostTodos = dedupedHostTodos.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const importEdit = needsOutputImport ? buildOutputImportEdit(sourceFile) : null;\n\n return {\n source: applyEdits(source, [...keptEdits, ...dedupedTodos, ...keptHostTodos, ...(importEdit ? [importEdit] : [])]),\n editCount: keptEdits.length,\n todoCount: dedupedTodos.length + keptHostTodos.length,\n };\n}\n\n/**\n * Scans the source file for class properties or variables typed as EUI component classes.\n * Returns a map: localName → Set of signal property names.\n *\n * Handles:\n * @ViewChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild(EuiXxxComponent) name!: EuiXxxComponent;\n * @ViewChild('ref') name: EuiXxxComponent;\n * @ContentChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild('ref') name: ElementRef; (resolved via template #ref → EUI selector)\n * someVar: EuiXxxComponent; (typed class field, even without decorator)\n * const alias = this.viewChildRef; (alias tracking)\n */\nfunction collectEuiReferences(\n sourceFile: ts.SourceFile,\n source: string,\n templateRefMap: Map<string, string>,\n): Refs {\n const tracked: Refs = { props: new Map(), propLists: new Map(), decls: new Map(), listDecls: new Map() };\n const { props, propLists, decls, listDecls } = tracked;\n\n // Pass 1: collect directly-typed references\n const visitDirect = (node: ts.Node): void => {\n // Class property declarations\n if (ts.isPropertyDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const euiClass = resolveEuiClassName(node, sourceFile, templateRefMap);\n if (isKnownClass(euiClass)) {\n (isListProperty(node) ? propLists : props).set(node.name.text, euiClass);\n }\n }\n\n // Variable (const x: EuiXxxComponent = ...) and parameter (method(ref: EuiXxxComponent)) declarations\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name)) {\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n decls.set(node, typeName);\n // constructor parameter property: also reachable as `this.name`\n if (ts.isParameter(node) && (ts.getModifiers?.(node) ?? []).length > 0) props.set(node.name.text, typeName);\n } else {\n const listClass = listElementClass(node.type);\n if (listClass) listDecls.set(node, listClass);\n }\n }\n\n ts.forEachChild(node, visitDirect);\n };\n\n ts.forEachChild(sourceFile, visitDirect);\n\n // Pass 2: aliases, QueryList/array iteration (source order)\n const visitAlias = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && !decls.has(node)) {\n const aliased = trackedClass(node.initializer, tracked);\n if (aliased) decls.set(node, aliased);\n const aliasedList = listClassOf(node.initializer, tracked);\n if (aliasedList) listDecls.set(node, aliasedList);\n }\n\n // list.forEach((el) => ...) / list.map(function (el) {...}) -> `el` is an element of the list\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n LIST_ITERATION_METHODS.has(node.expression.name.text)\n ) {\n const listClass = listClassOf(node.expression.expression, tracked);\n const callback = node.arguments[0];\n if (\n listClass &&\n callback &&\n (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&\n callback.parameters[0] &&\n ts.isIdentifier(callback.parameters[0].name) &&\n !callback.parameters[0].type\n ) {\n decls.set(callback.parameters[0], listClass);\n }\n }\n\n // for (const el of list) -> `el` is an element of the list\n if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {\n const listClass = listClassOf(node.expression, tracked);\n const decl = node.initializer.declarations[0];\n if (listClass && decl && ts.isIdentifier(decl.name) && !decls.has(decl)) decls.set(decl, listClass);\n }\n\n ts.forEachChild(node, visitAlias);\n };\n\n ts.forEachChild(sourceFile, visitAlias);\n return tracked;\n}\n\n/** `EuiXxx[]`, `Array<EuiXxx>`, `QueryList<EuiXxx>` -> the known element class. */\nfunction listElementClass(type: ts.TypeNode | undefined): string | null {\n if (!type) return null;\n if (ts.isArrayTypeNode(type)) {\n const n = getTypeAnnotationName(type.elementType);\n return isKnownClass(n) ? n : null;\n }\n if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && ['Array', 'ReadonlyArray', 'QueryList'].includes(type.typeName.text)) {\n const n = getTypeAnnotationName(type.typeArguments?.[0]);\n return isKnownClass(n) ? n : null;\n }\n return null;\n}\n\n/** Strips parentheses, `!`, `as T`, `<T>x` and `satisfies`. */\nfunction unwrap(expr: ts.Expression): ts.Expression {\n let cur = expr;\n while (\n ts.isParenthesizedExpression(cur) ||\n ts.isNonNullExpression(cur) ||\n ts.isAsExpression(cur) ||\n ts.isTypeAssertionExpression(cur) ||\n ts.isSatisfiesExpression(cur)\n ) {\n cur = cur.expression;\n }\n return cur;\n}\n\n/** Nearest declaration (parameter / variable / binding element) of a bare identifier, or null. */\nfunction findDeclaration(id: ts.Identifier): ts.Node | null {\n const name = id.text;\n const boundIn = (bn: ts.BindingName): boolean =>\n ts.isIdentifier(bn) ? bn.text === name : bn.elements.some((e) => !ts.isOmittedExpression(e) && boundIn(e.name));\n const matchDecl = (d: ts.ParameterDeclaration | ts.VariableDeclaration): ts.Node | null => (boundIn(d.name) ? d : null);\n\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n if (ts.isFunctionLike(cur)) {\n for (const p of cur.parameters) {\n const m = matchDecl(p);\n if (m) return m;\n }\n }\n if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur) || ts.isCaseClause(cur) || ts.isDefaultClause(cur)) {\n const stmts = ts.isCaseClause(cur) || ts.isDefaultClause(cur) ? cur.statements : cur.statements;\n for (const st of stmts) {\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n }\n }\n if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n for (const d of cur.initializer.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n if (ts.isCatchClause(cur) && cur.variableDeclaration) {\n const m = matchDecl(cur.variableDeclaration);\n if (m) return m;\n }\n }\n return null;\n}\n\n/** `this.name` -> name; anything else null. */\nfunction thisMemberName(expr: ts.Expression): string | null {\n return ts.isPropertyAccessExpression(expr) && expr.expression.kind === ts.SyntaxKind.ThisKeyword ? expr.name.text : null;\n}\n\n/** Element class of a tracked QueryList / array expression, or null. */\nfunction listClassOf(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.listDecls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n return member ? (tracked.propLists.get(member) ?? null) : null;\n}\n\n/**\n * Resolves the EUI class name from a property declaration.\n * Checks: type annotation → decorator class argument → template ref map.\n */\nfunction resolveEuiClassName(\n node: ts.PropertyDeclaration,\n sourceFile: ts.SourceFile,\n templateRefMap: Map<string, string>,\n): string | null {\n // Check type annotation first\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n return typeName;\n }\n\n const arrayClass = listElementClass(node.type);\n if (arrayClass) return arrayClass;\n\n // Check generic type argument: ElementRef<EuiXxxComponent> / QueryList<EuiXxxComponent>\n if (node.type && ts.isTypeReferenceNode(node.type) && node.type.typeArguments?.length) {\n const genericArg = getTypeAnnotationName(node.type.typeArguments[0]);\n if (isKnownClass(genericArg)) {\n return genericArg;\n }\n }\n\n // Check decorator arguments: @ViewChild(EuiXxxComponent) or @ViewChild('refName')\n if (node.modifiers) {\n for (const modifier of node.modifiers) {\n if (!ts.isDecorator(modifier)) continue;\n if (!ts.isCallExpression(modifier.expression)) continue;\n\n const decoratorName = getDecoratorName(modifier.expression);\n if (!decoratorName) continue;\n if (!['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'].includes(decoratorName)) continue;\n\n const args = modifier.expression.arguments;\n if (args.length > 0) {\n const firstArg = args[0];\n\n // @ViewChild(EuiXxxComponent) — class reference\n if (ts.isIdentifier(firstArg) && isKnownClass(firstArg.text)) {\n return firstArg.text;\n }\n\n // @ViewChild('refName') — string template ref, resolve via template\n if (ts.isStringLiteralLike(firstArg)) {\n const refName = firstArg.text;\n const euiClass = templateRefMap.get(refName);\n if (isKnownClass(euiClass)) {\n return euiClass;\n }\n }\n }\n }\n }\n\n return null;\n}\n\n/** True for `@ViewChildren/@ContentChildren` fields and `QueryList<...>`-typed fields. */\nfunction isListProperty(node: ts.PropertyDeclaration): boolean {\n if (listElementClass(node.type)) return true;\n if (node.type && ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === 'QueryList') {\n return true;\n }\n return (ts.getDecorators?.(node) ?? []).some(\n (d) => ts.isCallExpression(d.expression) && ['ViewChildren', 'ContentChildren'].includes(getDecoratorName(d.expression) ?? ''),\n );\n}\n\n/**\n * Resolves an expression to the tracked EUI class: `ref`, `this.ref`, `this.ref!`, `(this.ref as any)`,\n * the `.first` / `.last` element of a tracked QueryList, or `list[i]` of a tracked list/array.\n */\nfunction trackedClass(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.decls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n if (member) return tracked.props.get(member) ?? null;\n if (ts.isPropertyAccessExpression(e) && (e.name.text === 'first' || e.name.text === 'last')) {\n return listClassOf(e.expression, tracked);\n }\n if (ts.isElementAccessExpression(e)) return listClassOf(e.expression, tracked);\n return null;\n}\n\nfunction getDecoratorName(callExpr: ts.CallExpression): string | null {\n if (ts.isIdentifier(callExpr.expression)) {\n return callExpr.expression.text;\n }\n return null;\n}\n\nfunction getTypeAnnotationName(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n return typeNode.typeName.text;\n }\n return null;\n}\n\n/**\n * Checks if a property access `ref.prop` should be rewritten to `ref.prop()`.\n *\n * We rewrite if:\n * - `ref` is tracked in euiRefs\n * - `prop` is in the signal set for that EUI class\n * - The access is NOT already a call expression (not `ref.prop()` or `ref.prop(args)`)\n * - The access is NOT a write target (not `ref.prop = value`)\n * - The access is NOT a template binding argument (those are unaffected)\n */\nfunction tryRewritePropertyAccess(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n // Resolve the reference class — handle `this.ref.prop`, `ref.prop`, `list.first.prop`\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Skip if parent is already a call expression on this property: ref.prop(...)\n if (ts.isCallExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip a signal handed to toObservable(ref.prop): it needs the signal itself (e.g. written by migrate-eui-tab-signals)\n if (ts.isCallExpression(node.parent) && node.parent.arguments[0] === node &&\n ts.isIdentifier(node.parent.expression) && node.parent.expression.text === 'toObservable') {\n return null;\n }\n\n // Skip signal API access already in place: ref.prop.set(..) / .update(..) / .asReadonly()\n if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node &&\n ['set', 'update', 'asReadonly'].includes(node.parent.name.text)) {\n return null;\n }\n\n // Skip if this is the left side of an assignment: ref.prop = value\n if (ts.isBinaryExpression(node.parent) &&\n node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n node.parent.left === node) {\n return null;\n }\n\n // Skip if this is a compound assignment: ref.prop += value, ref.prop &&= value, etc.\n if (ts.isBinaryExpression(node.parent) && isAssignmentOperator(node.parent.operatorToken.kind) && node.parent.left === node) {\n return null;\n }\n\n // Skip if this is used with delete: delete ref.prop\n if (ts.isDeleteExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip if inside a typeof: typeof ref.prop\n if (ts.isTypeOfExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip property access chains that go deeper: ref.prop.something → ref.prop().something\n // This IS correct — we still want to add ()\n\n // Rewrite: insert () after the property name\n const end = node.name.getEnd();\n return {\n start: end,\n end: end,\n replacement: '()',\n };\n}\n\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;\n}\n\n/** Marker used to detect an already-inserted TODO so the schematic stays idempotent. */\nconst WRITE_TODO_MARKER = 'TODO(eui-signals):';\n\n/**\n * Detects a programmatic WRITE to a now-signal input and returns an edit that\n * comments out the offending statement and prepends an explanatory TODO.\n *\n * A signal input (`input()`) exposes a read-only getter — it cannot be assigned\n * from outside the component (`comp.prop = value` no longer compiles, and\n * `comp.prop()` is a getter, not a setter). There is no safe, mechanical\n * rewrite: the correct fix is to drive the value declaratively through a\n * template binding (`[prop]=\"...\"`) or, when a ComponentRef is genuinely\n * available, `componentRef.setInput('prop', value)`. Both require human\n * judgement, so instead of rewriting we comment the statement out (keeping the\n * build green) and leave a TODO pointing at the manual fix.\n *\n * Only acts when the assignment is the ENTIRE statement\n * (`ExpressionStatement` whose expression is exactly this assignment):\n * ref.prop = value (simple assignment)\n * ref.prop += value, etc. (compound assignment)\n * where `ref` is a tracked EUI/ECL reference and `prop` is in its signal set.\n *\n * When the write is only part of a larger statement (e.g. inside an `if`\n * without a block, or nested in another expression), commenting it out would\n * also remove unrelated logic, so we leave it untouched (it will surface as a\n * compile error the developer must resolve by hand).\n */\nfunction tryInsertWriteTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Only act on assignment targets: `ref.prop = ...` or `ref.prop <op>= ...`\n if (\n !ts.isBinaryExpression(node.parent) ||\n node.parent.left !== node ||\n !isAssignmentOperator(node.parent.operatorToken.kind)\n ) {\n return null;\n }\n\n const assignment = node.parent;\n\n // A plain `=` to a writable signal is migrated to `.set()` by trySetRewrite\n if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken && EUI_WRITABLE_SIGNAL_MAP[cls]?.has(propName)) {\n return null;\n }\n\n // Only comment out when the assignment IS the whole statement — otherwise we'd\n // delete unrelated logic from a larger statement.\n const statement = node.parent.parent;\n if (!statement || !ts.isExpressionStatement(statement) || statement.expression !== assignment) {\n return null;\n }\n\n // The statement must stand on its own (a direct child of a block/source), not\n // be the unbraced body of an `if`/`for`/`while` etc. — commenting those out by\n // line would swallow the surrounding `if (...)` and break the code.\n const parent = statement.parent;\n if (\n !parent ||\n !(ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isModuleBlock(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent))\n ) {\n return null;\n }\n\n const stmtStart = statement.getStart(sourceFile);\n const stmtEnd = statement.getEnd(); // includes the trailing semicolon\n const lineStart = getLineStartPosition(source, stmtStart);\n const indent = source.slice(lineStart, stmtStart);\n\n // Commenting works per line: the statement must be alone on its lines, otherwise\n // (e.g. `run() { ref.prop = 1; }`) we would comment out surrounding code.\n const eol = source.indexOf('\\n', stmtEnd);\n const restOfLine = source.slice(stmtEnd, eol === -1 ? source.length : eol);\n if (indent.trim() !== '' || restOfLine.trim() !== '') {\n return null;\n }\n\n // The statement text, as written (may span multiple lines).\n const statementText = source.slice(stmtStart, stmtEnd);\n\n // Comment out every line of the statement, preserving each line's own\n // indentation (insert `// ` after the leading whitespace). The first line's\n // indentation was stripped by starting the replacement at lineStart, so we\n // re-add it explicitly.\n const commentedStatement = statementText\n .split('\\n')\n .map((line, i) => {\n if (i === 0) return `${indent}// ${line}`;\n const lineIndent = line.slice(0, line.length - line.trimStart().length);\n return `${lineIndent}// ${line.trimStart()}`;\n })\n .join('\\n');\n\n const todo =\n `${indent}// ${WRITE_TODO_MARKER} '${propName}' is now a signal input and cannot be assigned directly.\\n` +\n `${indent}// Set it via a template binding ([${propName}]=\"...\") or componentRef.setInput('${propName}', ...).\\n` +\n `${indent}// The original statement is commented out below so the build does not fail:\\n`;\n\n // Replace the statement (from the start of its line, to drop the original\n // indentation we re-add) with the TODO + commented-out statement.\n return {\n start: lineStart,\n end: stmtEnd,\n replacement: todo + commentedStatement,\n };\n}\n\n/** `ref.prop = value;` on a writable signal -> `ref.prop.set(value);` (two zero-width-safe edits). */\nfunction trySetRewrite(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] {\n const assignment = node.parent;\n if (\n !ts.isBinaryExpression(assignment) ||\n assignment.left !== node ||\n assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||\n !ts.isExpressionStatement(assignment.parent)\n ) {\n return [];\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_WRITABLE_SIGNAL_MAP[cls]?.has(node.name.text)) return [];\n\n return [\n { start: node.getEnd(), end: assignment.right.getStart(sourceFile), replacement: '.set(' },\n { start: assignment.right.getEnd(), end: assignment.right.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** `ref.out.subscribe(...)` -> `outputToObservable(ref.out).subscribe(...)`. */\nfunction tryWrapOutput(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] | null {\n const parent = node.parent;\n if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || !OBSERVABLE_METHODS.has(parent.name.text)) {\n return null;\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n\n const start = node.getStart(sourceFile);\n return [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** Marker for a read of a property that was a @HostBinding and no longer exists. */\nconst HOST_TODO_MARKER = 'TODO(eui-signals):';\n\nfunction tryHostBindingTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_HOST_BINDING_REMOVED_MAP[cls]?.has(propName) || EUI_SIGNAL_MAP[cls]?.has(propName)) return null;\n return flagTodo(\n node,\n sourceFile,\n source,\n `'${propName}' was a @HostBinding`,\n `'${propName}' was a @HostBinding property of ${cls} and no longer exists on the instance ` +\n '(moved to static host metadata). Remove or replace this access.',\n );\n}\n\n/**\n * Inserts a `// TODO(eui-signals): <message>` line above the enclosing statement / class member.\n * `key` identifies the TODO for idempotency (looked for in the comment lines right above).\n */\nfunction flagTodo(node: ts.Node, sourceFile: ts.SourceFile, source: string, key: string, message: string): Edit | null {\n // Anchor on the enclosing statement / class member\n let anchor: ts.Node = node;\n while (\n anchor.parent &&\n !(\n ts.isBlock(anchor.parent) ||\n ts.isSourceFile(anchor.parent) ||\n ts.isModuleBlock(anchor.parent) ||\n ts.isCaseClause(anchor.parent) ||\n ts.isDefaultClause(anchor.parent) ||\n ts.isClassLike(anchor.parent)\n )\n ) {\n anchor = anchor.parent;\n }\n\n const lineStart = getLineStartPosition(source, anchor.getStart(sourceFile));\n const indent = source.slice(lineStart).match(/^[ \\t]*/)![0];\n const text = `${indent}// ${HOST_TODO_MARKER} ${message}\\n`;\n\n // Idempotent: look at the contiguous comment lines right above\n const above = source.slice(0, lineStart).split('\\n').slice(-8).reverse();\n for (const line of above.slice(1)) {\n if (!line.trim().startsWith('//')) break;\n if (line.includes(`${HOST_TODO_MARKER} ${key}`) || line.includes(key)) return null;\n }\n // A single-line anchor like `run() { ... }` shares its line with other code: still fine, the comment goes above the line.\n return { start: lineStart, end: lineStart, replacement: text };\n}\n\n/**\n * An output (OutputEmitterRef) used as a value:\n * - an argument of an rxjs combinator (`merge(ref.out, ...)`, also inside an array) is wrapped in `outputToObservable()`;\n * - any other use that is not `.emit()` / `.subscribe()` & co / already wrapped is flagged with a TODO.\n */\nfunction tryOutputUsage(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): { edits: Edit[]; todo?: Edit | null } | null {\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n const parent = node.parent;\n\n // handled elsewhere (tryWrapOutput) or fine as is\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return null;\n if (ts.isNonNullExpression(parent) || ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent)) return null;\n // declared / written outputs are not reads\n if (ts.isBinaryExpression(parent) && parent.left === node) return null;\n\n // argument of a combinator?\n let arg: ts.Node = node;\n if (ts.isArrayLiteralExpression(arg.parent)) arg = arg.parent;\n const call = arg.parent;\n if (ts.isCallExpression(call) && call.arguments.includes(arg as ts.Expression)) {\n const callee = ts.isIdentifier(call.expression) ? call.expression.text : null;\n if (callee === 'outputToObservable') return null; // already migrated\n if (callee && OBSERVABLE_COMBINATORS.has(callee)) {\n const start = node.getStart(sourceFile);\n return {\n edits: [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ],\n };\n }\n }\n\n return {\n edits: [],\n todo: flagTodo(\n node,\n sourceFile,\n source,\n `output '${node.name.text}'`,\n `output '${node.name.text}' of ${cls} is an OutputEmitterRef, not an Observable. Wrap it with outputToObservable() ` +\n '(@angular/core/rxjs-interop) where an Observable is needed.',\n ),\n };\n}\n\n/** Destructuring of a tracked reference, or storing it in a field/variable we cannot follow. */\nfunction tryAliasTodo(node: ts.Node, euiRefs: Refs, sourceFile: ts.SourceFile, source: string): Edit | null {\n if (ts.isVariableDeclaration(node) && node.initializer && !ts.isIdentifier(node.name)) {\n const cls = trackedClass(node.initializer, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `destructuring of ${cls}`,\n `destructuring of ${cls} cannot be migrated automatically: its signal inputs/outputs must be read as ref.prop() / outputToObservable(ref.out).`,\n );\n }\n }\n if (\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n !ts.isIdentifier(unwrap(node.left)) &&\n ts.isExpressionStatement(node.parent)\n ) {\n const cls = trackedClass(node.right, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `aliasing of ${cls}`,\n `aliasing of ${cls}: this copy is not tracked, so its signal inputs/outputs must be updated manually (ref.prop()).`,\n );\n }\n }\n return null;\n}\n\n/** Adds `outputToObservable` to the file's imports (merging into an existing rxjs-interop import). */\nfunction buildOutputImportEdit(sourceFile: ts.SourceFile): Edit | null {\n let lastImportEnd = 0;\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n lastImportEnd = stmt.getEnd();\n if (!ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== '@angular/core/rxjs-interop') continue;\n const bindings = stmt.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n if (bindings.elements.some((e) => e.name.text === 'outputToObservable')) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (last) {\n return { start: last.getEnd(), end: last.getEnd(), replacement: ', outputToObservable' };\n }\n }\n }\n const line = 'import { outputToObservable } from \\'@angular/core/rxjs-interop\\';';\n return lastImportEnd === 0\n ? { start: 0, end: 0, replacement: `${line}\\n` }\n : { start: lastImportEnd, end: lastImportEnd, replacement: `\\n${line}` };\n}\n\n/** True if `edit`'s position falls within any of the given ranges. */\nfunction isInsideAnyRange(edit: Edit, ranges: Edit[]): boolean {\n return ranges.some((range) => edit.start >= range.start && edit.end <= range.end);\n}\n\n/** Returns the index of the first character of the line containing `pos`. */\nfunction getLineStartPosition(source: string, pos: number): number {\n const newlineIndex = source.lastIndexOf('\\n', pos - 1);\n return newlineIndex === -1 ? 0 : newlineIndex + 1;\n}\n\n// ---------------------------------------------------------------------------\n// Template ref resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a map of template reference variable names (#ref) to EUI class names.\n *\n * Parses the component's template (inline or external) and finds elements like:\n * <eui-alert #myAlert> → myAlert → EuiAlertComponent\n * <input euiAutocomplete #ac> → ac → EuiAutocompleteComponent\n *\n * Returns Map<refName, euiClassName>.\n */\nfunction buildTemplateRefMap(\n sourceFile: ts.SourceFile,\n source: string,\n filePath: string,\n tree: Tree,\n): Map<string, string> {\n const refMap = new Map<string, string>();\n\n // Find @Component decorator\n const componentMeta = findComponentMetadata(sourceFile, source);\n if (!componentMeta) return refMap;\n\n let templateSource: string | null = null;\n\n if (componentMeta.inlineTemplate !== null) {\n templateSource = componentMeta.inlineTemplate;\n } else if (componentMeta.templateUrl) {\n // Resolve templateUrl relative to the TS file\n const dir = filePath.substring(0, filePath.lastIndexOf('/'));\n const templatePath = `${dir}/${componentMeta.templateUrl}`;\n const buffer = tree.read(templatePath);\n if (buffer) {\n templateSource = buffer.toString('utf-8');\n }\n }\n\n if (!templateSource) return refMap;\n\n // Parse the template and collect #refs\n try {\n const parsed = parseTemplate(templateSource, '', { preserveWhitespaces: true });\n collectTemplateRefs(parsed.nodes, refMap);\n } catch {\n // Template parse failure — silently skip (might be malformed or use third-party syntax)\n }\n\n return refMap;\n}\n\n/**\n * Extracts @Component metadata: templateUrl or inline template content.\n */\nfunction findComponentMetadata(\n sourceFile: ts.SourceFile,\n source: string,\n): { templateUrl: string | null; inlineTemplate: string | null } | null {\n let result: { templateUrl: string | null; inlineTemplate: string | null } | null = null;\n\n const visit = (node: ts.Node): void => {\n if (result) return;\n\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {\n const name = getDecoratorName(node.expression);\n if (name !== 'Component') {\n ts.forEachChild(node, visit);\n return;\n }\n\n const args = node.expression.arguments;\n if (args.length === 0 || !ts.isObjectLiteralExpression(args[0])) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const meta: { templateUrl: string | null; inlineTemplate: string | null } = {\n templateUrl: null,\n inlineTemplate: null,\n };\n\n for (const prop of args[0].properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n\n if (prop.name.text === 'templateUrl') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.templateUrl = init.text;\n }\n }\n\n if (prop.name.text === 'template') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.inlineTemplate = init.text;\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n meta.inlineTemplate = init.text;\n }\n }\n }\n\n result = meta;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n return result;\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (ts.isParenthesizedExpression(current)) current = current.expression;\n return current;\n}\n\n/**\n * Recursively walks template AST nodes, collecting #refName → EUI class name mappings.\n *\n * For each element with a template reference (#ref), we try to resolve its EUI class:\n * 1. Match element tag name against EUI_SELECTOR_TO_CLASS (e.g. 'eui-alert' → EuiAlertComponent)\n * 2. Match element attributes against attribute selectors (e.g. [euiAutocomplete] → EuiAutocompleteComponent)\n */\nfunction collectTemplateRefs(nodes: TmplAstNode[], refMap: Map<string, string>): void {\n forEachElement(nodes, (node) => {\n if (node.references === undefined || node.references.length === 0) return;\n const euiClass = resolveElementToEuiClass(node);\n if (!euiClass) return;\n for (const ref of node.references) {\n refMap.set(ref.name, euiClass);\n }\n });\n}\n\n/**\n * Given a template element, resolves it to an EUI class name by checking:\n * 1. Tag name: <eui-alert> → look up 'eui-alert' in EUI_SELECTOR_TO_CLASS\n * 2. Attribute selectors: <input euiAutocomplete> → look up 'input[euiAutocomplete]' or '[euiAutocomplete]'\n */\nfunction resolveElementToEuiClass(element: TmplAstElement): string | null {\n const tag = element.name;\n\n // Direct tag match: eui-alert, eui-dialog, etc.\n if (EUI_SELECTOR_TO_CLASS[tag]) {\n return EUI_SELECTOR_TO_CLASS[tag];\n }\n\n // Attribute selector match: check all attributes against known patterns\n const allAttrNames = [\n ...element.attributes.map((a) => a.name),\n ...element.inputs.map((i) => i.name),\n ];\n\n for (const attrName of allAttrNames) {\n // Try tag[attr] pattern first (e.g. 'button[euiButton]', 'input[euiAutocomplete]')\n const tagAttrSelector = `${tag}[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[tagAttrSelector]) {\n return EUI_SELECTOR_TO_CLASS[tagAttrSelector];\n }\n\n // Try [attr] pattern (e.g. '[euiTooltip]', '[euiLoading]')\n const attrSelector = `[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[attrSelector]) {\n return EUI_SELECTOR_TO_CLASS[attrSelector];\n }\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Edit helpers\n// ---------------------------------------------------------------------------\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n // Descending by position; at equal positions `after` edits are applied first so they land last.\n for (const edit of unique.sort((a, b) => b.start - a.start || Number(!!b.after) - Number(!!a.after))) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}:${edit.replacement}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
5972
|
+
"sourceCode": "import { parseTemplate } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { forEachElement } from '../utils/template-walk';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\n\ninterface ModuleMapping {\n importPath: string;\n selectors: Record<string, string>;\n}\n\nconst MODULE_MAPPINGS: Record<string, ModuleMapping> = {\n EuiAccordionModule: {\n importPath: '@eui/components/eui-accordion',\n selectors: {\n 'eui-accordion': 'EuiAccordionComponent',\n 'eui-accordion-item': 'EuiAccordionItemComponent',\n euiAccordionItemHeader: 'EuiAccordionItemHeaderDirective',\n },\n },\n EuiAlertModule: {\n importPath: '@eui/components/eui-alert',\n selectors: {\n 'eui-alert': 'EuiAlertComponent',\n euiAlert: 'EuiAlertComponent',\n 'eui-alert-title': 'EuiAlertTitleComponent',\n },\n },\n EuiAutocompleteModule: {\n importPath: '@eui/components/eui-autocomplete',\n selectors: {\n 'eui-autocomplete': 'EuiAutocompleteComponent',\n euiAutocomplete: 'EuiAutocompleteComponent',\n 'eui-autocomplete-option': 'EuiAutocompleteOptionComponent',\n 'eui-autocomplete-option-group': 'EuiAutocompleteOptionGroupComponent',\n 'eui-autocomplete-panel': 'EuiAutocompletePanelComponent',\n },\n },\n EuiAvatarModule: {\n importPath: '@eui/components/eui-avatar',\n selectors: {\n 'eui-avatar': 'EuiAvatarComponent',\n euiAvatar: 'EuiAvatarComponent',\n },\n },\n EuiBadgeModule: {\n importPath: '@eui/components/eui-badge',\n selectors: {\n 'eui-badge': 'EuiBadgeComponent',\n euiBadge: 'EuiBadgeComponent',\n },\n },\n EuiBlockContentModule: {\n importPath: '@eui/components/eui-block-content',\n selectors: {\n 'eui-block-content': 'EuiBlockContentComponent',\n },\n },\n EuiBreadcrumbModule: {\n importPath: '@eui/components/eui-breadcrumb',\n selectors: {\n 'eui-breadcrumb': 'EuiBreadcrumbComponent',\n },\n },\n EuiButtonModule: {\n importPath: '@eui/components/eui-button',\n selectors: {\n euiButton: 'EuiButtonComponent',\n },\n },\n EuiButtonGroupModule: {\n importPath: '@eui/components/eui-button-group',\n selectors: {\n 'eui-button-group': 'EuiButtonGroupComponent',\n },\n },\n EuiCardModule: {\n importPath: '@eui/components/eui-card',\n selectors: {\n 'eui-card': 'EuiCardComponent',\n 'eui-card-header': 'EuiCardHeaderComponent',\n 'eui-card-header-title': 'EuiCardHeaderTitleComponent',\n 'eui-card-content': 'EuiCardContentComponent',\n 'eui-card-footer': 'EuiCardFooterComponent',\n 'eui-card-media': 'EuiCardMediaComponent',\n },\n },\n EuiChipModule: {\n importPath: '@eui/components/eui-chip',\n selectors: {\n 'eui-chip': 'EuiChipComponent',\n euiChip: 'EuiChipComponent',\n },\n },\n EuiChipListModule: {\n importPath: '@eui/components/eui-chip-list',\n selectors: {\n 'eui-chip-list': 'EuiChipListComponent',\n },\n },\n EuiChipGroupModule: {\n importPath: '@eui/components/eui-chip-group',\n selectors: {\n 'eui-chip-group': 'EuiChipGroupComponent',\n },\n },\n EuiDashboardCardModule: {\n importPath: '@eui/components/eui-dashboard-card',\n selectors: {\n 'eui-dashboard-card': 'EuiDashboardCardComponent',\n 'eui-dashboard-card-content': 'EuiDashboardCardContentComponent',\n 'eui-dashboard-card-content-header': 'EuiDashboardCardContentHeaderComponent',\n 'eui-dashboard-card-content-body': 'EuiDashboardCardContentBodyComponent',\n 'eui-dashboard-card-content-footer': 'EuiDashboardCardContentFooterComponent',\n },\n },\n EuiDashboardButtonModule: {\n importPath: '@eui/components/eui-dashboard-card',\n selectors: {\n 'eui-dashboard-card': 'EuiDashboardCardComponent',\n 'eui-dashboard-card-content': 'EuiDashboardCardContentComponent',\n 'eui-dashboard-card-content-header': 'EuiDashboardCardContentHeaderComponent',\n 'eui-dashboard-card-content-body': 'EuiDashboardCardContentBodyComponent',\n 'eui-dashboard-card-content-footer': 'EuiDashboardCardContentFooterComponent',\n },\n },\n EuiDatepickerModule: {\n importPath: '@eui/components/eui-datepicker',\n selectors: {\n 'eui-datepicker': 'EuiDatepickerComponent',\n },\n },\n EuiDateRangeSelectorModule: {\n importPath: '@eui/components/eui-date-range-selector',\n selectors: {\n 'eui-date-range-selector': 'EuiDateRangeSelectorComponent',\n },\n },\n EuiDialogModule: {\n importPath: '@eui/components/eui-dialog',\n selectors: {\n 'eui-dialog': 'EuiDialogComponent',\n 'eui-dialog-header': 'EuiDialogHeaderDirective',\n 'eui-dialog-footer': 'EuiDialogFooterDirective',\n 'eui-dialog-container': 'EuiDialogContainerComponent',\n },\n },\n EuiDisableContentModule: {\n importPath: '@eui/components/eui-disable-content',\n selectors: {\n 'eui-disable-content': 'EuiDisableContentComponent',\n },\n },\n EuiDiscussionThreadModule: {\n importPath: '@eui/components/eui-discussion-thread',\n selectors: {\n 'eui-discussion-thread': 'EuiDiscussionThreadComponent',\n 'eui-discussion-thread-item': 'EuiDiscussionThreadItemComponent',\n },\n },\n EuiDropdownModule: {\n importPath: '@eui/components/eui-dropdown',\n selectors: {\n 'eui-dropdown': 'EuiDropdownComponent',\n },\n },\n EuiFeedbackMessageModule: {\n importPath: '@eui/components/eui-feedback-message',\n selectors: {\n 'eui-feedback-message': 'EuiFeedbackMessageComponent',\n },\n },\n EuiFieldsetModule: {\n importPath: '@eui/components/eui-fieldset',\n selectors: {\n 'eui-fieldset': 'EuiFieldsetComponent',\n euiFieldsetLabelRightContent: 'EuiFieldsetLabelRightContentTagDirective',\n euiFieldsetLabelExtraContent: 'EuiFieldsetLabelExtraContentTagDirective',\n },\n },\n EuiFileUploadModule: {\n importPath: '@eui/components/eui-file-upload',\n selectors: {\n 'eui-file-upload': 'EuiFileUploadComponent',\n },\n },\n EuiGrowlModule: {\n importPath: '@eui/components/eui-growl',\n selectors: {\n 'eui-growl': 'EuiGrowlComponent',\n },\n },\n EuiIconModule: {\n importPath: '@eui/components/eui-icon',\n selectors: {\n 'eui-icon-svg': 'EuiIconSvgComponent',\n euiIconSvg: 'EuiIconSvgComponent',\n },\n },\n EuiIconButtonModule: {\n importPath: '@eui/components/eui-icon-button',\n selectors: {\n 'eui-icon-button': 'EuiIconButtonComponent',\n },\n },\n EuiIconToggleModule: {\n importPath: '@eui/components/eui-icon-toggle',\n selectors: {\n 'eui-icon-toggle': 'EuiIconToggleComponent',\n },\n },\n EuiInputCheckboxModule: {\n importPath: '@eui/components/eui-input-checkbox',\n selectors: {\n euiInputCheckBox: 'EuiInputCheckboxComponent',\n },\n },\n EuiInputGroupModule: {\n importPath: '@eui/components/eui-input-group',\n selectors: {\n euiInputGroup: 'EuiInputGroupComponent',\n 'eui-input-group-addon': 'EuiInputGroupAddOnComponent',\n euiInputGroupAddOn: 'EuiInputGroupAddOnComponent',\n 'eui-input-group-addon-item': 'EuiInputGroupAddOnItemComponent',\n euiInputGroupAddOnItem: 'EuiInputGroupAddOnItemComponent',\n },\n },\n EuiInputNumberModule: {\n importPath: '@eui/components/eui-input-number',\n selectors: {\n euiInputNumber: 'EuiInputNumberComponent',\n },\n },\n EuiInputRadioModule: {\n importPath: '@eui/components/eui-input-radio',\n selectors: {\n euiInputRadio: 'EuiInputRadioComponent',\n },\n },\n EuiInputTextModule: {\n importPath: '@eui/components/eui-input-text',\n selectors: {\n euiInputText: 'EuiInputTextComponent',\n },\n },\n EuiLabelModule: {\n importPath: '@eui/components/eui-label',\n selectors: {\n 'eui-label': 'EuiLabelComponent',\n euiLabel: 'EuiLabelComponent',\n },\n },\n EuiListModule: {\n importPath: '@eui/components/eui-list',\n selectors: {\n 'eui-list': 'EuiListComponent',\n euiList: 'EuiListComponent',\n 'eui-list-item': 'EuiListItemComponent',\n euiListItem: 'EuiListItemComponent',\n },\n },\n EuiMenuModule: {\n importPath: '@eui/components/eui-menu',\n selectors: {\n 'eui-menu': 'EuiMenuComponent',\n 'eui-menu-item': 'EuiMenuItemComponent',\n },\n },\n EuiMessageBoxModule: {\n importPath: '@eui/components/eui-message-box',\n selectors: {\n 'eui-message-box': 'EuiMessageBoxComponent',\n 'eui-message-box-footer': 'EuiMessageBoxFooterDirective',\n },\n },\n EuiOverlayModule: {\n importPath: '@eui/components/eui-overlay',\n selectors: {\n 'eui-overlay': 'EuiOverlayComponent',\n },\n },\n EuiPageModule: {\n importPath: '@eui/components/eui-page',\n selectors: {\n 'eui-page': 'EuiPageComponent',\n },\n },\n EuiPaginatorModule: {\n importPath: '@eui/components/eui-paginator',\n selectors: {\n 'eui-paginator': 'EuiPaginatorComponent',\n },\n },\n EuiPopoverModule: {\n importPath: '@eui/components/eui-popover',\n selectors: {\n 'eui-popover': 'EuiPopoverComponent',\n },\n },\n EuiProgressBarModule: {\n importPath: '@eui/components/eui-progress-bar',\n selectors: {\n 'eui-progress-bar': 'EuiProgressBarComponent',\n },\n },\n EuiProgressCircleModule: {\n importPath: '@eui/components/eui-progress-circle',\n selectors: {\n 'eui-progress-circle': 'EuiProgressCircleComponent',\n },\n },\n EuiSelectModule: {\n importPath: '@eui/components/eui-select',\n selectors: {\n euiSelect: 'EuiSelectComponent',\n },\n },\n EuiSidebarMenuModule: {\n importPath: '@eui/components/eui-sidebar-menu',\n selectors: {\n 'eui-sidebar-menu': 'EuiSidebarMenuComponent',\n },\n },\n EuiSkeletonModule: {\n importPath: '@eui/components/eui-skeleton',\n selectors: {\n 'eui-skeleton': 'EuiSkeletonComponent',\n },\n },\n EuiSlideToggleModule: {\n importPath: '@eui/components/eui-slide-toggle',\n selectors: {\n 'eui-slide-toggle': 'EuiSlideToggleComponent',\n },\n },\n EuiTableModule: {\n importPath: '@eui/components/eui-table',\n selectors: {\n 'eui-table': 'EuiTableComponent',\n euiTable: 'EuiTableComponent',\n 'eui-table-filter': 'EuiTableFilterComponent',\n isSortable: 'EuiTableSortableColComponent',\n isStickyCol: 'EuiTableStickyColDirective',\n isHeaderSelectable: 'EuiTableSelectableHeaderComponent',\n isDataSelectable: 'EuiTableSelectableRowComponent',\n isExpandableRow: 'EuiTableExpandableRowDirective',\n },\n },\n EuiTableV2Module: {\n importPath: '@eui/components/eui-table',\n selectors: {\n 'eui-table': 'EuiTableComponent',\n euiTable: 'EuiTableComponent',\n 'eui-table-filter': 'EuiTableFilterComponent',\n isSortable: 'EuiTableSortableColComponent',\n isStickyCol: 'EuiTableStickyColDirective',\n isHeaderSelectable: 'EuiTableSelectableHeaderComponent',\n isDataSelectable: 'EuiTableSelectableRowComponent',\n isExpandableRow: 'EuiTableExpandableRowDirective',\n },\n },\n EuiTabsModule: {\n importPath: '@eui/components/eui-tabs',\n selectors: {\n 'eui-tabs': 'EuiTabsComponent',\n 'eui-tab': 'EuiTabComponent',\n 'eui-tab-header': 'EuiTabHeaderComponent',\n 'eui-tab-body': 'EuiTabBodyComponent',\n },\n },\n EuiTextAreaModule: {\n importPath: '@eui/components/eui-textarea',\n selectors: {\n euiTextArea: 'EuiTextareaComponent',\n },\n },\n EuiTimelineModule: {\n importPath: '@eui/components/eui-timeline',\n selectors: {\n 'eui-timeline': 'EuiTimelineComponent',\n 'eui-timeline-item': 'EuiTimelineItemComponent',\n },\n },\n EuiTimepickerModule: {\n importPath: '@eui/components/eui-timepicker',\n selectors: {\n 'eui-timepicker': 'EuiTimepickerComponent',\n },\n },\n EuiTreeModule: {\n importPath: '@eui/components/eui-tree',\n selectors: {\n 'eui-tree': 'EuiTreeComponent',\n },\n },\n EuiTreeListModule: {\n importPath: '@eui/components/eui-tree-list',\n selectors: {\n 'eui-tree-list': 'EuiTreeListComponent',\n 'eui-tree-list-item': 'EuiTreeListItemComponent',\n },\n },\n EuiUserProfileModule: {\n importPath: '@eui/components/eui-user-profile',\n selectors: {\n 'eui-user-profile': 'EuiUserProfileComponent',\n },\n },\n EuiWizardModule: {\n importPath: '@eui/components/eui-wizard',\n selectors: {\n 'eui-wizard': 'EuiWizardComponent',\n 'eui-wizard-step': 'EuiWizardStepComponent',\n },\n },\n EuiTooltipDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiTooltip: 'EuiTooltipDirective',\n },\n },\n EuiTemplateDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiTemplate: 'EuiTemplateDirective',\n },\n },\n EuiResizableDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiResizable: 'EuiResizableDirective',\n 'eui-resizable': 'EuiResizableComponent',\n },\n },\n EuiMaxLengthDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiEditorMaxlength: 'EuiMaxLengthDirective',\n },\n },\n EuiTruncatePipeModule: {\n importPath: '@eui/components/pipes',\n selectors: {\n euiTruncate: 'EuiTruncatePipe',\n },\n },\n EuiLayoutModule: {\n importPath: '@eui/components/layout',\n selectors: {\n 'eui-app': 'EuiAppComponent',\n 'eui-header': 'EuiHeaderComponent',\n 'eui-footer': 'EuiFooterComponent',\n 'eui-toolbar': 'EuiToolbarComponent',\n 'eui-sidebar-toggle': 'EuiSidebarToggleComponent',\n },\n },\n};\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\nexport function migrateToStandalone(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const allModuleNames = Object.keys(MODULE_MAPPINGS);\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const source = buffer.toString('utf-8');\n if (!allModuleNames.some((m) => source.includes(m))) return;\n\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);\n const componentDecorators = findComponentDecorators(sourceFile);\n\n for (const decorator of componentDecorators) {\n const importsNode = findImportsArrayNode(decorator);\n if (!importsNode) continue;\n\n const currentSource = tree.read(path)!.toString('utf-8');\n const modulesInArray = allModuleNames.filter((m) => hasModuleInArray(importsNode, m, source));\n if (modulesInArray.length === 0) continue;\n\n const templateSelectors = getTemplateSelectors(tree, path, decorator, source);\n const replacements = buildReplacements(modulesInArray, templateSelectors);\n if (replacements.size === 0) continue;\n\n const result = applyReplacements(currentSource, path, replacements);\n if (options.dryRun) {\n logDryRun(context, `Would replace module imports with standalone imports in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n }\n });\n\n context.logger.info('Migration to standalone imports complete.');\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\nfunction buildReplacements(moduleNames: string[], templateSelectors: Set<string>): Map<string, { components: string[]; importPath: string }> {\n const map = new Map<string, { components: string[]; importPath: string }>();\n\n for (const moduleName of moduleNames) {\n const mapping = MODULE_MAPPINGS[moduleName];\n const components: string[] = [];\n\n for (const [selector, component] of Object.entries(mapping.selectors)) {\n if (templateSelectors.has(selector)) {\n components.push(component);\n }\n }\n\n if (components.length > 0) {\n map.set(moduleName, { components: [...new Set(components)].sort(), importPath: mapping.importPath });\n }\n }\n\n return map;\n}\n\nfunction findComponentDecorators(sourceFile: ts.SourceFile): ts.Decorator[] {\n const decorators: ts.Decorator[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isClassDeclaration(node)) {\n const decs = ts.getDecorators(node);\n if (decs) {\n for (const dec of decs) {\n if (ts.isCallExpression(dec.expression) && ts.isIdentifier(dec.expression.expression) && dec.expression.expression.text === 'Component') {\n decorators.push(dec);\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return decorators;\n}\n\nfunction findImportsArrayNode(decorator: ts.Decorator): ts.ArrayLiteralExpression | undefined {\n const call = decorator.expression as ts.CallExpression;\n const metadata = call.arguments[0];\n if (!ts.isObjectLiteralExpression(metadata)) return undefined;\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'imports') {\n if (ts.isArrayLiteralExpression(prop.initializer)) {\n return prop.initializer;\n }\n }\n }\n return undefined;\n}\n\nfunction hasModuleInArray(array: ts.ArrayLiteralExpression, moduleName: string, source: string): boolean {\n return array.elements.some((el) => source.slice(el.getStart(), el.getEnd()).trim() === moduleName);\n}\n\nfunction getTemplateSelectors(tree: Tree, tsPath: string, decorator: ts.Decorator, source: string): Set<string> {\n const call = decorator.expression as ts.CallExpression;\n const metadata = call.arguments[0] as ts.ObjectLiteralExpression;\n const allSelectors = Object.values(MODULE_MAPPINGS).flatMap((m) => Object.keys(m.selectors));\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'template') {\n const init = prop.initializer;\n if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {\n return findSelectorsInTemplate(init.text, allSelectors);\n }\n }\n }\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'templateUrl') {\n if (ts.isStringLiteral(prop.initializer)) {\n const dir = tsPath.substring(0, tsPath.lastIndexOf('/'));\n const templateBuffer = tree.read(`${dir}/${prop.initializer.text}`);\n if (templateBuffer) {\n return findSelectorsInTemplate(templateBuffer.toString('utf-8'), allSelectors);\n }\n }\n }\n }\n\n return new Set();\n}\n\nfunction findSelectorsInTemplate(html: string, knownSelectors: string[]): Set<string> {\n const selectors = new Set<string>();\n const parsed = parseTemplate(html, '', { preserveWhitespaces: true });\n\n forEachElement(parsed.nodes, (node) => {\n if (knownSelectors.includes(node.name)) selectors.add(node.name);\n for (const attr of node.attributes) {\n if (knownSelectors.includes(attr.name)) selectors.add(attr.name);\n }\n });\n return selectors;\n}\n\nfunction applyReplacements(source: string, filePath: string, replacements: Map<string, { components: string[]; importPath: string }>): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n let result = replaceInImportsArray(source, sourceFile, replacements);\n result = updateEsImports(result, filePath, replacements);\n return result;\n}\n\nfunction replaceInImportsArray(source: string, sourceFile: ts.SourceFile, replacements: Map<string, { components: string[]; importPath: string }>): string {\n let result = source;\n const visit = (node: ts.Node): void => {\n if (ts.isClassDeclaration(node)) {\n const decs = ts.getDecorators(node);\n if (!decs) return;\n for (const dec of decs) {\n if (!ts.isCallExpression(dec.expression) || !ts.isIdentifier(dec.expression.expression) || dec.expression.expression.text !== 'Component') continue;\n const metadata = dec.expression.arguments[0];\n if (!ts.isObjectLiteralExpression(metadata)) continue;\n for (const prop of metadata.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name) || prop.name.text !== 'imports') continue;\n if (!ts.isArrayLiteralExpression(prop.initializer)) continue;\n const newElements = prop.initializer.elements\n .map((el) => {\n const text = result.slice(el.getStart(sourceFile), el.getEnd()).trim();\n const replacement = replacements.get(text);\n return replacement ? replacement.components.join(', ') : text;\n })\n .join(', ');\n result = result.slice(0, prop.initializer.getStart(sourceFile) + 1) + newElements + result.slice(prop.initializer.getEnd() - 1);\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return result;\n}\n\nfunction updateEsImports(source: string, filePath: string, replacements: Map<string, { components: string[]; importPath: string }>): string {\n let result = source;\n\n for (const [moduleName, { components, importPath }] of replacements) {\n const sf = ts.createSourceFile(filePath, result, ts.ScriptTarget.Latest, true);\n\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !stmt.importClause?.namedBindings || !ts.isNamedImports(stmt.importClause.namedBindings)) continue;\n const namedBindings = stmt.importClause.namedBindings;\n const importNames = namedBindings.elements.map((el) => el.name.text);\n if (!importNames.includes(moduleName)) continue;\n\n const moduleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n const remaining = importNames.filter((n) => n !== moduleName);\n const toAdd = components.filter((c) => !importNames.includes(c));\n\n if (moduleSpecifier === importPath) {\n const newNames = [...remaining, ...toAdd].sort();\n const newClause = `{ ${newNames.join(', ')} }`;\n result = result.slice(0, namedBindings.getStart(sf)) + newClause + result.slice(namedBindings.getEnd());\n } else {\n if (remaining.length > 0) {\n const newClause = `{ ${remaining.join(', ')} }`;\n result = result.slice(0, namedBindings.getStart(sf)) + newClause + result.slice(namedBindings.getEnd());\n } else {\n result = result.slice(0, stmt.getStart(sf)) + result.slice(stmt.getEnd()).replace(/^\\r?\\n/, '');\n }\n\n if (toAdd.length > 0) {\n const updatedSf = ts.createSourceFile(filePath, result, ts.ScriptTarget.Latest, true);\n const existing = updatedSf.statements.find(\n (s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === importPath,\n ) as ts.ImportDeclaration | undefined;\n\n if (existing?.importClause?.namedBindings && ts.isNamedImports(existing.importClause.namedBindings)) {\n const existingNames = existing.importClause.namedBindings.elements.map((el) => el.name.text);\n const allNames = [...new Set([...existingNames, ...toAdd])].sort();\n const newClause = `{ ${allNames.join(', ')} }`;\n result = result.slice(0, existing.importClause.namedBindings.getStart(updatedSf)) + newClause + result.slice(existing.importClause.namedBindings.getEnd());\n } else {\n const newImport = `import { ${toAdd.join(', ')} } from '${importPath}';\\n`;\n result = newImport + result;\n }\n }\n }\n break;\n }\n }\n\n return result;\n}\n",
|
|
5973
5973
|
"displayName": "Schema",
|
|
5974
5974
|
"properties": [
|
|
5975
5975
|
{
|
|
@@ -5981,7 +5981,7 @@
|
|
|
5981
5981
|
"indexKey": "",
|
|
5982
5982
|
"optional": true,
|
|
5983
5983
|
"description": "",
|
|
5984
|
-
"line":
|
|
5984
|
+
"line": 461,
|
|
5985
5985
|
"rawdescription": "\n"
|
|
5986
5986
|
},
|
|
5987
5987
|
{
|
|
@@ -5993,7 +5993,7 @@
|
|
|
5993
5993
|
"indexKey": "",
|
|
5994
5994
|
"optional": true,
|
|
5995
5995
|
"description": "",
|
|
5996
|
-
"line":
|
|
5996
|
+
"line": 460,
|
|
5997
5997
|
"rawdescription": "\n"
|
|
5998
5998
|
}
|
|
5999
5999
|
],
|
|
@@ -6011,12 +6011,12 @@
|
|
|
6011
6011
|
},
|
|
6012
6012
|
{
|
|
6013
6013
|
"name": "Schema",
|
|
6014
|
-
"id": "interface-Schema-
|
|
6015
|
-
"file": "packages/core/schematics/migrate-to-
|
|
6014
|
+
"id": "interface-Schema-bdeb132e57974e9cf0ecc701fc740055cb5bf71469a03b748668e1c33e6365cc60701d8ed980432fc5cd62827c42a92a1166a7cfa04156ee9c1f5e504c35781c-43",
|
|
6015
|
+
"file": "packages/core/schematics/migrate-to-signals/index.ts",
|
|
6016
6016
|
"deprecated": false,
|
|
6017
6017
|
"deprecationMessage": "",
|
|
6018
6018
|
"type": "interface",
|
|
6019
|
-
"sourceCode": "import { parseTemplate } from '@angular/compiler';\nimport { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport * as ts from 'typescript';\nimport { forEachElement } from '../utils/template-walk';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\n\ninterface ModuleMapping {\n importPath: string;\n selectors: Record<string, string>;\n}\n\nconst MODULE_MAPPINGS: Record<string, ModuleMapping> = {\n EuiAccordionModule: {\n importPath: '@eui/components/eui-accordion',\n selectors: {\n 'eui-accordion': 'EuiAccordionComponent',\n 'eui-accordion-item': 'EuiAccordionItemComponent',\n euiAccordionItemHeader: 'EuiAccordionItemHeaderDirective',\n },\n },\n EuiAlertModule: {\n importPath: '@eui/components/eui-alert',\n selectors: {\n 'eui-alert': 'EuiAlertComponent',\n euiAlert: 'EuiAlertComponent',\n 'eui-alert-title': 'EuiAlertTitleComponent',\n },\n },\n EuiAutocompleteModule: {\n importPath: '@eui/components/eui-autocomplete',\n selectors: {\n 'eui-autocomplete': 'EuiAutocompleteComponent',\n euiAutocomplete: 'EuiAutocompleteComponent',\n 'eui-autocomplete-option': 'EuiAutocompleteOptionComponent',\n 'eui-autocomplete-option-group': 'EuiAutocompleteOptionGroupComponent',\n 'eui-autocomplete-panel': 'EuiAutocompletePanelComponent',\n },\n },\n EuiAvatarModule: {\n importPath: '@eui/components/eui-avatar',\n selectors: {\n 'eui-avatar': 'EuiAvatarComponent',\n euiAvatar: 'EuiAvatarComponent',\n },\n },\n EuiBadgeModule: {\n importPath: '@eui/components/eui-badge',\n selectors: {\n 'eui-badge': 'EuiBadgeComponent',\n euiBadge: 'EuiBadgeComponent',\n },\n },\n EuiBlockContentModule: {\n importPath: '@eui/components/eui-block-content',\n selectors: {\n 'eui-block-content': 'EuiBlockContentComponent',\n },\n },\n EuiBreadcrumbModule: {\n importPath: '@eui/components/eui-breadcrumb',\n selectors: {\n 'eui-breadcrumb': 'EuiBreadcrumbComponent',\n },\n },\n EuiButtonModule: {\n importPath: '@eui/components/eui-button',\n selectors: {\n euiButton: 'EuiButtonComponent',\n },\n },\n EuiButtonGroupModule: {\n importPath: '@eui/components/eui-button-group',\n selectors: {\n 'eui-button-group': 'EuiButtonGroupComponent',\n },\n },\n EuiCardModule: {\n importPath: '@eui/components/eui-card',\n selectors: {\n 'eui-card': 'EuiCardComponent',\n 'eui-card-header': 'EuiCardHeaderComponent',\n 'eui-card-header-title': 'EuiCardHeaderTitleComponent',\n 'eui-card-content': 'EuiCardContentComponent',\n 'eui-card-footer': 'EuiCardFooterComponent',\n 'eui-card-media': 'EuiCardMediaComponent',\n },\n },\n EuiChipModule: {\n importPath: '@eui/components/eui-chip',\n selectors: {\n 'eui-chip': 'EuiChipComponent',\n euiChip: 'EuiChipComponent',\n },\n },\n EuiChipListModule: {\n importPath: '@eui/components/eui-chip-list',\n selectors: {\n 'eui-chip-list': 'EuiChipListComponent',\n },\n },\n EuiChipGroupModule: {\n importPath: '@eui/components/eui-chip-group',\n selectors: {\n 'eui-chip-group': 'EuiChipGroupComponent',\n },\n },\n EuiDashboardCardModule: {\n importPath: '@eui/components/eui-dashboard-card',\n selectors: {\n 'eui-dashboard-card': 'EuiDashboardCardComponent',\n 'eui-dashboard-card-content': 'EuiDashboardCardContentComponent',\n 'eui-dashboard-card-content-header': 'EuiDashboardCardContentHeaderComponent',\n 'eui-dashboard-card-content-body': 'EuiDashboardCardContentBodyComponent',\n 'eui-dashboard-card-content-footer': 'EuiDashboardCardContentFooterComponent',\n },\n },\n EuiDashboardButtonModule: {\n importPath: '@eui/components/eui-dashboard-card',\n selectors: {\n 'eui-dashboard-card': 'EuiDashboardCardComponent',\n 'eui-dashboard-card-content': 'EuiDashboardCardContentComponent',\n 'eui-dashboard-card-content-header': 'EuiDashboardCardContentHeaderComponent',\n 'eui-dashboard-card-content-body': 'EuiDashboardCardContentBodyComponent',\n 'eui-dashboard-card-content-footer': 'EuiDashboardCardContentFooterComponent',\n },\n },\n EuiDatepickerModule: {\n importPath: '@eui/components/eui-datepicker',\n selectors: {\n 'eui-datepicker': 'EuiDatepickerComponent',\n },\n },\n EuiDateRangeSelectorModule: {\n importPath: '@eui/components/eui-date-range-selector',\n selectors: {\n 'eui-date-range-selector': 'EuiDateRangeSelectorComponent',\n },\n },\n EuiDialogModule: {\n importPath: '@eui/components/eui-dialog',\n selectors: {\n 'eui-dialog': 'EuiDialogComponent',\n 'eui-dialog-header': 'EuiDialogHeaderDirective',\n 'eui-dialog-footer': 'EuiDialogFooterDirective',\n 'eui-dialog-container': 'EuiDialogContainerComponent',\n },\n },\n EuiDisableContentModule: {\n importPath: '@eui/components/eui-disable-content',\n selectors: {\n 'eui-disable-content': 'EuiDisableContentComponent',\n },\n },\n EuiDiscussionThreadModule: {\n importPath: '@eui/components/eui-discussion-thread',\n selectors: {\n 'eui-discussion-thread': 'EuiDiscussionThreadComponent',\n 'eui-discussion-thread-item': 'EuiDiscussionThreadItemComponent',\n },\n },\n EuiDropdownModule: {\n importPath: '@eui/components/eui-dropdown',\n selectors: {\n 'eui-dropdown': 'EuiDropdownComponent',\n },\n },\n EuiFeedbackMessageModule: {\n importPath: '@eui/components/eui-feedback-message',\n selectors: {\n 'eui-feedback-message': 'EuiFeedbackMessageComponent',\n },\n },\n EuiFieldsetModule: {\n importPath: '@eui/components/eui-fieldset',\n selectors: {\n 'eui-fieldset': 'EuiFieldsetComponent',\n euiFieldsetLabelRightContent: 'EuiFieldsetLabelRightContentTagDirective',\n euiFieldsetLabelExtraContent: 'EuiFieldsetLabelExtraContentTagDirective',\n },\n },\n EuiFileUploadModule: {\n importPath: '@eui/components/eui-file-upload',\n selectors: {\n 'eui-file-upload': 'EuiFileUploadComponent',\n },\n },\n EuiGrowlModule: {\n importPath: '@eui/components/eui-growl',\n selectors: {\n 'eui-growl': 'EuiGrowlComponent',\n },\n },\n EuiIconModule: {\n importPath: '@eui/components/eui-icon',\n selectors: {\n 'eui-icon-svg': 'EuiIconSvgComponent',\n euiIconSvg: 'EuiIconSvgComponent',\n },\n },\n EuiIconButtonModule: {\n importPath: '@eui/components/eui-icon-button',\n selectors: {\n 'eui-icon-button': 'EuiIconButtonComponent',\n },\n },\n EuiIconToggleModule: {\n importPath: '@eui/components/eui-icon-toggle',\n selectors: {\n 'eui-icon-toggle': 'EuiIconToggleComponent',\n },\n },\n EuiInputCheckboxModule: {\n importPath: '@eui/components/eui-input-checkbox',\n selectors: {\n euiInputCheckBox: 'EuiInputCheckboxComponent',\n },\n },\n EuiInputGroupModule: {\n importPath: '@eui/components/eui-input-group',\n selectors: {\n euiInputGroup: 'EuiInputGroupComponent',\n 'eui-input-group-addon': 'EuiInputGroupAddOnComponent',\n euiInputGroupAddOn: 'EuiInputGroupAddOnComponent',\n 'eui-input-group-addon-item': 'EuiInputGroupAddOnItemComponent',\n euiInputGroupAddOnItem: 'EuiInputGroupAddOnItemComponent',\n },\n },\n EuiInputNumberModule: {\n importPath: '@eui/components/eui-input-number',\n selectors: {\n euiInputNumber: 'EuiInputNumberComponent',\n },\n },\n EuiInputRadioModule: {\n importPath: '@eui/components/eui-input-radio',\n selectors: {\n euiInputRadio: 'EuiInputRadioComponent',\n },\n },\n EuiInputTextModule: {\n importPath: '@eui/components/eui-input-text',\n selectors: {\n euiInputText: 'EuiInputTextComponent',\n },\n },\n EuiLabelModule: {\n importPath: '@eui/components/eui-label',\n selectors: {\n 'eui-label': 'EuiLabelComponent',\n euiLabel: 'EuiLabelComponent',\n },\n },\n EuiListModule: {\n importPath: '@eui/components/eui-list',\n selectors: {\n 'eui-list': 'EuiListComponent',\n euiList: 'EuiListComponent',\n 'eui-list-item': 'EuiListItemComponent',\n euiListItem: 'EuiListItemComponent',\n },\n },\n EuiMenuModule: {\n importPath: '@eui/components/eui-menu',\n selectors: {\n 'eui-menu': 'EuiMenuComponent',\n 'eui-menu-item': 'EuiMenuItemComponent',\n },\n },\n EuiMessageBoxModule: {\n importPath: '@eui/components/eui-message-box',\n selectors: {\n 'eui-message-box': 'EuiMessageBoxComponent',\n 'eui-message-box-footer': 'EuiMessageBoxFooterDirective',\n },\n },\n EuiOverlayModule: {\n importPath: '@eui/components/eui-overlay',\n selectors: {\n 'eui-overlay': 'EuiOverlayComponent',\n },\n },\n EuiPageModule: {\n importPath: '@eui/components/eui-page',\n selectors: {\n 'eui-page': 'EuiPageComponent',\n },\n },\n EuiPaginatorModule: {\n importPath: '@eui/components/eui-paginator',\n selectors: {\n 'eui-paginator': 'EuiPaginatorComponent',\n },\n },\n EuiPopoverModule: {\n importPath: '@eui/components/eui-popover',\n selectors: {\n 'eui-popover': 'EuiPopoverComponent',\n },\n },\n EuiProgressBarModule: {\n importPath: '@eui/components/eui-progress-bar',\n selectors: {\n 'eui-progress-bar': 'EuiProgressBarComponent',\n },\n },\n EuiProgressCircleModule: {\n importPath: '@eui/components/eui-progress-circle',\n selectors: {\n 'eui-progress-circle': 'EuiProgressCircleComponent',\n },\n },\n EuiSelectModule: {\n importPath: '@eui/components/eui-select',\n selectors: {\n euiSelect: 'EuiSelectComponent',\n },\n },\n EuiSidebarMenuModule: {\n importPath: '@eui/components/eui-sidebar-menu',\n selectors: {\n 'eui-sidebar-menu': 'EuiSidebarMenuComponent',\n },\n },\n EuiSkeletonModule: {\n importPath: '@eui/components/eui-skeleton',\n selectors: {\n 'eui-skeleton': 'EuiSkeletonComponent',\n },\n },\n EuiSlideToggleModule: {\n importPath: '@eui/components/eui-slide-toggle',\n selectors: {\n 'eui-slide-toggle': 'EuiSlideToggleComponent',\n },\n },\n EuiTableModule: {\n importPath: '@eui/components/eui-table',\n selectors: {\n 'eui-table': 'EuiTableComponent',\n euiTable: 'EuiTableComponent',\n 'eui-table-filter': 'EuiTableFilterComponent',\n isSortable: 'EuiTableSortableColComponent',\n isStickyCol: 'EuiTableStickyColDirective',\n isHeaderSelectable: 'EuiTableSelectableHeaderComponent',\n isDataSelectable: 'EuiTableSelectableRowComponent',\n isExpandableRow: 'EuiTableExpandableRowDirective',\n },\n },\n EuiTableV2Module: {\n importPath: '@eui/components/eui-table',\n selectors: {\n 'eui-table': 'EuiTableComponent',\n euiTable: 'EuiTableComponent',\n 'eui-table-filter': 'EuiTableFilterComponent',\n isSortable: 'EuiTableSortableColComponent',\n isStickyCol: 'EuiTableStickyColDirective',\n isHeaderSelectable: 'EuiTableSelectableHeaderComponent',\n isDataSelectable: 'EuiTableSelectableRowComponent',\n isExpandableRow: 'EuiTableExpandableRowDirective',\n },\n },\n EuiTabsModule: {\n importPath: '@eui/components/eui-tabs',\n selectors: {\n 'eui-tabs': 'EuiTabsComponent',\n 'eui-tab': 'EuiTabComponent',\n 'eui-tab-header': 'EuiTabHeaderComponent',\n 'eui-tab-body': 'EuiTabBodyComponent',\n },\n },\n EuiTextAreaModule: {\n importPath: '@eui/components/eui-textarea',\n selectors: {\n euiTextArea: 'EuiTextareaComponent',\n },\n },\n EuiTimelineModule: {\n importPath: '@eui/components/eui-timeline',\n selectors: {\n 'eui-timeline': 'EuiTimelineComponent',\n 'eui-timeline-item': 'EuiTimelineItemComponent',\n },\n },\n EuiTimepickerModule: {\n importPath: '@eui/components/eui-timepicker',\n selectors: {\n 'eui-timepicker': 'EuiTimepickerComponent',\n },\n },\n EuiTreeModule: {\n importPath: '@eui/components/eui-tree',\n selectors: {\n 'eui-tree': 'EuiTreeComponent',\n },\n },\n EuiTreeListModule: {\n importPath: '@eui/components/eui-tree-list',\n selectors: {\n 'eui-tree-list': 'EuiTreeListComponent',\n 'eui-tree-list-item': 'EuiTreeListItemComponent',\n },\n },\n EuiUserProfileModule: {\n importPath: '@eui/components/eui-user-profile',\n selectors: {\n 'eui-user-profile': 'EuiUserProfileComponent',\n },\n },\n EuiWizardModule: {\n importPath: '@eui/components/eui-wizard',\n selectors: {\n 'eui-wizard': 'EuiWizardComponent',\n 'eui-wizard-step': 'EuiWizardStepComponent',\n },\n },\n EuiTooltipDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiTooltip: 'EuiTooltipDirective',\n },\n },\n EuiTemplateDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiTemplate: 'EuiTemplateDirective',\n },\n },\n EuiResizableDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiResizable: 'EuiResizableDirective',\n 'eui-resizable': 'EuiResizableComponent',\n },\n },\n EuiMaxLengthDirectiveModule: {\n importPath: '@eui/components/directives',\n selectors: {\n euiEditorMaxlength: 'EuiMaxLengthDirective',\n },\n },\n EuiTruncatePipeModule: {\n importPath: '@eui/components/pipes',\n selectors: {\n euiTruncate: 'EuiTruncatePipe',\n },\n },\n EuiLayoutModule: {\n importPath: '@eui/components/layout',\n selectors: {\n 'eui-app': 'EuiAppComponent',\n 'eui-header': 'EuiHeaderComponent',\n 'eui-footer': 'EuiFooterComponent',\n 'eui-toolbar': 'EuiToolbarComponent',\n 'eui-sidebar-toggle': 'EuiSidebarToggleComponent',\n },\n },\n};\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\nexport function migrateToStandalone(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n const allModuleNames = Object.keys(MODULE_MAPPINGS);\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const source = buffer.toString('utf-8');\n if (!allModuleNames.some((m) => source.includes(m))) return;\n\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);\n const componentDecorators = findComponentDecorators(sourceFile);\n\n for (const decorator of componentDecorators) {\n const importsNode = findImportsArrayNode(decorator);\n if (!importsNode) continue;\n\n const currentSource = tree.read(path)!.toString('utf-8');\n const modulesInArray = allModuleNames.filter((m) => hasModuleInArray(importsNode, m, source));\n if (modulesInArray.length === 0) continue;\n\n const templateSelectors = getTemplateSelectors(tree, path, decorator, source);\n const replacements = buildReplacements(modulesInArray, templateSelectors);\n if (replacements.size === 0) continue;\n\n const result = applyReplacements(currentSource, path, replacements);\n if (options.dryRun) {\n logDryRun(context, `Would replace module imports with standalone imports in ${path}`);\n } else {\n tree.overwrite(path, result);\n }\n }\n });\n\n context.logger.info('Migration to standalone imports complete.');\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n\nfunction buildReplacements(moduleNames: string[], templateSelectors: Set<string>): Map<string, { components: string[]; importPath: string }> {\n const map = new Map<string, { components: string[]; importPath: string }>();\n\n for (const moduleName of moduleNames) {\n const mapping = MODULE_MAPPINGS[moduleName];\n const components: string[] = [];\n\n for (const [selector, component] of Object.entries(mapping.selectors)) {\n if (templateSelectors.has(selector)) {\n components.push(component);\n }\n }\n\n if (components.length > 0) {\n map.set(moduleName, { components: [...new Set(components)].sort(), importPath: mapping.importPath });\n }\n }\n\n return map;\n}\n\nfunction findComponentDecorators(sourceFile: ts.SourceFile): ts.Decorator[] {\n const decorators: ts.Decorator[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isClassDeclaration(node)) {\n const decs = ts.getDecorators(node);\n if (decs) {\n for (const dec of decs) {\n if (ts.isCallExpression(dec.expression) && ts.isIdentifier(dec.expression.expression) && dec.expression.expression.text === 'Component') {\n decorators.push(dec);\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return decorators;\n}\n\nfunction findImportsArrayNode(decorator: ts.Decorator): ts.ArrayLiteralExpression | undefined {\n const call = decorator.expression as ts.CallExpression;\n const metadata = call.arguments[0];\n if (!ts.isObjectLiteralExpression(metadata)) return undefined;\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'imports') {\n if (ts.isArrayLiteralExpression(prop.initializer)) {\n return prop.initializer;\n }\n }\n }\n return undefined;\n}\n\nfunction hasModuleInArray(array: ts.ArrayLiteralExpression, moduleName: string, source: string): boolean {\n return array.elements.some((el) => source.slice(el.getStart(), el.getEnd()).trim() === moduleName);\n}\n\nfunction getTemplateSelectors(tree: Tree, tsPath: string, decorator: ts.Decorator, source: string): Set<string> {\n const call = decorator.expression as ts.CallExpression;\n const metadata = call.arguments[0] as ts.ObjectLiteralExpression;\n const allSelectors = Object.values(MODULE_MAPPINGS).flatMap((m) => Object.keys(m.selectors));\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'template') {\n const init = prop.initializer;\n if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {\n return findSelectorsInTemplate(init.text, allSelectors);\n }\n }\n }\n\n for (const prop of metadata.properties) {\n if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'templateUrl') {\n if (ts.isStringLiteral(prop.initializer)) {\n const dir = tsPath.substring(0, tsPath.lastIndexOf('/'));\n const templateBuffer = tree.read(`${dir}/${prop.initializer.text}`);\n if (templateBuffer) {\n return findSelectorsInTemplate(templateBuffer.toString('utf-8'), allSelectors);\n }\n }\n }\n }\n\n return new Set();\n}\n\nfunction findSelectorsInTemplate(html: string, knownSelectors: string[]): Set<string> {\n const selectors = new Set<string>();\n const parsed = parseTemplate(html, '', { preserveWhitespaces: true });\n\n forEachElement(parsed.nodes, (node) => {\n if (knownSelectors.includes(node.name)) selectors.add(node.name);\n for (const attr of node.attributes) {\n if (knownSelectors.includes(attr.name)) selectors.add(attr.name);\n }\n });\n return selectors;\n}\n\nfunction applyReplacements(source: string, filePath: string, replacements: Map<string, { components: string[]; importPath: string }>): string {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);\n let result = replaceInImportsArray(source, sourceFile, replacements);\n result = updateEsImports(result, filePath, replacements);\n return result;\n}\n\nfunction replaceInImportsArray(source: string, sourceFile: ts.SourceFile, replacements: Map<string, { components: string[]; importPath: string }>): string {\n let result = source;\n const visit = (node: ts.Node): void => {\n if (ts.isClassDeclaration(node)) {\n const decs = ts.getDecorators(node);\n if (!decs) return;\n for (const dec of decs) {\n if (!ts.isCallExpression(dec.expression) || !ts.isIdentifier(dec.expression.expression) || dec.expression.expression.text !== 'Component') continue;\n const metadata = dec.expression.arguments[0];\n if (!ts.isObjectLiteralExpression(metadata)) continue;\n for (const prop of metadata.properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name) || prop.name.text !== 'imports') continue;\n if (!ts.isArrayLiteralExpression(prop.initializer)) continue;\n const newElements = prop.initializer.elements\n .map((el) => {\n const text = result.slice(el.getStart(sourceFile), el.getEnd()).trim();\n const replacement = replacements.get(text);\n return replacement ? replacement.components.join(', ') : text;\n })\n .join(', ');\n result = result.slice(0, prop.initializer.getStart(sourceFile) + 1) + newElements + result.slice(prop.initializer.getEnd() - 1);\n }\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return result;\n}\n\nfunction updateEsImports(source: string, filePath: string, replacements: Map<string, { components: string[]; importPath: string }>): string {\n let result = source;\n\n for (const [moduleName, { components, importPath }] of replacements) {\n const sf = ts.createSourceFile(filePath, result, ts.ScriptTarget.Latest, true);\n\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt) || !stmt.importClause?.namedBindings || !ts.isNamedImports(stmt.importClause.namedBindings)) continue;\n const namedBindings = stmt.importClause.namedBindings;\n const importNames = namedBindings.elements.map((el) => el.name.text);\n if (!importNames.includes(moduleName)) continue;\n\n const moduleSpecifier = (stmt.moduleSpecifier as ts.StringLiteral).text;\n const remaining = importNames.filter((n) => n !== moduleName);\n const toAdd = components.filter((c) => !importNames.includes(c));\n\n if (moduleSpecifier === importPath) {\n const newNames = [...remaining, ...toAdd].sort();\n const newClause = `{ ${newNames.join(', ')} }`;\n result = result.slice(0, namedBindings.getStart(sf)) + newClause + result.slice(namedBindings.getEnd());\n } else {\n if (remaining.length > 0) {\n const newClause = `{ ${remaining.join(', ')} }`;\n result = result.slice(0, namedBindings.getStart(sf)) + newClause + result.slice(namedBindings.getEnd());\n } else {\n result = result.slice(0, stmt.getStart(sf)) + result.slice(stmt.getEnd()).replace(/^\\r?\\n/, '');\n }\n\n if (toAdd.length > 0) {\n const updatedSf = ts.createSourceFile(filePath, result, ts.ScriptTarget.Latest, true);\n const existing = updatedSf.statements.find(\n (s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === importPath,\n ) as ts.ImportDeclaration | undefined;\n\n if (existing?.importClause?.namedBindings && ts.isNamedImports(existing.importClause.namedBindings)) {\n const existingNames = existing.importClause.namedBindings.elements.map((el) => el.name.text);\n const allNames = [...new Set([...existingNames, ...toAdd])].sort();\n const newClause = `{ ${allNames.join(', ')} }`;\n result = result.slice(0, existing.importClause.namedBindings.getStart(updatedSf)) + newClause + result.slice(existing.importClause.namedBindings.getEnd());\n } else {\n const newImport = `import { ${toAdd.join(', ')} } from '${importPath}';\\n`;\n result = newImport + result;\n }\n }\n }\n break;\n }\n }\n\n return result;\n}\n",
|
|
6019
|
+
"sourceCode": "import { DirEntry, Rule, SchematicContext, Tree } from '@angular-devkit/schematics';\nimport { parseTemplate, TmplAstElement, TmplAstNode } from '@angular/compiler';\nimport { forEachElement } from '../utils/template-walk';\nimport * as ts from 'typescript';\nimport { logDryRun, logDryRunNote } from '../utils/dry-run';\nimport {\n EUI_SIGNAL_MAP as EUI_SIGNAL_MAP_RAW,\n EUI_SELECTOR_TO_CLASS as EUI_SELECTOR_TO_CLASS_RAW,\n EUI_OUTPUT_MAP,\n EUI_HOST_BINDING_REMOVED_MAP,\n EUI_WRITABLE_SIGNAL_MAP,\n} from './signal-map';\nimport { ECL_SIGNAL_MAP, ECL_SELECTOR_TO_CLASS } from './ecl-signal-map';\n\n/**\n * Combined EUI + ECL signal maps. The migration logic is identical for both\n * libraries (plain field → signal getter), so the maps are merged and the rest\n * of the engine treats them uniformly. EUI and ECL class names don't collide\n * (Eui* vs Ecl* prefixes), and the selector namespaces are disjoint.\n */\nconst EUI_SIGNAL_MAP: Record<string, ReadonlySet<string>> = { ...EUI_SIGNAL_MAP_RAW, ...ECL_SIGNAL_MAP };\nconst EUI_SELECTOR_TO_CLASS: Record<string, string> = { ...EUI_SELECTOR_TO_CLASS_RAW, ...ECL_SELECTOR_TO_CLASS };\n\n/** Every class the schematic knows about (signals, outputs or removed host bindings). */\nconst KNOWN_CLASSES: ReadonlySet<string> = new Set([\n ...Object.keys(EUI_SIGNAL_MAP),\n ...Object.keys(EUI_OUTPUT_MAP),\n ...Object.keys(EUI_HOST_BINDING_REMOVED_MAP),\n]);\nconst isKnownClass = (name: string | null | undefined): name is string => !!name && KNOWN_CLASSES.has(name);\n\n/**\n * Tracked references. Class members are tracked by name (reached via `this.name`); locals/parameters are\n * tracked by their DECLARATION node, so a same-named untracked parameter or variable is never confused\n * with a tracked class member (shadowing). `lists*` hold QueryList<EuiXxx> / EuiXxx[] holders.\n */\ninterface Refs {\n props: Map<string, string>;\n propLists: Map<string, string>;\n decls: Map<ts.Node, string>;\n listDecls: Map<ts.Node, string>;\n}\n\n/** rxjs functions that take Observables as (possibly array-wrapped) arguments. */\nconst OBSERVABLE_COMBINATORS = new Set([\n 'merge', 'race', 'combineLatest', 'forkJoin', 'concat', 'zip', 'firstValueFrom', 'lastValueFrom', 'raceWith', 'mergeWith', 'concatWith', 'zipWith', 'combineLatestWith',\n]);\n\n/** Observable methods that need a real Observable instead of an OutputEmitterRef. */\nconst OBSERVABLE_METHODS = new Set(['subscribe', 'pipe', 'asObservable', 'forEach', 'toPromise']);\n/** QueryList iteration methods whose callback parameter is an element of the list. */\nconst LIST_ITERATION_METHODS = new Set(['forEach', 'map', 'filter', 'some', 'every', 'find', 'findIndex', 'reduce']);\n\ninterface Schema {\n path?: string;\n dryRun?: boolean;\n}\n\ninterface Edit {\n start: number;\n end: number;\n replacement: string;\n /** When several zero-width edits share a position, `after` ones end up after the others. */\n after?: boolean;\n}\n\n/**\n * Migrates consumer code that accesses EUI or ECL component instances\n * programmatically.\n *\n * When EUI/ECL migrated @Input() → input(), @ViewChild() → viewChild(), and\n * @ContentChild() → contentChild(), properties that were plain class fields\n * became signal getters. Consumers who access them via @ViewChild need to\n * change `comp.prop` to `comp.prop()`.\n *\n * This schematic:\n * 1. Finds @ViewChild / @ContentChild fields typed as EUI component classes\n * 2. Resolves untyped @ViewChild('refName') by reading the component template\n * and matching #refName to an EUI element tag/selector\n * 3. Tracks which local variable names hold EUI component references (incl. aliases)\n * 4. Rewrites property accesses on those references: `ref.prop` → `ref.prop()`\n * (only for properties listed in the signal map)\n * 5. Does NOT touch template bindings — those are unaffected by signal migrations\n */\nexport function migrateToSignals(options: Schema = {}): Rule {\n return (tree: Tree, context: SchematicContext) => {\n const scanPath = options.path ? '/' + options.path.replace(/^\\.?\\//, '').replace(/\\/$/, '') : '';\n let fileCount = 0;\n let propCount = 0;\n let todoCount = 0;\n\n visitDir(tree.getDir(scanPath || '/'), (path) => {\n if (!path.endsWith('.ts')) return;\n // Skip spec files — test code may use different patterns\n if (path.endsWith('.spec.ts')) return;\n\n const buffer = tree.read(path);\n if (!buffer) return;\n\n const original = buffer.toString('utf-8');\n\n // Fast bail: file must mention at least one EUI class name or have\n // ViewChild/ContentChild with string refs (which might reference EUI elements)\n if (!hasEuiReference(original) && !hasStringRefQuery(original)) return;\n\n const result = migrateTypeScript(original, path, tree, context);\n if (result.source !== original) {\n if (options.dryRun) {\n if (result.editCount > 0) {\n logDryRun(context, `Would migrate ${result.editCount} signal property access(es) in ${path}`);\n }\n if (result.todoCount > 0) {\n logDryRun(\n context,\n `Would comment out ${result.todoCount} programmatic signal-input write(s) with a TODO in ${path}`,\n );\n }\n } else {\n tree.overwrite(path, result.source);\n }\n fileCount++;\n propCount += result.editCount;\n todoCount += result.todoCount;\n }\n });\n\n context.logger.info(`Migrated ${propCount} property access(es) to signal getters in ${fileCount} file(s).`);\n if (todoCount > 0) {\n context.logger.info(\n `Commented out ${todoCount} programmatic signal-input write(s) and left a TODO — these cannot be migrated automatically and need a manual fix.`,\n );\n }\n if (options.dryRun) {\n logDryRunNote(context);\n }\n return tree;\n };\n}\n\n/** Quick check: does the file reference any EUI class name from the signal map? */\nfunction hasEuiReference(source: string): boolean {\n for (const className of KNOWN_CLASSES) {\n if (source.includes(className)) return true;\n }\n return false;\n}\n\n/** Quick check: does the file have @ViewChild('...') or @ContentChild('...') with string refs? */\nfunction hasStringRefQuery(source: string): boolean {\n return /(@ViewChild|@ContentChild|@ViewChildren|@ContentChildren)\\s*\\(\\s*['\"]/.test(source);\n}\n\ninterface MigrateResult {\n source: string;\n editCount: number;\n todoCount: number;\n}\n\nfunction migrateTypeScript(source: string, filePath: string, tree: Tree, context: SchematicContext): MigrateResult {\n const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n const edits: Edit[] = [];\n const todoEdits: Edit[] = [];\n\n // Phase 0: Build template ref map (#refName → EUI class name) from the component's template\n const templateRefMap = buildTemplateRefMap(sourceFile, source, filePath, tree);\n\n // Phase 1: Collect all variables/properties typed as EUI classes\n const euiRefs = collectEuiReferences(sourceFile, source, templateRefMap);\n\n if (euiRefs.props.size === 0 && euiRefs.propLists.size === 0 && euiRefs.decls.size === 0 && euiRefs.listDecls.size === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const hostTodoEdits: Edit[] = [];\n let needsOutputImport = false;\n\n // Phase 2: Find property accesses on those references and rewrite signal props\n const visitNode = (node: ts.Node): void => {\n // Match: ref.prop (PropertyAccessExpression)\n if (ts.isPropertyAccessExpression(node)) {\n const rewrite = tryRewritePropertyAccess(node, euiRefs, sourceFile, source);\n if (rewrite) {\n edits.push(rewrite);\n }\n\n // Writable signal (model()): `ref.prop = value` -> `ref.prop.set(value)`\n edits.push(...trySetRewrite(node, euiRefs, sourceFile));\n\n // Output: `ref.out.subscribe()` -> `outputToObservable(ref.out).subscribe()`\n const wrap = tryWrapOutput(node, euiRefs, sourceFile);\n if (wrap) {\n edits.push(...wrap);\n needsOutputImport = true;\n }\n\n // Output handed to rxjs combinators / used as a value: wrap or flag\n const outputUse = tryOutputUsage(node, euiRefs, sourceFile, source);\n if (outputUse) {\n edits.push(...outputUse.edits);\n if (outputUse.todo) hostTodoEdits.push(outputUse.todo);\n if (outputUse.edits.length > 0) needsOutputImport = true;\n }\n\n // Removed @HostBinding property: flag with a TODO\n const hostTodo = tryHostBindingTodo(node, euiRefs, sourceFile, source);\n if (hostTodo) {\n hostTodoEdits.push(hostTodo);\n }\n\n // Separately: a programmatic WRITE to a now-signal input cannot be\n // migrated automatically. Flag it with a TODO instead of silently\n // leaving a line that will fail to compile against the signal API.\n const todo = tryInsertWriteTodo(node, euiRefs, sourceFile, source);\n if (todo) {\n todoEdits.push(todo);\n }\n }\n // Destructuring / aliasing of a tracked reference cannot be followed: flag it.\n const alias = tryAliasTodo(node, euiRefs, sourceFile, source);\n if (alias) hostTodoEdits.push(alias);\n ts.forEachChild(node, visitNode);\n };\n\n ts.forEachChild(sourceFile, visitNode);\n\n if (edits.length === 0 && todoEdits.length === 0 && hostTodoEdits.length === 0) {\n return { source, editCount: 0, todoCount: 0 };\n }\n\n const dedupedTodos = deduplicateEdits(todoEdits);\n const dedupedHostTodos = deduplicateEdits(hostTodoEdits);\n\n // A TODO edit comments out the whole write statement. Any read-rewrite `()`\n // edit whose position falls inside that commented-out range must be dropped,\n // otherwise we'd both edit and comment the same text (and produce overlapping\n // edits that corrupt the output).\n const keptEdits = edits.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const keptHostTodos = dedupedHostTodos.filter((edit) => !isInsideAnyRange(edit, dedupedTodos));\n const importEdit = needsOutputImport ? buildOutputImportEdit(sourceFile) : null;\n\n return {\n source: applyEdits(source, [...keptEdits, ...dedupedTodos, ...keptHostTodos, ...(importEdit ? [importEdit] : [])]),\n editCount: keptEdits.length,\n todoCount: dedupedTodos.length + keptHostTodos.length,\n };\n}\n\n/**\n * Scans the source file for class properties or variables typed as EUI component classes.\n * Returns a map: localName → Set of signal property names.\n *\n * Handles:\n * @ViewChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild(EuiXxxComponent) name!: EuiXxxComponent;\n * @ViewChild('ref') name: EuiXxxComponent;\n * @ContentChild(EuiXxxComponent) name: EuiXxxComponent;\n * @ViewChild('ref') name: ElementRef; (resolved via template #ref → EUI selector)\n * someVar: EuiXxxComponent; (typed class field, even without decorator)\n * const alias = this.viewChildRef; (alias tracking)\n */\nfunction collectEuiReferences(\n sourceFile: ts.SourceFile,\n source: string,\n templateRefMap: Map<string, string>,\n): Refs {\n const tracked: Refs = { props: new Map(), propLists: new Map(), decls: new Map(), listDecls: new Map() };\n const { props, propLists, decls, listDecls } = tracked;\n\n // Pass 1: collect directly-typed references\n const visitDirect = (node: ts.Node): void => {\n // Class property declarations\n if (ts.isPropertyDeclaration(node) && node.name && ts.isIdentifier(node.name)) {\n const euiClass = resolveEuiClassName(node, sourceFile, templateRefMap);\n if (isKnownClass(euiClass)) {\n (isListProperty(node) ? propLists : props).set(node.name.text, euiClass);\n }\n }\n\n // Variable (const x: EuiXxxComponent = ...) and parameter (method(ref: EuiXxxComponent)) declarations\n if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name)) {\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n decls.set(node, typeName);\n // constructor parameter property: also reachable as `this.name`\n if (ts.isParameter(node) && (ts.getModifiers?.(node) ?? []).length > 0) props.set(node.name.text, typeName);\n } else {\n const listClass = listElementClass(node.type);\n if (listClass) listDecls.set(node, listClass);\n }\n }\n\n ts.forEachChild(node, visitDirect);\n };\n\n ts.forEachChild(sourceFile, visitDirect);\n\n // Pass 2: aliases, QueryList/array iteration (source order)\n const visitAlias = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && !decls.has(node)) {\n const aliased = trackedClass(node.initializer, tracked);\n if (aliased) decls.set(node, aliased);\n const aliasedList = listClassOf(node.initializer, tracked);\n if (aliasedList) listDecls.set(node, aliasedList);\n }\n\n // list.forEach((el) => ...) / list.map(function (el) {...}) -> `el` is an element of the list\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n LIST_ITERATION_METHODS.has(node.expression.name.text)\n ) {\n const listClass = listClassOf(node.expression.expression, tracked);\n const callback = node.arguments[0];\n if (\n listClass &&\n callback &&\n (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) &&\n callback.parameters[0] &&\n ts.isIdentifier(callback.parameters[0].name) &&\n !callback.parameters[0].type\n ) {\n decls.set(callback.parameters[0], listClass);\n }\n }\n\n // for (const el of list) -> `el` is an element of the list\n if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {\n const listClass = listClassOf(node.expression, tracked);\n const decl = node.initializer.declarations[0];\n if (listClass && decl && ts.isIdentifier(decl.name) && !decls.has(decl)) decls.set(decl, listClass);\n }\n\n ts.forEachChild(node, visitAlias);\n };\n\n ts.forEachChild(sourceFile, visitAlias);\n return tracked;\n}\n\n/** `EuiXxx[]`, `Array<EuiXxx>`, `QueryList<EuiXxx>` -> the known element class. */\nfunction listElementClass(type: ts.TypeNode | undefined): string | null {\n if (!type) return null;\n if (ts.isArrayTypeNode(type)) {\n const n = getTypeAnnotationName(type.elementType);\n return isKnownClass(n) ? n : null;\n }\n if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && ['Array', 'ReadonlyArray', 'QueryList'].includes(type.typeName.text)) {\n const n = getTypeAnnotationName(type.typeArguments?.[0]);\n return isKnownClass(n) ? n : null;\n }\n return null;\n}\n\n/** Strips parentheses, `!`, `as T`, `<T>x` and `satisfies`. */\nfunction unwrap(expr: ts.Expression): ts.Expression {\n let cur = expr;\n while (\n ts.isParenthesizedExpression(cur) ||\n ts.isNonNullExpression(cur) ||\n ts.isAsExpression(cur) ||\n ts.isTypeAssertionExpression(cur) ||\n ts.isSatisfiesExpression(cur)\n ) {\n cur = cur.expression;\n }\n return cur;\n}\n\n/** Nearest declaration (parameter / variable / binding element) of a bare identifier, or null. */\nfunction findDeclaration(id: ts.Identifier): ts.Node | null {\n const name = id.text;\n const boundIn = (bn: ts.BindingName): boolean =>\n ts.isIdentifier(bn) ? bn.text === name : bn.elements.some((e) => !ts.isOmittedExpression(e) && boundIn(e.name));\n const matchDecl = (d: ts.ParameterDeclaration | ts.VariableDeclaration): ts.Node | null => (boundIn(d.name) ? d : null);\n\n for (let cur: ts.Node | undefined = id.parent; cur; cur = cur.parent) {\n if (ts.isFunctionLike(cur)) {\n for (const p of cur.parameters) {\n const m = matchDecl(p);\n if (m) return m;\n }\n }\n if (ts.isBlock(cur) || ts.isSourceFile(cur) || ts.isModuleBlock(cur) || ts.isCaseClause(cur) || ts.isDefaultClause(cur)) {\n const stmts = ts.isCaseClause(cur) || ts.isDefaultClause(cur) ? cur.statements : cur.statements;\n for (const st of stmts) {\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n }\n }\n if ((ts.isForStatement(cur) || ts.isForOfStatement(cur) || ts.isForInStatement(cur)) && cur.initializer && ts.isVariableDeclarationList(cur.initializer)) {\n for (const d of cur.initializer.declarations) {\n const m = matchDecl(d);\n if (m) return m;\n }\n }\n if (ts.isCatchClause(cur) && cur.variableDeclaration) {\n const m = matchDecl(cur.variableDeclaration);\n if (m) return m;\n }\n }\n return null;\n}\n\n/** `this.name` -> name; anything else null. */\nfunction thisMemberName(expr: ts.Expression): string | null {\n return ts.isPropertyAccessExpression(expr) && expr.expression.kind === ts.SyntaxKind.ThisKeyword ? expr.name.text : null;\n}\n\n/** Element class of a tracked QueryList / array expression, or null. */\nfunction listClassOf(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.listDecls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n return member ? (tracked.propLists.get(member) ?? null) : null;\n}\n\n/**\n * Resolves the EUI class name from a property declaration.\n * Checks: type annotation → decorator class argument → template ref map.\n */\nfunction resolveEuiClassName(\n node: ts.PropertyDeclaration,\n sourceFile: ts.SourceFile,\n templateRefMap: Map<string, string>,\n): string | null {\n // Check type annotation first\n const typeName = getTypeAnnotationName(node.type);\n if (isKnownClass(typeName)) {\n return typeName;\n }\n\n const arrayClass = listElementClass(node.type);\n if (arrayClass) return arrayClass;\n\n // Check generic type argument: ElementRef<EuiXxxComponent> / QueryList<EuiXxxComponent>\n if (node.type && ts.isTypeReferenceNode(node.type) && node.type.typeArguments?.length) {\n const genericArg = getTypeAnnotationName(node.type.typeArguments[0]);\n if (isKnownClass(genericArg)) {\n return genericArg;\n }\n }\n\n // Check decorator arguments: @ViewChild(EuiXxxComponent) or @ViewChild('refName')\n if (node.modifiers) {\n for (const modifier of node.modifiers) {\n if (!ts.isDecorator(modifier)) continue;\n if (!ts.isCallExpression(modifier.expression)) continue;\n\n const decoratorName = getDecoratorName(modifier.expression);\n if (!decoratorName) continue;\n if (!['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'].includes(decoratorName)) continue;\n\n const args = modifier.expression.arguments;\n if (args.length > 0) {\n const firstArg = args[0];\n\n // @ViewChild(EuiXxxComponent) — class reference\n if (ts.isIdentifier(firstArg) && isKnownClass(firstArg.text)) {\n return firstArg.text;\n }\n\n // @ViewChild('refName') — string template ref, resolve via template\n if (ts.isStringLiteralLike(firstArg)) {\n const refName = firstArg.text;\n const euiClass = templateRefMap.get(refName);\n if (isKnownClass(euiClass)) {\n return euiClass;\n }\n }\n }\n }\n }\n\n return null;\n}\n\n/** True for `@ViewChildren/@ContentChildren` fields and `QueryList<...>`-typed fields. */\nfunction isListProperty(node: ts.PropertyDeclaration): boolean {\n if (listElementClass(node.type)) return true;\n if (node.type && ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === 'QueryList') {\n return true;\n }\n return (ts.getDecorators?.(node) ?? []).some(\n (d) => ts.isCallExpression(d.expression) && ['ViewChildren', 'ContentChildren'].includes(getDecoratorName(d.expression) ?? ''),\n );\n}\n\n/**\n * Resolves an expression to the tracked EUI class: `ref`, `this.ref`, `this.ref!`, `(this.ref as any)`,\n * the `.first` / `.last` element of a tracked QueryList, or `list[i]` of a tracked list/array.\n */\nfunction trackedClass(expr: ts.Expression, tracked: Refs): string | null {\n const e = unwrap(expr);\n if (ts.isIdentifier(e)) {\n const d = findDeclaration(e);\n return d ? (tracked.decls.get(d) ?? null) : null;\n }\n const member = thisMemberName(e);\n if (member) return tracked.props.get(member) ?? null;\n if (ts.isPropertyAccessExpression(e) && (e.name.text === 'first' || e.name.text === 'last')) {\n return listClassOf(e.expression, tracked);\n }\n if (ts.isElementAccessExpression(e)) return listClassOf(e.expression, tracked);\n return null;\n}\n\nfunction getDecoratorName(callExpr: ts.CallExpression): string | null {\n if (ts.isIdentifier(callExpr.expression)) {\n return callExpr.expression.text;\n }\n return null;\n}\n\nfunction getTypeAnnotationName(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n return typeNode.typeName.text;\n }\n return null;\n}\n\n/**\n * Checks if a property access `ref.prop` should be rewritten to `ref.prop()`.\n *\n * We rewrite if:\n * - `ref` is tracked in euiRefs\n * - `prop` is in the signal set for that EUI class\n * - The access is NOT already a call expression (not `ref.prop()` or `ref.prop(args)`)\n * - The access is NOT a write target (not `ref.prop = value`)\n * - The access is NOT a template binding argument (those are unaffected)\n */\nfunction tryRewritePropertyAccess(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n // Resolve the reference class — handle `this.ref.prop`, `ref.prop`, `list.first.prop`\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Skip if parent is already a call expression on this property: ref.prop(...)\n if (ts.isCallExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip a signal handed to toObservable(ref.prop): it needs the signal itself (e.g. written by migrate-eui-tab-signals)\n if (ts.isCallExpression(node.parent) && node.parent.arguments[0] === node &&\n ts.isIdentifier(node.parent.expression) && node.parent.expression.text === 'toObservable') {\n return null;\n }\n\n // Skip signal API access already in place: ref.prop.set(..) / .update(..) / .asReadonly()\n if (ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node &&\n ['set', 'update', 'asReadonly'].includes(node.parent.name.text)) {\n return null;\n }\n\n // Skip if this is the left side of an assignment: ref.prop = value\n if (ts.isBinaryExpression(node.parent) &&\n node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n node.parent.left === node) {\n return null;\n }\n\n // Skip if this is a compound assignment: ref.prop += value, ref.prop &&= value, etc.\n if (ts.isBinaryExpression(node.parent) && isAssignmentOperator(node.parent.operatorToken.kind) && node.parent.left === node) {\n return null;\n }\n\n // Skip if this is used with delete: delete ref.prop\n if (ts.isDeleteExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip if inside a typeof: typeof ref.prop\n if (ts.isTypeOfExpression(node.parent) && node.parent.expression === node) {\n return null;\n }\n\n // Skip property access chains that go deeper: ref.prop.something → ref.prop().something\n // This IS correct — we still want to add ()\n\n // Rewrite: insert () after the property name\n const end = node.name.getEnd();\n return {\n start: end,\n end: end,\n replacement: '()',\n };\n}\n\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;\n}\n\n/** Marker used to detect an already-inserted TODO so the schematic stays idempotent. */\nconst WRITE_TODO_MARKER = 'TODO(eui-signals):';\n\n/**\n * Detects a programmatic WRITE to a now-signal input and returns an edit that\n * comments out the offending statement and prepends an explanatory TODO.\n *\n * A signal input (`input()`) exposes a read-only getter — it cannot be assigned\n * from outside the component (`comp.prop = value` no longer compiles, and\n * `comp.prop()` is a getter, not a setter). There is no safe, mechanical\n * rewrite: the correct fix is to drive the value declaratively through a\n * template binding (`[prop]=\"...\"`) or, when a ComponentRef is genuinely\n * available, `componentRef.setInput('prop', value)`. Both require human\n * judgement, so instead of rewriting we comment the statement out (keeping the\n * build green) and leave a TODO pointing at the manual fix.\n *\n * Only acts when the assignment is the ENTIRE statement\n * (`ExpressionStatement` whose expression is exactly this assignment):\n * ref.prop = value (simple assignment)\n * ref.prop += value, etc. (compound assignment)\n * where `ref` is a tracked EUI/ECL reference and `prop` is in its signal set.\n *\n * When the write is only part of a larger statement (e.g. inside an `if`\n * without a block, or nested in another expression), commenting it out would\n * also remove unrelated logic, so we leave it untouched (it will surface as a\n * compile error the developer must resolve by hand).\n */\nfunction tryInsertWriteTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls) return null;\n\n const signalProps = EUI_SIGNAL_MAP[cls];\n if (!signalProps || !signalProps.has(propName)) return null;\n\n // Only act on assignment targets: `ref.prop = ...` or `ref.prop <op>= ...`\n if (\n !ts.isBinaryExpression(node.parent) ||\n node.parent.left !== node ||\n !isAssignmentOperator(node.parent.operatorToken.kind)\n ) {\n return null;\n }\n\n const assignment = node.parent;\n\n // A plain `=` to a writable signal is migrated to `.set()` by trySetRewrite\n if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken && EUI_WRITABLE_SIGNAL_MAP[cls]?.has(propName)) {\n return null;\n }\n\n // Only comment out when the assignment IS the whole statement — otherwise we'd\n // delete unrelated logic from a larger statement.\n const statement = node.parent.parent;\n if (!statement || !ts.isExpressionStatement(statement) || statement.expression !== assignment) {\n return null;\n }\n\n // The statement must stand on its own (a direct child of a block/source), not\n // be the unbraced body of an `if`/`for`/`while` etc. — commenting those out by\n // line would swallow the surrounding `if (...)` and break the code.\n const parent = statement.parent;\n if (\n !parent ||\n !(ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isModuleBlock(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent))\n ) {\n return null;\n }\n\n const stmtStart = statement.getStart(sourceFile);\n const stmtEnd = statement.getEnd(); // includes the trailing semicolon\n const lineStart = getLineStartPosition(source, stmtStart);\n const indent = source.slice(lineStart, stmtStart);\n\n // Commenting works per line: the statement must be alone on its lines, otherwise\n // (e.g. `run() { ref.prop = 1; }`) we would comment out surrounding code.\n const eol = source.indexOf('\\n', stmtEnd);\n const restOfLine = source.slice(stmtEnd, eol === -1 ? source.length : eol);\n if (indent.trim() !== '' || restOfLine.trim() !== '') {\n return null;\n }\n\n // The statement text, as written (may span multiple lines).\n const statementText = source.slice(stmtStart, stmtEnd);\n\n // Comment out every line of the statement, preserving each line's own\n // indentation (insert `// ` after the leading whitespace). The first line's\n // indentation was stripped by starting the replacement at lineStart, so we\n // re-add it explicitly.\n const commentedStatement = statementText\n .split('\\n')\n .map((line, i) => {\n if (i === 0) return `${indent}// ${line}`;\n const lineIndent = line.slice(0, line.length - line.trimStart().length);\n return `${lineIndent}// ${line.trimStart()}`;\n })\n .join('\\n');\n\n const todo =\n `${indent}// ${WRITE_TODO_MARKER} '${propName}' is now a signal input and cannot be assigned directly.\\n` +\n `${indent}// Set it via a template binding ([${propName}]=\"...\") or componentRef.setInput('${propName}', ...).\\n` +\n `${indent}// The original statement is commented out below so the build does not fail:\\n`;\n\n // Replace the statement (from the start of its line, to drop the original\n // indentation we re-add) with the TODO + commented-out statement.\n return {\n start: lineStart,\n end: stmtEnd,\n replacement: todo + commentedStatement,\n };\n}\n\n/** `ref.prop = value;` on a writable signal -> `ref.prop.set(value);` (two zero-width-safe edits). */\nfunction trySetRewrite(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] {\n const assignment = node.parent;\n if (\n !ts.isBinaryExpression(assignment) ||\n assignment.left !== node ||\n assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||\n !ts.isExpressionStatement(assignment.parent)\n ) {\n return [];\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_WRITABLE_SIGNAL_MAP[cls]?.has(node.name.text)) return [];\n\n return [\n { start: node.getEnd(), end: assignment.right.getStart(sourceFile), replacement: '.set(' },\n { start: assignment.right.getEnd(), end: assignment.right.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** `ref.out.subscribe(...)` -> `outputToObservable(ref.out).subscribe(...)`. */\nfunction tryWrapOutput(node: ts.PropertyAccessExpression, euiRefs: Refs, sourceFile: ts.SourceFile): Edit[] | null {\n const parent = node.parent;\n if (!ts.isPropertyAccessExpression(parent) || parent.expression !== node || !OBSERVABLE_METHODS.has(parent.name.text)) {\n return null;\n }\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n\n const start = node.getStart(sourceFile);\n return [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ];\n}\n\n/** Marker for a read of a property that was a @HostBinding and no longer exists. */\nconst HOST_TODO_MARKER = 'TODO(eui-signals):';\n\nfunction tryHostBindingTodo(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): Edit | null {\n const propName = node.name.text;\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_HOST_BINDING_REMOVED_MAP[cls]?.has(propName) || EUI_SIGNAL_MAP[cls]?.has(propName)) return null;\n return flagTodo(\n node,\n sourceFile,\n source,\n `'${propName}' was a @HostBinding`,\n `'${propName}' was a @HostBinding property of ${cls} and no longer exists on the instance ` +\n '(moved to static host metadata). Remove or replace this access.',\n );\n}\n\n/**\n * Inserts a `// TODO(eui-signals): <message>` line above the enclosing statement / class member.\n * `key` identifies the TODO for idempotency (looked for in the comment lines right above).\n */\nfunction flagTodo(node: ts.Node, sourceFile: ts.SourceFile, source: string, key: string, message: string): Edit | null {\n // Anchor on the enclosing statement / class member\n let anchor: ts.Node = node;\n while (\n anchor.parent &&\n !(\n ts.isBlock(anchor.parent) ||\n ts.isSourceFile(anchor.parent) ||\n ts.isModuleBlock(anchor.parent) ||\n ts.isCaseClause(anchor.parent) ||\n ts.isDefaultClause(anchor.parent) ||\n ts.isClassLike(anchor.parent)\n )\n ) {\n anchor = anchor.parent;\n }\n\n const lineStart = getLineStartPosition(source, anchor.getStart(sourceFile));\n const indent = source.slice(lineStart).match(/^[ \\t]*/)![0];\n const text = `${indent}// ${HOST_TODO_MARKER} ${message}\\n`;\n\n // Idempotent: look at the contiguous comment lines right above\n const above = source.slice(0, lineStart).split('\\n').slice(-8).reverse();\n for (const line of above.slice(1)) {\n if (!line.trim().startsWith('//')) break;\n if (line.includes(`${HOST_TODO_MARKER} ${key}`) || line.includes(key)) return null;\n }\n // A single-line anchor like `run() { ... }` shares its line with other code: still fine, the comment goes above the line.\n return { start: lineStart, end: lineStart, replacement: text };\n}\n\n/**\n * An output (OutputEmitterRef) used as a value:\n * - an argument of an rxjs combinator (`merge(ref.out, ...)`, also inside an array) is wrapped in `outputToObservable()`;\n * - any other use that is not `.emit()` / `.subscribe()` & co / already wrapped is flagged with a TODO.\n */\nfunction tryOutputUsage(\n node: ts.PropertyAccessExpression,\n euiRefs: Refs,\n sourceFile: ts.SourceFile,\n source: string,\n): { edits: Edit[]; todo?: Edit | null } | null {\n const cls = trackedClass(node.expression, euiRefs);\n if (!cls || !EUI_OUTPUT_MAP[cls]?.has(node.name.text)) return null;\n const parent = node.parent;\n\n // handled elsewhere (tryWrapOutput) or fine as is\n if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return null;\n if (ts.isNonNullExpression(parent) || ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent)) return null;\n // declared / written outputs are not reads\n if (ts.isBinaryExpression(parent) && parent.left === node) return null;\n\n // argument of a combinator?\n let arg: ts.Node = node;\n if (ts.isArrayLiteralExpression(arg.parent)) arg = arg.parent;\n const call = arg.parent;\n if (ts.isCallExpression(call) && call.arguments.includes(arg as ts.Expression)) {\n const callee = ts.isIdentifier(call.expression) ? call.expression.text : null;\n if (callee === 'outputToObservable') return null; // already migrated\n if (callee && OBSERVABLE_COMBINATORS.has(callee)) {\n const start = node.getStart(sourceFile);\n return {\n edits: [\n { start, end: start, replacement: 'outputToObservable(' },\n { start: node.getEnd(), end: node.getEnd(), replacement: ')', after: true },\n ],\n };\n }\n }\n\n return {\n edits: [],\n todo: flagTodo(\n node,\n sourceFile,\n source,\n `output '${node.name.text}'`,\n `output '${node.name.text}' of ${cls} is an OutputEmitterRef, not an Observable. Wrap it with outputToObservable() ` +\n '(@angular/core/rxjs-interop) where an Observable is needed.',\n ),\n };\n}\n\n/** Destructuring of a tracked reference, or storing it in a field/variable we cannot follow. */\nfunction tryAliasTodo(node: ts.Node, euiRefs: Refs, sourceFile: ts.SourceFile, source: string): Edit | null {\n if (ts.isVariableDeclaration(node) && node.initializer && !ts.isIdentifier(node.name)) {\n const cls = trackedClass(node.initializer, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `destructuring of ${cls}`,\n `destructuring of ${cls} cannot be migrated automatically: its signal inputs/outputs must be read as ref.prop() / outputToObservable(ref.out).`,\n );\n }\n }\n if (\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&\n !ts.isIdentifier(unwrap(node.left)) &&\n ts.isExpressionStatement(node.parent)\n ) {\n const cls = trackedClass(node.right, euiRefs);\n if (cls) {\n return flagTodo(\n node,\n sourceFile,\n source,\n `aliasing of ${cls}`,\n `aliasing of ${cls}: this copy is not tracked, so its signal inputs/outputs must be updated manually (ref.prop()).`,\n );\n }\n }\n return null;\n}\n\n/** Adds `outputToObservable` to the file's imports (merging into an existing rxjs-interop import). */\nfunction buildOutputImportEdit(sourceFile: ts.SourceFile): Edit | null {\n let lastImportEnd = 0;\n for (const stmt of sourceFile.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n lastImportEnd = stmt.getEnd();\n if (!ts.isStringLiteral(stmt.moduleSpecifier) || stmt.moduleSpecifier.text !== '@angular/core/rxjs-interop') continue;\n const bindings = stmt.importClause?.namedBindings;\n if (bindings && ts.isNamedImports(bindings)) {\n if (bindings.elements.some((e) => e.name.text === 'outputToObservable')) return null;\n const last = bindings.elements[bindings.elements.length - 1];\n if (last) {\n return { start: last.getEnd(), end: last.getEnd(), replacement: ', outputToObservable' };\n }\n }\n }\n const line = 'import { outputToObservable } from \\'@angular/core/rxjs-interop\\';';\n return lastImportEnd === 0\n ? { start: 0, end: 0, replacement: `${line}\\n` }\n : { start: lastImportEnd, end: lastImportEnd, replacement: `\\n${line}` };\n}\n\n/** True if `edit`'s position falls within any of the given ranges. */\nfunction isInsideAnyRange(edit: Edit, ranges: Edit[]): boolean {\n return ranges.some((range) => edit.start >= range.start && edit.end <= range.end);\n}\n\n/** Returns the index of the first character of the line containing `pos`. */\nfunction getLineStartPosition(source: string, pos: number): number {\n const newlineIndex = source.lastIndexOf('\\n', pos - 1);\n return newlineIndex === -1 ? 0 : newlineIndex + 1;\n}\n\n// ---------------------------------------------------------------------------\n// Template ref resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a map of template reference variable names (#ref) to EUI class names.\n *\n * Parses the component's template (inline or external) and finds elements like:\n * <eui-alert #myAlert> → myAlert → EuiAlertComponent\n * <input euiAutocomplete #ac> → ac → EuiAutocompleteComponent\n *\n * Returns Map<refName, euiClassName>.\n */\nfunction buildTemplateRefMap(\n sourceFile: ts.SourceFile,\n source: string,\n filePath: string,\n tree: Tree,\n): Map<string, string> {\n const refMap = new Map<string, string>();\n\n // Find @Component decorator\n const componentMeta = findComponentMetadata(sourceFile, source);\n if (!componentMeta) return refMap;\n\n let templateSource: string | null = null;\n\n if (componentMeta.inlineTemplate !== null) {\n templateSource = componentMeta.inlineTemplate;\n } else if (componentMeta.templateUrl) {\n // Resolve templateUrl relative to the TS file\n const dir = filePath.substring(0, filePath.lastIndexOf('/'));\n const templatePath = `${dir}/${componentMeta.templateUrl}`;\n const buffer = tree.read(templatePath);\n if (buffer) {\n templateSource = buffer.toString('utf-8');\n }\n }\n\n if (!templateSource) return refMap;\n\n // Parse the template and collect #refs\n try {\n const parsed = parseTemplate(templateSource, '', { preserveWhitespaces: true });\n collectTemplateRefs(parsed.nodes, refMap);\n } catch {\n // Template parse failure — silently skip (might be malformed or use third-party syntax)\n }\n\n return refMap;\n}\n\n/**\n * Extracts @Component metadata: templateUrl or inline template content.\n */\nfunction findComponentMetadata(\n sourceFile: ts.SourceFile,\n source: string,\n): { templateUrl: string | null; inlineTemplate: string | null } | null {\n let result: { templateUrl: string | null; inlineTemplate: string | null } | null = null;\n\n const visit = (node: ts.Node): void => {\n if (result) return;\n\n if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {\n const name = getDecoratorName(node.expression);\n if (name !== 'Component') {\n ts.forEachChild(node, visit);\n return;\n }\n\n const args = node.expression.arguments;\n if (args.length === 0 || !ts.isObjectLiteralExpression(args[0])) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const meta: { templateUrl: string | null; inlineTemplate: string | null } = {\n templateUrl: null,\n inlineTemplate: null,\n };\n\n for (const prop of args[0].properties) {\n if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue;\n\n if (prop.name.text === 'templateUrl') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.templateUrl = init.text;\n }\n }\n\n if (prop.name.text === 'template') {\n const init = unwrapExpression(prop.initializer);\n if (ts.isStringLiteralLike(init)) {\n meta.inlineTemplate = init.text;\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n meta.inlineTemplate = init.text;\n }\n }\n }\n\n result = meta;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n return result;\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (ts.isParenthesizedExpression(current)) current = current.expression;\n return current;\n}\n\n/**\n * Recursively walks template AST nodes, collecting #refName → EUI class name mappings.\n *\n * For each element with a template reference (#ref), we try to resolve its EUI class:\n * 1. Match element tag name against EUI_SELECTOR_TO_CLASS (e.g. 'eui-alert' → EuiAlertComponent)\n * 2. Match element attributes against attribute selectors (e.g. [euiAutocomplete] → EuiAutocompleteComponent)\n */\nfunction collectTemplateRefs(nodes: TmplAstNode[], refMap: Map<string, string>): void {\n forEachElement(nodes, (node) => {\n if (node.references === undefined || node.references.length === 0) return;\n const euiClass = resolveElementToEuiClass(node);\n if (!euiClass) return;\n for (const ref of node.references) {\n refMap.set(ref.name, euiClass);\n }\n });\n}\n\n/**\n * Given a template element, resolves it to an EUI class name by checking:\n * 1. Tag name: <eui-alert> → look up 'eui-alert' in EUI_SELECTOR_TO_CLASS\n * 2. Attribute selectors: <input euiAutocomplete> → look up 'input[euiAutocomplete]' or '[euiAutocomplete]'\n */\nfunction resolveElementToEuiClass(element: TmplAstElement): string | null {\n const tag = element.name;\n\n // Direct tag match: eui-alert, eui-dialog, etc.\n if (EUI_SELECTOR_TO_CLASS[tag]) {\n return EUI_SELECTOR_TO_CLASS[tag];\n }\n\n // Attribute selector match: check all attributes against known patterns\n const allAttrNames = [\n ...element.attributes.map((a) => a.name),\n ...element.inputs.map((i) => i.name),\n ];\n\n for (const attrName of allAttrNames) {\n // Try tag[attr] pattern first (e.g. 'button[euiButton]', 'input[euiAutocomplete]')\n const tagAttrSelector = `${tag}[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[tagAttrSelector]) {\n return EUI_SELECTOR_TO_CLASS[tagAttrSelector];\n }\n\n // Try [attr] pattern (e.g. '[euiTooltip]', '[euiLoading]')\n const attrSelector = `[${attrName}]`;\n if (EUI_SELECTOR_TO_CLASS[attrSelector]) {\n return EUI_SELECTOR_TO_CLASS[attrSelector];\n }\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Edit helpers\n// ---------------------------------------------------------------------------\n\nfunction applyEdits(source: string, edits: Edit[]): string {\n const unique = deduplicateEdits(edits);\n let result = source;\n // Descending by position; at equal positions `after` edits are applied first so they land last.\n for (const edit of unique.sort((a, b) => b.start - a.start || Number(!!b.after) - Number(!!a.after))) {\n result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);\n }\n return result;\n}\n\nfunction deduplicateEdits(edits: Edit[]): Edit[] {\n const seen = new Map<string, Edit>();\n for (const edit of edits) {\n const key = `${edit.start}:${edit.end}:${edit.replacement}`;\n seen.set(key, edit);\n }\n return Array.from(seen.values());\n}\n\nfunction visitDir(dir: DirEntry, callback: (path: string) => void): void {\n for (const file of dir.subfiles) {\n if (file.endsWith('.d.ts')) continue;\n if (!file.endsWith('.ts')) continue;\n callback(`${dir.path}/${file}`);\n }\n for (const sub of dir.subdirs) {\n if (sub === 'node_modules' || sub === 'dist') continue;\n visitDir(dir.dir(sub), callback);\n }\n}\n",
|
|
6020
6020
|
"displayName": "Schema",
|
|
6021
6021
|
"properties": [
|
|
6022
6022
|
{
|
|
@@ -6028,7 +6028,7 @@
|
|
|
6028
6028
|
"indexKey": "",
|
|
6029
6029
|
"optional": true,
|
|
6030
6030
|
"description": "",
|
|
6031
|
-
"line":
|
|
6031
|
+
"line": 56,
|
|
6032
6032
|
"rawdescription": "\n"
|
|
6033
6033
|
},
|
|
6034
6034
|
{
|
|
@@ -6040,7 +6040,7 @@
|
|
|
6040
6040
|
"indexKey": "",
|
|
6041
6041
|
"optional": true,
|
|
6042
6042
|
"description": "",
|
|
6043
|
-
"line":
|
|
6043
|
+
"line": 55,
|
|
6044
6044
|
"rawdescription": "\n"
|
|
6045
6045
|
}
|
|
6046
6046
|
],
|
|
@@ -31375,7 +31375,7 @@
|
|
|
31375
31375
|
},
|
|
31376
31376
|
{
|
|
31377
31377
|
"name": "applyEdits",
|
|
31378
|
-
"file": "packages/core/schematics/migrate-
|
|
31378
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
31379
31379
|
"ctype": "miscellaneous",
|
|
31380
31380
|
"subtype": "function",
|
|
31381
31381
|
"coverageIgnore": false,
|
|
@@ -31420,7 +31420,7 @@
|
|
|
31420
31420
|
},
|
|
31421
31421
|
{
|
|
31422
31422
|
"name": "applyEdits",
|
|
31423
|
-
"file": "packages/core/schematics/migrate-
|
|
31423
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
31424
31424
|
"ctype": "miscellaneous",
|
|
31425
31425
|
"subtype": "function",
|
|
31426
31426
|
"coverageIgnore": false,
|
|
@@ -31465,7 +31465,7 @@
|
|
|
31465
31465
|
},
|
|
31466
31466
|
{
|
|
31467
31467
|
"name": "applyEdits",
|
|
31468
|
-
"file": "packages/core/schematics/
|
|
31468
|
+
"file": "packages/core/schematics/utils/tooltip-message.ts",
|
|
31469
31469
|
"ctype": "miscellaneous",
|
|
31470
31470
|
"subtype": "function",
|
|
31471
31471
|
"coverageIgnore": false,
|
|
@@ -31510,7 +31510,7 @@
|
|
|
31510
31510
|
},
|
|
31511
31511
|
{
|
|
31512
31512
|
"name": "applyEdits",
|
|
31513
|
-
"file": "packages/core/schematics/
|
|
31513
|
+
"file": "packages/core/schematics/migrate-to-signals/index.ts",
|
|
31514
31514
|
"ctype": "miscellaneous",
|
|
31515
31515
|
"subtype": "function",
|
|
31516
31516
|
"coverageIgnore": false,
|
|
@@ -42955,7 +42955,7 @@
|
|
|
42955
42955
|
},
|
|
42956
42956
|
{
|
|
42957
42957
|
"name": "lineOf",
|
|
42958
|
-
"file": "packages/core/schematics/migrate-
|
|
42958
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
42959
42959
|
"ctype": "miscellaneous",
|
|
42960
42960
|
"subtype": "function",
|
|
42961
42961
|
"coverageIgnore": false,
|
|
@@ -42978,7 +42978,7 @@
|
|
|
42978
42978
|
"deprecationMessage": ""
|
|
42979
42979
|
}
|
|
42980
42980
|
],
|
|
42981
|
-
"returnType": "number",
|
|
42981
|
+
"returnType": "{ line: number }",
|
|
42982
42982
|
"jsdoctags": [
|
|
42983
42983
|
{
|
|
42984
42984
|
"name": "source",
|
|
@@ -43002,7 +43002,7 @@
|
|
|
43002
43002
|
},
|
|
43003
43003
|
{
|
|
43004
43004
|
"name": "lineOf",
|
|
43005
|
-
"file": "packages/core/schematics/migrate-
|
|
43005
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
43006
43006
|
"ctype": "miscellaneous",
|
|
43007
43007
|
"subtype": "function",
|
|
43008
43008
|
"coverageIgnore": false,
|
|
@@ -43025,7 +43025,7 @@
|
|
|
43025
43025
|
"deprecationMessage": ""
|
|
43026
43026
|
}
|
|
43027
43027
|
],
|
|
43028
|
-
"returnType": "
|
|
43028
|
+
"returnType": "number",
|
|
43029
43029
|
"jsdoctags": [
|
|
43030
43030
|
{
|
|
43031
43031
|
"name": "source",
|
|
@@ -45751,7 +45751,7 @@
|
|
|
45751
45751
|
},
|
|
45752
45752
|
{
|
|
45753
45753
|
"name": "migrateInlineTemplates",
|
|
45754
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
45754
|
+
"file": "packages/core/schematics/migrate-eui-dialog/index.ts",
|
|
45755
45755
|
"ctype": "miscellaneous",
|
|
45756
45756
|
"subtype": "function",
|
|
45757
45757
|
"coverageIgnore": false,
|
|
@@ -45766,6 +45766,11 @@
|
|
|
45766
45766
|
"type": "string",
|
|
45767
45767
|
"deprecated": false,
|
|
45768
45768
|
"deprecationMessage": ""
|
|
45769
|
+
},
|
|
45770
|
+
{
|
|
45771
|
+
"name": "warn",
|
|
45772
|
+
"deprecated": false,
|
|
45773
|
+
"deprecationMessage": ""
|
|
45769
45774
|
}
|
|
45770
45775
|
],
|
|
45771
45776
|
"returnType": "string",
|
|
@@ -45778,12 +45783,20 @@
|
|
|
45778
45783
|
"tagName": {
|
|
45779
45784
|
"text": "param"
|
|
45780
45785
|
}
|
|
45786
|
+
},
|
|
45787
|
+
{
|
|
45788
|
+
"name": "warn",
|
|
45789
|
+
"deprecated": false,
|
|
45790
|
+
"deprecationMessage": "",
|
|
45791
|
+
"tagName": {
|
|
45792
|
+
"text": "param"
|
|
45793
|
+
}
|
|
45781
45794
|
}
|
|
45782
45795
|
]
|
|
45783
45796
|
},
|
|
45784
45797
|
{
|
|
45785
45798
|
"name": "migrateInlineTemplates",
|
|
45786
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
45799
|
+
"file": "packages/core/schematics/migrate-eui-discussion-thread/index.ts",
|
|
45787
45800
|
"ctype": "miscellaneous",
|
|
45788
45801
|
"subtype": "function",
|
|
45789
45802
|
"coverageIgnore": false,
|
|
@@ -45798,11 +45811,6 @@
|
|
|
45798
45811
|
"type": "string",
|
|
45799
45812
|
"deprecated": false,
|
|
45800
45813
|
"deprecationMessage": ""
|
|
45801
|
-
},
|
|
45802
|
-
{
|
|
45803
|
-
"name": "warn",
|
|
45804
|
-
"deprecated": false,
|
|
45805
|
-
"deprecationMessage": ""
|
|
45806
45814
|
}
|
|
45807
45815
|
],
|
|
45808
45816
|
"returnType": "string",
|
|
@@ -45815,14 +45823,6 @@
|
|
|
45815
45823
|
"tagName": {
|
|
45816
45824
|
"text": "param"
|
|
45817
45825
|
}
|
|
45818
|
-
},
|
|
45819
|
-
{
|
|
45820
|
-
"name": "warn",
|
|
45821
|
-
"deprecated": false,
|
|
45822
|
-
"deprecationMessage": "",
|
|
45823
|
-
"tagName": {
|
|
45824
|
-
"text": "param"
|
|
45825
|
-
}
|
|
45826
45826
|
}
|
|
45827
45827
|
]
|
|
45828
45828
|
},
|
|
@@ -48823,7 +48823,7 @@
|
|
|
48823
48823
|
},
|
|
48824
48824
|
{
|
|
48825
48825
|
"name": "migrateTypeScript",
|
|
48826
|
-
"file": "packages/core/schematics/migrate-
|
|
48826
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
48827
48827
|
"ctype": "miscellaneous",
|
|
48828
48828
|
"subtype": "function",
|
|
48829
48829
|
"coverageIgnore": false,
|
|
@@ -48850,12 +48850,6 @@
|
|
|
48850
48850
|
"type": "SchematicContext",
|
|
48851
48851
|
"deprecated": false,
|
|
48852
48852
|
"deprecationMessage": ""
|
|
48853
|
-
},
|
|
48854
|
-
{
|
|
48855
|
-
"name": "env",
|
|
48856
|
-
"type": "TsEnv",
|
|
48857
|
-
"deprecated": false,
|
|
48858
|
-
"deprecationMessage": ""
|
|
48859
48853
|
}
|
|
48860
48854
|
],
|
|
48861
48855
|
"returnType": "string",
|
|
@@ -48886,21 +48880,12 @@
|
|
|
48886
48880
|
"tagName": {
|
|
48887
48881
|
"text": "param"
|
|
48888
48882
|
}
|
|
48889
|
-
},
|
|
48890
|
-
{
|
|
48891
|
-
"name": "env",
|
|
48892
|
-
"type": "TsEnv",
|
|
48893
|
-
"deprecated": false,
|
|
48894
|
-
"deprecationMessage": "",
|
|
48895
|
-
"tagName": {
|
|
48896
|
-
"text": "param"
|
|
48897
|
-
}
|
|
48898
48883
|
}
|
|
48899
48884
|
]
|
|
48900
48885
|
},
|
|
48901
48886
|
{
|
|
48902
48887
|
"name": "migrateTypeScript",
|
|
48903
|
-
"file": "packages/core/schematics/migrate-
|
|
48888
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
48904
48889
|
"ctype": "miscellaneous",
|
|
48905
48890
|
"subtype": "function",
|
|
48906
48891
|
"coverageIgnore": false,
|
|
@@ -48927,6 +48912,12 @@
|
|
|
48927
48912
|
"type": "SchematicContext",
|
|
48928
48913
|
"deprecated": false,
|
|
48929
48914
|
"deprecationMessage": ""
|
|
48915
|
+
},
|
|
48916
|
+
{
|
|
48917
|
+
"name": "env",
|
|
48918
|
+
"type": "TsEnv",
|
|
48919
|
+
"deprecated": false,
|
|
48920
|
+
"deprecationMessage": ""
|
|
48930
48921
|
}
|
|
48931
48922
|
],
|
|
48932
48923
|
"returnType": "string",
|
|
@@ -48957,6 +48948,15 @@
|
|
|
48957
48948
|
"tagName": {
|
|
48958
48949
|
"text": "param"
|
|
48959
48950
|
}
|
|
48951
|
+
},
|
|
48952
|
+
{
|
|
48953
|
+
"name": "env",
|
|
48954
|
+
"type": "TsEnv",
|
|
48955
|
+
"deprecated": false,
|
|
48956
|
+
"deprecationMessage": "",
|
|
48957
|
+
"tagName": {
|
|
48958
|
+
"text": "param"
|
|
48959
|
+
}
|
|
48960
48960
|
}
|
|
48961
48961
|
]
|
|
48962
48962
|
},
|
|
@@ -50348,14 +50348,14 @@
|
|
|
50348
50348
|
},
|
|
50349
50349
|
{
|
|
50350
50350
|
"name": "removeObjectProperty",
|
|
50351
|
-
"file": "packages/core/schematics/migrate-
|
|
50351
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
50352
50352
|
"ctype": "miscellaneous",
|
|
50353
50353
|
"subtype": "function",
|
|
50354
50354
|
"coverageIgnore": false,
|
|
50355
50355
|
"deprecated": false,
|
|
50356
50356
|
"deprecationMessage": "",
|
|
50357
|
-
"rawdescription": "
|
|
50358
|
-
"description": "
|
|
50357
|
+
"rawdescription": "",
|
|
50358
|
+
"description": "",
|
|
50359
50359
|
"displayName": "removeObjectProperty",
|
|
50360
50360
|
"args": [
|
|
50361
50361
|
{
|
|
@@ -50364,7 +50364,7 @@
|
|
|
50364
50364
|
"deprecationMessage": ""
|
|
50365
50365
|
},
|
|
50366
50366
|
{
|
|
50367
|
-
"name": "
|
|
50367
|
+
"name": "sourceFile",
|
|
50368
50368
|
"deprecated": false,
|
|
50369
50369
|
"deprecationMessage": ""
|
|
50370
50370
|
},
|
|
@@ -50385,7 +50385,7 @@
|
|
|
50385
50385
|
}
|
|
50386
50386
|
},
|
|
50387
50387
|
{
|
|
50388
|
-
"name": "
|
|
50388
|
+
"name": "sourceFile",
|
|
50389
50389
|
"deprecated": false,
|
|
50390
50390
|
"deprecationMessage": "",
|
|
50391
50391
|
"tagName": {
|
|
@@ -50404,14 +50404,14 @@
|
|
|
50404
50404
|
},
|
|
50405
50405
|
{
|
|
50406
50406
|
"name": "removeObjectProperty",
|
|
50407
|
-
"file": "packages/core/schematics/migrate-
|
|
50407
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
50408
50408
|
"ctype": "miscellaneous",
|
|
50409
50409
|
"subtype": "function",
|
|
50410
50410
|
"coverageIgnore": false,
|
|
50411
50411
|
"deprecated": false,
|
|
50412
50412
|
"deprecationMessage": "",
|
|
50413
|
-
"rawdescription": "",
|
|
50414
|
-
"description": "",
|
|
50413
|
+
"rawdescription": "Removes one object property together with its separating comma.",
|
|
50414
|
+
"description": "<p>Removes one object property together with its separating comma.</p>\n",
|
|
50415
50415
|
"displayName": "removeObjectProperty",
|
|
50416
50416
|
"args": [
|
|
50417
50417
|
{
|
|
@@ -50420,7 +50420,7 @@
|
|
|
50420
50420
|
"deprecationMessage": ""
|
|
50421
50421
|
},
|
|
50422
50422
|
{
|
|
50423
|
-
"name": "
|
|
50423
|
+
"name": "sf",
|
|
50424
50424
|
"deprecated": false,
|
|
50425
50425
|
"deprecationMessage": ""
|
|
50426
50426
|
},
|
|
@@ -50441,7 +50441,7 @@
|
|
|
50441
50441
|
}
|
|
50442
50442
|
},
|
|
50443
50443
|
{
|
|
50444
|
-
"name": "
|
|
50444
|
+
"name": "sf",
|
|
50445
50445
|
"deprecated": false,
|
|
50446
50446
|
"deprecationMessage": "",
|
|
50447
50447
|
"tagName": {
|
|
@@ -55688,7 +55688,7 @@
|
|
|
55688
55688
|
},
|
|
55689
55689
|
{
|
|
55690
55690
|
"name": "visitDir",
|
|
55691
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
55691
|
+
"file": "packages/core/schematics/migrate-eui-dialog/index.ts",
|
|
55692
55692
|
"ctype": "miscellaneous",
|
|
55693
55693
|
"subtype": "function",
|
|
55694
55694
|
"coverageIgnore": false,
|
|
@@ -55733,7 +55733,7 @@
|
|
|
55733
55733
|
},
|
|
55734
55734
|
{
|
|
55735
55735
|
"name": "visitDir",
|
|
55736
|
-
"file": "packages/core/schematics/migrate-eui-
|
|
55736
|
+
"file": "packages/core/schematics/migrate-eui-discussion-thread/index.ts",
|
|
55737
55737
|
"ctype": "miscellaneous",
|
|
55738
55738
|
"subtype": "function",
|
|
55739
55739
|
"coverageIgnore": false,
|
|
@@ -56273,7 +56273,7 @@
|
|
|
56273
56273
|
},
|
|
56274
56274
|
{
|
|
56275
56275
|
"name": "visitDir",
|
|
56276
|
-
"file": "packages/core/schematics/migrate-
|
|
56276
|
+
"file": "packages/core/schematics/migrate-eui-tooltip/index.ts",
|
|
56277
56277
|
"ctype": "miscellaneous",
|
|
56278
56278
|
"subtype": "function",
|
|
56279
56279
|
"coverageIgnore": false,
|
|
@@ -56318,7 +56318,7 @@
|
|
|
56318
56318
|
},
|
|
56319
56319
|
{
|
|
56320
56320
|
"name": "visitDir",
|
|
56321
|
-
"file": "packages/core/schematics/migrate-
|
|
56321
|
+
"file": "packages/core/schematics/migrate-ngx-translate-18/index.ts",
|
|
56322
56322
|
"ctype": "miscellaneous",
|
|
56323
56323
|
"subtype": "function",
|
|
56324
56324
|
"coverageIgnore": false,
|
|
@@ -56363,7 +56363,7 @@
|
|
|
56363
56363
|
},
|
|
56364
56364
|
{
|
|
56365
56365
|
"name": "visitDir",
|
|
56366
|
-
"file": "packages/core/schematics/migrate-to-
|
|
56366
|
+
"file": "packages/core/schematics/migrate-to-standalone/index.ts",
|
|
56367
56367
|
"ctype": "miscellaneous",
|
|
56368
56368
|
"subtype": "function",
|
|
56369
56369
|
"coverageIgnore": false,
|
|
@@ -56408,7 +56408,7 @@
|
|
|
56408
56408
|
},
|
|
56409
56409
|
{
|
|
56410
56410
|
"name": "visitDir",
|
|
56411
|
-
"file": "packages/core/schematics/migrate-to-
|
|
56411
|
+
"file": "packages/core/schematics/migrate-to-signals/index.ts",
|
|
56412
56412
|
"ctype": "miscellaneous",
|
|
56413
56413
|
"subtype": "function",
|
|
56414
56414
|
"coverageIgnore": false,
|