All files CodeFactory.ts

85.46% Statements 194/227
76.11% Branches 86/113
87.5% Functions 35/40
85.52% Lines 189/221

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424                    26x   26x       26x   18x           14x   11x       18x   4x             6x 2x 4x     4x   4x 4x   6x 6x   2x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x   4x 4x 4x   26x 26x       26x 47x               26x 26x       26x 26x       26x 26x 3x   23x   26x 26x       26x 26x 44x 3x       23x                       47x   47x     47x 47x 47x   31x       31x 26x       5x       31x             31x 26x   31x 5x   31x     31x   8x 8x 4x   4x   8x 8x 8x 8x 4x   8x 4x   8x 8x 8x       8x   8x 8x     8x 8x 8x 8x 8x 4x   8x 4x   8x 8x 8x 8x 8x   47x                     18x     31x 18x 18x 18x 18x 18x 31x   31x 31x             31x 31x 7x 7x       31x         26x         31x   18x 18x       4x     7x 4x 4x       4x 4x 4x 4x     7x 7x 7x 7x     7x 7x 7x 7x 7x         4x 4x 4x 4x 4x       4x 4x         4x               8x         8x     8x               8x 8x 8x 8x 8x 8x 8x   8x 16x   28x 28x         16x 24x 24x         16x 16x     16x   16x 16x 16x 16x 16x         8x 8x 8x 8x 8x         8x               8x 8x       73x   73x 6x     73x 12x     73x 30x   43x         47x               7x  
class CodeFactory {
    protected _args: string[] | undefined
    protected options: HookCompileOptions | undefined
 
    // @ts-ignore
    content(options: CodeFactoryContent) {
        throw new Error('CodeFactory must be abstract')
    }
 
    create(options: HookCompileOptions) {
        this.init(options)
        let fn
        Iif (!this.options || !this._args) {
            return
        }
 
        switch (this.options.type) {
            case 'sync':
                fn = new Function(
                    this.args({}),
                    '"use strict";\n' +
                        this.header() +
                        this.content({
                            onError: (err) => `throw ${err};\n`,
                            onResult: (result) => `return ${result};\n`,
                            resultReturns: true,
                            onDone: () => '',
                            rethrowIfPossible: true
                        })
                )
                break
            case 'async':
                fn = new Function(
                    this.args({
                        after: '_callback'
                    }),
                    '"use strict";\n' +
                        this.header() +
                        this.content({
                            onError: (err) => `_callback(${err});\n`,
                            onResult: (result: any) => `_callback(null, ${result});\n`,
                            onDone: () => '_callback();\n'
                        })
                )
                break
            case 'promise':
                let errorHelperUsed = false
                const content = this.content({
                    onError: (err) => {
                        errorHelperUsed = true
                        return `_error(${err});\n`
                    },
                    onResult: (result: any) => `_resolve(${result});\n`,
                    onDone: () => '_resolve();\n'
                })
                let code = ''
                code += '"use strict";\n'
                code += this.header()
                code += 'return new Promise((function(_resolve, _reject) {\n'
                Eif (errorHelperUsed) {
                    code += 'var _sync = true;\n'
                    code += 'function _error(_err) {\n'
                    code += 'if(_sync)\n'
                    code += '_resolve(Promise.resolve().then((function() { throw _err; })));\n'
                    code += 'else\n'
                    code += '_reject(_err);\n'
                    code += '};\n'
                }
                code += content
                Eif (errorHelperUsed) {
                    code += '_sync = false;\n'
                }
                code += '}));\n'
                fn = new Function(this.args({}), code)
                break
        }
        this.deinit()
        return fn
    }
 
    setup(fns: any[], options: HookCompileOptions) {
        options.taps.forEach((item) => {
            fns.push(item.fn)
        })
    }
 
    /**
     * @param {{ type: "sync" | "promise" | "async", taps: Array<Tap>, interceptors: Array<Interceptor> }} options
     */
    init(options: HookCompileOptions) {
        this.options = options
        this._args = options.args.slice()
    }
 
    deinit() {
        this.options = undefined
        this._args = undefined
    }
 
