-
-
Notifications
You must be signed in to change notification settings - Fork 518
/
Copy pathTemplateMap.js
671 lines (575 loc) · 18.8 KB
/
TemplateMap.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
const DependencyGraph = require("dependency-graph").DepGraph;
const { isPlainObject } = require("@11ty/eleventy-utils");
const TemplateCollection = require("./TemplateCollection");
const EleventyErrorUtil = require("./EleventyErrorUtil");
const UsingCircularTemplateContentReferenceError = require("./Errors/UsingCircularTemplateContentReferenceError");
const debug = require("debug")("Eleventy:TemplateMap");
const debugDev = require("debug")("Dev:Eleventy:TemplateMap");
const getPaginationDataKey = require("./Util/GetPaginationDataKey");
const EleventyBaseError = require("./EleventyBaseError");
class TemplateMapConfigError extends EleventyBaseError {}
class DuplicatePermalinkOutputError extends EleventyBaseError {
get removeDuplicateErrorStringFromOutput() {
return true;
}
}
class TemplateMap {
constructor(eleventyConfig) {
if (!eleventyConfig) {
throw new TemplateMapConfigError("Missing config argument.");
}
this.eleventyConfig = eleventyConfig;
this.map = [];
this.collectionsData = null;
this.cached = false;
this.configCollections = null;
this.verboseOutput = true;
this.collection = new TemplateCollection();
}
set userConfig(config) {
this._userConfig = config;
}
get userConfig() {
if (!this._userConfig) {
// TODO use this.config for this, need to add collections to mergable props in userconfig
this._userConfig = this.eleventyConfig.userConfig;
}
return this._userConfig;
}
get config() {
if (!this._config) {
this._config = this.eleventyConfig.getConfig();
}
return this._config;
}
get tagPrefix() {
return "___TAG___";
}
async add(template) {
// This is where the data is first generated for the template
let data = await template.getData();
for (let map of await template.getTemplateMapEntries(data)) {
this.map.push(map);
}
}
getMap() {
return this.map;
}
getTagTarget(str) {
if (str.startsWith("collections.")) {
return str.slice("collections.".length);
}
}
/* ---
* pagination:
* data: collections
* ---
*/
isPaginationOverAllCollections(entry) {
if (entry.data.pagination && entry.data.pagination.data) {
const key = getPaginationDataKey(entry.data);
return key === "collections" || key === "collections.all";
}
}
getPaginationTagTarget(entry) {
if (entry.data.pagination && entry.data.pagination.data) {
return this.getTagTarget(getPaginationDataKey(entry.data));
}
}
getMappedDependencies() {
let graph = new DependencyGraph();
let tagPrefix = this.tagPrefix;
graph.addNode(tagPrefix + "all");
for (let entry of this.map) {
if (this.isPaginationOverAllCollections(entry)) {
continue;
}
// using Pagination (but not targeting a user config collection)
let paginationTagTarget = this.getPaginationTagTarget(entry);
if (paginationTagTarget) {
if (this.isUserConfigCollectionName(paginationTagTarget)) {
// delay this one to the second stage
continue;
} else {
// using pagination but over a tagged collection
graph.addNode(entry.inputPath);
if (!graph.hasNode(tagPrefix + paginationTagTarget)) {
graph.addNode(tagPrefix + paginationTagTarget);
}
graph.addDependency(entry.inputPath, tagPrefix + paginationTagTarget);
}
} else {
// not using pagination
graph.addNode(entry.inputPath);
}
if (!entry.data.eleventyExcludeFromCollections) {
// collections.all
graph.addDependency(tagPrefix + "all", entry.inputPath);
if (entry.data.tags) {
for (let tag of entry.data.tags) {
let tagWithPrefix = tagPrefix + tag;
if (!graph.hasNode(tagWithPrefix)) {
graph.addNode(tagWithPrefix);
}
// collections.tagName
// Dependency from tag to inputPath
graph.addDependency(tagWithPrefix, entry.inputPath);
}
}
}
}
return graph.overallOrder();
}
getDelayedMappedDependencies() {
let graph = new DependencyGraph();
let tagPrefix = this.tagPrefix;
graph.addNode(tagPrefix + "all");
let userConfigCollections = this.getUserConfigCollectionNames();
// Add tags from named user config collections
for (let tag of userConfigCollections) {
graph.addNode(tagPrefix + tag);
// graph.addDependency( tagPrefix + tag, tagPrefix + "all" );
}
for (let entry of this.map) {
if (this.isPaginationOverAllCollections(entry)) {
continue;
}
let paginationTagTarget = this.getPaginationTagTarget(entry);
if (
paginationTagTarget &&
this.isUserConfigCollectionName(paginationTagTarget)
) {
if (!graph.hasNode(entry.inputPath)) {
graph.addNode(entry.inputPath);
}
graph.addDependency(entry.inputPath, tagPrefix + paginationTagTarget);
if (!entry.data.eleventyExcludeFromCollections) {
// collections.all
graph.addDependency(tagPrefix + "all", entry.inputPath);
if (entry.data.tags) {
for (let tag of entry.data.tags) {
let tagWithPrefix = tagPrefix + tag;
if (!graph.hasNode(tagWithPrefix)) {
graph.addNode(tagWithPrefix);
}
// collections.tagName
// Dependency from tag to inputPath
graph.addDependency(tagWithPrefix, entry.inputPath);
}
}
}
}
}
let order = graph.overallOrder();
return order;
}
getPaginatedOverCollectionsMappedDependencies() {
let graph = new DependencyGraph();
let tagPrefix = this.tagPrefix;
let allNodeAdded = false;
for (let entry of this.map) {
if (
this.isPaginationOverAllCollections(entry) &&
!this.getPaginationTagTarget(entry)
) {
if (!allNodeAdded) {
graph.addNode(tagPrefix + "all");
allNodeAdded = true;
}
if (!graph.hasNode(entry.inputPath)) {
graph.addNode(entry.inputPath);
}
if (!entry.data.eleventyExcludeFromCollections) {
// collections.all
graph.addDependency(tagPrefix + "all", entry.inputPath);
}
}
}
return graph.overallOrder();
}
getPaginatedOverAllCollectionMappedDependencies() {
let graph = new DependencyGraph();
let tagPrefix = this.tagPrefix;
let allNodeAdded = false;
for (let entry of this.map) {
if (
this.isPaginationOverAllCollections(entry) &&
this.getPaginationTagTarget(entry) === "all"
) {
if (!allNodeAdded) {
graph.addNode(tagPrefix + "all");
allNodeAdded = true;
}
if (!graph.hasNode(entry.inputPath)) {
graph.addNode(entry.inputPath);
}
if (!entry.data.eleventyExcludeFromCollections) {
// collections.all
graph.addDependency(tagPrefix + "all", entry.inputPath);
}
}
}
return graph.overallOrder();
}
async setCollectionByTagName(tagName) {
if (this.isUserConfigCollectionName(tagName)) {
// async
this.collectionsData[tagName] = await this.getUserConfigCollection(
tagName
);
} else {
this.collectionsData[tagName] = this.getTaggedCollection(tagName);
}
let precompiled = this.config.precompiledCollections;
if (precompiled && precompiled[tagName]) {
if (
tagName === "all" ||
!Array.isArray(this.collectionsData[tagName]) ||
this.collectionsData[tagName].length === 0
) {
this.collectionsData[tagName] = precompiled[tagName];
}
}
}
// TODO(slightlyoff): major bottleneck
async initDependencyMap(dependencyMap) {
let tagPrefix = this.tagPrefix;
for (let depEntry of dependencyMap) {
if (depEntry.startsWith(tagPrefix)) {
// is a tag (collection) entry
let tagName = depEntry.slice(tagPrefix.length);
await this.setCollectionByTagName(tagName);
} else {
// is a template entry
let map = this.getMapEntryForInputPath(depEntry);
map._pages = await map.template.getTemplates(map.data);
if (map._pages.length === 0) {
// Setup serverlessUrls even if data set is 0 pages. This fixes 404 issue
// with full build not including Sanity drafts but serverless render does
// include Sanity drafts.
// We want these empty-data pagination templates to show up in the serverlessUrlMap.
map.template.initServerlessUrlsForEmptyPaginationTemplates(
map.data.permalink
);
} else {
let counter = 0;
for (let page of map._pages) {
// Copy outputPath to map entry
if (!map.outputPath) {
map.outputPath = page.outputPath;
}
if (
counter === 0 ||
(map.data.pagination &&
map.data.pagination.addAllPagesToCollections)
) {
if (!map.data.eleventyExcludeFromCollections) {
// TODO do we need .template in collection entries?
this.collection.add(page);
}
}
counter++;
}
}
}
}
}
async cache() {
debug("Caching collections objects.");
this.collectionsData = {};
for (let entry of this.map) {
entry.data.collections = this.collectionsData;
}
let dependencyMap = this.getMappedDependencies();
await this.initDependencyMap(dependencyMap);
let delayedDependencyMap = this.getDelayedMappedDependencies();
await this.initDependencyMap(delayedDependencyMap);
let firstPaginatedDepMap =
this.getPaginatedOverCollectionsMappedDependencies();
await this.initDependencyMap(firstPaginatedDepMap);
let secondPaginatedDepMap =
this.getPaginatedOverAllCollectionMappedDependencies();
await this.initDependencyMap(secondPaginatedDepMap);
await this.resolveRemainingComputedData();
let orderedPaths = this.getOrderedInputPaths(
dependencyMap,
delayedDependencyMap,
firstPaginatedDepMap,
secondPaginatedDepMap
);
let orderedMap = orderedPaths.map(
function (inputPath) {
return this.getMapEntryForInputPath(inputPath);
}.bind(this)
);
await this.populateContentDataInMap(orderedMap);
this.populateCollectionsWithContent();
this.cached = true;
this.checkForDuplicatePermalinks();
await this.config.events.emit(
"eleventy.serverlessUrlMap",
this.generateServerlessUrlMap(orderedMap)
);
}
generateServerlessUrlMap(orderedMap) {
let entries = [];
for (let entry of orderedMap) {
// Pagination templates with 0 pages should still populate
// serverlessUrls into this event. We want these to still show up
// in the inputPath to URL map and in the redirects.
if (entry._pages.length === 0) {
let serverless = {};
if (isPlainObject(entry.data.permalink)) {
// These are rendered in the template language!
Object.assign(serverless, entry.template.getServerlessUrls());
entries.push({
inputPath: entry.inputPath,
serverless,
});
}
} else {
for (let page of entry._pages) {
let serverless = {};
if (isPlainObject(page.data.permalink)) {
// These are rendered in the template language!
Object.assign(serverless, page.template.getServerlessUrls());
entries.push({
inputPath: entry.inputPath,
serverless,
});
}
}
}
}
return entries;
}
// TODO(slightlyoff): hot inner loop?
getMapEntryForInputPath(inputPath) {
for (let map of this.map) {
if (map.inputPath === inputPath) {
return map;
}
}
}
getOrderedInputPaths(
dependencyMap,
delayedDependencyMap,
firstPaginatedDepMap,
secondPaginatedDepMap
) {
let orderedMap = [];
let tagPrefix = this.tagPrefix;
for (let dep of dependencyMap) {
if (!dep.startsWith(tagPrefix)) {
orderedMap.push(dep);
}
}
for (let dep of delayedDependencyMap) {
if (!dep.startsWith(tagPrefix)) {
orderedMap.push(dep);
}
}
for (let dep of firstPaginatedDepMap) {
if (!dep.startsWith(tagPrefix)) {
orderedMap.push(dep);
}
}
for (let dep of secondPaginatedDepMap) {
if (!dep.startsWith(tagPrefix)) {
orderedMap.push(dep);
}
}
return orderedMap;
}
async populateContentDataInMap(orderedMap) {
let usedTemplateContentTooEarlyMap = [];
for (let map of orderedMap) {
if (!map._pages) {
throw new Error(`Content pages not found for ${map.inputPath}`);
}
if (!map.template.behavior.isRenderable()) {
// Note that empty pagination templates will be skipped here as not renderable
continue;
}
try {
for (let pageEntry of map._pages) {
pageEntry.templateContent =
await pageEntry.template.renderWithoutLayout(pageEntry.data);
}
} catch (e) {
if (EleventyErrorUtil.isPrematureTemplateContentError(e)) {
usedTemplateContentTooEarlyMap.push(map);
} else {
throw e;
}
}
debugDev(
"Added this.map[...].templateContent, outputPath, et al for one map entry"
);
}
for (let map of usedTemplateContentTooEarlyMap) {
try {
for (let pageEntry of map._pages) {
pageEntry.templateContent =
await pageEntry.template.renderWithoutLayout(pageEntry.data);
}
} catch (e) {
if (EleventyErrorUtil.isPrematureTemplateContentError(e)) {
throw new UsingCircularTemplateContentReferenceError(
`${map.inputPath} contains a circular reference (using collections) to its own templateContent.`
);
} else {
// rethrow?
throw e;
}
}
}
}
_testGetAllTags() {
let allTags = {};
for (let map of this.map) {
let tags = map.data.tags;
if (Array.isArray(tags)) {
for (let tag of tags) {
allTags[tag] = true;
}
}
}
return Object.keys(allTags);
}
getTaggedCollection(tag) {
let result;
if (!tag || tag === "all") {
result = this.collection.getAllSorted();
} else {
result = this.collection.getFilteredByTag(tag);
}
debug(`Collection: collections.${tag || "all"} size: ${result.length}`);
return result;
}
async _testGetTaggedCollectionsData() {
let collections = {};
collections.all = this.collection.getAllSorted();
debug(`Collection: collections.all size: ${collections.all.length}`);
let tags = this._testGetAllTags();
for (let tag of tags) {
collections[tag] = this.collection.getFilteredByTag(tag);
debug(`Collection: collections.${tag} size: ${collections[tag].length}`);
}
return collections;
}
setUserConfigCollections(configCollections) {
return (this.configCollections = configCollections);
}
isUserConfigCollectionName(name) {
let collections =
this.configCollections || this.userConfig.getCollections();
return name && !!collections[name];
}
getUserConfigCollectionNames() {
return Object.keys(
this.configCollections || this.userConfig.getCollections()
);
}
async getUserConfigCollection(name) {
let configCollections =
this.configCollections || this.userConfig.getCollections();
// This works with async now
let result = await configCollections[name](this.collection);
debug(`Collection: collections.${name} size: ${result.length}`);
return result;
}
async _testGetUserConfigCollectionsData() {
let collections = {};
let configCollections =
this.configCollections || this.userConfig.getCollections();
for (let name in configCollections) {
collections[name] = configCollections[name](this.collection);
debug(
`Collection: collections.${name} size: ${collections[name].length}`
);
}
return collections;
}
async _testGetAllCollectionsData() {
let collections = {};
let taggedCollections = await this._testGetTaggedCollectionsData();
Object.assign(collections, taggedCollections);
let userConfigCollections = await this._testGetUserConfigCollectionsData();
Object.assign(collections, userConfigCollections);
return collections;
}
populateCollectionsWithContent() {
for (let collectionName in this.collectionsData) {
// skip custom collections set in configuration files that have arbitrary types
if (!Array.isArray(this.collectionsData[collectionName])) {
continue;
}
for (let item of this.collectionsData[collectionName]) {
// skip custom collections set in configuration files that have arbitrary types
if (!isPlainObject(item) || !("inputPath" in item)) {
continue;
}
let entry = this.getMapEntryForInputPath(item.inputPath);
// This check skips precompiled collections
if (entry) {
let index = item.pageNumber || 0;
let content = entry._pages[index]._templateContent;
if (content !== undefined) {
item.templateContent = content;
}
}
}
}
}
async resolveRemainingComputedData() {
let promises = [];
for (let entry of this.map) {
for (let page of entry._pages) {
if (this.config.keys.computed in page.data) {
promises.push(page.template.resolveRemainingComputedData(page.data));
}
}
}
return Promise.all(promises);
}
checkForDuplicatePermalinks() {
let permalinks = {};
let warnings = {};
for (let entry of this.map) {
for (let page of entry._pages) {
if (page.outputPath === false || page.url === false) {
// do nothing (also serverless)
} else if (!permalinks[page.url]) {
permalinks[page.url] = [entry.inputPath];
} else {
warnings[
page.outputPath
] = `Output conflict: multiple input files are writing to \`${
page.outputPath
}\`. Use distinct \`permalink\` values to resolve this conflict.
1. ${entry.inputPath}
${permalinks[page.url]
.map(function (inputPath, index) {
return ` ${index + 2}. ${inputPath}\n`;
})
.join("")}
`;
permalinks[page.url].push(entry.inputPath);
}
}
}
let warningList = Object.values(warnings);
if (warningList.length) {
// throw one at a time
throw new DuplicatePermalinkOutputError(warningList[0]);
}
}
async _testGetCollectionsData() {
if (!this.cached) {
await this.cache();
}
return this.collectionsData;
}
}
module.exports = TemplateMap;