summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Engines/Custom.js
blob: 17a0da143ef5b2b0c8d40af2b1e5ad502ef3f8c2 (plain)
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
import TemplateEngine from "./TemplateEngine.js";
import getJavaScriptData from "../Util/GetJavaScriptData.js";

export default class CustomEngine extends TemplateEngine {
	constructor(name, eleventyConfig) {
		super(name, eleventyConfig);

		this.entry = this.getExtensionMapEntry();
		this.needsInit = "init" in this.entry && typeof this.entry.init === "function";

		this.setDefaultEngine(undefined);
	}

	getExtensionMapEntry() {
		if ("extensionMap" in this.config) {
			let name = this.name.toLowerCase();
			// Iterates over only the user config `addExtension` entries
			for (let entry of this.config.extensionMap) {
				let entryKey = (entry.aliasKey || entry.key || "").toLowerCase();
				if (entryKey === name) {
					return entry;
				}
			}
		}

		throw Error(
			`Could not find a custom extension for ${this.name}. Did you add it to your config file?`,
		);
	}

	setDefaultEngine(defaultEngine) {
		this._defaultEngine = defaultEngine;
	}

	get cacheable() {
		// Enable cacheability for this template
		if (this.entry?.compileOptions?.cache !== undefined) {
			return this.entry.compileOptions.cache;
		} else if (this.needsToReadFileContents()) {
			return true;
		} else if (this._defaultEngine?.cacheable !== undefined) {
			return this._defaultEngine.cacheable;
		}

		return super.cacheable;
	}

	async getInstanceFromInputPath(inputPath) {
		if (
			"getInstanceFromInputPath" in this.entry &&
			typeof this.entry.getInstanceFromInputPath === "function"
		) {
			// returns Promise
			return this.entry.getInstanceFromInputPath(inputPath);
		}

		// aliased upstream type
		if (
			this._defaultEngine &&
			"getInstanceFromInputPath" in this._defaultEngine &&
			typeof this._defaultEngine.getInstanceFromInputPath === "function"
		) {
			// returns Promise
			return this._defaultEngine.getInstanceFromInputPath(inputPath);
		}

		return false;
	}

	/**
	 * Whether to use the module loader directly
	 *
	 * @override
	 */
	useJavaScriptImport() {
		if ("useJavaScriptImport" in this.entry) {
			return this.entry.useJavaScriptImport;
		}

		if (
			this._defaultEngine &&
			"useJavaScriptImport" in this._defaultEngine &&
			typeof this._defaultEngine.useJavaScriptImport === "function"
		) {
			return this._defaultEngine.useJavaScriptImport();
		}

		return false;
	}

	/**
	 * @override
	 */
	needsToReadFileContents() {
		if ("read" in this.entry) {
			return this.entry.read;
		}

		// Handle aliases to `11ty.js` templates, avoid reading files in the alias, see #2279
		// Here, we are short circuiting fallback to defaultRenderer, does not account for compile
		// functions that call defaultRenderer explicitly
		if (this._defaultEngine && "needsToReadFileContents" in this._defaultEngine) {
			return this._defaultEngine.needsToReadFileContents();
		}

		return true;
	}

