All files / server-renderer/src renderToStream.ts

85.13% Statements 63/74
76% Branches 19/25
70% Functions 14/20
85.91% Lines 61/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2058x               8x 8x     8x                     110x 8x 26x 26x 10x   26x 16x   10x           102x         160x 206x 206x 148x     58x         8x         128x   28x 28x             100x 100x   100x   100x 100x 100x         100x           8x                   8x       49x       49x               49x     8x         49x   128x 79x   49x                 8x       1x               1x 1x   1x   1x   4x 4x 3x   1x                           8x         1x 1x     1x 1x 1x     1x   4x 4x   4x 3x   1x                    
import {
  App,
  VNode,
  createVNode,
  ssrUtils,
  createApp,
  ssrContextKey
} from 'vue'
import { isString, isPromise } from '@vue/shared'
import { renderComponentVNode, SSRBuffer, SSRContext } from './render'
import { Readable, Writable } from 'stream'
 
const { isVNode } = ssrUtils
 
export interface SimpleReadable {
  push(chunk: string | null): void
  destroy(err: any): void
}
 
async function unrollBuffer(
  buffer: SSRBuffer,
  stream: SimpleReadable
): Promise<void> {
  if (buffer.hasAsync) {
    for (let i = 0; i < buffer.length; i++) {
      let item = buffer[i]
      if (isPromise(item)) {
        item = await item
      }
      if (isString(item)) {
        stream.push(item)
      } else {
        await unrollBuffer(item, stream)
      }
    }
  } else {
    // sync buffer can be more efficiently unrolled without unnecessary await
    // ticks
    unrollBufferSync(buffer, stream)
  }
}
 
function unrollBufferSync(buffer: SSRBuffer, stream: SimpleReadable) {
  for (let i = 0; i < buffer.length; i++) {
    let item = buffer[i]
    if (isString(item)) {
      stream.push(item)
    } else {
      // since this is a sync buffer, child buffers are never promises
      unrollBufferSync(item as SSRBuffer, stream)
    }
  }
}
 
export function renderToSimpleStream<T extends SimpleReadable>(
  input: App | VNode,
  context: SSRContext,
  stream: T
): T {
  if (isVNode(input)) {
    // raw vnode, wrap with app (for context)
    return renderToSimpleStream(
      createApp({ render: () => input }),
      context,
      stream
    )
  }
 
  // rendering an app
  const vnode = createVNode(input._component, input._props)
  vnode.appContext = input._context
  // provide the ssr context to the tree
  input.provide(ssrContextKey, context)
 
  Promise.resolve(renderComponentVNode(vnode))
    .then(buffer => unrollBuffer(buffer, stream))
    .then(() => stream.push(null))
    .catch(error => {
      stream.destroy(error)
    })
 
  return stream
}
 
/**
 * @deprecated
 */
export function renderToStream(
  input: App | VNode,
  context: SSRContext = {}
): Readable {
  console.warn(
    `[@vue/server-renderer] renderToStream is deprecated - use renderToNodeStream instead.`
  )
  return renderToNodeStream(input, context)
}
 
export function renderToNodeStream(
  input: App | VNode,
  context: SSRContext = {}
): Readable {
  const stream: Readable = __NODE_JS__
    ? new (require('stream').Readable)()
    : null
 
  Iif (!stream) {
    throw new Error(
      `ESM build of renderToStream() does not support renderToNodeStream(). ` +
        `Use pipeToNodeWritable() with an existing Node.js Writable stream ` +
        `instance instead.`
    )
  }
 
  return renderToSimpleStream(input, context, stream)
}
 
export function pipeToNodeWritable(
  input: App | VNode,
  context: SSRContext = {},
  writable: Writable
) {
  renderToSimpleStream(input, context, {
    push(content) {
      if (content != null) {
        writable.write(content)
      } else {
        writable.end()
      }
    },
    destroy(err) {
      writable.destroy(err)
    }
  })
}
 
export function renderToWebStream(
  input: App | VNode,
  context: SSRContext = {}
): ReadableStream {
  Iif (typeof ReadableStream !== 'function') {
    throw new Error(
      `ReadableStream constructor is not available in the global scope. ` +
        `If the target environment does support web streams, consider using ` +
        `pipeToWebWritable() with an existing WritableStream instance instead.`
    )
  }
 
  const encoder = new TextEncoder()
  let cancelled = false
 
  return new ReadableStream({
    start(controller) {
      renderToSimpleStream(input, context, {
        push(content) {
          Iif (cancelled) return
          if (content != null) {
            controller.enqueue(encoder.encode(content))
          } else {
            controller.close()
          }
        },
        destroy(err) {
          controller.error(err)
        }
      })
    },
    cancel() {
      cancelled = true
    }
  })
}
 
export function pipeToWebWritable(
  input: App | VNode,
  context: SSRContext = {},
  writable: WritableStream
): void {
  const writer = writable.getWriter()
  const encoder = new TextEncoder()
 
  // #4287 CloudFlare workers do not implement `ready` property
  let hasReady = false
  try {
    hasReady = isPromise(writer.ready)
  } catch (e: any) {}
 
  renderToSimpleStream(input, context, {
    async push(content) {
      if (hasReady) {
        await writer.ready
      }
      if (content != null) {
        return writer.write(encoder.encode(content))
      } else {
        return writer.close()
      }
    },
    destroy(err) {
      // TODO better error handling?
      console.log(err)
      writer.close()
    }
  })
}