-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathx-include.js
239 lines (199 loc) · 6.48 KB
/
x-include.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
// Cross-site HTML includes (v1.0) | github.com/miragecraft/x-include
'use strict';
const include = (()=>{
let self = caller();
// include directory, relative to this file
let dir = self.getAttribute('data-dir');
let path = dir ? link()(dir) + '/' : '';
let f = (src,data) => {
let loop = caller().hasAttribute('data-loop') ? 'data-loop' : '';
f.html(`<script src="${path}${src}" ${loop} x>${data ? JSON.stringify(data) : ''}</script>`);
}
let log = [];
let cache = new Map();
let global_loop = self.hasAttribute('data-loop');
let blockable = 'blocking' in document.createElement('link');
f.html = (html)=>{
let self = caller();
if (typeof html === 'function') {
let params = (()=>{
let _p = {};
return {
get link() {
return _p.link ??= link();
},
get data() {
return _p.data ??= data();
},
get template() {
return _p.template ??= template();
}
}
})();
html = html(params);
}
// DOM insertion allow <script> to trigger
html = document.createRange().createContextualFragment(html);
html.querySelectorAll('include-once').forEach((e)=>{
let entry = e.getAttribute('id') ?? self.src;
if (log.includes(entry)) {
e.remove()
} else {
log.push(entry);
e.replaceWith(...e.childNodes)
}
});
let scripts = html.querySelectorAll('script');
if (scripts.length) {
let ancestry = new Set(self.getAttribute('data-injected')?.split(',') ?? []);
if (self.src) ancestry.add(index(self.src));
let ancestry_str = [...ancestry].join(',');
let loop = global_loop || self.hasAttribute('data-loop');
scripts.forEach((e)=>{
if (ancestry.size) e.setAttribute('data-injected', ancestry_str);
if (loop) e.setAttribute('data-loop', '');
if (!e.src) return;
if (!e.hasAttribute('async')) e.async = false;
// if (e.hasAttribute('data-unique') && log.includes(e.src)) e.remove();
if (!loop && ancestry.has(index(e.src))) {
throw new Error('Infinite include loop terminated');
}
});
}
if (document.readyState === 'loading') {
// preserve evaluation order via document.write
scripts.forEach((e)=>{e.replaceWith(write(e))})
// FOUC mitigation for external CSS
let links = html.querySelectorAll('link[rel=stylesheet]');
if (links.length) {
// use "blocking" attribute (Chrome)
if (blockable) {
links.forEach((e)=>{
e.setAttribute('blocking','render');
});
}
// document.write fallback
else if (!self.hasAttribute('data-injected')) {
links.forEach((e)=>{
e.replaceWith(write(e));
})
}
}
} else {
// preserve evaluation order via include unwrapping
if (cache.has(self)) {
let combined = cache.get(self);
combined.querySelector('x-include').replaceWith(html);
html = combined;
cache.delete(self);
}
// detect include script via 'x' attribute
let target = html.querySelector('script[x]');
// detect by function call
if (!target) {
[...scripts].some((e)=>{
if (
!e.src && e.textContent
// remove strings
.replaceAll(/(?:(["'`])[^\1]*?\1)/g, '')
// remove comments
.replaceAll(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g,'')
// has the include function call
.match(/(?<=\s|^)include\(/)
) {
target = e; return true;
}
});
}
if (target) {
let marker = document.createElement('x-include');
target.replaceWith(marker);
cache.set(target, html);
html = target;
}
}
self.replaceWith(html);
function write(e){
let str = e.outerHTML.replaceAll('</script>', '<\`+\`/script>');
return document.createRange().createContextualFragment(`
<script>
document.write(\`${str}\`);
document.currentScript.remove()
</script>
`)
}
function index(str) {
let i = log.indexOf(str)+1;
if (!i) i = log.push(str);
return i.toString();
}
function data() {
return JSON.parse(self.innerHTML)
// allow parsing native JS object notation
// new Function('return '+self.innerHTML.trim())()
}
function template() {
let prev = self.previousElementSibling;
if (!prev.matches('template')) {
throw new Error('Missing <template> before the include <script>');
}
return prev.parentElement.removeChild(prev);
}
}
function caller() {
return document.currentScript;
}
function link() {
let base = (caller().getAttribute('src') ?? '').trim();
let prefix = '';
if (base.includes('//')) {
let split = 1+base.indexOf('/', 2+base.indexOf('//'));
prefix = base.substring(0, split);
base = base.substring(split);
} else
if (base.startsWith('/')) {
prefix = '/';
base = base.substring(1);
} else
if (base.startsWith('./')) {
base = base.substring(2)
} else
if (base.startsWith('../')) {
let split = 3+base.lastIndexOf('../');
prefix = base.substring(0, split);
base = base.substring(split);
}
base = base.split('/');
base.pop();
return function(path) {
if (!path) return;
path = path.trim();
if (
path.includes('//') ||
path.startsWith('/') ||
path.startsWith('data:')
) {return path}
if (path.startsWith('./')) {
path = path.subString(2)
}
path = base.concat(path.split('/'));
let total = path.indexOf('..');
if (total>0) {
let intent = path.lastIndexOf('..')-total+1;
let actual = Math.min(total,intent);
path.splice(total-actual,actual*2);
}
/* simpler but less efficient
for (let i = path.indexOf('..'); i>0; i = path.indexOf('..')) {
path.splice(i-1,2)
}
*/
path = prefix + path.join('/');
if (path.indexOf('../') > 0) {
throw new Error('Cannot resolve path');
}
return path
}
}
return f;
})();