-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (77 loc) · 4.31 KB
/
index.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
const { parseHtmlx } = require('./htmlxparser');
const { walk } = require('svelte/compiler');
const MagicString = require('magic-string');
module.exports = {
pageqlAuthPreprocess: () => {
return {
markup: (source) => {
//input
let out = new MagicString(source.content);
let src = source.content;
const processPageQLAttributes = (node) => {
if (node.type == 'Element') {
for (const attribute of (node.attributes || []).filter((a) => a.type == 'Attribute')) {
const attributeValue = attribute.value;
const prop = attribute.name;
const splitProp = prop.split(':');
if (splitProp[0] == "pageql") {
let overwriter;
switch (splitProp[1]) {
case "authLogin":
if (node.name == 'form') {
const authLoginVariable = src.substring(attributeValue[0].expression.start, attributeValue[0].expression.end);
overwriter = `on:submit|preventDefault={(event) => window.pageql.auth.doLogin(${authLoginVariable}, event)}`;
}
break;
case "authLogout":
const authLogoutVariable = src.substring(attributeValue[0].expression.start, attributeValue[0].expression.end);
overwriter = `on:click={(event) => window.pageql.auth.doLogout(${authLogoutVariable}, event)}`;
break;
case "authRegister":
if (node.name == 'form') {
const authRegisterVariable = src.substring(attributeValue[0].expression.start, attributeValue[0].expression.end);
overwriter = `on:submit|preventDefault={(event) => window.pageql.auth.doRegister(${authRegisterVariable}, event)}`;
}
break;
case "authRole":
const authRoleVariable = src.substring(attributeValue[0].expression.start, attributeValue[0].expression.end);
overwriter = `class:hidden={window.pageql.auth.checkRole(${authRoleVariable})}`;
break;
default:
let error = new Error(`Custom PageQL directive ${splitProp[1]} is invalid`);
throw error;
}
out.overwrite(
attribute.start,
attribute.end,
overwriter,
);
}
}
}
};
//apply transforms
try {
const ast = parseHtmlx(source.content);
walk(ast, {
enter: (node, parent, prop, index) => {
processPageQLAttributes(node);
}
})
} catch (e) {
//convert svelte CompilerError to string for our loader (rollup/webpack)
let error = new Error(`${source.file ? `${source.file} :` : ""}${e.toString()}`);
error.name = `PageQLPreprocessor/${e.name}`
throw error;
}
//output
const map = out.generateMap({
source: source.file,
file: source.file + ".map",
includeContent: true
});
return { code: out.toString(), map: map.toString() };
},
};
},
};