My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Saturday, April 27, 2013

Few Modern JavaScript Inconsistencies

While the JavaScript weekly mailing list still points to 90s style articles about the old JavaScript Internet Explorer 5 was supporting too, the current world has different real problems to consider.
Here a quick list of things you might not know about the current status of JavaScript possibilities.

Reserved Words As Properties

Number one of the list is the myth that reserved words cannot be used as properties. Here platforms that cannot:

  1. iOS 4
  2. IE less than 9
  3. Android less than 2.1

So, basically, 99% of mobile browsers support properties such obj.delete(), used in most recent JavaScript specifications, while those jurassic browsers need the obj['delete']() convention.

// exactly same good old ES3 behavior
// using ES5 capabilities
Function.prototype.new = function () {
  var
    // grab the prototype
    p = this.prototype,
    // create from it
    o = Object.create(p),
    // invoke the real constructor
    r = this.apply(o, arguments);
  // if the result is not undefined or null
  // and the returned value is an object/function
  // overwrite the result
  return r != null && (
    typeof r === 'object' ||
    typeof r === 'function'
  ) ? r : o;
};

// you can be Rubyish now ^_^
var instance = MyClass.new(1, 2, 3);

// P.S. if you have problems with JSLint
// and the r != null part in above snippet
// it's just time for you to upgrade to JSHint

Please Do Not Support Too Old Browsers

As easy as that. As a developer, company, software provider, whatever, you are trapping yourself behind problems that will never be fixed in those browsers and you are limiting your customer too, embracing development for such old environment, instead of promoting an update that will benefit them in terms of both potentials, expenses, and security.
Any company that will say no to that should be kindly be abandoned, IMHO, they're already out of web/JS business and they don't realize yet.
I understand some graceful measurement should be taken in order to migrate old users, but as long as they feel confortable, they won't migrate sooner for sure.
Customers or people we'd like to let them access our service, should be informed somehow of new possibilities too.

Apple Drops 3 Years Old Software Too

If Apple not accepting non retina software anymore is not enough as an argument, think how many possibilities you are dropping to your software in order to work the same in those old browsers.
You chose Web technologies, you should catch up with these, end of the story.

Object.defineProperty() *Is* Available

Even my Palm Pre 2 webOS supports Object.defineProperty(), together with Object.defineProperties(), Object.getPrototypeOf() and Object.getOwnPropertyDescriptor()!
If you don't want to deal with all this verbosity but you like the power behind, redefine is really your best friend then!

The most widely adopted list of ES5 features down to Android 2.1 phones and webOS are:

  1. Object.create()
  2. Object.defineProperty()
  3. Object.defineProperties()
  4. Object.getOwnPropertyNames()
  5. Object.getOwnPropertyDescriptor()
  6. Object.getPrototypeOf()

Things like Object.freeze() might have been introduced later on so don't trust them ... but, whenever you wanna try that:

var freeze = Object.freeze || Object;
freeze({}); // frozen where possible

function returnFrozen(object) {
  return (Object.freeze || Object)(object);
}

As it is for "use strict"; and all other things that works best natively, above technique will work with Object.seal(), Object.preventExtensions(), and why not, a shimmable Object.isExtensible()

'isExtensible' in Object || (function(){
  // no way ES3 can prevent extension so ...
  Object.isExtensible = function (object) {
    // ... if an object, it's extensible
    return object != null && (
      typeof object === 'object' ||
      typeof object === 'function'
    )
  };
}());

Function.prototype get caller() {return WTF}

Generally speaking the caller property works since ever but there are cases where it does not and this is iOS5 and lower fault.
What am I talking about? About caller over getters, with or without __defineGetter__ old style approach, the new one fails too ^_^
Bear in mind iOS 5.1 and 6.0+ are just fine so you can still use that magic, if needed.
Note a part, that magic ain't disappearing any time soon so ... go on, use caller until there is an alternative: so far, not a single one ^_^

Function.prototype.bind()

It took literarily ages for WebKit to adopt this method so this is something available in all modern browsers but most likely not available with not so old mobile one: easy shim from callerOf!

(function (P, l) {
  'use strict';
  if (!P.bind) {
    P.bind = function (s) {
      var
        c = this,
        a = l.call(arguments, 1);
      return function bind() {
        return c.apply(s, a.concat(l.call(arguments)));
      };
    };
  }
}(Function.prototype, [].slice));

This is the kind of code that I would like to see in CDN, not just 50K libraries for client sake!

Avoid __proto__

Not only conceptually an error and used only to gain some arguable performance boost, __proto__ is absolutely something that IE 10 and 9 will never have in a consistent way.

If you want to transform a list into an array, just var slice = Function.call.bind([].slice); so that you can slice(whatever, optionalIndex) ALL the things, right? The bind() is there and costs nothing ... just use it!

Better Than Zepto

What this library is doing, except from ignoring IE as a Mobile browser, is a poor/quick&dirty design/convention to obtain a prototype swap instead of initializing things in the right way.
The previously linked code could be represented by exactly the same syntax:

// an IE9 and 10 compatible zero bullshit Zepto core
var emptyArray = [];
zepto.Z = function(dom, selector) {
  var result = Object.create($.fn);
  emptyArray.push.apply(
    result, dom || emptyArray
  );
  result.selector = selector || '';
  return result;
}

While performance might not be that good in some engine, and everybody knows that you should never $('select') twice per collection so actually, considering above snippet goes 400.000 objects per seconds, that's not a big/real deal at all!
If that is, I tell you something else is wrong in the app logic!
In any case, actually, there's some mobile platform there, those Zepto thinks is supporting, that scores more with lower results than with a prototype swap, which is the most common selector case, BlackBerry 10 is 8 thousands operations per seconds there compared with __proto__
Thomas Fuchs has been so nice in his repository I cannot even push/contributes these improvements ... surely he would get this one as an insult too, isn't it?

