Showing posts with label deployment. Show all posts
Showing posts with label deployment. Show all posts

Tuesday, April 8, 2014

Still Almost: JS Interop in Polymer.dart


Up today, I try to finish my efforts to get JavaScript Polymer elements working inside Polymer.dart elements.

As noted last night, the 0.10 release of Polymer.dart, which currently only works with the dev channel / 1.3 version of Dart, promises to make this possible. After last night, I actually seem to have this nearly working. Of course “nearly working” is another way of saying not working at all, so let's see if I can address that.

I continue to work with my <x-pizza> pizza builder element that will star in several Patterns in Polymer chapters. This element makes use of a second element under the covers—<x-pizza-toppings>—to enable a hungry pizza buyer to customize his/her pizza:



Since Patterns in Polymer comes in two flavors (Dart and JavaScript), I have two different flavors of both <x-pizza> and x-pizza-toppings>. To experiment with JavaScript interoperability from Dart Polymer elements, I am trying to use the JavaScript version of <x-pizza-toppings> from the Dart version of <x-pizza>.

The last error that I saw last night turns out to be fairly easy to solve. To access those “model” properties from my JavaScript element, I need to use dart:js to grab a Dart proxy to a browser object:
updatePizzaState([_]) {
    pizzaState = JSON.encode({
      'firstHalfToppings': new JsObject.fromBrowserObject($['firstHalfToppings'])['model'],
      'secondHalfToppings': new JsObject.fromBrowserObject($['secondHalfToppings'])['model'],
      'wholeToppings': new JsObject.fromBrowserObject($['wholeToppings'])['model']
    });
  }


Without the JsObject.fromBrowserObject wrapper, I would get invalid property errors when trying to access the “model” property of these child-JavaScript objects.

That leaves me with another error that is not nearly as obvious:
Uncaught TypeError: undefined is not a function polymer-expressions.js:552
(anonymous function) polymer-expressions.js:552
Through trial an error (the Dartium debugger still leaves much to be desired), I eventually track it down to a fairly innocuous on-click bound method in the JavaScript <x-pizza-toppings> element:
<polymer-element name="x-pizza-toppings" attributes="ingredients name">
  <template>
    <!-- ... -->
    <p>
      <button id="add" on-click="{{add}}" type="button" class="btn btn-default">
        Add {{name}}
      </button>
    </p>
  </template>
  <script>Polymer('x-pizza-toppings', {
  // ...
  add: function() {
    this.model.push(this.current);
    this.current = '';
  },
  // ...
});
</script>
</polymer-element>
When the pizza buyer clicks the Add button, whatever current ingredient is selected is then added to the internal model. Only it isn't. At least not when used in Polymer.dart. I am unable to solve this tonight, but I do determine that, if I build this in a JavaScript element (instead accessing it in Dartium), I am able to click the button to access the add() method. So it would seem that something is missing from the Dart implementation.

Bummer. This has the feel of a rabbit hole I would rather not travel down at this time, but I will sleep on it to see if I can come up with a better way to investigate. If not, there is still one thing that I do not have working in the compiled-to-JavaScript version of the Dart+JavaScript interop experiment: my ingredients list, which comes from <x-pizza> is not being bound properly inside <x-pizza-toppings>. Hopefully I can solve that mystery tomorrow.


Day #28

Monday, April 7, 2014

Kicking the Tires on Polymer.dart 0.10 (and js-interop)


Curiosity got the better of me yesterday as I wondered if I might use a Vulcanized JavaScript Polymer element inside a Polymer.dart. It couldn't—but maybe it will be able to...

The CHANGELOG for the 0.10-pre release of Polymer.dart includes this nifty little tidbit:
* Interop with polymer-js elements now works.
That makes it seem like the next release of Polymer.dart will support it. So, letting my curiosity drive me yet again, I will give it a go tonight. First up, I need to replace the 0.9 dependency in my application's pubspec.yaml package configuration. It is currently being locked to 0.9 in the resulting pubspec.lock:
# ...
  polymer:
    description: polymer
    source: hosted
    version: "0.9.5"
# ...
So, back in the application's pubspec.yaml, I try to limit the dependency to 0.10.0-pre.7 or higher:
name: deployment_experiment
# ...
dependencies:
  polymer: ">=0.10.0-pre.7"
# ...
That is, of course a non-started with the current 1.2 version of Dart:
➜  dart git:(master) ✗ pub update    
Resolving dependencies........
Package polymer requires SDK version >=1.3.0-dev.5.0 <2.0.0 but the current SDK is 1.2.0
No worries, I should have been using the prerelease all along and especially should be using it now that it is nearing the release.

So I grab the latest dev channel release of Dart:
➜  Downloads  wget http://storage.googleapis.com/dart-archive/channels/dev/release/latest/editor/darteditor-linux-x64.zip
➜  Downloads  cd ~/local
➜  local  unzip ~/Downloads/darteditor-linux-x64.zip
That expands into the dart directory. I have various locations under $HOME/local/dart in my $PATH:
PATH=$HOME/local/dart/chromium:$HOME/local/dart/content_shell:$HOME/local/dart/dart-sdk/bin:$PATH
Some of those come directly from the ZIP file, others I need to massage or outright download. I complete the installation by downloading and installing (per my $PATH) the content_shell executable for running headless tests:
➜  local  cd dart/
➜  dart  ./chromium/download_contentshell.sh
Downloading http://dartlang.org/editor/update/channels/dev/34756/dartium/content_shell-linux-x64-release.zip to content_shell-linux-x64-release.zip.
Download finished.
➜  dart  mv drt-lucid64-full-dev-34756.0 content_shell
Then I replace the regular Dartium with the debug version:
➜  dart  ./chromium/download_dartium_debug.sh
Downloading http://dartlang.org/editor/update/channels/dev/34756/dartium/dartium-linux-x64-debug.zip to dartium-linux-x64-debug.zip.
Download finished.
➜  dart  unzip dartium-linux-x64-debug.zip 
➜  dart  mv chromium chromium.orig                             
➜  dart  mv dartium-lucid64-debug-dev-34756.0 chromium
Now I am ready to roll. Back in my application, I again pub update to get the latest Polymer.dart:
➜  dart git:(master) ✗ pub update
...
These packages are no longer being depended on:
- custom_element 0.9.2
- html_import 0.9.0
- mutation_observer 0.9.0
- shadow_dom 0.9.2
- unmodifiable_collection 0.9.2+1
Downloading polymer 0.10.0-pre.8...
...
Changed 17 dependencies!
I have to make a few minor changes to the overall application to work with 0.10. First, there is no more initPolymer() (yay!). Instead, I now need to import a Polymer HTML file similar to how it is done in JavaScript-land:
    <link rel="import" href="packages/polymer/polymer.html">
    <link rel="import" href="packages/deployment_experiment/elements/x-pizza.html">
In each of the Polymer template files, I also have to modify the mime-type of the backing script:
<link rel="import" href="x-pizza-toppings.html">
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
  <script type="application/dart;component=1" src="x_pizza.dart"></script>
</polymer-element>
The component=1 parameter is an uglyish way to signal to the Dart VM in the browser that it should not run this script in a separate isolate—that it should be run as part of the same isolate used by other Polymer elements. After making those changes to the Polymer.dart code, my Polymer is working perfectly again. Now to the task at hand. Instead of using the Dart version of the <x-pizza-toppings> Polymer element, I want to use last night's Vulcanized JavaScript version.

So I swap the import from the template definition file of the containing <x-pizza> element:
<!-- <link rel="import" href="x-pizza-toppings.html"> -->
<link rel="import" href="vulcanized.html">
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
  <script type="application/dart;component=1" src="x_pizza.dart"></script>
</polymer-element>
Unfortunately, when I fire this up in Dartium, I get errors:
Uncaught Possible attempt to load Polymer
--
Exception: NoSuchMethodError: method not found: 'whenPolymerReady'
Receiver: Instance of 'JsFunction'
Arguments: [Closure: () => dynamic]
When I vulcanized this polymer, I did so by inlining all of the backing JavaScript, including the platform and polymer libraries. After removing the inlined Polymer library code from vulcanized.html, I am a little closer. The Dart <x-pizza> element now displays as does the template from the 3 JavaScript <x-pizza-toppings> elements:



