aboutsummaryrefslogtreecommitdiffstats
path: root/vanilla/node_modules/undici/lib/handler/unwrap-handler.js
blob: 865593a327bdb6ec5f8f0bc863a68514cbfaae13 (plain) (blame)
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
'use strict'

const { parseHeaders } = require('../core/util')
const { InvalidArgumentError } = require('../core/errors')

const kResume = Symbol('resume')

class UnwrapController {
  #paused = false
  #reason = null
  #aborted = false
  #abort

  [kResume] = null

  constructor (abort) {
    this.#abort = abort
  }

  pause () {
    this.#paused = true
  }

  resume () {
    if (this.#paused) {
      this.#paused = false
      this[kResume]?.()
    }
  }

  abort (reason) {
    if (!this.#aborted) {
      this.#aborted = true
      this.#reason = reason
      this.#abort(reason)
    }
  }

  get aborted () {
    return this.#aborted
  }

  get reason () {
    return this.#reason
  }

  get paused () {
    return this.#paused
  }
}

module.exports = class UnwrapHandler {
  #handler
  #controller

  constructor (handler) {
    this.#handler = handler
  }

  static unwrap (handler) {
    // TODO (fix): More checks...
    return !handler.onRequestStart ? handler : new UnwrapHandler(handler)
  }

  onConnect (abort, context) {
    this.#controller = new UnwrapController(abort)
    this.#handler.onRequestStart?.(this.#controller, context)
  }

  onUpgrade (statusCode, rawHeaders, socket) {
    this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket)
  }

  onHeaders (statusCode, rawHeaders, resume, statusMessage) {
    this.#controller[kResume] = resume
    this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage)
    return !this.#controller.paused
  }

  onData (data) {
    this.#handler.onResponseData?.(this.#controller, data)
    return !this.#controller.paused
  }

  onComplete (rawTrailers) {
    this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers))
  }

  onError (err) {
    if (!this.#handler.onResponseError) {
      throw new InvalidArgumentError('invalid onError method')
    }

    this.#handler.onResponseError?.(this.#controller, err)
  }
}