A Swap Oriented __proto__ Attempt

Assuming you still want to swap runtime classes because you cannot define a proper inheritance upfront, here a broken attempt to do that in IE8 and lower:

object = dunder(object, proto);

what's dunder()

dunder() is my attempt to bring a friendly cross platform way, included older IE, to swap proto at runtime.
It requires an assignment so, back to Zepto example, return dunder(dom || [], $.fn) would be all you need to make it work everywhere.

JSON.stringify(object, *replacer*)

This is Safari specific gotcha, and it's about the replacer.
While specs say that Let newElement be the result of calling the abstract operation Walk, passing val and **ToString**(I), Safari will send to the receiver the number 0 instead of the string '0'.
What's the big deal here? That in JavaScript, 0 == false while '0' == true so ... if you have this kind of check in your receiver thinking that if empty, nothing should be done:

if (key) {
  // parse your value
}

Improve that check with if (key === ''), probably the only place on earth where JSLint would have helped you for real instead of messing up your own code.

And for today, that's all folks!

Wednesday, April 24, 2013

Boot To Node.js In 7 Seconds On Arch Linux

This is a long story that started with me buying a Raspberry Pi with the goal of discovering how good performance could have been in such device used as dedicated server.
The story goes on with pcDuino too, and tricks you might want to know about booting up and building node on them.

Why A Pi As A Server

The story of computers is not actually that fair for same computers, as not fair is the Moore's law itself.
Bear in mind, I am not saying that's not working, all I am saying is that if in 6 months we've got double amount of transistors in some CPU, this does not mean we've been used the previous CPU at its best for last 6 months!

Gaming, immortal, consoles such PS2 can describe better than my words what I am talking about: hardware is good until what you need does not fit under that 100% of potentials!

ARM Is Powerful

Not only is becoming one of the most ambitious target for any Operating System, probably including Microsoft, ARM is also both powerful and power consumption aware, something we've never rarely thought about before .. I mean, a server that does not need much electricity so that if some blackout happens it does not dry whatever counter blackout part is playing in the building? And what about a web farm?

A Raspberry Pi Web Hosting Colocation

Yes, it's not just me, and actually ... WTF!
When I've invested a bit of extra time trying to have up and running my own idea of a co-location, raspberrycolocation.com was born instead and sold out ... gosh I'm always late at the party!
What this smart guys did, is to offer a full server for about $50, being absolutely the most competitive dedicated server company in the world right now ... that's as easy as that .... but ...

Arch linux

