forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.js
242 lines (198 loc) · 5.52 KB
/
helpers.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
import * as jsdom from 'jsdom';
import * as assert from 'assert';
import * as glob from 'tiny-glob/sync.js';
import * as fs from 'fs';
import * as colors from 'kleur';
// for coverage purposes, we need to test source files,
// but for sanity purposes, we need to test dist files
export function loadSvelte(test) {
process.env.TEST = test ? 'true' : '';
const resolved = require.resolve('../compiler.js');
delete require.cache[resolved];
return require(resolved);
}
export const svelte = loadSvelte();
export function exists(path) {
try {
fs.statSync(path);
return true;
} catch (err) {
return false;
}
}
export function tryToLoadJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf-8'));
} catch (err) {
if (err.code !== 'ENOENT') throw err;
return null;
}
}
export function tryToReadFile(file) {
try {
return fs.readFileSync(file, 'utf-8');
} catch (err) {
if (err.code !== 'ENOENT') throw err;
return null;
}
}
const virtualConsole = new jsdom.VirtualConsole();
virtualConsole.sendTo(console);
global.window = new jsdom.JSDOM('<main></main>', {virtualConsole}).window;
global.document = window.document;
global.requestAnimationFrame = null; // placeholder, filled in using set_raf
// add missing ecmascript globals to window
for (const key of Object.getOwnPropertyNames(global)) {
window[key] = window[key] || global[key];
}
export function env() {
window._svelteTransitionManager = null;
window.document.title = '';
window.document.body.innerHTML = '<main></main>';
return window;
}
function cleanChildren(node) {
let previous = null;
// sort attributes
const attributes = Array.from(node.attributes).sort((a, b) => {
return a.name < b.name ? -1 : 1;
});
attributes.forEach(attr => {
node.removeAttribute(attr.name);
});
attributes.forEach(attr => {
node.setAttribute(attr.name, attr.value);
});
// recurse
[...node.childNodes].forEach(child => {
if (child.nodeType === 3) {
// text
if (
node.namespaceURI === 'http://www.w3.org/2000/svg' &&
node.tagName !== 'text' &&
node.tagName !== 'tspan'
) {
node.removeChild(child);
}
child.data = child.data.replace(/\s+/g, '\n');
if (previous && previous.nodeType === 3) {
previous.data += child.data;
previous.data = previous.data.replace(/\s+/g, '\n');
node.removeChild(child);
child = previous;
}
} else {
cleanChildren(child);
}
previous = child;
});
// collapse whitespace
if (node.firstChild && node.firstChild.nodeType === 3) {
node.firstChild.data = node.firstChild.data.replace(/^\s+/, '');
if (!node.firstChild.data) node.removeChild(node.firstChild);
}
if (node.lastChild && node.lastChild.nodeType === 3) {
node.lastChild.data = node.lastChild.data.replace(/\s+$/, '');
if (!node.lastChild.data) node.removeChild(node.lastChild);
}
}
export function normalizeHtml(window, html) {
try {
const node = window.document.createElement('div');
node.innerHTML = html
.replace(/<!--.*?-->/g, '')
.replace(/>[\s\r\n]+</g, '><')
.trim();
cleanChildren(node);
return node.innerHTML.replace(/<\/?noscript\/?>/g, '');
} catch (err) {
throw new Error(`Failed to normalize HTML:\n${html}`);
}
}
export function setupHtmlEqual() {
const window = env();
assert.htmlEqual = (actual, expected, message) => {
assert.deepEqual(
normalizeHtml(window, actual),
normalizeHtml(window, expected),
message
);
};
}
export function loadConfig(file) {
try {
const resolved = require.resolve(file);
delete require.cache[resolved];
const config = require(resolved);
return config.default || config;
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
return {};
}
throw err;
}
}
export function addLineNumbers(code) {
return code
.split('\n')
.map((line, i) => {
i = String(i + 1);
while (i.length < 3) i = ` ${i}`;
return (
colors.gray(` ${i}: `) +
line.replace(/^\t+/, match => match.split('\t').join(' '))
);
})
.join('\n');
}
export function showOutput(cwd, options = {}, compile = svelte.compile) {
glob('**/*.svelte', { cwd }).forEach(file => {
if (file[0] === '_') return;
const { js } = compile(
fs.readFileSync(`${cwd}/${file}`, 'utf-8'),
Object.assign(options, {
filename: file
})
);
console.log( // eslint-disable-line no-console
`\n>> ${colors.cyan().bold(file)}\n${addLineNumbers(js.code)}\n<< ${colors.cyan().bold(file)}`
);
});
}
const start = /\n(\t+)/;
export function deindent(strings, ...values) {
const indentation = start.exec(strings[0])[1];
const pattern = new RegExp(`^${indentation}`, 'gm');
let result = strings[0].replace(start, '').replace(pattern, '');
let trailingIndentation = getTrailingIndentation(result);
for (let i = 1; i < strings.length; i += 1) {
let expression = values[i - 1];
const string = strings[i].replace(pattern, '');
if (Array.isArray(expression)) {
expression = expression.length ? expression.join('\n') : null;
}
if (expression || expression === '') {
const value = String(expression).replace(
/\n/g,
`\n${trailingIndentation}`
);
result += value + string;
} else {
let c = result.length;
while (/\s/.test(result[c - 1])) c -= 1;
result = result.slice(0, c) + string;
}
trailingIndentation = getTrailingIndentation(result);
}
return result.trim().replace(/\t+$/gm, '');
}
function getTrailingIndentation(str) {
let i = str.length;
while (str[i - 1] === ' ' || str[i - 1] === '\t') i -= 1;
return str.slice(i, str.length);
}
export function spaces(i) {
let result = '';
while (i--) result += ' ';
return result;
}