1 // Copyright 2014 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.
5 // Routines used to normalize arguments to messaging functions.
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
)
14 var lastArg
= args
.length
- 1;
16 // responseCallback (last argument) is optional.
17 var responseCallback
= null;
18 if (typeof args
[lastArg
] == 'function')
19 responseCallback
= args
[lastArg
--];
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:
27 options
= args
[lastArg
--];
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
--];
38 // request (second argument) is required.
39 var request
= args
[lastArg
--];
41 // targetId (first argument, extensionId in the manifest) is optional.
44 targetId
= args
[lastArg
--];
48 if (hasOptionsArgument
)
49 return [targetId
, request
, options
, responseCallback
];
50 return [targetId
, request
, responseCallback
];
53 exports
.alignSendMessageArguments
= alignSendMessageArguments
;