	// If we init from multiple places, wait for the first init to finish before continuing on.
	async _runningInit() {
		if (this.needsInit) {
			if (!this._initing) {
				this._initBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Init`);
				this._initBench.before();
				this._initing = this.entry.init.bind({
					config: this.config,
					bench: this.benchmarks.aggregate,
				})();
			}
			await this._initing;
			this.needsInit = false;

			if (this._initBench) {
				this._initBench.after();
				this._initBench = undefined;
			}
		}
	}

	async getExtraDataFromFile(inputPath) {
		if (this.entry.getData === false) {
			return;
		}

		if (!("getData" in this.entry)) {
			// Handle aliases to `11ty.js` templates, use upstream default engine data fetch, see #2279
			if (this._defaultEngine && "getExtraDataFromFile" in this._defaultEngine) {
				return this._defaultEngine.getExtraDataFromFile(inputPath);
			}

			return;
		}

		await this._runningInit();

		if (typeof this.entry.getData === "function") {
			let dataBench = this.benchmarks.aggregate.get(
				`Engine (${this.name}) Get Data From File (Function)`,
			);
			dataBench.before();
			let data = this.entry.getData(inputPath);
			dataBench.after();
			return data;
		}

		let keys = new Set();
		if (this.entry.getData === true) {
			keys.add("data");
		} else if (Array.isArray(this.entry.getData)) {
			for (let key of this.entry.getData) {
				keys.add(key);
			}
		}

		let dataBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Get Data From File`);
		dataBench.before();

		let inst = await this.getInstanceFromInputPath(inputPath);

		if (inst === false) {
			dataBench.after();

			return Promise.reject(
				new Error(
					`\`getInstanceFromInputPath\` callback missing from '${this.name}' template engine plugin. It is required when \`getData\` is in use. You can set \`getData: false\` to opt-out of this.`,
				),
			);
		}

		// override keys set at the plugin level in the individual template
		if (inst.eleventyDataKey) {
			keys = new Set(inst.eleventyDataKey);
		}

		let mixins;
		if (this.config) {
			// Object.assign usage: see TemplateRenderCustomTest.js: `JavaScript functions should not be mutable but not *that* mutable`
			mixins = Object.assign({}, this.config.javascriptFunctions);
		}

		let promises = [];
		for (let key of keys) {
			promises.push(
				getJavaScriptData(inst, inputPath, key, {
					mixins,
					isObjectRequired: key === "data",
				}),
			);
		}

		let results = await Promise.all(promises);
		let data = {};
		for (let result of results) {
			Object.assign(data, result);
		}
		dataBench.after();

		return data;
	}

	async compile(str, inputPath, ...args) {
		await this._runningInit();
		let defaultCompilationFn;
		if (this._defaultEngine) {
			defaultCompilationFn = async (data) => {
				const renderFn = await this._defaultEngine.compile(str, inputPath, ...args);
				return renderFn(data);
			};
		}

		// Fall back to default compiler if the user does not provide their own
		if (!this.entry.compile) {
			if (defaultCompilationFn) {
				return defaultCompilationFn;
			} else {
				throw new Error(
					`Missing \`compile\` property for custom template syntax definition eleventyConfig.addExtension("${this.name}"). This is not necessary when aliasing to an existing template syntax.`,
				);
			}
		}

		// TODO generalize this (look at JavaScript.js)
		let compiledFn = this.entry.compile.bind({
			config: this.config,
			addDependencies: (from, toArray = []) => {
				this.config.uses.addDependency(from, toArray);
			},
			defaultRenderer: defaultCompilationFn, // bind defaultRenderer to compile function
		})(str, inputPath);

		// Support `undefined` to skip compile/render
		if (compiledFn) {
			// Bind defaultRenderer to render function
			if ("then" in compiledFn && typeof compiledFn.then === "function") {
				// Promise, wait to bind
				return compiledFn.then((fn) => {
					if (typeof fn === "function") {
						return fn.bind({
							defaultRenderer: defaultCompilationFn,
						});
					}
					return fn;
				});
			} else if ("bind" in compiledFn && typeof compiledFn.bind === "function") {
				return compiledFn.bind({
					defaultRenderer: defaultCompilationFn,
				});
			}
		}

		return compiledFn;
	}

	get defaultTemplateFileExtension() {
		return this.entry.outputFileExtension ?? "html";
	}

	// Whether or not to wrap in Eleventy layouts
	useLayouts() {
		// TODO future change fallback to `this.defaultTemplateFileExtension === "html"`
		return this.entry.useLayouts ?? true;
	}

	hasDependencies(inputPath) {
		if (this.config.uses.getDependencies(inputPath) === false) {
			return false;
		}
		return true;
	}

	isFileRelevantTo(inputPath, comparisonFile, includeLayouts) {
		return this.config.uses.isFileRelevantTo(inputPath, comparisonFile, includeLayouts);
	}

	getCompileCacheKey(str, inputPath) {
		let lastModifiedFile = this.eleventyConfig.getPreviousBuildModifiedFile();
		// Return this separately so we know whether or not to use the cached version
		// but still return a key to cache this new render for next time
		let isRelevant = this.isFileRelevantTo(inputPath, lastModifiedFile, false);
		let useCache = !isRelevant;

		if (this.entry.compileOptions && "getCacheKey" in this.entry.compileOptions) {
			if (typeof this.entry.compileOptions.getCacheKey !== "function") {
				throw new Error(
					`\`compileOptions.getCacheKey\` must be a function in addExtension for the ${this.name} type`,
				);
			}

			return {
				useCache,
				key: this.entry.compileOptions.getCacheKey(str, inputPath),
			};
		}

		let { key } = super.getCompileCacheKey(str, inputPath);
		return {
			useCache,
			key,
		};
	}

	permalinkNeedsCompilation(/*str*/) {
		if (this.entry.compileOptions && "permalink" in this.entry.compileOptions) {
			let p = this.entry.compileOptions.permalink;
			if (p === "raw") {
				return false;
			}

			// permalink: false is aliased to permalink: () => false
			if (p === false) {
				return () => false;
			}

			return this.entry.compileOptions.permalink;
		}

		// Breaking: default changed from `true` to `false` in 3.0.0-alpha.13
		// Note: `false` is the same as "raw" here.
		return false;
	}

	static shouldSpiderJavaScriptDependencies(entry) {
		if (entry.compileOptions && "spiderJavaScriptDependencies" in entry.compileOptions) {
			return entry.compileOptions.spiderJavaScriptDependencies;
		}

		return false;
	}
}