Some of the bindings between the elements are even working—the button names in the JavaScript <x-pizza-toppings> elements are bound variables from the Dart <x-pizza>. Unfortunately, the ingredient list is not bound properly, nor are the events that transfer information.

Looking through some of the js-interop tests in the Polymer.dart project, it seems that some js-interop method calling from Dart may be in order. I will investigate that further tomorrow and give it a try in code tomorrow night. For now, just getting this far will be enough progress for one day.


Day #27

Sunday, April 6, 2014

Vulcanize Inline… Into Polymer.dart?


Up tonight, a bit of Polymer deployment sanity checking. Does the approach that I have taken in polymer-one-script for deployment of Polymer.dart elements make sense?

I have enjoyed exploring the issue of deploying Dart Polymer element the past few days, but I begin to realize that it may not wind up being relevant in Patterns in Polymer. In that book, I am trying to find patterns and approaches that work well in both the JavaScript and Dart versions of the project. That is, I hope to identify patterns that transcend individual language implementations and instead cut to the core of what it means to be a Polymer element.

Herein lies my problem: deployment of JavaScript Polymers is trivial thanks to Vulcanize. I cannot very well write a “transcendent” chapter in the two different versions of the book where it takes me 20 pages to describe a thing in one language and one paragraph in the other. That is hardly transcendent.

Still, it seems worth taking a look. The default vulcanize command indeed does not produce what I have polymer-one-script doing in Dart. It produces a deployable HTML description of the element with external <script> references:
➜  js git:(master) ✗ vulcanize elements/x-pizza.html       
Default output to vulcanized.html in the input directory.
➜  js git:(master) ✗ grep src elements/vulcanized.html 
<script src="../bower_components/polymer/polymer.js"></script>
  <script src="x_pizza_toppings.js"></script>
  <script src="x_pizza.js"></script>
It does, however, support the --inline option to accomplish more or less (actually much less size-wise) the same thing that polymer-one-script does:
➜  js git:(master) ✗ vulcanize --inline elements/x-pizza.html
Default output to vulcanized.html in the input directory.
➜  js git:(master) ✗ grep src elements/vulcanized.html       
➜  js git:(master) ✗ 
Actually, that is not quite the same thing that polymer-one-script does. My script produces a JavaScript source file for the element instead of an HTML description of the element with the code embedded in it. Ah well, I am not going to sweat that difference much.

With that question answered, I ought to call it a night, but… Darn it I am curious about something else now. The example on which I have been experimenting, <x-pizza>, is actually comprised of two elements: the parent <x-pizza> and several child <x-pizza-toppings> elements that enable the discerning pizza buyer to add toppings:



