180ea250cfe6fbfb838e04c0190ec31655121d4c3e81f12538991718ab8c4df82cd7ceaeeaa8a4b422d594800237c24a0de1c091f90a99c51328d907c8ba35 1.2 KB

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