-
-
Notifications
You must be signed in to change notification settings - Fork 493
/
TemplateConfig.js
550 lines (460 loc) · 14.4 KB
/
TemplateConfig.js
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import fs from "node:fs";
import chalk from "kleur";
import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import debugUtil from "debug";
import { EleventyImportRaw, EleventyImportRawFromEleventy } from "./Util/Require.js";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
import UserConfig from "./UserConfig.js";
import GlobalDependencyMap from "./GlobalDependencyMap.js";
import ExistsCache from "./Util/ExistsCache.js";
import eventBus from "./EventBus.js";
import ProjectTemplateFormats from "./Util/ProjectTemplateFormats.js";
const debug = debugUtil("Eleventy:TemplateConfig");
const debugDev = debugUtil("Dev:Eleventy:TemplateConfig");
/**
* @module 11ty/eleventy/TemplateConfig
*/
/**
* Config as used by the template.
* @typedef {object} module:11ty/eleventy/TemplateConfig~TemplateConfig~config
* @property {String} [pathPrefix] - The path prefix.
*/
/**
* Errors in eleventy config.
* @ignore
*/
class EleventyConfigError extends EleventyBaseError {}
/**
* Errors in eleventy plugins.
* @ignore
*/
class EleventyPluginError extends EleventyBaseError {}
/**
* Config for a template.
* @ignore
* @param {{}} customRootConfig - tbd.
* @param {String} projectConfigPath - Path to local project config.
*/
class TemplateConfig {
#templateFormats;
#runMode;
#configManuallyDefined = false;
/** @type {UserConfig} */
#userConfig = new UserConfig();
constructor(customRootConfig, projectConfigPath) {
/** @type {object} */
this.overrides = {};
/**
* @type {String}
* @description Path to local project config.
* @default .eleventy.js
*/
if (projectConfigPath !== undefined) {
this.#configManuallyDefined = true;
if (!projectConfigPath) {
// falsy skips config files
this.projectConfigPaths = [];
} else {
this.projectConfigPaths = [projectConfigPath];
}
} else {
this.projectConfigPaths = [
".eleventy.js",
"eleventy.config.js",
"eleventy.config.mjs",
"eleventy.config.cjs",
];
}
if (customRootConfig) {
/**
* @type {object}
* @description Custom root config.
*/
this.customRootConfig = customRootConfig;
debug("Warning: Using custom root config!");
} else {
this.customRootConfig = null;
}
this.hasConfigMerged = false;
this.isEsm = false;
}
get userConfig() {
return this.#userConfig;
}
get aggregateBenchmark() {
return this.userConfig.benchmarks.aggregate;
}
/* Setter for Logger */
setLogger(logger) {
this.logger = logger;
this.userConfig.logger = this.logger;
}
/* Setter for Directories instance */
setDirectories(directories) {
this.directories = directories;
this.userConfig.directories = directories.getUserspaceInstance();
}
/* Setter for TemplateFormats instance */
setTemplateFormats(templateFormats) {
this.#templateFormats = templateFormats;
}
get templateFormats() {
if (!this.#templateFormats) {
this.#templateFormats = new ProjectTemplateFormats();
}
return this.#templateFormats;
}
/* Backwards compat */
get inputDir() {
return this.directories.input;
}
setRunMode(runMode) {
this.#runMode = runMode;
}
shouldSpiderJavaScriptDependencies() {
// not for a standard build
return (
(this.#runMode === "watch" || this.#runMode === "serve") &&
this.userConfig.watchJavaScriptDependencies
);
}
/**
* Normalises local project config file path.
*
* @method
* @returns {String|undefined} - The normalised local project config file path.
*/
getLocalProjectConfigFile() {
let configFiles = this.getLocalProjectConfigFiles();
// Add the configFiles[0] in case of a test, where no file exists on the file system
let configFile = configFiles.find((path) => path && fs.existsSync(path)) || configFiles[0];
if (configFile) {
return configFile;
}
}
getLocalProjectConfigFiles() {
if (this.projectConfigPaths?.length > 0) {
return TemplatePath.addLeadingDotSlashArray(this.projectConfigPaths.filter((path) => path));
}
return [];
}
setProjectUsingEsm(isEsmProject) {
this.isEsm = !!isEsmProject;
this.usesGraph.setIsEsm(isEsmProject);
}
getIsProjectUsingEsm() {
return this.isEsm;
}
/**
* Resets the configuration.
*/
async reset() {
debugDev("Resetting configuration: TemplateConfig and UserConfig.");
this.userConfig.reset();
// await this.initializeRootConfig();
await this.forceReloadConfig();
this.usesGraph.reset();
// Clear the compile cache
eventBus.emit("eleventy.compileCacheReset");
}
/**
* Resets the configuration while in watch mode.
*
* @todo Add implementation.
*/
resetOnWatch() {
// nothing yet
}
hasInitialized() {
return this.hasConfigMerged;
}
/**
* Async-friendly init method
*/
async init(overrides) {
await this.initializeRootConfig();
if (overrides) {
this.appendToRootConfig(overrides);
}
this.config = await this.mergeConfig();
this.hasConfigMerged = true;
}
/**
* Force a reload of the configuration object.
*/
async forceReloadConfig() {
this.hasConfigMerged = false;
await this.init();
}
/**
* Returns the config object.
*
* @returns {{}} - The config object.
*/
getConfig() {
if (!this.hasConfigMerged) {
throw new Error("Invalid call to .getConfig(). Needs an .init() first.");
}
return this.config;
}
/**
* Overwrites the config path.
*
* @param {String} path - The new config path.
*/
async setProjectConfigPath(path) {
this.#configManuallyDefined = true;
if (path !== undefined) {
this.projectConfigPaths = [path];
} else {
this.projectConfigPaths = [];
}
if (this.hasConfigMerged) {
// merge it again
debugDev("Merging in getConfig again after setting the local project config path.");
await this.forceReloadConfig();
}
}
/**
* Overwrites the path prefix.
*
* @param {String} pathPrefix - The new path prefix.
*/
setPathPrefix(pathPrefix) {
if (pathPrefix && pathPrefix !== "/") {
debug("Setting pathPrefix to %o", pathPrefix);
this.overrides.pathPrefix = pathPrefix;
}
}
/**
* Gets the current path prefix denoting the root folder the output will be deployed to
*
* @returns {String} - The path prefix string
*/
getPathPrefix() {
if (this.overrides.pathPrefix) {
return this.overrides.pathPrefix;
}
if (!this.hasConfigMerged) {
throw new Error("Config has not yet merged. Needs `init()`.");
}
return this.config?.pathPrefix;
}
/**
* Bootstraps the config object.
*/
async initializeRootConfig() {
this.rootConfig = this.customRootConfig;
if (!this.rootConfig) {
let { default: cfg } = await EleventyImportRawFromEleventy("./src/defaultConfig.js");
this.rootConfig = cfg;
}
if (typeof this.rootConfig === "function") {
// Not yet using async in defaultConfig.js
this.rootConfig = this.rootConfig.call(this, this.userConfig);
}
debug("Default Eleventy config %o", this.rootConfig);
}
/*
* Add additional overrides to the root config object, used for testing
*
* @param {object} - a subset of the return Object from the user’s config file.
*/
appendToRootConfig(obj) {
Object.assign(this.rootConfig, obj);
}
/*
* Process the userland plugins from the Config
*
* @param {object} - the return Object from the user’s config file.
*/
async processPlugins({ dir, pathPrefix }) {
this.userConfig.dir = dir;
this.userConfig.pathPrefix = pathPrefix;
// for Nested addPlugin calls, Issue #1925
this.userConfig._enablePluginExecution();
let storedActiveNamespace = this.userConfig.activeNamespace;
for (let { plugin, options, pluginNamespace } of this.userConfig.plugins) {
try {
this.userConfig.activeNamespace = pluginNamespace;
await this.userConfig._executePlugin(plugin, options);
} catch (e) {
let name = this.userConfig._getPluginName(plugin);
let namespaces = [storedActiveNamespace, pluginNamespace].filter((entry) => !!entry);
let namespaceStr = "";
if (namespaces.length) {
namespaceStr = ` (namespace: ${namespaces.join(".")})`;
}
throw new EleventyPluginError(
`Error processing ${name ? `the \`${name}\`` : "a"} plugin${namespaceStr}`,
e,
);
}
}
this.userConfig.activeNamespace = storedActiveNamespace;
this.userConfig._disablePluginExecution();
}
/**
* Fetches and executes the local configuration file
*
* @returns {Promise<object>} merged - The merged config file object.
*/
async requireLocalConfigFile() {
let localConfig = {};
let exportedConfig = {};
let path = this.projectConfigPaths.filter((path) => path).find((path) => fs.existsSync(path));
if (this.projectConfigPaths.length > 0 && this.#configManuallyDefined && !path) {
throw new EleventyConfigError(
"A configuration file was specified but not found: " + this.projectConfigPaths.join(", "),
);
}
debug(`Merging default config with ${path}`);
if (path) {
try {
let { default: configDefaultReturn, config: exportedConfigObject } =
await EleventyImportRaw(path, this.isEsm ? "esm" : "cjs");
exportedConfig = exportedConfigObject || {};
if (this.directories && Object.keys(exportedConfigObject?.dir || {}).length > 0) {
debug(
"Setting directories via `config.dir` export from config file: %o",
exportedConfigObject.dir,
);
this.directories.setViaConfigObject(exportedConfigObject.dir);
}
if (typeof configDefaultReturn === "function") {
localConfig = await configDefaultReturn(this.userConfig);
} else {
localConfig = configDefaultReturn;
}
// Removed a check for `filters` in 3.0.0-alpha.6 (now using addTransform instead) https://v3.11ty.dev/docs/config/#transforms
} catch (err) {
let isModuleError =
err instanceof Error && (err?.message || "").includes("Cannot find module");
// TODO the error message here is bad and I feel bad (needs more accurate info)
return Promise.reject(
new EleventyConfigError(
`Error in your Eleventy config file '${path}'.` +
(isModuleError ? chalk.cyan(" You may need to run `npm install`.") : ""),
err,
),
);
}
} else {
debug(
"Project config file not found (not an error—skipping). Looked in: %o",
this.projectConfigPaths,
);
}
return {
localConfig,
exportedConfig,
};
}
/**
* Merges different config files together.
*
* @returns {Promise<object>} merged - The merged config file.
*/
async mergeConfig() {
let { localConfig, exportedConfig } = await this.requireLocalConfigFile();
// Merge `export const config = {}` with `return {}` in config callback
if (isPlainObject(exportedConfig)) {
localConfig = Merge(localConfig || {}, exportedConfig);
}
if (this.directories) {
if (Object.keys(this.userConfig.directoryAssignments || {}).length > 0) {
debug(
"Setting directories via set*Directory configuration APIs %o",
this.userConfig.directoryAssignments,
);
this.directories.setViaConfigObject(this.userConfig.directoryAssignments);
}
if (localConfig && Object.keys(localConfig?.dir || {}).length > 0) {
debug(
"Setting directories via `dir` object return from configuration file: %o",
localConfig.dir,
);
this.directories.setViaConfigObject(localConfig.dir);
}
}
// `templateFormats` is an override via `setTemplateFormats`
if (this.userConfig?.templateFormats) {
this.templateFormats.setViaConfig(this.userConfig.templateFormats);
} else if (localConfig?.templateFormats || this.rootConfig?.templateFormats) {
// Local project config or defaultConfig.js
this.templateFormats.setViaConfig(
localConfig.templateFormats || this.rootConfig?.templateFormats,
);
}
// `templateFormatsAdded` is additive via `addTemplateFormats`
if (this.userConfig?.templateFormatsAdded) {
this.templateFormats.addViaConfig(this.userConfig.templateFormatsAdded);
}
let mergedConfig = Merge({}, this.rootConfig, localConfig);
// Setup a few properties for plugins:
// Set frozen templateFormats
mergedConfig.templateFormats = Object.freeze(this.templateFormats.getTemplateFormats());
// Setup pathPrefix set via command line for plugin consumption
if (this.overrides.pathPrefix) {
mergedConfig.pathPrefix = this.overrides.pathPrefix;
}
// Returning a falsy value (e.g. "") from user config should reset to the default value.
if (!mergedConfig.pathPrefix) {
mergedConfig.pathPrefix = this.rootConfig.pathPrefix;
}
// This is not set in UserConfig.js so that getters aren’t converted to strings
// We want to error if someone attempts to use a setter there.
if (this.directories) {
mergedConfig.directories = this.directories.getUserspaceInstance();
}
// Delay processing plugins until after the result of localConfig is returned
// But BEFORE the rest of the config options are merged
// this way we can pass directories and other template information to plugins
await this.userConfig.events.emit("eleventy.beforeConfig", this.userConfig);
let pluginsBench = this.aggregateBenchmark.get("Processing plugins in config");
pluginsBench.before();
await this.processPlugins(mergedConfig);
pluginsBench.after();
// Template formats added via plugins
if (this.userConfig?.templateFormatsAdded) {
this.templateFormats.addViaConfig(this.userConfig.templateFormatsAdded);
mergedConfig.templateFormats = Object.freeze(this.templateFormats.getTemplateFormats());
}
let eleventyConfigApiMergingObject = this.userConfig.getMergingConfigObject();
if ("templateFormats" in eleventyConfigApiMergingObject) {
throw new Error(
"Internal error: templateFormats should not return from `getMergingConfigObject`",
);
}
// Overrides are only used by pathPrefix
debug("Configuration overrides: %o", this.overrides);
Merge(mergedConfig, eleventyConfigApiMergingObject, this.overrides);
debug("Current configuration: %o", mergedConfig);
// Add to the merged config too
mergedConfig.uses = this.usesGraph;
// this is used for the layouts event
this.usesGraph.setConfig(mergedConfig);
return mergedConfig;
}
get usesGraph() {
if (!this._usesGraph) {
this._usesGraph = new GlobalDependencyMap();
this._usesGraph.setIsEsm(this.isEsm);
this._usesGraph.setTemplateConfig(this);
}
return this._usesGraph;
}
get uses() {
if (!this.usesGraph) {
throw new Error("The Eleventy Global Dependency Graph has not yet been initialized.");
}
return this.usesGraph;
}
get existsCache() {
if (!this._existsCache) {
this._existsCache = new ExistsCache();
}
return this._existsCache;
}
}
export default TemplateConfig;