@sixbell-telco/sdk 4.4.0 → 4.6.0
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 +272 -985
- package/GLOSSARY.md +76 -0
- package/README.md +143 -1346
- package/banner.webp +0 -0
- package/components/badge/src/badge.component.d.ts +6 -1
- package/components/dropdown-menu/README.md +1 -0
- package/components/dropdown-menu/bar/dropdown-menu-bar/dropdown-menu-bar.component.d.ts +2 -0
- package/components/dropdown-menu/bar/dropdown-menu-bar-sub-trigger/dropdown-menu-bar-sub-trigger.component.d.ts +9 -2
- package/components/dropdown-menu/bar/dropdown-menu-bar-trigger/dropdown-menu-bar-trigger.component.d.ts +6 -0
- package/components/dropdown-menu/context/dropdown-context-menu-trigger/dropdown-context-menu-trigger.component.d.ts +7 -0
- package/components/dropdown-menu/public-api.d.ts +1 -0
- package/components/dropdown-menu/src/directives/dropdown-menu-keyboard.directive.d.ts +54 -0
- package/components/dropdown-menu/src/dropdown-menu-sub-trigger/dropdown-menu-sub-trigger.component.d.ts +5 -0
- package/components/dropdown-menu/src/dropdown-menu-trigger/dropdown-menu-trigger.component.d.ts +15 -2
- package/components/forms/checkbox/src/checkbox.component.d.ts +12 -1
- package/components/status-illustration/README.md +38 -0
- package/components/status-illustration/index.d.ts +5 -0
- package/components/status-illustration/public-api.d.ts +1 -0
- package/components/status-illustration/src/status-illustration.component.d.ts +42 -0
- package/components/tab/directives/tab-content/tab-content.directive.d.ts +1 -1
- package/components/tree/README.md +11 -1
- package/components/tree/src/tree.component.d.ts +44 -5
- package/components/wizard/README.md +17 -0
- package/components/wizard/services/wizard.service.d.ts +9 -0
- package/components/wizard/wizard-indicator/wizard-indicator.component.d.ts +71 -0
- package/components/wizard/wizard-wrapper/wizard-wrapper.component.d.ts +24 -1
- package/directives/text/src/text.directive.d.ts +6 -2
- package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs +5 -5
- package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-badge.mjs +8 -2
- package/fesm2022/sixbell-telco-sdk-components-badge.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-button.mjs +1 -1
- package/fesm2022/sixbell-telco-sdk-components-button.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-card.mjs +3 -3
- package/fesm2022/sixbell-telco-sdk-components-card.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-data-table.mjs +4 -4
- package/fesm2022/sixbell-telco-sdk-components-data-table.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dialog.mjs +3 -3
- package/fesm2022/sixbell-telco-sdk-components-dialog.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-bar.mjs +92 -25
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-bar.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-context.mjs +29 -3
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu-context.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs +271 -21
- package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs +1 -1
- package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-checkbox.mjs +14 -3
- package/fesm2022/sixbell-telco-sdk-components-forms-checkbox.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-form-error.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-forms-form-error.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs +15 -5
- package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-paginator.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-paginator.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-product-card.mjs +1 -1
- package/fesm2022/sixbell-telco-sdk-components-product-card.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-segmented-button.mjs +1 -1
- package/fesm2022/sixbell-telco-sdk-components-segmented-button.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-sonner.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-components-sonner.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-status-illustration.mjs +66 -0
- package/fesm2022/sixbell-telco-sdk-components-status-illustration.mjs.map +1 -0
- package/fesm2022/sixbell-telco-sdk-components-tab.mjs +1 -0
- package/fesm2022/sixbell-telco-sdk-components-tab.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-table.mjs +4 -4
- package/fesm2022/sixbell-telco-sdk-components-table.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-tooltip.mjs +1 -1
- package/fesm2022/sixbell-telco-sdk-components-tooltip.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-tree.mjs +171 -51
- package/fesm2022/sixbell-telco-sdk-components-tree.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-components-wizard.mjs +123 -356
- package/fesm2022/sixbell-telco-sdk-components-wizard.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-directives-text.mjs +4 -1
- package/fesm2022/sixbell-telco-sdk-directives-text.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-directives-truncate.mjs +2 -2
- package/fesm2022/sixbell-telco-sdk-directives-truncate.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-layouts.mjs +61 -17
- package/fesm2022/sixbell-telco-sdk-layouts.mjs.map +1 -1
- package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +23 -4
- package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
- package/i18n/sdk/en.json +4 -1
- package/i18n/sdk/es.json +4 -1
- package/i18n/sdk/pt.json +4 -1
- package/layouts/README.md +24 -6
- package/layouts/public-api.d.ts +1 -1
- package/layouts/src/layout-account.d.ts +16 -0
- package/layouts/src/page-banner/page-banner.component.d.ts +37 -6
- package/layouts/src/user-menu/user-menu.component.d.ts +4 -2
- package/manifest.json +10943 -0
- package/package.json +50 -38
- package/schematics/lib/plan.cjs +179 -0
- package/schematics/lib/tokens.cjs +133 -0
- package/schematics/lib/workspace.cjs +118 -0
- package/schematics/manual-steps.json +90 -0
- package/schematics/migration.json +15 -0
- package/schematics/migrations/v4-0-0/assets.cjs +331 -0
- package/schematics/migrations/v4-0-0/canonical/enghouse_networks.json +360 -0
- package/schematics/migrations/v4-0-0/canonical/shell.json +25 -0
- package/schematics/migrations/v4-0-0/canonical/theme-assets.json +44 -0
- package/schematics/migrations/v4-0-0/canonical/themes.json +11 -0
- package/schematics/migrations/v4-0-0/index.cjs +96 -0
- package/schematics/migrations/v4-0-0/layout.cjs +269 -0
- package/schematics/migrations/v4-0-0/shell.cjs +1864 -0
- package/schematics/migrations/v4-6-0/index.cjs +394 -0
- package/src/_index.css +257 -26
- package/utils/theme/README.md +1 -1
- package/utils/theme/public-api.d.ts +1 -1
- package/utils/theme/src/models/theme.d.ts +10 -0
- package/utils/theme/src/theme-assets/theme-assets.service.d.ts +12 -1
- package/banner.png +0 -0
- package/components/wizard/wizard-marker/wizard-marker.component.d.ts +0 -85
- package/components/wizard/wizard-step/wizard-step.component.d.ts +0 -83
- package/components/wizard/wizard-sub-step/wizard-sub-step.component.d.ts +0 -95
|
@@ -0,0 +1,1864 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* The shell step of the 4.0.0 migration, ported from the mfe-tools apply-sdk4-shell script: the kit
|
|
4
|
+
* `st-app-layout` shell, the kit layout/account/HTTP/title/favicon providers, the menu adapter, the
|
|
5
|
+
* child `MfeShadowShellComponent` route and the pruning of the legacy local shell.
|
|
6
|
+
*
|
|
7
|
+
* Planning reads the tree only; unsupported shapes become conflicts (manual items) instead of a
|
|
8
|
+
* partial rewrite, and any conflict leaves every shell file unchanged. TypeScript edits use the
|
|
9
|
+
* TypeScript AST of the app. Module resolution runs on the tree (tsconfig paths included).
|
|
10
|
+
*/
|
|
11
|
+
const path = require('node:path').posix;
|
|
12
|
+
const ts = require('typescript');
|
|
13
|
+
const { hashContent, hashFile, listFiles, readText, treeHost } = require('../../lib/plan.cjs');
|
|
14
|
+
const { resolveLayoutConfig, syncAppLayoutInputs, validateLayoutConfig, renderShellTemplate } = require('./layout.cjs');
|
|
15
|
+
|
|
16
|
+
/** The tree the current plan reads, and a TypeScript host over it (set by buildShellPlan). */
|
|
17
|
+
let TREE = null;
|
|
18
|
+
let HOST = null;
|
|
19
|
+
|
|
20
|
+
const FOUNDATION_CONFIG = 'mfe-foundation.config.json';
|
|
21
|
+
/**
|
|
22
|
+
* How to run this migration again once a manual item is resolved. `ng update --migrate-only` refuses
|
|
23
|
+
* a dirty tree (commit first or add --allow-dirty); without --to it runs every migration up to the
|
|
24
|
+
* installed version, so the 4.6.0 renames also reach what 4.0.0 writes. Reruns are idempotent.
|
|
25
|
+
*/
|
|
26
|
+
const RERUN = 'ng update @sixbell-telco/sdk --migrate-only --from 3.99.0';
|
|
27
|
+
const MAIN_LAYOUT_TS = 'src/app/core/layouts/main-layout/main-layout.component.ts';
|
|
28
|
+
const MAIN_LAYOUT_HTML = 'src/app/core/layouts/main-layout/main-layout.component.html';
|
|
29
|
+
const MAIN_LAYOUT_SPEC = 'src/app/core/layouts/main-layout/main-layout.component.spec.ts';
|
|
30
|
+
const APP_CONFIG = 'src/app/app.config.ts';
|
|
31
|
+
const LAYOUT_ACCOUNT_PROVIDER = 'src/app/core/providers/layout-account.provider.ts';
|
|
32
|
+
const LAYOUT_ACCOUNT_SPEC = 'src/app/core/providers/layout-account.provider.spec.ts';
|
|
33
|
+
const HTTP_MODEL = 'src/app/core/models/Http.ts';
|
|
34
|
+
const MENU_MODEL = 'src/app/core/models/Menu.ts';
|
|
35
|
+
const MENU_SERVICE = 'src/app/core/services/menu/menu.service.ts';
|
|
36
|
+
const ENVIRONMENT_DIR = 'src/environments';
|
|
37
|
+
|
|
38
|
+
const SKIP_DIRS = new Set([
|
|
39
|
+
'.git',
|
|
40
|
+
'node_modules',
|
|
41
|
+
'dist',
|
|
42
|
+
'coverage',
|
|
43
|
+
'.angular',
|
|
44
|
+
'.nx',
|
|
45
|
+
'tmp',
|
|
46
|
+
'out-tsc',
|
|
47
|
+
'.agents',
|
|
48
|
+
'.claude',
|
|
49
|
+
'.opencode',
|
|
50
|
+
'.cursor',
|
|
51
|
+
'.superpowers',
|
|
52
|
+
]);
|
|
53
|
+
const SCRIPT_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs'];
|
|
54
|
+
const TEXT_EXTENSIONS = new Set(['.ts', '.html', '.json', '.js', '.mjs', '.css', '.scss']);
|
|
55
|
+
|
|
56
|
+
/** Obsolete local shell implementations the kit `st-app-layout` replaces. */
|
|
57
|
+
const LEGACY_SHELL_FILES = [
|
|
58
|
+
{ ts: 'src/app/core/layouts/navigation/navbar/navbar.component.ts', selector: 'app-navbar' },
|
|
59
|
+
{ ts: 'src/app/core/layouts/navigation/side-menu/side-menu.component.ts', selector: 'app-side-menu' },
|
|
60
|
+
{ ts: 'src/app/shared/components/navigation/sidebar/sidebar.component.ts', selector: 'app-sidebar' },
|
|
61
|
+
{ ts: 'src/app/shared/components/sidebar-avatar-dropdown/sidebar-avatar-dropdown.component.ts', selector: 'app-sidebar-avatar-dropdown' },
|
|
62
|
+
{ ts: 'src/app/shared/components/layout-switcher-dialog/layout-switcher-dialog.component.ts', selector: 'app-layout-switcher-dialog' },
|
|
63
|
+
{ ts: 'src/app/shared/components/page-banner/page-banner.component.ts', selector: 'app-page-banner' },
|
|
64
|
+
{ ts: 'src/app/core/services/layout/layout.service.ts', selector: null },
|
|
65
|
+
{ ts: 'src/app/core/interceptors/token/token.interceptor.ts', selector: null },
|
|
66
|
+
{
|
|
67
|
+
ts: 'src/app/core/providers/custom-page-title-strategy.ts',
|
|
68
|
+
selector: null,
|
|
69
|
+
companions: ['src/app/core/providers/custom-page-title.stragety.spec.ts'],
|
|
70
|
+
},
|
|
71
|
+
{ ts: 'src/app/core/services/favicon/favicon.service.ts', selector: null },
|
|
72
|
+
].map((legacy) => ({
|
|
73
|
+
...legacy,
|
|
74
|
+
token: legacy.ts.replace(/^src\/app\//, '').replace(/\.ts$/, ''),
|
|
75
|
+
base: legacy.ts.replace(/^.*\//, '').replace(/\.ts$/, ''),
|
|
76
|
+
}));
|
|
77
|
+
|
|
78
|
+
const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
79
|
+
|
|
80
|
+
function conflict(target, ruleId, message) {
|
|
81
|
+
return { path: target, ruleId, message };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function variantPaths(tsPath) {
|
|
85
|
+
return [tsPath, tsPath.replace(/\.ts$/, '.html'), tsPath.replace(/\.ts$/, '.spec.ts')];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function readTextOrNull(_root, relative) {
|
|
89
|
+
return readText(TREE, relative);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function hashFileOrNull(_root, relative) {
|
|
93
|
+
return hashFile(TREE, relative);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const SCRIPT_FILE = /\.(?:ts|html|js|mjs|cjs)$/;
|
|
97
|
+
|
|
98
|
+
/** Script and template files of the project (not dependencies, build output or dot folders). */
|
|
99
|
+
async function listProjectFiles() {
|
|
100
|
+
return listFiles(TREE, '', (name) => SCRIPT_FILE.test(name));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Text files under src. */
|
|
104
|
+
async function listSourceFiles() {
|
|
105
|
+
return listFiles(TREE, 'src', (name) => TEXT_EXTENSIONS.has(path.extname(name)));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// --- TypeScript helpers -----------------------------------------------------
|
|
109
|
+
|
|
110
|
+
function parseSourceFile(filePath, source) {
|
|
111
|
+
return ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sliceNode(source, node) {
|
|
115
|
+
return source.slice(node.getStart(), node.getEnd());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function identifierSet(node) {
|
|
119
|
+
const names = new Set();
|
|
120
|
+
const visit = (current) => {
|
|
121
|
+
if (ts.isIdentifier(current)) names.add(current.text);
|
|
122
|
+
ts.forEachChild(current, visit);
|
|
123
|
+
};
|
|
124
|
+
visit(node);
|
|
125
|
+
return names;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Named/default/namespace bindings of every import declaration, with their specifier. */
|
|
129
|
+
function collectImportBindings(ast) {
|
|
130
|
+
const bindings = [];
|
|
131
|
+
for (const statement of ast.statements) {
|
|
132
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
133
|
+
const specifier = statement.moduleSpecifier.text;
|
|
134
|
+
const clause = statement.importClause;
|
|
135
|
+
if (!clause) continue;
|
|
136
|
+
if (clause.name) bindings.push({ specifier, imported: 'default', local: clause.name.text });
|
|
137
|
+
if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {
|
|
138
|
+
bindings.push({ specifier, imported: '*', local: clause.namedBindings.name.text });
|
|
139
|
+
} else if (clause.namedBindings) {
|
|
140
|
+
for (const element of clause.namedBindings.elements) {
|
|
141
|
+
bindings.push({ specifier, imported: element.propertyName?.text ?? element.name.text, local: element.name.text });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return bindings;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function findImportDeclaration(ast, specifier) {
|
|
149
|
+
return (
|
|
150
|
+
ast.statements.find(
|
|
151
|
+
(statement) =>
|
|
152
|
+
ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === specifier,
|
|
153
|
+
) ?? null
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function usageCount(source, name) {
|
|
158
|
+
const pattern = new RegExp(`\\b${escapeRegExp(name)}\\b`, 'g');
|
|
159
|
+
return (source.match(pattern) ?? []).length;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Rewrites named imports with alias/collision safety. Returns { content, conflicts }. */
|
|
163
|
+
function applyImportEdits(source, ast, { add = [], remove = [] }) {
|
|
164
|
+
const conflicts = [];
|
|
165
|
+
const replacements = [];
|
|
166
|
+
const bindings = collectImportBindings(ast);
|
|
167
|
+
const bySpecifier = new Map();
|
|
168
|
+
for (const binding of bindings) {
|
|
169
|
+
if (!bySpecifier.has(binding.specifier)) bySpecifier.set(binding.specifier, []);
|
|
170
|
+
bySpecifier.get(binding.specifier).push(binding);
|
|
171
|
+
}
|
|
172
|
+
const localOwners = new Map();
|
|
173
|
+
for (const binding of bindings) {
|
|
174
|
+
if (!localOwners.has(binding.local)) localOwners.set(binding.local, `${binding.specifier}#${binding.imported}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const addsBySpecifier = new Map();
|
|
178
|
+
for (const entry of add) {
|
|
179
|
+
if (!addsBySpecifier.has(entry.specifier)) addsBySpecifier.set(entry.specifier, []);
|
|
180
|
+
addsBySpecifier.get(entry.specifier).push(entry);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
for (const [specifier, entries] of addsBySpecifier) {
|
|
184
|
+
const existing = findImportDeclaration(ast, specifier);
|
|
185
|
+
const names = [...new Set(entries.map((entry) => entry.name))];
|
|
186
|
+
const already = new Set((bySpecifier.get(specifier) ?? []).map((binding) => binding.imported));
|
|
187
|
+
for (const name of names) {
|
|
188
|
+
const owner = localOwners.get(name);
|
|
189
|
+
if (owner && owner !== `${specifier}#${name}`) {
|
|
190
|
+
conflicts.push(
|
|
191
|
+
conflict(APP_CONFIG, 'SDK4_SHELL_IMPORT_COLLISION', `cannot import ${name} from ${specifier}: the local name is already bound to ${owner}`),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const missing = names.filter((name) => !already.has(name));
|
|
196
|
+
if (missing.length === 0 || conflicts.length > 0) continue;
|
|
197
|
+
if (existing && existing.importClause?.namedBindings && ts.isNamedImports(existing.importClause.namedBindings)) {
|
|
198
|
+
const clause = existing.importClause.namedBindings;
|
|
199
|
+
const existingNames = clause.elements.map((element) => element.getText());
|
|
200
|
+
replacements.push({ start: clause.getStart(), end: clause.getEnd(), text: `{ ${[...existingNames, ...missing].join(', ')} }` });
|
|
201
|
+
} else {
|
|
202
|
+
const lastImport = [...ast.statements].reverse().find((statement) => ts.isImportDeclaration(statement));
|
|
203
|
+
const at = lastImport ? lastImport.getEnd() : 0;
|
|
204
|
+
replacements.push({ start: at, end: at, text: `\nimport { ${missing.join(', ')} } from '${specifier}';` });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const removeBySpecifier = new Map();
|
|
209
|
+
for (const entry of remove) {
|
|
210
|
+
if (!removeBySpecifier.has(entry.specifier)) removeBySpecifier.set(entry.specifier, new Set());
|
|
211
|
+
removeBySpecifier.get(entry.specifier).add(entry.name);
|
|
212
|
+
}
|
|
213
|
+
for (const [specifier, names] of removeBySpecifier) {
|
|
214
|
+
const declaration = findImportDeclaration(ast, specifier);
|
|
215
|
+
if (!declaration || !declaration.importClause?.namedBindings || !ts.isNamedImports(declaration.importClause.namedBindings)) continue;
|
|
216
|
+
const clause = declaration.importClause.namedBindings;
|
|
217
|
+
const remaining = clause.elements.filter(
|
|
218
|
+
(element) => !names.has(element.propertyName?.text ?? element.name.text) && !names.has(element.name.text),
|
|
219
|
+
);
|
|
220
|
+
if (remaining.length === clause.elements.length) continue;
|
|
221
|
+
if (remaining.length === 0) {
|
|
222
|
+
replacements.push({ start: declaration.getFullStart(), end: declaration.getEnd(), text: '' });
|
|
223
|
+
} else {
|
|
224
|
+
replacements.push({
|
|
225
|
+
start: clause.getStart(),
|
|
226
|
+
end: clause.getEnd(),
|
|
227
|
+
text: `{ ${remaining.map((element) => sliceNode(source, element)).join(', ')} }`,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (conflicts.length > 0) return { content: source, conflicts };
|
|
233
|
+
return { content: applyReplacements(source, replacements), conflicts };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Applies AST text replacements (non-overlapping) in one pass. */
|
|
237
|
+
function applyReplacements(source, replacements) {
|
|
238
|
+
return [...replacements]
|
|
239
|
+
.sort((left, right) => right.start - left.start)
|
|
240
|
+
.reduce((content, replacement) => `${content.slice(0, replacement.start)}${replacement.text}${content.slice(replacement.end)}`, source);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const KIT_PROVIDERS = [
|
|
244
|
+
{
|
|
245
|
+
symbol: 'provideLayout',
|
|
246
|
+
specifier: '@sixbell-telco/sdk/layouts',
|
|
247
|
+
environment: true,
|
|
248
|
+
call: (name) => `${name}({ defaultLayout: environment.defaultLayout })`,
|
|
249
|
+
},
|
|
250
|
+
{ symbol: 'provideAppLayoutAccount', specifier: '@core/providers/layout-account.provider', account: true, call: (name) => `${name}()` },
|
|
251
|
+
{
|
|
252
|
+
symbol: 'provideSchemeFavicon',
|
|
253
|
+
specifier: '@sixbell-telco/sdk/utils/theme',
|
|
254
|
+
call: (name) => `${name}({ light: '/assets/favicon/favicon-light.svg', dark: '/assets/favicon/favicon-dark.svg' })`,
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
symbol: 'provideTranslatedTitleStrategy',
|
|
258
|
+
specifier: '@sixbell-telco/sdk/utils/translation',
|
|
259
|
+
hostOnly: true,
|
|
260
|
+
call: (name) => `${name}({ fallbackKey: 'common.default_page_title' })`,
|
|
261
|
+
},
|
|
262
|
+
];
|
|
263
|
+
const KIT_SYMBOLS = new Set([...KIT_PROVIDERS.map((provider) => provider.symbol), 'provideAuthToken']);
|
|
264
|
+
const AUTH_TOKEN_PROVIDER = {
|
|
265
|
+
symbol: 'provideAuthToken',
|
|
266
|
+
specifier: '@sixbell-telco/sdk/utils/http',
|
|
267
|
+
call: (name) => `${name}(() => {\n\tconst session = inject(SessionService);\n\treturn () => session.token();\n})`,
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/** One indentation level next to `indent`: its own whitespace kind (two spaces for space-indented files). */
|
|
271
|
+
function indentUnit(indent) {
|
|
272
|
+
return indent.includes(' ') && !indent.includes('\t') ? ' ' : '\t';
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Re-indents a snippet written with one tab per level: its first line stays as is (it follows the
|
|
277
|
+
* insertion point), every next line gets `base` plus `unit` per leading tab.
|
|
278
|
+
* @param {string} text
|
|
279
|
+
* @param {string} base
|
|
280
|
+
* @param {string} unit
|
|
281
|
+
*/
|
|
282
|
+
function indentSnippet(text, base, unit) {
|
|
283
|
+
return text
|
|
284
|
+
.split('\n')
|
|
285
|
+
.map((line, index) => (index === 0 ? line : line.replace(/^\t*/, (tabs) => `${base}${unit.repeat(tabs.length)}`)))
|
|
286
|
+
.join('\n');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function findIdentifier(node, name) {
|
|
290
|
+
let found = null;
|
|
291
|
+
const visit = (current) => {
|
|
292
|
+
if (found) return;
|
|
293
|
+
if (ts.isIdentifier(current) && current.text === name) {
|
|
294
|
+
found = current;
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
ts.forEachChild(current, visit);
|
|
298
|
+
};
|
|
299
|
+
visit(node);
|
|
300
|
+
return found;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function dropElementRange(source, element) {
|
|
304
|
+
let start = element.getFullStart();
|
|
305
|
+
let end = element.getEnd();
|
|
306
|
+
let after = end;
|
|
307
|
+
while (after < source.length && /\s/.test(source[after])) after += 1;
|
|
308
|
+
if (source[after] === ',') end = after + 1;
|
|
309
|
+
else {
|
|
310
|
+
const comma = source.lastIndexOf(',', start);
|
|
311
|
+
if (comma !== -1) start = comma;
|
|
312
|
+
}
|
|
313
|
+
return { start, end, text: '' };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function removeIdentifierRange(source, node) {
|
|
317
|
+
let start = node.getStart();
|
|
318
|
+
let end = node.getEnd();
|
|
319
|
+
let after = end;
|
|
320
|
+
while (after < source.length && /\s/.test(source[after])) after += 1;
|
|
321
|
+
if (source[after] === ',') end = after + 1;
|
|
322
|
+
else {
|
|
323
|
+
let before = start;
|
|
324
|
+
while (before > 0 && /\s/.test(source[before - 1])) before -= 1;
|
|
325
|
+
if (source[before - 1] === ',') start = before - 1;
|
|
326
|
+
}
|
|
327
|
+
return { start, end, text: '' };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Resolve an identifier to the imported symbol it binds, if any. */
|
|
331
|
+
function resolveImportSymbol(bindings, localName) {
|
|
332
|
+
const binding = bindings.find((entry) => entry.local === localName);
|
|
333
|
+
return binding ? { imported: binding.imported, specifier: binding.specifier } : null;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function localNameFor(bindings, specifier, imported) {
|
|
337
|
+
const binding = bindings.find((entry) => entry.specifier === specifier && entry.imported === imported);
|
|
338
|
+
return binding ? binding.local : null;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Property name of a PropertyAssignment, from an identifier or a string-literal key. */
|
|
342
|
+
function propertyName(property) {
|
|
343
|
+
if (!ts.isPropertyAssignment(property)) return null;
|
|
344
|
+
if (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name)) return property.name.text;
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** The complete exact redundant local title provider: two fields, `provide: TitleStrategy`, `useClass: <local CustomPageTitleStrategy>`. */
|
|
349
|
+
function recognizeLocalTitleProvider(element, bindings, localTitleNames) {
|
|
350
|
+
if (!ts.isObjectLiteralExpression(element) || element.properties.length !== 2) return null;
|
|
351
|
+
let provideName = null;
|
|
352
|
+
let useClassName = null;
|
|
353
|
+
for (const property of element.properties) {
|
|
354
|
+
const name = propertyName(property);
|
|
355
|
+
if (name === 'provide' && ts.isIdentifier(property.initializer)) provideName = property.initializer.text;
|
|
356
|
+
else if (name === 'useClass' && ts.isIdentifier(property.initializer)) useClassName = property.initializer.text;
|
|
357
|
+
else return null;
|
|
358
|
+
}
|
|
359
|
+
if (!provideName || !useClassName) return null;
|
|
360
|
+
if (resolveImportSymbol(bindings, provideName)?.imported !== 'TitleStrategy') return null;
|
|
361
|
+
if (!localTitleNames.has(useClassName)) return null;
|
|
362
|
+
return { titleLocal: useClassName, routerLocal: provideName };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** A favicon initializer is `pure` only when its body is just `inject(<local FaviconService>)`. */
|
|
366
|
+
function recognizeFaviconInitializer(element, bindings, localFaviconNames) {
|
|
367
|
+
if (!ts.isCallExpression(element) || !ts.isIdentifier(element.expression)) return null;
|
|
368
|
+
const symbol = resolveImportSymbol(bindings, element.expression.text);
|
|
369
|
+
if (element.expression.text !== 'provideAppInitializer' && symbol?.imported !== 'provideAppInitializer') return null;
|
|
370
|
+
const callback = element.arguments[0];
|
|
371
|
+
if (!callback || !(ts.isArrowFunction(callback) || ts.isFunctionExpression(callback))) return null;
|
|
372
|
+
const injections = [];
|
|
373
|
+
const visit = (node) => {
|
|
374
|
+
if (
|
|
375
|
+
ts.isCallExpression(node) &&
|
|
376
|
+
ts.isIdentifier(node.expression) &&
|
|
377
|
+
node.expression.text === 'inject' &&
|
|
378
|
+
node.arguments[0] &&
|
|
379
|
+
ts.isIdentifier(node.arguments[0])
|
|
380
|
+
)
|
|
381
|
+
injections.push(node.arguments[0].text);
|
|
382
|
+
ts.forEachChild(node, visit);
|
|
383
|
+
};
|
|
384
|
+
visit(callback);
|
|
385
|
+
const faviconLocal = injections.find((name) => localFaviconNames.has(name));
|
|
386
|
+
if (!faviconLocal) return null;
|
|
387
|
+
const body = callback.body;
|
|
388
|
+
if (ts.isBlock(body)) {
|
|
389
|
+
const statements = [...body.statements];
|
|
390
|
+
const pure =
|
|
391
|
+
statements.length === 1 &&
|
|
392
|
+
ts.isExpressionStatement(statements[0]) &&
|
|
393
|
+
ts.isCallExpression(statements[0].expression) &&
|
|
394
|
+
ts.isIdentifier(statements[0].expression.expression) &&
|
|
395
|
+
statements[0].expression.expression.text === 'inject' &&
|
|
396
|
+
injections.length === 1;
|
|
397
|
+
return { kind: pure ? 'pure' : 'mixed', local: faviconLocal };
|
|
398
|
+
}
|
|
399
|
+
const pure = ts.isCallExpression(body) && ts.isIdentifier(body.expression) && body.expression.text === 'inject' && injections.length === 1;
|
|
400
|
+
return { kind: pure ? 'pure' : 'mixed', local: faviconLocal };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Rewrite the local token interceptor inside `withInterceptors([...])` to the kit bearer interceptor. */
|
|
404
|
+
function rewriteInterceptors(element, source, localTokenNames, bearerLocal) {
|
|
405
|
+
const replacements = [];
|
|
406
|
+
const removed = [];
|
|
407
|
+
const visit = (node) => {
|
|
408
|
+
if (
|
|
409
|
+
ts.isCallExpression(node) &&
|
|
410
|
+
ts.isIdentifier(node.expression) &&
|
|
411
|
+
node.expression.text === 'withInterceptors' &&
|
|
412
|
+
node.arguments[0] &&
|
|
413
|
+
ts.isArrayLiteralExpression(node.arguments[0])
|
|
414
|
+
) {
|
|
415
|
+
const array = node.arguments[0];
|
|
416
|
+
const hasBearer = array.elements.some(
|
|
417
|
+
(entry) => ts.isIdentifier(entry) && (entry.text === 'bearerTokenInterceptor' || entry.text === bearerLocal),
|
|
418
|
+
);
|
|
419
|
+
for (const entry of array.elements) {
|
|
420
|
+
if (!ts.isIdentifier(entry) || !localTokenNames.has(entry.text)) continue;
|
|
421
|
+
removed.push(entry.text);
|
|
422
|
+
if (hasBearer) replacements.push(removeIdentifierRange(source, entry));
|
|
423
|
+
else replacements.push({ start: entry.getStart(), end: entry.getEnd(), text: bearerLocal ?? 'bearerTokenInterceptor' });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
ts.forEachChild(node, visit);
|
|
427
|
+
};
|
|
428
|
+
visit(element);
|
|
429
|
+
return { replacements, removed };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function isTitleStrategyProvider(element, bindings) {
|
|
433
|
+
if (!ts.isObjectLiteralExpression(element)) return false;
|
|
434
|
+
for (const property of element.properties) {
|
|
435
|
+
if (propertyName(property) === 'provide' && ts.isIdentifier(property.initializer)) {
|
|
436
|
+
return resolveImportSymbol(bindings, property.initializer.text)?.imported === 'TitleStrategy';
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function collectPresentSymbols(element, bindings, presentSymbols, accountCalls) {
|
|
443
|
+
const visit = (node) => {
|
|
444
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
445
|
+
const symbol = resolveImportSymbol(bindings, node.expression.text);
|
|
446
|
+
const imported = symbol?.imported ?? node.expression.text;
|
|
447
|
+
if (imported === 'provideLayoutAccount') {
|
|
448
|
+
if (symbol?.specifier === '@sixbell-telco/sdk/layouts') presentSymbols.add('provideLayoutAccount');
|
|
449
|
+
} else if (imported === 'provideAppLayoutAccount') {
|
|
450
|
+
if (symbol?.specifier === '@core/providers/layout-account.provider') presentSymbols.add('provideAppLayoutAccount');
|
|
451
|
+
} else if (KIT_SYMBOLS.has(imported)) {
|
|
452
|
+
presentSymbols.add(imported);
|
|
453
|
+
}
|
|
454
|
+
if (/LayoutAccount$/.test(node.expression.text)) accountCalls.add(node.expression.text);
|
|
455
|
+
}
|
|
456
|
+
ts.forEachChild(node, visit);
|
|
457
|
+
};
|
|
458
|
+
visit(element);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Verify that a product account wrapper actually registers the SDK layout account:
|
|
463
|
+
* resolve the imported symbol to its module and check the function body calls the
|
|
464
|
+
* SDK `provideLayoutAccount`. `unknown` when the definition cannot be inspected.
|
|
465
|
+
*/
|
|
466
|
+
function verifyAccountWrapper(name, bindings, appConfigPath, options) {
|
|
467
|
+
const binding = bindings.find((entry) => entry.local === name);
|
|
468
|
+
if (!binding) return 'unknown';
|
|
469
|
+
const resolved = ts.resolveModuleName(binding.specifier, appConfigPath, options, HOST).resolvedModule?.resolvedFileName;
|
|
470
|
+
if (!resolved) return 'unknown';
|
|
471
|
+
const source = HOST.readFile(resolved);
|
|
472
|
+
if (source === undefined) return 'unknown';
|
|
473
|
+
const ast = parseSourceFile(resolved, source);
|
|
474
|
+
const moduleBindings = collectImportBindings(ast);
|
|
475
|
+
let target = null;
|
|
476
|
+
const visit = (node) => {
|
|
477
|
+
if (target) return;
|
|
478
|
+
if (
|
|
479
|
+
(ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node)) &&
|
|
480
|
+
node.name &&
|
|
481
|
+
ts.isIdentifier(node.name) &&
|
|
482
|
+
node.name.text === binding.imported
|
|
483
|
+
)
|
|
484
|
+
target = node;
|
|
485
|
+
ts.forEachChild(node, visit);
|
|
486
|
+
};
|
|
487
|
+
visit(ast);
|
|
488
|
+
if (!target) return 'unknown';
|
|
489
|
+
const body = ts.isFunctionDeclaration(target) ? target.body : target.initializer;
|
|
490
|
+
if (!body) return 'unknown';
|
|
491
|
+
let produces = false;
|
|
492
|
+
const scan = (node) => {
|
|
493
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
494
|
+
const symbol = resolveImportSymbol(moduleBindings, node.expression.text);
|
|
495
|
+
if (symbol?.imported === 'provideLayoutAccount' && symbol.specifier === '@sixbell-telco/sdk/layouts') produces = true;
|
|
496
|
+
}
|
|
497
|
+
ts.forEachChild(node, scan);
|
|
498
|
+
};
|
|
499
|
+
scan(body);
|
|
500
|
+
return produces ? 'verified' : 'unverified';
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Merge the kit providers into an existing app.config.ts with symbol-aware
|
|
505
|
+
* TypeScript AST range edits: add only missing kit providers (reusing an existing
|
|
506
|
+
* import alias), remove only the exact recognized local title/favicon duplicates,
|
|
507
|
+
* keep every business provider and its comments, and conflict on a name collision
|
|
508
|
+
* or a mixed initializer instead of silently dropping business work. The host-owned
|
|
509
|
+
* translated title strategy is only added when `context.role` is the host (the
|
|
510
|
+
* default): a child keeps Angular's DefaultTitleStrategy because the host owns the
|
|
511
|
+
* browser tab.
|
|
512
|
+
*/
|
|
513
|
+
function mergeAppConfig(source, filePath = APP_CONFIG, context = {}) {
|
|
514
|
+
const ast = parseSourceFile(filePath, source);
|
|
515
|
+
const variable = ast.statements
|
|
516
|
+
.filter(ts.isVariableStatement)
|
|
517
|
+
.flatMap((statement) => [...statement.declarationList.declarations])
|
|
518
|
+
.find((declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'appConfig');
|
|
519
|
+
const object = variable?.initializer && ts.isObjectLiteralExpression(variable.initializer) ? variable.initializer : null;
|
|
520
|
+
const providersProperty = object?.properties.find(
|
|
521
|
+
(property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'providers',
|
|
522
|
+
);
|
|
523
|
+
const array = providersProperty?.initializer && ts.isArrayLiteralExpression(providersProperty.initializer) ? providersProperty.initializer : null;
|
|
524
|
+
if (!array)
|
|
525
|
+
return {
|
|
526
|
+
content: source,
|
|
527
|
+
conflicts: [
|
|
528
|
+
conflict(
|
|
529
|
+
filePath,
|
|
530
|
+
'SDK4_SHELL_APP_CONFIG_001',
|
|
531
|
+
'app.config.ts does not declare `appConfig` with a `providers` array; adopt the shell providers manually',
|
|
532
|
+
),
|
|
533
|
+
],
|
|
534
|
+
addedAccount: false,
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
const bindings = collectImportBindings(ast);
|
|
538
|
+
const localTokenNames = new Set(
|
|
539
|
+
bindings.filter((entry) => entry.specifier === '@core/interceptors/token/token.interceptor').map((entry) => entry.local),
|
|
540
|
+
);
|
|
541
|
+
const localTitleNames = new Set(
|
|
542
|
+
bindings.filter((entry) => entry.specifier === '@core/providers/custom-page-title-strategy').map((entry) => entry.local),
|
|
543
|
+
);
|
|
544
|
+
const localFaviconNames = new Set(
|
|
545
|
+
bindings.filter((entry) => entry.specifier === '@core/services/favicon/favicon.service').map((entry) => entry.local),
|
|
546
|
+
);
|
|
547
|
+
const bearerLocal = localNameFor(bindings, '@sixbell-telco/sdk/utils/http', 'bearerTokenInterceptor');
|
|
548
|
+
|
|
549
|
+
const role = context.role === 'child' ? 'child' : 'host';
|
|
550
|
+
const replacements = [];
|
|
551
|
+
const removeImports = [];
|
|
552
|
+
const addImports = [];
|
|
553
|
+
const dropped = new Set();
|
|
554
|
+
const presentSymbols = new Set();
|
|
555
|
+
const accountCalls = new Set();
|
|
556
|
+
const conflicts = [];
|
|
557
|
+
let hasTitleStrategyProvider = false;
|
|
558
|
+
for (const element of array.elements) {
|
|
559
|
+
const titleDrop = recognizeLocalTitleProvider(element, bindings, localTitleNames);
|
|
560
|
+
if (titleDrop) {
|
|
561
|
+
replacements.push(dropElementRange(source, element));
|
|
562
|
+
dropped.add(element);
|
|
563
|
+
removeImports.push({ specifier: '@core/providers/custom-page-title-strategy', name: titleDrop.titleLocal });
|
|
564
|
+
removeImports.push({ specifier: '@angular/router', name: titleDrop.routerLocal });
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
const favicon = recognizeFaviconInitializer(element, bindings, localFaviconNames);
|
|
568
|
+
if (favicon?.kind === 'pure') {
|
|
569
|
+
replacements.push(dropElementRange(source, element));
|
|
570
|
+
dropped.add(element);
|
|
571
|
+
removeImports.push({ specifier: '@core/services/favicon/favicon.service', name: favicon.local });
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (favicon?.kind === 'mixed') {
|
|
575
|
+
conflicts.push(
|
|
576
|
+
conflict(
|
|
577
|
+
filePath,
|
|
578
|
+
'SDK4_SHELL_APP_CONFIG_005',
|
|
579
|
+
'provideAppInitializer mixes inject(FaviconService) with other work; remove only the favicon injection by hand and keep the rest',
|
|
580
|
+
),
|
|
581
|
+
);
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
const interceptor = rewriteInterceptors(element, source, localTokenNames, bearerLocal);
|
|
585
|
+
replacements.push(...interceptor.replacements);
|
|
586
|
+
for (const local of interceptor.removed) removeImports.push({ specifier: '@core/interceptors/token/token.interceptor', name: local });
|
|
587
|
+
if (isTitleStrategyProvider(element, bindings)) hasTitleStrategyProvider = true;
|
|
588
|
+
collectPresentSymbols(element, bindings, presentSymbols, accountCalls);
|
|
589
|
+
}
|
|
590
|
+
let hasAccountProvider = presentSymbols.has('provideLayoutAccount');
|
|
591
|
+
for (const name of accountCalls) {
|
|
592
|
+
if (hasAccountProvider) break;
|
|
593
|
+
const symbol = resolveImportSymbol(bindings, name);
|
|
594
|
+
if (symbol?.imported === 'provideLayoutAccount' && symbol.specifier === '@sixbell-telco/sdk/layouts') {
|
|
595
|
+
hasAccountProvider = true;
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
if (symbol?.imported === 'provideAppLayoutAccount' && symbol.specifier === '@core/providers/layout-account.provider') {
|
|
599
|
+
hasAccountProvider = true;
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
const verdict = context.accountResolver ? context.accountResolver(name, bindings) : 'unverified';
|
|
603
|
+
if (verdict === 'verified') hasAccountProvider = true;
|
|
604
|
+
else if (verdict === 'unknown')
|
|
605
|
+
conflicts.push(
|
|
606
|
+
conflict(
|
|
607
|
+
filePath,
|
|
608
|
+
'SDK4_SHELL_ACCOUNT_002',
|
|
609
|
+
`cannot verify that ${name}() registers the SDK layout account; register provideAppLayoutAccount or confirm the wrapper`,
|
|
610
|
+
),
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
const missing = KIT_PROVIDERS.filter((provider) => !presentSymbols.has(provider.symbol))
|
|
614
|
+
.filter((provider) => !(provider.account && hasAccountProvider))
|
|
615
|
+
.filter((provider) => !(provider.hostOnly && role === 'child'))
|
|
616
|
+
.filter((provider) => !(provider.symbol === 'provideTranslatedTitleStrategy' && hasTitleStrategyProvider));
|
|
617
|
+
const addedAccount = missing.some((provider) => provider.account);
|
|
618
|
+
const additions = [...missing];
|
|
619
|
+
if (!presentSymbols.has('provideAuthToken')) additions.push(AUTH_TOKEN_PROVIDER);
|
|
620
|
+
for (const provider of additions) {
|
|
621
|
+
if (provider.environment && !/from\s+['"]@env\/environment['"]/.test(source))
|
|
622
|
+
addImports.push({ specifier: '@env/environment', name: 'environment' });
|
|
623
|
+
const existingLocal = localNameFor(bindings, provider.specifier, provider.symbol);
|
|
624
|
+
if (existingLocal) provider.name = existingLocal;
|
|
625
|
+
else {
|
|
626
|
+
provider.name = provider.symbol;
|
|
627
|
+
addImports.push({ specifier: provider.specifier, name: provider.symbol });
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
if (additions.length > 0) {
|
|
631
|
+
// Inserted providers take the indentation of the array's elements (tabs or spaces, as the file has them).
|
|
632
|
+
const propertyIndent = lineIndent(source, providersProperty.getStart());
|
|
633
|
+
const last = array.elements[array.elements.length - 1];
|
|
634
|
+
const sameLine = (/** @type {number} */ position) => !source.slice(array.getStart(), position).includes('\n');
|
|
635
|
+
const elementIndent = last && !sameLine(last.getStart()) ? lineIndent(source, last.getStart()) : `${propertyIndent}${indentUnit(propertyIndent)}`;
|
|
636
|
+
const unit =
|
|
637
|
+
elementIndent.startsWith(propertyIndent) && elementIndent.length > propertyIndent.length ? elementIndent.slice(propertyIndent.length) : '\t';
|
|
638
|
+
const snippets = additions.map((provider) => indentSnippet(provider.call(provider.name), elementIndent, unit));
|
|
639
|
+
// The appended providers turn the array multiline, so it carries a trailing comma
|
|
640
|
+
// on its last element to match the canonical template and prettier `trailingComma: all`.
|
|
641
|
+
const snippetText = `${snippets.join(`,\n${elementIndent}`)},`;
|
|
642
|
+
if (last) {
|
|
643
|
+
let at = last.getEnd();
|
|
644
|
+
const comma = source.slice(at).match(/^[ \t]*,/);
|
|
645
|
+
if (comma) at += comma[0].length;
|
|
646
|
+
replacements.push({ start: at, end: at, text: `${comma ? '' : ','}\n${elementIndent}${snippetText}` });
|
|
647
|
+
} else {
|
|
648
|
+
replacements.push({ start: array.getStart() + 1, end: array.getStart() + 1, text: `\n${elementIndent}${snippetText}\n${propertyIndent}` });
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const withEdits = applyReplacements(source, replacements);
|
|
652
|
+
if (!bearerLocal && /\bbearerTokenInterceptor\b/.test(withEdits))
|
|
653
|
+
addImports.push({ specifier: '@sixbell-telco/sdk/utils/http', name: 'bearerTokenInterceptor' });
|
|
654
|
+
|
|
655
|
+
const removable = removeImports.filter((entry) => {
|
|
656
|
+
const clauseUses = (findImportDeclaration(ast, entry.specifier)?.importClause?.namedBindings?.elements ?? []).filter(
|
|
657
|
+
(element) => element.name.text === entry.name,
|
|
658
|
+
).length;
|
|
659
|
+
return usageCount(withEdits, entry.name) - clauseUses <= 0;
|
|
660
|
+
});
|
|
661
|
+
const reparse = parseSourceFile(filePath, withEdits);
|
|
662
|
+
const importEdits = applyImportEdits(withEdits, reparse, { add: addImports, remove: removable });
|
|
663
|
+
if (importEdits.conflicts.length > 0) return { content: source, conflicts: [...conflicts, ...importEdits.conflicts], addedAccount: false };
|
|
664
|
+
if (conflicts.length > 0) return { content: source, conflicts, addedAccount: false };
|
|
665
|
+
return { content: importEdits.content, conflicts: [], addedAccount };
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Replace a local BYPASS_INTERCEPTOR allocation (any HttpContextToken alias) with the SDK re-export. */
|
|
669
|
+
function mergeHttpModel(source, filePath = HTTP_MODEL) {
|
|
670
|
+
const ast = parseSourceFile(filePath, source);
|
|
671
|
+
const reexport = ast.statements.find(
|
|
672
|
+
(statement) =>
|
|
673
|
+
ts.isExportDeclaration(statement) &&
|
|
674
|
+
statement.moduleSpecifier &&
|
|
675
|
+
ts.isStringLiteral(statement.moduleSpecifier) &&
|
|
676
|
+
statement.moduleSpecifier.text === '@sixbell-telco/sdk/utils/http' &&
|
|
677
|
+
statement.exportClause &&
|
|
678
|
+
ts.isNamedExports(statement.exportClause) &&
|
|
679
|
+
statement.exportClause.elements.some((element) => element.name.text === 'BYPASS_INTERCEPTOR'),
|
|
680
|
+
);
|
|
681
|
+
if (reexport) return { content: source, conflicts: [] };
|
|
682
|
+
const declaration = ast.statements
|
|
683
|
+
.filter(ts.isVariableStatement)
|
|
684
|
+
.flatMap((statement) => [...statement.declarationList.declarations])
|
|
685
|
+
.find((candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === 'BYPASS_INTERCEPTOR');
|
|
686
|
+
if (!declaration) return { content: source, conflicts: [] };
|
|
687
|
+
const bindings = collectImportBindings(ast);
|
|
688
|
+
const initializer = declaration.initializer;
|
|
689
|
+
const constructorName =
|
|
690
|
+
initializer && ts.isNewExpression(initializer) && ts.isIdentifier(initializer.expression) ? initializer.expression.text : null;
|
|
691
|
+
const resolvesToContextToken =
|
|
692
|
+
constructorName !== null &&
|
|
693
|
+
(constructorName === 'HttpContextToken' || resolveImportSymbol(bindings, constructorName)?.imported === 'HttpContextToken');
|
|
694
|
+
if (!resolvesToContextToken) {
|
|
695
|
+
return {
|
|
696
|
+
content: source,
|
|
697
|
+
conflicts: [
|
|
698
|
+
conflict(
|
|
699
|
+
filePath,
|
|
700
|
+
'SDK4_SHELL_HTTP_001',
|
|
701
|
+
'BYPASS_INTERCEPTOR is declared but is not `new HttpContextToken(...)`; re-export it from @sixbell-telco/sdk/utils/http by hand',
|
|
702
|
+
),
|
|
703
|
+
],
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
const statement = ts.isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : declaration;
|
|
707
|
+
const declarationList = ts.isVariableStatement(statement) ? statement.declarationList : null;
|
|
708
|
+
const declarations = declarationList ? [...declarationList.declarations] : [declaration];
|
|
709
|
+
const reexportText = "export { BYPASS_INTERCEPTOR } from '@sixbell-telco/sdk/utils/http';";
|
|
710
|
+
let replacementText = reexportText;
|
|
711
|
+
if (declarations.length > 1) {
|
|
712
|
+
const keyword = declarationList.flags & ts.NodeFlags.Const ? 'const' : declarationList.flags & ts.NodeFlags.Let ? 'let' : 'var';
|
|
713
|
+
const exported = (statement.modifiers ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ? 'export ' : '';
|
|
714
|
+
const siblings = declarations
|
|
715
|
+
.filter((candidate) => candidate !== declaration)
|
|
716
|
+
.map((candidate) => `${exported}${keyword} ${candidate.getFullText().trim()};`);
|
|
717
|
+
replacementText = [reexportText, ...siblings].join('\n');
|
|
718
|
+
}
|
|
719
|
+
const withoutAllocation = applyReplacements(source, [{ start: statement.getStart(), end: statement.getEnd(), text: replacementText }]);
|
|
720
|
+
const stillUsed = new RegExp(`\\b${escapeRegExp(constructorName)}\\b`).test(withoutAllocation.replace(/import[^;]*;/g, ''));
|
|
721
|
+
if (!stillUsed) {
|
|
722
|
+
const nextAst = parseSourceFile(filePath, withoutAllocation);
|
|
723
|
+
const importEdits = applyImportEdits(withoutAllocation, nextAst, { remove: [{ specifier: '@angular/common/http', name: constructorName }] });
|
|
724
|
+
if (importEdits.conflicts.length === 0) return { content: importEdits.content, conflicts: [] };
|
|
725
|
+
}
|
|
726
|
+
return { content: withoutAllocation, conflicts: [] };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** Add `defaultLayout` from the approved config to every environment variant that lacks it. */
|
|
730
|
+
function mergeEnvironment(source, filePath, defaultLayout) {
|
|
731
|
+
const ast = parseSourceFile(filePath, source);
|
|
732
|
+
const variable = ast.statements
|
|
733
|
+
.filter(ts.isVariableStatement)
|
|
734
|
+
.flatMap((statement) => [...statement.declarationList.declarations])
|
|
735
|
+
.find((declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'environment');
|
|
736
|
+
const object = variable?.initializer && ts.isObjectLiteralExpression(variable.initializer) ? variable.initializer : null;
|
|
737
|
+
if (!object)
|
|
738
|
+
return {
|
|
739
|
+
content: source,
|
|
740
|
+
conflicts: [
|
|
741
|
+
conflict(
|
|
742
|
+
filePath,
|
|
743
|
+
'SDK4_SHELL_ENVIRONMENT_001',
|
|
744
|
+
'environment.ts does not declare an `environment` object literal; add defaultLayout manually',
|
|
745
|
+
),
|
|
746
|
+
],
|
|
747
|
+
};
|
|
748
|
+
const existing = object.properties.find(
|
|
749
|
+
(property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'defaultLayout',
|
|
750
|
+
);
|
|
751
|
+
if (existing) {
|
|
752
|
+
const initializer = ts.isAsExpression(existing.initializer) ? existing.initializer.expression : existing.initializer;
|
|
753
|
+
const value = ts.isStringLiteralLike(initializer) ? initializer.text : null;
|
|
754
|
+
if (value && value !== defaultLayout)
|
|
755
|
+
return {
|
|
756
|
+
content: source,
|
|
757
|
+
conflicts: [
|
|
758
|
+
conflict(
|
|
759
|
+
filePath,
|
|
760
|
+
'SDK4_SHELL_ENVIRONMENT_002',
|
|
761
|
+
`environment defaultLayout is "${value}" but the approved config is "${defaultLayout}"; reconcile them first`,
|
|
762
|
+
),
|
|
763
|
+
],
|
|
764
|
+
};
|
|
765
|
+
return { content: source, conflicts: [] };
|
|
766
|
+
}
|
|
767
|
+
const lastProperty = object.properties[object.properties.length - 1];
|
|
768
|
+
let insertAt = lastProperty ? lastProperty.getEnd() : object.getStart() + 1;
|
|
769
|
+
let needsComma = false;
|
|
770
|
+
if (lastProperty) {
|
|
771
|
+
const comma = source.slice(insertAt).match(/^[ \t]*,/);
|
|
772
|
+
if (comma) insertAt += comma[0].length;
|
|
773
|
+
else needsComma = true;
|
|
774
|
+
}
|
|
775
|
+
const indent = lastProperty ? lineIndent(source, lastProperty.getStart()) : '\t';
|
|
776
|
+
const addition = `${needsComma ? ',' : ''}\n${indent || '\t'}defaultLayout: '${defaultLayout}' as const,`;
|
|
777
|
+
return { content: `${source.slice(0, insertAt)}${addition}${source.slice(insertAt)}`, conflicts: [] };
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// --- menu adapter -----------------------------------------------------------
|
|
781
|
+
|
|
782
|
+
const CANONICAL_MENU_HELPERS = /export function menuIconForTag[\s\S]*?\n}\n[\s\S]*?export function toLayoutMenuItems[\s\S]*?\n}\n/;
|
|
783
|
+
const MENU_HELPER_NAMES = ['menuIconForTag', 'menuSidebarIcon', 'toLayoutMenuItems'];
|
|
784
|
+
const MENU_CHILDREN_GUARDED = /'submenu' in menu \? toLayoutMenuItems\(menu\.submenu, translate((?:, depth \+ 1)?)\) : \[\]/;
|
|
785
|
+
const MENU_CHILDREN_OPTIONAL = /Array\.isArray\(menu\.submenu\) \? toLayoutMenuItems\(menu\.submenu, translate((?:, depth \+ 1)?)\) : \[\]/;
|
|
786
|
+
|
|
787
|
+
function hasMenuHelper(source, name) {
|
|
788
|
+
return new RegExp(`export function ${name}\\b`).test(source);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** True when the product already exports the canonical `toLayoutMenuItems(menus, translate)` declaration. */
|
|
792
|
+
function hasCanonicalToLayoutMenuItems(ast) {
|
|
793
|
+
const declaration = ast.statements.find((statement) => ts.isFunctionDeclaration(statement) && statement.name?.text === 'toLayoutMenuItems');
|
|
794
|
+
const parameters = declaration?.parameters ?? [];
|
|
795
|
+
return (
|
|
796
|
+
parameters.length === 2 &&
|
|
797
|
+
ts.isIdentifier(parameters[0].name) &&
|
|
798
|
+
parameters[0].name.text === 'menus' &&
|
|
799
|
+
ts.isIdentifier(parameters[1].name) &&
|
|
800
|
+
parameters[1].name.text === 'translate'
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** True when the product's `menuSidebarIcon` takes the canonical structural `isTopLevel` parameter (or is absent, so the canonical one is appended). */
|
|
805
|
+
function sidebarIconTakesTopLevel(ast) {
|
|
806
|
+
const declaration = ast.statements.find((statement) => ts.isFunctionDeclaration(statement) && statement.name?.text === 'menuSidebarIcon');
|
|
807
|
+
return !declaration || declaration.parameters.length >= 2;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** True when the model already declares a `MenuNode` type alias or interface. */
|
|
811
|
+
function hasMenuNode(ast) {
|
|
812
|
+
return ast.statements.some(
|
|
813
|
+
(statement) => (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name.text === 'MenuNode',
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/** The canonical helper block split per function, each part carrying its leading doc comment. */
|
|
818
|
+
function splitMenuHelpers(block) {
|
|
819
|
+
const starts = [];
|
|
820
|
+
for (const name of MENU_HELPER_NAMES) {
|
|
821
|
+
const at = block.indexOf(`export function ${name}`);
|
|
822
|
+
if (at === -1) return null;
|
|
823
|
+
const before = block.slice(0, at);
|
|
824
|
+
const doc = before.lastIndexOf('/**');
|
|
825
|
+
starts.push(doc !== -1 && /^\/\*\*[\s\S]*\*\/\s*$/.test(before.slice(doc)) ? doc : at);
|
|
826
|
+
}
|
|
827
|
+
return MENU_HELPER_NAMES.map((name, index) => ({ name, text: block.slice(starts[index], starts[index + 1] ?? block.length).trim() }));
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** True when both `Menu` and `Submenu` keep `submenu`, so `menu.submenu` needs no `in` narrowing. */
|
|
831
|
+
function submenuOnBothNodes(ast) {
|
|
832
|
+
const declaresSubmenu = (node) => {
|
|
833
|
+
let found = false;
|
|
834
|
+
const visit = (current) => {
|
|
835
|
+
if (found) return;
|
|
836
|
+
if (
|
|
837
|
+
ts.isPropertySignature(current) &&
|
|
838
|
+
current.name &&
|
|
839
|
+
(ts.isIdentifier(current.name) || ts.isStringLiteralLike(current.name)) &&
|
|
840
|
+
current.name.text === 'submenu'
|
|
841
|
+
) {
|
|
842
|
+
found = true;
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
ts.forEachChild(current, visit);
|
|
846
|
+
};
|
|
847
|
+
if (node) visit(node);
|
|
848
|
+
return found;
|
|
849
|
+
};
|
|
850
|
+
const menu = ast.statements.find((statement) => ts.isInterfaceDeclaration(statement) && statement.name.text === 'Menu');
|
|
851
|
+
const submenu = ast.statements.find((statement) => ts.isTypeAliasDeclaration(statement) && statement.name.text === 'Submenu');
|
|
852
|
+
return declaresSubmenu(menu) && (declaresSubmenu(submenu) || omitsWithoutSubmenu(submenu?.type));
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/** String-literal keys of an `Omit` key type, or [] when they are not literal. */
|
|
856
|
+
function omittedKeys(node) {
|
|
857
|
+
if (ts.isLiteralTypeNode(node) && ts.isStringLiteralLike(node.literal)) return [node.literal.text];
|
|
858
|
+
if (ts.isUnionTypeNode(node)) return node.types.flatMap((type) => omittedKeys(type));
|
|
859
|
+
return [];
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** True when the alias inherits `submenu` from `Omit<Menu, ...>` because the omitted keys do not include it. */
|
|
863
|
+
function omitsWithoutSubmenu(type) {
|
|
864
|
+
if (!type) return false;
|
|
865
|
+
let inherited = false;
|
|
866
|
+
const visit = (node) => {
|
|
867
|
+
if (inherited) return;
|
|
868
|
+
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.text === 'Omit' && node.typeArguments?.length === 2) {
|
|
869
|
+
const [target, keys] = node.typeArguments;
|
|
870
|
+
const keyTexts = omittedKeys(keys);
|
|
871
|
+
if (
|
|
872
|
+
ts.isTypeReferenceNode(target) &&
|
|
873
|
+
ts.isIdentifier(target.typeName) &&
|
|
874
|
+
target.typeName.text === 'Menu' &&
|
|
875
|
+
keyTexts.length > 0 &&
|
|
876
|
+
!keyTexts.includes('submenu')
|
|
877
|
+
)
|
|
878
|
+
inherited = true;
|
|
879
|
+
}
|
|
880
|
+
ts.forEachChild(node, visit);
|
|
881
|
+
};
|
|
882
|
+
visit(type);
|
|
883
|
+
return inherited;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** The emitted children guard matching the product's MenuNode shape, preserving the canonical call's extra arguments (e.g. `depth + 1`). */
|
|
887
|
+
function childrenGuard(text, optionalSubmenu) {
|
|
888
|
+
return optionalSubmenu
|
|
889
|
+
? text.replace(MENU_CHILDREN_GUARDED, (_, extra = '') => `Array.isArray(menu.submenu) ? toLayoutMenuItems(menu.submenu, translate${extra}) : []`)
|
|
890
|
+
: text.replace(MENU_CHILDREN_OPTIONAL, (_, extra = '') => `'submenu' in menu ? toLayoutMenuItems(menu.submenu, translate${extra}) : []`);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
function insertAfterStatement(source, matcher, block) {
|
|
894
|
+
const lines = source.split('\n');
|
|
895
|
+
const start = lines.findIndex((line) => matcher.test(line));
|
|
896
|
+
if (start === -1) return null;
|
|
897
|
+
let depth = 0;
|
|
898
|
+
for (let index = start; index < lines.length; index += 1) {
|
|
899
|
+
for (const char of lines[index]) {
|
|
900
|
+
if (char === '(' || char === '[' || char === '{') depth += 1;
|
|
901
|
+
else if (char === ')' || char === ']' || char === '}') depth -= 1;
|
|
902
|
+
}
|
|
903
|
+
if (depth <= 0 && lines[index].trimEnd().endsWith(';')) {
|
|
904
|
+
// The block is written with one tab per level; it takes the matched member's indentation.
|
|
905
|
+
const indent = lines[start].match(/^[ \t]*/)?.[0] || '\t';
|
|
906
|
+
lines.splice(index + 1, 0, ...block.split('\n').map((line) => line.replace(/^\t/, indent)));
|
|
907
|
+
return lines.join('\n');
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function addNamedImport(content, filePath, specifier, name) {
|
|
914
|
+
const ast = parseSourceFile(filePath, content);
|
|
915
|
+
const result = applyImportEdits(content, ast, { add: [{ specifier, name }] });
|
|
916
|
+
return result.conflicts.length > 0 ? null : result.content;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function planMenuAdapter({ menuModel, menuService, canonicalMenu }) {
|
|
920
|
+
if (/\blayoutItems\b/.test(menuService)) return { menuModel, menuService, changed: false };
|
|
921
|
+
if (/\blayoutMenu\b/.test(menuService)) {
|
|
922
|
+
const next = insertAfterStatement(
|
|
923
|
+
menuService,
|
|
924
|
+
/\blayoutMenu\b/,
|
|
925
|
+
'\t/** The menus as kit items for `st-app-layout`. */\n\treadonly layoutItems = this.layoutMenu;',
|
|
926
|
+
);
|
|
927
|
+
return next ? { menuModel, menuService: next, changed: true } : { conflict: 'menu.service.ts exposes layoutMenu but it could not be aliased' };
|
|
928
|
+
}
|
|
929
|
+
if (/computed<\s*LayoutMenuItem\[\]>/.test(menuService)) {
|
|
930
|
+
const next = insertAfterStatement(
|
|
931
|
+
menuService,
|
|
932
|
+
/(?:readonly\s+)?\bmenus\s*=\s*computed/,
|
|
933
|
+
'\t/** The menus as kit items for `st-app-layout`. */\n\treadonly layoutItems = this.menus;',
|
|
934
|
+
);
|
|
935
|
+
return next ? { menuModel, menuService: next, changed: true } : { conflict: 'menu.service.ts menus computed could not be aliased' };
|
|
936
|
+
}
|
|
937
|
+
if (
|
|
938
|
+
!/export interface Menu\b/.test(menuModel) ||
|
|
939
|
+
!/export type Submenu\b/.test(menuModel) ||
|
|
940
|
+
!/(?:readonly\s+)?\bmenus\s*=\s*computed/.test(menuService)
|
|
941
|
+
) {
|
|
942
|
+
return { conflict: 'menu model/service shape is not a recognized SDK 4 adapter; wire MenuService.layoutItems manually' };
|
|
943
|
+
}
|
|
944
|
+
const modelAst = parseSourceFile(MENU_MODEL, menuModel);
|
|
945
|
+
if (hasMenuHelper(menuModel, 'toLayoutMenuItems') && !hasCanonicalToLayoutMenuItems(modelAst)) {
|
|
946
|
+
return { conflict: 'Menu.ts already exports toLayoutMenuItems with a different signature; adapt it manually' };
|
|
947
|
+
}
|
|
948
|
+
const helperMatch = canonicalMenu.match(CANONICAL_MENU_HELPERS);
|
|
949
|
+
const helperParts = helperMatch ? splitMenuHelpers(helperMatch[0]) : null;
|
|
950
|
+
if (!helperParts) return { conflict: 'canonical menu adapter helpers are unavailable' };
|
|
951
|
+
const optionalSubmenu = submenuOnBothNodes(modelAst);
|
|
952
|
+
let nextModel = menuModel;
|
|
953
|
+
if (!hasMenuNode(modelAst)) {
|
|
954
|
+
const submenuDeclaration = modelAst.statements.find((statement) => ts.isTypeAliasDeclaration(statement) && statement.name.text === 'Submenu');
|
|
955
|
+
if (!submenuDeclaration) return { conflict: 'Menu.ts declares no `Submenu` type alias to anchor the MenuNode alias; add it manually' };
|
|
956
|
+
const anchor = submenuDeclaration.getEnd();
|
|
957
|
+
nextModel = `${nextModel.slice(0, anchor)}\n\nexport type MenuNode = Menu | Submenu;${nextModel.slice(anchor).replace(/^\n+/, '\n\n')}`;
|
|
958
|
+
}
|
|
959
|
+
const keepSidebarIconDepth = sidebarIconTakesTopLevel(modelAst);
|
|
960
|
+
const missingHelpers = helperParts
|
|
961
|
+
.filter((part) => !hasMenuHelper(menuModel, part.name))
|
|
962
|
+
.map((part) => {
|
|
963
|
+
if (part.name !== 'toLayoutMenuItems') return part.text;
|
|
964
|
+
const guarded = childrenGuard(part.text, optionalSubmenu);
|
|
965
|
+
return keepSidebarIconDepth ? guarded : guarded.replace('menuSidebarIcon(menu, depth === 0)', 'menuSidebarIcon(menu)');
|
|
966
|
+
});
|
|
967
|
+
if (missingHelpers.length > 0) nextModel = `${nextModel.trimEnd()}\n\n${missingHelpers.join('\n\n')}\n`;
|
|
968
|
+
nextModel = addNamedImport(nextModel, MENU_MODEL, '@sixbell-telco/sdk/layouts', 'LayoutMenuItem');
|
|
969
|
+
if (nextModel === null)
|
|
970
|
+
return { conflict: 'Menu.ts cannot import LayoutMenuItem from @sixbell-telco/sdk/layouts (name collision); adapt it manually' };
|
|
971
|
+
let nextService = addNamedImport(menuService, MENU_SERVICE, '@sixbell-telco/sdk/layouts', 'LayoutMenuItem');
|
|
972
|
+
if (nextService === null) return { conflict: 'menu.service.ts cannot import LayoutMenuItem (name collision); adapt it manually' };
|
|
973
|
+
nextService = addNamedImport(nextService, MENU_SERVICE, '@core/models/Menu', 'toLayoutMenuItems');
|
|
974
|
+
if (nextService === null) return { conflict: 'menu.service.ts cannot import toLayoutMenuItems (name collision); adapt it manually' };
|
|
975
|
+
const inserted = insertAfterStatement(
|
|
976
|
+
nextService,
|
|
977
|
+
/(?:readonly\s+)?\bmenus\s*=\s*computed/,
|
|
978
|
+
'\t/** The menus as kit items for `st-app-layout`; labels are already translated. */\n\treadonly layoutItems = computed<LayoutMenuItem[]>(() => toLayoutMenuItems(this.menus(), (label) => label));',
|
|
979
|
+
);
|
|
980
|
+
if (inserted === null) return { conflict: 'menu.service.ts menus computed could not be extended' };
|
|
981
|
+
return { menuModel: nextModel, menuService: inserted, changed: true };
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// --- module-reference resolution (prune safety) -----------------------------
|
|
985
|
+
|
|
986
|
+
function readProjectConfig(root) {
|
|
987
|
+
const optionSets = [];
|
|
988
|
+
for (const name of ['tsconfig.app.json', 'tsconfig.spec.json', 'tsconfig.json']) {
|
|
989
|
+
const configPath = path.join(root, name);
|
|
990
|
+
if (!HOST.fileExists(configPath)) continue;
|
|
991
|
+
const read = ts.readConfigFile(configPath, (file) => HOST.readFile(file));
|
|
992
|
+
if (read.error) return { options: null, optionSets: [], error: ts.flattenDiagnosticMessageText(read.error.messageText, '\n') };
|
|
993
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, HOST, path.dirname(configPath), undefined, configPath);
|
|
994
|
+
// The tree host lists no files, so "no inputs were found" (TS18003) says nothing about the config.
|
|
995
|
+
parsed.errors = (parsed.errors ?? []).filter((error) => error.code !== 18003);
|
|
996
|
+
if (parsed.errors.length > 0)
|
|
997
|
+
return {
|
|
998
|
+
options: null,
|
|
999
|
+
optionSets: [],
|
|
1000
|
+
error: parsed.errors.map((error) => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('; '),
|
|
1001
|
+
};
|
|
1002
|
+
optionSets.push({ name, options: parsed.options });
|
|
1003
|
+
}
|
|
1004
|
+
if (optionSets.length === 0) return { options: {}, optionSets: [{ name: null, options: {} }], error: null };
|
|
1005
|
+
const primary =
|
|
1006
|
+
optionSets.find((entry) => entry.name === 'tsconfig.app.json') ?? optionSets.find((entry) => entry.name === 'tsconfig.json') ?? optionSets[0];
|
|
1007
|
+
return { options: primary.options, optionSets, error: null };
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** Module specifiers from static imports/exports and dynamic import()/require(); `uncertain` for computed ones. */
|
|
1011
|
+
function collectModuleReferences(ast, source) {
|
|
1012
|
+
const specifiers = [];
|
|
1013
|
+
let uncertain = false;
|
|
1014
|
+
const visit = (node) => {
|
|
1015
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) {
|
|
1016
|
+
if (ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text);
|
|
1017
|
+
else uncertain = true;
|
|
1018
|
+
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
1019
|
+
const expression = node.moduleReference.expression;
|
|
1020
|
+
if (expression && ts.isStringLiteralLike(expression)) specifiers.push(expression.text);
|
|
1021
|
+
else uncertain = true;
|
|
1022
|
+
} else if (
|
|
1023
|
+
ts.isCallExpression(node) &&
|
|
1024
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
1025
|
+
(ts.isIdentifier(node.expression) && node.expression.text === 'require') ||
|
|
1026
|
+
(ts.isPropertyAccessExpression(node.expression) &&
|
|
1027
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
1028
|
+
node.expression.expression.text === 'require' &&
|
|
1029
|
+
node.expression.name.text === 'resolve'))
|
|
1030
|
+
) {
|
|
1031
|
+
const argument = node.arguments[0];
|
|
1032
|
+
if (argument && ts.isStringLiteralLike(argument)) specifiers.push(argument.text);
|
|
1033
|
+
else uncertain = true;
|
|
1034
|
+
}
|
|
1035
|
+
ts.forEachChild(node, visit);
|
|
1036
|
+
};
|
|
1037
|
+
visit(ast);
|
|
1038
|
+
for (const match of String(source).matchAll(/\/\/\/\s*<reference\s+path=["']([^"']+)["']/g)) specifiers.push(match[1]);
|
|
1039
|
+
return { specifiers, uncertain };
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function ownedPaths(legacy) {
|
|
1043
|
+
return [...variantPaths(legacy.ts), ...(legacy.companions ?? [])];
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function allLegacyVariants(legacyFiles = LEGACY_SHELL_FILES) {
|
|
1047
|
+
return legacyFiles.flatMap((legacy) => ownedPaths(legacy));
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/** Basenames of the recognized legacy files, used only for the conservative unresolved-reference clause. */
|
|
1051
|
+
function legacyBasenames(legacyFiles = LEGACY_SHELL_FILES) {
|
|
1052
|
+
return new Set(legacyFiles.flatMap((legacy) => ownedPaths(legacy).map((relative) => path.posix.basename(relative).replace(/\.(ts|html)$/, ''))));
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/**
|
|
1056
|
+
* Importers of each file through static module references, for the orphan cascade.
|
|
1057
|
+
* Specifiers that resolve to nothing are indexed by their basename: an alias the
|
|
1058
|
+
* tsconfig cannot resolve may still name the file, so it must count as a live
|
|
1059
|
+
* importer instead of letting the cascade delete its target.
|
|
1060
|
+
*/
|
|
1061
|
+
function collectModuleImporters({ root, sourceFiles, parsed, optionSets }) {
|
|
1062
|
+
const projectFiles = new Set(sourceFiles);
|
|
1063
|
+
const importers = new Map();
|
|
1064
|
+
const unresolved = new Map();
|
|
1065
|
+
const record = (target, importer) => {
|
|
1066
|
+
if (!projectFiles.has(target) || target === importer) return;
|
|
1067
|
+
if (!importers.has(target)) importers.set(target, new Set());
|
|
1068
|
+
importers.get(target).add(importer);
|
|
1069
|
+
};
|
|
1070
|
+
const recordUnresolved = (spec, importer) => {
|
|
1071
|
+
const name = spec
|
|
1072
|
+
.split('/')
|
|
1073
|
+
.pop()
|
|
1074
|
+
.replace(/\.(ts|js|mjs|cjs|html)$/, '');
|
|
1075
|
+
if (!name) return;
|
|
1076
|
+
if (!unresolved.has(name)) unresolved.set(name, new Set());
|
|
1077
|
+
unresolved.get(name).add(importer);
|
|
1078
|
+
};
|
|
1079
|
+
const relativeTarget = (absolute) => path.relative(root, path.resolve(absolute)).split(path.sep).join('/');
|
|
1080
|
+
for (const [relative, references] of parsed.entries()) {
|
|
1081
|
+
const absoluteFile = path.resolve(root, relative);
|
|
1082
|
+
for (const spec of references.specifiers) {
|
|
1083
|
+
if (spec.startsWith('.')) {
|
|
1084
|
+
const base = path.resolve(path.dirname(absoluteFile), spec);
|
|
1085
|
+
let resolved = false;
|
|
1086
|
+
for (const extension of ['', '.ts', '.html', '.spec.ts', '.js', '.mjs', '.cjs']) {
|
|
1087
|
+
const target = relativeTarget(base + extension);
|
|
1088
|
+
if (projectFiles.has(target)) {
|
|
1089
|
+
record(target, relative);
|
|
1090
|
+
resolved = true;
|
|
1091
|
+
break;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
if (!resolved) recordUnresolved(spec, relative);
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
let resolved = false;
|
|
1098
|
+
for (const entry of optionSets) {
|
|
1099
|
+
const resolvedName = ts.resolveModuleName(spec, absoluteFile, entry.options, HOST).resolvedModule?.resolvedFileName;
|
|
1100
|
+
if (!resolvedName) continue;
|
|
1101
|
+
resolved = true;
|
|
1102
|
+
const target = relativeTarget(resolvedName);
|
|
1103
|
+
if (projectFiles.has(target)) {
|
|
1104
|
+
record(target, relative);
|
|
1105
|
+
break;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (!resolved) recordUnresolved(spec, relative);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
return { importers, unresolved };
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* Deletes files orphaned by the planned deletions: a file is deleted when it has
|
|
1116
|
+
* at least one importer and every importer is either being deleted or is the
|
|
1117
|
+
* file's own spec, whose lifetime follows the subject. Specs and templates are
|
|
1118
|
+
* deleted with their subject, the loop repeats to a fixed point, plan rewrites
|
|
1119
|
+
* count as live importers, and files with no importer at all are out of scope.
|
|
1120
|
+
*/
|
|
1121
|
+
async function cascadeOrphanedDeletes({ root, sourceFiles, parsed, optionSets, projected, legacyFiles, legacyAll, deletes }) {
|
|
1122
|
+
const deleted = new Set(deletes);
|
|
1123
|
+
const legacyRoots = [...new Set(legacyFiles.filter((legacy) => legacy.selector).map((legacy) => path.posix.dirname(legacy.ts)))];
|
|
1124
|
+
const { importers, unresolved } = collectModuleImporters({ root, sourceFiles, parsed, optionSets });
|
|
1125
|
+
const contents = new Map();
|
|
1126
|
+
const contentOf = async (relative) => {
|
|
1127
|
+
if (!contents.has(relative)) {
|
|
1128
|
+
const content = projected.has(relative) ? projected.get(relative) : await readTextOrNull(root, relative);
|
|
1129
|
+
contents.set(relative, content ?? null);
|
|
1130
|
+
}
|
|
1131
|
+
return contents.get(relative);
|
|
1132
|
+
};
|
|
1133
|
+
const existsInProject = async (relative) =>
|
|
1134
|
+
projected.has(relative) ? projected.get(relative) !== null : (await hashFileOrNull(root, relative)) !== null;
|
|
1135
|
+
let changed = true;
|
|
1136
|
+
while (changed) {
|
|
1137
|
+
changed = false;
|
|
1138
|
+
for (const relative of sourceFiles) {
|
|
1139
|
+
if (deleted.has(relative) || legacyAll.has(relative)) continue;
|
|
1140
|
+
if (!SCRIPT_EXTENSIONS.some((extension) => relative.endsWith(extension)) || relative.endsWith('.spec.ts')) continue;
|
|
1141
|
+
if (projected.has(relative) && projected.get(relative) !== null) continue;
|
|
1142
|
+
const fileImporters = importers.get(relative);
|
|
1143
|
+
if (!fileImporters || fileImporters.size === 0) continue;
|
|
1144
|
+
const ownSpec = relative.replace(/\.ts$/, '.spec.ts');
|
|
1145
|
+
const live = (importer) => !deleted.has(importer) && importer !== ownSpec;
|
|
1146
|
+
if ([...fileImporters].some(live)) continue;
|
|
1147
|
+
const unresolvedImporters = unresolved.get(path.posix.basename(relative).replace(/\.(ts|js|mjs|cjs)$/, ''));
|
|
1148
|
+
if (unresolvedImporters && [...unresolvedImporters].some(live)) continue;
|
|
1149
|
+
// Only the local shell sub-trees, or files whose consumer was really deleted by the
|
|
1150
|
+
// plan, may cascade: unrelated spec-only files elsewhere are left alone.
|
|
1151
|
+
const inLegacyTree = legacyRoots.some((legacyRoot) => relative.startsWith(`${legacyRoot}/`));
|
|
1152
|
+
if (!inLegacyTree && ![...fileImporters].some((importer) => deleted.has(importer))) continue;
|
|
1153
|
+
const content = await contentOf(relative);
|
|
1154
|
+
const selector = typeof content === 'string' ? (content.match(/selector:\s*['"]([^'"]+)['"]/)?.[1] ?? null) : null;
|
|
1155
|
+
let templateReference = false;
|
|
1156
|
+
if (selector) {
|
|
1157
|
+
for (const html of sourceFiles) {
|
|
1158
|
+
if (!html.endsWith('.html') || deleted.has(html)) continue;
|
|
1159
|
+
const htmlContent = await contentOf(html);
|
|
1160
|
+
if (typeof htmlContent === 'string' && htmlContent.includes(`<${selector}`)) {
|
|
1161
|
+
templateReference = true;
|
|
1162
|
+
break;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
if (templateReference) continue;
|
|
1167
|
+
deleted.add(relative);
|
|
1168
|
+
changed = true;
|
|
1169
|
+
for (const variant of [relative.replace(/\.ts$/, '.html'), ownSpec]) {
|
|
1170
|
+
if (!deleted.has(variant) && (await existsInProject(variant))) deleted.add(variant);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
return [...deleted].sort();
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* A specifier TypeScript could not resolve is uncertain when it could still name a
|
|
1179
|
+
* recognized legacy file: its own basename matches one, or it matches a configured
|
|
1180
|
+
* `paths` alias whose target names one. Such a file blocks pruning until resolved.
|
|
1181
|
+
*/
|
|
1182
|
+
function uncertainSpecifier(spec, options, legacyFiles = LEGACY_SHELL_FILES) {
|
|
1183
|
+
const bases = legacyBasenames(legacyFiles);
|
|
1184
|
+
const last = spec.split('/').pop();
|
|
1185
|
+
if (bases.has(last)) return true;
|
|
1186
|
+
for (const [alias, targets] of Object.entries(options.paths ?? {})) {
|
|
1187
|
+
const matches = alias.endsWith('/*') ? spec.startsWith(alias.slice(0, -1)) : spec === alias;
|
|
1188
|
+
if (!matches) continue;
|
|
1189
|
+
const list = Array.isArray(targets) ? targets : [targets];
|
|
1190
|
+
if (list.some((target) => [...bases].some((base) => target.includes(base)))) return true;
|
|
1191
|
+
}
|
|
1192
|
+
return false;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
async function planLegacyPrune({ root, projected, config, legacyFiles = LEGACY_SHELL_FILES }) {
|
|
1196
|
+
if (config.error)
|
|
1197
|
+
return {
|
|
1198
|
+
deletes: [],
|
|
1199
|
+
conflicts: [
|
|
1200
|
+
conflict(
|
|
1201
|
+
'tsconfig.json',
|
|
1202
|
+
'SDK4_SHELL_TSCONFIG_001',
|
|
1203
|
+
`tsconfig could not be resolved (${config.error}); refusing to prune local shell copies until it parses`,
|
|
1204
|
+
),
|
|
1205
|
+
],
|
|
1206
|
+
};
|
|
1207
|
+
const optionSets = config.optionSets ?? [{ options: config.options ?? {} }];
|
|
1208
|
+
const deletes = [];
|
|
1209
|
+
const conflicts = [];
|
|
1210
|
+
const legacyAll = new Set(allLegacyVariants(legacyFiles));
|
|
1211
|
+
// Files the plan creates (the layout account provider) are live importers too, so what they
|
|
1212
|
+
// import (the session avatar util) is never pruned as an orphan.
|
|
1213
|
+
const created = [...projected.entries()]
|
|
1214
|
+
.filter(([relative, content]) => typeof content === 'string' && SCRIPT_FILE.test(relative))
|
|
1215
|
+
.map(([relative]) => relative);
|
|
1216
|
+
const sourceFiles = [...new Set([...(await listProjectFiles(root)), ...created])].sort();
|
|
1217
|
+
const parsed = new Map();
|
|
1218
|
+
const uncertainFiles = [];
|
|
1219
|
+
const unresolvedUncertain = (spec, absoluteFile) => {
|
|
1220
|
+
if (optionSets.some((entry) => ts.resolveModuleName(spec, absoluteFile, entry.options, HOST).resolvedModule?.resolvedFileName)) return false;
|
|
1221
|
+
return optionSets.some((entry) => uncertainSpecifier(spec, entry.options, legacyFiles));
|
|
1222
|
+
};
|
|
1223
|
+
for (const relative of sourceFiles) {
|
|
1224
|
+
if (!SCRIPT_EXTENSIONS.some((extension) => relative.endsWith(extension))) continue;
|
|
1225
|
+
const content = projected.has(relative) ? projected.get(relative) : await readTextOrNull(root, relative);
|
|
1226
|
+
if (content === null || content === undefined) continue;
|
|
1227
|
+
try {
|
|
1228
|
+
const references = collectModuleReferences(parseSourceFile(relative, content), content);
|
|
1229
|
+
parsed.set(relative, references);
|
|
1230
|
+
if (legacyAll.has(relative)) continue;
|
|
1231
|
+
const absoluteFile = path.resolve(root, relative);
|
|
1232
|
+
if (references.uncertain || references.specifiers.some((spec) => unresolvedUncertain(spec, absoluteFile))) uncertainFiles.push(relative);
|
|
1233
|
+
} catch {
|
|
1234
|
+
if (!legacyAll.has(relative)) uncertainFiles.push(relative);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const hasUncertainty = uncertainFiles.length > 0;
|
|
1238
|
+
if (hasUncertainty) {
|
|
1239
|
+
conflicts.push(
|
|
1240
|
+
conflict(
|
|
1241
|
+
uncertainFiles[0],
|
|
1242
|
+
'SDK4_SHELL_DYNAMIC_001',
|
|
1243
|
+
`computed or unresolved import in ${uncertainFiles.join(', ')}; refusing to prune local shell copies until it is resolved`,
|
|
1244
|
+
),
|
|
1245
|
+
);
|
|
1246
|
+
}
|
|
1247
|
+
for (const legacy of legacyFiles) {
|
|
1248
|
+
const owned = ownedPaths(legacy);
|
|
1249
|
+
const ownedSet = new Set(owned);
|
|
1250
|
+
const existing = [];
|
|
1251
|
+
for (const relative of owned) {
|
|
1252
|
+
if (projected.has(relative)) {
|
|
1253
|
+
if (projected.get(relative) !== null) existing.push(relative);
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
if ((await hashFileOrNull(root, relative)) !== null) existing.push(relative);
|
|
1257
|
+
}
|
|
1258
|
+
if (existing.length === 0) continue;
|
|
1259
|
+
const legacyVariants = new Set(variantPaths(legacy.ts).map((relative) => path.resolve(root, relative)));
|
|
1260
|
+
const referrers = [];
|
|
1261
|
+
for (const relative of sourceFiles) {
|
|
1262
|
+
if (legacyAll.has(relative) || ownedSet.has(relative)) continue;
|
|
1263
|
+
const content = projected.has(relative) ? projected.get(relative) : await readTextOrNull(root, relative);
|
|
1264
|
+
if (content === null || content === undefined) continue;
|
|
1265
|
+
if (relative.endsWith('.html')) {
|
|
1266
|
+
if (legacy.selector && content.includes(`<${legacy.selector}`)) referrers.push(relative);
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1269
|
+
if (!SCRIPT_EXTENSIONS.some((extension) => relative.endsWith(extension))) continue;
|
|
1270
|
+
const references = parsed.get(relative);
|
|
1271
|
+
if (!references) continue;
|
|
1272
|
+
const absoluteFile = path.resolve(root, relative);
|
|
1273
|
+
const matches = references.specifiers.some((spec) => {
|
|
1274
|
+
const resolvedToLegacy = optionSets.some((entry) => {
|
|
1275
|
+
const resolvedName = ts.resolveModuleName(spec, absoluteFile, entry.options, HOST).resolvedModule?.resolvedFileName;
|
|
1276
|
+
return Boolean(resolvedName) && legacyVariants.has(path.resolve(resolvedName));
|
|
1277
|
+
});
|
|
1278
|
+
if (resolvedToLegacy) return true;
|
|
1279
|
+
if (spec.startsWith('.')) {
|
|
1280
|
+
const base = path.resolve(path.dirname(absoluteFile), spec);
|
|
1281
|
+
return ['', '.ts', '.html', '.spec.ts'].some((extension) => legacyVariants.has(base + extension));
|
|
1282
|
+
}
|
|
1283
|
+
return false;
|
|
1284
|
+
});
|
|
1285
|
+
if (matches) referrers.push(relative);
|
|
1286
|
+
}
|
|
1287
|
+
if (referrers.length > 0) {
|
|
1288
|
+
conflicts.push(
|
|
1289
|
+
conflict(
|
|
1290
|
+
legacy.ts,
|
|
1291
|
+
'SDK4_SHELL_LOCAL_COPY_REFERENCED',
|
|
1292
|
+
`obsolete local shell ${legacy.ts} is still referenced by ${referrers.join(', ')}; remove those references before adopting the kit shell`,
|
|
1293
|
+
),
|
|
1294
|
+
);
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
if (hasUncertainty) continue;
|
|
1298
|
+
for (const relative of existing) deletes.push(relative);
|
|
1299
|
+
}
|
|
1300
|
+
const planned = hasUncertainty
|
|
1301
|
+
? deletes
|
|
1302
|
+
: await cascadeOrphanedDeletes({ root, sourceFiles, parsed, optionSets, projected, legacyFiles, legacyAll, deletes });
|
|
1303
|
+
return { deletes: [...new Set(planned)].sort(), conflicts };
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// --- federated child shell (kit MfeShadowShellComponent) --------------------
|
|
1307
|
+
|
|
1308
|
+
const FEDERATED_REMOTE_DIR = 'src/app/remote';
|
|
1309
|
+
const SDK_MFE_SPECIFIER = '@sixbell-telco/sdk/utils/mfe';
|
|
1310
|
+
const SDK_LAYOUTS_SPECIFIER = '@sixbell-telco/sdk/layouts';
|
|
1311
|
+
const BANNER_COMPONENT = 'src/app/core/components/general-banner/general-banner.component.ts';
|
|
1312
|
+
const BANNER_SPEC = 'src/app/core/components/general-banner/general-banner.component.spec.ts';
|
|
1313
|
+
|
|
1314
|
+
/** The local Shadow DOM remote shell and its shadow-root overlay copy, when the child still ships them. */
|
|
1315
|
+
async function discoverFederatedShell(root) {
|
|
1316
|
+
const entries = [...TREE.getDir(`/${FEDERATED_REMOTE_DIR}`).subfiles];
|
|
1317
|
+
if (entries.length === 0) return null;
|
|
1318
|
+
let shell = null;
|
|
1319
|
+
let overlay = null;
|
|
1320
|
+
for (const name of entries.filter((entry) => entry.endsWith('.ts') && !entry.endsWith('.spec.ts')).sort()) {
|
|
1321
|
+
const relative = `${FEDERATED_REMOTE_DIR}/${name}`;
|
|
1322
|
+
const content = await readTextOrNull(root, relative);
|
|
1323
|
+
if (content === null) continue;
|
|
1324
|
+
if (!shell && /ViewEncapsulation\.ShadowDom/.test(content)) shell = { relative, content };
|
|
1325
|
+
if (!overlay && /\bSHADOW_ROOT_HOST_SELECTOR\b/.test(content) && /\bShadowRootOverlayContainer\b/.test(content)) overlay = { relative, content };
|
|
1326
|
+
}
|
|
1327
|
+
if (!shell) return null;
|
|
1328
|
+
const className = shell.content.match(/export\s+class\s+([A-Za-z_$][\w$]*)/)?.[1] ?? null;
|
|
1329
|
+
return { shell: { ...shell, className }, overlay };
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/** Normalized mount base path: '/' stays '/', otherwise trailing slashes collapse into one. */
|
|
1333
|
+
function normalizeMountPath(mountPath) {
|
|
1334
|
+
return mountPath === '/' ? '/' : `${mountPath.replace(/\/+$/, '')}/`;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
const LITERAL_REMOTE_BASE_PATH = /const\s+REMOTE_BASE_PATH\s*(?::\s*string)?\s*=\s*(['"])([^'"]+)\1\s*;/;
|
|
1338
|
+
const CONFIGURED_MOUNT_PATH_LITERAL = /const\s+CONFIGURED_MOUNT_PATH\s*:\s*string\s*=\s*(['"])(\/[^'"]*)\1\s*;/;
|
|
1339
|
+
const CONFIGURED_REMOTE_BASE_PATH =
|
|
1340
|
+
/const\s+REMOTE_BASE_PATH\s*(?::\s*string)?\s*=\s*CONFIGURED_MOUNT_PATH\s*===\s*['"]\/['"]\s*\?\s*['"]\/['"]\s*:\s*`\$\{\s*(?:CONFIGURED_MOUNT_PATH\.replace\(\s*\/\\\/\+\$\/\s*,\s*['"]{2}\s*\)|trimTrailingSlashes\(\s*CONFIGURED_MOUNT_PATH\s*\))\s*\}\/\`\s*;/;
|
|
1341
|
+
const INLINE_REMOTE_BASE_PATH =
|
|
1342
|
+
/const\s+REMOTE_BASE_PATH\s*(?::\s*string)?\s*=\s*`\$\{\s*CONFIGURED_MOUNT_PATH\.replace\(\s*\/\\\/\+\$\/\s*,\s*['"]{2}\s*\)\s*\}\/\`\s*;/;
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* Resolve the shell basePath from either the canonical literal `REMOTE_BASE_PATH`
|
|
1346
|
+
* or a literal `CONFIGURED_MOUNT_PATH` normalized with a trailing-slash helper.
|
|
1347
|
+
* Unrecognized derivations return null so the caller conflicts instead of guessing.
|
|
1348
|
+
*/
|
|
1349
|
+
function extractRemoteBasePath(source) {
|
|
1350
|
+
const literal = source.match(LITERAL_REMOTE_BASE_PATH)?.[2];
|
|
1351
|
+
if (literal) return literal;
|
|
1352
|
+
const mountPath = source.match(CONFIGURED_MOUNT_PATH_LITERAL)?.[2];
|
|
1353
|
+
if (!mountPath) return null;
|
|
1354
|
+
if (CONFIGURED_REMOTE_BASE_PATH.test(source) || INLINE_REMOTE_BASE_PATH.test(source)) return normalizeMountPath(mountPath);
|
|
1355
|
+
return null;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
/** Exact local-shell config the kit provideMfeShadowShell needs, or a conflict when the shape is unrecognized. */
|
|
1359
|
+
async function extractFederatedShellConfig({ root, shell }) {
|
|
1360
|
+
const basePath = extractRemoteBasePath(shell.content);
|
|
1361
|
+
if (!basePath)
|
|
1362
|
+
return {
|
|
1363
|
+
conflict:
|
|
1364
|
+
"the remote shell does not declare `const REMOTE_BASE_PATH = '...'` or derive it from a literal `CONFIGURED_MOUNT_PATH` via trailing-slash normalization; migrate it by hand",
|
|
1365
|
+
};
|
|
1366
|
+
const stylesheetHrefModule = shell.content.match(/const\s+STYLESHEET_HREF_MODULE\s*(?::\s*string)?\s*=\s*`\$\{REMOTE_BASE_PATH\}([^`]+)`\s*;/)?.[1];
|
|
1367
|
+
if (!stylesheetHrefModule) return { conflict: 'the remote shell does not derive STYLESHEET_HREF_MODULE from REMOTE_BASE_PATH; migrate it by hand' };
|
|
1368
|
+
const assetPath = `src/${stylesheetHrefModule}`;
|
|
1369
|
+
const asset = await readTextOrNull(root, assetPath);
|
|
1370
|
+
const stylesheetHrefExport =
|
|
1371
|
+
asset?.match(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=/)?.[1] ??
|
|
1372
|
+
shell.content.match(/interface\s+\w+\s*\{[^}]*?([A-Za-z_$][\w$]*)\?:/)?.[1] ??
|
|
1373
|
+
null;
|
|
1374
|
+
if (!stylesheetHrefExport) return { conflict: `cannot read the stylesheet href export from ${assetPath}; migrate it by hand` };
|
|
1375
|
+
return { basePath, stylesheetHrefModule, stylesheetHrefExport };
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
function lineIndent(source, position) {
|
|
1379
|
+
const lineStart = source.lastIndexOf('\n', position - 1) + 1;
|
|
1380
|
+
return source.slice(lineStart, position).match(/^[ \t]*/)?.[0] ?? '';
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function renderShadowShellProviders(config, indent) {
|
|
1384
|
+
return `provideMfeShadowShell({\n${indent}\tbasePath: '${config.basePath}',\n${indent}\tstylesheetHrefModule: '${config.stylesheetHrefModule}',\n${indent}\tstylesheetHrefExport: '${config.stylesheetHrefExport}',\n${indent}})`;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
/** The exact local shadow-root overlay provider list, or null when any element is business work. */
|
|
1388
|
+
function recognizeShadowOverlayProviders(array, bindings) {
|
|
1389
|
+
const imports = [];
|
|
1390
|
+
for (const element of array.elements) {
|
|
1391
|
+
if (!ts.isObjectLiteralExpression(element)) return null;
|
|
1392
|
+
const provide = element.properties.find((property) => propertyName(property) === 'provide');
|
|
1393
|
+
const useClass = element.properties.find((property) => propertyName(property) === 'useClass');
|
|
1394
|
+
const useValue = element.properties.find((property) => propertyName(property) === 'useValue');
|
|
1395
|
+
const provideName = provide && ts.isIdentifier(provide.initializer) ? provide.initializer.text : null;
|
|
1396
|
+
if (!provideName) return null;
|
|
1397
|
+
const symbol = resolveImportSymbol(bindings, provideName);
|
|
1398
|
+
if (symbol?.imported === 'SHADOW_ROOT_HOST_SELECTOR' && useValue && ts.isStringLiteralLike(useValue.initializer)) {
|
|
1399
|
+
imports.push({ specifier: symbol.specifier, name: 'SHADOW_ROOT_HOST_SELECTOR' });
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
if (symbol?.imported === 'OverlayContainer' && symbol.specifier === '@angular/cdk/overlay') {
|
|
1403
|
+
const useClassName = useClass && ts.isIdentifier(useClass.initializer) ? useClass.initializer.text : null;
|
|
1404
|
+
const useClassSymbol = useClassName ? resolveImportSymbol(bindings, useClassName) : null;
|
|
1405
|
+
if (useClassSymbol?.imported !== 'ShadowRootOverlayContainer') return null;
|
|
1406
|
+
imports.push({ specifier: symbol.specifier, name: 'OverlayContainer' });
|
|
1407
|
+
imports.push({ specifier: useClassSymbol.specifier, name: 'ShadowRootOverlayContainer' });
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (
|
|
1411
|
+
(symbol?.imported === 'Overlay' && symbol.specifier === '@angular/cdk/overlay') ||
|
|
1412
|
+
(symbol?.imported === 'Dialog' && symbol.specifier === '@angular/cdk/dialog')
|
|
1413
|
+
) {
|
|
1414
|
+
if (!useClass || !ts.isIdentifier(useClass.initializer) || useClass.initializer.text !== provideName) return null;
|
|
1415
|
+
imports.push({ specifier: symbol.specifier, name: symbol.imported });
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
return null;
|
|
1419
|
+
}
|
|
1420
|
+
return { imports };
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/** Rewrite one route file that mounts the local shell: component, overlay providers and imports. */
|
|
1424
|
+
function rewriteFederatedRoute(source, filePath, { shellClassName, config }) {
|
|
1425
|
+
const ast = parseSourceFile(filePath, source);
|
|
1426
|
+
const bindings = collectImportBindings(ast);
|
|
1427
|
+
const shellBindings = bindings.filter((binding) => binding.imported === shellClassName);
|
|
1428
|
+
if (shellBindings.length === 0) return null;
|
|
1429
|
+
const shellLocals = new Set(shellBindings.map((binding) => binding.local));
|
|
1430
|
+
const replacements = [];
|
|
1431
|
+
const removeImports = [];
|
|
1432
|
+
const conflicts = [];
|
|
1433
|
+
let changed = false;
|
|
1434
|
+
const visit = (node) => {
|
|
1435
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
1436
|
+
const component = node.properties.find((property) => propertyName(property) === 'component');
|
|
1437
|
+
const initializer = component && ts.isPropertyAssignment(component) ? component.initializer : null;
|
|
1438
|
+
if (initializer && ts.isIdentifier(initializer) && shellLocals.has(initializer.text)) {
|
|
1439
|
+
const providers = node.properties.find((property) => propertyName(property) === 'providers');
|
|
1440
|
+
const providersInitializer = providers && ts.isPropertyAssignment(providers) ? providers.initializer : null;
|
|
1441
|
+
const recognized =
|
|
1442
|
+
providersInitializer && ts.isArrayLiteralExpression(providersInitializer)
|
|
1443
|
+
? recognizeShadowOverlayProviders(providersInitializer, bindings)
|
|
1444
|
+
: null;
|
|
1445
|
+
if (!recognized) {
|
|
1446
|
+
conflicts.push(
|
|
1447
|
+
conflict(
|
|
1448
|
+
filePath,
|
|
1449
|
+
'SDK4_SHELL_FEDERATED_002',
|
|
1450
|
+
`route mounting ${initializer.text} does not declare the exact local shadow-root overlay providers; migrate its providers to provideMfeShadowShell by hand`,
|
|
1451
|
+
),
|
|
1452
|
+
);
|
|
1453
|
+
} else {
|
|
1454
|
+
replacements.push({ start: initializer.getStart(), end: initializer.getEnd(), text: 'MfeShadowShellComponent' });
|
|
1455
|
+
replacements.push({
|
|
1456
|
+
start: providersInitializer.getStart(),
|
|
1457
|
+
end: providersInitializer.getEnd(),
|
|
1458
|
+
text: renderShadowShellProviders(config, lineIndent(source, providers.getStart())),
|
|
1459
|
+
});
|
|
1460
|
+
removeImports.push(...recognized.imports);
|
|
1461
|
+
changed = true;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
ts.forEachChild(node, visit);
|
|
1466
|
+
};
|
|
1467
|
+
visit(ast);
|
|
1468
|
+
for (const binding of shellBindings) removeImports.push({ specifier: binding.specifier, name: binding.imported });
|
|
1469
|
+
if (!changed) return conflicts.length > 0 ? { content: source, conflicts } : null;
|
|
1470
|
+
const withEdits = applyReplacements(source, replacements);
|
|
1471
|
+
const removable = removeImports.filter((entry) => {
|
|
1472
|
+
const clauseUses = (findImportDeclaration(ast, entry.specifier)?.importClause?.namedBindings?.elements ?? []).filter(
|
|
1473
|
+
(element) => element.name.text === entry.name,
|
|
1474
|
+
).length;
|
|
1475
|
+
return usageCount(withEdits, entry.name) - clauseUses <= 0;
|
|
1476
|
+
});
|
|
1477
|
+
const reparse = parseSourceFile(filePath, withEdits);
|
|
1478
|
+
const importEdits = applyImportEdits(withEdits, reparse, {
|
|
1479
|
+
add: [
|
|
1480
|
+
{ specifier: SDK_MFE_SPECIFIER, name: 'MfeShadowShellComponent' },
|
|
1481
|
+
{ specifier: SDK_MFE_SPECIFIER, name: 'provideMfeShadowShell' },
|
|
1482
|
+
],
|
|
1483
|
+
remove: removable,
|
|
1484
|
+
});
|
|
1485
|
+
return { content: importEdits.conflicts.length > 0 ? source : importEdits.content, conflicts: importEdits.conflicts };
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/** Rewrite a `PageBannerComponent` import from the local copy onto the kit layouts entry point. */
|
|
1489
|
+
function rewriteBannerImport(source, filePath) {
|
|
1490
|
+
const ast = parseSourceFile(filePath, source);
|
|
1491
|
+
const local = collectImportBindings(ast).find(
|
|
1492
|
+
(binding) => binding.imported === 'PageBannerComponent' && binding.specifier !== SDK_LAYOUTS_SPECIFIER,
|
|
1493
|
+
);
|
|
1494
|
+
if (!local) return { content: source, changed: false };
|
|
1495
|
+
const specifier = findImportDeclaration(ast, local.specifier)?.moduleSpecifier;
|
|
1496
|
+
if (!specifier) return { content: source, changed: false };
|
|
1497
|
+
return {
|
|
1498
|
+
content: applyReplacements(source, [{ start: specifier.getStart(), end: specifier.getEnd(), text: `'${SDK_LAYOUTS_SPECIFIER}'` }]),
|
|
1499
|
+
changed: true,
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
/** Add a symbol to the @Component imports array, or conflict when the array is missing. */
|
|
1504
|
+
function addToComponentImports(source, filePath, name) {
|
|
1505
|
+
const ast = parseSourceFile(filePath, source);
|
|
1506
|
+
let replacement = null;
|
|
1507
|
+
const visit = (node) => {
|
|
1508
|
+
if (replacement) return;
|
|
1509
|
+
if (
|
|
1510
|
+
ts.isDecorator(node) &&
|
|
1511
|
+
ts.isCallExpression(node.expression) &&
|
|
1512
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
1513
|
+
node.expression.expression.text === 'Component'
|
|
1514
|
+
) {
|
|
1515
|
+
const options = node.expression.arguments[0];
|
|
1516
|
+
if (options && ts.isObjectLiteralExpression(options)) {
|
|
1517
|
+
const imports = options.properties.find((property) => propertyName(property) === 'imports');
|
|
1518
|
+
const initializer = imports && ts.isPropertyAssignment(imports) ? imports.initializer : null;
|
|
1519
|
+
if (
|
|
1520
|
+
initializer &&
|
|
1521
|
+
ts.isArrayLiteralExpression(initializer) &&
|
|
1522
|
+
!initializer.elements.some((element) => ts.isIdentifier(element) && element.text === name)
|
|
1523
|
+
) {
|
|
1524
|
+
const last = initializer.elements[initializer.elements.length - 1];
|
|
1525
|
+
const at = last ? last.getEnd() : initializer.getStart() + 1;
|
|
1526
|
+
replacement = { start: at, end: at, text: last ? `, ${name}` : name };
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
ts.forEachChild(node, visit);
|
|
1531
|
+
};
|
|
1532
|
+
visit(ast);
|
|
1533
|
+
if (!replacement)
|
|
1534
|
+
return {
|
|
1535
|
+
conflict: conflict(
|
|
1536
|
+
filePath,
|
|
1537
|
+
'SDK4_SHELL_BANNER_002',
|
|
1538
|
+
`general-banner does not declare an @Component imports array to add ${name}; add it by hand`,
|
|
1539
|
+
),
|
|
1540
|
+
};
|
|
1541
|
+
return { content: applyReplacements(source, [replacement]) };
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/** Rewrite the general banner so the kit st-page-banner hosts the routed page. */
|
|
1545
|
+
function rewriteBannerComponent(source, filePath) {
|
|
1546
|
+
const imported = rewriteBannerImport(source, filePath);
|
|
1547
|
+
if (!imported.changed) return { content: source, changed: false, conflicts: [] };
|
|
1548
|
+
// Products use the network banner; the kit default up to SDK 4.5.0 is the gray `banner` art.
|
|
1549
|
+
const withTemplate = imported.content.replace(
|
|
1550
|
+
/<app-page-banner\b([^>]*?)\s*\/>/,
|
|
1551
|
+
(_tag, attrs) =>
|
|
1552
|
+
`<st-page-banner${attrs}${/\[?bannerAsset\]?=/.test(attrs) ? '' : ' bannerAsset="network-banner"'}><router-outlet /></st-page-banner>`,
|
|
1553
|
+
);
|
|
1554
|
+
if (withTemplate === imported.content) {
|
|
1555
|
+
return {
|
|
1556
|
+
content: source,
|
|
1557
|
+
changed: false,
|
|
1558
|
+
conflicts: [
|
|
1559
|
+
conflict(
|
|
1560
|
+
filePath,
|
|
1561
|
+
'SDK4_SHELL_BANNER_001',
|
|
1562
|
+
'general-banner template is not the recognized `<app-page-banner ... />` shape; project <router-outlet /> into st-page-banner by hand',
|
|
1563
|
+
),
|
|
1564
|
+
],
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
const withImport = applyImportEdits(withTemplate, parseSourceFile(filePath, withTemplate), {
|
|
1568
|
+
add: [{ specifier: '@angular/router', name: 'RouterOutlet' }],
|
|
1569
|
+
});
|
|
1570
|
+
if (withImport.conflicts.length > 0) return { content: source, changed: false, conflicts: withImport.conflicts };
|
|
1571
|
+
const withArray = addToComponentImports(withImport.content, filePath, 'RouterOutlet');
|
|
1572
|
+
if (withArray.conflict) return { content: source, changed: false, conflicts: [withArray.conflict] };
|
|
1573
|
+
return { content: withArray.content, changed: true, conflicts: [] };
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/** Migrate the general banner (component + spec) onto the kit st-page-banner. */
|
|
1577
|
+
async function planBannerAdapter({ root, projected }) {
|
|
1578
|
+
const changes = new Map();
|
|
1579
|
+
const conflicts = [];
|
|
1580
|
+
const read = async (relative) => (projected.has(relative) ? projected.get(relative) : readTextOrNull(root, relative));
|
|
1581
|
+
const component = await read(BANNER_COMPONENT);
|
|
1582
|
+
if (typeof component === 'string') {
|
|
1583
|
+
const rewritten = rewriteBannerComponent(component, BANNER_COMPONENT);
|
|
1584
|
+
conflicts.push(...(rewritten.conflicts ?? []));
|
|
1585
|
+
if (rewritten.changed && (rewritten.conflicts ?? []).length === 0) changes.set(BANNER_COMPONENT, rewritten.content);
|
|
1586
|
+
}
|
|
1587
|
+
const spec = await read(BANNER_SPEC);
|
|
1588
|
+
if (typeof spec === 'string') {
|
|
1589
|
+
const rewritten = rewriteBannerImport(spec, BANNER_SPEC);
|
|
1590
|
+
if (rewritten.changed) changes.set(BANNER_SPEC, rewritten.content);
|
|
1591
|
+
}
|
|
1592
|
+
return { changes, conflicts };
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
// --- planning ---------------------------------------------------------------
|
|
1596
|
+
|
|
1597
|
+
function isAllowedTarget(relative, legacyFiles = LEGACY_SHELL_FILES, extraTargets = new Set()) {
|
|
1598
|
+
if (extraTargets.has(relative)) return true;
|
|
1599
|
+
if (
|
|
1600
|
+
[
|
|
1601
|
+
MAIN_LAYOUT_TS,
|
|
1602
|
+
MAIN_LAYOUT_HTML,
|
|
1603
|
+
MAIN_LAYOUT_SPEC,
|
|
1604
|
+
APP_CONFIG,
|
|
1605
|
+
MENU_MODEL,
|
|
1606
|
+
MENU_SERVICE,
|
|
1607
|
+
LAYOUT_ACCOUNT_PROVIDER,
|
|
1608
|
+
LAYOUT_ACCOUNT_SPEC,
|
|
1609
|
+
HTTP_MODEL,
|
|
1610
|
+
].includes(relative)
|
|
1611
|
+
)
|
|
1612
|
+
return true;
|
|
1613
|
+
if (/^src\/environments\/environment[\w.-]*\.ts$/.test(relative)) return true;
|
|
1614
|
+
if (allLegacyVariants(legacyFiles).includes(relative)) return true;
|
|
1615
|
+
if (relative.endsWith('.spec.ts')) {
|
|
1616
|
+
const directory = path.posix.dirname(relative);
|
|
1617
|
+
return legacyFiles.some((legacy) => path.posix.dirname(legacy.ts) === directory);
|
|
1618
|
+
}
|
|
1619
|
+
return false;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/** The MFE template repositories the shell files come from. */
|
|
1623
|
+
const TEMPLATE_REPOS = { host: 'EnghouseGlobal/nw-sx-starters-mfe-host-template', child: 'EnghouseGlobal/nw-sx-starters-mfe-child-template' };
|
|
1624
|
+
|
|
1625
|
+
/** The required `layout` keys with the value the example suggests when the app has none. */
|
|
1626
|
+
const LAYOUT_EXAMPLE_DEFAULTS = { defaultLayout: 'modern', topLevelGroups: 'collapsible', activeMatch: 'route' };
|
|
1627
|
+
const LAYOUT_CHOICES = 'defaultLayout classic or modern, topLevelGroups divider or collapsible, activeMatch route or menu-id';
|
|
1628
|
+
|
|
1629
|
+
/**
|
|
1630
|
+
* One SDK4_SHELL_CONFIG_001 message for every layout error: the errors, then a layout block to paste
|
|
1631
|
+
* that keeps the values the app already has (its top-level defaultLayout first).
|
|
1632
|
+
* @param {string[]} errors
|
|
1633
|
+
* @param {any} config the parsed mfe-foundation.config.json, or null
|
|
1634
|
+
* @param {boolean} configFound
|
|
1635
|
+
*/
|
|
1636
|
+
function layoutConfigMessage(errors, config, configFound) {
|
|
1637
|
+
const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
1638
|
+
const current = plain(config?.layout) ? config.layout : {};
|
|
1639
|
+
const legacy = plain(config) && typeof config.defaultLayout === 'string' ? config.defaultLayout : undefined;
|
|
1640
|
+
const example = {};
|
|
1641
|
+
for (const [key, fallback] of Object.entries(LAYOUT_EXAMPLE_DEFAULTS)) {
|
|
1642
|
+
const own = typeof current[key] === 'string' ? current[key] : key === 'defaultLayout' ? legacy : undefined;
|
|
1643
|
+
example[key] = own ?? fallback;
|
|
1644
|
+
}
|
|
1645
|
+
for (const [key, value] of Object.entries(current)) if (!(key in example)) example[key] = value;
|
|
1646
|
+
const block = `{"layout": {${Object.entries(example)
|
|
1647
|
+
.map(([key, value]) => `"${key}": ${JSON.stringify(value)}`)
|
|
1648
|
+
.join(', ')}}}`;
|
|
1649
|
+
const agreement =
|
|
1650
|
+
legacy !== undefined
|
|
1651
|
+
? `; the shell reads layout.defaultLayout, so keep it and the top-level "defaultLayout": ${JSON.stringify(legacy)} in agreement`
|
|
1652
|
+
: '';
|
|
1653
|
+
const action = configFound ? `add this layout block to ${FOUNDATION_CONFIG}` : `create ${FOUNDATION_CONFIG} with this layout block`;
|
|
1654
|
+
return `${errors.join(', ')}; ${action}: ${block} (${LAYOUT_CHOICES}${agreement}), then commit and run the 4.0.0 migration again: ${RERUN}`;
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
/**
|
|
1658
|
+
* The SDK4_SHELL_ACCOUNT_003 message: which files to copy from which template repository, and how to
|
|
1659
|
+
* see what else the template adds.
|
|
1660
|
+
* @param {string[]} specifiers missing `@core/...` imports
|
|
1661
|
+
* @param {'host' | 'child'} role
|
|
1662
|
+
*/
|
|
1663
|
+
function templateCopyMessage(specifiers, role) {
|
|
1664
|
+
const files = specifiers.map((specifier) => `src/app/core/${specifier.slice('@core/'.length)}.ts`);
|
|
1665
|
+
return `the kit account provider imports ${specifiers.join(', ')}, which the app does not have; copy ${files.join(', ')} (and the .spec.ts next to each) to the same path in this app from the MFE ${role} template repository ${TEMPLATE_REPOS[role]} (github.com/${TEMPLATE_REPOS[role]}); run sdk-tools init --dry-run to see what else the template adds; or register provideLayoutAccount in app.config.ts by hand; then commit and run the 4.0.0 migration again: ${RERUN}`;
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
/**
|
|
1669
|
+
* Plans the shell adoption on `tree` for `role`, from the template snapshot in `canonical`.
|
|
1670
|
+
* @param {import('@angular-devkit/schematics').Tree} tree
|
|
1671
|
+
* @param {{ role: 'host' | 'child', canonical: { files: Record<string, string>, menuHelpers: string } }} options
|
|
1672
|
+
*/
|
|
1673
|
+
async function buildShellPlan(tree, { role, canonical }) {
|
|
1674
|
+
TREE = tree;
|
|
1675
|
+
HOST = treeHost(tree);
|
|
1676
|
+
const absoluteRoot = '/';
|
|
1677
|
+
const projectConfig = readProjectConfig(absoluteRoot);
|
|
1678
|
+
let config;
|
|
1679
|
+
try {
|
|
1680
|
+
config = JSON.parse(readText(tree, FOUNDATION_CONFIG) ?? 'null');
|
|
1681
|
+
} catch {
|
|
1682
|
+
config = null;
|
|
1683
|
+
}
|
|
1684
|
+
const operations = [];
|
|
1685
|
+
const conflicts = [];
|
|
1686
|
+
const projected = new Map();
|
|
1687
|
+
const addReplace = async (relative, content) => {
|
|
1688
|
+
const beforeHash = await hashFileOrNull(absoluteRoot, relative);
|
|
1689
|
+
const afterHash = hashContent(content);
|
|
1690
|
+
projected.set(relative, content);
|
|
1691
|
+
if (beforeHash === afterHash) return;
|
|
1692
|
+
operations.push({ path: relative, action: beforeHash === null ? 'create' : 'replace', beforeHash, afterHash });
|
|
1693
|
+
};
|
|
1694
|
+
|
|
1695
|
+
let legacyFiles = LEGACY_SHELL_FILES;
|
|
1696
|
+
const extraTargets = new Set();
|
|
1697
|
+
const configFound = TREE.exists(FOUNDATION_CONFIG);
|
|
1698
|
+
const layoutErrors =
|
|
1699
|
+
config && typeof config === 'object'
|
|
1700
|
+
? validateLayoutConfig(config)
|
|
1701
|
+
: [configFound ? `${FOUNDATION_CONFIG} is not valid JSON` : `${FOUNDATION_CONFIG} is missing`];
|
|
1702
|
+
if (layoutErrors.length > 0) {
|
|
1703
|
+
conflicts.push(conflict(FOUNDATION_CONFIG, 'SDK4_SHELL_CONFIG_001', layoutConfigMessage(layoutErrors, config, configFound)));
|
|
1704
|
+
} else {
|
|
1705
|
+
const layout = resolveLayoutConfig(config);
|
|
1706
|
+
const rendered = new Map(Object.entries(canonical.files).map(([file, text]) => [file, renderShellTemplate(text, layout)]));
|
|
1707
|
+
rendered.set(MENU_MODEL, canonical.menuHelpers);
|
|
1708
|
+
const canonicalTs = rendered.get(MAIN_LAYOUT_TS);
|
|
1709
|
+
const canonicalHtml = rendered.get(MAIN_LAYOUT_HTML);
|
|
1710
|
+
const canonicalSpec = rendered.get(MAIN_LAYOUT_SPEC);
|
|
1711
|
+
if (typeof canonicalTs !== 'string' || typeof canonicalHtml !== 'string') {
|
|
1712
|
+
conflicts.push(conflict(MAIN_LAYOUT_TS, 'SDK4_SHELL_TEMPLATE_001', 'the pinned template does not provide the st-app-layout shell files'));
|
|
1713
|
+
} else {
|
|
1714
|
+
await addReplace(MAIN_LAYOUT_TS, canonicalTs);
|
|
1715
|
+
await addReplace(MAIN_LAYOUT_HTML, syncAppLayoutInputs(canonicalHtml, layout));
|
|
1716
|
+
if (typeof canonicalSpec === 'string') await addReplace(MAIN_LAYOUT_SPEC, canonicalSpec);
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const existingConfig = await readTextOrNull(absoluteRoot, APP_CONFIG);
|
|
1720
|
+
if (existingConfig === null) {
|
|
1721
|
+
conflicts.push(conflict(APP_CONFIG, 'SDK4_SHELL_APP_CONFIG_002', 'app.config.ts is required to adopt the kit providers'));
|
|
1722
|
+
} else {
|
|
1723
|
+
const merged = mergeAppConfig(existingConfig, APP_CONFIG, {
|
|
1724
|
+
role,
|
|
1725
|
+
accountResolver: (name, bindings) => verifyAccountWrapper(name, bindings, path.join(absoluteRoot, APP_CONFIG), projectConfig.options ?? {}),
|
|
1726
|
+
});
|
|
1727
|
+
conflicts.push(...merged.conflicts);
|
|
1728
|
+
if (merged.conflicts.length === 0) {
|
|
1729
|
+
if (merged.addedAccount) {
|
|
1730
|
+
const canonicalProvider = rendered.get(LAYOUT_ACCOUNT_PROVIDER);
|
|
1731
|
+
const existingProvider = await hashFileOrNull(absoluteRoot, LAYOUT_ACCOUNT_PROVIDER);
|
|
1732
|
+
if (typeof canonicalProvider !== 'string')
|
|
1733
|
+
conflicts.push(
|
|
1734
|
+
conflict(LAYOUT_ACCOUNT_PROVIDER, 'SDK4_SHELL_TEMPLATE_002', 'the pinned template does not provide the layout account provider'),
|
|
1735
|
+
);
|
|
1736
|
+
else if (existingProvider === null) {
|
|
1737
|
+
// The template provider imports app services (session, account actions); an app without
|
|
1738
|
+
// them gets a manual item instead of a provider that does not compile.
|
|
1739
|
+
const missingImports = [
|
|
1740
|
+
...new Set(collectImportBindings(parseSourceFile(LAYOUT_ACCOUNT_PROVIDER, canonicalProvider)).map((binding) => binding.specifier)),
|
|
1741
|
+
]
|
|
1742
|
+
.filter((specifier) => specifier.startsWith('@core/'))
|
|
1743
|
+
.filter((specifier) => {
|
|
1744
|
+
const local = `src/app/core/${specifier.slice('@core/'.length)}.ts`;
|
|
1745
|
+
if (TREE.exists(local) || projected.has(local)) return false;
|
|
1746
|
+
return !ts.resolveModuleName(specifier, path.join(absoluteRoot, LAYOUT_ACCOUNT_PROVIDER), projectConfig.options ?? {}, HOST)
|
|
1747
|
+
.resolvedModule;
|
|
1748
|
+
});
|
|
1749
|
+
if (missingImports.length)
|
|
1750
|
+
conflicts.push(conflict(LAYOUT_ACCOUNT_PROVIDER, 'SDK4_SHELL_ACCOUNT_003', templateCopyMessage(missingImports, role)));
|
|
1751
|
+
else await addReplace(LAYOUT_ACCOUNT_PROVIDER, canonicalProvider);
|
|
1752
|
+
const canonicalAccountSpec = rendered.get(LAYOUT_ACCOUNT_SPEC);
|
|
1753
|
+
if (typeof canonicalAccountSpec === 'string' && (await hashFileOrNull(absoluteRoot, LAYOUT_ACCOUNT_SPEC)) === null)
|
|
1754
|
+
await addReplace(LAYOUT_ACCOUNT_SPEC, canonicalAccountSpec);
|
|
1755
|
+
} else if (existingProvider !== hashContent(canonicalProvider)) {
|
|
1756
|
+
// The consumer already has this provider (the foundation apply added it) but its bytes
|
|
1757
|
+
// differ from the pinned render, so it is customized: never overwrite it.
|
|
1758
|
+
conflicts.push(
|
|
1759
|
+
conflict(
|
|
1760
|
+
LAYOUT_ACCOUNT_PROVIDER,
|
|
1761
|
+
'SDK4_SHELL_ACCOUNT_001',
|
|
1762
|
+
'layout-account.provider.ts already exists but is not registered in app.config.ts; wire it up manually',
|
|
1763
|
+
),
|
|
1764
|
+
);
|
|
1765
|
+
}
|
|
1766
|
+
// When the file is byte-identical to the canonical render, keep it untouched and let the
|
|
1767
|
+
// app.config wiring below register it: no conflict, no rewrite.
|
|
1768
|
+
}
|
|
1769
|
+
await addReplace(APP_CONFIG, merged.content);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
const httpModel = await readTextOrNull(absoluteRoot, HTTP_MODEL);
|
|
1774
|
+
if (httpModel !== null) {
|
|
1775
|
+
const merged = mergeHttpModel(httpModel, HTTP_MODEL);
|
|
1776
|
+
conflicts.push(...merged.conflicts);
|
|
1777
|
+
if (merged.conflicts.length === 0) await addReplace(HTTP_MODEL, merged.content);
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
const environmentFiles = (await listSourceFiles(absoluteRoot)).filter((relative) => /^src\/environments\/environment[\w.-]*\.ts$/.test(relative));
|
|
1781
|
+
for (const relative of environmentFiles) {
|
|
1782
|
+
const content = await readTextOrNull(absoluteRoot, relative);
|
|
1783
|
+
if (content === null || !/export const environment\b/.test(content)) continue;
|
|
1784
|
+
const merged = mergeEnvironment(content, relative, layout.defaultLayout);
|
|
1785
|
+
conflicts.push(...merged.conflicts);
|
|
1786
|
+
if (merged.conflicts.length === 0) await addReplace(relative, merged.content);
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
const menuModel = await readTextOrNull(absoluteRoot, MENU_MODEL);
|
|
1790
|
+
const menuService = await readTextOrNull(absoluteRoot, MENU_SERVICE);
|
|
1791
|
+
if (menuModel === null || menuService === null) {
|
|
1792
|
+
conflicts.push(conflict(MENU_SERVICE, 'SDK4_SHELL_MENU_001', 'Menu.ts and menu.service.ts are required to adapt the shell menu'));
|
|
1793
|
+
} else {
|
|
1794
|
+
const canonicalMenu = rendered.get(MENU_MODEL);
|
|
1795
|
+
const adapter = planMenuAdapter({ menuModel, menuService, canonicalMenu: typeof canonicalMenu === 'string' ? canonicalMenu : '' });
|
|
1796
|
+
if (adapter.conflict) conflicts.push(conflict(MENU_SERVICE, 'SDK4_SHELL_MENU_002', adapter.conflict));
|
|
1797
|
+
else if (adapter.changed) {
|
|
1798
|
+
await addReplace(MENU_MODEL, adapter.menuModel);
|
|
1799
|
+
await addReplace(MENU_SERVICE, adapter.menuService);
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
const federated = await discoverFederatedShell(absoluteRoot);
|
|
1804
|
+
if (federated) {
|
|
1805
|
+
const shellConfig = federated.shell.className
|
|
1806
|
+
? await extractFederatedShellConfig({ root: absoluteRoot, shell: federated.shell })
|
|
1807
|
+
: { conflict: 'the remote shell does not export a component class; migrate it by hand' };
|
|
1808
|
+
if (shellConfig.conflict) {
|
|
1809
|
+
conflicts.push(conflict(federated.shell.relative, 'SDK4_SHELL_FEDERATED_001', shellConfig.conflict));
|
|
1810
|
+
} else {
|
|
1811
|
+
const routeFiles = (await listSourceFiles(absoluteRoot)).filter(
|
|
1812
|
+
(relative) => relative.endsWith('.ts') && relative !== federated.shell.relative && relative !== federated.overlay?.relative,
|
|
1813
|
+
);
|
|
1814
|
+
for (const relative of routeFiles) {
|
|
1815
|
+
const content = projected.has(relative) ? projected.get(relative) : await readTextOrNull(absoluteRoot, relative);
|
|
1816
|
+
if (typeof content !== 'string') continue;
|
|
1817
|
+
const rewritten = rewriteFederatedRoute(content, relative, { shellClassName: federated.shell.className, config: shellConfig });
|
|
1818
|
+
if (!rewritten) continue;
|
|
1819
|
+
conflicts.push(...rewritten.conflicts);
|
|
1820
|
+
if (rewritten.conflicts.length === 0) {
|
|
1821
|
+
await addReplace(relative, rewritten.content);
|
|
1822
|
+
extraTargets.add(relative);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
legacyFiles = [
|
|
1827
|
+
...LEGACY_SHELL_FILES,
|
|
1828
|
+
{ ts: federated.shell.relative, selector: null },
|
|
1829
|
+
...(federated.overlay ? [{ ts: federated.overlay.relative, selector: null }] : []),
|
|
1830
|
+
];
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
const banner = await planBannerAdapter({ root: absoluteRoot, projected });
|
|
1834
|
+
conflicts.push(...banner.conflicts);
|
|
1835
|
+
for (const [relative, content] of banner.changes) {
|
|
1836
|
+
await addReplace(relative, content);
|
|
1837
|
+
extraTargets.add(relative);
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
const prune = await planLegacyPrune({ root: absoluteRoot, projected, config: projectConfig, legacyFiles });
|
|
1841
|
+
conflicts.push(...prune.conflicts);
|
|
1842
|
+
for (const relative of prune.deletes) {
|
|
1843
|
+
operations.push({ path: relative, action: 'delete', beforeHash: await hashFileOrNull(absoluteRoot, relative), afterHash: null });
|
|
1844
|
+
extraTargets.add(relative);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
for (const [relative, content] of projected.entries()) {
|
|
1849
|
+
if (!relative.endsWith('.ts') || typeof content !== 'string') continue;
|
|
1850
|
+
const diagnostics = parseSourceFile(relative, content).parseDiagnostics;
|
|
1851
|
+
if (diagnostics.length > 0)
|
|
1852
|
+
conflicts.push(
|
|
1853
|
+
conflict(
|
|
1854
|
+
relative,
|
|
1855
|
+
'SDK4_SHELL_SYNTAX_001',
|
|
1856
|
+
`generated TypeScript does not parse: ${diagnostics.map((entry) => ts.flattenDiagnosticMessageText(entry.messageText, '\n')).join('; ')}`,
|
|
1857
|
+
),
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
operations.sort((left, right) => left.path.localeCompare(right.path));
|
|
1861
|
+
return { plan: { role, operations, conflicts }, projected, legacyFiles, extraTargets };
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
module.exports = { RERUN, buildShellPlan, isAllowedTarget, mergeAppConfig, mergeEnvironment, mergeHttpModel, planMenuAdapter, LEGACY_SHELL_FILES };
|