This is the same in both the Dart and JavaScript versions of my element. I wonder, can I create a single, inline version of the <x-pizza-toppings> element in JavaScript and use it in Dart? There is one way to find out!
➜  js git:(master) ✗ vulcanize --inline elements/x-pizza-toppings.html 
Default output to vulcanized.html in the input directory.
➜  js git:(master) ✗ cd ../dart      
➜  dart git:(master) ✗ cp ../js/elements/vulcanized.html lib/elements
Giving this a try with the pub serve built-in web server and Dartium, I find… an error:
Uncaught ReferenceError: PolymerExpressions is not defined
That would seem to indicate that I need some lovely JavaScript libraries, which make me think that this is going to wind up being prohibitively hard. Still, I give it a shot by copying the Bower configuration from my JavaScript sample and installing Polymer.js into my Polymer.dart application:
➜  web git:(master) ✗ cp ../../js/bower.json .
➜  web git:(master) ✗ bower install
After adding that to my containing page, however. I still get failures. I add the platform as:
<script src="bower_components/platform/platform.js"></script>
That ought to load the core of Polymer.JS—enough, at least, to define PolymerExpressions and anything else needed. Unfortunately, this seems to interact very badly with the JavaScript coming from pub build as I get crazy long error messages:
TypeError {stack: "TypeError: Cannot read property 'getAttribute' of …0/bower_components/platform/platform.js:35:22390)", message: "Cannot read property 'getAttribute' of undefined"}
 "TypeError: Cannot read property 'getAttribute' of undefined
    at eval [as getAttribute] (eval at getMethod (http://localhost:8080/packages/shadow_dom/shadow_dom.debug.js:1796:49), <anonymous>:2:17)
    at d.createdCallback (http://localhost:8080/index.html:85:22502)
    at k (http://localhost:8080/bower_components/platform/platform.js:35:27681)
    at h (http://localhost:8080/bower_components/platform/platform.js:35:27258)
    at Object.s [as upgrade] (http://localhost:8080/bower_components/platform/platform.js:35:28650)
    at h (http://localhost:8080/bower_components/platform/platform.js:35:22897)
    at e (http://localhost:8080/bower_components/platform/platform.js:35:22605)
    at http://localhost:8080/bower_components/platform/platform.js:35:22667
    at http://localhost:8080/bower_components/platform/platform.js:35:22555
    at b (http://localhost:8080/bower_components/platform/platform.js:35:22390)" shadow_dom.debug.js:2816
TypeError {stack: "TypeError: Cannot read property 'polymerShadowRoot…0/bower_components/platform/platform.js:35:25116)", message: "Cannot read property 'polymerShadowRoot_' of undefined"}
 "TypeError: Cannot read property 'polymerShadowRoot_' of undefined
    at shadowRoot (http://localhost:8080/packages/shadow_dom/shadow_dom.debug.js:4345:23)
    at c (http://localhost:8080/bower_components/platform/platform.js:35:22474)
    at http://localhost:8080/bower_components/platform/platform.js:35:22568
    at b (http://localhost:8080/bower_components/platform/platform.js:35:22390)
    at b (http://localhost:8080/bower_components/platform/platform.js:35:22403)
    at b (http://localhost:8080/bower_components/platform/platform.js:35:22403)
    at d (http://localhost:8080/bower_components/platform/platform.js:35:22532)
    at f (http://localhost:8080/bower_components/platform/platform.js:35:22644)
    at g (http://localhost:8080/bower_components/platform/platform.js:35:22711)
    at Object.y [as upgradeDocument] (http://localhost:8080/bower_components/platform/platform.js:35:25116)"
I suppose I should have left well enough alone, but this seems like something that might be nice. I may give this another try tomorrow—with the dev channel version of Dart and Polymer.dart.


Day #26

Saturday, April 5, 2014

A Pub Package for Building a Single JS from Polymer.dart


Up tonight: extracting a command-line Dart script from my application into a Dart Pub package. Hopefully I made the script general enough last night.

Aside from missing generalizations, the challenge for this is how best to bundle the script in a pub package. Dart Pub is great for managing dependencies and smoke testing applications, but it does not quite have a good solution for scripts. Also, I have no idea how to write a script for Windows machines (but that's a task for another day). In my application, I have the script in the bin directory, which makes sense and is the Dart Pub standard location. The problem with that is that the bin directory of a package is not easily reached from an installed package.

In fact, the only thing that is easy to reach is the lib directory, so I start with that. I create a new git repository for my package, give it a reasonable starting point for a pubspec.yaml configuration, and create a lib directory to hold the script:
➜  repos  mkdir polymer-one-script
➜  repos  cd !$
➜  repos  cd polymer-one-script
➜  polymer-one-script  git init .
Initialized empty Git repository in /home/chris/repos/polymer-one-script/.git/
➜  polymer-one-script git:(master) mkdir lib
➜  polymer-one-script git:(master) cp ~/repos/polymer-book/play/deployment/dart/pubspec.yaml .
➜  polymer-one-script git:(master) ✗ cp ~/repos/polymer-book/play/deployment/dart/bin/reduce.dart lib/
➜  polymer-one-script git:(master) ✗ chmod 755 lib/reduce.dart 
I edit the pubspec.yaml of my new package:
name: polymer_one_script
dependencies:
  yaml: any
dev_dependencies:
  scheduled_test: any
With that, I am ready to remove last night's version of the script from my application and replace it with my new packaged script. I start by referencing the local package in my application's pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
  polymer_one_script:
    path: /home/chris/repos/polymer-one-script
transformers:
- polymer:
    entry_points:
      - web/index.html
      - web/index2.html
Dart pub really is pretty awesome at packaging—including helping developers to build new packages. With the above path setting, pub build links to my local pub package directly where I am developing it:
➜  dart git:(master) ✗ ls -l packages/polymer_one_script 
lrwxrwxrwx 1 chris chris 40 Apr  5 21:59 packages/polymer_one_script -> /home/chris/repos/polymer-one-script/lib
I cannot run this packaged script directly from this location because the packages that it needs are not available in its installation location:
➜  dart git:(master) ✗ ./packages/polymer_one_script/reduce.dart
Unable to open file: /home/chris/repos/polymer-book/play/deployment/dart/packages/polymer_one_script/packages/yaml/yaml.dart'file:///home/chris/repos/polymer-book/play/deployment/dart/packages/polymer_one_script/reduce.dart': error: line 4 pos 1: library handler failed
import 'package:yaml/yaml.dart';
^
Instead, if I copy or link the packaged script into my application's bin directory, then it works:
➜  dart git:(master) ✗ ln -s packages/polymer_one_script/reduce.dart bin/
➜  dart git:(master) ✗ ./bin/reduce.dart
[web/index.html, web/index2.html]
And that does the trick. I'll upload a package to Pub shortly.

Update: and done.



Day #25

Friday, April 4, 2014

Generalizing a Single Script Polymer.dart Solution


I have a Dart script to combine JavaScript generated from a Polymer.dart element. I would like to see if I can generalize it a bit.

I failed in my attempts to make a single JS file for Polymer.dart elements from a Dart Pub transformer. This means that I cannot generate a single JS file with a simple pub build. So instead, I aim for he next best thing: pub build; polymer-reduce. Hopefully this will mostly involve removing hard-coded values. But first...

I need to parse my project's pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
The polymer transformer, which is part of Polymer.dart, uses the entry_points setting to decide which pages to inspect for Polymer elements in need of transforming. Based on the name, I would guess that entry_points can be more than one page.

Anyhow, first things first, I need to be able to parse the YAML in pubspec.yaml, so I add the YAML library to… pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
  yaml: any
transformers:
- polymer:
    entry_points: web/index.html
I also need to add this to last night's reduce.dart script:
#!/usr/bin/env dart

import 'dart:io';
import 'package:yaml/yaml.dart';

main() {
  var pubspecYaml = new File('pubspec.yaml').readAsStringSync();
  var pubspec = loadYaml(pubspecYaml);
  // ...
}
The transformers entry in pubspec.yaml is an ugly beast. It is a list of single key maps, which means that I need to filter the transformers list for entries where the single key is "polymer", then for each, I need to run last night's transform. It might be an ugly data structure, but Dart's built-in iterators take care of it nicely:
main() {
  var pubspecYaml = new File('pubspec.yaml').readAsStringSync();
  var pubspec = loadYaml(pubspecYaml);

  // var filename = 'web/index.html';
  pubspec['transformers'].
    where((t) => t.keys.length == 1 && t.keys.first == 'polymer').
    forEach((t){
      var filename = t['polymer']['entry_points'];
      new PolymerScriptReducer(filename).reduce();
    });
}
The PolymerScriptReducer class is a simple reworking of last night's procedural code into a procedural class that can run against multiple entries.

That turns out to be the most complex bit of the conversion. I rework last night's placement of reduced JavaScript and the HTML that uses it, which winds up simplifying things quite a bit. I had been creating the reduced files into a separate deploy sub-directory. Since this is meant to be part of pub build, I place the reduced files directly in the build directory generated by pub build.

The only other question that I would like answered is—what happens if multiple HTML files are listed as entry_points?
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
  yaml: any
transformers:
- polymer:
    entry_points:
      - web/index.html
      - web/index2.html
I make web/index2.html a copy of web/index.html and run pub build. That produces generated output for both HTML files:
➜  dart git:(master) ✗ tree -L 2 build
build
└── web
    ├── assets
    ├── index2.html
    ├── index2.html_bootstrap.dart.js
    ├── index2.html_bootstrap.dart.js.map
    ├── index2.html_bootstrap.dart.precompiled.js
    ├── index.html
    ├── index.html_bootstrap.dart.js
    ├── index.html_bootstrap.dart.js.map
    ├── index.html_bootstrap.dart.precompiled.js
    └── packages

3 directories, 8 files
To support either a single string entry or a list of strings, I need to inspect the runtime type of entry_points:
main() {
  var pubspecYaml = new File('pubspec.yaml').readAsStringSync();
  var pubspec = loadYaml(pubspecYaml);

  pubspec['transformers'].
    where((t) => t.keys.length == 1 && t.keys.first == 'polymer').
    forEach((t){
      var entry_points = t['polymer']['entry_points'];
      var filenames = entry_points.runtimeType == String ?
        [entry_points] : entry_points;

      filenames.
        forEach((filename) {
          new PolymerScriptReducer(filename).reduce();
        });
    });
}
And that does the trick. I doubt that anyone would need to generate multiple entry points like that—especially if the goal is a single JavaScript source file for a Polymer.dart element. Still, I cannot ignore the plural nature of the name. I will likely rework this bit further as a package in case others might have need of it—or if I need to reference it in Patterns in Polymer. Tomorrow.

Day #24

Wednesday, April 2, 2014

Giving Up on Single File Polymer.dart Transformers


Up today, I try to hack Polymer.dart, Dart Pub, and dart2js in the most horrible ways possible.

The end goal is to get a pub build of a Polymer element to produce a single deployment script. In its current incarnation, Polymer.dart's pub transformer produces 4 JavaScript files for deployment and it places the <polymer-element> templates directly in the transformed HTML:
<!DOCTYPE html><html lang="en">
<head>
<script src="packages/shadow_dom/shadow_dom.debug.js"></script>
<script src="packages/custom_element/custom-elements.debug.js"></script>
<script src="packages/browser/interop.js"></script>

    <!-- Load component(s) -->
    <!-- Load Polymer -->
    <script src="index.html_bootstrap.dart.js"></script>
</head>
<body>
<polymer-element name="x-pizza-toppings">
  <template><!-- ... --></template>
</polymer-element>
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
</polymer-element>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>
</body></html>
In the previous days, I have managed to manually combine all of that (<polymer-template> and 4 JavaScript files) into a single JavaScript file for reusable deployment. I was unsuccessful in my efforts to write my own pub transformer, primarily because manual dart2js appears to ignore Polymer.dart annotations. If I cannot write my own transformer, I am going to hack as much of the default Polymer.dart transformer as possible to see if I can generate a single, deployable JavaScript file from my Polymer.dart code.

Except if I can't

It turns out that much of dart2js transformer code is, naturally enough, part of Dart's internals instead of Barback or Polymer.

I cannot use the Dart2JSTransformer from internal without compiling Dart from source, which… ugh. It's not that it's a ton of work—just a yak that I do not want to shave tonight for exploring Polymer. So I spend some time looking through the dart2js options that are used by the transformer in the hopes that I am missing some magical setting that would pick up my missing Polymer annotations.

In the end, however, I am unsuccessful. Bother. I think it best to drop this line of exploration for now. There are still a few other avenues of exploration that I need to tackle before Patterns in Polymer is finally done and this avenue is proving less and less fruitful. I will likely throw together a quick shell script tomorrow and then move on. Time permitting, I will return here and investigate compiler Dart so that I have more access to the internal libraries.


Day #22

Tuesday, April 1, 2014

Can't Manually Dart2Js a Polymer


Tonight, I compile Polymer.dart transform assets. No excuses.

I am still trying to compile Polymer code inside a Dart Pub transformer because the default dart2js compilation that pub build does occurs too late for my transformer to use. Without the dart2js output, I cannot compile everything into a single deploy script instead of the multiple JS scripts that are currently created by the built-in Polymer transformer.

I ended last night thinking that I was relatively close. I had written a transform asset to the filesystem, forked a dart2js process, only to find that I needed at least one other asset to successfully compile. Tonight, I add that asset—the generated index.html.0.dart—to the list of files that need to be temporarily available to the transformer:
class SingleJsPolymerTransformer extends Transformer {
  List<AssetId> bootstrappedPolymerElements = [];
  // ...
  Future<bool> isPrimary(Asset input) {
    if (input.id.path.contains('html_bootstrap.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }
    if (input.id.path.contains('html.0.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }
    // ...
  }
  // ...
}
Assets are Future based, which means that I need a way to wait for any and all temporary files to be written to the file system. To make that happen, I write a method that returns a list of Futures that will complete when their files have been written:
  List<Future> writeTemporaryAssets(transform, List<AssetId> assets) {
    return assets.
      map((asset){
        return transform.
          readInputAsString(asset).
          then((code) {
            new File(asset.path).
              openSync(mode: FileMode.WRITE).
              writeStringSync(code);
          });
      });
  }
The return value of the innermost then() is itself a future (the then() method always returns a future), so I have successfully generated a list of Futures, each of which complete when the file has been written to the filesystem. Now I need to wait for all of those Futures to complete before attempting to dart2js compile my Polymer code. This is what Future.wait() does:
  buildSingleJavaScript(templateHtml, transform) {
    return Future.
      wait(writeTemporaryAssets(transform, bootstrappedPolymerElements)).
      then((_){
        var result = Process.runSync('dart2js', [ /* ... */]);
        // Assemble dart2js and various library code...
      });
  }
Given a list of writeTemporaryAssets() futures, Future.wait() returns another Future that will complete only when every future in the list has completed. In other words, I am now waiting until all temporary assets are available on the filesystem before running dart2js. Perfect!

Naturally, this still does not work. Actually, writing the temporary assets works as does compiling. Unfortunately, compiling these temporary assets does not generate the same code that the dart2js pub transformer generated. It is close, but a diff of my dart2js compiled JavaScript with that generated by the pub transformer reveals numerous differences, including:
...
 C.Ka=new H.GD("call")
+C.Je=new H.GD("current")
 C.nN=new H.GD("dynamic")
 C.AZ=new H.GD("dart.core.String")
+C.Kl=new H.GD("ingredients")
 C.Wn=new H.GD("length")a
 C.PC=new H.GD("dart.core.int")
+C.YS=new H.GD("name")
 C.OV=new H.GD("noSuchMethod")
+C.aC=new H.GD("pizzaState")
 C.c8=new H.GD("registerCallback")
 C.ok=new H.GD("dart.core.Null")
...
Unfortunately, the missing objects look to be annotated Polymer attributes:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  @published String name;
  @published List ingredients = [];
  @observable String current = '';
  // ...
}
Without those observed and published attributes, Polymer code isn't really Polymer code. And, even though there are no errors when I fire up the code, my <x-pizza> builder does not work. It does not even have ingredients:



Darn.

One the one hand, this was a terribly ugly approach, so it is not too much a shame that it will not work. On the other hand, why can't I compile annotated code with dart2js? Given that this approach is such an ugly mess, I likely will not try to answer that. Instead, I will probably take a closer look a the dart2js and Polymer.dart transformers tomorrow to see if I have any luck in there. And if not, I can always fall back to shell scripts.


Day #21

Monday, March 31, 2014

Forking Dart2JS in a Pub Transform (ICK)


My quest to generate a single JS file from a Polymer.dart source continues tonight with an attempt to get dart2js generated code into that single JS file.

After the previous two nights, I have the <polymer-element> template in said JS file (Polymer.dart puts it directly in the HTML by default) and various supporting libraries in that same JS file. But I lack the most important piece of this puzzle—the compiled backing class itself. The problem is that the dart2js transformer is run at the very end of the Dart Pub transform process.

The first thing that I try tonight is to place the $dart2js options before my custom, single JS transformer in my project's pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
- $dart2js:
    verbose: true
- deployment_experiment:
    entry_points: web/index.html
I have not looked into the $dart2js transformer code and the documentation never states this explicitly, but my sense is that the dart2js transformer is run last no matter what and that the $dart2js options are just that—options for that last transformer.

Still, best not to assume, so:
$ pub build
Building deployment_experiment.................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................^C
I let that run for a good ten minutes with no discernable results. There is nothing happening to the filesystem:
➜  polymer-book git:(master) ✗ find play/deployment -mmin -60 -ls | grep -v node_modules | grep -v dart/packages
1188688    4 drwxr-xr-x  10 chris    chris        4096 Mar 31 22:17 play/deployment/dart
1196105    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 21:58 play/deployment/dart/test
1186073    0 lrwxrwxrwx   1 chris    chris          11 Mar 31 21:58 play/deployment/dart/test/packages -> ../packages
1196106    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 21:58 play/deployment/dart/web
1186074    0 lrwxrwxrwx   1 chris    chris          11 Mar 31 21:58 play/deployment/dart/web/packages -> ../packages
1188969    4 -rw-r--r--   1 chris    chris         349 Mar 31 22:10 play/deployment/dart/pubspec.yaml
1188960    4 -rw-r--r--   1 chris    chris        2203 Mar 31 21:58 play/deployment/dart/pubspec.lock
1188690    4 drwxr-xr-x   3 chris    chris        4096 Mar 31 22:00 play/deployment/dart/lib
1186103    4 -rw-r--r--   1 chris    chris        2240 Mar 31 22:00 play/deployment/dart/lib/transformer.dart
1196109    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 22:10 play/deployment/dart/build
So I Ctrl-C the process.

If I move the $dart2js configuration to the end of pubspec.yaml, then the pub build works normally, albeit without the ability to transform dart2js output.

So ugh. It seems that I have do this the ugly way. The ugly way involves identifying the Polymer transform assets that get compiled into JavaScript by the default dart2js process at the end of pub build. Using that list, I then need to manually compiled these assets as part of my transform.

I identify the parts as part of the Transformer's determination of which elements are “primary” elements. These dart2js elements are not primary, but I squirrel them away in a list to be processed:
library single_file.transformer;

import 'dart:io';
import 'dart:async';
import 'package:barback/barback.dart';

class SingleJsPolymerTransformer extends Transformer {
  String entry_points;
  List<AssetId> bootstrappedPolymerElements = [];
  // ...
  Future<bool> isPrimary(Asset input) {
    if (input.id.path.contains('html_bootstrap.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }

    if (entry_points == input.id.path) return new Future.value(true);
    return new Future.value(false);
  }
  // ...
}
With that, I can then run dart2js on the assets, but...

But I have to first write them out to the disk. The built-in dart2js transformer must have some kind of compile-from-asset capability. I will look into that at some point, but for tonight I content myself with ugly hacks like:
  buildSingleJavaScript(templateHtml, transform) {
    return transform.
      readInputAsString(bootstrappedPolymerElements.first).
      then((code) {
        new File('index.html_bootstrap.dart').
          openSync(mode: FileMode.WRITE).
          writeStringSync(code);

        var result = Process.runSync(
         'dart2js',
         ['-o', 'index.html_bootstrap.dart.js', 'index.html_bootstrap.dart']
        );
        // ...
      });
  }
Even that does not quite do the trick. It seems that there are secondary Polymer.dart elements that are required because I wind up with compilation errors along the lines of:
index.html_bootstrap.dart:7:8: Error: Can't read 'file:///home/chris/repos/polymer-book/play/deployment/dart/index.html.0.dart' (Error reading
 'index.html.0.dart' (OS Error: No such file or directory, errno = 2)).
import 'index.html.0.dart' as i2;
       ^^^^^^^^^^^^^^^^^^^
index.html_bootstrap.dart:15:3: Warning: Cannot resolve 'i2'.
  i2.main();
  ^^
Error: Compilation failed.
Bother.

I do think I am on the right track, but I call it a night at this point. I will pick back up fresh tomorrow either investigating how dart2js compiles assets or working through the remaining secondary Polymer.dart elements that are needed to compile this darn file.



Day #20

Sunday, March 30, 2014

Reading Files During Dart Pub Transform


After last night, I have my post-Polymer.dart pub transformer on the road to building single-file JavaScript from Dart Polymer elements.

This transformer needs to run after the built-in Polymer.dart transformer and takes identical configuration in the pubspec.yaml file:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
- deployment_experiment:
    entry_points: web/index.html
Where the built-in Polymer.dart transformer leaves the <polymer-element> templates directly in the entry_points HTML, my deployment experiment transformer moves the templates into a new JavaScript file responsible for adding the templates to the DOM.

To complete my transformer, I need to combine the remaining <script> tags from the Polymer.dart transformer into a single script source:
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/x_pizza_templates.js"></script>
  <script src="/scripts/shadow_dom.min.js"></script>
  <script src="/scripts/custom-elements.min.js"></script>
  <script src="/scripts/interop.js"></script>
  <script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
</html>
The problem I am faced with is that none of those files is included as an asset coming from the Polymer.dart transform. So I cannot put my (admittedly small) pub transformer knowledge to use here. Regardless of how all of that JavaScript is going to get into my single “deploy.js” file, I will need to do the work near the buildSingleJavaScript() method of my transformer:
import 'package:barback/barback.dart';

class SingleJsPolymerTransformer extends Transformer {
  // ...
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );
    transform.addOutput(
      new Asset.fromString(templateId, _templateJs(templateHtml))
    );
  }
  // ...
}
This method created a new asset ID to be added to the transform process and it then adds the asset it from a string (which is the crazy JavaScript string version of the <polymer-element> tags from last night).

The absolute dumbest way that I can think to add all of the other JavaScript source files to this asset is read each synchronously from the file system, concatenating each to last night's _templateJS():
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );

    var js = _templateJs(templateHtml) +
      new File('packages/shadow_dom/shadow_dom.min.js').readAsStringSync() +
      new File('packages/custom_element/custom-elements.min.js').readAsStringSync() +
      new File('packages/browser/interop.js').readAsStringSync();

    transform.addOutput(new Asset.fromString(templateId, js));
  }
That works perfectly. At least it works perfectly until I try to read the dart2js generated Polymer code:
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );

    var js = _templateJs(templateHtml) +
      new File('packages/shadow_dom/shadow_dom.min.js').readAsStringSync() +
      new File('packages/custom_element/custom-elements.min.js').readAsStringSync() +
      new File('packages/browser/interop.js').readAsStringSync() +
      new File('build/web/index.html_bootstrap.dart.js').readAsStringSync();

    transform.addOutput(new Asset.fromString(templateId, js));
  }
When I try to pub build with that in my transformer, I am greeted with:
➜  dart git:(master) ✗ pub build
Building deployment_experiment...
Build error:
Transform SingleJsPolymer on deployment_experiment|web/index.html threw error: Cannot open file, path = 'build/web/index.html_bootstrap.dart.js' (OS E
rror: No such file or directory, errno = 2)
file_impl.dart 558                                                            _File.throwIfError
file_impl.dart 411                                                            _File.openSync
file_impl.dart 456                                                            _File.readAsBytesSync
file_impl.dart 479                                                            _File.readAsStringSync
http://127.0.0.1:46880/packages/deployment_experiment/transformer.dart 54:74  SingleJsPolymerTransformer.buildSingleJavaScript
...
The problem, of course, is that build/web/index.html_bootstrap.dart.js does not exist yet. This file is generated when pub build calls dart2js on *.dart code after the various transforms are invoked. But I need the code during a transform, so am I out of luck?

In fact, I may be out of luck. About the only thing that I can think to try is forking out a separate dart2js process during the transform. That seems ugly, but there may be no other option save for giving up the idea of doing this as a transformer and sticking with shell scripts. As wrong as the fork-dart2js-during-transform feels, I will likely give that a try tomorrow—at least to see just how ugly it is. Unless someone has a better idea?


Day #19

Friday, March 28, 2014

Deploying Polymer.dart in a Single, Compiled JavaScript File


Well that went better that I expected. Deploying Dart flavored Polymer elements, that is. So the question tonight it, am I overlooking something?

I've had troubles building Dart Polymer elements in the past, so I was trepidatious diving into it last night. But it went surprisingly well. At least some of my earlier trouble may have involved interoperating with JavaScript, but I still expected more trouble than I found last night. So let's see if I can cause trouble.

First up, let's see if I can do something about the sheer number of Dart compiled / supported JavaScript files that are necessary for my single <x-pizza> custom element:
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/x_pizza_templates.js"></script>
  <script src="/scripts/shadow_dom.min.js"></script>
  <script src="/scripts/custom-elements.min.js"></script>
  <script src="/scripts/interop.js"></script>
  <script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
</html>
These JavaScript files are already minified:
➜  scripts git:(master) ls -lh
total 800K
-rw-r----- 1 chris chris  11K Mar 27 23:14 custom-elements.min.js
-rw-r--r-- 1 chris chris 417K Mar 27 23:16 index.html_bootstrap.dart.js
-rw-r--r-- 1 chris chris 280K Mar 27 23:16 index.html_bootstrap.dart.js.map
-rw-r----- 1 chris chris  426 Mar 27 23:15 interop.js
-rw-r----- 1 chris chris  80K Mar 27 23:14 shadow_dom.min.js
-rw-r--r-- 1 chris chris 1.5K Mar 28 21:41 x_pizza_templates.js
Well, as minified as they get. The main index.html_bootstrap.dart.js file is definitely on the large side. There is not much that do about it as dart2js has done its best with a still early-in-development library. So, instead of worrying about making these any smaller, I hope to simply combine them into a single file:
➜  scripts git:(master) ✗ cat \
  x_pizza_templates.js \
  shadow_dom.min.js \
  custom-elements.min.js \
  interop.js \
  index.html_bootstrap.dart.js \
    > x_pizza.js
Well, of course I can combine them into a single file, but will it work for deployment purposes?
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/x_pizza.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
</html>
The answer, it would seem is a definite “yes”:



I am still able to build my pizzas with <x-pizza> in a non-Dart enabled Chrome (Firefox works as well) and am now using only a single, readily deployed <script> source to do so. Nice!

The other way that I thought to break this would be to include another compiled Dart script—event a simple one like:
import 'dart:html';
main(){
  query('h1').style.color = 'red';
}
After compiling that to JavaScript with dart2js, I pull the result into my deployment's script directory and try to use both this main() Dart script as well as the Dart Polymer element:
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/x_pizza.js"></script>
  <script src="/scripts/main.dart" type="application/dart"></script>
  <script src="/scripts/dart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
</html>
And, happily, that works absolutely as desired:



So wow. This Polymer.dart deployment really works. Sure, I might like the size of the Polymer elements to be smaller, but the compile size will gradually improve as Dart and Polymer.dart evolve. But to have everything else working this well, this early is wonderful. I think tomorrow I will look to automate all of this.


Day #17

Thursday, March 27, 2014

Polymer Deployment as an Afterthought


I really don't care about deployment. Except, of course, when it's time to deploy.

At this point, I have written some 1500+ blog posts on a number of subjects. Nearly 200 have been on testing. Fewer than 30 have been on deployment. And that seems about right to me. Pushing out software, whether it is rubbish or not, should be facilitated by a language, library, or framework—and then automated away. Making the software unrubbishy is the trick.

Still, I'd like a better idea of how best to deploy Polymer. At this point, I am more concerned about deploying Dart-flavored Polymer elements than JavaScript ones, so I start there tonight.

There are two different ways that I can think to categorize Polymer.dart deployments. The first is when a Polymer element is part of another application. The second is when the Polymer element is intended to be used on a page independently of other libraries or applications. I think I have a handle on the former from my work integrating Angular.dart and Polymer.dart. That leaves me with the question of how to best prepare a single element, say my <x-pizza> pizza builder element, for ease of inclusion on a page.

With Dart Polymers, deployment currently begins and ends with Dart Pub—the packaging tool. For Polymers, the application's pubspec.yaml configuration file needs to specify web page entry points:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
A simple pub build then takes that entry point:
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Load component(s) -->
    <link rel="import" href="packages/deployment_experiment/elements/x-pizza.html">
    <!-- Load Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
  <body>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>
  </body>
</html>
And compiles the Dart code to JavaScript and prepares the HTML for deployment. Preparing the HTML mostly involves including the Polymer element templates directly in the HTML and sourcing the compiled JavaScript:
<!DOCTYPE html><html lang="en">
<head>
<script src="packages/shadow_dom/shadow_dom.debug.js"></script>
<script src="packages/custom_element/custom-elements.debug.js"></script>
<script src="packages/browser/interop.js"></script>

    <!-- Load component(s) -->
    <!-- Load Polymer -->
    <script src="index.html_bootstrap.dart.js"></script>
</head>
<body>
<polymer-element name="x-pizza-toppings">
  <template><!-- ... --></template>
</polymer-element>
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
</polymer-element>

    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>

</body></html>
If I wanted to deploy most of this code to a CDN so that anyone could readily include <x-pizza> elements, I would copy the various libraries (although the “min” versions instead of the “debug” versions). To try this out, I create a deploy directory and copy said JavaScript libraries into it:
➜  dart git:(master) ✗ mkdir deploy
➜  dart git:(master) ✗ cd deploy 
➜  deploy git:(master) ✗ mkdir scripts
➜  deploy git:(master) ✗ cp ../packages/shadow_dom/shadow_dom.min.js scripts 
➜  deploy git:(master) ✗ cp ../packages/custom_element/custom-elements.min.js scripts 
➜  deploy git:(master) ✗ cp ../packages/browser/interop.js scripts 
➜  deploy git:(master) ✗ cp ../build/web/index.html_bootstrap.dart.js scripts 
➜  deploy git:(master) ✗ cp ../build/web/index.html_bootstrap.dart.js.map scripts
I then create a new HTML file referencing these scripts instead of the pub build package locations:
<!DOCTYPE html><html lang="en"><head>
<script src="/scripts/shadow_dom.min.js"></script>
<script src="/scripts/custom-elements.min.js"></script>
<script src="/scripts/interop.js"></script>
<script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <polymer-element name="x-pizza-toppings">
    <template><!-- ... --></template>
  </polymer-element>
  <polymer-element name="x-pizza">
    <template><!-- ... --></template>
  </polymer-element>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body></html>
And it works just fine. The only real problem is that developers using this would have to include the <polymer-element> templates in addition to the <script> tags. It would feel more like a “regular” library if it were all <script> tags. So I move the templates out into a JavaScript file that builds them from JavaScript strings:
var xPizzaToppingsHtml = '' +
'<polymer-element name="x-pizza-toppings">' +
'  <template>' +
// ...
'  </template>' +
'</polymer-element>';

var xPizzaHtml = '' +
'<polymer-element name="x-pizza">' +
'  <template>' +
// ...
'  </template>' +
'</polymer-element>';

var container = document.createElement('div');
container.innerHTML = xPizzaToppingsHtml + xPizzaHtml;
document.body.appendChild(container);
With that, my deployment becomes:
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/shadow_dom.min.js"></script>
  <script src="/scripts/custom-elements.min.js"></script>
  <script src="/scripts/interop.js"></script>
  <script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
<script src="/scripts/x_pizza_templates.js"></script>
</html>
Ideally, I would replace the five different <script> tags with a single <script> source, but I leave that for another day. For now, I would just like to have a quick way to deploy a single element for reuse on any kind of web page. And I think I have that:



The JavaScript files are all coming from my deploy-ready scripts directory. The HTML is all regular HTML, save for my custom <x-pizza> Polymer element. I think my custom Dart Polymer element is ready for public use!

Well, maybe and maybe not. There are still a few questions to answer. I would like to know if this still works should another Dart application exist on the page. It would be nice to combine all of the scripts into a single source file. I would also like to be able to automate all of this.

That said, I am pleased to have gotten this working as well as I have in a single night. The promise of deployable Dart Polymer elements feels that much closer!


Day #16

Saturday, January 11, 2014

Day 993: Vulcanize (with Exclusions)


Deployment of Polymer.dart is causing me a bit of bother. In a good way. I continue to stretch the boundaries of what Polymer can do—and probably should do. I have to admit that I am struggling with including data in Polymers—especially when it comes to deployment. I am so very close to having a working solution in Dart, but I begin to suspect that I am fighting the framework just a little too much. So I am switching apps, back to the JavaScript equivalent to see if I have similar problems.

I am still trying to read configuration from both the Polymer definition and when using the Polymer. I have been placing the configuration in a <link> import before the Polymer definition:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="hello-you.json">
<polymer-element name="hello-you">
  <!-- ... -->
</polymer-element>
The configuration when using the element goes inside the Polymer tags:
<hello-you>
  <link rel="import" href="scripts/hello-you.json">
  <p>And good-bye…</p>
</hello-you>
And, thanks to the magic of Polymer, that works just fine—when the Polymers are separate from the web and not combined into a single deployment asset. But I recognize that this might not be ideal for real-world usage, which is where the deployment-minded vulcanize comes in.

I start by installing vulcanize:
$ npm install -g vulcanize
Then I run it on the entry page to my JavaScript Polymer application:
$ vulcanize index.html
Default output to vulcanized.html in the input directory.
When I look at my JSON configured Polymer pre-vulcanize, I see:



When I load up the vulcanized version, I find:



Well, that does not bode well for my attempts at external configuration.

There are a couple of options that vulcanize supports. The --csp creates an external JavaScript file, but my configuration imports are still slurped directly into the page.

The only other option that I can think to use is the --config. In a configuration file, I find that I can specify imports that I want vulcanize to ignore. That sounds promising. So I create vulcanize_conf.js with the following content:
{
  "excludes": {
    "imports": [
      "\\.json$"
    ]
  }
}
The documentation suggests that I can exclude by regular expression, which is what I do above. I then use the configuration:
$ vulcanize --config=vulcanize_conf.js index.html 
Default output to vulcanized.html in the input directory.
And that actually works:



Well, not quite. The default configuration in the Polymer definition is still imported, but the configuration when I use the Polymer, while still in the HTML, is not imported properly.

Still, this seems promising. While not ideal to have to exclude JSON configuration in Polymers, it seems doable and seems, if anything, slightly easier than in the Dart equivalent.



Day #993

Friday, January 10, 2014

Day 992: Search and Replace Dart Transformer to Hide from Polymer


OK I lied. Yesterday, I breezed past a little Dart problem in an effort to finish off some work. Today I try to address that oversight.

As I briefly mentioned yesterday, I am able to read Polymer configuration that is stored <link> imports inside the definition of a Dart Polymer:
<script src="../../packages/browser/dart.js"></script>
<script src="../../packages/browser/interop.js"></script>
<polymer-element name="hello-you">
  <link rel="import" href="hello-you.json">
  <template>
    <!-- ... -->
  </template>
  <script type="application/dart" src="hello_you.dart"></script>
</polymer-element>
It takes a little effort, but I can grab hello-you.json from the Polymer, reading the data into the Polymer's configuration data. I have to work through the declaration property and run the result through a transformer, but it is doable.

What I cannot quite do is <link> import data when I use the Polymer:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
My problem is something of a running theme with Polymer.dart—the deployment transformer includes <link> imports inline, which results in actually seeing the JSON data embedded diring in the web page:



I can work around this inside the Polymer definition with a deployment build transformer that searched for raw JSON, wrapping it in a display: none styled tag. The actual <link> tag remains in the Polymer, allowing me to read it as configuration.

My problem with configuration in a Polymer is twofold. First, it is a little harder to find the JSON to wrap it inside display: none tags. Second, even if I could do so, the <link> tag is stripped out so that I could not read it even if I wanted to do so. I end up with this in the main web page:
{
  "hello": "Yo"
}
<div class="container">
  <hello-you>
    
    <p>And good-bye…</p>
  </hello-you>
</div>
I think the best thing would be to pre-transform the page so that, by the time the Polymer transformer sees it, it is no longer a <link>. The pre-transformer could take the Polymer:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
And transform it to:
<hello-you>
  <!-- link rel="import" href="hello-you.json" -->
  <p>And good-bye…</p>
</hello-you>
Then the code could pass through the Polymer transformer, which can do its usual thing—except that it will skip the commented <link> tag. Finally, a post-transformer could restore the original <link>:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
I have gotten pretty good at writing search and replace Dart Pub transformers. So good, in fact, that I think it is time to write a pub package. If I call the package replace_transformer, then my application could have a pubspec.yaml that looks like:
name: config_example
dependencies:
  polymer: any
  replace_transformer:
    path: /home/chris/repos/replace_transformer
dev_dependencies:
  unittest: any
transformers:
- replace_transformer:
    file: web/index.html
    match: '<link rel="import" href="hello-you.json">'
    replace: '<!-- link rel="import" href="hello-you.json" -->'
- polymer:
    entry_points: web/index.html
- replace_transformer:
    file: web/index.html
    match: '<!-- link rel="import" href="hello-you.json" -->'
    replace: '<link rel="import" href="hello-you.json">'
In the dependencies section of pubspec.yaml, I mark my new replace_transformer package as a dependency. Once I am ready to release this package to pub.dartlang.org, I will remove the local path. For now, the local path allows me to build my transformer and try it right away. Brilliant!

There are two ways to name a Dart transformer and I have forgotten one of them. The one I do remember is to create a file named transformer.dart. So in replace_transformer, I create lib/transformer:
library replace.transformer;
import 'dart:async';
import 'package:barback/barback.dart';

class ReplaceTransformer extends Transformer {
  String file;
  Pattern match;
  String replace;

  ReplaceTransformer(this.file, this.match, this.replace);

  Future isPrimary(Asset input) { /* ... */ }

  Future apply(Transform transform) { /* ... */ }
}
Nothing out of the ordinary there. I declare a library. I import packages—async for access to Future and barback from pub itself for the Transformer class as well as the ability to read the pubspec.yaml configuration. I declare the three instance variables that will be assigned from pubspec.yaml and define a constructor that assigns those instance variables. Lastly, I define the two methods that need to be implemented by a subclass of Transformer. The isPrimary() method indicates if a particular asset needs to be directly transformed (it will have to return true when the asset matches file). And the apply() method actually performs the transformation.

Pub expects its tranformers to define an asPlugin named constructor which access barback settings:
class ReplaceTransformer extends Transformer {
  String file;
  Pattern match;
  String replace;

  ReplaceTransformer(this.file, this.match, this.replace);

  ReplaceTransformer.fromList(List a): this(a[0], a[1], a[2]);

  ReplaceTransformer.asPlugin(BarbackSettings settings)
    : this.fromList(_parseSettings(settings));
  // ...
}
I redirect this constructor to the fromList() named constructor that takes a list and redirects to the primary constructor with the three expected values. The _parsedSettings() is easy enough:
List<String> _parseSettings(BarbackSettings settings) {
  var args = settings.configuration;
  return [
    args['file'],
    args['match'],
    args['replace']
  ];
}
With that, I need to teach my ReplaceTransfomer when to apply transforms:
  Future<bool> isPrimary(Asset input) {
    if (file == input.id.path) return new Future.value(true);
    return new Future.value(false);
  }
And I need to replace all instances of match with replace when the transform is applied:
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    return transform.
      readInputAsString(input.id).
      then((html){
        var fixed = html.replaceAllMapped(
          match,
          (m) => replace
        );

        transform.addOutput(new Asset.fromString(input.id, fixed));
      });
  }
And that actually does the trick. Now when I load my Polymer, the <link> tag makes it through Polymer's transformer unscathed:



Nice! I am still a little uncertain how to approach this stuff in Patterns in Polymer, especially since the JavaScript version of Polymer does not really have the concept of asset packaging. But, for now, I am glad to feel like I have a workable, if a bit verbose solution in Dart.

Day #992

Sunday, January 5, 2014

Cannot Minify Polymer.dart


I very much want to put a working example of <ice-code-editor> up for public consumption. This is the Polymer version of the ICE Code Editor. After the work of the past few days, I could do so—especially after figuring out how to swap out the debugging libraries for minified versions upon deployment. But deployment on the web usually means codebases that are south of the 2.5MB range.

And, unfortunately for me, that is where my Polymer currently resides:
ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  797 Jan  5 12:11 build/polymer.html
-rw-r--r-- 1 chris chris 2.6M Jan  5 22:12 build/polymer.html_bootstrap.dart.js
Although I might prefer to fix the root of the problem, that might take me more time than I have at my disposal. Since I am getting rather adept at writing Dart deployment transformers, I thought I might have a go at transforming that polymer.html_bootstrap.dart.js file. Its problem is that it contains the entire Dart core in JavaScript form. Since I have no need of web audio, web sql, svg, etc., I try manually removing their definitions from polymer.html_bootstrap.dart.js. Sadly, that gets me nowhere. Even if my code is not directly using these libraries, other parts of the JavaScript are using them. It was worth a go.

If I cannot treat the symptoms, let's see about the root cause of the problem. I start by upgrading the various “any” version dependencies that are present:
➜  ice-code-editor git:(polymer) ✗ pub upgrade
Resolving dependencies...............................................
Downloading js 0.2.1 from hosted...
Downloading browser 0.9.1 from hosted...
Dependencies upgraded!
That actually seems promising. I know, for instance, that the js-interop package recently closed a bug that was causing excessive dart2js code sizes.

So I pub build my Polymer to find:
➜  ice-code-editor git:(polymer) ✗ pub build
...
[Warning in Dart2JS]:
web/polymer.html_bootstrap.dart:1:1: Hint: 449 methods retained for use by dart:mirrors out of 2399 total methods (19%).
...
[Info in Dart2JS]:
Generated ice_code_editor|web/polymer.html_bootstrap.dart.js (416281 characters) in 0:00:09.092775
That is an improvement. Not only the in size, which really is less:
➜  ice-code-editor git:(polymer) ✗ ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  797 Jan  5 22:52 build/polymer.html
-rw-r--r-- 1 chris chris 407K Jan  5 22:52 build/polymer.html_bootstrap.dart.js
The build time is also less than half what it was. Great!

Except that now the Polymer will not run. Instead, I get:
Uncaught Error: NoSuchMethodError : method not found: 'Symbol("giR")'
Receiver: Instance of 'pk'
Arguments: [] polymer.html_bootstrap.dart.js:1846
Stack Trace: 
Error
    at Object.b (http://localhost:8000/polymer.html_bootstrap.dart.js:1117:3)
    at pk.a.T (http://localhost:8000/polymer.html_bootstrap.dart.js:6138:25)
    at pk.T (http://localhost:8000/polymer.html_bootstrap.dart.js:8671:22)
    at pk.giR (http://localhost:8000/polymer.html_bootstrap.dart.js:13237:59)
    at cz.A0 (http://localhost:8000/polymer.html_bootstrap.dart.js:8376:8)
    at Fv.call$1 (http://localhost:8000/polymer.html_bootstrap.dart.js:8508:34)
    at vs.GP (http://localhost:8000/polymer.html_bootstrap.dart.js:3505:34)
    at jb.call$0 (http://localhost:8000/polymer.html_bootstrap.dart.js:3653:25)
    at Object.T8 (http://localhost:8000/polymer.html_bootstrap.dart.js:3272:26)
    at R8.Gr (http://localhost:8000/polymer.html_bootstrap.dart.js:4595:25)
 polymer.html_bootstrap.dart.js:1846
It seems that this error has been seen once before. Only once, as best I can tell. By me.

I always love it when that happens. It seems that I am doing something wrong in a way that is uniquely me. No one else is wrongheaded in quite the same way as me. I could definitely use a pair at this point, but failing that, I try my solution from back then: building the code without minifying it. But how to do that?

The pub build page suggests using the --mode=debug option. That does not seem to work:
➜  ice-code-editor git:(polymer) ✗ pub build --mode=debug         
Could not find an option named "mode".
Run "pub help" to see available options.
And, sadly, I cannot figure this out. I know there must be a way to get this working in debug (non-minified) mode, but I cannot find it.

Update: I was able to finally get this working. The option is --no-minify, not --mode=debug. The end result is that I am less than half of what I started with, but am still uncomfortably large:
➜  ice-code-editor git:(polymer) ✗ ls -lh build/polymer.html*
-rw-r--r-- 1 chris chris  801 Jan  6 00:07 build/polymer.html
-rw-r--r-- 1 chris chris 945K Jan  6 00:07 build/polymer.html_bootstrap.dart.js
I may have a go at tweaking some of the JavaScript interoperability code in the ICE Code Editor tomorrow to see if that might fix my minified version of the code.



Day #987

Saturday, January 4, 2014

Building Minified Polymer Libraries from Dart


There are debug statements in my build code. Why are there debug statements in my build code?

I was pleased with my progress at getting my “old” Polymer version of the ICE Code Editor back up and running—even to the point that I could build it for JavaScript-only browsers. Only... why is that debug code in the generated HTML?
<html><head><script src="packages/shadow_dom/shadow_dom.debug.js"></script>
<script src="packages/custom_element/custom-elements.debug.js"></script>
<script src="packages/browser/interop.js"></script>
  <script src="polymer.html_bootstrap.dart.js"></script>
</head>
<body><polymer-element name="ice-code-editor"><!-- ... -->
</body></html>
It actually takes me a fair bit of digging, but I eventually find the following in polymer/src/build/polyfill_injector.dart:
      // TODO(sigmund): enable using .min.js. This currently fails in checked
      // mode because of bugs in dart2js mirrors (dartbug.com/14720).
      // var suffix = options.releaseMode ? '.min.js' : '.debug.js';
      var suffix = '.debug.js';
I am not quite sure that I follow the bug, but it seems like only affects unit testing. That is, I think that code would still work if the “min.js” versions were used, but there is currently no way for Polymer.dart to verify that it works. To put that theory to the test, I manually change both of the debug <script> tags to use the min versions instead:
<html><head><script src="packages/shadow_dom/shadow_dom.min.js"></script>
<script src="packages/custom_element/custom-elements.min.js"></script>
<script src="packages/browser/interop.js"></script>
  <script src="polymer.html_bootstrap.dart.js"></script>
</head>
<body><polymer-element name="ice-code-editor">
<!-- ... -->
</body></html>
And that seems to do the trick. When I load my smoke test page, the Polymers still work and the Network tab confirms that the minified versions of the two libraries are being used:



The Polymers even work in Internet Explorer so I think I am good:



Hand editing code is never a useful thing to do. I could write a script that always does this for me, but I would still have to remember to run that every time I build my application. Actually, I know how to do this. I already wrote one pub transformer. I can do it again. I start by adding an application specific transformer to my pubspec.yaml:
name: ice_code_editor
version: 0.0.11
# ...
dependencies:
  crypto: any
  js: any
  ctrl_alt_foo: any
  json: any
  polymer: any
transformers:
- polymer:
    entry_points: web/polymer.html
- ice_code_editor:
    entry_points: web/polymer.html
The transformer is then more or less a copy and paste job from that other transformer. The overall structure is identical (which means that I probably ought to extract it out into a library). The only difference is the name of the transformer (ProductionMode) and the regular expression replacement performed by the transformer's apply() method:
class ProductionMode extends Transformer {
  // ...
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    return transform.
      readInputAsString(input.id).
      then((html){
        var fixed = html.replaceAllMapped(
          new RegExp(r'\.debug\.js'),
          (m) => '.min.js'
        );
        transform.addOutput(new Asset.fromString(input.id, fixed));
      });
  }
}
And that does the trick. It does not speed up the build transformation by any stretch of the imagination, but whenever I do build my Polymer for deployment, it now includes the minified version of the JavaScript libraries instead of the debugging versions.

With that, I have a repeatable means of generating a minified version of my Polymer. At least until that bug is fixed.

Day #986

Tuesday, December 31, 2013

Polymer, External Libraries, and Latency


One of the many things I appreciate about Polymer is how it handles getting everything ready. There are a lot of interconnected parts that can be loaded in a Polymer application or widget, but Polymer manages them with aplomb. This is principally accomplished via the WebComponentsReady event which Polymer generates and uses—mostly in the form a nice, simple animated reveal of all Polymers when they are ready to be used.

I am unsure, however, how this WebComponentsReady strategy works when a Polymer is also dependent on third party libraries. I just so happen to be working on a Polymer that depends on Underscore.js. When everything is run locally with zero latency this seems to work just fine. But how will my initial approach fair under more realistic conditions?

From last night, my Polymer is pulling in Underscore.js from the same local web server that hosts my application and my Polymer code. The Polymer does this inside the defining <polymer-element>:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you">
  <template><!-- ... --></template>
  <script src="../bower_components/underscore/underscore.js"></script>
  <script>
    // Polymer element code here ...
  </script>
</polymer-element>
Currently, this produces network request like this:



My hello-you.html Polymer definition <link>-imports the polymer.html definition and the Underscore library. As soon as the relatively small polymer.html is imported, it requests polymer.js, which contains all of the necessary Polymer library code. While polymer.js is loading, Underscore.js completes loading and is evaluated, making it available when my Polymer code is evaluated. And this is important because my Polymer uses underscore as soon as it is ready:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you">
  <template>
    <!-- ... -->
  </template>
  <script src="../bower_components/underscore/underscore.js"></script>
  <script>
    Polymer('hello-you', {
      your_name: '',
      // ...
      feelingLucky: _.debounce(
        // A function in need of debouncing...
        750,
        true
      )
    });
  </script>
</polymer-element>
So what happens if there is a ton of latency (as in a mobile connection)? Will my Polymer class definition crash because the _ Underscore.js top-level variable is not defined?

That turns out to be a nearly impossible question to answer directly. Even though Underscore.js is larger than Polymer.js, the indirection of importing polymer.html which then imports polymer.js turns out to be sufficient to make it impossible to break my Polymer. Even if I create latency of up to 1.6 seconds:
$ sudo tc qdisc add dev lo root netem delay 800ms
(always, always, always remember to sudo tc qdisc del dev lo root when done testing latency)

Even this is not enough to make the evaluation times different enough so I can determine if Underscore.js is not available for Polymer. So instead, I create a gigantic JavaScript file that is mostly comment filler, but defines a single variable that I use in my Polymer. And, when I load the script I find:



That is beautiful. Even though the filler script takes significantly longer to load than Polymer does, Polymer is aware of the need to wait and does not do its thing until the <script> tag is ready.

The other question that I would like to answer has more to do with deployment—how does latency affect third party libraries when they are hosted on CDNs. It so happens that Underscore.js is hosted on a CDN, so I switch my <script> tag to point to such a CDN:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you">
  <template><!-- ... --></template>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
  <script>
    // Polymer element code here ...
  </script>
</polymer-element>
Now, I can add insane latency to my network connection, leaving the localhost connection effectively instantaneous:
$ sudo tc qdisc add dev eth1 root netem delay 10000ms
With that, I still see Polymer doing the right thing:



It takes 20 seconds to load underscore from that CDN because of my absurd traffic control (tc) setting. And yet Polymer just works. It waits until the library is loaded and then reveals the fully working Polymer element.

How cool is that?

One final note here is that it does not seem to matter where the <script> tag goes. Polymer still does right when the <script> tag goes at the top of the Polymer definition:
<link rel="import" href="../bower_components/polymer/polymer.html">
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<polymer-element name="hello-you">
  <template><!-- ... --></template>
  <script>
    // Polymer element code here ...
  </script>
</polymer-element>
I think that serves better to illustrate the immediate dependencies of a Polymer—something akin to declaring “normal” code's imports at the top of a file. Since there does not appear to be a difference in functionality or performance, I will likely opt for that approach in Patterns in Polymer.

I do love it when I discover that libraries and tools just work like this. Maybe someday I can write tools that behave this well, but until then I will have to content myself with being able to appreciate them. And write lots of books extolling their many virtues!



Day #982