@simplysm/sd-cli 6.0.19 → 6.0.27

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.
Files changed (99) hide show
  1. package/.eslintrc.js +1 -2
  2. package/dist-node/bin/sd-cli.js +25 -8
  3. package/dist-node/bin/sd-cli.js.map +1 -1
  4. package/dist-node/build-tools/SdCliIndexFileGenerator.js +51 -0
  5. package/dist-node/build-tools/SdCliIndexFileGenerator.js.map +1 -0
  6. package/dist-node/build-tools/SdCliNgModuleFilesGenerator.js +621 -0
  7. package/dist-node/build-tools/SdCliNgModuleFilesGenerator.js.map +1 -0
  8. package/dist-node/build-tools/metadata/SdAotMetadataReader.js +270 -0
  9. package/dist-node/build-tools/metadata/SdAotMetadataReader.js.map +1 -0
  10. package/dist-node/build-tools/metadata/SdIvyMetadataReader.js +101 -0
  11. package/dist-node/build-tools/metadata/SdIvyMetadataReader.js.map +1 -0
  12. package/dist-node/build-tools/metadata/SdMyMetadataReader.js +298 -0
  13. package/dist-node/build-tools/metadata/SdMyMetadataReader.js.map +1 -0
  14. package/dist-node/{build-tools → builders}/SdCliJavascriptLinter.js +1 -1
  15. package/dist-node/builders/SdCliJavascriptLinter.js.map +1 -0
  16. package/dist-node/{build-tools → builders}/SdCliNgClientBuilder.js +176 -102
  17. package/dist-node/builders/SdCliNgClientBuilder.js.map +1 -0
  18. package/dist-node/builders/SdCliNgLibraryBuilder.js +238 -0
  19. package/dist-node/builders/SdCliNgLibraryBuilder.js.map +1 -0
  20. package/dist-node/{build-tools → builders}/SdCliPublisher.js +0 -0
  21. package/dist-node/builders/SdCliPublisher.js.map +1 -0
  22. package/dist-node/{build-tools → builders}/SdCliServerBuilder.js +8 -6
  23. package/dist-node/builders/SdCliServerBuilder.js.map +1 -0
  24. package/dist-node/builders/SdCliTypescriptBuilder.js +304 -0
  25. package/dist-node/builders/SdCliTypescriptBuilder.js.map +1 -0
  26. package/dist-node/entry-points/SdCliLocalUpdater.js +9 -8
  27. package/dist-node/entry-points/SdCliLocalUpdater.js.map +1 -1
  28. package/dist-node/entry-points/SdCliProject.js +11 -9
  29. package/dist-node/entry-points/SdCliProject.js.map +1 -1
  30. package/dist-node/packages/SdCliClientPackage.js +12 -2
  31. package/dist-node/packages/SdCliClientPackage.js.map +1 -1
  32. package/dist-node/packages/SdCliLibraryPackage.js +17 -9
  33. package/dist-node/packages/SdCliLibraryPackage.js.map +1 -1
  34. package/dist-node/packages/SdCliServerPackage.js +2 -2
  35. package/dist-node/packages/SdCliServerPackage.js.map +1 -1
  36. package/dist-node/utils/SdCliFileCrypto.js +76 -0
  37. package/dist-node/utils/SdCliFileCrypto.js.map +1 -0
  38. package/dist-node/utils/SdProjectConfigUtil.js +1 -1
  39. package/dist-node/utils/SdProjectConfigUtil.js.map +1 -1
  40. package/dist-node/utils/SdWebpackUtil.js +12 -3
  41. package/dist-node/utils/SdWebpackUtil.js.map +1 -1
  42. package/dist-node/workers/lib-build-worker.js +7 -6
  43. package/dist-node/workers/lib-build-worker.js.map +1 -1
  44. package/dist-types/build-tools/SdCliIndexFileGenerator.d.ts +12 -0
  45. package/dist-types/build-tools/SdCliNgModuleFilesGenerator.d.ts +42 -0
  46. package/dist-types/build-tools/metadata/SdAotMetadataReader.d.ts +57 -0
  47. package/dist-types/build-tools/metadata/SdIvyMetadataReader.d.ts +41 -0
  48. package/dist-types/build-tools/metadata/SdMyMetadataReader.d.ts +57 -0
  49. package/dist-types/{build-tools → builders}/SdCliJavascriptLinter.d.ts +0 -0
  50. package/dist-types/{build-tools → builders}/SdCliNgClientBuilder.d.ts +1 -1
  51. package/dist-types/builders/SdCliNgLibraryBuilder.d.ts +27 -0
  52. package/dist-types/{build-tools → builders}/SdCliPublisher.d.ts +0 -0
  53. package/dist-types/{build-tools → builders}/SdCliServerBuilder.d.ts +0 -0
  54. package/dist-types/builders/SdCliTypescriptBuilder.d.ts +46 -0
  55. package/dist-types/commons.d.ts +11 -3
  56. package/dist-types/packages/SdCliClientPackage.d.ts +1 -1
  57. package/dist-types/utils/SdCliFileCrypto.d.ts +7 -0
  58. package/dist-types/utils/SdWebpackUtil.d.ts +1 -0
  59. package/package.json +10 -7
  60. package/schema/schema.json +247 -0
  61. package/src/bin/sd-cli.ts +37 -14
  62. package/src/build-tools/SdCliIndexFileGenerator.ts +61 -0
  63. package/src/build-tools/SdCliNgModuleFilesGenerator.ts +837 -0
  64. package/src/build-tools/metadata/SdAotMetadataReader.ts +368 -0
  65. package/src/build-tools/metadata/SdIvyMetadataReader.ts +152 -0
  66. package/src/build-tools/metadata/SdMyMetadataReader.ts +379 -0
  67. package/src/{build-tools → builders}/SdCliJavascriptLinter.ts +1 -1
  68. package/src/{build-tools → builders}/SdCliNgClientBuilder.ts +209 -111
  69. package/src/builders/SdCliNgLibraryBuilder.ts +336 -0
  70. package/src/{build-tools → builders}/SdCliPublisher.ts +0 -0
  71. package/src/{build-tools → builders}/SdCliServerBuilder.ts +14 -8
  72. package/src/builders/SdCliTypescriptBuilder.ts +488 -0
  73. package/src/commons.ts +11 -3
  74. package/src/entry-points/SdCliLocalUpdater.ts +9 -8
  75. package/src/entry-points/SdCliProject.ts +12 -9
  76. package/src/packages/SdCliClientPackage.ts +14 -3
  77. package/src/packages/SdCliLibraryPackage.ts +19 -11
  78. package/src/packages/SdCliServerPackage.ts +2 -2
  79. package/src/utils/SdCliFileCrypto.ts +87 -0
  80. package/src/utils/SdCliUtils.ts +56 -0
  81. package/src/utils/SdProjectConfigUtil.ts +1 -1
  82. package/src/utils/SdWebpackUtil.ts +13 -3
  83. package/src/workers/lib-build-worker.ts +8 -7
  84. package/dist-node/build-tools/SdCliJavascriptLinter.js.map +0 -1
  85. package/dist-node/build-tools/SdCliNgClientBuilder.js.map +0 -1
  86. package/dist-node/build-tools/SdCliNgLibraryBuilder.js +0 -164
  87. package/dist-node/build-tools/SdCliNgLibraryBuilder.js.map +0 -1
  88. package/dist-node/build-tools/SdCliPublisher.js.map +0 -1
  89. package/dist-node/build-tools/SdCliServerBuilder.js.map +0 -1
  90. package/dist-node/build-tools/SdCliTypescriptBuilder.js +0 -316
  91. package/dist-node/build-tools/SdCliTypescriptBuilder.js.map +0 -1
  92. package/dist-node/build-tools/SdCliTypescriptIndexFileGenerator.js +0 -75
  93. package/dist-node/build-tools/SdCliTypescriptIndexFileGenerator.js.map +0 -1
  94. package/dist-types/build-tools/SdCliNgLibraryBuilder.d.ts +0 -23
  95. package/dist-types/build-tools/SdCliTypescriptBuilder.d.ts +0 -37
  96. package/dist-types/build-tools/SdCliTypescriptIndexFileGenerator.d.ts +0 -12
  97. package/src/build-tools/SdCliNgLibraryBuilder.ts +0 -225
  98. package/src/build-tools/SdCliTypescriptBuilder.ts +0 -424
  99. package/src/build-tools/SdCliTypescriptIndexFileGenerator.ts +0 -93
