javascript codes refacting using ruby - javascript

Suppose I have some javascript code like this:
function Person(){}
var pro=Person.prototype;
pro["setName"]=function(){}
pro["setAge"]=function(){}
....
Now,I will use the closure compiler to minify the source codes.
However,since Closure Compiler compilation never changes string literals,so I want to replace the myself.
So before compile the codes,I want to replace the string literals like this:
var a="setName",b="setAge";
function Person(){}
var pro=Person.prototype;
pro[a]=function(){}
pro[b]=function(){}
I want to use ruby to do this job,then I have two questions:
1)how to do the replacement?
I tried scan the files line by line,but how to find the string literals and do the replacement?
2)code conflict
Since I have to generate the variables like 'a,b',how to make sure that they are not conflict with my source codes? For example,I generate code like this:
var something="setName";
then how about if there is a varible or function named "something" defined in my source code?

If for some reason you are concerned about raw JS size instead of compressed JS (most people should only worry about compressed size). Perhaps you should consider enabling the "alias all strings" compiler options (available in the Closure Compiler's Java API)?

Instead of doing this you should consider using gzip to compress your files after closure minifies them.
gzip works by finding duplicated strings in the input data and replaces the second occurrence of the string with a pointer to the previous string. It will do this to all your input data, not just javascript string literals.
http://www.gzip.org/

I don't think your overall idea is correct, and I particularly think that doing 1) is too complicated to be able to answer within a single webpage. For 2), it is similarly difficult to do it from outside of the Javascript code, but you may be able to adjoin the original Javascript code with a couple of lines, referencing Here, run the Javascript, and get the list of variables.

Related

Encoding/Decoding Javascript in Nashorn

I use the technique described here:
http://scriptasylum.com/tutorials/encode-decode.html
In a nutshell, one has a javascript file that looks like this, where the actual javascript is encoded:
document.write( unescape( 'escaped string' ) ); dF('encoded javascript');
I now want to run that same .js module under Nashorn, but Nashorn does not have a document object. Therefore, I can not do document.write().
Note: It is well known that this technique is easily bypassed and people modest technical ability can still look at the actual code. My use case does not require strong security so that is not a concern. That said, Please consider answers on why one should not do this as off topic. Thanks.
Basically, that code breaks down into two parts:
Un-obfuscate the string via unescape.
Write the string out via document.write.
It sounds like you want to use the string directly for some reason.
You have at least two options:
You can provide a document object to the scripting engine with a write method that accepts a string. Then you can do with it what you like. (Or substitute document.write before evaluating the string with any function you want called.)
Remove the document.write( and the corresponding ) at the end and have the engine evaluate the string and hand it to you directly as the result of ScriptEngine#eval.
Either way, you'll end up with a string that you can then do something with.

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

Multi language support

I'm developing a HTML5 application that uses jQuery. I want to make it multi language: detecting user language and changing all literals to user's language.
I think that one approach is to use one HTML file for each language supported, but it is a waste of space.
Another approach could be use jQuery to change all literals to user's language. But I'm not sure how to do this.
What do you think? Is there a better approach?
UPDATE:
I've forget it to say that I have some literals inside JavaScript too.
Coulnd't you do some sort of server-side query to the user's language and then load the appropriate text automatically? Maybe even a CMS is appropriate here.
For all the Javascript code, I would use String literals as a variable. So you can load a different language file appropriate to the user language.
File english.js:
var messages_siteA1 = "This is an alert.";
var messages_siteA2 = "...";
// ...
File german.js:
var messages_siteA1 = "Dies ist eine Warnung.";
var messages_siteA2 = "...";
// ...
And in your Javascript:
alert(messages_siteA1);
Or am I missing the point here? ;)
In the HTML5 Demo of my, the "HTML5 Word Clouds",
http://timc.idv.tw/wordcloud/
(source code can be found at https://github.com/timdream/wordcloud)
I wrote separate HTML for different languages, and includes a single set of Javascript files. For literal strings with in the script, I collect them into an object (named T) and put it into <script> block of each HTML files.
This give me the flexibility to customize pages for each language; as you can see, I listed CNN as example in English version, but list other sources in the Chinese version.
If you absolutely have to do it at client-side, how about using a json or xml file to store your translations? This avoids the trouble of creating copies of the same page. For example, in your json. you'd have "welcome_eng": "welcome" and "welcome_fr": "bienvenue", etc.
Then you load the appropriate one using javascript, as in, get the variables like this:
blablabla=["welcome_"+language]
Or, if you want even less work, your welcome text's div will have the id "welcome", then your javascript gets the id and add the appropriate content.
It mostly depends on how dynamic or static your pages are: If they contain much text, than it will be easier to duplicate the page for each language. In this case it is very important to carefully isolate HTML from CSS and scripts. All CSS and scripts should be stored in separate pages, in order to avoid having to update all translations whnever you update a style or a script.
OTOH, if it is mostly dynamic, than it makes sense to replace text snippets by their translation when creating the page. But I wouldn't do the text replacement client-side (jQuery). It's a server-side job.
Edit: If you have javascript literals, you should then of course keep them side by side with the HTML, either in the HTML file or in a separate .js file. But it remains up to the server to deliver the contents in the correct language.

Parsing Custom JavaScript Annotations

Implementing a large JavaScript application with a lot of scripts, its become necessary to put together a build script. JavaScript labels being ubiquitous, I've decided to use them as annotations for a custom script collator. So far, I'm just employing the use statement, like this:
use: com.example.Class;
However, I want to support an 'optional quotes' syntax, so the following would be parsed correctly as well
use: 'com.example.Class';
I'm currently using this pattern to parse the first form:
/\s*use:\s*(\S+);\s*/g
The '\S+' gloms all characters between the annotation name declaration and the terminating semi colon. What rule can I write to substitute for \S+ that will return an annotation value without quotes, no matter if it was quoted or not to begin with? I can do it in two steps, but I want to do it in one.
Thanks- I know I've put this a little awkwardly
Edit 1.
I've been able to use this, but IMHO its a mess- any more elegant solutions? (By the way, this one will parse ALL label names)
/\s*([a-z]+):\s*(?:['])([a-zA-Z0-9_.]+)(?:['])|([a-zA-Z0-9_.]+);/g
Edit 2.
The logic is the same, but expresses a little more succinctly. However, it poses a problem as it seems to pull in all sorts of javascript code as well.
/\s*([a-z]+):\s*'([\w_\.]+)'|([\w_\.]+);/g
Ok -this seemed to do it. Hope someone can improve on it.
/\s*([a-z]+): *('[\w_\/\.]+'|[\w_\/\.]+);/g

Best way to decompress javascript files

There are many tools to compress a Javascript file (Packer YUI for example).
But how can I decompress them back to a human readable format?
I have compressed a file using a tool like Packer YUI , but I couldn't reach the source back again.
Is there any good software or tricks you can suggest to decompress the JS ?
You can't. Javascript compression is usually a lossy one, and the information is lost forever.
What you can do, is use a source formatter and a good refactoring tool and -- painfully -- reconstruct the original source. Even if you are not familiar with the code it should be possible; Jeff and a few others reverse engineered the WMD javascript code from a minified version.
Finally, you should consider using a version control system and proper backups to keep your source code safe.
This website is really cool. You can paste a minified JS, then you get a human readable view.
Try JSMinNpp (now called JSToolNpp) plugin for notepad++ (to compress and decompress).
http://www.sunjw.us/jstoolnpp/
DECOMPRESS JAVASCRIPT
A typical JavaScript compressed with /packer/ starts with the following code:
`eval(function(p,a,c,k,e,r)`…
`eval` can simply be replaced by alert.
The eval function evaluates a string argument that contains JavaScript. In most packers, eval is used, followed by document.write.
To decompress JavaScript, replace these methods by one of the following:
1. Replace eval by alert (The alert will simply print the code in a popup-window)
2. If the JavaScript appears after the <body> element, you can add a <textarea> like so:
`<textarea id="code"></textarea>`
Then, replace eval(…); by document.getElementById("code").value=…;.
A linter like ESLint can be handy as well. It can format the code using the "fix all auto-fixable problems" to a point where you can at least start doing manual editing with greater ease.
I never used Packer YUI. But if you use this javascript packer, you can always get your code back using this javascript beautifier which also decompresses the code.
Some javascipt minifier shorten the variable names while compressing the js. In that case you could never get your original code back even if you beautify it.

Categories

Resources