forked from angular/components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-example-module.ts
222 lines (195 loc) · 7.5 KB
/
generate-example-module.ts
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
import * as fs from 'fs';
import * as path from 'path';
import {parseExampleFile} from './parse-example-file';
import {parseExampleModuleFile} from './parse-example-module-file';
interface ExampleMetadata {
/** Name of the example component. */
componentName: string;
/** Path to the source file that declares this example. */
sourcePath: string;
/** Path to the directory containing this example. */
packagePath: string;
/** Selector to match the component of this example. */
selector: string;
/** Unique id for this example. */
id: string;
/** Title of the example. */
title: string;
/** Additional components for this example. */
additionalComponents: string[];
/** Files for this example. */
files: string[];
/** Reference to the module that declares this example. */
module: ExampleModule;
}
interface ExampleModule {
/** Path to the package that the module is defined in. */
packagePath: string;
/** Name of the module. */
name: string;
}
interface AnalyzedExamples {
exampleMetadata: ExampleMetadata[];
}
/** Inlines the example module template with the specified parsed data. */
function inlineExampleModuleTemplate(parsedData: AnalyzedExamples): string {
const {exampleMetadata} = parsedData;
const exampleComponents = exampleMetadata.reduce((result, data) => {
if (result[data.id] !== undefined) {
throw Error(`Multiple examples with the same id have been discovered: ${data.id}`);
}
result[data.id] = {
packagePath: data.packagePath,
title: data.title,
componentName: data.componentName,
files: data.files,
selector: data.selector,
additionalComponents: data.additionalComponents,
primaryFile: path.basename(data.sourcePath),
module: {
name: data.module.name,
importSpecifier: data.module.packagePath,
},
};
return result;
}, {} as any);
return fs
.readFileSync(require.resolve('./example-module.template'), 'utf8')
.replace(/\${exampleComponents}/g, JSON.stringify(exampleComponents, null, 2));
}
/** Converts a given camel-cased string to a dash-cased string. */
function convertToDashCase(name: string): string {
name = name.replace(/[A-Z]/g, ' $&');
name = name.toLowerCase().trim();
return name.split(' ').join('-');
}
/**
* Analyzes the examples by parsing the given TypeScript files in order to find
* individual example modules and example metadata.
*/
function analyzeExamples(sourceFiles: string[], baseDir: string): AnalyzedExamples {
const exampleMetadata: ExampleMetadata[] = [];
const exampleModules: ExampleModule[] = [];
for (const sourceFile of sourceFiles) {
const relativePath = path.relative(baseDir, sourceFile).replace(/\\/g, '/');
const importPath = relativePath.replace(/\.ts$/, '');
const packagePath = path.dirname(relativePath);
// Collect all individual example modules.
if (path.basename(sourceFile) === 'index.ts') {
exampleModules.push(
...parseExampleModuleFile(sourceFile).map(name => ({
name,
importPath,
packagePath,
})),
);
}
// Avoid parsing non-example files.
if (!path.basename(sourceFile, path.extname(sourceFile)).endsWith('-example')) {
continue;
}
const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
const {primaryComponent, secondaryComponents} = parseExampleFile(sourceFile, sourceContent);
if (primaryComponent) {
// Generate a unique id for the component by converting the class name to dash-case.
const exampleId = convertToDashCase(primaryComponent.componentName.replace('Example', ''));
const example: ExampleMetadata = {
sourcePath: relativePath,
packagePath,
id: exampleId,
selector: primaryComponent.selector,
componentName: primaryComponent.componentName,
title: primaryComponent.title.trim(),
additionalComponents: [],
files: [],
// The `module` field will be set in a separate step below. We need to set
// it here as we are setting it later in a side-effect iteration.
module: null!,
};
// For consistency, we expect the example component selector to match
// the id of the example.
const expectedSelector = `${exampleId}-example`;
if (primaryComponent.selector !== expectedSelector) {
throw Error(
`Example ${exampleId} uses selector: ${primaryComponent.selector}, ` +
`but expected: ${expectedSelector}`,
);
}
example.files.push(path.basename(relativePath));
if (primaryComponent.templateUrl) {
example.files.push(primaryComponent.templateUrl);
}
if (primaryComponent.styleUrls) {
example.files.push(...primaryComponent.styleUrls);
}
if (primaryComponent.componentName.includes('Harness')) {
example.files.push(primaryComponent.selector + '.spec.ts');
}
if (secondaryComponents.length) {
for (const meta of secondaryComponents) {
example.additionalComponents.push(meta.componentName);
if (meta.templateUrl) {
example.files.push(meta.templateUrl);
}
if (meta.styleUrls) {
example.files.push(...meta.styleUrls);
}
}
}
// Ensure referenced files actually exist in the example.
example.files.forEach(f => assertReferencedExampleFileExists(baseDir, packagePath, f));
exampleMetadata.push(example);
} else {
throw Error(
`Could not find a primary example component in ${sourceFile}. ` +
`Ensure that there's a component with an @title annotation.`,
);
}
}
// Walk through all collected examples and find their parent example module. In View Engine,
// components cannot be lazy-loaded without the associated module being loaded.
exampleMetadata.forEach(example => {
const parentModule = exampleModules.find(module =>
example.sourcePath.startsWith(module.packagePath),
);
if (!parentModule) {
throw Error(`Could not determine example module for: ${example.id}`);
}
const actualPath = path.dirname(example.sourcePath);
const expectedPath = path.posix.join(parentModule.packagePath, example.id);
// Ensures that example ids match with the directory they are stored in. This is not
// necessary for the docs site, but it helps with consistency and makes it easy to
// determine an id for an example. We also ensures for consistency that example
// folders are direct siblings of the module file.
if (actualPath !== expectedPath) {
throw Error(`Example is stored in: ${actualPath}, but expected: ${expectedPath}`);
}
example.module = parentModule;
});
return {exampleMetadata};
}
/** Asserts that the given file exists for the specified example. */
function assertReferencedExampleFileExists(
baseDir: string,
examplePackagePath: string,
relativePath: string,
) {
if (!fs.existsSync(path.join(baseDir, examplePackagePath, relativePath))) {
throw Error(
`Example "${examplePackagePath}" references "${relativePath}", but file does not exist.`,
);
}
}
/**
* Generates the example module from the given source files and writes it to a specified output
* file.
*/
export function generateExampleModule(
sourceFiles: string[],
outputFile: string,
baseDir: string = path.dirname(outputFile),
) {
const analysisData = analyzeExamples(sourceFiles, baseDir);
const generatedModuleFile = inlineExampleModuleTemplate(analysisData);
fs.writeFileSync(outputFile, generatedModuleFile);
}