UNPKG

2.04 kBJavaScriptView Raw
1/**
2 * Copyright 2018 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16const {helper} = require('./helper');
17
18/**
19 * @implements {!Puppeteer.ConnectionTransport}
20 */
21class PipeTransport {
22 /**
23 * @param {!NodeJS.WritableStream} pipeWrite
24 * @param {!NodeJS.ReadableStream} pipeRead
25 */
26 constructor(pipeWrite, pipeRead) {
27 this._pipeWrite = pipeWrite;
28 this._pendingMessage = '';
29 this._eventListeners = [
30 helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer))
31 ];
32 this.onmessage = null;
33 this.onclose = null;
34 }
35
36 /**
37 * @param {string} message
38 */
39 send(message) {
40 this._pipeWrite.write(message);
41 this._pipeWrite.write('\0');
42 }
43
44 /**
45 * @param {!Buffer} buffer
46 */
47 _dispatch(buffer) {
48 let end = buffer.indexOf('\0');
49 if (end === -1) {
50 this._pendingMessage += buffer.toString();
51 return;
52 }
53 const message = this._pendingMessage + buffer.toString(undefined, 0, end);
54 if (this.onmessage)
55 this.onmessage.call(null, message);
56
57 let start = end + 1;
58 end = buffer.indexOf('\0', start);
59 while (end !== -1) {
60 if (this.onmessage)
61 this.onmessage.call(null, buffer.toString(undefined, start, end));
62 start = end + 1;
63 end = buffer.indexOf('\0', start);
64 }
65 this._pendingMessage = buffer.toString(undefined, start);
66 }
67
68 close() {
69 this._pipeWrite = null;
70 helper.removeEventListeners(this._eventListeners);
71 }
72}
73
74module.exports = PipeTransport;