UNPKG

1.27 kBJavaScriptView Raw
1/* @flow */
2
3const MAX_STACK_DEPTH = 900
4const noop = _ => _
5
6const defer = typeof process !== 'undefined' && process.nextTick
7 ? process.nextTick
8 : typeof Promise !== 'undefined'
9 ? fn => Promise.resolve().then(fn)
10 : typeof setTimeout !== 'undefined'
11 ? setTimeout
12 : noop
13
14if (defer === noop) {
15 throw new Error(
16 'Your JavaScript runtime does not support any asynchronous primitives ' +
17 'that are required by vue-server-renderer. Please use a polyfill for ' +
18 'either Promise or setTimeout.'
19 )
20}
21
22export function createWriteFunction (
23 write: (text: string, next: Function) => boolean,
24 onError: Function
25): Function {
26 let stackDepth = 0
27 const cachedWrite = (text, next) => {
28 if (text && cachedWrite.caching) {
29 cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text
30 }
31 const waitForNext = write(text, next)
32 if (waitForNext !== true) {
33 if (stackDepth >= MAX_STACK_DEPTH) {
34 defer(() => {
35 try { next() } catch (e) {
36 onError(e)
37 }
38 })
39 } else {
40 stackDepth++
41 next()
42 stackDepth--
43 }
44 }
45 }
46 cachedWrite.caching = false
47 cachedWrite.cacheBuffer = []
48 cachedWrite.componentBuffer = []
49 return cachedWrite
50}