-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathschematic.ts
More file actions
385 lines (320 loc) · 9.88 KB
/
schematic.ts
File metadata and controls
385 lines (320 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import {
chain,
Rule,
Tree,
url,
apply,
mergeWith,
template,
move,
noop,
} from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import { strings } from '@angular-devkit/core';
import { MfSchematicSchema } from './schema';
import {
addPackageJsonDependency,
NodeDependencyType,
} from '@schematics/angular/utility/dependencies';
import * as path from 'path';
type NormalizedOptions = {
polyfills: string;
projectName: string;
projectRoot: string;
projectSourceRoot: string;
manifestPath: string;
projectConfig: any;
main: string;
port: number;
};
export default function config(options: MfSchematicSchema): Rule {
return async function (tree, context) {
const workspaceFileName = getWorkspaceFileName(tree);
const workspace = JSON.parse(tree.read(workspaceFileName).toString('utf8'));
const normalized = normalizeOptions(options, workspace);
const {
polyfills,
projectName,
projectRoot,
projectSourceRoot,
manifestPath,
main,
} = normalized;
updatePolyfills(tree, polyfills);
const remoteMap = await generateRemoteMap(workspace, projectName);
if (options.type === 'dynamic-host' && !tree.exists(manifestPath)) {
tree.create(manifestPath, JSON.stringify(remoteMap, null, '\t'));
}
const federationConfigPath = path.join(projectRoot, 'federation.config.js');
const exists = tree.exists(federationConfigPath);
const generateRule = !exists
? await generateFederationConfig(
remoteMap,
projectRoot,
projectSourceRoot,
options
)
: noop;
updateWorkspaceConfig(tree, normalized, workspace, workspaceFileName);
addPackageJsonDependency(tree, {
name: 'es-module-shims',
type: NodeDependencyType.Default,
version: '^1.5.12',
overwrite: false,
});
addPackageJsonDependency(tree, {
name: '@softarc/native-federation-runtime',
type: NodeDependencyType.Default,
version: '2.0.8',
overwrite: false,
});
context.addTask(new NodePackageInstallTask());
return chain([generateRule, makeMainAsync(main, options, remoteMap)]);
};
}
function updateWorkspaceConfig(
tree: Tree,
options: NormalizedOptions,
workspace: any,
workspaceFileName: string
) {
const { projectConfig, projectName, port } = options;
if (!projectConfig?.architect?.build || !projectConfig?.architect?.serve) {
throw new Error(
`The project doen't have a build or serve target in angular.json!`
);
}
const originalBuild = projectConfig.architect.build;
if (originalBuild.builder !== '@angular-devkit/build-angular:application') {
console.log(
'Switching project to the application builder using esbuild ...'
);
originalBuild.builder = '@angular-devkit/build-angular:application';
delete originalBuild.configurations?.development?.buildOptimizer;
delete originalBuild.configurations?.development?.vendorChunk;
}
// if (originalBuild.options.browser) {
// const browser = originalBuild.options.browser;
// delete originalBuild.options.browser;
// originalBuild.options.main = browser;
// }
if (originalBuild.options.main) {
const main = originalBuild.options.main;
delete originalBuild.options.main;
originalBuild.options.browser = main;
}
projectConfig.architect.esbuild = originalBuild;
projectConfig.architect.build = {
builder: '@angular-architects/native-federation:build',
options: {},
configurations: {
production: {
target: `${projectName}:esbuild:production`,
},
development: {
target: `${projectName}:esbuild:development`,
dev: true,
},
},
defaultConfiguration: 'production',
};
const serve = projectConfig.architect.serve;
serve.options ??= {};
serve.options.port = port;
const serveProd = projectConfig.architect.serve.configurations?.production;
if (serveProd) {
serveProd.buildTarget = `${projectName}:esbuild:production`;
delete serveProd.browserTarget;
}
const serveDev = projectConfig.architect.serve.configurations?.development;
if (serveDev) {
serveDev.buildTarget = `${projectName}:esbuild:development`;
delete serveDev.browserTarget;
}
projectConfig.architect['serve-original'] = projectConfig.architect.serve;
projectConfig.architect.serve = {
builder: '@angular-architects/native-federation:build',
options: {
target: `${projectName}:serve-original:development`,
rebuildDelay: 0,
dev: true,
port: 0,
},
};
const serveSsr = projectConfig.architect['serve-ssr'];
if (serveSsr && !serveSsr.options) {
serveSsr.options = {};
}
if (serveSsr) {
serveSsr.options.port = port;
}
// projectConfig.architect.serve.builder = serveBuilder;
// TODO: Register further builders when ready
tree.overwrite(workspaceFileName, JSON.stringify(workspace, null, '\t'));
}
function normalizeOptions(
options: MfSchematicSchema,
workspace: any
): NormalizedOptions {
if (!options.project) {
options.project = workspace.defaultProject;
}
const projects = Object.keys(workspace.projects);
if (!options.project && projects.length === 0) {
throw new Error(
`No default project found. Please specifiy a project name!`
);
}
if (!options.project) {
console.log(
'Using first configured project as default project: ' + projects[0]
);
options.project = projects[0];
}
const projectName = options.project;
const projectConfig = workspace.projects[projectName];
if (!projectConfig) {
throw new Error(`Project ${projectName} not found!`);
}
const projectRoot: string = projectConfig.root?.replace(/\\/g, '/');
const projectSourceRoot: string = projectConfig.sourceRoot?.replace(
/\\/g,
'/'
);
const manifestPath = path
.join(projectRoot, 'src/assets/federation.manifest.json')
.replace(/\\/g, '/');
const main =
projectConfig.architect.build.options.main ||
projectConfig.architect.build.options.browser;
if (!projectConfig.architect.build.options.polyfills) {
projectConfig.architect.build.options.polyfills = [];
}
const polyfills = projectConfig.architect.build.options.polyfills;
return {
polyfills,
projectName,
projectRoot,
projectSourceRoot,
manifestPath,
projectConfig,
main,
port: +(options.port || 4200),
};
}
function updatePolyfills(tree, polyfills: any) {
if (typeof polyfills === 'string') {
updatePolyfillsFile(tree, polyfills);
} else {
updatePolyfillsArray(tree, polyfills);
}
}
function updatePolyfillsFile(tree, polyfills: any) {
let polyfillsContent = tree.readText(polyfills);
if (!polyfillsContent.includes('es-module-shims')) {
polyfillsContent += `\nimport 'es-module-shims';\n`;
tree.overwrite(polyfills, polyfillsContent);
}
}
function updatePolyfillsArray(tree, polyfills: any) {
const polyfillsConfig = polyfills as string[];
if (!polyfillsConfig.includes('es-module-shims')) {
polyfillsConfig.push('es-module-shims');
}
}
function generateRemoteMap(workspace: any, projectName: string) {
const result = {};
for (const p in workspace.projects) {
const project = workspace.projects[p];
const projectType = project.projectType ?? 'application';
if (
p !== projectName &&
projectType === 'application' &&
project?.architect?.serve &&
project?.architect?.build
) {
const pPort =
project.architect['serve-original']?.options?.port ??
project.architect.serve?.options?.port ??
4200;
result[
strings.camelize(p)
] = `http://localhost:${pPort}/remoteEntry.json`;
}
}
if (Object.keys(result).length === 0) {
result['mfe1'] = `http://localhost:3000/remoteEntry.json`;
}
return result;
}
function makeMainAsync(
main: string,
options: MfSchematicSchema,
remoteMap: unknown
): Rule {
return async function (tree, context) {
const mainPath = path.dirname(main);
const bootstrapName = path.join(mainPath, 'bootstrap.ts');
if (tree.exists(bootstrapName)) {
console.info(`${bootstrapName} already exists.`);
return;
}
const mainContent = tree.read(main);
tree.create(bootstrapName, mainContent);
let newMainContent = '';
if (options.type === 'dynamic-host') {
newMainContent = `import { initFederation } from '@softarc/native-federation-runtime';
initFederation('/assets/federation.manifest.json')
.catch(err => console.error(err))
.then(_ => import('./bootstrap'))
.catch(err => console.error(err));
`;
} else if (options.type === 'host') {
const manifest = JSON.stringify(remoteMap, null, 2).replace(/"/g, "'");
newMainContent = `import { initFederation } from '@softarc/native-federation-runtime';
initFederation(${manifest})
.catch(err => console.error(err))
.then(_ => import('./bootstrap'))
.catch(err => console.error(err));
`;
} else {
newMainContent = `import { initFederation } from '@softarc/native-federation-runtime';
initFederation()
.catch(err => console.error(err))
.then(_ => import('./bootstrap'))
.catch(err => console.error(err));
`;
}
tree.overwrite(main, newMainContent);
};
}
export function getWorkspaceFileName(tree: Tree): string {
if (tree.exists('angular.json')) {
return 'angular.json';
}
if (tree.exists('workspace.json')) {
return 'workspace.json';
}
throw new Error(
"angular.json or workspace.json expected! Did you call this in your project's root?"
);
}
async function generateFederationConfig(
remoteMap: Record<string, string>,
projectRoot: string,
projectSourceRoot: string,
options: MfSchematicSchema
) {
const tmpl = url('./files');
const applied = apply(tmpl, [
template({
projectRoot,
projectSourceRoot,
remoteMap,
...options,
tmpl: '',
}),
move(projectRoot),
]);
return mergeWith(applied);
}