Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
michael@0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public |
michael@0 | 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
michael@0 | 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
michael@0 | 4 | |
michael@0 | 5 | 'use strict'; |
michael@0 | 6 | |
michael@0 | 7 | module.metadata = { |
michael@0 | 8 | 'stability': 'experimental' |
michael@0 | 9 | }; |
michael@0 | 10 | |
michael@0 | 11 | let { request: hostReq, response: hostRes } = require('./host'); |
michael@0 | 12 | let { defer: async } = require('../lang/functional'); |
michael@0 | 13 | let { defer } = require('../core/promise'); |
michael@0 | 14 | let { emit: emitSync, on, off } = require('../event/core'); |
michael@0 | 15 | let { uuid } = require('../util/uuid'); |
michael@0 | 16 | let emit = async(emitSync); |
michael@0 | 17 | |
michael@0 | 18 | // Map of IDs to deferreds |
michael@0 | 19 | let requests = new Map(); |
michael@0 | 20 | |
michael@0 | 21 | // May not be necessary to wrap this in `async` |
michael@0 | 22 | // once promises are async via bug 881047 |
michael@0 | 23 | let receive = async(function ({data, id, error}) { |
michael@0 | 24 | let request = requests.get(id); |
michael@0 | 25 | if (request) { |
michael@0 | 26 | if (error) request.reject(error); |
michael@0 | 27 | else request.resolve(clone(data)); |
michael@0 | 28 | requests.delete(id); |
michael@0 | 29 | } |
michael@0 | 30 | }); |
michael@0 | 31 | on(hostRes, 'data', receive); |
michael@0 | 32 | |
michael@0 | 33 | /* |
michael@0 | 34 | * Send is a helper to be used in client APIs to send |
michael@0 | 35 | * a request to host |
michael@0 | 36 | */ |
michael@0 | 37 | function send (eventName, data) { |
michael@0 | 38 | let id = uuid(); |
michael@0 | 39 | let deferred = defer(); |
michael@0 | 40 | requests.set(id, deferred); |
michael@0 | 41 | emit(hostReq, 'data', { |
michael@0 | 42 | id: id, |
michael@0 | 43 | data: clone(data), |
michael@0 | 44 | event: eventName |
michael@0 | 45 | }); |
michael@0 | 46 | return deferred.promise; |
michael@0 | 47 | } |
michael@0 | 48 | exports.send = send; |
michael@0 | 49 | |
michael@0 | 50 | /* |
michael@0 | 51 | * Implement internal structured cloning algorithm in the future? |
michael@0 | 52 | * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm |
michael@0 | 53 | */ |
michael@0 | 54 | function clone (obj) JSON.parse(JSON.stringify(obj || {})) |