@@ -0,0 +1,837 @@
1
+ import { ISdPackageBuildResult } from "../commons";
2
+ import { NeverEntryError, ObjectUtil, StringUtil } from "@simplysm/sd-core-common";
3
+ import * as ts from "typescript";
4
+ import { FsUtil, PathUtil } from "@simplysm/sd-core-node";
5
+ import * as path from "path";
6
+ import { JSDOM } from "jsdom";
7
+ import * as os from "os";
8
+ import {
9
+ IMyComponentMetadata,
10
+ IMyDirectiveMetadata,
11
+ IMyInjectableMetadata,
12
+ IMyNgModuleMetadata,
13
+ IMyPipeMetadata,
14
+ SdMyMetadataReader,
15
+ TMyNgMetadata
16
+ } from "./metadata/SdMyMetadataReader";
17
+ import {
18
+ IAotComponentMetadata,
19
+ IAotDirectiveMetadata,
20
+ IAotModuleExport,
21
+ IAotNgModuleMetadata,
22
+ IAotPipeMetadata,
23
+ SdAotMetadataReader,
24
+ TAotNgMetadata
25
+ } from "./metadata/SdAotMetadataReader";
26
+ import { IIvyNgModuleMetadata, SdIvyMetadataReader, TIvyNgMetadata } from "./metadata/SdIvyMetadataReader";
27
+ import { NgtscProgram } from "@angular/compiler-cli";
28
+
29
+ export class SdCliNgModuleFilesGenerator {
30
+ private readonly _fileCache = new Map<string, TFileCache>();
31
+
32
+ private readonly _sourceDirPath = path.resolve(this._rootDir, "src");
33
+ private readonly _moduleDistDirPath = path.resolve(this._rootDir, "src/_modules");
34
+
35
+ private _compilerHost?: ts.CompilerHost;
36
+ private _moduleResolutionCache?: ts.ModuleResolutionCache;
37
+ private _program?: ts.Program;
38
+
39
+ public constructor(private readonly _rootDir: string) {
40
+ }
41
+
42
+ public deleteFileCaches(filePaths: string[]): void {
43
+ for (const filePath of filePaths) {
44
+ this._fileCache.delete(PathUtil.posix(filePath));
45
+ }
46
+ }
47
+
48
+ public async reloadSourceFilesAsync(dirtyFilePaths: string[],
49
+ compilerHost: ts.CompilerHost,
50
+ moduleResolutionCache: ts.ModuleResolutionCache,
51
+ ngProgram: NgtscProgram): Promise<{ result: ISdPackageBuildResult[]; changed: boolean }> {
52
+ this._compilerHost = compilerHost;
53
+ this._moduleResolutionCache = moduleResolutionCache;
54
+ this._program = ngProgram.getTsProgram();
55
+
56
+ const result: ISdPackageBuildResult[] = [];
57
+
58
+ let changed = false;
59
+ for (const dirtyFilePath of dirtyFilePaths) {
60
+ if (PathUtil.isChildPath(dirtyFilePath, this._moduleDistDirPath)) continue;
61
+
62
+ this._fileCache.delete(dirtyFilePath);
63
+
64
+ // 내 소스코드
65
+ if (dirtyFilePath.endsWith(".ts") && !dirtyFilePath.endsWith(".d.ts")) {
66
+ const sourceFile = this._program.getSourceFile(dirtyFilePath);
67
+ if (!sourceFile) throw new NeverEntryError();
68
+
69
+ this._fileCache.set(dirtyFilePath, {
70
+ type: "my",
71
+ sourceFile,
72
+ metadata: new SdMyMetadataReader(sourceFile, this._program).getMetadatas()
73
+ });
74
+ changed = true;
75
+ }
76
+
77
+ // AOT 라이브러리
78
+ else if (dirtyFilePath.endsWith(".d.ts")) {
79
+ const sourceFile = this._program.getSourceFile(dirtyFilePath);
80
+ if (!sourceFile) throw new NeverEntryError();
81
+
82
+ // from METADATA
83
+ const metadataFilePath = dirtyFilePath.replace(/\.d\.ts$/, ".metadata.json");
84
+ const sdMetadataFilePath = dirtyFilePath.replace(/\.d\.ts$/, ".sd-metadata.json");
85
+
86
+ if (FsUtil.exists(metadataFilePath)) {
87
+ const metadataRoot = await FsUtil.readJsonAsync(metadataFilePath);
88
+
89
+ this._fileCache.set(dirtyFilePath, {
90
+ type: "aot",
91
+ sourceFile,
92
+ ...new SdAotMetadataReader(metadataRoot).getMetadatas()
93
+ });
94
+ changed = true;
95
+ }
96
+ else if (FsUtil.exists(sdMetadataFilePath)) {
97
+ const metadataRoot = await FsUtil.readJsonAsync(sdMetadataFilePath);
98
+
99
+ this._fileCache.set(dirtyFilePath, {
100
+ type: "aot",
101
+ sourceFile,
102
+ ...new SdAotMetadataReader(metadataRoot).getMetadatas()
103
+ });
104
+ changed = true;
105
+ }
106
+
107
+ // from IVY
108
+ else {
109
+ this._fileCache.set(dirtyFilePath, {
110
+ type: "ivy",
111
+ sourceFile,
112
+ ...new SdIvyMetadataReader(sourceFile, ngProgram).getMetadatas()
113
+ });
114
+ changed = true;
115
+ }
116
+ }
117
+ }
118
+
119
+ return { result, changed };
120
+ }
121
+
122
+ public async generateAsync(): Promise<{ result: ISdPackageBuildResult[]; changedFilePaths: string[] }> {
123
+ let moduleInfoMap = this._getModuleInfoMap();
124
+ moduleInfoMap = this._mergeCircularModuleInfoMap(moduleInfoMap);
125
+
126
+ const routingModuleMap = await this._getRoutingModuleInfoMapAsync();
127
+
128
+ const changedFilePaths = [
129
+ ...await this._writeNgModuleFileAsync(moduleInfoMap),
130
+ ...await this._writeRoutingModuleFileAsync(moduleInfoMap, routingModuleMap)
131
+ ];
132
+
133
+ const genFilePaths = [...moduleInfoMap.keys(), ...routingModuleMap.keys()].distinct();
134
+ const delFilePaths = (await FsUtil.globAsync(path.resolve(this._moduleDistDirPath, "**", "*")))
135
+ .filter((item) => (
136
+ !genFilePaths.includes(PathUtil.posix(item))
137
+ && !genFilePaths.some((item1) => PathUtil.isChildPath(item1, item))
138
+ ))
139
+ .map((item) => PathUtil.posix(item));
140
+ for (const delFilePath of delFilePaths) {
141
+ changedFilePaths.push(delFilePath);
142
+ await FsUtil.removeAsync(delFilePath);
143
+ }
144
+
145
+ return { result: [], changedFilePaths: changedFilePaths.distinct() };
146
+ }
147
+
148
+ // region NgModule
149
+
150
+ private _getModuleInfoMap(): Map<string, IGenNgModuleInfo> {
151
+ const moduleInfoMap = new Map<string, IGenNgModuleInfo>();
152
+
153
+ const ngModuleExportInfos = this._getAllNgModuleExportInfos();
154
+ const ngModuleExportMap = ngModuleExportInfos.groupBy((item) => item.exportModuleFilePath + "#" + item.exportName)
155
+ .toMap((item) => item.key, (item) => item.values);
156
+
157
+ for (const filePath of Array.from(this._fileCache.keys())) {
158
+ const fileCache = this._fileCache.get(filePath)!;
159
+ if (fileCache.type !== "my") continue;
160
+
161
+ for (const metadata of fileCache.metadata) {
162
+ if (
163
+ (
164
+ metadata.type === "Injectable"
165
+ && (
166
+ metadata.className.endsWith("Provider")
167
+ && metadata.providedIn !== "root"
168
+ )
169
+ )
170
+ || (
171
+ metadata.type === "Directive"
172
+ && metadata.className.endsWith("Directive")
173
+ )
174
+ || (
175
+ metadata.type === "Pipe"
176
+ && metadata.className.endsWith("Pipe")
177
+ )
178
+ || (
179
+ metadata.type === "Component"
180
+ && (
181
+ metadata.className.endsWith("Page")
182
+ || metadata.className.endsWith("Component")
183
+ || metadata.className.endsWith("Modal")
184
+ || metadata.className.endsWith("Control")
185
+ || metadata.className.endsWith("PrintTemplate")
186
+ || metadata.className.endsWith("Toast")
187
+ )
188
+ )
189
+ ) {
190
+ const newModuleInfo: IGenNgModuleInfo = {
191
+ moduleImportMap: new Map<string, string[]>(),
192
+ imports: [],
193
+ exports: [],
194
+ providers: [],
195
+ className: metadata.className + "Module"
196
+ };
197
+
198
+ if (metadata.type === "Injectable") {
199
+ newModuleInfo.providers.push({ moduleFilePath: filePath, name: metadata.className });
200
+ }
201
+ else {
202
+ newModuleInfo.exports.push({ moduleFilePath: filePath, name: metadata.className });
203
+ }
204
+
205
+ const moduleImport = newModuleInfo.moduleImportMap.getOrCreate(filePath, []);
206
+ moduleImport.push(metadata.className);
207
+
208
+ const ngModuleImportInfos = this._getNgModuleImportInfos(metadata, ngModuleExportMap);
209
+ for (const ngModuleImportInfo of ngModuleImportInfos) {
210
+ newModuleInfo.imports.push({ moduleFilePath: ngModuleImportInfo.filePath, name: ngModuleImportInfo.name });
211
+ const moduleImportMapValues = newModuleInfo.moduleImportMap.getOrCreate(ngModuleImportInfo.filePath, []);
212
+ moduleImportMapValues.push(ngModuleImportInfo.name);
213
+ }
214
+
215
+ moduleInfoMap.set(
216
+ this._getNgModulePath(filePath, metadata.className),
217
+ {
218
+ moduleImportMap: Array.from(newModuleInfo.moduleImportMap.entries())
219
+ .toMap((item) => item[0], (item) => item[1].distinct()),
220
+ className: newModuleInfo.className,
221
+ imports: newModuleInfo.imports.distinct(),
222
+ exports: newModuleInfo.exports.distinct(),
223
+ providers: newModuleInfo.providers.distinct()
224
+ }
225
+ );
226
+ }
227
+ }
228
+ }
229
+
230
+ // 변경 사항이 있으면 generate 다시 수행
231
+
232
+ const changed = this._reloadModuleInfoFileCache(moduleInfoMap);
233
+ if (changed) {
234
+ return this._getModuleInfoMap();
235
+ }
236
+
237
+ return moduleInfoMap;
238
+ }
239
+
240
+ private _reloadModuleInfoFileCache(moduleInfoMap: Map<string, IGenNgModuleInfo>): boolean {
241
+ let changed = false;
242
+ for (const moduleInfoMapEntry of moduleInfoMap.entries()) {
243
+ const moduleFilePath = moduleInfoMapEntry[0];
244
+ const moduleInfo = moduleInfoMapEntry[1];
245
+
246
+ const newFileCache: IMyFileCache = {
247
+ type: "my",
248
+ sourceFile: undefined,
249
+ metadata: [
250
+ {
251
+ type: "NgModule",
252
+ className: moduleInfo.className,
253
+ exports: moduleInfo.exports,
254
+ providers: moduleInfo.providers
255
+ }
256
+ ]
257
+ };
258
+
259
+ const prevFileCache = this._fileCache.get(moduleFilePath);
260
+ if (!prevFileCache) {
261
+ this._fileCache.set(moduleFilePath, newFileCache);
262
+ changed = true;
263
+ }
264
+ else if (!ObjectUtil.equal(prevFileCache.metadata, newFileCache.metadata, { ignoreArrayIndex: true })) {
265
+ prevFileCache.metadata = newFileCache.metadata;
266
+ changed = true;
267
+ }
268
+ }
269
+
270
+ return changed;
271
+ }
272
+
273
+ private _mergeCircularModuleInfoMap(moduleInfoMap: Map<string, IGenNgModuleInfo>): Map<string, IGenNgModuleInfo> {
274
+ const result = ObjectUtil.clone(moduleInfoMap);
275
+
276
+ const fnMerge = (): boolean => {
277
+ const moduleFilePaths = Array.from(result.keys()).orderBy().orderBy((item) => item.length);
278
+ for (const moduleFilePath of moduleFilePaths) {
279
+ const circularFilePaths = this._getModuleInfoMapExportCircular(result, [moduleFilePath]);
280
+ if (circularFilePaths.length === 0) continue;
281
+
282
+ for (const circularFilePath of circularFilePaths) {
283
+ const thisModuleInfo = result.get(moduleFilePath)!;
284
+ const circularModuleInfo = result.get(circularFilePath)!;
285
+
286
+ const mergedModuleInfo = ObjectUtil.merge(circularModuleInfo, thisModuleInfo, { arrayProcess: "concat" });
287
+ mergedModuleInfo.moduleImportMap.delete(moduleFilePath);
288
+ mergedModuleInfo.moduleImportMap.delete(circularFilePath);
289
+ mergedModuleInfo.imports.remove((item) => item.moduleFilePath === moduleFilePath && item.name === thisModuleInfo.className);
290
+ mergedModuleInfo.imports.remove((item) => item.moduleFilePath === circularFilePath && item.name === circularModuleInfo.className);
291
+
292
+ result.set(moduleFilePath, mergedModuleInfo);
293
+ result.delete(circularFilePath);
294
+ this._fileCache.delete(circularFilePath);
295
+
296
+ for (const otherModuleInfoFilePath of result.keys()) {
297
+ const otherModuleInfo = result.get(otherModuleInfoFilePath)!;
298
+ if (otherModuleInfo.moduleImportMap.has(circularFilePath)) {
299
+ otherModuleInfo.moduleImportMap.set(moduleFilePath, [
300
+ ...otherModuleInfo.moduleImportMap.get(moduleFilePath) ?? [],
301
+ thisModuleInfo.className
302
+ ].distinct());
303
+ otherModuleInfo.moduleImportMap.delete(circularFilePath);
304
+ otherModuleInfo.imports.remove((item) => item.moduleFilePath === circularFilePath && item.name === circularModuleInfo.className);
305
+ }
306
+ }
307
+ }
308
+
309
+ return true;
310
+ }
311
+ return false;
312
+ };
313
+ while (fnMerge()) {
314
+ }
315
+
316
+ return result;
317
+ }
318
+
319
+ private async _writeNgModuleFileAsync(moduleInfoMap: Map<string, IGenNgModuleInfo>): Promise<string[]> {
320
+ const changedDistFilePaths: string[] = [];
321
+
322
+ for (const distFilePath of moduleInfoMap.keys()) {
323
+ const moduleInfo = moduleInfoMap.get(distFilePath)!;
324
+
325
+ const moduleImportMap = Array.from(moduleInfo.moduleImportMap.entries())
326
+ .map((item) => ({
327
+ moduleName: this._getModuleModuleImportName(path.dirname(distFilePath), item[0]),
328
+ targetNames: item[1]
329
+ }))
330
+ .groupBy((item) => item.moduleName)
331
+ .toMap((item) => item.key, (item) => item.values.mapMany((v) => v.targetNames).distinct());
332
+ moduleImportMap.getOrCreate("@angular/core", []).push("NgModule");
333
+ moduleImportMap.getOrCreate("@angular/common", []).push("CommonModule");
334
+
335
+ const moduleImportTexts: string[] = [];
336
+ for (const moduleImportName of Array.from(moduleImportMap.keys()).orderBy()) {
337
+ const moduleImportInfo = moduleImportMap.get(moduleImportName)!.distinct();
338
+ if (moduleImportInfo.length === 0) continue;
339
+ moduleImportTexts.push(`import { ${moduleImportInfo.join(", ")} } from "${moduleImportName}";`);
340
+ }
341
+
342
+ const content = `
343
+ ${moduleImportTexts.join(os.EOL)}
344
+
345
+ @NgModule({
346
+ imports: [${moduleInfo.imports.map((item) => item.name).concat(["CommonModule"]).distinct().orderBy().join(", ")}],
347
+ declarations: [${moduleInfo.exports.map((item) => item.name).distinct().orderBy().join(", ")}],
348
+ exports: [${moduleInfo.exports.map((item) => item.name).distinct().orderBy().join(", ")}],
349
+ providers: [${moduleInfo.providers.map((item) => item.name).distinct().orderBy().join(", ")}]
350
+ })
351
+ export class ${moduleInfo.className} {
352
+ }`.split("\n").map((item) => item.trimEnd()).join(os.EOL).trim();
353
+
354
+ if (!FsUtil.exists(distFilePath) || await FsUtil.readFileAsync(distFilePath) !== content) {
355
+ await FsUtil.writeFileAsync(distFilePath, content);
356
+ changedDistFilePaths.push(distFilePath);
357
+ }
358
+ }
359
+
360
+ return changedDistFilePaths;
361
+ }
362
+
363
+ private _getNgModuleImportInfos(metadata: IMyInjectableMetadata | IMyDirectiveMetadata | IMyPipeMetadata | IMyComponentMetadata,
364
+ ngModuleExportMap: Map<string, INgModuleExportInfo[]>): { filePath: string; name: string }[] {
365
+ const importTargets: { filePath: string; name: string }[] = [];
366
+
367
+ // module import된 provider 찾기
368
+ for (const metadataModuleImport of metadata.moduleImports) {
369
+ importTargets.push({
370
+ filePath: metadataModuleImport.moduleFilePath,
371
+ name: metadataModuleImport.name
372
+ });
373
+ }
374
+
375
+ if ("template" in metadata && !StringUtil.isNullOrEmpty(metadata.template)) {
376
+ // template으로 component/directive 찾기
377
+ const selectorInfos = this._getAllSelectorInfos();
378
+ const templateDOM = new JSDOM(metadata.template);
379
+
380
+ for (const selectorInfo of selectorInfos) {
381
+ if (
382
+ templateDOM.window.document.querySelector([
383
+ selectorInfo.selector,
384
+ selectorInfo.selector.replace(/\[/g, "[\\[").replace(/]/g, "\\]]"),
385
+ selectorInfo.selector.replace(/\[/g, "[\\(").replace(/]/g, "\\)]")
386
+ ].join(", ")) != null
387
+ ) {
388
+ importTargets.push({ filePath: selectorInfo.filePath, name: selectorInfo.className });
389
+ }
390
+ }
391
+
392
+ // template으로 pipe 찾기
393
+ const pipeInfos = this._getAllPipeInfos();
394
+
395
+ for (const pipeInfo of pipeInfos) {
396
+ if (new RegExp("| *" + pipeInfo.name + "[^\\w]").test(metadata.template)) {
397
+ importTargets.push({ filePath: pipeInfo.filePath, name: pipeInfo.className });
398
+ }
399
+ }
400
+ }
401
+
402
+ // provider/component/directive/pipe에 따라 NgModule 찾아 import등록
403
+ const result: { filePath: string; name: string }[] = [];
404
+ for (const importTarget of importTargets) {
405
+ const ngModules = ngModuleExportMap.get(importTarget.filePath + "#" + importTarget.name);
406
+ if (ngModules) {
407
+ if (ngModules.length !== 1) throw new NeverEntryError();
408
+ result.push({ filePath: ngModules[0].filePath, name: ngModules[0].className });
409
+ }
410
+ }
411
+
412
+ return result;
413
+ }
414
+
415
+ private _getAllNgModuleExportInfos(): INgModuleExportInfo[] {
416
+ const result: INgModuleExportInfo[] = [];
417
+
418
+ for (const filePath of this._fileCache.keys()) {
419
+ const fileCache = this._fileCache.get(filePath)!;
420
+ if (fileCache.type === "my") {
421
+ const ngModules = fileCache.metadata.filter((item) => item.type === "NgModule") as IMyNgModuleMetadata[];
422
+
423
+ for (const ngModule of ngModules) {
424
+ for (const exp of ngModule.exports.concat(ngModule.providers)) {
425
+ result.push({
426
+ moduleName: undefined,
427
+ filePath,
428
+ className: ngModule.className,
429
+ exportModuleFilePath: exp.moduleFilePath,
430
+ exportName: exp.name
431
+ });
432
+ }
433
+ }
434
+ }
435
+ else if (fileCache.type === "aot") {
436
+ const ngModules = fileCache.metadata.filter((item) => item.type === "NgModule") as IAotNgModuleMetadata[];
437
+
438
+ for (const ngModule of ngModules) {
439
+ for (const exp of ngModule.exports.concat(ngModule.providers)) {
440
+ if (!StringUtil.isNullOrEmpty(exp.moduleName)) {
441
+ const newExp = this._getAotReferenceLastFilePath(filePath, exp.moduleName, exp.name);
442
+ if (!newExp) throw new NeverEntryError();
443
+
444
+ result.push({
445
+ moduleName: fileCache.moduleName,
446
+ filePath,
447
+ className: ngModule.className,
448
+ exportModuleFilePath: newExp.moduleFilePath,
449
+ exportName: newExp.name
450
+ });
451
+ }
452
+ else {
453
+ if (!fileCache.exports.some((item) => (item.as ?? item.name) === exp.name)) throw new NeverEntryError();
454
+ result.push({
455
+ moduleName: fileCache.moduleName,
456
+ filePath,
457
+ className: ngModule.className,
458
+ exportModuleFilePath: filePath,
459
+ exportName: exp.name
460
+ });
461
+ }
462
+ }
463
+ }
464
+ }
465
+ else {
466
+ const ngModules = fileCache.metadata.filter((item) => item.type === "NgModule") as IIvyNgModuleMetadata[];
467
+
468
+ for (const ngModule of ngModules) {
469
+ for (const exp of ngModule.exports) {
470
+ result.push({
471
+ moduleName: fileCache.moduleName,
472
+ filePath,
473
+ className: ngModule.className,
474
+ exportModuleFilePath: exp.moduleFilePath,
475
+ exportName: exp.name
476
+ });
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ return result.distinct();
483
+ }
484
+
485
+ private _getModuleInfoMapExportCircular(moduleInfoMap: Map<string, IGenNgModuleInfo>, arr: string[]): string[] {
486
+ if (moduleInfoMap.has(arr.last()!)) {
487
+ const moduleInfo = moduleInfoMap.get(arr.last()!)!;
488
+
489
+ const result: string[] = [];
490
+ for (const moduleImportFilePath of moduleInfo.moduleImportMap.keys()) {
491
+ if (arr.includes(moduleImportFilePath)) {
492
+ if (arr[0] === moduleImportFilePath) {
493
+ result.push(...arr.slice(1));
494
+ }
495
+ }
496
+ else {
497
+ result.push(...this._getModuleInfoMapExportCircular(moduleInfoMap, arr.concat([moduleImportFilePath])));
498
+ }
499
+ }
500
+ return result.distinct();
501
+ }
502
+ else {
503
+ return [];
504
+ }
505
+ }
506
+
507
+ private _getNgModulePath(pageFilePath: string, pageClassName: string): string {
508
+ return PathUtil.posix(this._getGenNgModuleDistPath(pageFilePath), pageClassName + "Module.ts");
509
+ }
510
+
511
+ private _getAotReferenceLastFilePath(filePath: string, moduleName: string, targetName: string): { moduleFilePath: string; name: string } | undefined {
512
+ const expFilePath = this._getResolvedFilePath(filePath, moduleName);
513
+ if (StringUtil.isNullOrEmpty(expFilePath)) throw new NeverEntryError();
514
+ const expFileCache = this._fileCache.get(expFilePath);
515
+ if (!expFileCache || expFileCache.type !== "aot") throw new NeverEntryError();
516
+ const newExp = expFileCache.exports.single((item) => (item.as ?? item.name) === targetName);
517
+ if (!newExp) throw new NeverEntryError();
518
+
519
+ if (!StringUtil.isNullOrEmpty(newExp.moduleName)) {
520
+ return this._getAotReferenceLastFilePath(expFilePath, newExp.moduleName, newExp.name!);
521
+ }
522
+ else {
523
+ return {
524
+ moduleFilePath: expFilePath,
525
+ name: newExp.as ?? newExp.name!
526
+ };
527
+ }
528
+ }
529
+
530
+ private _getAllSelectorInfos(): { selector: string; className: string; filePath: string }[] {
531
+ const result: { selector: string; className: string; filePath: string }[] = [];
532
+
533
+ for (const filePath of this._fileCache.keys()) {
534
+ const fileCache = this._fileCache.get(filePath)!;
535
+
536
+ const selectorMetadata = (fileCache.metadata as ((TAotNgMetadata | TMyNgMetadata)[]))
537
+ .filter((item) => item.type === "Component" || item.type === "Directive") as (IMyComponentMetadata | IMyDirectiveMetadata | IAotComponentMetadata | IAotDirectiveMetadata)[];
538
+
539
+ for (const selectorMetadataItem of selectorMetadata) {
540
+ if (StringUtil.isNullOrEmpty(selectorMetadataItem.selector)) continue;
541
+
542
+ result.push(({
543
+ selector: selectorMetadataItem.selector,
544
+ className: selectorMetadataItem.className,
545
+ filePath
546
+ }));
547
+ }
548
+ }
549
+ return result;
550
+ }
551
+
552
+ private _getAllPipeInfos(): { name: string; className: string; filePath: string }[] {
553
+ const result: { name: string; className: string; filePath: string }[] = [];
554
+ for (const filePath of this._fileCache.keys()) {
555
+ const fileCache = this._fileCache.get(filePath)!;
556
+
557
+ const pipeMetadata = (fileCache.metadata as ((TAotNgMetadata | TMyNgMetadata)[]))
558
+ .filter((item) => item.type === "Component" || item.type === "Directive") as (IMyPipeMetadata | IAotPipeMetadata)[];
559
+
560
+ for (const pipeMetadataItem of pipeMetadata) {
561
+ if (StringUtil.isNullOrEmpty(pipeMetadataItem.name)) continue;
562
+
563
+ result.push(({
564
+ name: pipeMetadataItem.name,
565
+ className: pipeMetadataItem.className,
566
+ filePath
567
+ }));
568
+ }
569
+ }
570
+ return result;
571
+ }
572
+
573
+ private _getModuleModuleImportName(distDirPath: string, filePath: string): string {
574
+ const fileCache = this._fileCache.get(filePath);
575
+ const presetModuleName = !fileCache || fileCache.type === "my" ? undefined : fileCache.moduleName;
576
+ if (!StringUtil.isNullOrEmpty(presetModuleName)) return presetModuleName;
577
+
578
+ const relativeFilePath = PathUtil.posix(path.relative(distDirPath, filePath));
579
+ return (relativeFilePath.startsWith(".") ? relativeFilePath : "./" + relativeFilePath)
580
+ .replace(/\.ts$/, "")
581
+ .replace(/\\/g, "/");
582
+ }
583
+
584
+ private _getResolvedFilePath(sourceFilePath: string, moduleName: string): string | undefined {
585
+ const resolvedModule = ts.resolveModuleName(
586
+ moduleName,
587
+ sourceFilePath,
588
+ this._program!.getCompilerOptions(),
589
+ this._compilerHost!,
590
+ this._moduleResolutionCache
591
+ ).resolvedModule;
592
+
593
+ if (resolvedModule) {
594
+ return PathUtil.posix(resolvedModule.resolvedFileName);
595
+ }
596
+ return undefined;
597
+ }
598
+
599
+ private _getGenNgModuleDistPath(filePath: string): string {
600
+ return path.resolve(this._moduleDistDirPath, path.relative(this._sourceDirPath, path.dirname(filePath)));
601
+ }
602
+
603
+ // endregion
604
+
605
+ // region RoutingModule
606
+
607
+ private async _getRoutingModuleInfoMapAsync(): Promise<Map<string, IGenRoutingModuleInfo>> {
608
+ const result = new Map<string, IGenRoutingModuleInfo>();
609
+
610
+ for (const filePath of Array.from(this._fileCache.keys())) {
611
+ const fileCache = this._fileCache.get(filePath)!;
612
+ if (fileCache.type !== "my") continue;
613
+
614
+ for (const metadata of fileCache.metadata) {
615
+ if (metadata.type !== "Component" || !metadata.className.endsWith("Page")) continue;
616
+
617
+ const newRoutingModuleInfo: IGenRoutingModuleInfo = {
618
+ path: "",
619
+ page: {
620
+ moduleFilePath: filePath,
621
+ name: metadata.className
622
+ },
623
+ children: []
624
+ };
625
+
626
+ const childDirName = StringUtil.toKebabCase(path.basename(filePath, path.extname(filePath)).replace(/Page$/, ""));
627
+ const childDirPath = path.resolve(path.dirname(filePath), childDirName);
628
+ if (FsUtil.exists(childDirPath)) {
629
+ newRoutingModuleInfo.children = await this._getRoutingModuleChildInfoAsync(childDirPath);
630
+ }
631
+
632
+ result.set(
633
+ this._getRoutingModulePath(filePath, metadata.className),
634
+ newRoutingModuleInfo
635
+ );
636
+ }
637
+ }
638
+
639
+ return result;
640
+ }
641
+
642
+ private async _getRoutingModuleChildInfoAsync(childDirPath: string): Promise<IGenRoutingChildModuleInfo[]> {
643
+ const result: IGenRoutingChildModuleInfo[] = [];
644
+
645
+ const childDirChildPaths = (await FsUtil.readdirAsync(childDirPath)).map((item) => path.resolve(childDirPath, item));
646
+
647
+ const ignoreDirPaths: string[] = [];
648
+ for (const childDirChildPath of childDirChildPaths) {
649
+ if (childDirChildPath.endsWith("Page.ts")) {
650
+ const childDirChildDirName = StringUtil.toKebabCase(path.basename(childDirChildPath, path.extname(childDirChildPath)).replace(/Page$/, ""));
651
+ result.push({
652
+ path: childDirChildDirName,
653
+ page: {
654
+ moduleFilePath: childDirChildPath,
655
+ name: path.basename(childDirChildPath, path.extname(childDirChildPath))
656
+ }
657
+ });
658
+ ignoreDirPaths.push(path.resolve(path.dirname(childDirChildPath), childDirChildDirName));
659
+ }
660
+ }
661
+
662
+ for (const childDirChildPath of childDirChildPaths) {
663
+ if (FsUtil.isDirectory(childDirChildPath) && !ignoreDirPaths.includes(childDirChildPath)) {
664
+ result.push({
665
+ path: path.basename(childDirChildPath),
666
+ children: await this._getRoutingModuleChildInfoAsync(childDirChildPath)
667
+ });
668
+ }
669
+ }
670
+
671
+ return result;
672
+ }
673
+
674
+ private async _writeRoutingModuleFileAsync(moduleInfoMap: Map<string, IGenNgModuleInfo>, routingModuleInfoMap: Map<string, IGenRoutingModuleInfo>): Promise<string[]> {
675
+ const changedDistFilePaths: string[] = [];
676
+ for (const distFilePath of routingModuleInfoMap.keys()) {
677
+ const routingModuleInfo = routingModuleInfoMap.get(distFilePath)!;
678
+
679
+ const routingModuleText = this._getRoutingModuleText(routingModuleInfo, distFilePath);
680
+
681
+ const moduleImportTexts: string[] = [];
682
+
683
+ const pageFilePath = this._getModuleModuleImportName(path.dirname(distFilePath), routingModuleInfo.page.moduleFilePath);
684
+ moduleImportTexts.push(`import { ${routingModuleInfo.page.name} } from "${pageFilePath}";`);
685
+
686
+ let content: string;
687
+ if (path.basename(distFilePath) === "_routes.ts") {
688
+ moduleImportTexts.push(`import { Routes } from "@angular/router";`);
689
+
690
+ content = `
691
+ ${moduleImportTexts.join(os.EOL)}
692
+
693
+ export const routes: Routes = [
694
+ ${routingModuleText.replace(/\r\n/g, "\r\n ")}
695
+ ];`.split("\n").map((item) => item.trimEnd()).join(os.EOL).trim();
696
+ }
697
+ else {
698
+ moduleImportTexts.push(`import { NgModule } from "@angular/core";`);
699
+ moduleImportTexts.push(`import { RouterModule } from "@angular/router";`);
700
+
701
+ const thisPageModuleInfoEntry = Array.from(moduleInfoMap.entries())
702
+ .single((item) => item[1].exports.some((exp) => exp.moduleFilePath === routingModuleInfo.page.moduleFilePath && exp.name === routingModuleInfo.page.name));
703
+ if (!thisPageModuleInfoEntry) throw new NeverEntryError();
704
+ const thisPageModuleInfo = {
705
+ filePath: thisPageModuleInfoEntry[0],
706
+ className: thisPageModuleInfoEntry[1].className
707
+ };
708
+
709
+ const pageNgModuleFilePath = this._getModuleModuleImportName(path.dirname(distFilePath), thisPageModuleInfo.filePath);
710
+ moduleImportTexts.push(`import { ${thisPageModuleInfo.className} } from "${pageNgModuleFilePath}";`);
711
+
712
+ content = `
713
+ ${moduleImportTexts.join(os.EOL)}
714
+
715
+ @NgModule({
716
+ imports: [
717
+ ${thisPageModuleInfo.className},
718
+ RouterModule.forChild([
719
+ ${routingModuleText.replace(/\r\n/g, "\r\n ")}
720
+ ])
721
+ ]
722
+ })
723
+ export class ${routingModuleInfo.page.name}RoutingModule {
724
+ }`.split("\n").map((item) => item.trimEnd()).join(os.EOL).trim();
725
+ }
726
+
727
+ if (!FsUtil.exists(distFilePath) || await FsUtil.readFileAsync(distFilePath) !== content) {
728
+ await FsUtil.writeFileAsync(distFilePath, content);
729
+ changedDistFilePaths.push(distFilePath);
730
+ }
731
+ }
732
+
733
+ return changedDistFilePaths;
734
+ }
735
+
736
+ private _getRoutingModulePath(pageFilePath: string, pageClassName: string): string {
737
+ if (pageFilePath === PathUtil.posix(this._sourceDirPath, "AppPage.ts")) {
738
+ return PathUtil.posix(this._sourceDirPath, "_routes.ts");
739
+ }
740
+ else {
741
+ return PathUtil.posix(this._getGenNgModuleDistPath(pageFilePath), pageClassName + "RoutingModule.ts");
742
+ }
743
+ }
744
+
745
+ private _getRoutingModuleText(routingModuleInfo: IGenRoutingModuleInfo, distFilePath: string): string {
746
+ let content = "{\r\n";
747
+ content += ` path: "${routingModuleInfo.path}",\r\n`;
748
+ content += ` component: ${routingModuleInfo.page.name},\r\n`;
749
+ if (routingModuleInfo.children.length > 0) {
750
+ content += ` children: [\r\n`;
751
+ for (const child of routingModuleInfo.children) {
752
+ const childText = this._getRoutingModuleChildText(child, path.dirname(distFilePath));
753
+ content += " " + childText.replace(/\r\n/g, "\r\n ") + ",\r\n";
754
+ }
755
+ content = content.slice(0, -3) + "\r\n";
756
+ content += ` ],\r\n`;
757
+ }
758
+
759
+ return content.slice(0, -3) + "\r\n}";
760
+ }
761
+
762
+ private _getRoutingModuleChildText(routingModuleChildInfo: IGenRoutingChildModuleInfo, distDirPath: string): string {
763
+ let content = "{\r\n";
764
+ content += ` path: "${routingModuleChildInfo.path}",\r\n`;
765
+ if (routingModuleChildInfo.page) {
766
+ const routingModuleFilePath = this._getRoutingModulePath(routingModuleChildInfo.page.moduleFilePath, routingModuleChildInfo.page.name);
767
+
768
+ const moduleDirPath = "./" + PathUtil.posix(path.dirname(path.relative(distDirPath, routingModuleFilePath)));
769
+
770
+ content += ` loadChildren: async () => await import("${moduleDirPath}/${routingModuleChildInfo.page.name}RoutingModule").then((m) => m.${routingModuleChildInfo.page.name}RoutingModule),\r\n`;
771
+ }
772
+ else if (routingModuleChildInfo.children && routingModuleChildInfo.children.length > 0) {
773
+ content += ` children: [\r\n`;
774
+ for (const child of routingModuleChildInfo.children) {
775
+ const childText = this._getRoutingModuleChildText(child, distDirPath);
776
+ content += " " + childText.replace(/\r\n/g, "\r\n ") + ",\r\n";
777
+ }
778
+ content = content.slice(0, -3) + "\r\n";
779
+ content += ` ],\r\n`;
780
+ }
781
+
782
+ return content.slice(0, -3) + "\r\n}";
783
+ }
784
+
785
+ // endregion
786
+ }
787
+
788
+ type TFileCache = IMyFileCache | IAotFileCache | IIvyFileCache;
789
+
790
+ interface IMyFileCache {
791
+ type: "my";
792
+ sourceFile?: ts.SourceFile;
793
+ metadata: TMyNgMetadata[];
794
+ }
795
+
796
+ interface IAotFileCache {
797
+ type: "aot";
798
+ sourceFile: ts.SourceFile;
799
+ moduleName: string;
800
+ exports: IAotModuleExport[];
801
+ metadata: TAotNgMetadata[];
802
+ }
803
+
804
+ interface IIvyFileCache {
805
+ type: "ivy";
806
+ sourceFile: ts.SourceFile;
807
+ moduleName: string;
808
+ metadata: TIvyNgMetadata[];
809
+ }
810
+
811
+ interface IGenNgModuleInfo {
812
+ moduleImportMap: Map<string, string[]>;
813
+ imports: { moduleFilePath: string; name: string }[];
814
+ exports: { moduleFilePath: string; name: string }[];
815
+ providers: { moduleFilePath: string; name: string }[];
816
+ className: string;
817
+ }
818
+
819
+ interface IGenRoutingModuleInfo {
820
+ path: string;
821
+ page: { moduleFilePath: string; name: string };
822
+ children: IGenRoutingChildModuleInfo[];
823
+ }
824
+
825
+ interface IGenRoutingChildModuleInfo {
826
+ path: string;
827
+ page?: { moduleFilePath: string; name: string };
828
+ children?: IGenRoutingChildModuleInfo[];
829
+ }
830
+
831
+ interface INgModuleExportInfo {
832
+ moduleName: string | undefined;
833
+ filePath: string;
834
+ className: string;
835
+ exportModuleFilePath: string;
836
+ exportName: string;
837
+ }