src/vs/workbench/api/common/extHostWebviewMessaging.ts/serializeWebviewMessage
export function serializeWebviewMessage(
	message: any,
	options: { serializeBuffersForPostMessage?: boolean }
): { message: string, buffers: VSBuffer[] } {
	if (options.serializeBuffersForPostMessage) {
		// Extract all ArrayBuffers from the message and replace them with references.
		const arrayBuffers = new ArrayBufferSet();

		const replacer = (_key: string, value: any) => {
			if (value instanceof ArrayBuffer) {
				const index = arrayBuffers.add(value);
				return <extHostProtocol.WebviewMessageArrayBufferReference>{
					$$vscode_array_buffer_reference$$: true,
					index,
				};
			} else if (ArrayBuffer.isView(value)) {
				const type = getTypedArrayType(value);
				if (type) {
					const index = arrayBuffers.add(value.buffer);
					return <extHostProtocol.WebviewMessageArrayBufferReference>{
						$$vscode_array_buffer_reference$$: true,
						index,
						view: {
							type: type,
							byteLength: value.byteLength,
							byteOffset: value.byteOffset,
						}
					};
				}
			}

			return value;
		};

		const serializedMessage = JSON.stringify(message, replacer);

		const buffers = arrayBuffers.buffers.map(arrayBuffer => {
			const bytes = new Uint8Array(arrayBuffer);
			return VSBuffer.wrap(bytes);
		});

		return { message: serializedMessage, buffers };
	} else {
		return { message: JSON.stringify(message), buffers: [] };
	}
}