text
stringlengths
0
601k
let choose_routers_without_path_builds_paths _ ( ) = let router = Sihl . Web . ( choose [ get " " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " foo " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " bar " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ] ) in let paths = router |> Sihl . Web . routes_of_router |> List . map ( fun ( _ , path , _ ) -> path ) in Alcotest . ( check ( list string ) " builds paths " [ " " ; " / foo " ; " / bar " ] paths ) ; Lwt . return ( ) ; ;
let choose_routers_with_empty_scope_builds_paths _ ( ) = let router = Sihl . Web . ( choose ~ scope " " : [ get " " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " " / ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " foo " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " bar " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ] ) in let paths = router |> Sihl . Web . routes_of_router |> List . map ( fun ( _ , path , _ ) -> path ) in Alcotest . ( check ( list string ) " builds paths " [ " " ; " " ; / " / foo " ; " / bar " ] paths ) ; Lwt . return ( ) ; ;
let choose_routers_with_slash_scope_builds_paths _ ( ) = let router = Sihl . Web . ( choose ~ scope " " :/ [ get " " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " foo " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " bar " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ] ) in let paths = router |> Sihl . Web . routes_of_router |> List . map ( fun ( _ , path , _ ) -> path ) in Alcotest . ( check ( list string ) " builds paths " [ " " ; / " / foo " ; " / bar " ] paths ) ; Lwt . return ( ) ; ;
let choose_routers_builds_paths _ ( ) = let router = Sihl . Web . ( choose ~ scope " :/ root " [ get " " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " " / ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " foo " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " bar " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ] ) in let paths = router |> Sihl . Web . routes_of_router |> List . map ( fun ( _ , path , _ ) -> path ) in Alcotest . ( check ( list string ) " builds paths " [ " / root " ; " / root " ; / " / root / foo " ; " / root / bar " ] paths ) ; Lwt . return ( ) ; ;
let choose_nested_routers_builds_paths _ ( ) = let router = Sihl . Web . ( choose ~ scope " :/ root " [ choose ~ scope " : sub " [ get " " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " foo " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ; get " fooz " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " " ) ] ; get " bar " ( fun _ -> Lwt . return @@ Opium . Response . of_plain_text " bar " ) ] ) in let paths = router |> Sihl . Web . routes_of_router |> List . map ( fun ( _ , path , _ ) -> path ) in Alcotest . ( check ( list string ) " builds paths " [ " / root / sub " ; " / root / sub / foo " ; " / root / sub / fooz " ; " / root / bar " ] paths ) ; Lwt . return ( ) ; ;
let externalize_link _ ( ) = let actual = Sihl . Web . externalize_path ~ prefix " : prefix " " foo / bar " in Alcotest . ( check string " prefixes path " " prefix / foo / bar " actual ) ; let actual = Sihl . Web . externalize_path ~ prefix " : prefix " " foo / bar " / in Alcotest . ( check string " preserve trailing " " prefix / foo / bar " / actual ) ; let actual = Sihl . Web . externalize_path ~ prefix " : prefix " " / foo / bar " / in Alcotest . ( check string " no duplicate slash " " prefix / foo / bar " / actual ) ; Lwt . return ( ) ; ;
let find_bearer_token _ ( ) = let token_value = " tokenvalue123 " in let token_header = Format . sprintf " Bearer % s " token_value in let req = Opium . Request . get " / some / path / login " |> Opium . Request . add_header ( " authorization " , token_header ) in let handler req = let token = Sihl . Web . Request . bearer_token req in Alcotest . ( check ( option string ) " has token " ( Some token_value ) token ) ; Lwt . return @@ Opium . Response . of_plain_text " " in let % lwt _ = handler req in Lwt . return ( ) ; ;
let find_bearer_token_with_space _ ( ) = let token_value = " tokenvalue123 and after space " in let token_header = Format . sprintf " Bearer % s " token_value in let req = Opium . Request . get " / some / path / login " |> Opium . Request . add_header ( " authorization " , token_header ) in let handler req = let token = Sihl . Web . Request . bearer_token req in Alcotest . ( check ( option string ) " has token " ( Some " tokenvalue123 " ) token ) ; Lwt . return @@ Opium . Response . of_plain_text " " in let % lwt _ = handler req in Lwt . return ( ) ; ;
let suite = [ ( " router " , [ test_case " choose routers without path builds paths " ` Quick choose_routers_without_path_builds_paths ; test_case " choose routers with empty scope builds paths " ` Quick choose_routers_with_empty_scope_builds_paths ; test_case " choose routers with slash scope builds paths " ` Quick choose_routers_with_slash_scope_builds_paths ; test_case " choose routers builds paths " ` Quick choose_routers_builds_paths ; test_case " choose nested routers builds paths " ` Quick choose_nested_routers_builds_paths ] ) ; " path " , [ test_case " prefix " ` Quick externalize_link ] ; ( " bearer token " , [ test_case " find bearer token " ` Quick find_bearer_token ; test_case " find bearer token with space " ` Quick find_bearer_token_with_space ] ) ] ; ;
let ( ) = Logs . set_level ( Sihl . Log . get_log_level ( ) ) ; Logs . set_reporter ( Sihl . Log . cli_reporter ( ) ) ; Lwt_main . run ( Alcotest_lwt . run " web " suite ) ; ;
type context = { arguments : ( string * string ) list ; connection : Cohttp_lwt_unix . Server . conn ; request : Cohttp . Request . t ; body : Cohttp_lwt . Body . t }
let headers = let h = Cohttp . Header . init_with " Access - Control - Allow - Origin " " " * in let h = Cohttp . Header . add h " content - type " " application / json " in h
let string_response ( ? headers = headers ) = Server . respond_string ~ headers
let error_response ( ? headers = headers ) ( ? status = ` Internal_server_error ) ( errors : Result_util . message list ) : ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = let error_msg : string = JsonUtil . string_of_write ( JsonUtil . write_list Result_util . write_message ) errors in let ( ) = Lwt . async ( fun ( ) -> Logs_lwt . debug ( fun m -> m " + error : % s " error_msg ) ) in Server . respond_string ~ headers ~ status ~ body : error_msg ( )
let api_result_response ( ~ string_of_success : ' ok -> string ) : ' ok Api . result -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = function | { Result_util . value = Result . Ok ok ; Result_util . status ; _ } -> let body : string = string_of_success ok in let status :> Cohttp . Code . status_code = status in Server . respond_string ~ headers ~ status ~ body ( ) | { Result_util . value = Result . Error errors ; Result_util . status ; _ } -> let error_msg : string = JsonUtil . string_of_write ( JsonUtil . write_list Result_util . write_message ) errors in let status :> Cohttp . Code . status_code = status in Logs_lwt . err ( fun m -> m " % s " error_msg ) >>= fun ( ) -> Server . respond_string ~ headers ~ status ~ body : error_msg ( )
let kasa_response ~ string_of_success x = api_result_response ~ string_of_success ( Api_common . result_kasa x )
let method_not_allowed_respond meths = let headers = Cohttp . Header . add_multi ( Cohttp . Header . init ( ) ) " Allow " ( List . map Cohttp . Code . string_of_method meths ) in Server . respond ~ headers ~ status ` : Method_not_allowed ~ body : Cohttp_lwt . Body . empty ( )
let options_respond methods = let meths_str = List . map Cohttp . Code . string_of_method methods in let headers = Cohttp . Header . init_with " Access - Control - Allow - Origin " " " * in let headers = Cohttp . Header . add headers " Access - Control - Allow - Headers " " Content - Type " in let headers = Cohttp . Header . add_multi headers " Allow " meths_str in let headers = Cohttp . Header . add_multi headers " Access - Control - Allow - Methods " meths_str in let headers = Cohttp . Header . add headers " Access - Control - Request - Headers " " X - Custom - Header " in Server . respond ~ headers ~ status ` : OK ~ body : Cohttp_lwt . Body . empty ( )
type ' a route = { path : string ; operation : ' a }
type route_handler = ( context : context -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t ) route
type route_filter = ( context : context -> chain ( : context : context -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t ) -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t ) route
type url_matcher = { re : Re . re ; labels : string list ; route : string }
let label_prepattern = Re . rep1 ( Re . alt [ Re . alnum ; Re . char ' _ ' ] )
let variable_pattern = Re . compile ( Re . seq [ Re . char ' { ' ; label_prepattern ; Re . char ' } ' ] )
let label_pattern = Re . compile label_prepattern
let create_url_matcher ( url : string ) : url_matcher = let labels = Re . matches variable_pattern url in let labels = List . flatten ( List . map ( Re . matches label_pattern ) labels ) in let pattern = Re . split_full variable_pattern url |> List . map ( function | ` Text s -> Re . str s | ` Delim _ -> Re . group ( Re . rep ( Re . compl [ Re . char ' ' ] ) ) ) / |> Re . seq |> Re . whole_string in let ( ) = Lwt . async ( fun ( ) -> Logs_lwt . debug ( fun m -> m " + route : % a " Re . pp pattern ) ) in let re = Re . compile pattern in { re ; labels ; route = url ; }
let rec match_url ( url_matchers : ( ' a * url_matcher ) list ) ( url : string ) : ( ' a * ( string * string ) list ) list = match url_matchers with | ( arg , matcher ) :: tail -> ( try let matching = Re . exec matcher . re url |> Re . Group . all |> Array . to_list |> List . tl in let get_parameters : ( string * string ) list = List . combine matcher . labels matching in let ( ) = Lwt . async ( fun ( ) -> Logs_lwt . debug ( fun m -> m " match_url :\ n + url : ' % s ' \ n + route : ' % s ' \ n + args : { [ @% a ] @ } " url matcher . route ( Pp . list Pp . comma ( fun f ( key , value ) -> Format . fprintf f " % s : % s " key value ) ) get_parameters ) ) in [ arg , get_parameters ] with Not_found -> [ ] ) ( @ match_url tail url ) | [ ] -> [ ]
let request_handler context = function | [ ] -> Server . respond_not_found ~ uri ( : Request . uri context . request ) ( ) | [ route , arguments ] -> Lwt . catch ( fun ( ) -> let context = { context with arguments = arguments } in route . operation ~ context ) ( fun exn -> api_result_response ~ string_of_success ( : fun x -> x ) ( match exn with | Yojson . Json_error e -> ( Api_common . result_error_msg e ) | exn -> ( Api_common . result_error_exception exn ) ) ) | _ :: _ -> error_response ? headers : None ? status : None [ Api_common . error_msg " multiple routes match url " ]
let route_handler ( routes : route_handler list ) : context : context -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = let url_matchers : ( route_handler * url_matcher ) list = List . map ( fun route -> ( route , create_url_matcher route . path ) ) routes in fun ~ context -> let url : string = Uri . pct_decode ( Uri . path ( Cohttp . Request . uri context . request ) ) in request_handler context ( match_url url_matchers url )
let inputString ( m : input ) : Pla . t = match m with | IContext -> Pla . string " processor . context " | IReal name | IInt name | IBool name -> Pla . string name
let inputName ( i , acc ) s = match s with | IContext -> i , Pla . string " processor . context " :: acc | _ -> i + 1 , [ % pla { | in_ <# i # i [ > n ] } ] | :: acc
let performFunctionCall module_name ( config : config ) = let args = List . fold_left inputName ( 0 , [ ] ) config . process_inputs |> snd |> List . rev |> Pla . join_sep Pla . comma in let copy = match config . process_outputs with | [ ] -> Pla . unit | [ _ ] -> let value = Pla . string " ret " in [ % pla { | out_0 [ n ] = <# value ; #> } ] | | o -> List . mapi ( fun i _ -> let value = [ % pla { |<# module_name # s > _process_ret_ <# i # i ( > processor . context ) } ] | in [ % pla { | out_ <# i # i [ > n ] = <# value ; #> } ] | ) o |> Pla . join_sep_all Pla . newline in [ % pla { | for ( var n = 0 ; n < e . inputBuffer . length ; n ) ++ { var ret = processor . <# module_name # s > _process ( <# args ) ; #> <#><# copy #> } } ] <#>|
let noteFunctions ( params : params ) = let module_name = params . module_name in let on_args = Pla . map_sep Pla . comma inputString params . config . noteon_inputs in let off_args = Pla . map_sep Pla . comma inputString params . config . noteoff_inputs in ( [ % pla { | node . noteOn = function ( note , velocity , channel ) { if ( velocity > 0 ) processor . <# module_name # s > _noteOn ( <# on_args ) ; #> else processor . <# module_name # s > _noteOff ( <# off_args ) ; #> } } ] | , [ % pla { | node . noteOff = function ( note , channel ) { processor . <# module_name # s > _noteOff ( <# off_args ) ; #> } } ] | )
let controlChangeFunction ( params : params ) = let module_name = params . module_name in let ctrl_args = Pla . map_sep Pla . comma inputString params . config . controlchange_inputs in [ % pla { | node . controlChange = function ( control , value , channel ) { processor . <# module_name # s > _controlChange ( <# ctrl_args ) ; #> } } ] |
let rec removeContext inputs = match inputs with | IContext :: t -> removeContext t | _ -> inputs
let get ( params : params ) runtime code : ( Pla . t * FileKind . t ) list = let config = params . config in let module_name = params . module_name in let inputs = removeContext config . process_inputs in let nprocess_inputs = List . length inputs in let nprocess_outputs = List . length config . process_outputs in let input_var = List . mapi ( fun i _ -> [ % pla { | var in_ <# i # i > = e . inputBuffer . getChannelData ( <# i # i ) ; > } ] ) | inputs |> Pla . join_sep Pla . newline in let output_var = List . mapi ( fun i _ -> [ % pla { | var out_ <# i # i > = e . outputBuffer . getChannelData ( <# i # i ) ; > } ] ) | config . process_outputs |> Pla . join_sep Pla . newline in let process_call = performFunctionCall params . module_name params . config in let note_on , note_off = noteFunctions params in let control_change = controlChangeFunction params in let text = [ % pla { | var code = function ( ) { <# runtime #> <# code #> this . context = this . <# module_name # s > _process_init ( ) ; } ; var processor = new code ( ) ; processor . <# module_name # s > _default ( processor . context ) ; var node = audioContext . createScriptProcessor ( 0 , <# nprocess_inputs # i , > <# nprocess_outputs # i ) ; > node . inputs = <# nprocess_inputs # i ; > node . outputs = <# nprocess_outputs # i ; > node . onaudioprocess = function ( e ) { <# input_var #+> <# output_var #+> <# process_call #+> } <# note_on #> <# note_off #> <# control_change #> return node ; } ) } ] | in [ text , FileKind . ExtOnly " js " ]
let oslo_polygon = { { | " type " : " Feature " , " geometry " : { " type " : " Polygon " , " coordinates " : [ [ [ 10 . 489165172838884 , 60 . 017259872374645 ] , [ 10 . 580764868996987 , 60 . 0762384207017 ] , [ 10 . 592122568549627 , 60 . 09394183519897 ] , [ 10 . 572782530207661 , 60 . 11678480264957 ] , [ 10 . 600720249305056 , 60 . 13160981872188 ] , [ 10 . 68031961054535 , 60 . 13353032001292 ] , [ 10 . 73711867703991 , 60 . 125733600579316 ] , [ 10 . 78802079942288 , 60 . 06755422118711 ] , [ 10 . 819765048019693 , 60 . 064296771632726 ] , [ 10 . 811720634337512 , 60 . 02561911878851 ] , [ 10 . 876109308200913 , 59 . 98547372050647 ] , [ 10 . 933734244914053 , 59 . 97416166211912 ] , [ 10 . 951389441905969 , 59 . 94924298867558 ] , [ 10 . 914816194580183 , 59 . 91161920924281 ] , [ 10 . 907158498257449 , 59 . 869893465966655 ] , [ 10 . 933102370207493 , 59 . 83659145034232 ] , [ 10 . 936527591798225 , 59 . 831669697457514 ] , [ 10 . 88029688872709 , 59 . 81138930328435 ] , [ 10 . 770788935602035 , 59 . 82510863617183 ] , [ 10 . 744019668227386 , 59 . 83928320264522 ] , [ 10 . 73100663891497 , 59 . 877178566827084 ] , [ 10 . 658082484659966 , 59 . 884410483442366 ] , [ 10 . 632783389561938 , 59 . 915118906971855 ] , [ 10 . 63388386110467 , 59 . 95342058502221 ] , [ 10 . 610456248652959 , 59 . 97660952873646 ] , [ 10 . 55585521816055 , 59 . 99672657430896 ] , [ 10 . 518070354830757 , 59 . 999291170702094 ] , [ 10 . 489165172838884 , 60 . 017259872374645 ] ] ] } , " properties " : { " kommunenummer " : " 0301 " , " objtype " : " Kommune " , " lokalid " : " 173018 " , " oppdateringsdato " : null , " datauttaksdato " : " 20191220110355 " , " versjonid " : " 4 . 1 " , " opphav " : null , " samiskforvaltningsomrade " : false , " datafangstdato " : null , " navnerom " : " http :// skjema . geonorge . no / SOSI / produktspesifikasjon / AdmEnheter / 4 . 1 " , " navn " : [ { " rekkefolge " : " " , " sprak " : " nor " , " navn " : " Oslo " } ] } } } | h " leafy - map " [ ] || [ h " leafy - feature - group " Prop . [ | bool " zoom - to - fit " true ] | [ h " leafy - geojson " Prop . [ | string " data " oslo_polygon ; string " fill " " forestgreen " ; string " stroke " " # 006400 " ; int " stroke - wdith " 1 ] | [ ] ; h " leafy - marker " Prop . [ | string " lat " " 59 . 9147857 " ; string " lng " " 10 . 7470423 " ; string " tooltip " " Hello Oslo " ! ] | [ ] ] ]
type objectType object method alpha : bool t prop method depth : bool t prop method stencil : bool t prop method antialias : bool t prop method premultipliedAlpha : bool t prop method preserveDrawingBuffer : bool t prop method preferLowPowerToHighPerformance : bool t prop method failIfMajorPerformanceCaveat : bool t prop end
let defaultContextAttributes = Js . Unsafe . ( obj [ | " alpha " , inject _true ; " depth " , inject _true ; " stencil " , inject _false ; " antialias " , inject _true ; " premultipliedAlpha " , inject _false ; " preserveDrawingBuffer " , inject _false ; " preferLowPowerToHighPerformance " , inject _false ; " failIfMajorPerformanceCaveat " , inject _false ] ) |
type ' a uniformLocation object method size : int readonly_prop method _type : uniformType readonly_prop method name : js_string t readonly_prop end object method rangeMin : int readonly_prop method rangeMax : int readonly_prop method precision : int readonly_prop end object method canvas : Dom_html . canvasElement t readonly_prop method drawingBufferWidth : sizei readonly_prop method drawingBufferHeight : sizei readonly_prop method getContextAttributes : contextAttributes t meth method activeTexture : textureUnit -> unit meth method blendColor : clampf -> clampf -> clampf -> clampf -> unit meth method blendEquation : blendMode -> unit meth method blendEquationSeparate : blendMode -> blendMode -> unit meth method blendFunc : blendingFactor -> blendingFactor -> unit meth method blendFuncSeparate : blendingFactor -> blendingFactor -> blendingFactor -> blendingFactor -> unit meth method clearColor : clampf -> clampf -> clampf -> clampf -> unit meth method clearDepth : clampf -> unit meth method clearStencil : int -> unit meth method colorMask : bool t -> bool t -> bool t -> bool t -> unit meth method cullFace : cullFaceMode -> unit meth method depthFunc : depthFunction -> unit meth method depthMask : bool t -> unit meth method depthRange : clampf -> clampf -> unit meth method disable : enableCap -> unit meth method enable : enableCap -> unit meth method frontFace : frontFaceDir -> unit meth method getParameter : ' a . ' a parameter -> ' a meth method getError : errorCode meth method hint : hintTarget -> hintMode -> unit meth method isEnabled : enableCap -> bool t meth method lineWidth : float -> unit meth method pixelStorei : ' a . ' a pixelStoreParam -> ' a -> unit meth method polygonOffset : float -> float -> unit meth method sampleCoverage : clampf -> bool t -> unit meth method stencilFunc : depthFunction -> int -> uint -> unit meth method stencilFuncSeparate : cullFaceMode -> depthFunction -> int -> uint -> unit meth method stencilMask : uint -> unit meth method stencilMaskSeparate : cullFaceMode -> uint -> unit meth method stencilOp : stencilOp -> stencilOp -> stencilOp -> unit meth method stencilOpSeparate : cullFaceMode -> stencilOp -> stencilOp -> stencilOp -> unit meth method scissor : int -> int -> sizei -> sizei -> unit meth method viewport : int -> int -> sizei -> sizei -> unit meth method bindBuffer : bufferTarget -> buffer t -> unit meth method bindBuffer_ : bufferTarget -> buffer t opt -> unit meth method bufferData_create : bufferTarget -> sizeiptr -> bufferUsage -> unit meth method bufferData : bufferTarget -> # Typed_array . arrayBufferView t -> bufferUsage -> unit meth method bufferData_raw : bufferTarget -> Typed_array . arrayBuffer t -> bufferUsage -> unit meth method bufferSubData : bufferTarget -> intptr -> # Typed_array . arrayBufferView t -> unit meth method bufferSubData_raw : bufferTarget -> intptr -> Typed_array . arrayBuffer t -> unit meth method createBuffer : buffer t meth method deleteBuffer : buffer t -> unit meth method getBufferParameter : ' a . bufferTarget -> ' a bufferParameter -> ' a meth method isBuffer : buffer t -> bool t meth method bindFramebuffer : fbTarget -> framebuffer t -> unit meth method bindFramebuffer_ : fbTarget -> framebuffer t opt -> unit meth method checkFramebufferStatus : fbTarget -> framebufferStatus meth method createFramebuffer : framebuffer t meth method deleteFramebuffer : framebuffer t -> unit meth method framebufferRenderbuffer : fbTarget -> attachmentPoint -> rbTarget -> renderbuffer t -> unit meth method framebufferTexture2D : fbTarget -> attachmentPoint -> texTarget -> texture t -> int -> unit meth method getFramebufferAttachmentParameter : ' a . fbTarget -> attachmentPoint -> ' a attachParam -> ' a meth method isFramebuffer : framebuffer t -> bool t meth method bindRenderbuffer : rbTarget -> renderbuffer t -> unit meth method bindRenderbuffer_ : rbTarget -> renderbuffer t opt -> unit meth method createRenderbuffer : renderbuffer t meth method deleteRenderbuffer : renderbuffer t -> unit meth method getRenderbufferParameter : ' a . rbTarget -> ' a renderbufferParam -> ' a meth method isRenderbuffer : renderbuffer t -> bool t meth method renderbufferStorage : rbTarget -> format -> sizei -> sizei -> unit meth method bindTexture : texTarget -> texture t -> unit meth method bindTexture_ : texTarget -> texture t opt -> unit meth method compressedTexImage2D : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> # Typed_array . arrayBufferView t -> unit meth method compressedTexSubImage2D : texTarget -> int -> int -> int -> sizei -> sizei -> pixelFormat -> # Typed_array . arrayBufferView t -> unit meth method copyTexImage2D : texTarget -> int -> pixelFormat -> int -> int -> sizei -> sizei -> int -> unit meth method copyTexSubImage2D : texTarget -> int -> int -> int -> int -> int -> sizei -> sizei -> unit meth method createTexture : texture t meth method deleteTexture : texture t -> unit meth method generateMipmap : texTarget -> unit meth method getTexParameter : texTarget -> ' a texParam -> ' a meth method isTexture : texture t -> bool t meth method texImage2D_new : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> pixelFormat -> pixelType -> void opt -> unit meth method texImage2D_fromView : texTarget -> int -> pixelFormat -> sizei -> sizei -> int -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method texImage2D_fromImageData : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . imageData t -> unit meth method texImage2D_fromImage : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . imageElement t -> unit meth method texImage2D_fromCanvas : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . canvasElement t -> unit meth method texImage2D_fromVideo : texTarget -> int -> pixelFormat -> pixelFormat -> pixelType -> Dom_html . videoElement t -> unit meth method texParameteri : texTarget -> ' a texParam -> ' a -> unit meth method texSubImage2D_fromView : texTarget -> int -> int -> int -> sizei -> sizei -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method texSubImage2D_fromImageData : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . imageData t -> unit meth method texSubImage2D_fromImage : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . imageElement t -> unit meth method texSubImage2D_fromCanvas : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . canvasElement t -> unit meth method texSubImage2D_fromVideo : texTarget -> int -> int -> int -> pixelFormat -> pixelType -> Dom_html . videoElement t -> unit meth method attachShader : program t -> shader t -> unit meth method bindAttribLocation : program t -> uint -> js_string t -> unit meth method compileShader : shader t -> unit meth method createProgram : program t meth method createShader : shaderType -> shader t meth method deleteProgram : program t -> unit meth method deleteShader : shader t -> unit meth method detachShader : program t -> shader t -> unit meth method getAttachedShaders : program t -> shader t js_array t meth method getProgramParameter : ' a . program t -> ' a programParam -> ' a meth method getProgramInfoLog : program t -> js_string t meth method getShaderParameter : ' a . shader t -> ' a shaderParam -> ' a meth method getShaderPrecisionFormat : shaderType -> shaderPrecisionType -> shaderPrecisionFormat t meth method getShaderInfoLog : shader t -> js_string t meth method getShaderSource : shader t -> js_string t meth method isProgram : program t -> bool t meth method isShader : shader t -> bool t meth method linkProgram : program t -> unit meth method shaderSource : shader t -> js_string t -> unit meth method useProgram : program t -> unit meth method validateProgram : program t -> unit meth method disableVertexAttribArray : uint -> unit meth method enableVertexAttribArray : uint -> unit meth method getActiveAttrib : program t -> uint -> activeInfo t meth method getActiveUniform : program t -> uint -> activeInfo t meth method getAttribLocation : program t -> js_string t -> int meth method getUniform : ' a ' b . program t -> ' a uniformLocation t -> ' b meth method getUniformLocation : ' a . program t -> js_string t -> ' a uniformLocation t meth method getVertexAttrib : ' a . uint -> ' a vertexAttribParam -> ' a meth method getVertexAttribOffset : uint -> vertexAttribPointerParam -> sizeiptr meth method uniform1f : float uniformLocation t -> float -> unit meth method uniform1fv_typed : float uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform1fv : float uniformLocation t -> float js_array t -> unit meth method uniform1i : int uniformLocation t -> int -> unit meth method uniform1iv_typed : int uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform1iv : int uniformLocation t -> int js_array t -> unit meth method uniform2f : [ ` vec2 ] uniformLocation t -> float -> float -> unit meth method uniform2fv_typed : [ ` vec2 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform2fv : [ ` vec2 ] uniformLocation t -> float js_array t -> unit meth method uniform2i : [ ` ivec2 ] uniformLocation t -> int -> int -> unit meth method uniform2iv : [ ` ivec2 ] uniformLocation t -> int js_array t -> unit meth method uniform2iv_typed : [ ` ivec2 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform3f : [ ` vec3 ] uniformLocation t -> float -> float -> float -> unit meth method uniform3fv_typed : [ ` vec3 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform3fv : [ ` vec3 ] uniformLocation t -> float js_array t -> unit meth method uniform3i : [ ` ivec3 ] uniformLocation t -> int -> int -> int -> unit meth method uniform3iv : [ ` ivec3 ] uniformLocation t -> int js_array t -> unit meth method uniform3iv_typed : [ ` ivec3 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniform4f : [ ` vec4 ] uniformLocation t -> float -> float -> float -> float -> unit meth method uniform4fv_typed : [ ` vec4 ] uniformLocation t -> Typed_array . float32Array t -> unit meth method uniform4fv : [ ` vec4 ] uniformLocation t -> float js_array t -> unit meth method uniform4i : [ ` ivec4 ] uniformLocation t -> int -> int -> int -> int -> unit meth method uniform4iv : [ ` ivec4 ] uniformLocation t -> int js_array t -> unit meth method uniform4iv_typed : [ ` ivec4 ] uniformLocation t -> Typed_array . int32Array t -> unit meth method uniformMatrix2fv : [ ` mat2 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix2fv_typed : [ ` mat2 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method uniformMatrix3fv : [ ` mat3 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix3fv_typed : [ ` mat3 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method uniformMatrix4fv : [ ` mat4 ] uniformLocation t -> bool t -> float js_array t -> unit meth method uniformMatrix4fv_typed : [ ` mat4 ] uniformLocation t -> bool t -> Typed_array . float32Array t -> unit meth method vertexAttrib1f : uint -> float -> unit meth method vertexAttrib1fv : uint -> float js_array t -> unit meth method vertexAttrib1fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib2f : uint -> float -> float -> unit meth method vertexAttrib2fv : uint -> float js_array t -> unit meth method vertexAttrib2fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib3f : uint -> float -> float -> float -> unit meth method vertexAttrib3fv : uint -> float js_array t -> unit meth method vertexAttrib3fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttrib4f : uint -> float -> float -> float -> float -> unit meth method vertexAttrib4fv : uint -> float js_array t -> unit meth method vertexAttrib4fv_typed : uint -> Typed_array . float32Array t -> unit meth method vertexAttribPointer : uint -> int -> dataType -> bool t -> sizei -> intptr -> unit meth method clear : clearBufferMask -> unit meth method drawArrays : beginMode -> int -> sizei -> unit meth method drawElements : beginMode -> sizei -> dataType -> intptr -> unit meth method finish : unit meth method flush : unit meth method readPixels : int -> int -> sizei -> sizei -> pixelFormat -> pixelType -> # Typed_array . arrayBufferView t -> unit meth method isContextLost : bool t meth method getSupportedExtensions : js_string t js_array t meth method getExtension : ' a . js_string t -> ' a t opt meth method _DEPTH_BUFFER_BIT_ : clearBufferMask readonly_prop method _STENCIL_BUFFER_BIT_ : clearBufferMask readonly_prop method _COLOR_BUFFER_BIT_ : clearBufferMask readonly_prop method _POINTS : beginMode readonly_prop method _LINES : beginMode readonly_prop method _LINE_LOOP_ : beginMode readonly_prop method _LINE_STRIP_ : beginMode readonly_prop method _TRIANGLES : beginMode readonly_prop method _TRIANGLE_STRIP_ : beginMode readonly_prop method _TRIANGLE_FAN_ : beginMode readonly_prop method _ZERO : blendingFactor readonly_prop method _ONE : blendingFactor readonly_prop method _SRC_COLOR_ : blendingFactor readonly_prop method _ONE_MINUS_SRC_COLOR_ : blendingFactor readonly_prop method _SRC_ALPHA_ : blendingFactor readonly_prop method _ONE_MINUS_SRC_ALPHA_ : blendingFactor readonly_prop method _DST_ALPHA_ : blendingFactor readonly_prop method _ONE_MINUS_DST_ALPHA_ : blendingFactor readonly_prop method _DST_COLOR_ : blendingFactor readonly_prop method _ONE_MINUS_DST_COLOR_ : blendingFactor readonly_prop method _SRC_ALPHA_SATURATE_ : blendingFactor readonly_prop method _FUNC_ADD_ : blendMode readonly_prop method _FUNC_SUBTRACT_ : blendMode readonly_prop method _FUNC_REVERSE_SUBTRACT_ : blendMode readonly_prop method _CONSTANT_COLOR_ : blendMode readonly_prop method _ONE_MINUS_CONSTANT_COLOR_ : blendMode readonly_prop method _CONSTANT_ALPHA_ : blendMode readonly_prop method _ONE_MINUS_CONSTANT_ALPHA_ : blendMode readonly_prop method _ARRAY_BUFFER_ : bufferTarget readonly_prop method _ELEMENT_ARRAY_BUFFER_ : bufferTarget readonly_prop method _STREAM_DRAW_ : bufferUsage readonly_prop method _STATIC_DRAW_ : bufferUsage readonly_prop method _DYNAMIC_DRAW_ : bufferUsage readonly_prop method _FRONT : cullFaceMode readonly_prop method _BACK : cullFaceMode readonly_prop method _FRONT_AND_BACK_ : cullFaceMode readonly_prop method _CULL_FACE_ : enableCap readonly_prop method _BLEND : enableCap readonly_prop method _DITHER : enableCap readonly_prop method _STENCIL_TEST_ : enableCap readonly_prop method _DEPTH_TEST_ : enableCap readonly_prop method _SCISSOR_TEST_ : enableCap readonly_prop method _POLYGON_OFFSET_FILL_ : enableCap readonly_prop method _SAMPLE_ALPHA_TO_COVERAGE_ : enableCap readonly_prop method _SAMPLE_COVERAGE_ : enableCap readonly_prop method _NO_ERROR_ : errorCode readonly_prop method _INVALID_ENUM_ : errorCode readonly_prop method _INVALID_VALUE_ : errorCode readonly_prop method _INVALID_OPERATION_ : errorCode readonly_prop method _OUT_OF_MEMORY_ : errorCode readonly_prop method _CONTEXT_LOST_WEBGL_ : errorCode readonly_prop method _INVALID_FRAMEBUFFER_OPERATION_ : errorCode readonly_prop method _CW : frontFaceDir readonly_prop method _CCW : frontFaceDir readonly_prop method _DONT_CARE_ : hintMode readonly_prop method _FASTEST : hintMode readonly_prop method _NICEST : hintMode readonly_prop method _GENERATE_MIPMAP_HINT_ : hintTarget readonly_prop method _BLEND_EQUATION_ : blendMode parameter readonly_prop method _BLEND_EQUATION_RGB_ : blendMode parameter readonly_prop method _BLEND_EQUATION_ALPHA_ : blendMode parameter readonly_prop method _BLEND_DST_RGB_ : blendingFactor parameter readonly_prop method _BLEND_SRC_RGB_ : blendingFactor parameter readonly_prop method _BLEND_DST_ALPHA_ : blendingFactor parameter readonly_prop method _BLEND_SRC_ALPHA_ : blendingFactor parameter readonly_prop method _BLEND_COLOR_ : Typed_array . float32Array t parameter readonly_prop method _ARRAY_BUFFER_BINDING_ : buffer t opt parameter readonly_prop method _ELEMENT_ARRAY_BUFFER_BINDING_ : buffer t opt parameter readonly_prop method _CULL_FACE_PARAM : bool t parameter readonly_prop method _BLEND_PARAM : bool t parameter readonly_prop method _DITHER_PARAM : bool t parameter readonly_prop method _STENCIL_TEST_PARAM : bool t parameter readonly_prop method _DEPTH_TEST_PARAM : bool t parameter readonly_prop method _SCISSOR_TEST_PARAM : bool t parameter readonly_prop method _POLYGON_OFFSET_FILL_PARAM : bool t parameter readonly_prop method _LINE_WIDTH_ : float parameter readonly_prop method _ALIASED_POINT_SIZE_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _ALIASED_LINE_WIDTH_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _CULL_FACE_MODE_ : cullFaceMode parameter readonly_prop method _FRONT_FACE_ : frontFaceDir parameter readonly_prop method _DEPTH_RANGE_ : Typed_array . float32Array t parameter readonly_prop method _DEPTH_WRITEMASK_ : bool t parameter readonly_prop method _DEPTH_CLEAR_VALUE_ : float parameter readonly_prop method _DEPTH_FUNC_ : depthFunction parameter readonly_prop method _STENCIL_CLEAR_VALUE_ : int parameter readonly_prop method _STENCIL_FUNC_ : int parameter readonly_prop method _STENCIL_FAIL_ : int parameter readonly_prop method _STENCIL_PASS_DEPTH_FAIL_ : int parameter readonly_prop method _STENCIL_PASS_DEPTH_PASS_ : int parameter readonly_prop method _STENCIL_REF_ : int parameter readonly_prop method _STENCIL_VALUE_MASK_ : int parameter readonly_prop method _STENCIL_WRITEMASK_ : int parameter readonly_prop method _STENCIL_BACK_FUNC_ : int parameter readonly_prop method _STENCIL_BACK_FAIL_ : int parameter readonly_prop method _STENCIL_BACK_PASS_DEPTH_FAIL_ : int parameter readonly_prop method _STENCIL_BACK_PASS_DEPTH_PASS_ : int parameter readonly_prop method _STENCIL_BACK_REF_ : int parameter readonly_prop method _STENCIL_BACK_VALUE_MASK_ : int parameter readonly_prop method _STENCIL_BACK_WRITEMASK_ : int parameter readonly_prop method _VIEWPORT : Typed_array . int32Array t parameter readonly_prop method _SCISSOR_BOX_ : Typed_array . int32Array t parameter readonly_prop method _COLOR_CLEAR_VALUE_ : Typed_array . float32Array t parameter readonly_prop method _COLOR_WRITEMASK_ : bool t js_array t parameter readonly_prop method _UNPACK_ALIGNMENT_PARAM : int parameter readonly_prop method _PACK_ALIGNMENT_ : int parameter readonly_prop method _MAX_TEXTURE_SIZE_ : int parameter readonly_prop method _MAX_VIEWPORT_DIMS_ : Typed_array . int32Array t parameter readonly_prop method _SUBPIXEL_BITS_ : int parameter readonly_prop method _RED_BITS_ : int parameter readonly_prop method _GREEN_BITS_ : int parameter readonly_prop method _BLUE_BITS_ : int parameter readonly_prop method _ALPHA_BITS_ : int parameter readonly_prop method _DEPTH_BITS_ : int parameter readonly_prop method _STENCIL_BITS_ : int parameter readonly_prop method _POLYGON_OFFSET_UNITS_ : float parameter readonly_prop method _POLYGON_OFFSET_FACTOR_ : float parameter readonly_prop method _TEXTURE_BINDING_2D_ : texture t opt parameter readonly_prop method _TEXTURE_BINDING_CUBE_MAP_ : texture t opt parameter readonly_prop method _SAMPLE_BUFFERS_ : int parameter readonly_prop method _SAMPLES_ : int parameter readonly_prop method _SAMPLE_COVERAGE_VALUE_ : float parameter readonly_prop method _SAMPLE_COVERAGE_INVERT_ : bool t parameter readonly_prop method _NUM_COMPRESSED_TEXTURE_FORMATS_ : int parameter readonly_prop method _COMPRESSED_TEXTURE_FORMATS_ : Typed_array . uint32Array t parameter readonly_prop method _GENERATE_MIPMAP_HINT_PARAM_ : hintMode parameter readonly_prop method _BUFFER_SIZE_ : int bufferParameter readonly_prop method _BUFFER_USAGE_ : bufferUsage bufferParameter readonly_prop method _BYTE : dataType readonly_prop method _UNSIGNED_BYTE_DT : dataType readonly_prop method _SHORT : dataType readonly_prop method _UNSIGNED_SHORT_ : dataType readonly_prop method _INT : dataType readonly_prop method _UNSIGNED_INT_ : dataType readonly_prop method _FLOAT : dataType readonly_prop method _UNSIGNED_BYTE_ : pixelType readonly_prop method _UNSIGNED_SHORT_4_4_4_4_ : pixelType readonly_prop method _UNSIGNED_SHORT_5_5_5_1_ : pixelType readonly_prop method _UNSIGNED_SHORT_5_6_5_ : pixelType readonly_prop method _ALPHA : pixelFormat readonly_prop method _RGB : pixelFormat readonly_prop method _RGBA : pixelFormat readonly_prop method _LUMINANCE : pixelFormat readonly_prop method _LUMINANCE_ALPHA_ : pixelFormat readonly_prop method _STENCIL_INDEX_ : pixelFormat readonly_prop method _DEPTH_STENCIL_ : pixelFormat readonly_prop method _DEPTH_COMPONENT_ : pixelFormat readonly_prop method _FRAGMENT_SHADER_ : shaderType readonly_prop method _VERTEX_SHADER_ : shaderType readonly_prop method _MAX_VERTEX_ATTRIBS_ : int parameter readonly_prop method _MAX_VERTEX_UNIFORM_VECTORS_ : int parameter readonly_prop method _MAX_VARYING_VECTORS_ : int parameter readonly_prop method _MAX_COMBINED_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_VERTEX_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_TEXTURE_IMAGE_UNITS_ : int parameter readonly_prop method _MAX_FRAGMENT_UNIFORM_VECTORS_ : int parameter readonly_prop method _SHADER_TYPE_ : shaderType shaderParam readonly_prop method _DELETE_STATUS_ : bool t shaderParam readonly_prop method _COMPILE_STATUS_ : bool t shaderParam readonly_prop method _DELETE_STATUS_PROG : bool t programParam readonly_prop method _LINK_STATUS_ : bool t programParam readonly_prop method _VALIDATE_STATUS_ : bool t programParam readonly_prop method _ATTACHED_SHADERS_ : int programParam readonly_prop method _ACTIVE_UNIFORMS_ : int programParam readonly_prop method _ACTIVE_ATTRIBUTES_ : int programParam readonly_prop method _SHADING_LANGUAGE_VERSION_ : js_string t parameter readonly_prop method _CURRENT_PROGRAM_ : program t opt parameter readonly_prop method _VENDOR : js_string t parameter readonly_prop method _RENDERER : js_string t parameter readonly_prop method _VERSION : js_string t parameter readonly_prop method _MAX_CUBE_MAP_TEXTURE_SIZE_ : int parameter readonly_prop method _ACTIVE_TEXTURE_ : int parameter readonly_prop method _FRAMEBUFFER_BINDING_ : framebuffer t opt parameter readonly_prop method _RENDERBUFFER_BINDING_ : renderbuffer t opt parameter readonly_prop method _MAX_RENDERBUFFER_SIZE : int parameter readonly_prop method _NEVER : depthFunction readonly_prop method _LESS : depthFunction readonly_prop method _EQUAL : depthFunction readonly_prop method _LEQUAL : depthFunction readonly_prop method _GREATER : depthFunction readonly_prop method _NOTEQUAL : depthFunction readonly_prop method _GEQUAL : depthFunction readonly_prop method _ALWAYS : depthFunction readonly_prop method _KEEP : stencilOp readonly_prop method _REPLACE : stencilOp readonly_prop method _INCR : stencilOp readonly_prop method _DECR : stencilOp readonly_prop method _INVERT : stencilOp readonly_prop method _INCR_WRAP_ : stencilOp readonly_prop method _DECR_WRAP_ : stencilOp readonly_prop method _ZERO_ : stencilOp readonly_prop method _NEAREST : texFilter readonly_prop method _LINEAR : texFilter readonly_prop method _NEAREST_MIPMAP_NEAREST_ : texFilter readonly_prop method _LINEAR_MIPMAP_NEAREST_ : texFilter readonly_prop method _NEAREST_MIPMAP_LINEAR_ : texFilter readonly_prop method _LINEAR_MIPMAP_LINEAR_ : texFilter readonly_prop method _TEXTURE_MAG_FILTER_ : texFilter texParam readonly_prop method _TEXTURE_MIN_FILTER_ : texFilter texParam readonly_prop method _TEXTURE_WRAP_S_ : wrapMode texParam readonly_prop method _TEXTURE_WRAP_T_ : wrapMode texParam readonly_prop method _NONE_OT : objectType readonly_prop method _TEXTURE_OT : objectType readonly_prop method _RENDERBUFFER_OT : objectType readonly_prop method _TEXTURE_2D_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_X_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_X_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_Y_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_Y_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_POSITIVE_Z_ : texTarget readonly_prop method _TEXTURE_CUBE_MAP_NEGATIVE_Z_ : texTarget readonly_prop method _TEXTURE0 : textureUnit readonly_prop method _TEXTURE1 : textureUnit readonly_prop method _TEXTURE2 : textureUnit readonly_prop method _TEXTURE3 : textureUnit readonly_prop method _TEXTURE4 : textureUnit readonly_prop method _TEXTURE5 : textureUnit readonly_prop method _TEXTURE6 : textureUnit readonly_prop method _TEXTURE7 : textureUnit readonly_prop method _TEXTURE8 : textureUnit readonly_prop method _TEXTURE9 : textureUnit readonly_prop method _TEXTURE10 : textureUnit readonly_prop method _TEXTURE11 : textureUnit readonly_prop method _TEXTURE12 : textureUnit readonly_prop method _TEXTURE13 : textureUnit readonly_prop method _TEXTURE14 : textureUnit readonly_prop method _TEXTURE15 : textureUnit readonly_prop method _TEXTURE16 : textureUnit readonly_prop method _TEXTURE17 : textureUnit readonly_prop method _TEXTURE18 : textureUnit readonly_prop method _TEXTURE19 : textureUnit readonly_prop method _TEXTURE20 : textureUnit readonly_prop method _TEXTURE21 : textureUnit readonly_prop method _TEXTURE22 : textureUnit readonly_prop method _TEXTURE23 : textureUnit readonly_prop method _TEXTURE24 : textureUnit readonly_prop method _TEXTURE25 : textureUnit readonly_prop method _TEXTURE26 : textureUnit readonly_prop method _TEXTURE27 : textureUnit readonly_prop method _TEXTURE28 : textureUnit readonly_prop method _TEXTURE29 : textureUnit readonly_prop method _TEXTURE30 : textureUnit readonly_prop method _TEXTURE31 : textureUnit readonly_prop method _REPEAT : wrapMode readonly_prop method _CLAMP_TO_EDGE_ : wrapMode readonly_prop method _MIRRORED_REPEAT_ : wrapMode readonly_prop method _FLOAT_ : uniformType readonly_prop method _FLOAT_VEC2_ : uniformType readonly_prop method _FLOAT_VEC3_ : uniformType readonly_prop method _FLOAT_VEC4_ : uniformType readonly_prop method _INT_ : uniformType readonly_prop method _INT_VEC2_ : uniformType readonly_prop method _INT_VEC3_ : uniformType readonly_prop method _INT_VEC4_ : uniformType readonly_prop method _BOOL_ : uniformType readonly_prop method _BOOL_VEC2_ : uniformType readonly_prop method _BOOL_VEC3_ : uniformType readonly_prop method _BOOL_VEC4_ : uniformType readonly_prop method _FLOAT_MAT2_ : uniformType readonly_prop method _FLOAT_MAT3_ : uniformType readonly_prop method _FLOAT_MAT4_ : uniformType readonly_prop method _SAMPLER_2D_ : uniformType readonly_prop method _SAMPLER_CUBE_ : uniformType readonly_prop method _VERTEX_ATTRIB_ARRAY_ENABLED_ : bool t vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_SIZE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_STRIDE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_TYPE_ : int vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_NORMALIZED_ : bool t vertexAttribParam readonly_prop method _VERTEX_ATTRIB_ARRAY_POINTER_ : vertexAttribPointerParam readonly_prop method _VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ : buffer t opt vertexAttribParam readonly_prop method _CURRENT_VERTEX_ATTRIB_ : Typed_array . float32Array t vertexAttribParam readonly_prop method _LOW_FLOAT_ : shaderPrecisionType readonly_prop method _MEDIUM_FLOAT_ : shaderPrecisionType readonly_prop method _HIGH_FLOAT_ : shaderPrecisionType readonly_prop method _LOW_INT_ : shaderPrecisionType readonly_prop method _MEDIUM_INT_ : shaderPrecisionType readonly_prop method _HIGH_INT_ : shaderPrecisionType readonly_prop method _FRAMEBUFFER : fbTarget readonly_prop method _RENDERBUFFER : rbTarget readonly_prop method _RGBA4 : format readonly_prop method _RGB5_A1_ : format readonly_prop method _RGB565 : format readonly_prop method _DEPTH_COMPONENT16_ : format readonly_prop method _STENCIL_INDEX8_ : format readonly_prop method _RENDERBUFFER_WIDTH_ : int renderbufferParam readonly_prop method _RENDERBUFFER_HEIGHT_ : int renderbufferParam readonly_prop method _RENDERBUFFER_INTERNAL_FORMAT_ : format renderbufferParam readonly_prop method _RENDERBUFFER_RED_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_GREEN_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_BLUE_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_ALPHA_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_DEPTH_SIZE_ : int renderbufferParam readonly_prop method _RENDERBUFFER_STENCIL_SIZE_ : int renderbufferParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_ : objectType attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_RENDERBUFFER : renderbuffer t attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_TEXTURE : texture t attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_ : int attachParam readonly_prop method _FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_ : int attachParam readonly_prop method _COLOR_ATTACHMENT0_ : attachmentPoint readonly_prop method _DEPTH_ATTACHMENT_ : attachmentPoint readonly_prop method _STENCIL_ATTACHMENT_ : attachmentPoint readonly_prop method _DEPTH_STENCIL_ATTACHMENT_ : attachmentPoint readonly_prop method _FRAMEBUFFER_COMPLETE_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_ATTACHMENT_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_ : framebufferStatus readonly_prop method _FRAMEBUFFER_INCOMPLETE_DIMENSIONS_ : framebufferStatus readonly_prop method _FRAMEBUFFER_UNSUPPORTED_ : framebufferStatus readonly_prop method _UNPACK_FLIP_Y_WEBGL_PARAM : bool t parameter readonly_prop method _UNPACK_PREMULTIPLY_ALPHA_WEBGL_PARAM : bool t parameter readonly_prop method _UNPACK_COLORSPACE_CONVERSION_WEBGL_PARAM : colorspaceConversion parameter readonly_prop method _NONE : colorspaceConversion readonly_prop method _BROWSER_DEFAULT_WEBGL_ : colorspaceConversion readonly_prop method _UNPACK_ALIGNMENT_ : int pixelStoreParam readonly_prop method _UNPACK_FLIP_Y_WEBGL_ : bool t pixelStoreParam readonly_prop method _UNPACK_PREMULTIPLY_ALPHA_WEBGL_ : bool t pixelStoreParam readonly_prop method _UNPACK_COLORSPACE_CONVERSION_WEBGL_ : int pixelStoreParam readonly_prop end object inherit Dom_html . event method statusMessage : js_string t readonly_prop end
module Event = struct let webglcontextlost = Dom_html . Event . make " webglcontextlost " let webglcontextrestored = Dom_html . Event . make " webglcontextrestored " let webglcontextcreationerror = Dom_html . Event . make " webglcontextcreationerror " end object method getContext : js_string t -> renderingContext t opt meth method getContext_ : js_string t -> contextAttributes t -> renderingContext t opt meth end
let getContext ( c : Dom_html . canvasElement t ) = let c : canvasElement t = Js . Unsafe . coerce c in let ctx = c ## getContext ( Js . string " webgl " ) in if Opt . test ctx then ctx else c ## ( getContext ( Js . string " experimental - webgl " ) )
let getContextWithAttributes ( c : Dom_html . canvasElement t ) attribs = let c : canvasElement t = Js . Unsafe . coerce c in let ctx = c ## getContext_ ( Js . string " webgl " ) attribs in if Opt . test ctx then ctx else c ## getContext_ ( Js . string " experimental - webgl " ) attribs
let error f = Printf . ksprintf ( fun s -> Firebug . console ## error ( Js . string s ) ; failwith s ) f
let debug f = Printf . ksprintf ( fun s -> Firebug . console ## log ( Js . string s ) ) f
let alert f = Printf . ksprintf ( fun s -> Dom_html . window ## alert ( Js . string s ) ; failwith s ) f
let check_error gl = if gl ## getError <> gl . ## _NO_ERROR_ then error " WebGL error "
let init_canvas canvas_id = let canvas = Opt . get ( Opt . bind ( Dom_html . document ## getElementById ( string canvas_id ) ) Dom_html . CoerceTo . canvas ) ( fun ( ) -> error " can ' t find canvas element % s " canvas_id ) in let gl = Opt . get ( try WebGL . getContext canvas with _ -> null ) ( fun ( ) -> alert " can ' t initialise webgl context " ) in canvas , gl
let load_shader ( gl : WebGL . renderingContext t ) shader text = gl ## shaderSource shader text ; gl ## compileShader shader ; if not ( to_bool ( gl ## getShaderParameter shader gl . ## _COMPILE_STATUS_ ) ) then error " An error occurred compiling the shaders : \ n % s \ n % s " ( to_string text ) ( to_string ( gl ## getShaderInfoLog shader ) )
let create_program ( gl : WebGL . renderingContext t ) vert_src frag_src = let vertexShader = gl ## createShader gl . ## _VERTEX_SHADER_ in let fragmentShader = gl ## createShader gl . ## _FRAGMENT_SHADER_ in load_shader gl vertexShader vert_src ; load_shader gl fragmentShader frag_src ; let prog = gl ## createProgram in gl ## attachShader prog vertexShader ; gl ## attachShader prog fragmentShader ; gl ## linkProgram prog ; if not ( to_bool ( gl ## getProgramParameter prog gl . ## _LINK_STATUS_ ) ) then error " Unable to link the shader program . " ; prog
let get_source src_id = let script = Opt . get ( Opt . bind ( Dom_html . document ## getElementById ( string src_id ) ) Dom_html . CoerceTo . script ) ( fun ( ) -> error " can ' t find script element % s " src_id ) in script . ## text
let float32array a = let array = new % js Typed_array . float32Array ( Array . length a ) in Array . iteri ( fun i v -> Typed_array . set array i v ) a ; array
module Proj3D = struct type t = float array let scale x y z : t = [ | x ; 0 . ; 0 . ; 0 . ; 0 . ; y ; 0 . ; 0 . ; 0 . ; 0 . ; z ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let translate x y z : t = [ | 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; x ; y ; z ; 1 . ] | let rotate_x t : t = [ | 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; cos t ; sin t ; 0 . ; 0 . ; . - sin t ; cos t ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let rotate_y t : t = [ | cos t ; 0 . ; . - sin t ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; sin t ; 0 . ; cos t ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ] | let c i j = ( i * 4 ) + j let o i = i / 4 , i mod 4 let mult m1 m2 = let v p = let i , j = o p in ( m1 . ( c i 0 ) . * m2 . ( c 0 j ) ) . + ( m1 . ( c i 1 ) . * m2 . ( c 1 j ) ) . + ( m1 . ( c i 2 ) . * m2 . ( c 2 j ) ) . + ( m1 . ( c i 3 ) . * m2 . ( c 3 j ) ) in Array . init 16 v let array m = float32array m end
type line = | V of ( float * float * float ) | VN of ( float * float * float ) | F of ( ( int * int ) * ( int * int ) * ( int * int ) )
let line_regexp = Regexp . regexp " ( v | vn | f ) \\ ( [ ^\\ ] ) +\\ ( [ ^\\ ] ) +\\ ( [ ^\\ ] ) " +
let couple_regexp = Regexp . regexp " ( [ 0 - 9 ] ) ( [ +// 0 - 9 ] ) " +
let read_coord_couple c = match Regexp . string_match couple_regexp c 0 with | None -> None | Some res -> ( match List . map ( Regexp . matched_group res ) [ 1 ; 2 ] with | [ Some v ; Some vn ] -> Some ( int_of_string v , int_of_string vn ) | _ -> None )
let read_line l = match Regexp . string_match line_regexp l 0 with | None -> None | Some res -> ( match List . map ( Regexp . matched_group res ) [ 1 ; 2 ; 3 ; 4 ] with | [ Some " v " ; Some x ; Some y ; Some z ] -> Some ( V ( float_of_string x , float_of_string y , float_of_string z ) ) | [ Some " vn " ; Some x ; Some y ; Some z ] -> Some ( VN ( float_of_string x , float_of_string y , float_of_string z ) ) | [ Some " f " ; Some x ; Some y ; Some z ] -> ( match List . map read_coord_couple [ x ; y ; z ] with | [ Some x ; Some y ; Some z ] -> Some ( F ( x , y , z ) ) | _ -> None ) | _ -> None )
let concat a = let length = Array . fold_left ( fun len l -> len + List . length l ) 0 a in let next = let pos = ref ( - 1 ) in let l = ref [ ] in let rec aux _ = match ! l with | t :: q -> l := q ; t | [ ] -> incr pos ; l := a . ( ! pos ) ; aux 0 in aux in Array . init length next
let make_model vertex norm face = let vertex ' = Array . init ( Array . length face ) ( fun i -> let ( av , _an ) , ( bv , _bn ) , ( cv , _cn ) = face . ( i ) in let a1 , a2 , a3 = vertex . ( av - 1 ) in let b1 , b2 , b3 = vertex . ( bv - 1 ) in let c1 , c2 , c3 = vertex . ( cv - 1 ) in [ a1 ; a2 ; a3 ; b1 ; b2 ; b3 ; c1 ; c2 ; c3 ] ) in let norm ' = Array . init ( Array . length face ) ( fun i -> let ( _av , an ) , ( _bv , bn ) , ( _cv , cn ) = face . ( i ) in let a1 , a2 , a3 = norm . ( an - 1 ) in let b1 , b2 , b3 = norm . ( bn - 1 ) in let c1 , c2 , c3 = norm . ( cn - 1 ) in [ a1 ; a2 ; a3 ; b1 ; b2 ; b3 ; c1 ; c2 ; c3 ] ) in let vertex = float32array ( concat vertex ' ) in let norm = float32array ( concat norm ' ) in vertex , norm
let read_model a = let vertex = ref [ ] in let norm = ref [ ] in let face = ref [ ] in Array . iter ( fun s -> match read_line s with | None -> ( ) | Some ( F ( a , b , c ) ) -> face := ( a , b , c ) :: ! face | Some ( V ( a , b , c ) ) -> vertex := ( a , b , c ) :: ! vertex | Some ( VN ( a , b , c ) ) -> norm := ( a , b , c ) :: ! norm ) a ; make_model ( Array . of_list ( List . rev ! vertex ) ) ( Array . of_list ( List . rev ! norm ) ) ( Array . of_list ( List . rev ! face ) )
let http_get url = XmlHttpRequest . get url >>= fun r -> let cod = r . XmlHttpRequest . code in let msg = r . XmlHttpRequest . content in if cod = 0 || cod = 200 then Lwt . return msg else fst ( Lwt . wait ( ) )
let getfile f = try Lwt . return ( Sys_js . read_file ~ name : f ) with Not_found -> http_get f >|= fun s -> s
let fetch_model s = getfile s >|= fun s -> let a = Regexp . split ( Regexp . regexp " \ n " ) s in read_model ( Array . of_list a )
let pi = 4 . . * atan 1 .
let start ( pos , norm ) = let fps_text = Dom_html . document ## createTextNode ( Js . string " loading " ) in Opt . iter ( Opt . bind ( Dom_html . document ## getElementById ( string " fps " ) ) Dom_html . CoerceTo . element ) ( fun span -> Dom . appendChild span fps_text ) ; debug " init canvas " ; let _canvas , gl = init_canvas " canvas " in debug " create program " ; let prog = create_program gl ( get_source " vertex - shader " ) ( get_source " fragment - shader " ) in debug " use program " ; gl ## useProgram prog ; check_error gl ; debug " program loaded " ; gl ## enable gl . ## _DEPTH_TEST_ ; gl ## depthFunc gl . ## _LESS ; let proj_loc = gl ## getUniformLocation prog ( string " u_proj " ) in let lightPos_loc = gl ## getUniformLocation prog ( string " u_lightPos " ) in let ambientLight_loc = gl ## getUniformLocation prog ( string " u_ambientLight " ) in let lightPos = float32array [ | 3 . ; 0 . ; - 1 . ] | in let ambientLight = float32array [ | 0 . 1 ; 0 . 1 ; 0 . 1 ] | in gl ## uniform3fv_typed lightPos_loc lightPos ; gl ## uniform3fv_typed ambientLight_loc ambientLight ; let pos_attr = gl ## getAttribLocation prog ( string " a_position " ) in gl ## enableVertexAttribArray pos_attr ; let array_buffer = gl ## createBuffer in gl ## bindBuffer gl . ## _ARRAY_BUFFER_ array_buffer ; gl ## bufferData gl . ## _ARRAY_BUFFER_ pos gl . ## _STATIC_DRAW_ ; gl ## vertexAttribPointer pos_attr 3 gl . ## _FLOAT _false 0 0 ; let norm_attr = gl ## getAttribLocation prog ( string " a_normal " ) in gl ## enableVertexAttribArray norm_attr ; let norm_buffer = gl ## createBuffer in gl ## bindBuffer gl . ## _ARRAY_BUFFER_ norm_buffer ; gl ## bufferData gl . ## _ARRAY_BUFFER_ norm gl . ## _STATIC_DRAW_ ; gl ## vertexAttribPointer norm_attr 3 gl . ## _FLOAT _false 0 0 ; let mat = Proj3D . ( mult ( rotate_x ( pi . / 2 . ) ) ( mult ( scale 0 . 5 0 . 5 0 . 5 ) ( translate 0 . 0 . 0 . ) ) ) in check_error gl ; debug " ready " ; let get_time ( ) = ( new % js date_now ) ## getTime in let last_draw = ref ( get_time ( ) ) in let draw_times = Queue . create ( ) in let rec f ( ) = let t = ( new % js date_now ) ## getTime . / 1000 . in let mat ' = Proj3D . mult mat ( Proj3D . rotate_y ( 1 . . * t ) ) in gl ## uniformMatrix4fv_typed proj_loc _false ( Proj3D . array mat ' ) ; gl ## clear ( gl . ## _DEPTH_BUFFER_BIT_ lor gl . ## _COLOR_BUFFER_BIT_ ) ; gl ## drawArrays gl . ## _TRIANGLES 0 ( pos . ## length / 3 ) ; check_error gl ; let now = get_time ( ) in Queue . push ( now . - ! last_draw ) draw_times ; last_draw := now ; if Queue . length draw_times > 50 then ignore ( Queue . pop draw_times ) ; let fps = 1 . . / Queue . fold ( . + ) 0 . draw_times . * float_of_int ( Queue . length draw_times ) . * 1000 . in fps_text . ## data := string ( Printf . sprintf " . % 1f " fps ) ; Lwt_js . sleep 0 . 02 >>= f in f ( )
let go _ = ignore ( debug " fetching model " ; catch ( fun ( ) -> fetch_model " monkey . model " >>= start ) ( fun exn -> error " uncaught exception : % s " ( Printexc . to_string exn ) ) ) ; _true
let _ = Dom_html . window . ## onload := Dom_html . handler go
type event_kind = | New_thread | Thread_switch | Cycle_start | Cycle_end | Pid_is | Event | Measure_start | Measure_end | Trace_end
type event = { name : string ; categories : string list ; phase : event_kind ; timestamp : int ; pid : int ; tid : int }
type events = event list
let create_event ( ? categories = [ ] ) ( ? pid = 0 ) 0 ( ? tid = 0 ) 0 ~ phase ~ timestamp name = { name ; categories ; phase ; timestamp ; pid ; tid }
module Output = struct module JSON = struct let phase_of_kind = function | New_thread | Pid_is -> ` String " M " | Cycle_start -> ` String " b " | Cycle_end -> ` String " e " | Thread_switch -> ` String " X " | Event -> ` String " i " | Measure_start -> ` String " B " | Measure_end -> ` String " E " | Trace_end -> ` String " e " let json_of_event { name ; categories ; phase ; timestamp ; pid ; tid } = let categories = String . concat ~ sep " , " : categories in match phase with | New_thread | Pid_is -> ` Assoc [ ( " name " , ` String " thread_name ) " ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ; ( " args " , ` Assoc [ ( " name " , ` String name ) name ] ) ] | Thread_switch -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " dur " , ` Int 0 ) 0 ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] | Cycle_start | Cycle_end | Trace_end -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " id " , ` Int 0 ) 0 ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] | Event | Measure_start | Measure_end -> ` Assoc [ ( " name " , ` String name ) name ; ( " cat " , ` String categories ) categories ; ( " ph " , phase_of_kind phase ) phase ; ( " ts " , ` Int timestamp ) timestamp ; ( " pid " , ` Int pid ) pid ; ( " tid " , ` Int tid ) tid ] let json_of_events ( events : events ) events = ` List ( List . map ~ f : json_of_event events ) events end end
let emitk ~ buf ( k : event_kind ) event_kind pos = let num = match k with | New_thread -> 0 | Thread_switch -> 1 | Cycle_start -> 2 | Cycle_end -> 3 | Pid_is -> 4 | Event -> 5 | Measure_start -> 6 | Measure_end -> 7 | Trace_end -> 8 in Bigstring . set_uint8_exn buf ~ pos num ; pos + 1
let emiti ~ buf ( i : int ) int pos = Bigstring . set_uint64_le_exn buf ~ pos i ; pos + 8
let emits ~ buf ( s : string ) string ( pos : int ) int = let sl = String . length s in let pos = emiti ~ buf sl pos in Bigstring . From_string . blit ~ src : s ~ src_pos : 0 ~ len : sl ~ dst : buf ~ dst_pos : pos ; pos + sl
let finish wr ~ buf final_len = Writer . write_bigstring wr ~ pos : 0 ~ len : final_len buf
let emit_event wr ~ buf ( event : event ) event = match event . phase with | New_thread -> emitk ~ buf New_thread 0 |> emiti ~ buf event . timestamp |> emiti ~ buf event . tid |> emits ~ buf event . name |> finish ~ buf wr | Thread_switch -> emitk ~ buf Thread_switch 0 |> emiti ~ buf event . timestamp |> emiti ~ buf event . tid |> finish ~ buf wr | Cycle_start -> ( ) | Cycle_end -> emitk ~ buf Cycle_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr | Pid_is -> emitk ~ buf Pid_is 0 |> emiti ~ buf event . pid |> finish ~ buf wr | Event -> emitk ~ buf Event 0 |> emiti ~ buf event . timestamp |> emits ~ buf event . name |> finish ~ buf wr | Measure_start -> emitk ~ buf Measure_start 0 |> emiti ~ buf event . timestamp |> emits ~ buf event . name |> finish ~ buf wr | Measure_end -> emitk ~ buf Measure_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr | Trace_end -> emitk ~ buf Trace_end 0 |> emiti ~ buf event . timestamp |> finish ~ buf wr
module type IO = sig type ' + a t val ( ) >>= : ' a t -> ( ' a -> ' b t ) -> ' b t val return : ' a -> ' a t end
module type S = sig type ' + a io type ' a result = | Ok of ' a | Error of int type ( ' a , ' body ) op = ' body Rd . t -> ( ' a result * ' body Rd . t ) io type ' body provider = ( ' body , ' body ) op type ' body acceptor = ( bool , ' body ) op type www_authenticate = { scheme : string ; realm : string ; params : ( string * string ) list } type auth = [ ` Authorized | ` Basic of string | ` Challenge of www_authenticate | ` Redirect of Uri . t ] val continue : ' a -> ( ' a , ' body ) op val respond : ? body ' : body -> int -> ( ' a , ' body ) op class virtual [ ' body ] resource : object constraint ' body = [ > ` Empty ] method virtual content_types_provided : ( ( string * ( ' body provider ) ) list , ' body ) op method virtual content_types_accepted : ( ( string * ( ' body acceptor ) ) list , ' body ) op method resource_exists : ( bool , ' body ) op method service_available : ( bool , ' body ) op method is_authorized : ( auth , ' body ) op method forbidden : ( bool , ' body ) op method malformed_request : ( bool , ' body ) op method uri_too_long : ( bool , ' body ) op method known_content_type : ( bool , ' body ) op method valid_content_headers : ( bool , ' body ) op method valid_entity_length : ( bool , ' body ) op method options : ( ( string * string ) list , ' body ) op method allowed_methods : ( Code . meth list , ' body ) op method known_methods : ( Code . meth list , ' body ) op method delete_resource : ( bool , ' body ) op method delete_completed : ( bool , ' body ) op method process_post : ( bool , ' body ) op method language_available : ( bool , ' body ) op method charsets_provided : ( ( string * ( ' body -> ' body ) ) list , ' body ) op method encodings_provided : ( ( string * ( ' body -> ' body ) ) list , ' body ) op method variances : ( string list , ' body ) op method is_conflict : ( bool , ' body ) op method multiple_choices : ( bool , ' body ) op method previously_existed : ( bool , ' body ) op method moved_permanently : ( Uri . t option , ' body ) op method moved_temporarily : ( Uri . t option , ' body ) op method last_modified : ( string option , ' body ) op method expires : ( string option , ' body ) op method generate_etag : ( string option , ' body ) op method finish_request : ( unit , ' body ) op method post_is_create : ( bool , ' body ) op method create_path : ( string , ' body ) op method allow_missing_post : ( bool , ' body ) op end val to_handler : ? dispatch_path : string -> ? path_info ( : string * string ) list -> resource ( ' : body resource ) -> body ' : body -> request : Request . t -> unit -> ( Code . status_code * Header . t * ' body * string list ) io val dispatch : ( ( Dispatch . tag * string ) list * Dispatch . typ * ( unit -> ' body resource ) ) list -> body ' : body -> request : Request . t -> ( Code . status_code * Header . t * ' body * string list ) option io val dispatch ' : ( string * ( unit -> ' body resource ) ) list -> body ' : body -> request : Request . t -> ( Code . status_code * Header . t * ' body * string list ) option io end
let default_variances = [ " Accept " ; " Accept - Encoding " ; " Accept - Charset " ; " Accept - Language " ]
module type CLOCK = sig val now : unit -> int end
module Make ( IO : IO ) ( Clock : CLOCK ) = struct type ' + a io = ' a IO . t open IO type ' a result = | Ok of ' a | Error of int type ( ' a , ' body ) op = ' body Rd . t -> ( ' a result * ' body Rd . t ) io type ' body provider = ( ' body , ' body ) op type ' body acceptor = ( bool , ' body ) op type www_authenticate = { scheme : string ; realm : string ; params : ( string * string ) list } type auth = [ ` Authorized | ` Basic of string | ` Challenge of www_authenticate | ` Redirect of Uri . t ] let ( ) >>=? m f = m >>= function | Ok x , rd -> f x rd | Error code , rd -> return ( Error code , rd ) let continue x rd = return ( Ok x , rd ) let respond ? body x rd = let rd = match body with | None -> rd | Some resp_body -> { rd with Rd . resp_body } in return ( Error x , rd ) class virtual [ ' body ] resource = object ( self ) constraint ' body = [ > ` Empty ] method virtual content_types_provided : ( ( string * ( ' body provider ) ) list , ' body ) op method virtual content_types_accepted : ( ( string * ( ' body acceptor ) ) list , ' body ) op method resource_exists ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method service_available ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method is_authorized ( rd ' : body Rd . t ) : ( auth result * ' body Rd . t ) IO . t = continue ` Authorized rd method forbidden ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method malformed_request ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method uri_too_long ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method known_content_type ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method valid_content_headers ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method valid_entity_length ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method options ( rd ' : body Rd . t ) : ( ( string * string ) list result * ' body Rd . t ) IO . t = self # allowed_methods rd >>=? fun meths rd -> continue [ " allow " , String . concat " , " ( List . map Code . string_of_method meths ) ] rd method allowed_methods ( rd ' : body Rd . t ) : ( Code . meth list result * ' body Rd . t ) IO . t = continue [ ` GET ; ` HEAD ] rd method known_methods ( rd ' : body Rd . t ) : ( Code . meth list result * ' body Rd . t ) IO . t = continue [ ` GET ; ` HEAD ; ` POST ; ` PUT ; ` DELETE ; ` Other " TRACE " ; ` Other " CONNECT " ; ` OPTIONS ] rd method delete_resource ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method delete_completed ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method process_post ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method language_available ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue true rd method charsets_provided ( rd ' : body Rd . t ) : ( ( string * ( ' body -> ' body ) ) list result * ' body Rd . t ) IO . t = continue [ ] rd method encodings_provided ( rd ' : body Rd . t ) : ( ( string * ( ' body -> ' body ) ) list result * ' body Rd . t ) IO . t = continue [ " identity " , fun x -> x ] rd method variances ( rd ' : body Rd . t ) : ( string list result * ' body Rd . t ) IO . t = continue [ ] rd method is_conflict ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method multiple_choices ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method previously_existed ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method moved_permanently ( rd ' : body Rd . t ) : ( Uri . t option result * ' body Rd . t ) IO . t = continue None rd method moved_temporarily ( rd ' : body Rd . t ) : ( Uri . t option result * ' body Rd . t ) IO . t = continue None rd method last_modified ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method expires ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method generate_etag ( rd ' : body Rd . t ) : ( string option result * ' body Rd . t ) IO . t = continue None rd method finish_request ( rd ' : body Rd . t ) : ( unit result * ' body Rd . t ) IO . t = continue ( ) rd method post_is_create ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd method create_path ( rd ' : body Rd . t ) : ( string result * ' body Rd . t ) IO . t = continue " " rd method allow_missing_post ( rd ' : body Rd . t ) : ( bool result * ' body Rd . t ) IO . t = continue false rd end let ( ) >>~ m f = m f class [ ' body ] logic ( ~ resource ' : body resource ) ( ~ rd ' : body Rd . t ) ( ) = object ( self ) constraint ' body = [ > ` Empty ] val mutable path = ( [ ] : string list ) val mutable rd = rd val mutable content_type = None val mutable charset = None val mutable encoding = None method private encode_body = let cf = match charset with | None -> fun x -> x | Some ( _ , f ) -> f in let ef = match encoding with | None -> fun x -> x | Some ( _ , f ) -> f in rd <- { rd with Rd . resp_body = ef ( cf rd . Rd . resp_body ) } method private meth = rd . Rd . meth method private uri = rd . Rd . uri method private set_response_header k v = rd <- Rd . with_resp_headers ( fun headers -> Header . replace headers k v ) rd method private get_request_header k = Header . get rd . Rd . req_headers k method private get_response_header k = Header . get rd . Rd . resp_headers k method private is_redirect = rd . Rd . resp_redirect method private respond ~ status ( ) : ( Code . status_code * Header . t * ' body ) IO . t = self # run_op resource # finish_request >>~ fun ( ) -> return ( status , rd . Rd . resp_headers , rd . Rd . resp_body ) method private halt code : ( Code . status_code * Header . t * ' body ) IO . t = let status = Code . status_of_code code in self # respond ~ status ( ) method private choose_charset acceptable k = resource # charsets_provided rd >>= function | Ok [ ] , rd ' -> rd <- rd ' ; k ` Any | Ok available , rd ' -> rd <- rd ' ; charset <- Encoding . choose_charset ~ available ~ acceptable ; k ( ` One charset ) | Error n , rd ' -> rd <- rd ' ; self # halt n method private choose_encoding acceptable k = resource # encodings_provided rd >>= function | Ok available , rd ' -> rd <- rd ' ; encoding <- Encoding . choose ~ available ~ acceptable ; k encoding | Error n , rd ' -> rd <- rd ' ; self # halt n method private run_op : ' a . ( ' a , ' body ) op -> ( ' a -> ( Code . status_code * Header . t * ' body ) IO . t ) -> ( Code . status_code * Header . t * ' body ) IO . t = fun op k -> op rd >>= function | Ok a , rd ' -> rd <- rd ' ; k a | Error n , rd ' -> rd <- rd ' ; self # halt n method private run_provider : ' body provider -> _ -> ( Code . status_code * Header . t * ' body ) IO . t = fun provider k -> provider rd >>= function | Ok resp_body , rd ' -> rd <- { rd ' with Rd . resp_body } ; k ( ) | Error n , rd ' -> rd <- rd ' ; self # halt n method private accept_helper k = let header = match self # get_request_header " content - type " with | None -> Some " application / octet - stream " | Some type_ -> Some type_ in self # run_op resource # content_types_accepted >>~ fun provided -> match Mediatype . match_header provided header with | None -> self # halt 415 | Some ( _ , of_content ) -> self # run_op of_content >>~ function complete -> if complete then self # encode_body ; k complete method private d state = path <- state :: path method run : ( Code . status_code * Header . t * ' body * string list ) IO . t = self # v3b13 >>= fun ( code , headers , body ) -> return ( code , headers , body , List . rev path ) method v3b13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b13 " ; self # run_op resource # service_available >>~ function | true -> self # v3b12 | false -> self # halt 503 method v3b12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b12 " ; let meth = self # meth in self # run_op resource # known_methods >>~ fun ( meths : Code . meth list ) -> if List . exists ( fun x -> Code . compare_method meth x = 0 ) meths then self # v3b11 else self # halt 501 method v3b11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b11 " ; self # run_op resource # uri_too_long >>~ function | true -> self # halt 414 | false -> self # v3b10 method v3b10 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b10 " ; let meth = self # meth in self # run_op resource # allowed_methods >>~ fun ( meths : Code . meth list ) -> if List . exists ( fun x -> Code . compare_method meth x = 0 ) meths then self # v3b9 else begin let allow = String . concat " , " ( List . map Code . string_of_method meths ) in self # set_response_header " allow " allow ; self # halt 405 end method v3b9 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b9 " ; self # run_op resource # malformed_request >>~ function | true -> self # halt 400 | false -> self # v3b8 method v3b8 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b8 " ; self # run_op resource # is_authorized >>~ function | ` Authorized -> self # v3b7 | ` Basic realm -> self # set_response_header " WWW - Authenticate " ( " Basic realm " " =\ ^ realm ^ " " " ) ; \ self # halt 401 | ` Challenge auth -> let challenge = let buffer = Buffer . create 80 in let add_kv ( k , v ) = Buffer . add_char buffer ' ' ; Buffer . add_string buffer k ; Buffer . add_string buffer " " " ; =\ Buffer . add_string buffer v ; Buffer . add_string buffer " " " ; \ in Buffer . add_string buffer auth . scheme ; add_kv ( " realm " , auth . realm ) ; List . iter add_kv auth . params ; Buffer . contents buffer in self # set_response_header " WWW - Authenticate " challenge ; self # halt 401 | ` Redirect uri -> rd <- Rd . redirect Uri . ( to_string uri ) rd ; self # halt 303 method v3b7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b7 " ; self # run_op resource # forbidden >>~ function | true -> self # halt 403 | false -> self # v3b6 method v3b6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b6 " ; self # run_op resource # valid_content_headers >>~ function | true -> self # v3b5 | false -> self # halt 501 method v3b5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b5 " ; self # run_op resource # known_content_type >>~ function | true -> self # v3b4 | false -> self # halt 415 method v3b4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b4 " ; self # run_op resource # valid_entity_length >>~ function | true -> self # v3b3 | false -> self # halt 413 method v3b3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3b3 " ; match self # meth with | ` OPTIONS -> self # run_op resource # options >>~ fun headers -> List . iter ( fun ( k , v ) -> self # set_response_header k v ) headers ; self # respond ~ status ` : OK ( ) | _ -> self # v3c3 method v3c3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3c3 " ; self # run_op resource # content_types_provided >>~ fun content_types -> match self # get_request_header " accept " with | None -> begin match content_types with | [ ] -> self # halt 500 | t :: _ -> content_type <- Some t ; self # v3d4 end | Some _ -> self # v3c4 method v3c4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3c4 " ; self # run_op resource # content_types_provided >>~ fun content_types -> let header = self # get_request_header " accept " in match Mediatype . match_header content_types header with | None -> self # halt 406 | Some t -> content_type <- Some t ; self # v3d4 method v3d4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3d4 " ; match self # get_request_header " accept - language " with | None -> self # v3e5 | Some _ -> self # v3d5 method v3d5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3d5 " ; self # run_op resource # language_available >>~ function | true -> self # v3e5 | false -> self # halt 406 method v3e5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3e5 " ; match self # get_request_header " accept - charset " with | None -> begin self # choose_charset ( Accept . charsets None ) >>~ function | ` Any | ` One ( Some _ ) -> self # v3f6 | ` One None -> self # halt 406 end | Some _ -> self # v3e6 method v3e6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3e6 " ; match self # get_request_header " accept - charset " with | None -> assert false | Some acceptable -> begin self # choose_charset ( Accept . charsets ( Some acceptable ) ) >>~ function | ` Any | ` One ( Some _ ) -> self # v3f6 | ` One None -> self # halt 406 end method v3f6 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3f6 " ; let type_ = match content_type with | None -> assert false | Some ( type_ , _ ) -> type_ in let value = match charset with | None -> type_ | Some ( charset , _ ) -> Printf . sprintf " % s ; charset =% s " type_ charset in self # set_response_header " Content - Type " value ; match self # get_request_header " accept - encoding " with | None -> let acceptable = Accept . encodings ( Some " identity ; q = 1 . 0 , ; * q = 0 . 5 " ) in self # choose_encoding acceptable >>~ fun chosen -> begin match chosen with | None -> self # halt 406 | Some _ -> self # v3g7 end | Some _ -> self # v3f7 method v3f7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3f7 " ; match self # get_request_header " accept - encoding " with | None -> assert false | Some acceptable -> let acceptable = Accept . encodings ( Some acceptable ) in self # choose_encoding acceptable >>~ fun chosen -> begin match chosen with | None -> self # halt 406 | Some _ -> self # v3g7 end method v3g7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g7 " ; self # run_op resource # variances >>~ fun variances -> let variances = variances @ default_variances in begin match String . concat " , " variances with | " " -> ( ) | vary -> self # set_response_header " vary " vary end ; self # run_op resource # resource_exists >>~ function | true -> self # v3g8 | false -> self # v3h7 method v3g8 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g8 " ; match self # get_request_header " if - match " with | None -> self # v3h10 | Some _ -> self # v3g9 method v3g9 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g9 " ; match self # get_request_header " if - match " with | None -> assert false | Some " " * -> self # v3h10 | Some _ -> self # v3g11 method v3g11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3g11 " ; match self # get_request_header " if - match " with | None -> assert false | Some if_match_header -> self # run_op resource # generate_etag >>~ function | None -> self # halt 412 | Some etag -> begin match List . mem etag ( Etag . from_header if_match_header ) with | true -> self # v3h10 | false -> self # halt 412 end method v3h7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h7 " ; match self # get_request_header " if - match " with | None -> self # v3i7 | Some _ -> self # halt 412 method v3h10 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h10 " ; match self # get_request_header " if - unmodified - since " with | None -> self # v3i12 | Some _ -> self # v3h11 method v3h11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h11 " ; let d = self # get_request_header " if - unmodified - since " in match d with | None -> self # v3i12 | Some d ' -> match ( Rfc1123 . parse_date d ' ) with | None -> self # v3i12 | Some _ -> self # v3h12 method v3h12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3h12 " ; try let u_mod = self # get_request_header " if - unmodified - since " in self # run_op resource # last_modified >>~ fun l_mod -> match ( u_mod , l_mod ) with | ( Some u_mod ' , Some l_mod ' ) -> ( match ( Rfc1123 . parse_date_exn l_mod ' ) > ( Rfc1123 . parse_date_exn u_mod ' ) with | false -> self # v3i12 | true -> self # halt 412 ) | ( _ , _ ) -> self # v3i12 with Invalid_argument _ -> self # halt 412 method v3i4 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i4 " ; self # run_op resource # moved_permanently >>~ function | None -> self # v3p3 | Some uri -> self # set_response_header " Location " ( Uri . to_string uri ) ; self # respond ~ status ` : Moved_permanently ( ) method v3i7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i7 " ; match self # meth with | ` OPTIONS -> assert false | ` PUT -> self # v3i4 | _ -> self # v3k7 method v3i12 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i12 " ; match self # get_request_header " if - none - match " with | None -> self # v3l13 | Some _ -> self # v3i13 method v3i13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3i13 " ; match self # get_request_header " if - none - match " with | None -> assert false | Some " " * -> self # v3j18 | Some _ -> self # v3k13 method v3k7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k7 " ; self # run_op resource # previously_existed >>~ function | true -> self # v3k5 | false -> self # v3l7 method v3k5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k5 " ; self # run_op resource # moved_permanently >>~ function | None -> self # v3l5 | Some uri -> self # set_response_header " location " ( Uri . to_string uri ) ; self # respond ~ status ` : Moved_permanently ( ) method v3k13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3k13 " ; match self # get_request_header " if - none - match " with | None -> assert false | Some if_none_match_header -> self # run_op resource # generate_etag >>~ function | None -> self # v3l13 | Some etag -> begin match List . mem etag ( Etag . from_header if_none_match_header ) with | true -> self # v3j18 | false -> self # v3l13 end method v3l5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l5 " ; self # run_op resource # moved_temporarily >>~ function | None -> self # v3m5 | Some uri -> self # set_response_header " location " ( Uri . to_string uri ) ; self # respond ~ status ` : Temporary_redirect ( ) method v3l7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l7 " ; match self # meth with | ` POST -> self # v3m7 | _ -> self # halt 404 method v3l13 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l13 " ; match self # get_request_header " if - modified - since " with | None -> self # v3m16 | Some _ -> self # v3l14 method v3l14 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l14 " ; match ( self # get_request_header " if - modified - since " ) with | None -> self # v3m16 | Some date -> match ( Rfc1123 . parse_date date ) with | Some _ -> self # v3l15 | None -> self # v3m16 method v3l15 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l15 " ; let now = Clock . now ( ) in match ( self # get_request_header " if - modified - since " ) with | None -> self # v3l17 | Some date -> match Rfc1123 . parse_date date with | None -> self # v3l17 | Some d -> match ( d > now ) with | true -> self # v3m16 | false -> self # v3l17 method v3l17 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3l17 " ; try let u_mod = self # get_request_header " if - modified - since " in self # run_op resource # last_modified >>~ fun l_mod -> match ( u_mod , l_mod ) with | ( Some l_mod ' , Some u_mod ' ) -> ( match ( Rfc1123 . parse_date_exn l_mod ' ) > ( Rfc1123 . parse_date_exn u_mod ' ) with | true -> self # v3m16 | false -> self # halt 304 ) | ( _ , _ ) -> self # halt 304 with Invalid_argument _ -> self # halt 304 method v3j18 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3j18 " ; match self # meth with | ` GET | ` HEAD -> self # halt 304 | _ -> self # halt 412 method v3m5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m5 " ; match self # meth with | ` POST -> self # v3n5 | _ -> self # halt 410 method v3m7 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m7 " ; self # run_op resource # allow_missing_post >>~ function | true -> self # v3n11 | false -> self # halt 404 method v3m16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m16 " ; match self # meth with | ` OPTIONS -> assert false | ` DELETE -> self # v3m20 | _ -> self # v3n16 method v3m20 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3m20 " ; self # run_op resource # delete_resource >>~ fun deleted -> if deleted then self # run_op resource # delete_completed >>~ function | true -> self # v3o20 | false -> self # respond ~ status ` : Accepted ( ) else self # halt 500 method v3n5 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3n5 " ; self # run_op resource # allow_missing_post >>~ function | true -> self # v3n11 | false -> self # halt 410 method v3n11 : ( Code . status_code * Header . t * ' body ) IO . t = let stage2 ( type a ) ( _ : a ) = if self # is_redirect then match self # get_response_header " location " with | None -> self # halt 500 | Some _ -> self # respond ~ status ` : See_other ( ) else self # v3p11 in self # d " v3n11 " ; self # run_op resource # post_is_create >>~ function | true -> self # run_op resource # create_path >>~ fun new_resource -> let uri ' = Uri . with_path self # uri ( Uri . path self # uri ^ " " / ^ new_resource ) in self # set_response_header " Location " ( Uri . to_string uri ' ) ; self # accept_helper stage2 | false -> self # run_op resource # process_post >>~ fun executed -> if executed then begin self # encode_body ; stage2 ( ) end else self # halt 500 method v3n16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3n16 " ; match self # meth with | ` OPTIONS | ` DELETE -> assert false | ` POST -> self # v3n11 | _ -> self # v3o16 method v3o14 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o14 " ; self # run_op resource # is_conflict >>~ function | true -> self # halt 409 | false -> self # accept_helper ( fun _ -> self # v3p11 ) method v3o16 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o16 " ; match self # meth with | ` OPTIONS | ` DELETE | ` POST -> assert false | ` PUT -> self # v3o14 | _ -> self # v3o18 method v3o18 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o18 " ; match self # meth with | ` OPTIONS -> assert false | ` HEAD | ` GET -> let _ , to_content = match content_type with | None -> assert false | Some x -> x in self # run_op resource # generate_etag >>~ fun etag -> begin match etag with | None -> ( ) | Some etag -> self # set_response_header " ETag " ( Etag . escape etag ) end ; self # run_provider to_content >>~ fun ( ) -> self # encode_body ; self # v3o18b | _ -> self # v3o18b method v3o18b ( : Code . status_code * Header . t * ' body ) IO . t = self # run_op resource # multiple_choices >>~ function | true -> self # halt 300 | false -> self # respond ~ status ` : OK ( ) method v3o20 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3o20 " ; match rd . Rd . resp_body with | ` Empty -> self # respond ~ status ` : No_content ( ) | _ -> self # v3o18 method v3p3 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3p3 " ; self # run_op resource # is_conflict >>~ function | true -> self # halt 409 | false -> self # accept_helper ( fun _ -> self # v3p11 ) method v3p11 : ( Code . status_code * Header . t * ' body ) IO . t = self # d " v3p11 " ; match self # get_response_header " location " with | None -> self # v3o20 | Some _ -> self # respond ~ status ` : Created ( ) end let to_handler ? dispatch_path ? path_info ~ resource ~ body ~ request ( ) = let rd = Rd . make ~ req_body : body ? dispatch_path ? path_info ~ request ( ) in let logic = new logic ~ resource ~ rd ( ) in logic # run ; ; let dispatch table = let table = Dispatch . create ( List . map ( fun ( p , t , mk_resource ) -> ( p , t , fun path_info dispatch_path ~ body ~ request -> let resource = mk_resource ( ) in to_handler ? dispatch_path ~ path_info ~ resource ~ body ~ request ( ) ) ) table ) in fun ~ body ~ request -> let path = Uri . path ( Cohttp . Request . uri request ) in match Dispatch . dispatch table path with | None -> return None | Some handler -> handler ~ body ~ request >>= fun x -> return ( Some x ) let dispatch ' table = dispatch ( List . map ( fun ( m , r ) -> let p , t = Dispatch . of_dsl m in ( p , t , r ) ) table ) end
module Session = struct module Backend = struct include Session . Lift . IO ( Deferred ) ( Session . Memory ) let create ( ) = Session . Memory . create ( ) end include Session_webmachine . Make ( Deferred ) ( Backend ) end
module UnixClock = struct let now ( ) = int_of_float ( Unix . gettimeofday ( ) ) end inherit [ Body . t ] resource inherit [ Body . t ] Session . manager ~ cookie_key backend method private increment session rd = let value = string_of_int ( 1 + int_of_string session . Session . value ) in self # session_set value rd method private to_plain rd = self # session_of_rd_or_create " 0 " rd >>= fun session -> self # increment session rd >>= fun ( ) -> continue ( ` String session . Session . value ) rd method ! allowed_methods rd = continue [ ` GET ] rd method content_types_accepted rd = continue [ ] rd method content_types_provided rd = continue [ " text / plain " , self # to_plain ] rd method ! finish_request rd = let rd = self # session_set_hdrs rd in continue ( ) rd end
let main ( ) = let port = 8080 in let mem = Session . Backend . create ( ) in let routes = [ " " , /* fun ( ) -> new counter mem ] in let dispatch = dispatch ' routes in let handler ~ body _ request = dispatch ~ body ~ request >>| begin function | None -> ( ` Not_found , Cohttp . Header . init ( ) , ` String " Not found " , [ ] ) | Some result -> result end >>= fun ( _status , headers , body , _ ) -> Server . respond ~ headers ~ body ` OK in Server . create ~ on_handler_error ` : Raise ( Tcp . Where_to_listen . of_port port ) handler >>> fun _server -> Log . Global . info " webmachine_async_counter : listening on 0 . 0 . 0 . 0 :% d " %! port
let _ = Mirage_crypto_rng_unix . initialize ( ) ; Scheduler . go_main ~ main ( )
module Session = struct module Backend = struct include Session . Lift . IO ( Lwt ) ( Session . Memory ) let create ( ) = Session . Memory . create ( ) end include Session_webmachine . Make ( Lwt ) ( Backend ) end
module UnixClock = struct let now ( ) = int_of_float ( Unix . gettimeofday ( ) ) end inherit [ Cohttp_lwt . Body . t ] resource inherit [ Cohttp_lwt . Body . t ] Session . manager ~ cookie_key backend method private increment session rd = let value = string_of_int ( 1 + int_of_string session . Session . value ) in self # session_set value rd method private to_plain rd = self # session_of_rd_or_create " 0 " rd >>= fun session -> self # increment session rd >>= fun ( ) -> continue ( ` String session . Session . value ) rd method ! allowed_methods rd = continue [ ` GET ] rd method content_types_accepted rd = continue [ ] rd method content_types_provided rd = continue [ " text / plain " , self # to_plain ] rd method ! finish_request rd = let rd = self # session_set_hdrs rd in continue ( ) rd end
let main ( ) = let port = 8080 in let mem = Session . Backend . create ( ) in let routes = [ " " , /* fun ( ) -> new counter mem ] in let dispatch = dispatch ' routes in let callback _conn request body = dispatch ~ body ~ request >|= begin function | None -> ( ` Not_found , Cohttp . Header . init ( ) , ` String " Not found " , [ ] ) | Some result -> result end >>= fun ( _status , headers , body , _ ) -> Server . respond ~ headers ~ body ~ status ` : OK ( ) in let config = Server . make ~ callback ( ) in Server . create ~ mode ( ` : TCP ( ` Port port ) ) config >|= fun ( ) -> Printf . eprintf " cohttp_lwt_counter : lsitening on 0 . 0 . 0 . 0 :% d \ n " %! port
let ( ) = Mirage_crypto_rng_unix . initialize ( ) ; Lwt_main . run ( main ( ) )
let logger ( handler : Cohttp_lwt_unix . Server . conn -> Cohttp . Request . t -> Cohttp_lwt . Body . t -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t ) ( conn : Cohttp_lwt_unix . Server . conn ) ( request : Cohttp . Request . t ) ( body : Cohttp_lwt . Body . t ) : ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = ( Lwt . catch ( fun ( ) -> handler conn request body ) ( fun exn -> Logs_lwt . err ( fun m -> m " % s " ( Printexc . to_string exn ) ) >>= ( fun ( ) -> Lwt . fail exn ) ) ) >>= ( fun ( response , body ) -> let ip : string = match fst conn with | Conduit_lwt_unix . TCP { Conduit_lwt_unix . fd ; _ } -> ( match Lwt_unix . getpeername fd with | Lwt_unix . ADDR_INET ( ia , port ) -> Printf . sprintf " % s :% d " ( Ipaddr . to_string ( Ipaddr_unix . of_inet_addr ia ) ) port | Lwt_unix . ADDR_UNIX path -> Printf . sprintf " sock :% s " path ) | Conduit_lwt_unix . Vchan _ | Conduit_lwt_unix . Domain_socket _ -> " unknown " in let t = Unix . localtime ( Unix . time ( ) ) in let request_method : string = Cohttp . Code . string_of_method request . Cohttp_lwt_unix . Request . meth in let uri : Uri . t = Cohttp_lwt_unix . Request . uri request in let request_path : string = Uri . path uri in let response_code : string = Cohttp . Code . string_of_status response . Cohttp . Response . status in Logs_lwt . info ( fun m -> m " % s \ t [ % 02d /% 02d /% 04d % 02d :% 02d :% 02d ] \ t " \% s % s " \\ t % s " ip t . Unix . tm_mday t . Unix . tm_mon ( 1900 + t . Unix . tm_year ) t . Unix . tm_hour t . Unix . tm_min t . Unix . tm_sec request_method request_path response_code ) >>= ( fun _ -> Lwt . return ( response , body ) ) )
let server = let app_args = App_args . default in let common_args = Common_args . default in let websim_args = Websim_args . default in let options = App_args . options app_args @ Websim_args . options websim_args @ Common_args . options common_args in let usage_msg : string = " kappa webservice " in let ( ) = Arg . parse options ( fun _ -> ( ) ) usage_msg in let ( ) = Logs . set_reporter ( Agent_common . lwt_reporter app_args . App_args . log_channel ) in let ( ) = Printexc . record_backtrace common_args . Common_args . backtrace in let mode = match websim_args . Websim_args . cert_dir with | None -> ` TCP ( ` Port websim_args . Websim_args . port ) | Some dir -> ` TLS ( ` Crt_file_path ( dir " ^ cert . pem " ) , ` Key_file_path ( dir " ^ privkey . pem " ) , ` No_password , ` Port websim_args . Websim_args . port ) in let route_handler : Cohttp_lwt_unix . Server . conn -> Cohttp . Request . t -> Cohttp_lwt . Body . t -> ( Cohttp . Response . t * Cohttp_lwt . Body . t ) Lwt . t = Webapp . route_handler ~ shutdown_key : websim_args . Websim_args . shutdown_key ( ) in Cohttp_lwt_unix . Server . create ~ mode ( Cohttp_lwt_unix . Server . make ~ callback : ( logger ( match app_args . App_args . api with | App_args . V2 -> route_handler ) ) ( ) ) >>= fun ( ) -> match app_args . App_args . log_channel with | None -> Lwt . return_unit | Some ch -> Lwt_io . close ch
let ( ) = let ( ) = Lwt . async_exception_hook := ignore in ignore ( Lwt_main . run server )
let og_image html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = og : image ] image " |> R . attribute " content " |> Option . some with Failure _ -> None
let image_src html = let open Soup in let soup = parse html in try soup $ " link [ linkrel " =\ image_src ] " " \ |> R . attribute " href " |> Option . some with Failure _ -> None
let twitter_image html = let open Soup in let soup = parse html in try soup $ " meta [ metaname " =\ twitter : image ] " " \ |> R . attribute " content " |> Option . some with Failure _ -> None
let og_description html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = og : description ] description " |> R . attribute " content " |> Option . some with Failure _ -> None
let description html = let open Soup in let soup = parse html in try soup $ " meta [ metaproperty = description ] description " |> R . attribute " content " |> Option . some with Failure _ -> None
let preview_image html = let preview_image = match og_image html with | None -> ( match image_src html with | None -> twitter_image html | Some x -> Some x ) x | Some x -> Some x in match Option . map String . trim preview_image with | Some " " -> None | Some x -> Some x | None -> None