What those guys offer is a colocation for your own Pi, a device I honestly would never put into anybody else hands (and that's the feeling you have when that little thing works as hell with awesome performance under your own software) over the Raspbian distro, surely a stable, well tested, etc, etc linux based OS, unfortunately kinda/"slightlier" heavy :(
R-Pi aim is to be a cheap replacement for a PC and in this case Raspbian is the most suitable distro you have there.
However, if you are planning to do something different that does not requires a GUI, and RAM is only 512 there, or any other extra thing on top, Arch Linux becomes the best alternative for this device.

The part I love the most about Arch Linux, is that it basically embraces my same philosophy when it comes to JavaScript or, generally speaking, programming with dependencies .... the less I have and the more I know about the app, the faster I move when it comes to add something, fix something, or experiment! (you should try this approach instead of putting, as example, jQuery or Zepto by default in your web page, it works, trust me!)

Living On The Edge

This Aerosmith song is probably looping inside any Arch Linux contributor, as this distribution is nothing about having frozen modules that pass some test and until tested everywhere else will never work, this distro is about having always the latest available software in your system, which will result in a freaking cool, always updated one, as ready for production as much as your node.js project or website is ... I mean, isn't modern JavaScript culture about serving what's the best thing available today? I love that too!

410+ MB of RAM

You don't need me to try the Raspbian distro and check how much require('os').freemem(); command will return in node pre 0.11.2, you can install the package instead of compiling it on the hardware as I am doing, and do the math.
If the device has 512MB of RAM, 410+ after OS booted in about 8 seconds ain't that bad, right? And I am sure the distro coul dbe even more minimalistic ... as it is, as example in the following platform:

The Allwinner 10

If I have to be honest with you, I would rather consider this platform, or any of its new derived, more than a Pi.
I know, kids price not so friendly, but here you have an ARMv7 with most likely at least 1Ghz of clock speed and 1GB of RAM over some NAND which is alwas faster than inboard SD controller (I'll come back on this part too)

The pcDuino Case

As example, you can have an Arch Linux distro able to boot up in 6 seconds into node.js, with an average of 0.3% of CPU usage via SSH to monitor what's going on behind the top scene!

If you try to do the same with the minimalistic full Desktop version of Ubuntu for this device, you'll notice at least 6 to 9% of default CPU usage because of the graphic OS, plus 691511296 of available RAM after boot against a require('os').freemem() resut of 797020160 for the Arch Linux headless distro .. yeah, you heard that right!

Slow Down, You Punk!

While Raspberry Pi has a pretty decent and complete image of Arch Linux that includes all hardware activation at boot time, no led excluded, pcDuino is kinda "problematic" as any Allwinner platform is because of the not so stable graphic videos ... who cares indeed!

If your goal is to have a dedicated server on the palm of your hand, the graphic whatever is something you won't care at all. I agree this might sound confusing at the beginning, if you are not familiar with linux bootable distros, but hey ... the video is such a pain in your spine I am not sure you really want to know how to fix that, do you?

Install Arch Linux In Allwinner A10 ARM Devices

This post and its welcomeness are kinda the beginning of the story about Arch Linux.
What you think makes sense for an OS ... well, you are already out of sync: Arch is kinda the skeleton of that OS, anything else is your choice/matter/problem/duty, if you want to support that platform.

Even More Annoying

Is not just the fact if you are noob in *nix world you should drop this distro by default since nobody wants to deal with you, the instructions, even if you are part of that world, are kinda crap too.

Thank You André

Despite André post talks about a different A10 board, the used code is clearly something you might find handy, once re-elaborated as such:

In my case I had to:

sh a10.sh /dev/sdb pcduino-bootloader.tar.gz pcduino

after changing things might be different for other A10 boards.

As Result

I've been impressed by polpetta performance, as generic hard drive surfer/common intra-cloud, on a network of 15+ devices: not a glitch over these platforms under hand compiled node.js 11.2 versions.
The average ping for this device in the network is 1.3 milli seconds, which is nothing!
Are you sure your initial web business demands much more as dedicated server?
What if a $40 dollars board plus SD card is all you need, to measure your startup success?

What's With SD Cards

The situation around SD Cards is awkward at least. So here the thing, I haven't spot any difference between an 8GB Extreme Pro SanDisk micro SD Card, and an Ultra 32GB version of the micro usb card ... but more over, I don't think you need such amount of space for any of these devices since even looping through FileSystem tables has a cost I believe your cheap ARM dedicated web server should not take into consideration ;)

Have fun with hints on the web about how to build your first dedicated web host in no more than $100 for years, network a part!

Sunday, April 21, 2013

The __proto__ Comic

© all images from ragefac.es and some from knowyourmeme
Being a comic, sentences are not all real, mostly made up for this post.

TC39

WTF is this shit?!

es-discuss

The community needs it and the de-facto library with stars on github uses that instead of [].push.call(new SimplifiedDOMShit, NodeListResult)

TC39

OK, here what we can spec ... making it configurable, so that shit can be dropped at any time in any module

es-discuss

Community, we are going to spec __proto__ shenanigans all over so that any environment will have a special property able to cause more disasters than what eval did before: you should appreciate!

community

so, proto gonna be standard we don't have to change those 2 lines of code?!

me plus some other

what kind of horrible decision is this?

es-discuss

de-facto is de-facto, people use this, people want this! IE ... who cares !

just me

OK, probably this is just a massive misunderstanding between what's truly needed, and what should be proposed ... let's try to fight back in es-discuss ...

es-discuss

You don't understand, you are late, even if not spec'd yet, you are really late

just me

I gonna show you that JavaScript developers understand this is a no-go and it's bad for the language they use on daily basis as bad, and even worse than boring hasOwnProperty check has been for all these years!

still me

Hello Zepto, somebody thinks we are all bigots unable to make simple changes ... here the patch for you repo, it's green, it works, it has no side effect, it demonstrates we are not bigots, what do you say?

Zepto.js

You White Knight bla, bla, bla ... horse shit bla ...

just me

WTF? I can't even explain myself there, they blocked me ... what should I do?

still just me

... well, I gonna see if at least node.js community, with much more unified environment, would accept a proposal...

still me

Hello node, here a patch that is waiting for a patch in V8 so the patch gonna patch the patch, what do you say?

node.js

We don't extend the language and we don't impose coding standards on our users.

again me

Will you consider at least this .. or that ... ?

again node.js

But we're not going to float a patch that adds this feature to V8

still just me

... well, I gonna see if at least V8 will accept my flag that gonna affect node at startup ...

V8

Well, I don't know if V8 will ever accept my patch (update: they didn't ... if in specs, V8 is ignoring Object.setPrototypeOf while IE11 put it there as native function) but actually there is no reason to not accept it, it does not change anything in core, it does not affect anythign around, is something that if explicitly set, enable something that might be specified like that in ES6 in any case so together with all harmony flags and stuff usable when you run d8 or node, what could possibly go wrong?
Let me hope, at least, this is not a conspiracy against my mental sanity ... and if you star it it might go in before node 1 is released, thank you!

sad thing is, Zepto patch was not affecting Zepto performance or logic, neither was breaking things.
Same thing was for node.js, so I started doubting JS community is able to be proactive when it comes to decisions made somewhere else and for the community.
Developers are pragmatic, they use what's available at that time. If this means create a standard out of it, JavaScript will be anarchy and not a language anymore.
And this, my friend, is unfortunately a specifications circle that is not bringing only good things to the JavaScript as your favorite programming language.

Playing With V8 Native And JavaScript

What my Don Quixote like adventure against __proto__ gave me, if nothing, is a better understanding about how V8 engine internals work and how to bind JavaScript to native and vice-versa.

Please Note

Nobody told me anything I've written in this article is true. These are all assumptions after pushing a patch to V8 and learning by mistakes, compilation errors, and "code around reading", done in a couple of hours so apologies in advance if some term or some concept is not perfectly and deeply explained.
Let's start with this!

JavaScript In JavaScript

This was kinda surprising to me, almost the whole ECMAScript is implemented in JavaScript itself.
In few words, what V8 does is not something like Rhino, reimplementing the whole language via a statically compiled one as Java is in Rhino case, V8 is rather the compiler for the specific ES syntax, following an example ...

JSON In JavaScript

It's funny when we compare in jsperf json2 vs native vs jQuery.json vs json3 etc etc, knowing that V8 native JSON is 90% JavaScript, isn't it?

// just a chunk/example from V8 JSON
function JSONParse(text, reviver) {
  var unfiltered = %ParseJson(TO_STRING_INLINE(text));
  if (IS_SPEC_FUNCTION(reviver)) {
    return Revive({'': unfiltered}, '', reviver);
  } else {
    return unfiltered;
  }
}

