Skip to content

Instantly share code, notes, and snippets.

@onionhammer
Last active October 4, 2015 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onionhammer/066480187e9cd4c7d053 to your computer and use it in GitHub Desktop.
Save onionhammer/066480187e9cd4c7d053 to your computer and use it in GitHub Desktop.
Compiles F# to javascript then invokes closure compiler on it, parses response w/ json data provider
#load "Scripts/load-references.fsx"
open System
open System.Net.Http
open System.Collections.Generic
open FSharp.Data
let map (items: seq<'a * 'b>) = items |> Seq.map(KeyValuePair)
type compilationResult = JsonProvider<"""
{
"compiledCode":"",
"errors":[{"charno":4321,
"error":"ERROR: You failed.",
"lineno":1234,
"file":"default.js",
"type":"ERROR_TYPE",
"line":"var x=-'hello';"
}],
"serverErrors":[
{"code":123,"error":"Over quota"}
],
"statistics": {
"originalSize":10,
"compressedSize":3000,
"compileTime":10
}
}
""">
let postSource src =
async {
use client = new HttpClient()
client.BaseAddress <- Uri("https://closure-compiler.appspot.com/compile")
use content =
new FormUrlEncodedContent(
map [
("js_code", src)
("compilation_level", "ADVANCED_OPTIMIZATIONS")
("output_format", "json")
("output_info", "compiled_code")
("output_info", "statistics")
])
let! response = client.PostAsync("", content) |> Async.AwaitTask
return response.EnsureSuccessStatusCode()
}
let closureCompile src = async {
let! response = postSource src
let! json = response.Content.ReadAsStringAsync() |> Async.AwaitTask
return json |> compilationResult.Parse
}
let compileScript p = async {
return! FunScript.Compiler.compileWithoutReturn(p) |> closureCompile
}
[<FunScript.JS>]
module PageA =
open FunScript
open FunScript.TypeScript
let add n =
for i = 0 to n do
let div = Globals.document.createElement "div"
div.innerText <- "Num: " + i.ToString()
Globals.document.body.appendChild(div) |> ignore
let main () =
add 50
let result = compileScript <@ PageA.main() @> |> Async.RunSynchronously
@onionhammer
Copy link
Author

val result : JsonProvider<...>.Root =
  {
  "compiledCode": "for(var a=0;50>=a;a++){var b=window.document.createElement(\"div\");b.innerText=\"Num: \"+a.toString();null;window.document.body.appendChild(b)};",
  "statistics": {
    "originalSize": 459,
    "originalGzipSize": 262,
    "compressedSize": 141,
    "compressedGzipSize": 139,
    "compileTime": 0
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment