/
processor.test.ts
executable file
·639 lines (556 loc) · 15 KB
/
processor.test.ts
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
import { is, type, equal, match, throws, not, instance } from 'uvu/assert'
import { resolve as pathResolve } from 'path'
import { spyOn, restoreAll } from 'nanospy'
import { delay } from 'nanodelay'
import { test } from 'uvu'
import postcss, {
Plugin,
Result,
Node,
Root,
parse,
PluginCreator,
Document,
Parser,
Stringifier
} from '../lib/postcss.js'
import CssSyntaxError from '../lib/css-syntax-error.js'
import LazyResult from '../lib/lazy-result.js'
import NoWorkResult from '../lib/no-work-result.js'
import Processor from '../lib/processor.js'
import Rule from '../lib/rule.js'
test.after.each(() => {
restoreAll()
})
function prs(): Root {
return new Root({ raws: { after: 'ok' } })
}
function str(node: Node, builder: (s: string) => void): void {
builder(`${node.raws.after}!`)
}
async function catchError(cb: () => Promise<any>): Promise<Error> {
try {
await cb()
} catch (e) {
if (e instanceof Error) return e
}
throw new Error('Error was not thrown')
}
let beforeFix = new Processor([
(root: Root) => {
root.walkRules(rule => {
if (!rule.selector.match(/::(before|after)/)) return
if (!rule.some(i => i.type === 'decl' && i.prop === 'content')) {
rule.prepend({ prop: 'content', value: '""' })
}
})
}
])
test('adds new plugins', () => {
let a = (): void => {}
let processor = new Processor()
processor.use(a)
equal(processor.plugins, [a])
})
test('adds new plugin by object', () => {
let a = (): void => {}
let processor = new Processor()
processor.use({ postcss: a })
equal(processor.plugins, [a])
})
test('adds new plugin by object-function', () => {
let a = (): void => {}
let obj: any = () => {}
obj.postcss = a
let processor = new Processor()
processor.use(obj)
equal(processor.plugins, [a])
})
test('adds new processors of another postcss instance', () => {
let a = (): void => {}
let processor = new Processor()
let other = new Processor([a])
processor.use(other)
equal(processor.plugins, [a])
})
test('adds new processors from object', () => {
let a = (): void => {}
let processor = new Processor()
let other = new Processor([a])
processor.use({ postcss: other })
equal(processor.plugins, [a])
})
test('returns itself', () => {
let a = (): void => {}
let b = (): void => {}
let processor = new Processor()
equal(processor.use(a).use(b).plugins, [a, b])
})
test('throws on wrong format', () => {
let pr = new Processor()
throws(() => {
// @ts-expect-error
pr.use(1)
}, /1 is not a PostCSS plugin/)
})
test('processes CSS', () => {
let result = beforeFix.process('a::before{top:0}')
is(result.css, 'a::before{content:"";top:0}')
})
test('processes parsed AST', () => {
let root = parse('a::before{top:0}')
let result = beforeFix.process(root)
is(result.css, 'a::before{content:"";top:0}')
})
test('processes previous result', () => {
let result = new Processor([() => {}]).process('a::before{top:0}')
result = beforeFix.process(result)
is(result.css, 'a::before{content:"";top:0}')
})
test('takes maps from previous result', () => {
let one = new Processor([() => {}]).process('a{}', {
from: 'a.css',
to: 'b.css',
map: { inline: false }
})
let two = new Processor([() => {}]).process(one, { to: 'c.css' })
equal(two.map.toJSON().sources, ['a.css'])
})
test('inlines maps from previous result', () => {
let one = new Processor([() => {}]).process('a{}', {
from: 'a.css',
to: 'b.css',
map: { inline: false }
})
let two = new Processor([() => {}]).process(one, {
to: 'c.css',
map: { inline: true }
})
type(two.map, 'undefined')
})
test('throws with file name', () => {
let error: CssSyntaxError | undefined
try {
new Processor([() => {}]).process('a {', { from: 'a.css' }).css
} catch (e) {
if (e instanceof CssSyntaxError) {
error = e
} else {
throw e
}
}
is(error?.file, pathResolve('a.css'))
match(String(error?.message), /a.css:1:1: Unclosed block$/)
})
test('allows to replace Root', () => {
let processor = new Processor([
(css, result) => {
result.root = new Root()
}
])
is(processor.process('a {}').css, '')
})
test('returns LazyResult object', () => {
let result = new Processor([() => {}]).process('a{}')
is(result instanceof LazyResult, true)
is(result.css, 'a{}')
is(result.toString(), 'a{}')
})
test('calls all plugins once', async () => {
let calls = ''
let a = (): void => {
calls += 'a'
}
let b = (): void => {
calls += 'b'
}
let result = new Processor([a, b]).process('', { from: undefined })
result.css
result.map
result.root
await result
is(calls, 'ab')
})
test('parses, converts and stringifies CSS', () => {
is(
typeof new Processor([
(css: Root) => {
equal(css instanceof Root, true)
}
]).process('a {}').css,
'string'
)
})
test('send result to plugins', () => {
let processor = new Processor([() => {}])
processor
.use((css, result) => {
is(result instanceof Result, true)
equal(result.processor, processor)
equal(result.opts, { map: true })
equal(result.root, css)
})
.process('a {}', { map: true, from: undefined })
})
test('accepts source map from PostCSS', () => {
let one = new Processor([() => {}]).process('a{}', {
from: 'a.css',
to: 'b.css',
map: { inline: false }
})
let two = new Processor([() => {}]).process(one.css, {
from: 'b.css',
to: 'c.css',
map: { prev: one.map, inline: false }
})
equal(two.map.toJSON().sources, ['a.css'])
})
test('supports async plugins', async () => {
let starts = 0
let finish = 0
let async1 = (css: Root): Promise<void> =>
new Promise<void>(resolve => {
starts += 1
setTimeout(() => {
equal(starts, 1)
css.append('a {}')
finish += 1
resolve()
}, 1)
})
let async2 = (css: Root): Promise<void> =>
new Promise<void>(resolve => {
equal(starts, 1)
equal(finish, 1)
starts += 1
setTimeout(() => {
css.append('b {}')
finish += 1
resolve()
}, 1)
})
let r = await new Processor([async1, async2]).process('', { from: 'a' })
is(starts, 2)
is(finish, 2)
is(r.css, 'a {}b {}')
})
test('works async without plugins', async () => {
let r = await new Processor([() => {}]).process('a {}', { from: 'a' })
is(r.css, 'a {}')
})
test('runs async plugin only once', async () => {
let calls = 0
let async = (): Promise<void> => {
return new Promise<void>(resolve => {
setTimeout(() => {
calls += 1
resolve()
}, 1)
})
}
let result = new Processor([async]).process('a {}', { from: undefined })
result.then(() => {})
await result
await result
is(calls, 1)
})
test('supports async errors', async () => {
let error = new Error('Async')
let async = (): Promise<void> => {
return new Promise<void>((resolve, reject) => {
reject(error)
})
}
let result = new Processor([async]).process('', { from: undefined })
let err1 = await catchError(async () => await result)
equal(err1, error)
let err2: Error | undefined
result.catch(catched => {
err2 = catched
})
await delay(10)
equal(err2, error)
})
test('supports sync errors in async mode', async () => {
let error = new Error('Async')
let async = (): void => {
throw error
}
let err = await catchError(() =>
new Processor([async]).process('', { from: undefined })
)
equal(err, error)
})
test('throws parse error in async', async () => {
let err = await catchError(() =>
new Processor([() => {}]).process('a{', { from: undefined })
)
is(err.message, '<css input>:1:1: Unclosed block')
})
test('throws error on sync method to async plugin', () => {
let async = (): Promise<void> => {
return new Promise<void>(resolve => {
resolve()
})
}
throws(() => {
new Processor([async]).process('a{}').css
}, /async/)
})
test('throws a sync call in async running', async () => {
let async = (): Promise<void> =>
new Promise<void>(resolve => setTimeout(resolve, 1))
let processor = new Processor([async]).process('a{}', { from: 'a.css' })
processor.async()
throws(() => {
processor.sync()
}, /then/)
})
test('remembers errors', async () => {
let calls = 0
let plugin: Plugin = {
postcssPlugin: 'plugin',
Once() {
calls += 1
throw new Error('test')
}
}
let processing = postcss([plugin]).process('a{}', { from: undefined })
throws(() => {
processing.css
}, 'test')
throws(() => {
processing.css
}, 'test')
throws(() => {
processing.root
}, 'test')
let asyncError: any
try {
await processing
} catch (e) {
asyncError = e
}
is(asyncError.message, 'test')
is(calls, 1)
})
test('checks plugin compatibility', () => {
let error = spyOn(console, 'error', () => {})
let warn = spyOn(console, 'warn', () => {})
let plugin = (postcss as any).plugin('test', () => {
return () => {
throw new Error('Er')
}
})
let func = plugin()
equal(warn.callCount, 1)
func.postcssVersion = '2.1.5'
function processBy(version: string): void {
let processor = new Processor([func])
processor.version = version
processor.process('a{}').css
}
throws(() => {
processBy('1.0.0')
}, 'Er')
equal(error.callCount, 1)
equal(error.calls, [
[
'Unknown error from PostCSS plugin. ' +
'Your current PostCSS version is 1.0.0, but test uses 2.1.5. ' +
'Perhaps this is the source of the error below.'
]
])
throws(() => {
processBy('3.0.0')
}, 'Er')
equal(error.callCount, 2)
throws(() => {
processBy('2.0.0')
}, 'Er')
equal(error.callCount, 3)
throws(() => {
processBy('2.1.0')
}, 'Er')
equal(error.callCount, 3)
})
test('sets last plugin to result', async () => {
let plugin1 = (css: Root, result: Result): void => {
equal(result.lastPlugin, plugin1)
}
let plugin2 = (css: Root, result: Result): void => {
equal(result.lastPlugin, plugin2)
}
let processor = new Processor([plugin1, plugin2])
let result = await processor.process('a{}', { from: undefined })
equal(result.lastPlugin, plugin2)
})
test('uses custom parsers', async () => {
let processor = new Processor([])
let result = await processor.process('a{}', { parser: prs, from: undefined })
is(result.css, 'ok')
})
test('uses custom parsers from object', async () => {
let processor = new Processor([])
let syntax = { parse: prs, stringify: str }
let result = await processor.process('a{}', { parser: syntax, from: 'a' })
equal(result.css, 'ok')
})
test('uses custom stringifier', async () => {
let processor = new Processor([])
let result = await processor.process('a{}', { stringifier: str, from: 'a' })
is(result.css, '!')
})
test('uses custom stringifier from object', async () => {
let processor = new Processor([])
let syntax = { parse: prs, stringify: str }
let result = await processor.process('', { stringifier: syntax, from: 'a' })
is(result.css, '!')
})
test('uses custom stringifier with source maps', async () => {
let processor = new Processor([])
let result = await processor.process('a{}', {
map: true,
stringifier: str,
from: undefined
})
match(result.css, /!\n\/\*# sourceMap/)
})
test('uses custom syntax', async () => {
let processor = new Processor([() => {}])
let result = await processor.process('a{}', {
syntax: { parse: prs, stringify: str },
from: undefined
})
is(result.css, 'ok!')
})
test('contains PostCSS version', () => {
match(new Processor().version, /\d+.\d+.\d+/)
})
test('throws on syntax as plugin', () => {
let processor = new Processor([() => {}])
throws(() => {
processor.use({
// @ts-expect-error
parse() {}
})
}, /syntax/)
})
test('warns about missed from', async () => {
let warn = spyOn(console, 'warn', () => {})
let processor = new Processor([() => {}])
processor.process('a{}').css
equal(warn.calls, [])
await processor.process('a{}')
equal(warn.calls, [
[
'Without `from` option PostCSS could generate wrong source map ' +
'and will not find Browserslist config. Set it to CSS file path ' +
'or to `undefined` to prevent this warning.'
]
])
})
test('returns NoWorkResult object', async () => {
let result = new Processor().process('a{}')
instance(result, NoWorkResult)
})
test('without plugins parses CSS only on root access', async () => {
let noWorkResult = new Processor().process('a{}')
let result = await noWorkResult
// @ts-expect-error
type(noWorkResult._root, 'undefined')
is(result.root.nodes.length, 1)
// @ts-expect-error
not.type(noWorkResult._root, 'undefined')
is(noWorkResult.root.nodes.length, 1)
})
test('catches error with empty processor', async () => {
let noWorkResult = new Processor().process('a {')
try {
noWorkResult.root
} catch {}
let err = await catchError(async () => await noWorkResult)
noWorkResult.catch(e => {
instance(e, CssSyntaxError)
})
instance(err, CssSyntaxError)
})
test('throws an error on root access on no plugins mode', () => {
throws(() => {
postcss().process('// invalid', { from: 'a' }).root
}, 'Unknown word')
})
test('supports plugins returning processors', () => {
let warn = spyOn(console, 'warn', () => {})
let a = (): void => {}
let processor = new Processor()
let other: any = (postcss as any).plugin('test', () => {
return new Processor([a])
})
processor.use(other)
equal(processor.plugins, [a])
equal(warn.callCount, 1)
})
test('supports plugin creators returning processors', () => {
let a = (): void => {}
let processor = new Processor()
let other = (() => {
return new Processor([a])
}) as PluginCreator<void>
other.postcss = true
processor.use(other)
equal(processor.plugins, [a])
})
test('uses custom syntax for document', async () => {
let customParser: Parser<Document> = () => {
return new Document({
nodes: [
new Root({
raws: {
codeBefore: '<html>\n<head>\n<style id="id1">',
after: '\n\n\n'
},
nodes: [new Rule({ selector: 'a' })]
}),
new Root({
raws: {
codeBefore: '</style>\n<style id="id2">',
after: '\n',
codeAfter: '</style>\n</head>'
},
nodes: [new Rule({ selector: 'b' })]
})
]
})
}
let customStringifier: Stringifier = (doc, builder) => {
if (doc.type === 'document') {
for (let root of doc.nodes) {
if (root.raws.codeBefore) {
builder(root.raws.codeBefore, root)
}
builder(root.toString(), root)
if (root.raws.codeAfter) {
builder(root.raws.codeAfter, root)
}
}
}
}
let processor = new Processor([() => {}])
let result = await processor.process('a{}', {
syntax: {
parse: customParser,
stringify: customStringifier
},
from: undefined
})
is(
result.css,
'<html>\n<head>\n<style id="id1">' +
'a {}\n\n\n' +
'</style>\n<style id="id2">' +
'b {}\n' +
'</style>\n</head>'
)
})
test.run()