Above snippet is simply a compact one with few things non common in Javascript: %PrefixedFunctions(), and UPPERCASE_FUNCTIONS().
These could or could not be bound in any V8 JavaScript files and we can see these JS files are those that will create the JS environment we are going to use but let's see how those special things work, OK?

Interoperation Between C++ And JavaScript

runtime.cc and runtime.h files are dedicated to, as the name suggests, runtime JavaScript calls into C++ world.
The runtime.js files contains instead many JS functions used internally to satisfy ECMAScript specifications but not exposed to the outer world.
Bear in mind latter is not the only file that has not exposed JavaScript, while everything that will go out is defined at bootstrap, as you would expect, per each global context (here why two sandboxes have different native constructors) and you can find it in the bootstrapper.cc file.
Scroll a bit, and you'll see how all known Array, String, Boolean, etc, are initialized, while in array.js you can see how the prototype is created: it's again a mix of native and JavaScript, passing though macros!

How To RUNTIME_FUNCTION

RUNTIME_FUNCTION(
  // return type, for JS interaction
  // will be a MaybeObject* one
  MaybeObject*,

  // the exposed %DoNotExposeProtoSetter()
  // function in the hidden JS world
  // behind the user available scene
  Runtime_DoNotExposeProtoSetter
) {
  // isolate pointer is necessary to access
  // heap and all JS types in C++
  // even true or false are a specific type
  // we cannot return true directly, as example
  // or the type won't match
  NoHandleAllocation ha(isolate);
  // in this case, returning true or false
  // does not require allocation or new objects
  // we can simply use what's already in the heap
  return FLAG_expose_proto_setter ?
    // this is a flag defined at d8 launch,
    // I'll go there too
    isolate->heap()->false_value() :
    isolate->heap()->true_value();
    // returns a JS false or a JS true on
    // %DoNotExposeProtoSetter() invocation
}

Above function is the same I've used for the patch, it does not accept a thing, it checks a generic program flag and returns true or false accordingly.
As every developer with a bit of C background knows, when a function is declared, it should be defined in the file header too, so here the runtime.h declaration:

  /* __proto__ Setter */ \
  F(DoNotExposeProtoSetter, 0, 1) \
  \

F is the common shortcut for RUNTIME_FUNCTION_LIST_ALWAYS_N while the first argument is the length of accepted arguments, -1 if unknown or dynamic.
The second argument seems to be a default for all functions, stick with 1 and things gonna be fine.

Dealing With JS Objects

My patch has a quite simplified signature, if you are aiming to accept and/or return objects, you should do things in a slightly different way, here an example:

// function call :-)
RUNTIME_FUNCTION(MaybeObject*, Runtime_Call) {
  // required to handle the current function scope
  HandleScope scope(isolate);
  // arguments are checked runtime, always
  ASSERT(args.length() >= 2);
  int argc = args.length() - 2;
  CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1);
  // the `this` context :-)
  Object* receiver = args[0];

  // If there are too many arguments,
  // allocate argv via malloc.
  const int argv_small_size = 10;
  // now you know, functions with more than 10 args
  // are slower :-)
  Handle<Object> argv_small_buffer[argv_small_size];
  // ...

  // in case it needs to throw an error ...
  bool threw;
  Handle<JSReceiver> hfun(fun);
  Handle<Object> hreceiver(receiver, isolate);

  // the result, could be undefined too,
  // which is a type indeed
  Handle<Object> result =
      // note, threw passed by reference
      Execution::Call(hfun, hreceiver, argc, argv,
      &threw, true);

  // do not return anything if there was an error
  if (threw) return Failure::Exception();

  // eventually, we got a function.call()
  return *result;
  // don't you feel a bit like "f**k yeah" ?
}

I've removed some extra loop for malloc but basically that's the lifecycle of a JavaScript call invocation.

What About Macros

macros.py contains some (I believe) highly optimized and target specific (x86, x64, arm) function, able to use %_CPlusPlus() functions, and containing most common/used functions across all JavaScript APIs such IS_UNDEFINED(obj).
It also contains many constants used here and there such common date numbers:

const HoursPerDay      = 24;
const MinutesPerHour   = 60;
const SecondsPerMinute = 60;
const msPerSecond      = 1000;
const msPerMinute      = 60000;
const msPerHour        = 3600000;
const msPerDay         = 86400000;
const msPerMonth       = 2592000000;

Dunno you, but I find myself often writing similar variables so I wonder if we should simply have them as public static Date properties ... never mind ...

d8 Options And Flags

To complete my journey into V8, I had to set a --expose-proto-setter flag into d8, which is the command line tool or the dll what you'll have after a successful build of the V8 project.

flag-definitions.h is basically all you need to define a runtime flag providing a decent description that will show up if you d8 --help:

DEFINE_bool(
  // the flag name
  // d8 --expose_proto_setter
  // OR
  // d8 --expose-proto-setter
  // is the same
  expose_proto_setter,
  // the default value
  false,
  // the flag description, better if meaningful ...
  "exposes ObjectSetProto though __proto__ descriptor.set")

In order to access that flag in runtime, do not forget to prefix it as FLAG_expose_proto_setter.
Remember, even a simple value as boolean is cannot be handled like that in JS so check again the RUNTIME_FUNCTION example.

Building V8

There is a V8 page specific for this task, all I can add here is that make x64.release is the fastest way to have a ./out/x64/release/d8 executable and start playing, at least in most common/modern PCs or Macs.

And That's All Folks!

I know it does not seem much, but this article covers:

  1. how to define a launch-time flag for d8
  2. how to interact with C++ bindings for JS code
  3. how to optimize some macro function
  4. how to understand magic V8 JS syntax
  5. how to manipulate, create, change, augment, natives and their prototypes
