OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012 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 require('json_schema'); | |
6 require('event_bindings'); | |
7 var schemaRegistry = requireNative('schema_registry'); | |
8 var sendRequest = require('sendRequest').sendRequest; | |
9 var utils = require('utils'); | |
10 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); | |
11 var chrome = requireNative('chrome').GetChrome(); | |
12 var schemaUtils = require('schemaUtils'); | |
13 var process = requireNative('process'); | |
14 var manifestVersion = process.GetManifestVersion(); | |
15 var extensionId = process.GetExtensionId(); | |
16 var contextType = process.GetContextType(); | |
17 var GetAvailability = requireNative('v8_context').GetAvailability; | |
18 var logging = requireNative('logging'); | |
19 | |
20 // Stores the name and definition of each API function, with methods to | |
21 // modify their behaviour (such as a custom way to handle requests to the | |
22 // API, a custom callback, etc). | |
23 function APIFunctions() { | |
24 this.apiFunctions_ = {}; | |
25 this.unavailableApiFunctions_ = {}; | |
26 } | |
27 | |
28 APIFunctions.prototype.register = function(apiName, apiFunction) { | |
29 this.apiFunctions_[apiName] = apiFunction; | |
30 }; | |
31 | |
32 // Registers a function as existing but not available, meaning that calls to | |
33 // the set* methods that reference this function should be ignored rather | |
34 // than throwing Errors. | |
35 APIFunctions.prototype.registerUnavailable = function(apiName) { | |
36 this.unavailableApiFunctions_[apiName] = apiName; | |
37 }; | |
38 | |
39 APIFunctions.prototype.setHook_ = | |
40 function(apiName, propertyName, customizedFunction) { | |
41 if (this.unavailableApiFunctions_.hasOwnProperty(apiName)) | |
42 return; | |
43 if (!this.apiFunctions_.hasOwnProperty(apiName)) | |
44 throw new Error('Tried to set hook for unknown API "' + apiName + '"'); | |
45 this.apiFunctions_[apiName][propertyName] = customizedFunction; | |
46 }; | |
47 | |
48 APIFunctions.prototype.setHandleRequest = | |
49 function(apiName, customizedFunction) { | |
50 return this.setHook_(apiName, 'handleRequest', customizedFunction); | |
51 }; | |
52 | |
53 APIFunctions.prototype.setUpdateArgumentsPostValidate = | |
54 function(apiName, customizedFunction) { | |
55 return this.setHook_( | |
56 apiName, 'updateArgumentsPostValidate', customizedFunction); | |
57 }; | |
58 | |
59 APIFunctions.prototype.setUpdateArgumentsPreValidate = | |
60 function(apiName, customizedFunction) { | |
61 return this.setHook_( | |
62 apiName, 'updateArgumentsPreValidate', customizedFunction); | |
63 }; | |
64 | |
65 APIFunctions.prototype.setCustomCallback = | |
66 function(apiName, customizedFunction) { | |
67 return this.setHook_(apiName, 'customCallback', customizedFunction); | |
68 }; | |
69 | |
70 function CustomBindingsObject() { | |
71 } | |
72 | |
73 CustomBindingsObject.prototype.setSchema = function(schema) { | |
74 // The functions in the schema are in list form, so we move them into a | |
75 // dictionary for easier access. | |
76 var self = this; | |
77 self.functionSchemas = {}; | |
78 schema.functions.forEach(function(f) { | |
79 self.functionSchemas[f.name] = { | |
80 name: f.name, | |
81 definition: f | |
82 } | |
83 }); | |
84 }; | |
85 | |
86 // Get the platform from navigator.appVersion. | |
87 function getPlatform() { | |
88 var platforms = [ | |
89 [/CrOS Touch/, "chromeos touch"], | |
90 [/CrOS/, "chromeos"], | |
91 [/Linux/, "linux"], | |
92 [/Mac/, "mac"], | |
93 [/Win/, "win"], | |
94 ]; | |
95 | |
96 for (var i = 0; i < platforms.length; i++) { | |
97 if (platforms[i][0].test(navigator.appVersion)) { | |
98 return platforms[i][1]; | |
99 } | |
100 } | |
101 return "unknown"; | |
102 } | |
103 | |
104 function isPlatformSupported(schemaNode, platform) { | |
105 return !schemaNode.platforms || | |
106 schemaNode.platforms.indexOf(platform) > -1; | |
107 } | |
108 | |
109 function isManifestVersionSupported(schemaNode, manifestVersion) { | |
110 return !schemaNode.maximumManifestVersion || | |
111 manifestVersion <= schemaNode.maximumManifestVersion; | |
112 } | |
113 | |
114 function isSchemaNodeSupported(schemaNode, platform, manifestVersion) { | |
115 return isPlatformSupported(schemaNode, platform) && | |
116 isManifestVersionSupported(schemaNode, manifestVersion); | |
117 } | |
118 | |
119 var platform = getPlatform(); | |
120 | |
121 function Binding(schema) { | |
122 this._schema = schema; | |
Matt Perry
2013/02/21 01:07:57
you missed these ones.
cduvall
2013/02/26 00:36:57
Oops, got them now.
| |
123 this.apiFunctions_ = new APIFunctions(); | |
124 this._customEvent = null; | |
125 this._customTypes = {}; | |
126 this._customHooks = []; | |
127 }; | |
128 | |
129 Binding.create = function(apiName) { | |
130 return new Binding(schemaRegistry.GetSchema(apiName)); | |
131 }; | |
132 | |
133 Binding.prototype = { | |
134 // The API through which the ${api_name}_custom_bindings.js files customize | |
135 // their API bindings beyond what can be generated. | |
136 // | |
137 // There are 2 types of customizations available: those which are required in | |
138 // order to do the schema generation (registerCustomEvent and | |
139 // registerCustomType), and those which can only run after the bindings have | |
140 // been generated (registerCustomHook). | |
141 // | |
142 | |
143 // Registers a custom type referenced via "$ref" fields in the API schema | |
144 // JSON. | |
145 registerCustomType: function(typeName, customTypeFactory) { | |
146 var customType = customTypeFactory(); | |
147 customType.prototype = new CustomBindingsObject(); | |
148 this._customTypes[typeName] = customType; | |
149 }, | |
150 | |
151 // Registers a custom event type for the API identified by |namespace|. | |
152 // |event| is the event's constructor. | |
153 registerCustomEvent: function(event) { | |
154 this._customEvent = event; | |
155 }, | |
156 | |
157 // Registers a function |hook| to run after the schema for all APIs has been | |
158 // generated. The hook is passed as its first argument an "API" object to | |
159 // interact with, and second the current extension ID. See where | |
160 // |customHooks| is used. | |
161 registerCustomHook: function(fn) { | |
162 this._customHooks.push(fn); | |
163 }, | |
164 | |
165 // TODO(kalman/cduvall): Refactor this so |runHooks_| is not needed. | |
166 runHooks_: function(api) { | |
167 this._customHooks.forEach(function(hook) { | |
168 if (!isSchemaNodeSupported(this._schema, platform, manifestVersion)) | |
169 return; | |
170 | |
171 if (!hook) | |
172 return; | |
173 | |
174 hook({ | |
175 apiFunctions: this.apiFunctions_, | |
176 schema: this._schema, | |
177 compiledApi: api | |
178 }, extensionId, contextType); | |
179 }, this); | |
180 }, | |
181 | |
182 // Generates the bindings from |this._schema| and integrates any custom | |
183 // bindings that might be present. | |
184 generate: function() { | |
185 var schema = this._schema; | |
186 var customTypes = this._customTypes; | |
187 | |
188 // TODO(kalman/cduvall): Make GetAvailability handle this, then delete the | |
189 // supporting code. | |
190 if (!isSchemaNodeSupported(schema, platform, manifestVersion)) | |
191 return; | |
192 | |
193 var availability = GetAvailability(schema.namespace); | |
194 if (!availability.is_available) { | |
195 console.error('chrome.' + schema.namespace + ' is not available: ' + | |
196 availability.message); | |
197 return; | |
198 } | |
199 | |
200 // See comment on internalAPIs at the top. | |
201 var mod = {}; | |
202 | |
203 var namespaces = schema.namespace.split('.'); | |
204 for (var index = 0, name; name = namespaces[index]; index++) { | |
205 mod[name] = mod[name] || {}; | |
206 mod = mod[name]; | |
207 } | |
208 | |
209 // Add types to global schemaValidator | |
210 if (schema.types) { | |
211 schema.types.forEach(function(t) { | |
212 if (!isSchemaNodeSupported(t, platform, manifestVersion)) | |
213 return; | |
214 | |
215 schemaUtils.schemaValidator.addTypes(t); | |
216 if (t.type == 'object' && this._customTypes[t.id]) { | |
217 var parts = t.id.split("."); | |
218 this._customTypes[t.id].prototype.setSchema(t); | |
219 mod[parts[parts.length - 1]] = this._customTypes[t.id]; | |
220 } | |
221 }, this); | |
222 } | |
223 | |
224 // Returns whether access to the content of a schema should be denied, | |
225 // based on the presence of "unprivileged" and whether this is an | |
226 // extension process (versus e.g. a content script). | |
227 function isSchemaAccessAllowed(itemSchema) { | |
228 return (contextType == 'BLESSED_EXTENSION') || | |
229 schema.unprivileged || | |
230 itemSchema.unprivileged; | |
231 }; | |
232 | |
233 // Adds a getter that throws an access denied error to object |mod| | |
234 // for property |name|. | |
235 function addUnprivilegedAccessGetter(mod, name) { | |
236 mod.__defineGetter__(name, function() { | |
237 throw new Error( | |
238 '"' + name + '" can only be used in extension processes. See ' + | |
239 'the content scripts documentation for more details.'); | |
240 }); | |
241 } | |
242 | |
243 // Setup Functions. | |
244 if (schema.functions) { | |
245 schema.functions.forEach(function(functionDef) { | |
246 if (functionDef.name in mod) { | |
247 throw new Error('Function ' + functionDef.name + | |
248 ' already defined in ' + schema.namespace); | |
249 } | |
250 | |
251 if (!isSchemaNodeSupported(functionDef, platform, manifestVersion)) { | |
252 this.apiFunctions_.registerUnavailable(functionDef.name); | |
253 return; | |
254 } | |
255 if (!isSchemaAccessAllowed(functionDef)) { | |
256 this.apiFunctions_.registerUnavailable(functionDef.name); | |
257 addUnprivilegedAccessGetter(mod, functionDef.name); | |
258 return; | |
259 } | |
260 | |
261 var apiFunction = {}; | |
262 apiFunction.definition = functionDef; | |
263 apiFunction.name = schema.namespace + '.' + functionDef.name; | |
264 | |
265 // TODO(aa): It would be best to run this in a unit test, but in order | |
266 // to do that we would need to better factor this code so that it | |
267 // doesn't depend on so much v8::Extension machinery. | |
268 if (chromeHidden.validateAPI && | |
269 schemaUtils.isFunctionSignatureAmbiguous( | |
270 apiFunction.definition)) { | |
271 throw new Error( | |
272 apiFunction.name + ' has ambiguous optional arguments. ' + | |
273 'To implement custom disambiguation logic, add ' + | |
274 '"allowAmbiguousOptionalArguments" to the function\'s schema.'); | |
275 } | |
276 | |
277 this.apiFunctions_.register(functionDef.name, apiFunction); | |
278 | |
279 mod[functionDef.name] = (function() { | |
280 var args = Array.prototype.slice.call(arguments); | |
281 if (this.updateArgumentsPreValidate) | |
282 args = this.updateArgumentsPreValidate.apply(this, args); | |
283 | |
284 args = schemaUtils.normalizeArgumentsAndValidate(args, this); | |
285 if (this.updateArgumentsPostValidate) | |
286 args = this.updateArgumentsPostValidate.apply(this, args); | |
287 | |
288 var retval; | |
289 if (this.handleRequest) { | |
290 retval = this.handleRequest.apply(this, args); | |
291 } else { | |
292 var optArgs = { | |
293 customCallback: this.customCallback | |
294 }; | |
295 retval = sendRequest(this.name, args, | |
296 this.definition.parameters, | |
297 optArgs); | |
298 } | |
299 | |
300 // Validate return value if defined - only in debug. | |
301 if (chromeHidden.validateCallbacks && | |
302 this.definition.returns) { | |
303 schemaUtils.validate([retval], [this.definition.returns]); | |
304 } | |
305 return retval; | |
306 }).bind(apiFunction); | |
307 }, this); | |
308 } | |
309 | |
310 // Setup Events | |
311 if (schema.events) { | |
312 schema.events.forEach(function(eventDef) { | |
313 if (eventDef.name in mod) { | |
314 throw new Error('Event ' + eventDef.name + | |
315 ' already defined in ' + schema.namespace); | |
316 } | |
317 if (!isSchemaNodeSupported(eventDef, platform, manifestVersion)) | |
318 return; | |
319 if (!isSchemaAccessAllowed(eventDef)) { | |
320 addUnprivilegedAccessGetter(mod, eventDef.name); | |
321 return; | |
322 } | |
323 | |
324 var eventName = schema.namespace + "." + eventDef.name; | |
325 var options = eventDef.options || {}; | |
326 | |
327 if (eventDef.filters && eventDef.filters.length > 0) | |
328 options.supportsFilters = true; | |
329 | |
330 if (this._customEvent) { | |
331 mod[eventDef.name] = new this._customEvent( | |
332 eventName, eventDef.parameters, eventDef.extraParameters, | |
333 options); | |
334 } else if (eventDef.anonymous) { | |
335 mod[eventDef.name] = new chrome.Event(); | |
336 } else { | |
337 mod[eventDef.name] = new chrome.Event( | |
338 eventName, eventDef.parameters, options); | |
339 } | |
340 }, this); | |
341 } | |
342 | |
343 function addProperties(m, parentDef) { | |
344 var properties = parentDef.properties; | |
345 if (!properties) | |
346 return; | |
347 | |
348 utils.forEach(properties, function(propertyName, propertyDef) { | |
349 if (propertyName in m) | |
350 return; // TODO(kalman): be strict like functions/events somehow. | |
351 if (!isSchemaNodeSupported(propertyDef, platform, manifestVersion)) | |
352 return; | |
353 if (!isSchemaAccessAllowed(propertyDef)) { | |
354 addUnprivilegedAccessGetter(m, propertyName); | |
355 return; | |
356 } | |
357 | |
358 var value = propertyDef.value; | |
359 if (value) { | |
360 // Values may just have raw types as defined in the JSON, such | |
361 // as "WINDOW_ID_NONE": { "value": -1 }. We handle this here. | |
362 // TODO(kalman): enforce that things with a "value" property can't | |
363 // define their own types. | |
364 var type = propertyDef.type || typeof(value); | |
365 if (type === 'integer' || type === 'number') { | |
366 value = parseInt(value); | |
367 } else if (type === 'boolean') { | |
368 value = value === 'true'; | |
369 } else if (propertyDef['$ref']) { | |
370 if (propertyDef['$ref'] in customTypes) { | |
371 var constructor = customTypes[propertyDef['$ref']]; | |
372 } else { | |
373 var refParts = propertyDef['$ref'].split('.'); | |
374 // This should never try to load a $ref in the current namespace. | |
375 var constructor = utils.loadRefDependency( | |
376 propertyDef['$ref'])[refParts[refParts.length - 1]]; | |
377 } | |
378 if (!constructor) | |
379 throw new Error('No custom binding for ' + propertyDef['$ref']); | |
380 var args = value; | |
381 // For an object propertyDef, |value| is an array of constructor | |
382 // arguments, but we want to pass the arguments directly (i.e. | |
383 // not as an array), so we have to fake calling |new| on the | |
384 // constructor. | |
385 value = { __proto__: constructor.prototype }; | |
386 constructor.apply(value, args); | |
387 // Recursively add properties. | |
388 addProperties(value, propertyDef); | |
389 } else if (type === 'object') { | |
390 // Recursively add properties. | |
391 addProperties(value, propertyDef); | |
392 } else if (type !== 'string') { | |
393 throw new Error('NOT IMPLEMENTED (extension_api.json error): ' + | |
394 'Cannot parse values for type "' + type + '"'); | |
395 } | |
396 m[propertyName] = value; | |
397 } | |
398 }); | |
399 }; | |
400 | |
401 addProperties(mod, schema); | |
402 this.runHooks_(mod); | |
403 return mod; | |
404 } | |
405 }; | |
406 | |
407 exports.Binding = Binding; | |
OLD | NEW |