summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Errors/EleventyErrorUtil.js
blob: 6b374d01a589432645e9bc61c8016ae116bb2a9d (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
import TemplateContentPrematureUseError from "./TemplateContentPrematureUseError.js";

/* Hack to workaround the variety of error handling schemes in template languages */
class EleventyErrorUtil {
	static get prefix() {
		return ">>>>>11ty>>>>>";
	}
	static get suffix() {
		return "<<<<<11ty<<<<<";
	}

	static hasEmbeddedError(msg) {
		if (!msg) {
			return false;
		}

		return msg.includes(EleventyErrorUtil.prefix) && msg.includes(EleventyErrorUtil.suffix);
	}

	static cleanMessage(msg) {
		if (!msg) {
			return "";
		}

		if (!EleventyErrorUtil.hasEmbeddedError(msg)) {
			return "" + msg;
		}

		return msg.slice(0, Math.max(0, msg.indexOf(EleventyErrorUtil.prefix)));
	}

	static deconvertErrorToObject(error) {
		if (!error || !error.message) {
			throw new Error(`Could not convert error object from: ${error}`);
		}
		if (!EleventyErrorUtil.hasEmbeddedError(error.message)) {
			return error;
		}

		let msg = error.message;
		let objectString = msg.substring(
			msg.indexOf(EleventyErrorUtil.prefix) + EleventyErrorUtil.prefix.length,
			msg.lastIndexOf(EleventyErrorUtil.suffix),
		);
		let obj = JSON.parse(objectString);
		obj.name = error.name;
		return obj;
	}

	// pass an error through a random template engine’s error handling unscathed
	static convertErrorToString(error) {
		return (
			EleventyErrorUtil.prefix +
			JSON.stringify({ message: error.message, stack: error.stack }) +
			EleventyErrorUtil.suffix
		);
	}

	static isPrematureTemplateContentError(e) {
		// TODO the rest of the template engines
		return (
			e instanceof TemplateContentPrematureUseError ||
			e?.cause instanceof TemplateContentPrematureUseError || // Custom (per Node-convention)
			["RenderError", "UndefinedVariableError"].includes(e?.originalError?.name) && e?.originalError?.originalError instanceof TemplateContentPrematureUseError || // Liquid
			e?.message?.includes("TemplateContentPrematureUseError") // Nunjucks
		);
	}
}

export default EleventyErrorUtil;