In few words with these steps anyone could write her/his own version of JavaScript, relying in a robust, extremely fast, and cross platform engine, able to also interact with PHP or other languages.
Bear in mind I am not suggesting anyone out there should start subfragmenting V8, I am sayng that if you need a very specific thing in the environment for a very specific project, you should not be scared by changing what you need and you can also help V8 to be better trying changes directly without just filing bugs: isn't this what Open Source is good for too?

I hope you enjoyed this post, have a nice day!

Friday, April 19, 2013

A Journey To V8 ObjectSetProto Native Function

Update ^_^

whatever story you are interested about in this post, one is that I've proposed a patch to V8 engine (please star it so it gets in faster) to accept a --expose-proto-setter flag at runtime able to expose the proper __proto__ setter so that my node JS pull request could start warning modules using __proto__ instead of Object.setPrototypeOf(target, proto).
What can I say ... open source is beautiful, you can potentially patch everything you want for anything you need ... even behind stubborn, politics, or decisions nobody agreed on :P
Now back to the original post ...


first thing: I write HTML manually in the textarea instead of Markdown, yeah!!!
Why? 'cause nobody on the internet moves fast ... really, no-bloody-body!
so ... back to manual tags writing instead of broken meaningless layout created via magic html editor ... yeeeeeeah!

The Story ...

I know this is getting boring and annoying, and I swear I wish I could say it's the last post but every day there's something more and this story is getting both entertaining and ridiculous!
I gonna tell you how I ended up blocked in Zepto.js repository, and how the rest of reasonable developers are acting instead.
This time, the experiment, is me reporting this story and nothing else. I give you links, I give you facts!

Quick note: they keep telling me I should let it go, but "I cannot sleep anymore" because of this so here my attempt to describe the whole story! Have a coffee, some new tab link to click and dig into, and please, please, keep reading ... also because you might realize ...

It's Not Just Me !

Isaac Z. Schlueter, the man behind node.js, twitted this

@littlecalculist So, why hasn't that been removed in favor of Object.setPrototypeOf? Got a link to discussions, or a shorthand version?

The conversation keeps going and has one conclusion

@izs one-line fix: delete Object.prototype.__proto__; // put this in a module called "raygun-neutralizer" :)

Ha ha ha .. so funny the future of JavaScript comes with a foot-raygun included, don't you think? ^_^

V8 *Is* Based On An Object.setPrototypeOf Equivalent

Breaking news, uh? The internal ObjectSetProto function simply wraps exactly what I've proposed in es-discuss as Object.setPrototypeOf(target, proto).
In V8 internals represented as return %SetPrototype(this, obj);
So here the first thing: the engine of miracles needs such power but we, stupid JavaScripters, how do we dare!

A Poisoned __proto__

Not only this is the less consistent and the most ridiculous property ever introduced in Javascript, this is also intentionally poisoned as broken in Google engine.
These are a couple of quotes in my last attempt to make people reasonable in es-discuss, the first one is from Alex Russell, in this reply:

Assuming "this property" is __proto__, that ship sailed in V8 a long ago and there's zero chance of it ever being removed. It they want to remove it, they can simply fork V8 or ask for a build flag for it.

Not only this is alarming me, as V8 incapable of making changes if considered dangerous as security problems would be, but turned also out that Alex was wrong since today __proto__ is configurable so you can delete it..
.. and all you need to do, after forking, is to build putting a comment here.

set: desc.getSet(),// === ObjectSetProto ? ObjectPoisonProto
                   // : desc.getSet(),

That's it, after that you can have both __proto__ and a usable descriptor of it.
At this point, after a line change in V8 source code, all node.js could do to have a better environment is to do this during the sturtup:

(function(setPrototypeOf){
  if (setPrototypeOf in Object) return;
  var set = Object.getOwnPropertyDescriptor(
    Object.prototype, '__proto__'
  ).set;
  Object.defineProperty(
    Object,
    setPrototypeOf,
    {
      enumerable: false,
      configurable: true,
      value: function setPrototypeOf(target, proto) {
        set.call(target, proto);
        return target;
      }
    }
  );
  // TA-DAAAAAAA!!!
  delete Object.prototype.__proto__;
  // problem solved
}('setPrototypeOf'));

// example
var a = {},
    b = Object.setPrototypeOf({}, a);

a.isPrototypeOf(b); // true!

Above scenario does not look like so hard to implement, isn't it Brendan?
However, another concern was about all npm modules will be broken without considering node has versioning so that no, not a single npm will be broken and updated modules could easily swap to this new API maintaining the environment nice, still fast, and clean!

Moreover, the Object.setPrototypeOf equivalent, called ObjectSetProto and wrapping %SetPrototype(this, proto) in V8, is used to set all __proto__ properties, how cool is that?!

InstallGetterSetter($Object.prototype, "__proto__",
    ObjectGetProto, /* ARE YOU READY???? */ ObjectSetProto);

In few words, my proposal is naturally part of the language ... uh wait, this specific features has been commented as:

an added, _de novo_ API that no one wants, which is an ambient capability on Object, is bad and it won't happen

... it was here!
How would any developer want more power under her/his hands ... don't you dare thinking about it!

A Bit More Background

Brendan Eich excellently summarized with all links the story behind this property.
In few words, this property has been discussed and nobody wanted it.
They better preferred to quickly, dirty, spec it as configurable, at least, and as non present in Object.create(null) objects, so that finally some project could directly get rid of it and drop it via
delete Object.prototype.__proto__;
as mentioned before.
Moreover, this is another quote from Brendan the same es-discuss post:

Because @izs tweeted something you think Node is going to fork V8? Get real!

... So I Tried To Get Real ...

The change required to make that possible in V8 is a 10 seconds task, network push a part ... anyway ...

In Isaac slides you can read at page 26 that:

not developing a language removes a huge burden. Let TC-39 and V8 fight those battles for us!

