Prevent Closure Compiler from renaming properties without using bracket notation - javascript

I'm working on a product which needs to conditionally expose an API to the end user. We're using the Closure Compiler for minification. The part of the API that I'm trying to expose is a function that calls a callback with a Result whose value is an object with certain properties.
Specifically, the function I'm trying to expose looks like this (in pseudo-jsdoc notation):
/**
* #type DocumentRenderResult {status: String, image?: HTMLImageElement|HTMLCanvasElement}
* #param {function(Result<DocumentRenderResult>)} callback
**/
function renderDocument (url, page, callback) {
}
And the Result class looks like this:
/**
* #template T
* #param {Boolean} ok
* #param {T} val
* #param {Error} err
**/
function Result (ok, val, err) {
this.ok = ok;
this.val = val;
this.err = err;
}
What I'd like is to expose both the Result object API - that is, the fact that there are ok, val, and err properties, and expose the renderDocument interface so that users providing a callback will be able to access the status and image properties.
One solution (possibly) is to use bracket notation everywhere, but since this is supposed to be only conditionally exposed (for certain end users), I'd like to separate the concept of whether it's minified or not from the code.
I think some combination of #implements and #export and an externs file can accomplish this, but I haven't figured it out.
Is what I'm trying to do possible?

There are 2 primary ways to handle this situation:
Without Closure-Library
Store all of your exports in a separate file that becomes the main entry point for the api exposed library. This methodology has no dependencies on external libraries. For an example of this, see my GeolocationMarker library.
With Closure-Library (or at least a part of it)
If you are willing to utilize a very small part of closure-library code in your project, you can use the #export annotation. #export annotations do nothing unless the compilation flag --generate_exports is specified.
When --generate_exports is used, the compiler will add the appropriate call to either closure-library's goog.exportProperty or goog.exportSymbol method.
/** #const */
var mynamespace = {};
/** #export */
mynamespace.maybeExposedMethod = function() {};
With the --generate_exports flag, the compiler will generate the code:
var mynamespace = {maybeExposedMethod:function() {}};
goog.exportSymbol("mynamespace.maybeExposedMethod",
mynamespace.maybeExposedMethod);
Instead of having to depend on all of closure-library. You can copy the definition for those 2 methods into your source. All that's needed is that they exist as those names.
Conditionally Renaming Record Types
Functions which return anonymous objects must be treated differently to prevent renaming. The best option here would be to define a record type in its own file. For the public api to block renaming, include the record definition as an extern. When you want the record properties to be renamed, include the definition as source.
my_typedefs.js
/** #typedef {{image: string, status: number}} */
var my_record_type;
my_method_def.js
/** #return {my_record_type} */
function my_method() {
return {
image: 'some_image.jpg',
status: 200
};
}
If my_typedefs.js is included in the compilation with the --js flag, the record properties will be renamed, but if it is included with the --externs flag, they will not be renamed.

Related

Javascript Dot-Syntax function disappears in listen callback

