forked from ionic-team/ionic-app-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.ts
More file actions
216 lines (169 loc) Β· 7.29 KB
/
template.ts
File metadata and controls
216 lines (169 loc) Β· 7.29 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
import { readFileSync, writeFileSync } from 'fs';
import { dirname, extname, join, parse, resolve } from 'path';
import * as Constants from './util/constants';
import { BuildContext, BuildState, ChangedFile, File } from './util/interfaces';
import { changeExtension, getStringPropertyValue } from './util/helpers';
import { Logger } from './logger/logger';
export function templateUpdate(changedFiles: ChangedFile[], context: BuildContext) {
try {
const changedTemplates = changedFiles.filter(changedFile => changedFile.ext === '.html');
const start = Date.now();
const bundleFiles = context.fileCache.getAll().filter(file => file.path.indexOf(context.buildDir) >= 0 && extname(file.path) === '.js');
// update the corresponding transpiled javascript file with the template changed (inline it)
// as well as the bundle
for (const changedTemplateFile of changedTemplates) {
const file = context.fileCache.get(changedTemplateFile.filePath);
if (!updateCorrespondingJsFile(context, file.content, changedTemplateFile.filePath)) {
throw new Error(`Failed to inline template ${changedTemplateFile.filePath}`);
}
// find the corresponding bundle
for (const bundleFile of bundleFiles) {
const newContent = replaceExistingJsTemplate(bundleFile.content, file.content, changedTemplateFile.filePath);
if (newContent && newContent !== bundleFile.content) {
context.fileCache.set(bundleFile.path, { path: bundleFile.path, content: newContent});
writeFileSync(bundleFile.path, newContent);
break;
}
}
}
// awesome, all good and template updated in the bundle file
const logger = new Logger(`template update`);
logger.setStartTime(start);
// congrats, all good
changedTemplates.forEach(changedTemplate => {
Logger.debug(`templateUpdate, updated: ${changedTemplate.filePath}`);
});
context.templateState = BuildState.SuccessfulBuild;
logger.finish();
return Promise.resolve();
} catch (ex) {
Logger.debug(`templateUpdate error: ${ex.message}`);
context.transpileState = BuildState.RequiresBuild;
context.deepLinkState = BuildState.RequiresBuild;
context.bundleState = BuildState.RequiresUpdate;
return Promise.resolve();
}
}
function updateCorrespondingJsFile(context: BuildContext, newTemplateContent: string, existingHtmlTemplatePath: string) {
const moduleFileExtension = changeExtension(getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX), '.js');
const javascriptFiles = context.fileCache.getAll().filter((file: File) => dirname(file.path) === dirname(existingHtmlTemplatePath) && extname(file.path) === '.js' && !file.path.endsWith(moduleFileExtension));
for (const javascriptFile of javascriptFiles) {
const newContent = replaceExistingJsTemplate(javascriptFile.content, newTemplateContent, existingHtmlTemplatePath);
if (newContent && newContent !== javascriptFile.content) {
javascriptFile.content = newContent;
// set the file again to generate a new timestamp
// do the same for the typescript file just to invalidate any caches, etc.
context.fileCache.set(javascriptFile.path, javascriptFile);
const typescriptFilePath = changeExtension(javascriptFile.path, '.ts');
context.fileCache.set(typescriptFilePath, context.fileCache.get(typescriptFilePath));
return true;
}
}
return false;
}
export function inlineTemplate(sourceText: string, sourcePath: string): string {
const componentDir = parse(sourcePath).dir;
let match: TemplateUrlMatch;
let replacement: string;
let lastMatch: string = null;
while (match = getTemplateMatch(sourceText)) {
if (match.component === lastMatch) {
// panic! we don't want to melt any machines if there's a bug
Logger.debug(`Error matching component: ${match.component}`);
return sourceText;
}
lastMatch = match.component;
if (match.templateUrl === '') {
Logger.error(`Error @Component templateUrl missing in: "${sourcePath}"`);
return sourceText;
}
replacement = updateTemplate(componentDir, match);
if (replacement) {
sourceText = sourceText.replace(match.component, replacement);
}
}
return sourceText;
}
export function updateTemplate(componentDir: string, match: TemplateUrlMatch): string {
const htmlFilePath = join(componentDir, match.templateUrl);
try {
const templateContent = readFileSync(htmlFilePath, 'utf8');
return replaceTemplateUrl(match, htmlFilePath, templateContent);
} catch (e) {
Logger.error(`template error, "${htmlFilePath}": ${e}`);
}
return null;
}
export function replaceTemplateUrl(match: TemplateUrlMatch, htmlFilePath: string, templateContent: string): string {
const orgTemplateProperty = match.templateProperty;
const newTemplateProperty = getTemplateFormat(htmlFilePath, templateContent);
return match.component.replace(orgTemplateProperty, newTemplateProperty);
}
export function replaceExistingJsTemplate(existingSourceText: string, newTemplateContent: string, htmlFilePath: string): string {
let prefix = getTemplatePrefix(htmlFilePath);
let startIndex = existingSourceText.indexOf(prefix);
let isStringified = false;
if (startIndex === -1) {
prefix = stringify(prefix);
isStringified = true;
}
startIndex = existingSourceText.indexOf(prefix);
if (startIndex === -1) {
return null;
}
let suffix = getTemplateSuffix(htmlFilePath);
if (isStringified) {
suffix = stringify(suffix);
}
const endIndex = existingSourceText.indexOf(suffix, startIndex + 1);
if (endIndex === -1) {
return null;
}
const oldTemplate = existingSourceText.substring(startIndex, endIndex + suffix.length);
let newTemplate = getTemplateFormat(htmlFilePath, newTemplateContent);
if (isStringified) {
newTemplate = stringify(newTemplate);
}
let lastChange: string = null;
while (existingSourceText.indexOf(oldTemplate) > -1 && existingSourceText !== lastChange) {
lastChange = existingSourceText = existingSourceText.replace(oldTemplate, newTemplate);
}
return existingSourceText;
}
function stringify(str: string) {
str = JSON.stringify(str);
return str.substr(1, str.length - 2);
}
export function getTemplateFormat(htmlFilePath: string, content: string) {
// turn the template into one line and espcape single quotes
content = content.replace(/\r|\n/g, '\\n');
content = content.replace(/\'/g, '\\\'');
return `${getTemplatePrefix(htmlFilePath)}\'${content}\'${getTemplateSuffix(htmlFilePath)}`;
}
function getTemplatePrefix(htmlFilePath: string) {
return `template:/*ion-inline-start:"${resolve(htmlFilePath)}"*/`;
}
function getTemplateSuffix(htmlFilePath: string) {
return `/*ion-inline-end:"${resolve(htmlFilePath)}"*/`;
}
export function getTemplateMatch(str: string): TemplateUrlMatch {
const match = COMPONENT_REGEX.exec(str);
if (match) {
return {
start: match.index,
end: match.index + match[0].length,
component: match[0],
templateProperty: match[3],
templateUrl: match[5].trim()
};
}
return null;
}
const COMPONENT_REGEX = /Component\s*?\(\s*?(\{([\s\S]*?)(\s*templateUrl\s*:\s*(['"`])(.*?)(['"`])\s*?)([\s\S]*?)}\s*?)\)/m;
export interface TemplateUrlMatch {
start: number;
end: number;
component: string;
templateProperty: string;
templateUrl: string;
}