-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.js
72 lines (67 loc) · 1.82 KB
/
transform.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
'use strict'
const { Readable } = require('streamx')
function parse (template, locals) {
const args = []
const strings = []
let last = 0
template += ''
for (const result of template.matchAll(/__([a-zA-Z/\\.:]*?)__/g)) {
const [match, def] = result
const [name] = def.split(':').map((s) => s.trim())
const { index } = result
args.push(locals[name] + '')
strings.push(template.slice(last, index))
last = index + match.length
}
strings.push(template.slice(last))
return { strings, args }
}
function stream (template, locals) {
const { strings, args } = parse(template, locals)
return new Readable({
objectMode: true,
async read (cb) {
try {
for (let i = 0; i < strings.length; i++) {
this.push(strings[i])
if (i < args.length) for await (const chunk of interlope(await args[i])) this.push(chunk)
}
this.push(null)
cb(null)
} catch (err) {
cb(err)
}
}
})
}
function interlope (arg) {
return new Readable({
objectMode: true,
async read (cb) {
try {
if (arg === null || typeof arg !== 'object') {
this.push(arg)
} else if (Array.isArray(arg)) {
for (const item of arg) {
if (item === arg) continue
for await (const chunk of interlope(item)) this.push(chunk)
}
} else if (typeof arg[Symbol.asyncIterator] === 'function') {
for await (const chunk of arg) this.push(chunk)
} else {
this.push(await arg)
}
this.push(null)
cb(null)
} catch (err) {
this.destroy(err)
cb(err)
}
}
})
}
function sync (template, locals) {
const { strings, args } = parse(template, locals)
return String.raw({ raw: strings }, ...args)
}
module.exports = { stream, sync }