I'm trying to update Annotorious (https://annotorious.github.io/#) to the latest version of Closure / Javascript.
When I compile it with "SIMPLE" optimizations, dot-syntax functions seem to disappear when goog.events.listen callbacks are invoked. Here's an example:
Here's the "main":
goog.provide('annotorious.Annotorious');
...
/**
* The main entrypoint to the application. The Annotorious class is instantiated exactly once,
* and added to the global window object as 'window.anno'. It exposes the external JavaScript API
* and internally manages the 'modules'. (Each module is responsible for one particular media
* type - image, OpenLayers, etc.)
* #constructor
*/
annotorious.Annotorious = function() {
/** #private **/
this._isInitialized = false;
/** #private **/
this._modules = [ new annotorious.mediatypes.image.ImageModule() ];
...
In another file (they're all compiled together), we have this:
goog.provide('annotorious.Annotation');
goog.require('annotorious.shape');
/**
* A 'domain class' implementation of the external annotation interface.
* #param {string} src the source URL of the annotated object
* #param {string} text the annotation text
* #param {annotorious.shape.Shape} shape the annotated fragment shape
* #constructor
*/
annotorious.Annotation = function(src, text, shape) {
this.src = src;
this.text = text;
this.shapes = [ shape ];
this['context'] = document.URL; // Prevents dead code removal
}
So we start up the code, and at some point we end in the editor for the annotation, listening for a "Save" button:
goog.provide('annotorious.Editor');
....
/**
* Annotation edit form.
* #param {Object} annotator reference to the annotator
* #constructor
*/
annotorious.Editor = function(annotator) {
this.element = goog.soy.renderAsElement(annotorious.templates.editform);
....
/** #private **/
//this._btnSave = goog.dom.query('.annotorious-editor-button-save', this.element)[0];
this._btnSave = this.element.querySelector('.annotorious-editor-button-save');
...
goog.events.listen(this._btnSave, goog.events.EventType.CLICK, function(event) {
event.preventDefault();
var annotation = self.getAnnotation();
annotator.addAnnotation(annotation);
annotator.stopSelection();
if (self._original_annotation)
annotator.fireEvent(annotorious.events.EventType.ANNOTATION_UPDATED, annotation, annotator.getItem());
else
annotator.fireEvent(annotorious.events.EventType.ANNOTATION_CREATED, annotation, annotator.getItem());
self.close();
});
If I put a breakpoint at "goog.events.listen(this._btnSave...", and type "annotorious.Annotation", I get what I expect:
In fact, it has all kinds of methods:
Then I let the code go, and break in the listener (event.preventDefault();, etc, above):
Now, all the dot-syntax methods are gone.
This of course causes crashes later on.
All of these files are compiled together.
This happens for all callbacks - 'load' events, other ux callbacks, etc.
This must have worked in prior versions of Closure / JS.
What could be causing this?
Thanks!
Ok, I was able to resolve the problem by adding "--assume_function_wrapper" to the closure compiler command line.
Previously, I was compiling the package using Plovr. However, since Plovr hasn't been updated in a long time, I switched to using the closure compiler natively.
Apparently either Plovr provided '--assume_function_wrapper' internally or the version of the compiler Plovr used didn't break the functions as described.
As #john suggests above I'll bet '--assume_function_wrapper' keeps goog.provide from "destroying" namespaces by re-declaring them.

JSDoc for function parameter properties + WebStorm

What is the correct JSDdoc declaration for company being a String in the code below?
fetch('https://api.github.com/users/mdo').then(res => res.json()).then(res => {
console.log(res.company);
});
I use WebStorm and it understandably underscores company as an Unresolved variable:
if I add
/** #namespace bogus.company **/
anywhere in the file, WebStorm is happy, but that doesn't make sense:
Is this a bug in WebStorm, or am I missing something about how JSDoc declarations are supposed to work?
Is JSDoc even supposed to be used for this use case?
If you check the inspection for unresolved javascript variable there is a Report undeclared properties as error option that you could uncheck.
I like to do something like this:
/**
* #param {Object} res
* #property {String} company
*/
function myOutput(res) {
console.log(res.company);
}
fetch('https://api.github.com/users/mdo')
.then(myToJson)
.then(myOutput);
But for small anonymous functions I wouldn't even bother. It's a weak warning so turn the inspection off or learn to live with it, I'd say. It's possible to cram in /** #param {*} something */ in anonymous functions as well, but often it only serves to reduce readability.
Another option is to make a dummy file soomething.js somewhere under your content-root with an anonymous function like:
(() => {
return {
"github-users-response" : {
"company" : "sample"
}
}
});
And now webstorm will figure that company actually is defined in your other files. You can even put it in a different content-root if you want to keep it separate from your project.

How do I document NodeJS native (V8) modules?

I have developed a native NodeJS module (using the NAN helpers). Now I am wondering what is the best way to document it.
The methods the module exports exist only in the C++ source code, however I wish to export Javascript documentation.
EDIT: I found another way that I think is better:
All JSDoc needs is to be able to attach the doclet to SOMETHING, so you can actually just do this (if you ignore JSHint warning about expecting an assignment or call instead of expression):
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
* #class
*/
nativeStuff.MyCoolClass;
/**
* My Cool Method
* #function
* #param {String} [name] The argument
*/
nativeStuff.MyCoolClass.prototype.CoolMethod;
/**
* Some Other Value
* #type {String}
*/
nativeStuff.someStringValue;
module.exports = nativeStuff;
This has the advantage of working with IDE's (at least WebStorm) and not requiring you to copy or proxy the object itself. Note though that you have to explicitly tell it what kind of field each entry is (with #function or #class or #type) because it can't infer it automatically otherwise.
Original Answer
There are a couple ways I know of, though I admit none seem particularly elegant.
In the small adapter file where you require() the native parts of the code and make it available as a module, you can assign each component individually and document them that way:
var nativeStuff = require('some/native/stuff');
// If your module only has one thing
/**
* My Cool Class
* #class MyCoolClass
*/
module.exports = nativeStuff;
// If it has several things
module.exports = {
/**
* My cool class
* #class
*/
MyCoolClass: nativeStuff.MyCoolClass,
/**
* My Other Cool Member
*/
OtherCoolMember: nativeStuff.OtherCoolMember
};
You could document members of the class this way too if you want to pick apart the class and re-assemble it, but it gets kinda unwieldy the deeper you go.
The other way I know of is to wrap every class method in native JS, which comes with a (almost negligible) performance hit:
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
*/
class MyCoolClass {
constructor() {
this._nativeObj = new nativeStuff.MyCoolClass();
}
/**
* Some Cool Method
* #param {String} [name] My name
*/
coolMethod(name) {
return this._nativeObj(name);
}
}
module.exports = MyCoolClass;
(Note this also works in older JS versions, but ES6 classes make stuff way easier to understand visually :)
You also can try using the #typedef directive to define things since a doclet about a typedef can be separate from the object it describes, but I don't think typedef's can document methods or classes in general, they're just for data objects.
I had to create a simple documentation generator to scan comments in source code in Javadoc-like style: https://github.com/aspectron/gendoc
Here is a part of such documentation, that looks like this:
/**
#module crypto
**/
/**
#class Hash
Hash generator
#function Hash(algorithm)
#param algorithm {String}
Constructor. Initiaize hash generator with specified algorithm, see #getHashes
Throws exception on unknown algorithm
**/
v8pp::class_<hash_generator> hash_class(bindings.isolate(), v8pp::v8_args_ctor);
hash_class
/**
#function reset([algorithm])
#param [algorithm] {String}
#return {Hash}
Reset hash generator to initial state optionaly changing generator algorithm.
Throws exception on unknown algorithm.
**/
.set("reset", &hash_generator::reset_v8)
...
Finally I opted for a not very elegant solution. I have created a separate JavaScript file which only has methods that are exported by my native API.
This file looks like this:
/** #namespace AwesomeLibrary
*
* #description API overview
*/
AwesomeLibrary = {
/**
* #param {string} param Input parameter
* #return combobulates {#link param}
*/
combobulate: function (param) {}
}
Then I am using JsDoc to generate the documentation of the project and passing this JavaScript file as an input rather than my native code. Finally I bundle the documentation with the binary distribution of my module.
This solution is not ideal as the documentation and the source code have to be maintained separately, however it has the advantage of zero overhead and a (rather) clean file. I have also disabled the source code generation in JsDoc as this would be obviously quite useless and only show the empty stubs.

Javascript Module Pattern and Google Closure Compiler

I am using the Google Closure Compiler on a Drupal project right now. My Javascript is structured using the Javascript Module Pattern.
Because of the way Drupal works, I am compiling each JS file individually. Simple Compilation mode works well, but I would like to use Advanced Compilation on each file.
My files are all variations on
var FOO = (function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
My problem is that Drupal.behaviors is a specific object in Drupal, and the attach property also is a specific property. When a Drupal page renders, Drupal.behaviors gets looped through, and all of the attach functions are called with the proper arguments. In other words, I don't want anything renamed with the Drupal object.
When I use Advanced Compilation mode, I get
var c = function(a, d, b) {
b.b.FOO = {a:function() {
do_stuff()
}};
return a
}(c || {}, jQuery, Drupal);
I have tried many variations on trying to get the compiler to recognize the whole Drupal object as an extern without luck. No matter what I try, .behaviors and .attach always get renamed.
Is there a way to tell the compiler to keep its hands off an entire object?
There is no concept "Don't modify any properties on this object". You can however setup an extern such as:
/** #interface */
function DrupalBehavior() {}
DrupalBehavior.prototype.attach = function(){};
/** #constructor */
function DrupalObject () {}
/** #type {Object.<string, DrupalBehavior>} */
DrupalObject.prototype.behaviors = {};
Then, in your code:
var FOO = (
/**
* #param {Object} me
* #param {jQuery} $
* #param {DrupalObject} Drupal
* #param {*=} undefined
*/
function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
In this case the Drupal argument will be renamed, but the behaviors property and its associated attach sub-property will not be.
One note on jQuery: You are passing the jQuery namespace object into the function as a
parameter. Closure-compiler does not trace the type well in this object. The annotation I have listed would be for an instace of the jQuery object as opposed to the entire jQuery namespace. This is probably not what you intended. The only type-safe way to handle this in Closure-compiler is NOT to pass namespaces through function closure.
Update: After looking through the JavaScript Module Pattern post you linked, they encourage passing global namespace objects into function closures. This pattern has known problems with Closure-compiler. You will need to choose to either follow the pattern in this regard or opt for full compatibility with ADVANCED_OPTIMIZATIONS.

What does the #private annotation actually do in Google Closure JavaScript code?

When I put a comment above my variable or function with #private in it what is it actually doing? I have looked at the documentation but I'm still not sure.
goog.provide('myproject');
/** #private */
myproject.foo = "bar";
I can still access it when I open up chrome's development tools (myproject.foo). And...
goog.require('myproject');
window.addEventListener('load', function() {
//this works.
document.body.textContent = myproject.foo;
});
The above code still set's the bodies textContent to equal "bar", even when compiled. So what does #private actually do?
The access control annotations #private, #protected, and #public are
directives for the Closure Compiler that help developers enforce the
desired level of visibility for properties and functions.
To emit warnings for access violations use the Compiler flag:
--jscomp_warning=visibility
To emit errors for access violations use the Compiler flag:
--jscomp_error=visibility
Access control annotations are enforced on a per file basis,
meaning that any properties annotated #private or #protected may be
accessed anywhere within the same file. Also note that the compiler removes
these annotations from the compiled code since they are not part of the
JavaScript language.
Example
file1.js
goog.provide('ns1');
/**
* Global private variable.
* #private
*/
ns1.global = 'foo';
alert('ns1.global = ' + ns1.global); // OK in same file.
/** #constructor */
ns1.Constructor = function() {
/** #private */
this.secret_ = ns1.global;
};
ns1.instance = new ns1.Constructor();
alert(ns1.instance.secret_); // No warning in same file.
file2.js
goog.provide('ns2');
goog.require('ns1');
alert('ns1.global = ' + ns1.global); // Not allowed.
ns2.instance2 = new ns1.Constructor();
alert(ns2.instance2.secret_); // Not allowed.
With the flag --jscomp_error=visibility set, Closure Compiler emits the
following errors.
ERROR - Access to private property global of ns1 not allowed here.
alert('ns1.global = ' + ns1.global);
^
ERROR - Access to private property secret_ of ns1.Constructor not allowed here.
alert(ns2.instance2.secret_);
^
See Visibility (private and protected fields) in the Google JavaScript
Style Guide.
cpeisert implied this in his answer, but just to be explicit: these visibility annotations don't modify your output at all.
Marking a function as #private does not hide it or make it any less accessible in the resulting code than the Compiler normally would, and any third-party code that you introduce at runtime will be able to invoke such functions.
The only access protection offered by these annotations is against code that you compile in with them.

Categories