This repository has been archived by the owner on Dec 8, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpreprocess-embedded-templates.ts
260 lines (220 loc) · 6.29 KB
/
preprocess-embedded-templates.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
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
import MagicString from 'magic-string';
import path from 'path';
import parseStaticImports from 'parse-static-imports';
import lineColumn from 'line-column';
import { expect } from './debug';
import { parseTemplates, TemplateMatch } from './parse-templates';
interface PreprocessOptionsEager {
getTemplateLocals: GetTemplateLocals;
importIdentifier?: string;
importPath?: string;
templateTag?: string;
templateTagReplacement?: string;
relativePath: string;
includeSourceMaps: boolean;
includeTemplateTokens: boolean;
}
interface PreprocessOptionsLazy {
getTemplateLocalsRequirePath: string;
getTemplateLocalsExportPath: string;
importIdentifier?: string;
importPath?: string;
templateTag?: string;
templateTagReplacement?: string;
relativePath: string;
includeSourceMaps: boolean;
includeTemplateTokens: boolean;
}
type PreprocessOptions = PreprocessOptionsLazy | PreprocessOptionsEager;
interface PreprocessedOutput {
output: string;
replacements: Replacement[];
}
interface Replacement {
type: 'start' | 'end';
index: number;
oldLength: number;
newLength: number;
originalLine: number;
originalCol: number;
}
type GetTemplateLocals = (template: string) => string[];
function getMatchStartAndEnd(match: RegExpMatchArray) {
return {
start: expect(match.index, 'Expected regular expression match to have an index'),
end:
expect(match.index, 'Expected regular expression match to have an index') + match[0].length,
};
}
function findImportedName(
template: string,
importPath: string,
importIdentifier: string
): string | undefined {
for (const $import of parseStaticImports(template)) {
if ($import.moduleName === importPath) {
const match = $import.namedImports.find(({ name }) => name === importIdentifier);
return match?.alias || match?.name;
}
}
return undefined;
}
function replacementFrom(
template: string,
index: number,
oldLength: number,
newLength: number,
type: 'start' | 'end'
): Replacement {
const loc = expect(
lineColumn(template).fromIndex(index),
'BUG: expected to find a line/column based on index'
);
return {
type,
index,
oldLength,
newLength,
originalCol: loc.col,
originalLine: loc.line,
};
}
function loadGetTemplateLocals(path: string, exportPath: string): GetTemplateLocals {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const templateLocals = require(path);
let getTemplateLocals = templateLocals;
for (const segment of exportPath.split('.')) {
getTemplateLocals = getTemplateLocals[segment];
}
return getTemplateLocals;
}
function replaceMatch(
s: MagicString,
match: TemplateMatch,
startReplacement: string,
endReplacement: string,
template: string,
getTemplateLocals: GetTemplateLocals,
includeTemplateTokens: boolean
): Replacement[] {
const { start: openStart, end: openEnd } = getMatchStartAndEnd(match.start);
const { start: closeStart, end: closeEnd } = getMatchStartAndEnd(match.end);
let options = '';
if (includeTemplateTokens) {
const tokensString = getTemplateLocals(template.slice(openEnd, closeStart))
.filter((local: string) => local.match(/^[$A-Z_][0-9A-Z_$]*$/i))
.join(',');
if (tokensString.length > 0) {
options = `, { scope() { return {${tokensString}}; } }`;
}
}
const newStart = `${startReplacement}\``;
const newEnd = `\`${options}${endReplacement}`;
s.overwrite(openStart, openEnd, newStart);
s.overwrite(closeStart, closeEnd, newEnd);
return [
replacementFrom(template, openStart, openEnd - openStart, newStart.length, 'start'),
replacementFrom(template, closeStart, closeEnd - closeStart, newEnd.length, 'end'),
];
}
/**
* Preprocesses all embedded templates within a JavaScript or TypeScript file.
* This function replaces all embedded templates that match our template syntax
* with valid, parseable JS. Optionally, it can also include a source map, and
* it can also include all possible values used within the template.
*
* Input:
*
* <template><MyComponent/><template>
*
* Output:
*
* [GLIMMER_TEMPLATE(`<MyComponent/>`, { scope() { return {MyComponent}; } })];
*
* It can also be used with template literals to provide the in scope values:
*
* Input:
*
* hbs`<MyComponent/>`;
*
* Output
*
* hbs(`<MyComponent/>`, { scope() { return {MyComponent}; } });
*/
export default function preprocessEmbeddedTemplates(
template: string,
options: PreprocessOptions
): PreprocessedOutput {
let getTemplateLocals: GetTemplateLocals;
const {
importPath,
templateTag,
templateTagReplacement,
includeSourceMaps,
includeTemplateTokens,
relativePath,
} = options;
let { importIdentifier } = options;
if ('getTemplateLocals' in options) {
getTemplateLocals = options.getTemplateLocals;
} else {
getTemplateLocals = loadGetTemplateLocals(
options.getTemplateLocalsRequirePath,
options.getTemplateLocalsExportPath
);
}
if (importPath && importIdentifier) {
importIdentifier = findImportedName(template, importPath, importIdentifier);
if (!importIdentifier) {
return {
output: template,
replacements: [],
};
}
}
const matches = parseTemplates(template, relativePath, templateTag);
const replacements: Replacement[] = [];
const s = new MagicString(template);
for (const match of matches) {
if (match.type === 'template-literal' && match.tagName === importIdentifier) {
replacements.push(
...replaceMatch(
s,
match,
`${match.tagName}(`,
')',
template,
getTemplateLocals,
includeTemplateTokens
)
);
} else if (match.type === 'template-tag') {
replacements.push(
...replaceMatch(
s,
match,
`[${templateTagReplacement}(`,
')]',
template,
getTemplateLocals,
includeTemplateTokens
)
);
}
}
let output = s.toString();
if (includeSourceMaps) {
const { dir, name } = path.parse(relativePath);
const map = s.generateMap({
file: `${dir}/${name}.js`,
source: relativePath,
includeContent: true,
hires: true,
});
output += `\n//# sourceMappingURL=${map.toUrl()}`;
}
return {
output,
replacements,
};
}