- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / renderer / resources / extensions / messaging_utils.js
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Routines used to normalize arguments to messaging functions.
6
7 function alignSendMessageArguments(args, hasOptionsArgument) {
8   // Align missing (optional) function arguments with the arguments that
9   // schema validation is expecting, e.g.
10   //   extension.sendRequest(req)     -> extension.sendRequest(null, req)
11   //   extension.sendRequest(req, cb) -> extension.sendRequest(null, req, cb)
12   if (!args || !args.length)
13     return null;
14   var lastArg = args.length - 1;
15
16   // responseCallback (last argument) is optional.
17   var responseCallback = null;
18   if (typeof args[lastArg] == 'function')
19     responseCallback = args[lastArg--];
20
21   var options = null;
22   if (hasOptionsArgument && lastArg >= 1) {
23     // options (third argument) is optional. It can also be ambiguous which
24     // argument it should match. If there are more than two arguments remaining,
25     // options is definitely present:
26     if (lastArg > 1) {
27       options = args[lastArg--];
28     } else {
29       // Exactly two arguments remaining. If the first argument is a string,
30       // it should bind to targetId, and the second argument should bind to
31       // request, which is required. In other words, when two arguments remain,
32       // only bind options when the first argument cannot bind to targetId.
33       if (!(args[0] === null || typeof args[0] == 'string'))
34         options = args[lastArg--];
35     }
36   }
37
38   // request (second argument) is required.
39   var request = args[lastArg--];
40
41   // targetId (first argument, extensionId in the manifest) is optional.
42   var targetId = null;
43   if (lastArg >= 0)
44     targetId = args[lastArg--];
45
46   if (lastArg != -1)
47     return null;
48   if (hasOptionsArgument)
49     return [targetId, request, options, responseCallback];
50   return [targetId, request, responseCallback];
51 }
52
53 exports.alignSendMessageArguments = alignSendMessageArguments;