UNPKG

10.7 kBJavaScriptView Raw
1"use strict";
2// Copyright (c) Jupyter Development Team.
3// Distributed under the terms of the Modified BSD License.
4var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5 if (k2 === undefined) k2 = k;
6 var desc = Object.getOwnPropertyDescriptor(m, k);
7 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8 desc = { enumerable: true, get: function() { return m[k]; } };
9 }
10 Object.defineProperty(o, k2, desc);
11}) : (function(o, m, k, k2) {
12 if (k2 === undefined) k2 = k;
13 o[k2] = m[k];
14}));
15var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16 Object.defineProperty(o, "default", { enumerable: true, value: v });
17}) : function(o, v) {
18 o["default"] = v;
19});
20var __importStar = (this && this.__importStar) || function (mod) {
21 if (mod && mod.__esModule) return mod;
22 var result = {};
23 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24 __setModuleDefault(result, mod);
25 return result;
26};
27Object.defineProperty(exports, "__esModule", { value: true });
28exports.deserialize = exports.serialize = void 0;
29const KernelMessage = __importStar(require("./messages"));
30/**
31 * Serialize a kernel message for transport.
32 */
33function serialize(msg, protocol = '') {
34 switch (protocol) {
35 case KernelMessage.supportedKernelWebSocketProtocols
36 .v1KernelWebsocketJupyterOrg:
37 return Private.serializeV1KernelWebsocketJupyterOrg(msg);
38 default:
39 return Private.serializeDefault(msg);
40 }
41}
42exports.serialize = serialize;
43/**
44 * Deserialize and return the unpacked message.
45 */
46function deserialize(data, protocol = '') {
47 switch (protocol) {
48 case KernelMessage.supportedKernelWebSocketProtocols
49 .v1KernelWebsocketJupyterOrg:
50 return Private.deserializeV1KernelWebsocketJupyterOrg(data);
51 default:
52 return Private.deserializeDefault(data);
53 }
54}
55exports.deserialize = deserialize;
56var Private;
57(function (Private) {
58 /**
59 * Deserialize and return the unpacked message.
60 * Protocol `v1.kernel.websocket.jupyter.org`
61 */
62 function deserializeV1KernelWebsocketJupyterOrg(binMsg) {
63 let msg;
64 const data = new DataView(binMsg);
65 const offsetNumber = Number(data.getBigUint64(0, true /* littleEndian */));
66 let offsets = [];
67 for (let i = 0; i < offsetNumber; i++) {
68 // WARNING: we cast our 64-bit unsigned int to a number!
69 // so offsets cannot index up to 2**64 bytes
70 offsets.push(Number(data.getBigUint64(8 * (i + 1), true /* littleEndian */)));
71 }
72 const decoder = new TextDecoder('utf8');
73 const channel = decoder.decode(binMsg.slice(offsets[0], offsets[1]));
74 const header = JSON.parse(decoder.decode(binMsg.slice(offsets[1], offsets[2])));
75 const parent_header = JSON.parse(decoder.decode(binMsg.slice(offsets[2], offsets[3])));
76 const metadata = JSON.parse(decoder.decode(binMsg.slice(offsets[3], offsets[4])));
77 const content = JSON.parse(decoder.decode(binMsg.slice(offsets[4], offsets[5])));
78 let buffers = [];
79 for (let i = 5; i < offsets.length - 1; i++) {
80 buffers.push(new DataView(binMsg.slice(offsets[i], offsets[i + 1])));
81 }
82 msg = {
83 channel,
84 header,
85 parent_header,
86 metadata,
87 content,
88 buffers
89 };
90 return msg;
91 }
92 Private.deserializeV1KernelWebsocketJupyterOrg = deserializeV1KernelWebsocketJupyterOrg;
93 /**
94 * Serialize a kernel message for transport.
95 * Protocol `v1.kernel.websocket.jupyter.org`
96 */
97 function serializeV1KernelWebsocketJupyterOrg(msg) {
98 const header = JSON.stringify(msg.header);
99 const parentHeader = msg.parent_header == null ? '{}' : JSON.stringify(msg.parent_header);
100 const metadata = JSON.stringify(msg.metadata);
101 const content = JSON.stringify(msg.content);
102 const buffers = msg.buffers !== undefined ? msg.buffers : [];
103 const offsetNumber = 1 + 4 + buffers.length + 1;
104 let offsets = [];
105 offsets.push(8 * (1 + offsetNumber));
106 offsets.push(msg.channel.length + offsets[offsets.length - 1]);
107 const encoder = new TextEncoder();
108 const channelEncoded = encoder.encode(msg.channel);
109 const headerEncoded = encoder.encode(header);
110 const parentHeaderEncoded = encoder.encode(parentHeader);
111 const metadataEncoded = encoder.encode(metadata);
112 const contentEncoded = encoder.encode(content);
113 const binMsgNoBuff = new Uint8Array(channelEncoded.length +
114 headerEncoded.length +
115 parentHeaderEncoded.length +
116 metadataEncoded.length +
117 contentEncoded.length);
118 binMsgNoBuff.set(channelEncoded);
119 binMsgNoBuff.set(headerEncoded, channelEncoded.length);
120 binMsgNoBuff.set(parentHeaderEncoded, channelEncoded.length + headerEncoded.length);
121 binMsgNoBuff.set(metadataEncoded, channelEncoded.length + headerEncoded.length + parentHeaderEncoded.length);
122 binMsgNoBuff.set(contentEncoded, channelEncoded.length +
123 headerEncoded.length +
124 parentHeaderEncoded.length +
125 metadataEncoded.length);
126 for (let length of [
127 headerEncoded.length,
128 parentHeaderEncoded.length,
129 metadataEncoded.length,
130 contentEncoded.length
131 ]) {
132 offsets.push(length + offsets[offsets.length - 1]);
133 }
134 let buffersByteLength = 0;
135 for (let buffer of buffers) {
136 let length = buffer.byteLength;
137 offsets.push(length + offsets[offsets.length - 1]);
138 buffersByteLength += length;
139 }
140 const binMsg = new Uint8Array(8 * (1 + offsetNumber) + binMsgNoBuff.byteLength + buffersByteLength);
141 const word = new ArrayBuffer(8);
142 const data = new DataView(word);
143 data.setBigUint64(0, BigInt(offsetNumber), true /* littleEndian */);
144 binMsg.set(new Uint8Array(word), 0);
145 for (let i = 0; i < offsets.length; i++) {
146 data.setBigUint64(0, BigInt(offsets[i]), true /* littleEndian */);
147 binMsg.set(new Uint8Array(word), 8 * (i + 1));
148 }
149 binMsg.set(binMsgNoBuff, offsets[0]);
150 for (let i = 0; i < buffers.length; i++) {
151 const buffer = buffers[i];
152 binMsg.set(new Uint8Array(ArrayBuffer.isView(buffer) ? buffer.buffer : buffer), offsets[5 + i]);
153 }
154 return binMsg.buffer;
155 }
156 Private.serializeV1KernelWebsocketJupyterOrg = serializeV1KernelWebsocketJupyterOrg;
157 /**
158 * Deserialize and return the unpacked message.
159 * Default protocol
160 *
161 * #### Notes
162 * Handles JSON blob strings and binary messages.
163 */
164 function deserializeDefault(data) {
165 let value;
166 if (typeof data === 'string') {
167 value = JSON.parse(data);
168 }
169 else {
170 value = deserializeBinary(data);
171 }
172 return value;
173 }
174 Private.deserializeDefault = deserializeDefault;
175 /**
176 * Serialize a kernel message for transport.
177 * Default protocol
178 *
179 * #### Notes
180 * If there is binary content, an `ArrayBuffer` is returned,
181 * otherwise the message is converted to a JSON string.
182 */
183 function serializeDefault(msg) {
184 var _a;
185 let value;
186 if ((_a = msg.buffers) === null || _a === void 0 ? void 0 : _a.length) {
187 value = serializeBinary(msg);
188 }
189 else {
190 value = JSON.stringify(msg);
191 }
192 return value;
193 }
194 Private.serializeDefault = serializeDefault;
195 /**
196 * Deserialize a binary message to a Kernel Message.
197 */
198 function deserializeBinary(buf) {
199 const data = new DataView(buf);
200 // read the header: 1 + nbufs 32b integers
201 const nbufs = data.getUint32(0);
202 const offsets = [];
203 if (nbufs < 2) {
204 throw new Error('Invalid incoming Kernel Message');
205 }
206 for (let i = 1; i <= nbufs; i++) {
207 offsets.push(data.getUint32(i * 4));
208 }
209 const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));
210 const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));
211 // the remaining chunks are stored as DataViews in msg.buffers
212 msg.buffers = [];
213 for (let i = 1; i < nbufs; i++) {
214 const start = offsets[i];
215 const stop = offsets[i + 1] || buf.byteLength;
216 msg.buffers.push(new DataView(buf.slice(start, stop)));
217 }
218 return msg;
219 }
220 /**
221 * Implement the binary serialization protocol.
222 *
223 * Serialize Kernel message to ArrayBuffer.
224 */
225 function serializeBinary(msg) {
226 const offsets = [];
227 const buffers = [];
228 const encoder = new TextEncoder();
229 let origBuffers = [];
230 if (msg.buffers !== undefined) {
231 origBuffers = msg.buffers;
232 delete msg['buffers'];
233 }
234 const jsonUtf8 = encoder.encode(JSON.stringify(msg));
235 buffers.push(jsonUtf8.buffer);
236 for (let i = 0; i < origBuffers.length; i++) {
237 // msg.buffers elements could be either views or ArrayBuffers
238 // buffers elements are ArrayBuffers
239 const b = origBuffers[i];
240 buffers.push(ArrayBuffer.isView(b) ? b.buffer : b);
241 }
242 const nbufs = buffers.length;
243 offsets.push(4 * (nbufs + 1));
244 for (let i = 0; i + 1 < buffers.length; i++) {
245 offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);
246 }
247 const msgBuf = new Uint8Array(offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength);
248 // use DataView.setUint32 for network byte-order
249 const view = new DataView(msgBuf.buffer);
250 // write nbufs to first 4 bytes
251 view.setUint32(0, nbufs);
252 // write offsets to next 4 * nbufs bytes
253 for (let i = 0; i < offsets.length; i++) {
254 view.setUint32(4 * (i + 1), offsets[i]);
255 }
256 // write all the buffers at their respective offsets
257 for (let i = 0; i < buffers.length; i++) {
258 msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);
259 }
260 return msgBuf.buffer;
261 }
262})(Private || (Private = {}));
263//# sourceMappingURL=serialize.js.map
\No newline at end of file