@sixbell-telco/sdk-tools 0.0.0-stage → 0.1.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 +32 -0
- package/README.md +277 -2
- package/data/security-floors.json +47 -0
- package/package.json +43 -4
- package/recipes/README.md +53 -0
- package/recipes/crud-list.md +21 -0
- package/recipes/custom-component.md +35 -0
- package/recipes/detail-page.md +19 -0
- package/recipes/form-dialog.md +17 -0
- package/recipes/parts/crud-list/i18n.json +83 -0
- package/recipes/parts/crud-list/src/app/features/__name__/__name__.routes.ts.tpl +30 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.html.tpl +102 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.spec.ts.tpl +101 -0
- package/recipes/parts/crud-list/src/app/features/__name__/pages/__name__-list/__name__-list.component.ts.tpl +143 -0
- package/recipes/parts/detail-page/i18n.json +32 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.html.tpl +35 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.spec.ts.tpl +58 -0
- package/recipes/parts/detail-page/src/app/features/__name__/pages/__name__-detail/__name__-detail.component.ts.tpl +68 -0
- package/recipes/parts/entity/i18n.json +5 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.model.ts.tpl +9 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.service.spec.ts.tpl +29 -0
- package/recipes/parts/entity/src/app/features/__name__/__name__.service.ts.tpl +33 -0
- package/recipes/parts/form-dialog/i18n.json +35 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.html.tpl +33 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.spec.ts.tpl +69 -0
- package/recipes/parts/form-dialog/src/app/features/__name__/components/__name__-form-dialog/__name__-form-dialog.component.ts.tpl +73 -0
- package/src/add/add.mjs +251 -0
- package/src/check/config.mjs +112 -0
- package/src/check/exceptions.mjs +103 -0
- package/src/check/federation.mjs +224 -0
- package/src/check/finding.mjs +23 -0
- package/src/check/harness.mjs +146 -0
- package/src/check/i18n.mjs +218 -0
- package/src/check/integration.mjs +566 -0
- package/src/check/security.mjs +165 -0
- package/src/check/steps.mjs +37 -0
- package/src/check/styles.mjs +347 -0
- package/src/check/wiring.mjs +198 -0
- package/src/check.mjs +333 -0
- package/src/cli.mjs +551 -0
- package/src/docs/docs.mjs +154 -0
- package/src/doctor/doctor.mjs +492 -0
- package/src/format.mjs +102 -0
- package/src/info/info.mjs +149 -0
- package/src/init/init.mjs +490 -0
- package/src/init/merge.mjs +191 -0
- package/src/init/template.mjs +292 -0
- package/src/mcp/catalog.mjs +248 -0
- package/src/mcp/glossary.mjs +75 -0
- package/src/mcp/manifest.mjs +53 -0
- package/src/mcp/recipes.mjs +198 -0
- package/src/mcp/server.mjs +249 -0
- package/src/mcp/upgrade-guide.mjs +116 -0
- package/src/mcp/usage.mjs +48 -0
- package/src/project/project.mjs +220 -0
- package/src/types.d.ts +448 -0
- package/src/upgrade/lockstep.mjs +153 -0
- package/src/upgrade/upgrade.mjs +623 -0
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sdk-tools init`: creates an MFE from its template repo, or brings an existing MFE up to the
|
|
3
|
+
* template. It always builds the whole plan first; `--dry-run` stops there, otherwise the plan is
|
|
4
|
+
* applied in one step and rolled back if any write fails.
|
|
5
|
+
*
|
|
6
|
+
* On an existing app every template file gets one decision:
|
|
7
|
+
* add the app lacks it;
|
|
8
|
+
* update the app has an untouched copy of an older template version (found in the template's
|
|
9
|
+
* git history), so the current version replaces it;
|
|
10
|
+
* merge JSON and ignore files: the template adds the keys, array items and lines the app lacks,
|
|
11
|
+
* and every product value stays;
|
|
12
|
+
* manual a foundation file the product changed, or a shape the merge cannot read: init leaves
|
|
13
|
+
* it alone and reports it (fail closed);
|
|
14
|
+
* kept any other file the product changed: the product copy stays.
|
|
15
|
+
* Product-owned paths (features, expose shells, the product config, README, CI) are never touched.
|
|
16
|
+
*/
|
|
17
|
+
import { spawnSync } from 'node:child_process';
|
|
18
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
20
|
+
import { formatJson, mergeJson, mergeLines, parseJsonc } from './merge.mjs';
|
|
21
|
+
import { blobId, resolveTemplate, templateFiles, templateHistory } from './template.mjs';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {import('../types.js').InitOptions} InitOptions
|
|
25
|
+
* @typedef {import('../types.js').InitPlan} InitPlan
|
|
26
|
+
* @typedef {import('../types.js').InitRole} InitRole
|
|
27
|
+
* @typedef {import('../types.js').InitOperation} InitOperation
|
|
28
|
+
* @typedef {import('../types.js').JsonValue} JsonValue
|
|
29
|
+
* @typedef {InitOperation & { content: Buffer, before: Buffer | null }} PlannedWrite
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** An error in what the caller asked for (exit code 2). */
|
|
33
|
+
export class InitUsageError extends Error {}
|
|
34
|
+
|
|
35
|
+
/** Template files a new app does not get: the template's own release history and sync record. */
|
|
36
|
+
const NEW_EXCLUDED = [/^CHANGELOG\.md$/, /^\.mfe-foundation\.json$/];
|
|
37
|
+
|
|
38
|
+
/** Paths the product owns on an existing app; init never reads or writes them. */
|
|
39
|
+
const PRODUCT_OWNED = [
|
|
40
|
+
/^README(\.[a-z-]+)?\.md$/,
|
|
41
|
+
/^CHANGELOG\.md$/,
|
|
42
|
+
/^CODEOWNERS$/,
|
|
43
|
+
/^\.github\//,
|
|
44
|
+
/^\.mfe-foundation\.json$/,
|
|
45
|
+
/^mfe-foundation\.config\.json$/,
|
|
46
|
+
/^package-lock\.json$/,
|
|
47
|
+
/^sonar-project\.properties$/,
|
|
48
|
+
/^scripts\/rename-project\.mjs$/,
|
|
49
|
+
/^src\/app\/features\//,
|
|
50
|
+
/^src\/app\/[^/]+-shell\.routes(\.spec)?\.ts$/,
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/** Foundation code a product often edits: a changed copy needs a person, not a silent keep. */
|
|
54
|
+
const FOUNDATION_OWNED = [
|
|
55
|
+
/^federation\.config\.js$/,
|
|
56
|
+
/^src\/app\/app\.(config|routes)\.ts$/,
|
|
57
|
+
/^src\/app\/core\/models\/Menu\.ts$/,
|
|
58
|
+
/^src\/app\/core\/services\/(account-actions|environment|menu|pubsub|session)\/[^/]+\.service\.ts$/,
|
|
59
|
+
/^src\/environments\/environment[^/]*\.ts$/,
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
/** Theme catalogs: an existing app picks its own, so a missing one is not added. */
|
|
63
|
+
const THEME_CATALOG = /^src\/assets\/themes\/catalog\/[^/]+\.json$/;
|
|
64
|
+
|
|
65
|
+
/** The app's own i18n files, where the template keeps the strings of its example feature. */
|
|
66
|
+
const APP_I18N = /^src\/assets\/i18n\/[a-z]{2}(-[A-Z]{2})?\.json$/;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The template i18n without the example feature's strings (the top-level key named after the
|
|
70
|
+
* project), which an existing app does not have.
|
|
71
|
+
* @param {Buffer} content
|
|
72
|
+
* @param {string} key
|
|
73
|
+
* @returns {Buffer}
|
|
74
|
+
*/
|
|
75
|
+
function withoutExampleKeys(content, key) {
|
|
76
|
+
try {
|
|
77
|
+
const value = asObject(parseJsonc(content.toString('utf8')));
|
|
78
|
+
if (!Object.hasOwn(value, key)) return content;
|
|
79
|
+
const { [key]: _example, ...rest } = value;
|
|
80
|
+
return Buffer.from(JSON.stringify(rest));
|
|
81
|
+
} catch {
|
|
82
|
+
return content;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Ignore files merged line by line. */
|
|
87
|
+
const LINE_MERGED = new Set(['.gitignore', '.prettierignore']);
|
|
88
|
+
|
|
89
|
+
const PROJECT_NAME = /^[a-z][a-z0-9-]*$/;
|
|
90
|
+
|
|
91
|
+
/** @param {string} rel */
|
|
92
|
+
const safeRelative = (rel) => !rel.startsWith('/') && !rel.includes('\\') && !rel.split('/').some((part) => part === '..' || part === '');
|
|
93
|
+
|
|
94
|
+
/** @param {RegExp[]} patterns @param {string} rel */
|
|
95
|
+
const matches = (patterns, rel) => patterns.some((pattern) => pattern.test(rel));
|
|
96
|
+
|
|
97
|
+
/** @param {Buffer} content */
|
|
98
|
+
const isText = (content) => !content.includes(0);
|
|
99
|
+
|
|
100
|
+
/** @param {string} file @returns {JsonValue | undefined} */
|
|
101
|
+
function readJsonFile(file) {
|
|
102
|
+
try {
|
|
103
|
+
return parseJsonc(readFileSync(file, 'utf8'));
|
|
104
|
+
} catch {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** @param {unknown} value @returns {Record<string, any>} */
|
|
110
|
+
const asObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? /** @type {Record<string, any>} */ (value) : {});
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The role of an existing app: its product config, else its federation config (exposes => child).
|
|
114
|
+
* @param {string} root
|
|
115
|
+
* @returns {InitRole | undefined}
|
|
116
|
+
*/
|
|
117
|
+
function detectRole(root) {
|
|
118
|
+
const role = asObject(readJsonFile(join(root, 'mfe-foundation.config.json'))).role;
|
|
119
|
+
if (role === 'host' || role === 'child') return role;
|
|
120
|
+
const federation = join(root, 'federation.config.js');
|
|
121
|
+
if (!existsSync(federation)) return undefined;
|
|
122
|
+
return /\bexposes\s*:\s*\{\s*['"]/.test(readFileSync(federation, 'utf8')) ? 'child' : 'host';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The paths the app's git ignores (a local proxy config, for example); init does not add those.
|
|
127
|
+
* @param {string} root
|
|
128
|
+
* @param {string[]} paths
|
|
129
|
+
* @returns {Set<string>}
|
|
130
|
+
*/
|
|
131
|
+
function gitIgnored(root, paths) {
|
|
132
|
+
if (!existsSync(join(root, '.git')) || paths.length === 0) return new Set();
|
|
133
|
+
const result = spawnSync('git', ['-C', root, 'check-ignore', '--stdin', '-z'], { input: paths.join('\0'), encoding: 'utf8' });
|
|
134
|
+
return new Set((result.stdout ?? '').split('\0').filter(Boolean));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The i18n prefix the templates derive from the project name (`mfe-child-template` -> `mfe_child_template`). @param {string} name */
|
|
138
|
+
const snake = (name) => name.replaceAll('-', '_');
|
|
139
|
+
|
|
140
|
+
/** @param {string} name */
|
|
141
|
+
const titleCase = (name) =>
|
|
142
|
+
name
|
|
143
|
+
.split('-')
|
|
144
|
+
.filter(Boolean)
|
|
145
|
+
.map((word) => word[0].toUpperCase() + word.slice(1))
|
|
146
|
+
.join(' ');
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Text replacements that turn template identity into app identity (and back, to compare an app file
|
|
150
|
+
* with the template history). Same pairs as the templates' own scripts/rename-project.mjs.
|
|
151
|
+
* @param {{ projectName: string, displayName: string | null }} from
|
|
152
|
+
* @param {{ projectName: string, displayName: string | null }} to
|
|
153
|
+
* @returns {(text: string) => string}
|
|
154
|
+
*/
|
|
155
|
+
function renamer(from, to) {
|
|
156
|
+
/** @type {[string, string][]} */
|
|
157
|
+
const pairs = [];
|
|
158
|
+
if (from.projectName !== to.projectName) pairs.push([from.projectName, to.projectName], [snake(from.projectName), snake(to.projectName)]);
|
|
159
|
+
if (from.displayName && to.displayName && from.displayName !== to.displayName) pairs.push([from.displayName, to.displayName]);
|
|
160
|
+
return (text) => pairs.reduce((out, [a, b]) => out.split(a).join(b), text);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Builds the plan and, unless `dryRun`, applies it.
|
|
165
|
+
* @param {InitOptions} options
|
|
166
|
+
* @returns {InitPlan}
|
|
167
|
+
*/
|
|
168
|
+
export function init({ cwd = process.cwd(), dir, role, dryRun = false, templateDir, roots = [], offline = false, name, displayName } = {}) {
|
|
169
|
+
const root = resolve(cwd, dir ?? '.');
|
|
170
|
+
const entries = existsSync(root) ? readdirSync(root).filter((entry) => entry !== '.git') : [];
|
|
171
|
+
/** @type {'new' | 'upgrade'} */
|
|
172
|
+
let mode;
|
|
173
|
+
if (entries.length === 0) mode = 'new';
|
|
174
|
+
else if (existsSync(join(root, 'package.json')) && existsSync(join(root, 'angular.json'))) mode = 'upgrade';
|
|
175
|
+
else
|
|
176
|
+
throw new InitUsageError(
|
|
177
|
+
`${root} is neither empty nor an Angular app (no package.json and angular.json); init creates an MFE in an empty folder or upgrades one`,
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
const detected = mode === 'upgrade' ? detectRole(root) : undefined;
|
|
181
|
+
if (role && detected && role !== detected)
|
|
182
|
+
throw new InitUsageError(`--${role} does not match this app, which is a ${detected} (mfe-foundation.config.json or federation.config.js)`);
|
|
183
|
+
const resolvedRole = role ?? detected;
|
|
184
|
+
if (!resolvedRole) {
|
|
185
|
+
throw new InitUsageError(
|
|
186
|
+
mode === 'new' ? 'pass --host or --child for a new MFE' : 'cannot tell whether this app is a host or a child; pass --host or --child',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const template = resolveTemplate(resolvedRole, { target: root, templateDir, roots, offline });
|
|
191
|
+
const templateIdentity = {
|
|
192
|
+
projectName: String(asObject(readJsonFile(join(template.path, 'package.json'))).name ?? ''),
|
|
193
|
+
displayName: asObject(asObject(readJsonFile(join(template.path, 'mfe-foundation.config.json'))).identity).displayName ?? null,
|
|
194
|
+
};
|
|
195
|
+
if (!PROJECT_NAME.test(templateIdentity.projectName)) throw new Error(`the template at ${template.path} has no usable package.json name`);
|
|
196
|
+
|
|
197
|
+
let identity;
|
|
198
|
+
if (mode === 'new') {
|
|
199
|
+
const projectName = name ?? basename(root);
|
|
200
|
+
if (!PROJECT_NAME.test(projectName))
|
|
201
|
+
throw new InitUsageError(
|
|
202
|
+
`"${projectName}" is not a valid project name (lowercase letters, digits and hyphens, starting with a letter); pass --name`,
|
|
203
|
+
);
|
|
204
|
+
identity = { projectName, displayName: displayName ?? titleCase(projectName) };
|
|
205
|
+
} else {
|
|
206
|
+
const projectName = String(asObject(readJsonFile(join(root, 'package.json'))).name ?? '');
|
|
207
|
+
if (!projectName) throw new InitUsageError(`${join(root, 'package.json')} has no name`);
|
|
208
|
+
identity = {
|
|
209
|
+
projectName,
|
|
210
|
+
displayName: asObject(asObject(readJsonFile(join(root, 'mfe-foundation.config.json'))).identity).displayName ?? displayName ?? null,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const rename = renamer(templateIdentity, identity);
|
|
214
|
+
const unrename = renamer(identity, templateIdentity);
|
|
215
|
+
|
|
216
|
+
/** @type {PlannedWrite[]} */
|
|
217
|
+
const writes = [];
|
|
218
|
+
/** @type {InitPlan['manual']} */
|
|
219
|
+
const manual = [];
|
|
220
|
+
/** @type {InitPlan['kept']} */
|
|
221
|
+
const kept = [];
|
|
222
|
+
let unchanged = 0;
|
|
223
|
+
let skipped = 0;
|
|
224
|
+
const history = mode === 'upgrade' ? templateHistory(template.path) : new Map();
|
|
225
|
+
const files = templateFiles(template.path);
|
|
226
|
+
/** @type {Map<string, Buffer>} */
|
|
227
|
+
const rendered = new Map();
|
|
228
|
+
for (const rel of files) {
|
|
229
|
+
if (!safeRelative(rel)) {
|
|
230
|
+
manual.push({ path: rel, reason: 'the template path leaves the app folder; not written' });
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const source = join(template.path, rel);
|
|
234
|
+
if (!lstatSync(source).isFile()) {
|
|
235
|
+
skipped++;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const raw = readFileSync(source);
|
|
239
|
+
rendered.set(rel, isText(raw) ? Buffer.from(rename(raw.toString('utf8'))) : raw);
|
|
240
|
+
}
|
|
241
|
+
const ignored =
|
|
242
|
+
mode === 'upgrade'
|
|
243
|
+
? gitIgnored(
|
|
244
|
+
root,
|
|
245
|
+
[...rendered.keys()].filter((rel) => !existsSync(join(root, rel))),
|
|
246
|
+
)
|
|
247
|
+
: new Set();
|
|
248
|
+
const angularProject = mode === 'upgrade' ? angularProjectRename(root, rendered.get('angular.json')) : undefined;
|
|
249
|
+
|
|
250
|
+
// Specs last, so a spec can see what happened to its subject.
|
|
251
|
+
const ordered = [...rendered.keys()].sort((a, b) => Number(a.endsWith('.spec.ts')) - Number(b.endsWith('.spec.ts')) || a.localeCompare(b));
|
|
252
|
+
/** @type {Set<string>} */
|
|
253
|
+
const written = new Set();
|
|
254
|
+
for (const rel of ordered) {
|
|
255
|
+
const content = /** @type {Buffer} */ (rendered.get(rel));
|
|
256
|
+
const target = join(root, rel);
|
|
257
|
+
if (mode === 'new') {
|
|
258
|
+
if (matches(NEW_EXCLUDED, rel)) skipped++;
|
|
259
|
+
else writes.push({ path: rel, action: 'add', reason: 'new app', content, before: null });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (matches(PRODUCT_OWNED, rel)) {
|
|
263
|
+
skipped++;
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (!existsSync(target)) {
|
|
267
|
+
if (ignored.has(rel)) {
|
|
268
|
+
kept.push({ path: rel, reason: "not added: the app's .gitignore ignores it" });
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (THEME_CATALOG.test(rel)) {
|
|
272
|
+
kept.push({ path: rel, reason: 'not added: the app chooses its theme catalogs (themes.json)' });
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
const subject = rel.endsWith('.spec.ts') ? rel.replace(/\.spec\.ts$/, '.ts') : undefined;
|
|
276
|
+
if (
|
|
277
|
+
subject &&
|
|
278
|
+
rendered.has(subject) &&
|
|
279
|
+
existsSync(join(root, subject)) &&
|
|
280
|
+
!written.has(subject) &&
|
|
281
|
+
!readFileSync(join(root, subject)).equals(/** @type {Buffer} */ (rendered.get(subject)))
|
|
282
|
+
) {
|
|
283
|
+
kept.push({ path: rel, reason: `not added: the product changed ${subject}, so the template spec would test code the app does not have` });
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
writes.push({ path: rel, action: 'add', reason: 'missing in the app', content, before: null });
|
|
287
|
+
written.add(rel);
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (!lstatSync(target).isFile()) {
|
|
291
|
+
manual.push({ path: rel, reason: 'the app has a folder or link where the template has a file' });
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
const before = readFileSync(target);
|
|
295
|
+
if (before.equals(content)) {
|
|
296
|
+
unchanged++;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const pastBlobs = history.get(rel);
|
|
300
|
+
if (pastBlobs && pastBlobs.has(blobId(isText(before) ? Buffer.from(unrename(before.toString('utf8'))) : before))) {
|
|
301
|
+
writes.push({ path: rel, action: 'update', reason: 'untouched copy of an older template version', content, before });
|
|
302
|
+
written.add(rel);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (rel.endsWith('.json')) {
|
|
306
|
+
let incoming = rel === 'angular.json' && angularProject ? angularProject(content) : content;
|
|
307
|
+
if (APP_I18N.test(rel)) incoming = withoutExampleKeys(incoming, snake(identity.projectName));
|
|
308
|
+
const outcome = planJsonMerge(rel, before, incoming);
|
|
309
|
+
if ('manual' in outcome) manual.push({ path: rel, reason: outcome.manual });
|
|
310
|
+
else if (outcome.content)
|
|
311
|
+
writes.push({ path: rel, action: 'merge', reason: 'template keys and items the app lacks', content: outcome.content, before });
|
|
312
|
+
else unchanged++;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (LINE_MERGED.has(rel)) {
|
|
316
|
+
const merged = mergeLines(before.toString('utf8'), content.toString('utf8'));
|
|
317
|
+
if (merged === before.toString('utf8')) unchanged++;
|
|
318
|
+
else writes.push({ path: rel, action: 'merge', reason: 'template lines the app lacks', content: Buffer.from(merged), before });
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (matches(FOUNDATION_OWNED, rel))
|
|
322
|
+
manual.push({ path: rel, reason: 'foundation file the product changed; compare it with the template and merge by hand' });
|
|
323
|
+
else kept.push({ path: rel, reason: 'the product changed it; the product copy stays' });
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const operations = writes.map(({ path, action, reason }) => ({ path, action, reason }));
|
|
327
|
+
/** @type {InitPlan} */
|
|
328
|
+
const plan = {
|
|
329
|
+
mode,
|
|
330
|
+
role: resolvedRole,
|
|
331
|
+
root,
|
|
332
|
+
dryRun,
|
|
333
|
+
applied: false,
|
|
334
|
+
template,
|
|
335
|
+
identity,
|
|
336
|
+
operations,
|
|
337
|
+
manual,
|
|
338
|
+
kept,
|
|
339
|
+
counts: {
|
|
340
|
+
add: operations.filter((o) => o.action === 'add').length,
|
|
341
|
+
update: operations.filter((o) => o.action === 'update').length,
|
|
342
|
+
merge: operations.filter((o) => o.action === 'merge').length,
|
|
343
|
+
manual: manual.length,
|
|
344
|
+
kept: kept.length,
|
|
345
|
+
unchanged,
|
|
346
|
+
skipped,
|
|
347
|
+
},
|
|
348
|
+
next:
|
|
349
|
+
mode === 'new'
|
|
350
|
+
? ['npm install', 'npm run build', 'npx @sixbell-telco/sdk-tools check']
|
|
351
|
+
: [
|
|
352
|
+
'npm install',
|
|
353
|
+
'npm run build',
|
|
354
|
+
'npx @sixbell-telco/sdk-tools check',
|
|
355
|
+
...(manual.length ? ['merge the manual files by hand, then run sdk-tools init --dry-run again'] : []),
|
|
356
|
+
],
|
|
357
|
+
};
|
|
358
|
+
if (!dryRun && writes.length) {
|
|
359
|
+
applyWrites(root, writes);
|
|
360
|
+
plan.applied = true;
|
|
361
|
+
}
|
|
362
|
+
return plan;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* When the app names its angular.json project differently from its package (the template uses the
|
|
367
|
+
* package name for both), returns a function that renames the template's project to the app's, so the
|
|
368
|
+
* merge does not add a second project. Undefined when no rename is needed or the shapes are unclear.
|
|
369
|
+
* @param {string} root
|
|
370
|
+
* @param {Buffer | undefined} templateAngular
|
|
371
|
+
* @returns {((content: Buffer) => Buffer) | undefined}
|
|
372
|
+
*/
|
|
373
|
+
function angularProjectRename(root, templateAngular) {
|
|
374
|
+
if (!templateAngular) return undefined;
|
|
375
|
+
let theirs;
|
|
376
|
+
try {
|
|
377
|
+
theirs = Object.keys(asObject(asObject(parseJsonc(templateAngular.toString('utf8'))).projects));
|
|
378
|
+
} catch {
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
const ours = Object.keys(asObject(asObject(readJsonFile(join(root, 'angular.json'))).projects));
|
|
382
|
+
if (theirs.length !== 1 || ours.length !== 1 || theirs[0] === ours[0]) return undefined;
|
|
383
|
+
const [from, to] = [theirs[0], ours[0]];
|
|
384
|
+
return (content) => {
|
|
385
|
+
const value = asObject(parseJsonc(content.toString('utf8')));
|
|
386
|
+
const projects = asObject(value.projects);
|
|
387
|
+
const text = JSON.stringify({ ...value, projects: { [to]: projects[from] } })
|
|
388
|
+
.split(`"${from}:`)
|
|
389
|
+
.join(`"${to}:`);
|
|
390
|
+
return Buffer.from(text);
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* @param {string} rel
|
|
396
|
+
* @param {Buffer} before
|
|
397
|
+
* @param {Buffer} incoming
|
|
398
|
+
* @returns {{ manual: string } | { content: Buffer | null }}
|
|
399
|
+
*/
|
|
400
|
+
function planJsonMerge(rel, before, incoming) {
|
|
401
|
+
let existing;
|
|
402
|
+
let template;
|
|
403
|
+
try {
|
|
404
|
+
existing = parseJsonc(before.toString('utf8'));
|
|
405
|
+
} catch (error) {
|
|
406
|
+
return { manual: `the app copy is not valid JSON (${/** @type {Error} */ (error).message}); merge by hand` };
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
template = parseJsonc(incoming.toString('utf8'));
|
|
410
|
+
} catch (error) {
|
|
411
|
+
return { manual: `the template copy is not valid JSON (${/** @type {Error} */ (error).message})` };
|
|
412
|
+
}
|
|
413
|
+
const { value, conflicts } = mergeJson(existing, template, rel);
|
|
414
|
+
if (conflicts.length) return { manual: `cannot merge: ${conflicts.join('; ')}` };
|
|
415
|
+
if (JSON.stringify(value) === JSON.stringify(existing)) return { content: null };
|
|
416
|
+
return { content: Buffer.from(formatJson(value)) };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Writes the plan. Every target must still hold what the plan read; if anything fails, the files
|
|
421
|
+
* written so far are restored (or removed) before the error is rethrown.
|
|
422
|
+
* @param {string} root
|
|
423
|
+
* @param {PlannedWrite[]} writes
|
|
424
|
+
*/
|
|
425
|
+
function applyWrites(root, writes) {
|
|
426
|
+
/** @type {{ file: string, before: Buffer | null }[]} */
|
|
427
|
+
const done = [];
|
|
428
|
+
/** @type {string[]} */
|
|
429
|
+
const createdDirs = [];
|
|
430
|
+
try {
|
|
431
|
+
for (const write of writes) {
|
|
432
|
+
const file = join(root, write.path);
|
|
433
|
+
const now = existsSync(file) ? readFileSync(file) : null;
|
|
434
|
+
if ((now === null) !== (write.before === null) || (now && write.before && !now.equals(write.before))) {
|
|
435
|
+
throw new Error(`${write.path} changed while init was planning; nothing was written, run init again`);
|
|
436
|
+
}
|
|
437
|
+
let parent = dirname(file);
|
|
438
|
+
/** @type {string[]} */
|
|
439
|
+
const missing = [];
|
|
440
|
+
while (!existsSync(parent)) {
|
|
441
|
+
missing.push(parent);
|
|
442
|
+
parent = dirname(parent);
|
|
443
|
+
}
|
|
444
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
445
|
+
createdDirs.push(...missing);
|
|
446
|
+
done.push({ file, before: now });
|
|
447
|
+
writeFileSync(file, write.content);
|
|
448
|
+
}
|
|
449
|
+
} catch (error) {
|
|
450
|
+
for (const { file, before } of done.reverse()) {
|
|
451
|
+
if (before === null) rmSync(file, { force: true });
|
|
452
|
+
else writeFileSync(file, before);
|
|
453
|
+
}
|
|
454
|
+
for (const created of createdDirs.sort((a, b) => b.length - a.length)) rmSync(created, { recursive: true, force: true });
|
|
455
|
+
throw error;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The plan as text for a terminal.
|
|
461
|
+
* @param {InitPlan} plan
|
|
462
|
+
* @returns {string}
|
|
463
|
+
*/
|
|
464
|
+
export function formatInit(plan) {
|
|
465
|
+
const { counts, template } = plan;
|
|
466
|
+
const where = template.source === 'cache' ? 'cached clone' : template.source === 'local' ? 'local checkout' : 'folder';
|
|
467
|
+
const lines = [
|
|
468
|
+
`sdk-tools init: ${plan.mode === 'new' ? 'new' : 'upgrade'} ${plan.role} "${plan.identity.projectName}" in ${plan.root}`,
|
|
469
|
+
`template ${template.repo} (${where} ${template.path}${template.commit ? ` @ ${template.commit.slice(0, 7)}` : ''})`,
|
|
470
|
+
'',
|
|
471
|
+
];
|
|
472
|
+
const verb = plan.applied ? '' : 'would ';
|
|
473
|
+
if (plan.mode === 'new') lines.push(`${plan.applied ? 'Created' : 'Would create'} ${counts.add} files from the template.`);
|
|
474
|
+
else for (const op of plan.operations) lines.push(` ${op.action.padEnd(7)} ${op.path} (${op.reason})`);
|
|
475
|
+
if (plan.manual.length) {
|
|
476
|
+
lines.push('', `Manual: init ${verb}leave${plan.applied ? 's' : ''} these alone; merge them by hand`);
|
|
477
|
+
for (const item of plan.manual) lines.push(` ${item.path}: ${item.reason}`);
|
|
478
|
+
}
|
|
479
|
+
if (plan.kept.length) {
|
|
480
|
+
lines.push('', 'Kept (product copies):');
|
|
481
|
+
for (const item of plan.kept) lines.push(` ${item.path}`);
|
|
482
|
+
}
|
|
483
|
+
lines.push(
|
|
484
|
+
'',
|
|
485
|
+
`${counts.add} add, ${counts.update} update, ${counts.merge} merge, ${counts.manual} manual, ${counts.kept} kept, ${counts.unchanged} unchanged.` +
|
|
486
|
+
(plan.dryRun ? ' Dry run: nothing written.' : plan.applied ? '' : ' Nothing to write.'),
|
|
487
|
+
);
|
|
488
|
+
if (!plan.dryRun) lines.push(`Next: ${plan.next.join(', then ')}`);
|
|
489
|
+
return lines.join('\n');
|
|
490
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured merges for `sdk-tools init`: template JSON into product JSON, and template ignore lines
|
|
3
|
+
* into product ignore files. A merge never drops or changes a product value; a shape it cannot merge
|
|
4
|
+
* (an object where the template has an array, a file that does not parse) is reported as a conflict
|
|
5
|
+
* so the caller leaves the file to a person.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** @typedef {import('../types.js').JsonValue} JsonValue */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Arrays of objects matched by a key field instead of kept as the product wrote them. Paths use `*`
|
|
12
|
+
* for one segment; the angular.json budgets are the only ones the templates need.
|
|
13
|
+
* @type {Record<string, Record<string, string>>}
|
|
14
|
+
*/
|
|
15
|
+
const KEYED_ARRAYS = {
|
|
16
|
+
'angular.json': { 'projects.*.architect.*.configurations.*.budgets': 'type' },
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** @param {unknown} value @returns {value is Record<string, JsonValue>} */
|
|
20
|
+
const plainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
|
|
22
|
+
/** @param {unknown} value */
|
|
23
|
+
const primitive = (value) => value === null || typeof value !== 'object';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Removes comments while keeping quoted strings, so JSONC globs such as `src/**\/*.spec.ts` survive.
|
|
27
|
+
* An unterminated block comment stays literal.
|
|
28
|
+
* @param {string} source
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
function stripJsonComments(source) {
|
|
32
|
+
let result = '';
|
|
33
|
+
let index = 0;
|
|
34
|
+
while (index < source.length) {
|
|
35
|
+
const char = source[index];
|
|
36
|
+
const next = source[index + 1];
|
|
37
|
+
if (char === '"') {
|
|
38
|
+
const start = index;
|
|
39
|
+
index += 1;
|
|
40
|
+
while (index < source.length && source[index] !== '"') index += source[index] === '\\' ? 2 : 1;
|
|
41
|
+
index += 1;
|
|
42
|
+
result += source.slice(start, index);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (char === '/' && next === '*') {
|
|
46
|
+
const end = source.indexOf('*/', index + 2);
|
|
47
|
+
if (end !== -1) {
|
|
48
|
+
index = end + 2;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (char === '/' && next === '/') {
|
|
53
|
+
while (index < source.length && source[index] !== '\n') index += 1;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
result += char;
|
|
57
|
+
index += 1;
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Parses JSON or JSONC (comments and trailing commas, as tsconfig files have them).
|
|
64
|
+
* @param {string} text
|
|
65
|
+
* @returns {JsonValue}
|
|
66
|
+
*/
|
|
67
|
+
export function parseJsonc(text) {
|
|
68
|
+
return JSON.parse(stripJsonComments(text).replace(/,(\s*[}\]])/g, '$1'));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Prettier's printWidth in the MFE templates. */
|
|
72
|
+
const PRINT_WIDTH = 150;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* JSON as Prettier prints it in the MFE templates (two spaces, an array of primitives on one line when
|
|
76
|
+
* it fits), so merged files stay `prettier --check` clean.
|
|
77
|
+
* @param {JsonValue} value
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function formatJson(value) {
|
|
81
|
+
return `${printJson(value, 0, 0, false)}\n`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {JsonValue} value
|
|
86
|
+
* @param {number} indent
|
|
87
|
+
* @param {number} prefixWidth
|
|
88
|
+
* @param {boolean} trailingComma
|
|
89
|
+
* @returns {string}
|
|
90
|
+
*/
|
|
91
|
+
function printJson(value, indent, prefixWidth, trailingComma) {
|
|
92
|
+
if (primitive(value)) return JSON.stringify(value);
|
|
93
|
+
const pad = ' '.repeat(indent + 2);
|
|
94
|
+
const close = ' '.repeat(indent);
|
|
95
|
+
if (Array.isArray(value)) {
|
|
96
|
+
if (value.length === 0) return '[]';
|
|
97
|
+
if (value.every(primitive)) {
|
|
98
|
+
const inline = `[${value.map((item) => JSON.stringify(item)).join(', ')}]`;
|
|
99
|
+
if (indent + prefixWidth + inline.length + (trailingComma ? 1 : 0) <= PRINT_WIDTH) return inline;
|
|
100
|
+
}
|
|
101
|
+
return `[\n${value.map((item, i) => `${pad}${printJson(item, indent + 2, 0, i < value.length - 1)}`).join(',\n')}\n${close}]`;
|
|
102
|
+
}
|
|
103
|
+
const entries = Object.entries(/** @type {Record<string, JsonValue>} */ (value));
|
|
104
|
+
if (entries.length === 0) return '{}';
|
|
105
|
+
const lines = entries.map(([key, item], i) => {
|
|
106
|
+
const prefix = `${JSON.stringify(key)}: `;
|
|
107
|
+
return `${pad}${prefix}${printJson(item, indent + 2, prefix.length, i < entries.length - 1)}`;
|
|
108
|
+
});
|
|
109
|
+
return `{\n${lines.join(',\n')}\n${close}}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {string} path dotted path without array indexes
|
|
114
|
+
* @param {Record<string, string>} keyed
|
|
115
|
+
* @returns {string | undefined} the key field when `path` is a keyed array
|
|
116
|
+
*/
|
|
117
|
+
function keyedField(path, keyed) {
|
|
118
|
+
for (const [pattern, field] of Object.entries(keyed)) {
|
|
119
|
+
const regex = new RegExp(`^${pattern.replaceAll('.', '\\.').replaceAll('*', '[^.]+')}$`);
|
|
120
|
+
if (regex.test(path)) return field;
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Merges template JSON into product JSON. The product wins every value and every list it has; the
|
|
127
|
+
* template adds the keys the product lacks and the keyed items it lacks (an angular.json budget type).
|
|
128
|
+
* Key order follows the product file.
|
|
129
|
+
* @param {JsonValue} existing the product file
|
|
130
|
+
* @param {JsonValue} incoming the template file
|
|
131
|
+
* @param {string} [file] the repo-relative path, for keyed arrays
|
|
132
|
+
* @returns {{ value: JsonValue, conflicts: string[] }}
|
|
133
|
+
*/
|
|
134
|
+
export function mergeJson(existing, incoming, file = '') {
|
|
135
|
+
/** @type {string[]} */
|
|
136
|
+
const conflicts = [];
|
|
137
|
+
const keyed = KEYED_ARRAYS[file] ?? {};
|
|
138
|
+
/**
|
|
139
|
+
* @param {JsonValue} left
|
|
140
|
+
* @param {JsonValue} right
|
|
141
|
+
* @param {string} path
|
|
142
|
+
* @returns {JsonValue}
|
|
143
|
+
*/
|
|
144
|
+
const merge = (left, right, path) => {
|
|
145
|
+
if (plainObject(left) && plainObject(right)) {
|
|
146
|
+
/** @type {Record<string, JsonValue>} */
|
|
147
|
+
const out = { ...left };
|
|
148
|
+
for (const [key, value] of Object.entries(right)) {
|
|
149
|
+
out[key] = Object.hasOwn(left, key) ? merge(left[key], value, path ? `${path}.${key}` : key) : value;
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
154
|
+
const field = keyedField(path, keyed);
|
|
155
|
+
if (field) {
|
|
156
|
+
const out = [...left];
|
|
157
|
+
for (const item of right) {
|
|
158
|
+
const key = plainObject(item) ? item[field] : undefined;
|
|
159
|
+
const at = out.findIndex((candidate) => plainObject(candidate) && candidate[field] === key);
|
|
160
|
+
if (at === -1) out.push(item);
|
|
161
|
+
else out[at] = merge(out[at], item, `${path}[]`);
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
// Lists (tsconfig files, theme catalogs, translation paths) are product choices: the product's stays.
|
|
166
|
+
return left;
|
|
167
|
+
}
|
|
168
|
+
if (Array.isArray(left) !== Array.isArray(right) || plainObject(left) !== plainObject(right)) {
|
|
169
|
+
conflicts.push(`${path || '(root)'}: the product has ${kind(left)} where the template has ${kind(right)}`);
|
|
170
|
+
}
|
|
171
|
+
return left;
|
|
172
|
+
};
|
|
173
|
+
return { value: merge(existing, incoming, ''), conflicts };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** @param {JsonValue} value */
|
|
177
|
+
const kind = (value) => (Array.isArray(value) ? 'an array' : plainObject(value) ? 'an object' : `a ${value === null ? 'null' : typeof value}`);
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Appends the template lines the product file lacks (ignore files), keeping every product line.
|
|
181
|
+
* @param {string} existing
|
|
182
|
+
* @param {string} incoming
|
|
183
|
+
* @returns {string}
|
|
184
|
+
*/
|
|
185
|
+
export function mergeLines(existing, incoming) {
|
|
186
|
+
const have = new Set(existing.split('\n').map((line) => line.trim()));
|
|
187
|
+
const missing = incoming.split('\n').filter((line) => line.trim() && !line.trim().startsWith('#') && !have.has(line.trim()));
|
|
188
|
+
if (missing.length === 0) return existing;
|
|
189
|
+
const base = existing.length === 0 || existing.endsWith('\n') ? existing : `${existing}\n`;
|
|
190
|
+
return `${base}${missing.join('\n')}\n`;
|
|
191
|
+
}
|