So I didn't even bother him with this discussion ... I mean, he's doing the right thing: let other specialists solve problems for you so you can focus on something else .. right ?
The reality is that even if I send that patch to V8, they will not accept it, not even if Microsoft will agree as the right direction to promote a better standard!
The parody about this de-facto utopia is that all current IE browsers do not support __proto__.
IE is desperate to be part of the not finalized yet spec, and this is probably why the leaked version 11 shows __proto__ shenanigans in the wild .. and those specs are not final ...!

The Very Sad Result Of Thomas Fuchs Reaction

Since I've been fighting, blogging, and discussing this problem for months, and since many times they came back to me or others saying that:

It wasn't Node.js that drove that -- it was the "mobile (iOS WebKit first) web" that wanted __proto__ due to libraries such as Zepto.

So I've tried to reply at some point like:

I think zepto is using that to modify runtime NodeList results after querySelectorAll but in any case it was not me saying that __proto__ isn't used already...

The discussion goes on and on until I think one action is better than many words, right?

What Allen Wirfs-Brock Said

The good @awbjs, who writes ECMAScript Specifications, took kindly some of his time to reply to my post entitled Yet Another Reason To Drop __proto__.
This is his comment:

__proto__ wasn't TC39's mistake and everybody who participates on TC39 is aware of how terrible it is.
...
If you want to eliminate __proto__ you will have to eliminate its usage. Write a shim for Object.setPrototypeOf:
...
Then evangelize web developers like crazy to update all their existing deployed code to use this shim instead of directly using __proto__.
...
Good luck (seriously)

Challenge Accepted! ... so here the big drama ... that Allen "Good luck (seriously)" "benediction" transpiled in my mind as:

What the hack ... what does he mean with "goog luck (seriusly)", that JavaScript community is made by passive bigot developers that cannot change simple things?
Of course we are as good developers as those you can find in any other language ... let me demonstrate it describing the situation in a pull request commit with all tests greens and zero side effects!

The Community Reaction

Sure that once described the problem in Zepto.js repository, and I swear never a Zepto.js developer I know ever showed up in es-discuss or my blog, I've simply committed a patch that was tests approved and changing two lines of code promoting Object.setPrototypeOf instead of __proto__.
Long story short:

Here the Thomas rant, accusing me of trolling, after (kinda obviously) him not being aware of anything I've been written 'till now:

It's not about not agreeing with you. It's the form of how you imply or directly state that we're, I quote, "passive bigots" and that somehow __proto__ is insecure and "may" be removed and other weasel words that imply that we don't know what we're doing and you're a white knight to rescue us from ourselves. No, thank you. Please troll someone else.

Now, whatever Thomas thought was good to demonstrate with his reaction, which is simply, in my opinion, "the ball here is mine, nobody plays if I'm pissed off" ... since he decided to block me from the whole repository, all I could do is to write an answer in the same gist that is describing the current madness behind that property.
Really Thomas ... what can I say, congrats!

Thomas, Not Flex Box Again, Please!

So if IE will spec a document that's still a draft, and just to make for the broken web __proto__ can create, don't blame anyone if IE will implement that as broken as it is now almost spec'd!
Version 9 won't have it and neither 10, the current one in 2013!
If Zepto.js decides IE is not a target browser, this does not mean every library should decide the same!
Isn't one of our duty, as Web developers, to make the Web available to as many people as possible?
jQuery released today version 2 and IE9 and IE10 are supported, as easy as that .. or maybe that was the reason you were so nervous?
If Zepto wants to shoot in its foot saying __proto__ or nothing .. deal with that, you have less targets there and of course, you know that!
I mean, you better support IE9 and 10 in both Desktop and mobile for a while in any case, don't you?
So since this is the best moment to drop that mistake and go for a better, less obtrusive, pattern, why wouldn't you?

Update On The Repository

I am still blocked as if I've been trolling Zepto since ever but at least now Thomas rant is gone and there is a statement from Mislav Marohnić there I cannot comment but that makes sense for that library, except when it comes to talking about standards, since __proto__ is not even standard yet:

We generally don't pull contributions that don't improve anything. If, for instance, IE implemented the standard API but doesn't support __proto__, we would pull this. But we don't gain anything tangible with this change. We only believe in standards if they actually result in some benefit. We don't know what the "future of JS" is going to be, so we're making this neat little library that works in the present. When the future of JS arrives, I'm sure we'll adapt accordingly.

Revelation: Why Is Dropping Proto So Important To Me!!!

First of all, as I've said, is not just me ...
Secondly, __proto__ cannot be polyfilled while a modern Object.setPrototypeOf method could be much easier and consistently polyfilled across current browsers.
ES6 specifications aren't going out anny time soon so it's not too late to put a simple method out there able to make the future a bit brighter .. for node.js, for quickly updated browsers, for JavaScript, your favorite programming language.
You don't want too much power in a function? You shouldn't care since the language behind that function has it, so you are just thinking you should be limited, no matter how good or powerful or evil the function will be.
Thanks for reading until here, really appreciated!

Wednesday, April 17, 2013

How About KISS vs YAGNI ?

I know this might sound silly but I keep having fun writing stuff here
since I've switched to mark down text :P


### Is This A Natural Conflict ?
If you are wondering what I am talking about I have a very simple example:
the Linux world!  

In the specific case, file system operations!

```
# copy a file
cp file1.txt fle2.txt

# remove a file
rm file1.txt
```


### That's A Move File !
Yes, is really that simple! When you move a file you are sure that file has been copied,
it has the new name or the same, if in a different folder, and you can remove the first one.  
OK, OK, if you are a Windows user you might have experienced some lost file in the past
due accidents during the copy such "_not enough space_" I got it, but what if that's because you've been too KISS and not YAGNI?  