    header() {
        let code = ''
        if (this.needContext()) {
            code += 'var _context = {};\n'
        } else {
            code += 'var _context;\n'
        }
        code += 'var fns = this.fns;\n'
        return code
    }
 
    needContext() {
        Eif (this.options) {
            for (const tap of this.options.taps) {
                if (tap.context) {
                    return true
                }
            }
        }
        return false
    }
 
    callTap(
        tapIndex: number,
        {
            onError,
            onResult,
            onDone,
            rethrowIfPossible
        }: Omit<CodeFactoryContent, 'onDone'> & { onDone: false | (() => any) }
    ) {
        let code = ''
 
        Iif (!this.options) {
            return code
        }
        code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`
        const tap = this.options.taps[tapIndex]
        switch (tap.type) {
            case 'sync':
                Iif (!rethrowIfPossible) {
                    code += `var _hasError${tapIndex} = false;\n`
                    code += 'try {\n'
                }
                if (onResult) {
                    code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
                        before: tap.context ? '_context' : undefined
                    })});\n`
                } else {
                    code += `_fn${tapIndex}(${this.args({
                        before: tap.context ? '_context' : undefined
                    })});\n`
                }
                Iif (!rethrowIfPossible) {
                    code += '} catch(_err) {\n'
                    code += `_hasError${tapIndex} = true;\n`
                    code += onError('_err')
                    code += '}\n'
                    code += `if(!_hasError${tapIndex}) {\n`
                }
                if (onResult) {
                    code += onResult(`_result${tapIndex}`)
                }
                if (onDone) {
                    code += onDone()
                }
                Iif (!rethrowIfPossible) {
                    code += '}\n'
                }
                break
            case 'async':
                let cbCode = ''
                if (onResult) {
                    cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`
                } else {
                    cbCode += `(function(_err${tapIndex}) {\n`
                }
                cbCode += `if(_err${tapIndex}) {\n`
                cbCode += onError(`_err${tapIndex}`)
                cbCode += '} else {\n'
                if (onResult) {
                    cbCode += onResult(`_result${tapIndex}`)
                }
                if (onDone) {
                    cbCode += onDone()
                }
                cbCode += '}\n'
                cbCode += '})'
                code += `_fn${tapIndex}(${this.args({
                    before: tap.context ? '_context' : undefined,
                    after: cbCode
                })});\n`
                break
            case 'promise':
                code += `var _hasResult${tapIndex} = false;\n`
                code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({
                    before: tap.context ? '_context' : undefined
                })});\n`
                code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`
                code += `  throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`
                code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`
                code += `_hasResult${tapIndex} = true;\n`
                if (onResult) {
                    code += onResult(`_result${tapIndex}`)
                }
                if (onDone) {
                    code += onDone()
                }
                code += `}), function(_err${tapIndex}) {\n`
                code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`
                code += onError(`_err${tapIndex}`)
                code += '});\n'
                break
        }
        return code
    }
 
    callTapsSeries({
        onError,
        onResult,
        resultReturns,
        onDone,
        doneReturns,
        rethrowIfPossible
    }: CodeFactoryContent) {
        Iif (!this.options || this.options.taps.length === 0) {
            return onDone()
        }
        const firstAsync = this.options.taps.findIndex((t) => t.type !== 'sync')
        const somethingReturns = resultReturns || doneReturns
        let code = ''
        let current = onDone
        let unrollCounter = 0
        for (let j = this.options.taps.length - 1; j >= 0; j--) {
            const i = j
            const unroll =
                current !== onDone && (this.options.taps[i].type !== 'sync' || unrollCounter++ > 20)
            Iif (unroll) {
                unrollCounter = 0
                code += `function _next${i}() {\n`
                code += current()
                code += `}\n`
                current = () => `${somethingReturns ? 'return ' : ''}_next${i}();\n`
            }
            const done = current
            const doneBreak = (skipDone: boolean) => {
                Eif (skipDone) {
                    return ''
                }
                return onDone()
            }
            const content = this.callTap(i, {
                onError: (error: any) => onError(i, error, done, doneBreak),
                onResult:
                    onResult &&
                    ((result: any) => {
                        return onResult(i, result, done, doneBreak)
                    }),
                onDone: !onResult && done,
                rethrowIfPossible: rethrowIfPossible && (firstAsync < 0 || i < firstAsync)
            })
            current = () => content
        }
        code += current()
        return code
    }
 
    callTapsLooping({ onError, onDone, rethrowIfPossible }: CodeFactoryContent) {
        Iif (!this.options || this.options.taps.length === 0) {
            return onDone()
        }
        const syncOnly = this.options.taps.every((t) => t.type === 'sync')
        let code = ''
        Iif (!syncOnly) {
            code += 'var _looper = (function() {\n'
            code += 'var _loopAsync = false;\n'
        }
        code += 'var _loop;\n'
        code += 'do {\n'
        code += '_loop = false;\n'
        code += this.callTapsSeries({
            onError,
            onResult: (_i, result, next, doneBreak) => {
                let _code = ''
                _code += `if(${result} !== undefined) {\n`
                _code += '_loop = true;\n'
                Iif (!syncOnly) {
                    _code += 'if(_loopAsync) _looper();\n'
                }
                _code += doneBreak(true)
                _code += `} else {\n`
                _code += next()
                _code += `}\n`
                return _code
            },
            onDone:
                onDone &&
                (() => {
                    let _code = ''
                    _code += 'if(!_loop) {\n'
                    _code += onDone()
                    _code += '}\n'
                    return _code
                }),
            rethrowIfPossible: rethrowIfPossible && syncOnly
        })
        code += '} while(_loop);\n'
        Iif (!syncOnly) {
            code += '_loopAsync = true;\n'
            code += '});\n'
            code += '_looper();\n'
        }
        return code
    }
 
    callTapsParallel({
        onError,
        onResult,
        onDone,
        rethrowIfPossible,
        onTap = (_i, run) => run()
    }: CodeFactoryContent & {
        // 每一个tap hook之间连接的作用
        onTap?: (...args: any[]) => any
    }) {
        Iif (!this.options) {
            return ''
        }
        Iif (this.options.taps.length <= 1) {
            return this.callTapsSeries({
                onError,
                onResult,
                onDone,
                rethrowIfPossible
            })
        }
        let code = ''
        code += 'do {\n'
        code += `var _counter = ${this.options.taps.length};\n`
        Eif (onDone) {
            code += 'var _done = (function() {\n'
            code += onDone()
            code += '});\n'
        }
        for (let i = 0; i < this.options.taps.length; i++) {
            const done = () => {
                // @ts-ignore
                Eif (onDone) {
                    return 'if(--_counter === 0) _done();\n'
                } else {
                    return '--_counter;'
                }
            }
            const doneBreak = (skipDone: boolean) => {
                Eif (skipDone || !onDone) {
                    return '_counter = 0;\n'
                } else {
                    return '_counter = 0;\n_done();\n'
                }
            }
            code += 'if(_counter <= 0) break;\n'
            code += onTap(
                i,
                () =>
                    this.callTap(i, {
                        onError: (error) => {
                            let _code = ''
                            _code += 'if(_counter > 0) {\n'
                            _code += onError(i, error, done, doneBreak)
                            _code += '}\n'
                            return _code
                        },
                        onResult:
                            onResult &&
                            ((result) => {
                                let _code = ''
                                _code += 'if(_counter > 0) {\n'
                                _code += onResult(i, result, done, doneBreak)
                                _code += '}\n'
                                return _code
                            }),
                        onDone:
                            !onResult &&
                            (() => {
                                return done()
                            }),
                        rethrowIfPossible
                    }),
                done,
                doneBreak
            )
        }
        code += '} while(false);\n'
        return code
    }
 
    args({ before, after }: { before?: string; after?: string }) {
        let allArgs = this._args || []
 
        if (before) {
            allArgs = [before].concat(allArgs)
        }
 
        if (after) {
            allArgs = allArgs.concat(after)
        }
 
        if (allArgs.length === 0) {
            return ''
        } else {
            return allArgs.join(', ')
        }
    }
 
    getTapFn(idx: number) {
        return `fns[${idx}]`
    }
 
    getTap(idx: number) {
        return `_taps[${idx}]`
    }
}
 
export default CodeFactory