forked from 11ty/eleventy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserConfig.js
1338 lines (1121 loc) · 36.2 KB
/
UserConfig.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import chalk from "kleur";
import { DateTime } from "luxon";
import yaml from "js-yaml";
import matter from "gray-matter";
import debugUtil from "debug";
import { DeepCopy, TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import HtmlBasePlugin from "./Plugins/HtmlBasePlugin.js";
import RenderPlugin from "./Plugins/RenderPlugin.js";
import InputPathToUrlPlugin from "./Plugins/InputPathToUrl.js";
import isAsyncFunction from "./Util/IsAsyncFunction.js";
import objectFilter from "./Util/Objects/ObjectFilter.js";
import AsyncEventEmitter from "./Util/AsyncEventEmitter.js";
import EleventyCompatibility from "./Util/Compatibility.js";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
import BenchmarkManager from "./Benchmark/BenchmarkManager.js";
import JavaScriptFrontMatter from "./Engines/FrontMatter/JavaScript.js";
import { augmentFunction } from "./Engines/Util/ContextAugmenter.js";
const debug = debugUtil("Eleventy:UserConfig");
class UserConfigError extends EleventyBaseError {}
/**
* Eleventy’s user-land Configuration API
* @module 11ty/eleventy/UserConfig
*/
class UserConfig {
/** @type {boolean} */
#pluginExecution = false;
/** @type {boolean} */
#quietModeLocked = false;
/** @type {boolean} */
#dataDeepMergeModified = false;
/** @type {number|undefined} */
#uniqueId;
/** @type {number} */
#concurrency = 1;
// Before using os.availableParallelism(); see https://github.com/11ty/eleventy/issues/3596
constructor() {
// These are completely unnecessary lines to satisfy TypeScript
this.plugins = [];
this.templateFormatsAdded = [];
this.additionalWatchTargets = [];
this.watchTargetsConfigReset = new Set();
this.extensionMap = new Set();
this.dataExtensions = new Map();
this.urlTransforms = [];
this.customDateParsingCallbacks = new Set();
this.ignores = new Set();
this.events = new AsyncEventEmitter();
/** @type {object} */
this.directories = {};
/** @type {undefined} */
this.logger;
/** @type {string} */
this.dir;
/** @type {string} */
this.pathPrefix;
/** @type {object} */
this.errorReporting = {};
/** @type {object} */
this.templateHandling = {};
this.reset();
this.#uniqueId = Math.random();
}
// Internally used in TemplateContent for cache keys
_getUniqueId() {
return this.#uniqueId;
}
reset() {
debug("Resetting EleventyConfig to initial values.");
/** @type {AsyncEventEmitter} */
this.events = new AsyncEventEmitter();
/** @type {BenchmarkManager} */
this.benchmarkManager = new BenchmarkManager();
/** @type {object} */
this.benchmarks = {
/** @type {import('./Benchmark/BenchmarkGroup.js')} */
config: this.benchmarkManager.get("Configuration"),
/** @type {import('./Benchmark/BenchmarkGroup.js')} */
aggregate: this.benchmarkManager.get("Aggregate"),
};
/** @type {object} */
this.directoryAssignments = {};
/** @type {object} */
this.collections = {};
/** @type {object} */
this.precompiledCollections = {};
this.templateFormats = undefined;
this.templateFormatsAdded = [];
/** @type {object} */
this.universal = {
filters: {},
shortcodes: {},
pairedShortcodes: {},
};
/** @type {object} */
this.liquid = {
options: {},
tags: {},
filters: {},
shortcodes: {},
pairedShortcodes: {},
parameterParsing: "legacy", // or builtin
};
/** @type {object} */
this.nunjucks = {
// `dev: true` gives us better error messaging
environmentOptions: { dev: true },
precompiledTemplates: {},
filters: {},
asyncFilters: {},
tags: {},
globals: {},
shortcodes: {},
pairedShortcodes: {},
asyncShortcodes: {},
asyncPairedShortcodes: {},
};
/** @type {object} */
this.javascript = {
functions: {},
filters: {},
shortcodes: {},
pairedShortcodes: {},
};
this.markdownHighlighter = null;
/** @type {object} */
this.libraryOverrides = {};
/** @type {object} */
this.passthroughCopies = {};
this.passthroughCopiesHtmlRelative = new Set();
/** @type {object} */
this.layoutAliases = {};
this.layoutResolution = true; // extension-less layout files
/** @type {object} */
this.linters = {};
/** @type {object} */
this.transforms = {};
/** @type {object} */
this.preprocessors = {};
this.activeNamespace = "";
this.DateTime = DateTime;
this.dynamicPermalinks = true;
this.useGitIgnore = true;
let defaultIgnores = new Set();
defaultIgnores.add("**/node_modules/**");
defaultIgnores.add(".git/**");
this.ignores = new Set(defaultIgnores);
this.watchIgnores = new Set(defaultIgnores);
this.dataDeepMerge = true;
this.extensionMap = new Set();
/** @type {object} */
this.extensionConflictMap = {};
this.watchJavaScriptDependencies = true;
this.additionalWatchTargets = [];
this.watchTargetsConfigReset = new Set();
/** @type {object} */
this.serverOptions = {};
/** @type {object} */
this.globalData = {};
/** @type {object} */
this.chokidarConfig = {};
this.watchThrottleWaitTime = 0; //ms
// using Map to preserve insertion order
this.dataExtensions = new Map();
this.quietMode = false;
this.plugins = [];
this.useTemplateCache = true;
this.dataFilterSelectors = new Set();
/** @type {object} */
this.libraryAmendments = {};
this.serverPassthroughCopyBehavior = "copy"; // or "passthrough"
this.urlTransforms = [];
// Defaults in `defaultConfig.js`
this.dataFileSuffixesOverride = false;
this.dataFileDirBaseNameOverride = false;
/** @type {object} */
this.frontMatterParsingOptions = {
// Set a project-wide default.
// language: "yaml",
// Supplementary engines
engines: {
yaml: yaml.load.bind(yaml),
// Backwards compatible with `js` object front matter
// https://github.com/11ty/eleventy/issues/2819
javascript: JavaScriptFrontMatter,
// Needed for fallback behavior in the new `javascript` engine
// @ts-ignore
jsLegacy: matter.engines.javascript,
node: function () {
throw new Error(
"The `node` front matter type was a 3.0.0-alpha.x only feature, removed for stable release. Rename to `js` or `javascript` instead!",
);
},
},
};
/** @type {object} */
this.virtualTemplates = {};
this.freezeReservedData = true;
this.customDateParsingCallbacks = new Set();
/** @type {object} */
this.errorReporting = {};
/** @type {object} */
this.templateHandling = {};
// Before using os.availableParallelism(); see https://github.com/11ty/eleventy/issues/3596
this.#concurrency = 1;
}
// compatibleRange is optional in 2.0.0-beta.2
versionCheck(compatibleRange) {
let compat = new EleventyCompatibility(compatibleRange);
if (!compat.isCompatible()) {
throw new UserConfigError(compat.getErrorMessage());
}
}
/*
* Events
*/
// Duplicate event bindings are avoided with the `reset` method above.
// A new EventEmitter instance is created when the config is reset.
on(eventName, callback) {
return this.events.on(eventName, callback);
}
once(eventName, callback) {
return this.events.once(eventName, callback);
}
emit(eventName, ...args) {
return this.events.emit(eventName, ...args);
}
setEventEmitterMode(mode) {
this.events.setHandlerMode(mode);
}
/*
* Universal getters
*/
getFilter(name) {
// JavaScript functions are included here for backwards compatibility https://github.com/11ty/eleventy/issues/3365
return this.universal.filters[name] || this.javascript.functions[name];
}
getFilters(options = {}) {
if (options.type) {
return objectFilter(
this.universal.filters,
(entry) => entry.__eleventyInternal?.type === options.type,
);
}
return this.universal.filters;
}
getShortcode(name) {
return this.universal.shortcodes[name];
}
getShortcodes(options = {}) {
if (options.type) {
return objectFilter(
this.universal.shortcodes,
(entry) => entry.__eleventyInternal?.type === options.type,
);
}
return this.universal.shortcodes;
}
getPairedShortcode(name) {
return this.universal.pairedShortcodes[name];
}
getPairedShortcodes(options = {}) {
if (options.type) {
return objectFilter(
this.universal.pairedShortcodes,
(entry) => entry.__eleventyInternal?.type === options.type,
);
}
return this.universal.pairedShortcodes;
}
/*
* Private utilities
*/
#add(target, originalName, callback, options) {
let { description, functionName } = options;
if (typeof callback !== "function") {
throw new Error(`Invalid definition for "${originalName}" ${description}.`);
}
let name = this.getNamespacedName(originalName);
if (target[name]) {
debug(
chalk.yellow(`Warning, overwriting previous ${description} "%o" via \`%o(%o)\``),
name,
functionName,
originalName,
);
} else {
debug(`Adding new ${description} "%o" via \`%o(%o)\``, name, functionName, originalName);
}
target[name] = this.#decorateCallback(`"${name}" ${description}`, callback);
}
#decorateCallback(type, callback) {
return this.benchmarks.config.add(type, callback);
}
/*
* Markdown
*/
// This is a method for plugins, probably shouldn’t use this in projects.
// Projects should use `setLibrary` as documented here:
// https://github.com/11ty/eleventy/blob/master/docs/engines/markdown.md#use-your-own-options
addMarkdownHighlighter(highlightFn) {
this.markdownHighlighter = highlightFn;
}
/*
* Filters
*/
addLiquidFilter(name, callback) {
this.#add(this.liquid.filters, name, callback, {
description: "Liquid Filter",
functionName: "addLiquidFilter",
});
}
addNunjucksAsyncFilter(name, callback) {
this.#add(this.nunjucks.asyncFilters, name, callback, {
description: "Nunjucks Filter",
functionName: "addNunjucksAsyncFilter",
});
}
// Support the nunjucks style syntax for asynchronous filter add
addNunjucksFilter(name, callback, isAsync = false) {
if (isAsync) {
// namespacing happens downstream
this.addNunjucksAsyncFilter(name, callback);
} else {
this.#add(this.nunjucks.filters, name, callback, {
description: "Nunjucks Filter",
functionName: "addNunjucksFilter",
});
}
}
addJavaScriptFilter(name, callback) {
this.#add(this.javascript.filters, name, callback, {
description: "JavaScript Filter",
functionName: "addJavaScriptFilter",
});
// Backwards compat for a time before `addJavaScriptFilter` existed.
this.addJavaScriptFunction(name, callback);
}
addFilter(name, callback) {
// This method *requires* `async function` and will not work with `function` that returns a promise
if (isAsyncFunction(callback)) {
this.addAsyncFilter(name, callback);
return;
}
// namespacing happens downstream
this.#add(this.universal.filters, name, callback, {
description: "Universal Filter",
functionName: "addFilter",
});
this.addLiquidFilter(name, callback);
this.addJavaScriptFilter(name, callback);
this.addNunjucksFilter(
name,
/** @this {any} */
function (...args) {
// Note that `callback` is already a function as the `#add` method throws an error if not.
let ret = callback.call(this, ...args);
if (ret instanceof Promise) {
throw new Error(
`Nunjucks *is* async-friendly with \`addFilter("${name}", async function() {})\` but you need to supply an \`async function\`. You returned a promise from \`addFilter("${name}", function() {})\`. Alternatively, use the \`addAsyncFilter("${name}")\` configuration API method.`,
);
}
return ret;
},
);
}
// Liquid, Nunjucks, and JS only
addAsyncFilter(name, callback) {
// namespacing happens downstream
this.#add(this.universal.filters, name, callback, {
description: "Universal Filter",
functionName: "addAsyncFilter",
});
this.addLiquidFilter(name, callback);
this.addJavaScriptFilter(name, callback);
this.addNunjucksAsyncFilter(
name,
/** @this {any} */
async function (...args) {
let cb = args.pop();
// Note that `callback` is already a function as the `#add` method throws an error if not.
let ret = await callback.call(this, ...args);
cb(null, ret);
},
);
}
/*
* Shortcodes
*/
addShortcode(name, callback) {
// This method *requires* `async function` and will not work with `function` that returns a promise
if (isAsyncFunction(callback)) {
this.addAsyncShortcode(name, callback);
return;
}
this.#add(this.universal.shortcodes, name, callback, {
description: "Universal Shortcode",
functionName: "addShortcode",
});
this.addLiquidShortcode(name, callback);
this.addJavaScriptShortcode(name, callback);
this.addNunjucksShortcode(name, callback);
}
addAsyncShortcode(name, callback) {
this.#add(this.universal.shortcodes, name, callback, {
description: "Universal Shortcode",
functionName: "addAsyncShortcode",
});
// Related: #498
this.addNunjucksAsyncShortcode(name, callback);
this.addLiquidShortcode(name, callback);
this.addJavaScriptShortcode(name, callback);
}
addNunjucksAsyncShortcode(name, callback) {
this.#add(this.nunjucks.asyncShortcodes, name, callback, {
description: "Nunjucks Async Shortcode",
functionName: "addNunjucksAsyncShortcode",
});
}
addNunjucksShortcode(name, callback, isAsync = false) {
if (isAsync) {
this.addNunjucksAsyncShortcode(name, callback);
} else {
this.#add(this.nunjucks.shortcodes, name, callback, {
description: "Nunjucks Shortcode",
functionName: "addNunjucksShortcode",
});
}
}
addLiquidShortcode(name, callback) {
this.#add(this.liquid.shortcodes, name, callback, {
description: "Liquid Shortcode",
functionName: "addLiquidShortcode",
});
}
addPairedShortcode(name, callback) {
// This method *requires* `async function` and will not work with `function` that returns a promise
if (isAsyncFunction(callback)) {
this.addPairedAsyncShortcode(name, callback);
return;
}
this.#add(this.universal.pairedShortcodes, name, callback, {
description: "Universal Paired Shortcode",
functionName: "addPairedShortcode",
});
this.addPairedNunjucksShortcode(name, callback);
this.addPairedLiquidShortcode(name, callback);
this.addPairedJavaScriptShortcode(name, callback);
}
// Related: #498
addPairedAsyncShortcode(name, callback) {
this.#add(this.universal.pairedShortcodes, name, callback, {
description: "Universal Paired Async Shortcode",
functionName: "addPairedAsyncShortcode",
});
this.addPairedNunjucksAsyncShortcode(name, callback);
this.addPairedLiquidShortcode(name, callback);
this.addPairedJavaScriptShortcode(name, callback);
}
addPairedNunjucksAsyncShortcode(name, callback) {
this.#add(this.nunjucks.asyncPairedShortcodes, name, callback, {
description: "Nunjucks Async Paired Shortcode",
functionName: "addPairedNunjucksAsyncShortcode",
});
}
addPairedNunjucksShortcode(name, callback, isAsync = false) {
if (isAsync) {
this.addPairedNunjucksAsyncShortcode(name, callback);
} else {
this.#add(this.nunjucks.pairedShortcodes, name, callback, {
description: "Nunjucks Paired Shortcode",
functionName: "addPairedNunjucksShortcode",
});
}
}
addPairedLiquidShortcode(name, callback) {
this.#add(this.liquid.pairedShortcodes, name, callback, {
description: "Liquid Paired Shortcode",
functionName: "addPairedLiquidShortcode",
});
}
addJavaScriptShortcode(name, callback) {
this.#add(this.javascript.shortcodes, name, callback, {
description: "JavaScript Shortcode",
functionName: "addJavaScriptShortcode",
});
// Backwards compat for a time before `addJavaScriptShortcode` existed.
this.addJavaScriptFunction(name, callback);
}
addPairedJavaScriptShortcode(name, callback) {
this.#add(this.javascript.pairedShortcodes, name, callback, {
description: "JavaScript Paired Shortcode",
functionName: "addPairedJavaScriptShortcode",
});
// Backwards compat for a time before `addJavaScriptShortcode` existed.
this.addJavaScriptFunction(name, callback);
}
// Both Filters and shortcodes feed into this
addJavaScriptFunction(name, callback) {
this.#add(this.javascript.functions, name, callback, {
description: "JavaScript Function",
functionName: "addJavaScriptFunction",
});
}
/*
* Custom Tags
*/
// tagCallback: function(liquidEngine) { return { parse: …, render: … }} };
addLiquidTag(name, tagFn) {
if (typeof tagFn !== "function") {
throw new UserConfigError(
`EleventyConfig.addLiquidTag expects a callback function to be passed in for ${name}: addLiquidTag(name, function(liquidEngine) { return { parse: …, render: … } })`,
);
}
this.#add(this.liquid.tags, name, tagFn, {
description: "Liquid Custom Tag",
functionName: "addLiquidTag",
});
}
addNunjucksTag(name, tagFn) {
if (typeof tagFn !== "function") {
throw new UserConfigError(
`EleventyConfig.addNunjucksTag expects a callback function to be passed in for ${name}: addNunjucksTag(name, function(nunjucksEngine) {})`,
);
}
this.#add(this.nunjucks.tags, name, tagFn, {
description: "Nunjucks Custom Tag",
functionName: "addNunjucksTag",
});
}
/*
* Plugins
*/
// Internal method
_enablePluginExecution() {
this.#pluginExecution = true;
}
// Internal method
_disablePluginExecution() {
this.#pluginExecution = false;
}
/* Config is executed in two stages and plugins are the second stage—are we in the plugins stage? */
isPluginExecution() {
return this.#pluginExecution;
}
/**
* @typedef {function|Promise<function>|object} PluginDefinition
* @property {Function} [configFunction]
* @property {string} [eleventyPackage]
* @property {object} [eleventyPluginOptions={}]
* @property {boolean} [eleventyPluginOptions.unique]
*/
/**
* addPlugin: async friendly in 3.0
*
* @param {PluginDefinition} plugin
*/
addPlugin(plugin, options = {}) {
// First addPlugin of a unique plugin wins
if (plugin?.eleventyPluginOptions?.unique && this.hasPlugin(plugin)) {
debug("Skipping duplicate unique addPlugin for %o", this._getPluginName(plugin));
return;
}
if (this.isPluginExecution() || options?.immediate) {
// this might return a promise
return this._executePlugin(plugin, options);
} else {
this.plugins.push({
plugin,
options,
pluginNamespace: this.activeNamespace,
});
}
}
/** @param {string} name */
resolvePlugin(name) {
let filenameLookup = {
"@11ty/eleventy/html-base-plugin": HtmlBasePlugin,
"@11ty/eleventy/render-plugin": RenderPlugin,
"@11ty/eleventy/inputpath-to-url-plugin": InputPathToUrlPlugin,
// Async plugins:
// requires e.g. `await resolvePlugin("@11ty/eleventy/i18n-plugin")` to avoid preloading i18n dependencies.
// see https://github.com/11ty/eleventy-plugin-rss/issues/52
"@11ty/eleventy/i18n-plugin": "./Plugins/I18nPlugin.js",
};
if (!filenameLookup[name]) {
throw new Error(
`Invalid name "${name}" passed to resolvePlugin. Valid options: ${Object.keys(filenameLookup).join(", ")}`,
);
}
// Future improvement: add support for any npm package name?
if (typeof filenameLookup[name] === "string") {
// returns promise
return import(filenameLookup[name]).then((plugin) => plugin.default);
}
// return reference
return filenameLookup[name];
}
/** @param {string|PluginDefinition} plugin */
hasPlugin(plugin) {
let pluginName;
if (typeof plugin === "string") {
pluginName = plugin;
} else {
pluginName = this._getPluginName(plugin);
}
return this.plugins.some((entry) => this._getPluginName(entry.plugin) === pluginName);
}
// Using Function.name https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#examples
/** @param {PluginDefinition} plugin */
_getPluginName(plugin) {
if (plugin?.eleventyPackage) {
return plugin.eleventyPackage;
}
if (typeof plugin === "function") {
return plugin.name;
}
if (plugin?.configFunction && typeof plugin.configFunction === "function") {
return plugin.configFunction.name;
}
}
// Starting in 3.0 the plugin callback might be asynchronous!
_executePlugin(plugin, options) {
let name = this._getPluginName(plugin);
let ret;
debug(`Adding %o plugin`, name || "anonymous");
let pluginBenchmark = this.benchmarks.aggregate.get("Configuration addPlugin");
if (typeof plugin === "function") {
pluginBenchmark.before();
this.benchmarks.config;
let configFunction = plugin;
ret = configFunction(this, options);
pluginBenchmark.after();
} else if (plugin?.configFunction) {
pluginBenchmark.before();
if (options && typeof options.init === "function") {
// init is not yet async-friendly but it’s also barely used
options.init.call(this, plugin.initArguments || {});
}
ret = plugin.configFunction(this, options);
pluginBenchmark.after();
} else {
throw new UserConfigError(
"Invalid EleventyConfig.addPlugin signature. Should be a function or a valid Eleventy plugin object.",
);
}
return ret;
}
/** @param {string} name */
getNamespacedName(name) {
return this.activeNamespace + name;
}
async namespace(pluginNamespace, callback) {
let validNamespace = pluginNamespace && typeof pluginNamespace === "string";
if (validNamespace) {
this.activeNamespace = pluginNamespace || "";
}
await callback(this);
if (validNamespace) {
this.activeNamespace = "";
}
}
/**
* Adds a path to a file or directory to the list of pass-through copies
* which are copied as-is to the output.
*
* @param {string|object} fileOrDir The path to the file or directory that should
* be copied. OR an object where the key is the input glob and the property is the output directory
* @param {object} copyOptions options for recursive-copy.
* see https://www.npmjs.com/package/recursive-copy#arguments
* default options are defined in TemplatePassthrough copyOptionsDefault
* @returns {any} a reference to the `EleventyConfig` object.
*/
addPassthroughCopy(fileOrDir, copyOptions = {}) {
if (copyOptions.mode) {
if (copyOptions.mode !== "html-relative") {
throw new Error(
"Invalid `mode` option for `addPassthroughCopy`. Received: '" + copyOptions.mode + "'",
);
}
if (isPlainObject(fileOrDir)) {
throw new Error(
"mode: 'html-relative' does not yet support passthrough copy objects (input -> output mapping). Use a string glob or an Array of string globs.",
);
}
this.passthroughCopiesHtmlRelative?.add({
match: fileOrDir,
...copyOptions,
});
} else if (typeof fileOrDir === "string") {
this.passthroughCopies[fileOrDir] = { outputPath: true, copyOptions };
} else {
for (let [inputPath, outputPath] of Object.entries(fileOrDir)) {
this.passthroughCopies[inputPath] = { outputPath, copyOptions };
}
}
return this;
}
/*
* Template Formats
*/
_normalizeTemplateFormats() {
throw new Error("The internal _normalizeTemplateFormats() method was removed in Eleventy 3.0");
}
setTemplateFormats(templateFormats) {
this.templateFormats = templateFormats;
}
// additive, usually for plugins
addTemplateFormats(templateFormats) {
this.templateFormatsAdded.push(templateFormats);
}
/*
* Library Overrides and Options
*/
setLibrary(engineName, libraryInstance) {
if (engineName === "liquid" && Object.keys(this.liquid.options).length) {
debug(
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setLiquidOptions` via the config API. You’ll need to pass these options to the library yourself.",
);
} else if (engineName === "njk" && Object.keys(this.nunjucks.environmentOptions).length) {
debug(
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setNunjucksEnvironmentOptions` via the config API. You’ll need to pass these options to the library yourself.",
);
}
this.libraryOverrides[engineName.toLowerCase()] = libraryInstance;
}
/* These callbacks run on both libraryOverrides and default library instances */
amendLibrary(engineName, callback) {
let name = engineName.toLowerCase();
if (!this.libraryAmendments[name]) {
this.libraryAmendments[name] = [];
}
this.libraryAmendments[name].push(callback);
}
setLiquidOptions(options) {
this.liquid.options = options;
}
setLiquidParameterParsing(behavior) {
if (behavior !== "legacy" && behavior !== "builtin") {
throw new Error(
`Invalid argument passed to \`setLiquidParameterParsing\`. Expected one of "legacy" or "builtin".`,
);
}
this.liquid.parameterParsing = behavior;
}
setNunjucksEnvironmentOptions(options) {
this.nunjucks.environmentOptions = options;
}
setNunjucksPrecompiledTemplates(templates) {
this.nunjucks.precompiledTemplates = templates;
}
setDynamicPermalinks(enabled) {
this.dynamicPermalinks = !!enabled;
}
setUseGitIgnore(enabled) {
this.useGitIgnore = !!enabled;
}
setDataDeepMerge(deepMerge) {
this.#dataDeepMergeModified = true;
this.dataDeepMerge = !!deepMerge;
}
// Used by the Upgrade Helper Plugin
isDataDeepMergeModified() {
return this.#dataDeepMergeModified;
}
addWatchTarget(additionalWatchTargets, options = {}) {
// Reset the config when the target path changes
if (options.resetConfig) {
this.watchTargetsConfigReset.add(additionalWatchTargets);
}
this.additionalWatchTargets.push(additionalWatchTargets);
}
setWatchJavaScriptDependencies(watchEnabled) {
this.watchJavaScriptDependencies = !!watchEnabled;
}
setServerOptions(options = {}, override = false) {
if (override) {
this.serverOptions = options;
} else {
this.serverOptions = DeepCopy(this.serverOptions, options);
}
}
setBrowserSyncConfig() {
this._attemptedBrowserSyncUse = true;
debug(
"The `setBrowserSyncConfig` method was removed in Eleventy 2.0.0. Use `setServerOptions` with the new Eleventy development server or the `@11ty/eleventy-browser-sync` plugin moving forward.",
);
}
setChokidarConfig(options = {}) {
this.chokidarConfig = options;
}
setWatchThrottleWaitTime(time = 0) {
this.watchThrottleWaitTime = time;
}
// 3.0 change: this does a top level merge instead of reset.
setFrontMatterParsingOptions(options = {}) {
DeepCopy(this.frontMatterParsingOptions, options);
}
/* Internal method for CLI --quiet */
_setQuietModeOverride(quietMode) {
this.setQuietMode(quietMode);
this.#quietModeLocked = true;
}
setQuietMode(quietMode) {
if (this.#quietModeLocked) {
debug(
"Attempt to `setQuietMode(%o)` ignored, --quiet command line argument override in place.",
!!quietMode,
);
// override via CLI takes precedence
return;
}
this.quietMode = !!quietMode;
}
addExtension(fileExtension, options = {}) {
let extensions;
// Array support added in 2.0.0-canary.19
if (Array.isArray(fileExtension)) {
extensions = fileExtension;
} else {
// single string
extensions = [fileExtension];
}
for (let extension of extensions) {
if (this.extensionConflictMap[extension]) {
throw new Error(
`An attempt was made to override the "${extension}" template syntax twice (via the \`addExtension\` configuration API). A maximum of one override is currently supported.`,
);
}
this.extensionConflictMap[extension] = true;
/** @type {object} */
let extensionOptions = Object.assign(
{
// Might be overridden for aliasing in options.key
key: extension,
extension: extension,
},
options,
);
if (extensionOptions.key !== extensionOptions.extension) {
extensionOptions.aliasKey = extensionOptions.extension;