### The Software YAGNI Approach
If you can obtain that in a quite simple way, no need to complicate things around.


### The KISS Approach
If everything I need is more than an action, I am not going to like that.  
KISS is also used as concept behind APIs and final, production ready, products.


### The Reality
KISS, however, is probably the most difficult thing ever in programming languages ... 
guess why? There's no such thing as **simple** when it come to programming.  

Actually, the most user-friendly interfaces and interactions, are probably also
the most over engineered so ... you see?


### As Summary
I've no idea if these two approaches, both my favorites, could be confusing and in collision.  
What I know, is that while I was writing this post I've been thinking all the time how to represent
bloody acronyms in Markdown.  
  

It came out that basing my experience with KISS and YAGNI, the best solution I had in mind
was under everybody nose as **JSON**:
`{"KISS":"Keep It Simple, Stupid"}` and `{"YAGNI":"You Ain't Gonna Need It"}`  

Both have never been mentioned in the [Markdown famous post](http://daringfireball.net/projects/markdown/syntax), something I'd love to contribute updating it!

Monday, April 15, 2013

Can Deal With Markdown In RSS Readers ?

I've spent some time trying to solve the
[tinydown](https://github.com/WebReflection/tinydown#tinydown)
runtime blogspot parsing and this is the current status:

  1. desktop browsers are fine
  2. mobile browsers are now fine too
  3. textual browsers lynx like are wonderful now!
  4. browsers without CSS are just fine
  5. browsers without JS are kinda fine too
  6. browsers without CSS and JS are almost fine


### Your RSS Reader
Most likely, what you are experiencing is something similar to point 5 or,
in the worst case scenario, point 6 of above list.

Being markdown easy to read as any plain text or book
you are familiar with, can you cope with that for RSS readers?


### As Experiment
Please give you some times to see if this work before answering.

I realy don't want to piss off my followers so the last option would be
to revert all my changes done in blogger
(or eventually host my blog in my own space)

One thing I am doing different now, is to preserve a decent amount
of columns before I go into a new line so readers unable
to adopt a `white-space: pre-wrap;` like rendering for feeds
should not be that disturbed anymore ...

If this is going to work, I think everyone could be happy
about the fact not only you can blog on the cloud without a host,
but what you write can be compatible with emails and everything
that is not HTML enabled ... all plain text, as universal way to
write a human friendly formatted document.

What do you think? Thanks for your patience!

Sunday, April 14, 2013

Flight Mixins Are Awesome!

OK, OK, probably is just that I cannot wait to start writing stuff with [tinydown](https://github.com/WebReflection/tinydown#tinydown) but I tweeted about this after last #FlightNight and @angustweets demo ... so here what is behind [Flight](http://twitter.github.io/flight/) mixins choice.


### The Basics

JavaScript polymorphism is probably one of the best things you can find out there.

Not kidding, the flexibility that this language offers when it comes to context injection and runtime class definition is simply amazing, as simple, and amazing, is this idea:

```js
// most basic example
function enriched() {
  this.method = function () {
    // do stuff
  };
}
```

Most common books and online documents usually describe above example as a _constructor with privileged methods_.

Well, that's actually what you get if you `var obj = new enriched();` but that's just one story.
Flight uses a different story, offering alternative methods with better semantics but basically going down to:

```js
enriched.call(object);
```


### Mixins Baby!

Using above pattern we can enrich any sort of object with the extra benefit of having a private scope the moment we invoke once the function.
This gives us the opportunity to pass arguments or simply have some private, shared in case of a prototype, variable too.

```js
// with arguments and private variables
var Mixin = function Mixin(arg0, argN) {

  // private variables
  var scoped = {};

  // privileged methods
  this.method = function method() {
    return scoped;
  };

  // default properties or initialization
  this.prop = arg0 || 'default';
  this.other = argN;

};

// ========================================

// as Singleton
var singleton = new Mixin;
singleton.method(); // object
singleton.prop; // default
singleton.other; // undefined

// as prototype with defaults
function Class() {}
Mixin.call(Class.prototype, 'a', 'b');

var instance1 = new Class,
    instance2 = new Class;

instance1.method(); // object
instance2.method(); // same object

// same methods
instance1.method === instance2.method; // true

// and same object
instance1.method() === instance2.method(); // true

instance1.prop;  // a
instance1.other; // b
instance2.prop;  // a
instance2.other; // b
```

I have realized how powerful is this simply considering the same approach with prototypes rather than each objects, where methods are of course created per each invokation of the mixin, but that would be indeed absolutely meant and expected.

What I am saying, is that if you are worried about too many closures and functions generated per each mixin, and you believe your mixin does not need any initialization and methods can be used anywhere without needing a private scope, here all you can do to follow same pattern and save a bit of memory:

```js
var Mixin = function(){
  // created once and never again
  function method1(){}
  function method2(){}
  function methodN(){}
  return function () {
    this.method1 = method1;
    this.method2 = method2;
    this.methodN = methodN;
  };
}();
```

I guess that's it, right? But what if we need some sort of initialization per each mixin?

  
### Initializing A Mixing

There could be things we need to do to ensure the mixin will work as expected per each instance but if we want to coexist out there in the wild, we cannot name methods like `.init()` because of the name clashing if more than a mixin needs to be initialized ... are you following?

One possible solution that came into my mind is to prefix, with `init` the method, and use the mixin name as suffix.

```js
// defaults plus init
var Mixin = function Mixin(dflt0, dfltN) {

  // private variables
  var scoped = {};

  // privileged methods
  this.method = function method() {
    return scoped;
  };

  // avoid multiple mixins name clashing
  // prefix eventual initialization
  // with 'init' plus mixinname
  this.initMixin = function (arg0, argN) {
    this.prop = arg0 || dflt0 || 'default';
    this.other = argN || dfltN;
  };

};
```

If we follow this approach, we can initialize any mixin we want at any time, e.g.:

```js
// explicit initialization
function Class(arg0, argN) {
  this.initMixin(arg0, argN);
}
Mixin.call(Class.prototype, 'a', 'b');

var instance1 = new Class,
    instance2 = new Class('different');

instance1.prop;  // a
instance2.prop;  // different
instance1.other; // b
instance2.other; // b
```

Per each instance we can then enrich the constructor so that every mixin that needs to be initialized at that time can be simply call the non clashing method.


#### Some Bad Idea You might Have

Well, it is common in JS to think about `for/in` loops and stuff so that if we know a prefix we can automate tasks ... but in this case I strongly discourage this approach unless you are not 100% sure all mixins initializations support same signature.

```js
// *DONT* automatic mixin initialization
function Class() {
  for (var key in this) {
    if (key.slice(0, 4) === 'init') {
      this[key]();
      // or
      this[key].apply(this, arguments);
    }
  }
}
```

In few words, using above technique means coupling mixins with a specific, probably unknown in advance, class signature so it is strongly discouraged.

Sticking with an explicit mixin initialization is not only faster but able to create any sort of mixin signature.


### Events To The Rescue

As @kpk reminds me, [Flight is event based](https://twitter.com/kpk/status/323272363053551616) so there's also an easy way to do more after all mixins initialization: `this.after('initialize', fn);`


### As Summary

This is only one part of [Flight](http://twitter.github.io/flight/) where [**performance**](http://jsperf.com/mixin-fun/31) were strongly considered for all old and new browsers and this works.

In an era were many developers are looking for better classes this framework came out with such simple and powerful solution I can't believe I would like to have anything more than this for real apps!

Enjoy the Flight philosophy and embrace powerful simplicity any time you _A-HA_ it ;)

Saturday, April 13, 2013

tinydown test

OK ladies & gentlemen, time to test [tinydown](https://github.com/WebReflection/tinydown#tinydown) for real.

### What's New
Well, first of all there are [35 tests](http://webreflection.github.io/tinydown/test/) with nice and/or screwed input and an expected output to complete the library so that any improvement or change will not compromise what's already working.

The second thing is ... **I am using tinydown now**!

You can check the source page of this post and see that all it contains is markdown.

### What's Different
There at least two things different:

  * it supports more inside the image markup, such youtube and gists
  * it supports twitter handlers, like @WebReflection
  * even if so damn small, like less _than 2Kb_ minzipped, it supports nested blockquotes and lists

`inline code` is also available together with triple tick syntax and/or tab and spaces so that

    var code = 'can be be written multiline';
    function alCodeIsPreserved() {
      with(out) {
        alert('problems');
      }
    }

I also implemented only here the highlighter for js so

```js
var code = this.should();

code.look('gorgeous');
```

### What's Missing
I don't know yet, I think almost everything I need for blogging should be there.

The library is compatible with both _node.js_ and web browsers, of course, and if tests are green you should good to use it runtime in your blog too or any other place you think.

Last but not least, you can **test everything** you want in [this page](http://webreflection.github.io/tinydown/test/test.html live test) and eventually file bugs copying the generated link with your content so it will be straight forward to see what's broken, the why and the how.  
  
Have fun!

Thursday, April 11, 2013

Writing Markdown In Blogger

Update

Added tests and support for nested blocks and lists plus youtube video and gists instead of just images.
Here, have a look at tinydown, compatible with both node and web.
Something I've been thinking about since last year JS1K contest ... what if I could just write mark down on internet and let crawlers and bots do the math while I just write all I need to?

tinydown and CloudReflection

This is basically all it took to create a markdown blogger enabled service as CloudReflection is.
That's correct, if I edit that post the text I gonna deal with is this one:
Isn't a tiny markdown parser lovely ?
=====================================

A markdown is an _easy to read and quite easy to parse_ syntax, ideal for documents
that could be understood by human, and easily converted by machines.

You are reading markdown now!
-----------------------------
This blogpost is generated on the fly via the proposed script.  
Here the code **example** used for this page:

    this.onload = function () {
      document.body.innerHTML = tinydown(
        document.body.textContent
      );
    };

You can find a very nice guide about [how to markdown here](http://daringfireball.net/projects/markdown/syntax "markdown style guide").

### What is supported ?
  * headers with = or - notation
  * headers with # notation
  * blockquotes and nested blockquotes
  * ordered and unordered lists
  * images with optional alt ant title
  * inline links with arbitrary title
  * <em> via single asterisks/underscore, or double for <strong> tag
  * inline `code` via `` ` `` backtick

### What is not supported ? ###
  * paragraphs are missings
  * nested lists and nested markdown inside lists
  * links with references and/or id
  * raw html is not recognized, validated, parsed

> and just to demonstrate it works
> > this is a nested blockquote example :-)
> have a lovely day

- - -
© WebReflection
This is basically the same text I've used in the original demo page, except links and images are now finalyl supported.
That is going to look exactly the same way you look at it in the following iframe:

What Else On Blogger Side

So I had to include a couple of scripts:
  1. <script src='http://webreflection.github.io/tinydown/test/build/tinydown.js'/>
  2. <script src='http://webreflection.github.io/tinydown/test/build/onstuff.js'/>
While the first one is the actual tinydown parser, the second one is just some logic to parse the right content at the right time.
If you want to play with npm install tinydown parser consider that's just a function and is not as complet eas any other fully compatible markdown parsers ... it just gives me basically everything I need to write my technical posts on blogger ... can I ask anything more? I don't think so!
Bear in mind you should not use same scripts with github external repository file in your production code/blog ... just follow these direction, and stay tuned with the tiny down repository.