├── .haxerc ├── tests.hxml ├── .gitignore ├── dev.hxml ├── src └── tink │ ├── web │ ├── Session.hx │ ├── routing │ │ ├── Router.hx │ │ ├── Response.hx │ │ └── Context.hx │ ├── macros │ │ ├── import.hx │ │ ├── RouteCollection.hx │ │ ├── Signature.hx │ │ ├── Result.hx │ │ ├── Variant.hx │ │ ├── MimeType.hx │ │ ├── Arguments.hx │ │ ├── Paths.hx │ │ ├── Parameters.hx │ │ ├── Route.hx │ │ ├── Proxify.hx │ │ └── Routing.hx │ ├── proxy │ │ ├── ConnectOptions.hx │ │ └── Remote.hx │ ├── Response.hx │ └── forms │ │ ├── FormField.hx │ │ └── FormFile.hx │ └── Web.hx ├── haxe_libraries ├── ansi.hxml ├── deep_equal.hxml ├── tink_core.hxml ├── tink_chunk.hxml ├── http-status.hxml ├── tink_tcp.hxml ├── tink_url.hxml ├── hxnodejs.hxml ├── tink_anon.hxml ├── tink_priority.hxml ├── tink_macro.hxml ├── tink_io.hxml ├── tink_json.hxml ├── tink_stringly.hxml ├── tink_typecrawler.hxml ├── tink_http.hxml ├── tink_web.hxml ├── tink_multipart.hxml ├── tink_querystring.hxml ├── tink_await.hxml ├── tink_syntaxhub.hxml ├── tink_cli.hxml ├── tink_streams.hxml ├── tink_unittest.hxml ├── tink_testrunner.hxml └── travix.hxml ├── tests ├── import.hx ├── RunTests.hx ├── Helpers.hx ├── FacadeTest.hx ├── RemoteEndpoints.hx ├── RawTest.hx ├── TestRpc.hx ├── Fake.hx ├── ProxyTest.hx └── DispatchTest.hx ├── .vscode ├── tasks.json └── settings.json ├── README.md ├── haxelib.json ├── .travis.yml.disabled └── .github └── workflows └── ci.yml /.haxerc: -------------------------------------------------------------------------------- 1 | { 2 | "version": "4.2.5", 3 | "resolveLibs": "scoped" 4 | } -------------------------------------------------------------------------------- /tests.hxml: -------------------------------------------------------------------------------- 1 | -cp tests 2 | -main RunTests 3 | -lib deep_equal 4 | -lib tink_unittest -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | !bin/node 3 | bin/node/tests.js 4 | node_modules 5 | /travix.n 6 | -------------------------------------------------------------------------------- /dev.hxml: -------------------------------------------------------------------------------- 1 | tests.hxml 2 | -lib tink_web 3 | -lib travix 4 | -lib hxnodejs 5 | -js bin/node/tests.js -------------------------------------------------------------------------------- /src/tink/web/Session.hx: -------------------------------------------------------------------------------- 1 | package tink.web; 2 | 3 | import tink.CoreApi; 4 | 5 | typedef Session = { 6 | function getUser():Promise>; 7 | } -------------------------------------------------------------------------------- /src/tink/web/routing/Router.hx: -------------------------------------------------------------------------------- 1 | package tink.web.routing; 2 | 3 | using tink.CoreApi; 4 | 5 | @:genericBuild(tink.web.macros.Routing.apply()) 6 | class Router { } -------------------------------------------------------------------------------- /haxe_libraries/ansi.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download haxelib:ansi#1.0.0 into ansi/1.0.0/haxelib 2 | -D ansi=1.0.0 3 | -cp ${HAXESHIM_LIBCACHE}/ansi/1.0.0/haxelib/src 4 | -------------------------------------------------------------------------------- /haxe_libraries/deep_equal.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download haxelib:deep_equal#0.2.0 into deep_equal/0.2.0/haxelib 2 | -D deep_equal=0.2.0 3 | -cp ${HAXESHIM_LIBCACHE}/deep_equal/0.2.0/haxelib/src 4 | -------------------------------------------------------------------------------- /tests/import.hx: -------------------------------------------------------------------------------- 1 | import Helpers.*; 2 | import tink.http.Header; 3 | import tink.http.Request; 4 | import tink.http.Response; 5 | import tink.testrunner.*; 6 | 7 | using tink.io.Source; 8 | using tink.CoreApi; -------------------------------------------------------------------------------- /src/tink/web/macros/import.hx: -------------------------------------------------------------------------------- 1 | import haxe.macro.Type; 2 | import haxe.macro.Expr; 3 | import haxe.macro.Context; 4 | 5 | using haxe.macro.Tools; 6 | using tink.MacroApi; 7 | using tink.CoreApi; 8 | using Lambda; -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "command": "lix", 4 | "args": ["run","travix","node"], 5 | "problemMatcher": "$haxe", 6 | "isShellCommand": true, 7 | "group": { 8 | "kind": "build", 9 | "isDefault": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/tink/web/proxy/ConnectOptions.hx: -------------------------------------------------------------------------------- 1 | package tink.web.proxy; 2 | 3 | import tink.http.Client; 4 | import tink.http.Header; 5 | 6 | typedef ConnectOptions = {>TestOptions, 7 | ?client:Client, 8 | } 9 | 10 | typedef TestOptions = { 11 | ?headers:Array, 12 | ?augment:Processors, 13 | } -------------------------------------------------------------------------------- /haxe_libraries/tink_core.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_core#aea0dd2227d22156716c70561168765f6294de15" into tink_core/2.0.2/github/aea0dd2227d22156716c70561168765f6294de15 2 | -cp ${HAXE_LIBCACHE}/tink_core/2.0.2/github/aea0dd2227d22156716c70561168765f6294de15/src 3 | -D tink_core=2.0.2 -------------------------------------------------------------------------------- /haxe_libraries/tink_chunk.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_chunk#f178d47593e42ba184af2eb88db4f8f1f554dbf3" into tink_chunk/0.4.0/github/f178d47593e42ba184af2eb88db4f8f1f554dbf3 2 | -cp ${HAXE_LIBCACHE}/tink_chunk/0.4.0/github/f178d47593e42ba184af2eb88db4f8f1f554dbf3/src 3 | -D tink_chunk=0.4.0 -------------------------------------------------------------------------------- /haxe_libraries/http-status.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/kevinresol/http-status#33c5ea57d8117bdb64ac01e66766e917eacec8c4" into http-status/1.3.2/github/33c5ea57d8117bdb64ac01e66766e917eacec8c4 2 | -cp ${HAXE_LIBCACHE}/http-status/1.3.2/github/33c5ea57d8117bdb64ac01e66766e917eacec8c4/src 3 | -D http-status=1.3.2 -------------------------------------------------------------------------------- /haxe_libraries/tink_tcp.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_tcp#b0961db4db515d6f695a23b09234412dbbbd09f7" into tink_tcp/0.1.1/github/b0961db4db515d6f695a23b09234412dbbbd09f7 2 | -lib tink_io 3 | -cp ${HAXE_LIBCACHE}/tink_tcp/0.1.1/github/b0961db4db515d6f695a23b09234412dbbbd09f7/src 4 | -D tink_tcp=0.1.1 -------------------------------------------------------------------------------- /haxe_libraries/tink_url.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_url#4f53997c488e0ac33545a096968da6274bd7b064" into tink_url/0.5.0/github/4f53997c488e0ac33545a096968da6274bd7b064 2 | -lib tink_stringly 3 | -cp ${HAXE_LIBCACHE}/tink_url/0.5.0/github/4f53997c488e0ac33545a096968da6274bd7b064/src 4 | -D tink_url=0.5.0 -------------------------------------------------------------------------------- /haxe_libraries/hxnodejs.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "haxelib:/hxnodejs#12.0.0" into hxnodejs/12.0.0/haxelib 2 | -cp ${HAXE_LIBCACHE}/hxnodejs/12.0.0/haxelib/src 3 | -D hxnodejs=12.0.0 4 | --macro allowPackage('sys') 5 | # should behave like other target defines and not be defined in macro context 6 | --macro define('nodejs') 7 | -------------------------------------------------------------------------------- /haxe_libraries/tink_anon.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_anon#0277e6e3f97a7878f1aa9aeeccc4b7be0e9c82bc" into tink_anon/0.7.0/github/0277e6e3f97a7878f1aa9aeeccc4b7be0e9c82bc 2 | -lib tink_macro 3 | -cp ${HAXE_LIBCACHE}/tink_anon/0.7.0/github/0277e6e3f97a7878f1aa9aeeccc4b7be0e9c82bc/src 4 | -D tink_anon=0.7.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_priority.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_priority#b4b772298676314d0672d64ddc8e7f4ffece0f1b" into tink_priority/0.1.4/github/b4b772298676314d0672d64ddc8e7f4ffece0f1b 2 | -cp ${HAXE_LIBCACHE}/tink_priority/0.1.4/github/b4b772298676314d0672d64ddc8e7f4ffece0f1b/src 3 | -D tink_priority=0.1.4 -------------------------------------------------------------------------------- /haxe_libraries/tink_macro.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_macro#c400f5af51773a694942631ab55026956f021562" into tink_macro/1.0.0/github/c400f5af51773a694942631ab55026956f021562 2 | -lib tink_core 3 | -cp ${HAXE_LIBCACHE}/tink_macro/1.0.0/github/c400f5af51773a694942631ab55026956f021562/src 4 | -D tink_macro=1.0.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_io.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_io#e75bd9d718eda4fea58a49de952fd5439e336d81" into tink_io/0.9.0/github/e75bd9d718eda4fea58a49de952fd5439e336d81 2 | -lib tink_chunk 3 | -lib tink_streams 4 | -cp ${HAXE_LIBCACHE}/tink_io/0.9.0/github/e75bd9d718eda4fea58a49de952fd5439e336d81/src 5 | -D tink_io=0.9.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_json.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_json#7dd309a8c4153eb7d89ab05d34d2fb7037b83681" into tink_json/0.11.0/github/7dd309a8c4153eb7d89ab05d34d2fb7037b83681 2 | -lib tink_typecrawler 3 | -cp ${HAXE_LIBCACHE}/tink_json/0.11.0/github/7dd309a8c4153eb7d89ab05d34d2fb7037b83681/src 4 | -D tink_json=0.11.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_stringly.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_stringly#38fcef46679d45bdfc33fe31f341d8d0787cc98c" into tink_stringly/0.5.0/github/38fcef46679d45bdfc33fe31f341d8d0787cc98c 2 | -lib tink_core 3 | -cp ${HAXE_LIBCACHE}/tink_stringly/0.5.0/github/38fcef46679d45bdfc33fe31f341d8d0787cc98c/src 4 | -D tink_stringly=0.5.0 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tinkerbell Web Routing 2 | [![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg?maxAge=2592000)](https://gitter.im/haxetink/public) 3 | 4 | In simple terms, `tink_web` is a super-charged router for `tink_http`, that strives to embed the semantics of REST and HTTP into Haxe in a seamless way. 5 | 6 | Documentations: https://haxetink.github.io/tink_web/ 7 | -------------------------------------------------------------------------------- /haxe_libraries/tink_typecrawler.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_typecrawler#abd2dec61e8fe98305021372e3a31efdce92bbc8" into tink_typecrawler/0.7.0/github/abd2dec61e8fe98305021372e3a31efdce92bbc8 2 | -lib tink_macro 3 | -cp ${HAXE_LIBCACHE}/tink_typecrawler/0.7.0/github/abd2dec61e8fe98305021372e3a31efdce92bbc8/src 4 | -D tink_typecrawler=0.7.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_http.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_http#7ff3dfa798aa1ca5d402e0ef5026fb6b6a9a2626" into tink_http/0.10.0/github/7ff3dfa798aa1ca5d402e0ef5026fb6b6a9a2626 2 | -lib http-status 3 | -lib tink_io 4 | -lib tink_url 5 | -cp ${HAXE_LIBCACHE}/tink_http/0.10.0/github/7ff3dfa798aa1ca5d402e0ef5026fb6b6a9a2626/src 6 | -D tink_http=0.10.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_web.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_web#2a209424c24002aa45dad77b8c85d3af943246f5" into tink_web/0.3.0/github/2a209424c24002aa45dad77b8c85d3af943246f5 2 | -lib tink_http 3 | -lib tink_json 4 | -lib tink_querystring 5 | -cp ${HAXE_LIBCACHE}/tink_web/0.3.0/github/2a209424c24002aa45dad77b8c85d3af943246f5/src 6 | -D tink_web=0.3.0 -------------------------------------------------------------------------------- /tests/RunTests.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import tink.testrunner.*; 4 | import tink.unit.*; 5 | 6 | class RunTests { 7 | static function main() { 8 | Runner.run(TestBatch.make([ 9 | new RemoteEndpoints(), 10 | new FacadeTest(), 11 | new ProxyTest(), 12 | new DispatchTest(), 13 | new RawTest(), 14 | new TestRpc(), 15 | ])).handle(Runner.exit); 16 | } 17 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "haxe.displayConfigurations": [ 3 | ["dev.hxml"] 4 | ], 5 | "haxe.displayServer": { 6 | "haxePath": "./node_modules/.bin/haxe", 7 | "windows": { 8 | "haxePath": "node_modules\\.bin\\haxe.cmd" 9 | } 10 | }, 11 | "editor.useTabStops": false, 12 | "editor.tabSize": 2 13 | } 14 | -------------------------------------------------------------------------------- /haxe_libraries/tink_multipart.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_multipart#a5b15378ea872132e9490cfadc1f6c107620ef81" into tink_multipart/0.3.0/github/a5b15378ea872132e9490cfadc1f6c107620ef81 2 | -lib tink_http 3 | -lib tink_state 4 | -cp ${HAXE_LIBCACHE}/tink_multipart/0.3.0/github/a5b15378ea872132e9490cfadc1f6c107620ef81/src 5 | -D tink_multipart=0.3.0 -------------------------------------------------------------------------------- /haxe_libraries/tink_querystring.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_querystring#7333282fa0ac69c2096f1feb4ef7b9514155b582" into tink_querystring/0.7.0/github/7333282fa0ac69c2096f1feb4ef7b9514155b582 2 | -lib tink_typecrawler 3 | -lib tink_url 4 | -cp ${HAXE_LIBCACHE}/tink_querystring/0.7.0/github/7333282fa0ac69c2096f1feb4ef7b9514155b582/src 5 | -D tink_querystring=0.7.0 -------------------------------------------------------------------------------- /src/tink/web/Response.hx: -------------------------------------------------------------------------------- 1 | package tink.web; 2 | 3 | import tink.http.Message; 4 | import tink.http.Response; 5 | 6 | typedef TypedResponse = Message; 7 | 8 | @:forward 9 | abstract Response(TypedResponse) { 10 | public inline function new(header, body) 11 | this = new Message(header, body); 12 | 13 | @:to 14 | public inline function getData():T 15 | return this.body; 16 | } -------------------------------------------------------------------------------- /haxe_libraries/tink_await.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_await#045b8370ecd30a307b2aa71593f2bc850b7f46d2" into tink_await/0.6.0/github/045b8370ecd30a307b2aa71593f2bc850b7f46d2 2 | -lib tink_core 3 | -lib tink_macro 4 | -lib tink_syntaxhub 5 | -cp ${HAXE_LIBCACHE}/tink_await/0.6.0/github/045b8370ecd30a307b2aa71593f2bc850b7f46d2/src 6 | -D tink_await=0.6.0 7 | --macro tink.await.Await.use() -------------------------------------------------------------------------------- /haxe_libraries/tink_syntaxhub.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_syntaxhub#854dae9201d59e1856293f073b24c7ef0b3c9796" into tink_syntaxhub/0.5.0/github/854dae9201d59e1856293f073b24c7ef0b3c9796 2 | -lib tink_macro 3 | -lib tink_priority 4 | -cp ${HAXE_LIBCACHE}/tink_syntaxhub/0.5.0/github/854dae9201d59e1856293f073b24c7ef0b3c9796/src 5 | -D tink_syntaxhub=0.5.0 6 | --macro tink.SyntaxHub.use() -------------------------------------------------------------------------------- /haxe_libraries/tink_cli.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_cli#c9124f9be04baca0cd55f06237a0a9fffb6287dc" into tink_cli/0.5.1/github/c9124f9be04baca0cd55f06237a0a9fffb6287dc 2 | -lib tink_io 3 | -lib tink_macro 4 | -lib tink_stringly 5 | -cp ${HAXE_LIBCACHE}/tink_cli/0.5.1/github/c9124f9be04baca0cd55f06237a0a9fffb6287dc/src 6 | -D tink_cli=0.5.1 7 | # Make sure docs are generated 8 | -D use-rtti-doc -------------------------------------------------------------------------------- /haxe_libraries/tink_streams.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_streams#5066a96c4a8b483479b6a8df8893eaf8922d3bea" into tink_streams/0.4.0/github/5066a96c4a8b483479b6a8df8893eaf8922d3bea 2 | -lib tink_core 3 | -cp ${HAXE_LIBCACHE}/tink_streams/0.4.0/github/5066a96c4a8b483479b6a8df8893eaf8922d3bea/src 4 | -D tink_streams=0.4.0 5 | # temp for development, delete this file when pure branch merged 6 | -D pure -------------------------------------------------------------------------------- /haxe_libraries/tink_unittest.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_unittest#1e5a32110a5921ecacf27d189d1e47311a3ce6dc" into tink_unittest/0.8.0/github/1e5a32110a5921ecacf27d189d1e47311a3ce6dc 2 | -lib tink_syntaxhub 3 | -lib tink_testrunner 4 | -cp ${HAXE_LIBCACHE}/tink_unittest/0.8.0/github/1e5a32110a5921ecacf27d189d1e47311a3ce6dc/src 5 | -D tink_unittest=0.8.0 6 | --macro tink.unit.AssertionBufferInjector.use() -------------------------------------------------------------------------------- /haxe_libraries/tink_testrunner.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/haxetink/tink_testrunner#45f704215ae28c3d864755036dc2ee63f7c44e8a" into tink_testrunner/0.9.0/github/45f704215ae28c3d864755036dc2ee63f7c44e8a 2 | -lib ansi 3 | -lib tink_macro 4 | -lib tink_streams 5 | -cp ${HAXE_LIBCACHE}/tink_testrunner/0.9.0/github/45f704215ae28c3d864755036dc2ee63f7c44e8a/src 6 | -D tink_testrunner=0.9.0 7 | --macro addGlobalMetadata('ANSI.Attribute', "@:native('ANSIAttribute')", false) -------------------------------------------------------------------------------- /haxelib.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tink_web", 3 | "classPath": "src", 4 | "dependencies": { 5 | "tink_querystring": "", 6 | "tink_http": "", 7 | "tink_json": "" 8 | }, 9 | "url": "https://github.com/haxetink/tink_web/", 10 | "contributors": [ 11 | "back2dos" 12 | ], 13 | "version": "0.3.0", 14 | "releasenote": "Various updates.", 15 | "tags": [ 16 | "tink", 17 | "http", 18 | "routing", 19 | "dispatch", 20 | "api", 21 | "rest" 22 | ], 23 | "license": "MIT" 24 | } -------------------------------------------------------------------------------- /haxe_libraries/travix.hxml: -------------------------------------------------------------------------------- 1 | # @install: lix --silent download "gh://github.com/back2dos/travix#63b230b854c6f02cf2ac04bb758c09751f28b8e8" into travix/0.15.0/github/63b230b854c6f02cf2ac04bb758c09751f28b8e8 2 | # @post-install: cd ${HAXE_LIBCACHE}/travix/0.15.0/github/63b230b854c6f02cf2ac04bb758c09751f28b8e8 && haxe -cp src --run travix.PostDownload 3 | # @run: haxelib run-dir travix ${HAXE_LIBCACHE}/travix/0.15.0/github/63b230b854c6f02cf2ac04bb758c09751f28b8e8 4 | -lib tink_cli 5 | -cp ${HAXE_LIBCACHE}/travix/0.15.0/github/63b230b854c6f02cf2ac04bb758c09751f28b8e8/src 6 | -D travix=0.15.0 7 | --macro travix.Macro.setup() -------------------------------------------------------------------------------- /src/tink/web/forms/FormField.hx: -------------------------------------------------------------------------------- 1 | package tink.web.forms; 2 | 3 | import tink.http.StructuredBody; 4 | import tink.http.Request; 5 | import tink.Stringly; 6 | 7 | abstract FormField(BodyPart) from BodyPart to BodyPart { 8 | public function getValue():Stringly 9 | return switch this { 10 | case Value(v): v; 11 | case File(_): throw 'expected plain value but received file'; 12 | } 13 | 14 | @:to function toFloat():Float 15 | return getValue(); 16 | 17 | @:to function toInt():Int 18 | return getValue(); 19 | 20 | @:to function toString():String 21 | return getValue(); 22 | 23 | @:to public function getFile():FormFile 24 | return switch this { 25 | case Value(_): throw 'expected file but got plain value'; 26 | case File(u): @:privateAccess new FormFile(u); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /.travis.yml.disabled: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: xenial 3 | 4 | stages: 5 | - test 6 | - deploy 7 | 8 | language: node_js 9 | node_js: 8 10 | 11 | os: 12 | - linux 13 | # - osx 14 | 15 | env: 16 | 17 | - HAXE_VERSION=latest 18 | - HAXE_VERSION=nightly 19 | 20 | install: 21 | - npm i -g lix@15.8.17 22 | - lix install haxe $HAXE_VERSION 23 | - lix download 24 | 25 | script: 26 | - lix run travix node 27 | - lix run travix php 28 | 29 | jobs: 30 | include: 31 | # - stage: test # should uncomment this when there is no matrix above (e.g. only one os, one env, etc) 32 | - stage: deploy 33 | os: linux 34 | install: 35 | - npm i -g lix 36 | - lix download 37 | script: skip 38 | env: 39 | secure: MamnIjFbl+sRoiwwiy3dcCSX1RuGPh2E1O7YeMIYfr0/MCogWQ2Boeg+Y0R+DCA3+MkfNWqWQzfdECpMVOByyYjWmkVbGZVcORI8Bdz+ICiFUTLdGZ3L3HqRBvtqn0wrFLwDeIGhjlfk+tmUcNDfv+L4ao6flrJ6wy+/GbL4kLQ= 40 | after_success: 41 | - lix run travix install 42 | - lix run travix release 43 | -------------------------------------------------------------------------------- /tests/Helpers.hx: -------------------------------------------------------------------------------- 1 | class Helpers { 2 | static public function get(url, ?headers) 3 | return req(url, GET, headers); 4 | 5 | static public function req(url:String, ?method = tink.http.Method.GET, ?headers, ?body:IdealSource) { 6 | if (headers == null) 7 | headers = [new HeaderField('accept', 'application/json')]; 8 | 9 | if (body == null) 10 | body = Source.EMPTY; 11 | return new IncomingRequest('1.2.3.4', new IncomingRequestHeader(method, url, '1.1', headers), Plain(body)); 12 | } 13 | 14 | static public function check(p:Promise, message:String, test:String->Bool) { 15 | return p.next(function (o) return switch o.header.statusCode { 16 | case 200: 17 | o.body.all().next(function (b) return switch test.bind(b.toString()).catchExceptions() { 18 | case Failure(e): e; 19 | case Success(passed): new Assertion(passed, message); 20 | }); 21 | case v: new Assertion(false, 'Request failed because ${o.header.reason} (${o.header.statusCode.toInt()})'); 22 | }); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/tink/web/macros/RouteCollection.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | class RouteCollection { 5 | 6 | public var routes(default, null):Array = []; 7 | public var type(default, null):Type; 8 | public var restricts(default, null):Array; 9 | 10 | public function new(type:Type, consumes:Array, produces:Array) { 11 | this.type = type; 12 | // override default mimes if corresponding meta specified 13 | switch type { 14 | case TInst(_.get().meta => m, _) | TAbstract(_.get().meta => m, _) | TType(_.get().meta => m, _): 15 | consumes = MimeType.fromMeta(m, 'consumes', consumes); 16 | produces = MimeType.fromMeta(m, 'produces', produces); 17 | default: 18 | } 19 | 20 | var placeholder = type.toComplex({ direct: true }); 21 | function getType(f:ClassField) { 22 | var name = f.name; 23 | return (macro @:pos(f.pos) (null:$placeholder).$name).typeof().sure(); 24 | } 25 | 26 | for(f in type.getFields(false).sure()) 27 | if(Route.hasWebMeta(f)) 28 | routes.push(new Route(f, consumes, produces, getType(f))); 29 | 30 | restricts = Route.getRestricts(type.getMeta()); 31 | } 32 | 33 | public inline function iterator() return routes.iterator(); 34 | } 35 | #end -------------------------------------------------------------------------------- /src/tink/web/macros/Signature.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | class Signature { 5 | 6 | static var CONTEXT:Lazy = Context.getType.bind('tink.web.routing.Context'); 7 | 8 | public var paths(default, null):Paths; 9 | public var params(default, null):Parameters; 10 | public var args(default, null):Arguments; 11 | public var result(default, null):Result; 12 | 13 | public function new(f:ClassField, type:Type) { 14 | switch type.reduce() { 15 | case TFun(args, ret): 16 | this.paths = new Paths(f.name, args, f.meta); 17 | this.params = new Parameters(f.meta, [for(a in args) a.name => a.t]); 18 | this.args = new Arguments(args, paths, params, f.pos); 19 | this.result = new Result(lift(ret, f.pos)); 20 | case t: 21 | this.paths = new Paths(f.name, [], f.meta); 22 | this.params = new Parameters(f.meta, new Map()); 23 | this.args = new Arguments([], paths, params, f.pos); 24 | this.result = new Result(lift(t, f.pos)); 25 | } 26 | } 27 | 28 | static function lift(t:Type, pos:Position) { 29 | var ct = t.toComplex(); 30 | return (macro @:pos(pos) { 31 | function get(p:tink.core.Promise):A throw 'whatever'; 32 | get((null : $ct)); 33 | }).typeof().sure(); 34 | } 35 | 36 | } 37 | #end -------------------------------------------------------------------------------- /src/tink/web/macros/Result.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import haxe.macro.Type; 5 | import haxe.macro.Context; 6 | 7 | using tink.CoreApi; 8 | using tink.MacroApi; 9 | 10 | class Result { 11 | 12 | var call:Lazy; 13 | var type:Type; 14 | 15 | static var RAW_RESPONSE:Lazy = Context.getType.bind('tink.web.routing.Response'); 16 | static var PARSED_RESPONSE:Lazy = Context.getType.bind('tink.web.Response'); 17 | 18 | public function new(type:Type) { 19 | this.type = type; 20 | this.call = function() return 21 | if (type.getID() == 'tink.core.Noise') 22 | RNoise; 23 | else if (type.unifiesWith(PARSED_RESPONSE)) { 24 | switch type.isSubTypeOf(PARSED_RESPONSE, type.getPosition().sure()) { 25 | case Success(TAbstract(_, [data])): ROpaque(OParsed(type, data)); 26 | default: throw 'assert'; 27 | } 28 | } 29 | else if (type.unifiesWith(RAW_RESPONSE)) 30 | ROpaque(ORaw(type)); 31 | else 32 | RData(type); 33 | } 34 | 35 | public inline function asSubTarget() return type; 36 | public inline function asCallResponse() return call.get(); 37 | } 38 | 39 | enum CallResponse { 40 | RNoise; 41 | RData(type:Type); 42 | ROpaque(res:OpaqueResponse); 43 | } 44 | 45 | enum OpaqueResponse { 46 | OParsed(response:Type, data:Type); 47 | ORaw(response:Type); 48 | } 49 | #end -------------------------------------------------------------------------------- /src/tink/web/forms/FormFile.hx: -------------------------------------------------------------------------------- 1 | package tink.web.forms; 2 | 3 | import haxe.io.Bytes; 4 | import tink.chunk.ByteChunk; 5 | import tink.json.Representation; 6 | import tink.http.StructuredBody; 7 | 8 | using tink.io.Source; 9 | using tink.CoreApi; 10 | 11 | typedef JsonFileRep = Representation<{ 12 | mimeType:String, 13 | fileName:String, 14 | content:Bytes, 15 | }>; 16 | 17 | @:forward 18 | abstract FormFile(UploadedFile) { 19 | 20 | inline function new(v) this = v; 21 | 22 | @:to function toJson():JsonFileRep { 23 | return new Representation({ 24 | fileName: this.fileName, 25 | mimeType: this.mimeType, 26 | content: { 27 | var src = this.read(); 28 | var chunk = null; 29 | var write = src.all().handle(function(c) chunk = c.sure()); 30 | if(chunk != null) 31 | chunk.toBytes(); 32 | else { 33 | write.dissolve(); 34 | throw new Error(NotImplemented, 'Can only upload files through JSON backed by with sync sources but got a $src'); 35 | } 36 | } 37 | }); 38 | } 39 | 40 | @:from static function ofJson(rep:JsonFileRep):FormFile { 41 | var data = rep.get(); 42 | return new FormFile(ofBlob(data.fileName, data.mimeType, data.content)); 43 | } 44 | 45 | static inline public function ofBlob(name:String, type:String, data:Bytes):UploadedFile 46 | return UploadedFile.ofBlob(name, type, data); 47 | } -------------------------------------------------------------------------------- /src/tink/web/macros/Variant.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.http.Method; 5 | import tink.web.macros.Paths; 6 | 7 | @:structInit 8 | class Variant { 9 | public var path(default, null):Path; 10 | 11 | public static function checkVariants(pos:Position, variants:Iterable) { 12 | function warn(prefix, pos:Position, args:Array) { 13 | var names = switch args { 14 | case [single]: '`$single`'; 15 | default: 16 | 's `${args.slice(0, -1).join("`, `")}` and `${args[args.length - 1]}`'; 17 | } 18 | pos.warning(prefix + names); 19 | } 20 | 21 | if (!Lambda.exists(variants, function (v) return v.path.deviation.missing.length == 0)) { 22 | pos.warning('All defined routes are incomplete'); 23 | for (v in variants) 24 | warn('Route does not capture argument', v.path.pos, v.path.deviation.missing); 25 | } 26 | 27 | if (!Lambda.exists(variants, function (v) return v.path.deviation.surplus.length == 0)) { 28 | pos.warning('All defined routes are overdetermined'); 29 | for (v in variants) 30 | warn('Route captures surplus portion', v.path.pos, v.path.deviation.surplus); 31 | } 32 | 33 | } 34 | 35 | public static function seek(paths:Paths, pos:Position) { 36 | for (path in paths) 37 | if (path.deviation.surplus.length == 0) 38 | return path; 39 | 40 | return pos.error('Cannot process route. See warnings.'); 41 | } 42 | } 43 | 44 | @:structInit 45 | class CallVariant extends Variant { 46 | public var method(default, null):Option; 47 | } 48 | #end -------------------------------------------------------------------------------- /src/tink/Web.hx: -------------------------------------------------------------------------------- 1 | package tink; 2 | 3 | #if macro 4 | import haxe.macro.Expr; 5 | using tink.MacroApi; 6 | #end 7 | class Web { 8 | static public macro function connect(e:Expr, ?options:ExprOf) 9 | return switch e { 10 | case macro ($url:$t), { expr: ENew(TPath(_) => t, [url])}: 11 | var options = switch options { 12 | case null | macro null: new Map(); 13 | case { expr: EObjectDecl(fields) }: 14 | // TODO: make sure to maintain display support 15 | (macro @:pos(options.pos) ($options:tink.web.proxy.ConnectOptions)).typeof().sure(); 16 | [for (f in fields) f.field => f.expr]; 17 | case v: 18 | v.reject('anonymous object expected'); 19 | } 20 | 21 | var client = switch options['client'] { 22 | case null: 23 | var isSecure = switch url.getString() { 24 | case Success(v): 25 | macro $v{tink.Url.parse(v, _ -> {}).scheme != 'http'}; 26 | default: 27 | macro tink.Url.parse($url, _ -> {}).scheme != 'http'; 28 | } 29 | macro @:privateAccess tink.http.Fetch.getClient(Default);//not sure how adequate this is 30 | case v: macro @:pos(v.pos) ($v:tink.http.Client); 31 | } 32 | 33 | switch options['augment'] { 34 | case null: 35 | case v: 36 | client = macro @:pos(v.pos) $client.augment($v); 37 | } 38 | 39 | var endpoint = macro @:pos(url.pos) tink.web.proxy.Remote.RemoteEndpoint.ofString($url); 40 | 41 | switch options['headers'] { 42 | case null: 43 | case v: 44 | endpoint = macro @:pos(v.pos) $endpoint.sub({ headers: $v }); 45 | } 46 | 47 | //TODO: if t is already a RemoteBase, don't wrap it 48 | macro @:pos(e.pos) new tink.web.proxy.Remote<$t>($client, $endpoint); 49 | default: e.pos.error('Expected `(url:Type)` or `new Type(url)`'); 50 | } 51 | } -------------------------------------------------------------------------------- /tests/FacadeTest.hx: -------------------------------------------------------------------------------- 1 | import tink.http.Client; 2 | import tink.web.proxy.Remote; 3 | 4 | @:asserts 5 | class FacadeTest { 6 | public function new() { 7 | 8 | } 9 | 10 | public function connect() { 11 | var p1 = tink.Web.connect(('http://example.com/':Fake)), 12 | p2 = tink.Web.connect(new Fake('http://example.com/')), 13 | p3 = new Remote(null, RemoteEndpoint.ofString('http://example.com/')); 14 | 15 | asserts.assert(Type.getClass(p1) == Type.getClass(p2)); 16 | asserts.assert(Type.getClass(p1) == Type.getClass(p3)); 17 | 18 | function getEndpoint(r:RemoteBase) 19 | return Std.string(@:privateAccess r.endpoint); 20 | 21 | asserts.assert(getEndpoint(p1) == getEndpoint(p2)); 22 | asserts.assert(getEndpoint(p1) == getEndpoint(p3)); 23 | 24 | var full = tink.Web.connect(('http://007:moneypenny@example.com/':Fake), { 25 | client: new FakeClient(), 26 | headers: [ 27 | new HeaderField('x-foo', 'bar'), 28 | ], 29 | augment: { 30 | before: [out -> new OutgoingRequest(out.header.concat([new HeaderField('x-bar', 'foo')]), out.body)], 31 | } 32 | }); 33 | 34 | full.count(123).handle(function (o) { 35 | asserts.assert(o.match(Failure({ message: 'fake' }))); 36 | switch FakeClient.log { 37 | case [{ header: h }]: 38 | asserts.assert(h.byName('x-foo').match(Success('bar'))); 39 | asserts.assert(h.byName('x-bar').match(Success('foo'))); 40 | asserts.assert(h.byName(CONTENT_LENGTH).match(Success('0'))); 41 | asserts.assert(h.byName(ACCEPT).match(Success('application/json'))); 42 | asserts.assert(h.byName(AUTHORIZATION).match(Success(_))); 43 | 44 | case a: asserts.assert(a.length == 1); 45 | } 46 | }); 47 | 48 | return asserts.done(); 49 | } 50 | } 51 | 52 | private class FakeClient implements ClientObject { 53 | public function new() {} 54 | static public var log:Array = []; 55 | public function request(req:OutgoingRequest):Promise { 56 | log.push(req); 57 | return new Error('fake'); 58 | } 59 | } -------------------------------------------------------------------------------- /tests/RemoteEndpoints.hx: -------------------------------------------------------------------------------- 1 | import tink.web.proxy.Remote; 2 | 3 | @:asserts 4 | class RemoteEndpoints { 5 | public function new() {} 6 | 7 | public function test() { 8 | function mk(v:Array) 9 | return v; 10 | 11 | var example = ['example'][Std.random(0)]; 12 | 13 | for (r in mk([ 14 | 'http://example.com/foo/bar%20bar?gl%26rgh=123%65', 15 | 'http://$example.com/foo/bar%20bar?gl%26rgh=123%65', 16 | RemoteEndpoint.ofString('http://$example.com/foo/bar%20bar?gl%26rgh=123%65'), 17 | ])) { 18 | 19 | asserts.assert(Lambda.count(r.headers) == 0); 20 | switch Lambda.array(r.path) { 21 | case [foo, barbar]: 22 | asserts.assert(foo.raw == 'foo'); 23 | asserts.assert(barbar.raw == 'bar%20bar'); 24 | asserts.assert((barbar:String) == 'bar bar'); 25 | case a: asserts.assert(a.length == 2); 26 | } 27 | 28 | switch Lambda.array(r.query) { 29 | case [{ name: n, value: v}]: 30 | asserts.assert(n.raw == 'gl%26rgh'); 31 | asserts.assert((n:String) == 'gl&rgh'); 32 | asserts.assert(v.raw == '123%65'); 33 | asserts.assert((v:String) == '123e'); 34 | case a: asserts.assert(a.length == 1); 35 | } 36 | 37 | } 38 | 39 | for (r in mk([ 40 | 'http://spaceballs:12345@example.com/foo/bar?glargh', 41 | 'http://spaceballs:12345@$example.com/foo/bar?glargh', 42 | RemoteEndpoint.ofString('http://spaceballs:12345@$example.com/foo/bar?glargh'), 43 | ])) { 44 | asserts.assert(r.host == 'example.com'); 45 | 46 | switch Lambda.array(r.headers) { 47 | case [h]: 48 | asserts.assert(h.name == AUTHORIZATION); 49 | asserts.assert(h.value == tink.http.Header.HeaderValue.basicAuth('spaceballs', '12345')); 50 | case a: asserts.assert(a.length == 1); 51 | } 52 | } 53 | 54 | for (r in mk([ 55 | 'http://spaceballs:12345@example.com/foo/bar?glargh=123#.json', 56 | 'http://spaceballs:12345@$example.com/foo/bar?glargh=123#.json', 57 | RemoteEndpoint.ofString('http://spaceballs:12345@$example.com/foo/bar?glargh=${123}#.json'), 58 | ])) { 59 | asserts.assert(r.pathSuffix == '.json'); 60 | } 61 | 62 | return asserts.done(); 63 | } 64 | 65 | public function issue123() { 66 | final endpoint = new RemoteEndpoint(new tink.url.Host("127.0.0.1", 8081)); 67 | asserts.assert(endpoint.scheme == ''); 68 | return asserts.done(); 69 | } 70 | } -------------------------------------------------------------------------------- /src/tink/web/routing/Response.hx: -------------------------------------------------------------------------------- 1 | package tink.web.routing; 2 | 3 | import haxe.io.Bytes; 4 | import httpstatus.HttpStatusCode; 5 | import tink.http.Response; 6 | import tink.http.Header; 7 | 8 | using tink.io.Source; 9 | 10 | @:forward 11 | abstract Response(OutgoingResponse) from OutgoingResponse to OutgoingResponse { 12 | 13 | static inline var BINARY = 'application/octet-stream'; 14 | 15 | static public function ofChunk(c:Chunk, ?contentType:String = BINARY) 16 | return binary(null, contentType, c); 17 | 18 | @:from static function ofString(s:String):Response 19 | return textual('text/plain', s); 20 | 21 | @:from static function ofBytes(b:Bytes):Response 22 | return binary(BINARY, b); 23 | 24 | @:from static function fromChunk(c:Chunk) 25 | return ofChunk(c); 26 | 27 | static public function ofRealSource(source:RealSource, ?contentType:String = BINARY):Response 28 | return new OutgoingResponse(new ResponseHeader(OK, OK, [new HeaderField(CONTENT_TYPE, contentType)]), source.idealize(function(_) return Source.EMPTY)); 29 | 30 | static public function ofIdealSource(source:IdealSource, ?contentType:String = BINARY):Response 31 | return new OutgoingResponse(new ResponseHeader(OK, OK, [new HeaderField(CONTENT_TYPE, contentType)]), source); 32 | 33 | @:from static function fromRealSource(source:RealSource):Response 34 | return ofRealSource(source.idealize(function(_) return Source.EMPTY)); 35 | 36 | @:from static function fromIdealSource(source:IdealSource):Response 37 | return ofIdealSource(source); 38 | 39 | #if tink_htmlstring 40 | @:from static function ofHtml(h:tink.HtmlString) 41 | return textual('text/html', h); 42 | #end 43 | #if tink_template 44 | @:from static function ofTemplate(h:tink.template.Html) 45 | return textual('text/html', h); 46 | #end 47 | 48 | @:from static function ofUrl(u:tink.Url):Response { 49 | return new OutgoingResponse(new ResponseHeader(Found, Found, [new HeaderField('location', u)]), Chunk.EMPTY); 50 | } 51 | 52 | static public function binary(?code = OK, contentType:String, bytes:Bytes, ?headers):Response { 53 | //TODO: calculate ETag 54 | return OutgoingResponse.blob(code, bytes, contentType, headers); 55 | } 56 | 57 | static public function empty(?code = OK):Response { 58 | return new OutgoingResponse(new ResponseHeader(code, code, [new HeaderField(CONTENT_LENGTH, '0')]), Chunk.EMPTY); 59 | } 60 | 61 | static public function textual(?code = OK, contentType:String, string:String, ?headers):Response 62 | return binary(code, contentType, Bytes.ofString(string), headers); 63 | } 64 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | branches: [ master ] 7 | 8 | jobs: 9 | test: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | haxe-version: 16 | - stable 17 | # - nightly 18 | target: 19 | - php 20 | - node 21 | 22 | steps: 23 | - name: Check out repo 24 | uses: actions/checkout@v3 25 | 26 | - name: Get yarn cache directory path 27 | id: yarn-cache-dir-path 28 | run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT 29 | 30 | - name: Cache Yarn 31 | uses: actions/cache@v3 32 | with: 33 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 34 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 35 | restore-keys: | 36 | ${{ runner.os }}-yarn- 37 | 38 | - name: Cache Haxe 39 | uses: actions/cache@v3 40 | with: 41 | path: ${{ startsWith(runner.os, 'windows') && '%AppData%' || '~/haxe' }} 42 | key: ${{ runner.os }}-haxe 43 | 44 | - name: Install Lix 45 | uses: lix-pm/setup-lix@master 46 | 47 | - name: Install Haxe 48 | run: lix install haxe ${{ matrix.haxe-version }} 49 | 50 | - name: Install Haxe Libraries 51 | run: lix download 52 | 53 | - name: Run Test 54 | run: lix run travix ${{ matrix.target }} 55 | 56 | release: 57 | runs-on: ubuntu-latest 58 | needs: test 59 | if: startsWith(github.ref, 'refs/tags/') # consider using the "release" event. see: https://docs.github.com/en/actions/reference/events-that-trigger-workflows#release 60 | 61 | steps: 62 | - name: Check out repo 63 | uses: actions/checkout@v3 64 | 65 | - name: Get yarn cache directory path 66 | id: yarn-cache-dir-path 67 | run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT 68 | 69 | - name: Cache Yarn 70 | uses: actions/cache@v3 71 | with: 72 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 73 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 74 | restore-keys: | 75 | ${{ runner.os }}-yarn- 76 | 77 | - name: Cache Haxe 78 | uses: actions/cache@v3 79 | with: 80 | path: ${{ startsWith(runner.os, 'windows') && '%AppData%' || '~/haxe' }} 81 | key: ${{ runner.os }}-haxe 82 | 83 | - name: Install Lix 84 | uses: lix-pm/setup-lix@master 85 | 86 | - name: Install Haxe 87 | run: lix install haxe stable 88 | 89 | - name: Install Haxe Libraries 90 | run: lix download 91 | 92 | - name: Release to Haxelib 93 | run: lix run travix release 94 | env: 95 | HAXELIB_AUTH: ${{ secrets.HAXELIB_AUTH }} 96 | -------------------------------------------------------------------------------- /src/tink/web/macros/MimeType.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | abstract MimeType(String) from String to String { 5 | 6 | static function typedString(e:Expr) 7 | return switch Context.typeExpr(e) { 8 | case { expr: TConst(TString(s)) }: 9 | s; 10 | case t: 11 | e.reject('Expected String but found $t'); 12 | } 13 | 14 | static public function fromMeta(meta:MetaAccess, kind:String, old:Array) 15 | return switch [for (m in meta.extract(':$kind')) for (e in m.params) e] { 16 | case []: old; 17 | case v: 18 | function isUnop(e:Expr) 19 | return e.expr.match(EUnop(_, _, _)); 20 | 21 | switch v.filter(isUnop) { 22 | case []: 23 | 24 | [for (e in v) typedString(e)]; 25 | 26 | case mixed if (mixed.length < v.length): 27 | 28 | mixed[0].reject('you must either modify or replace mime types'); 29 | 30 | case all: 31 | 32 | var ret = old.copy(); 33 | 34 | for (e in v) 35 | switch e { 36 | case (macro --$e) | (macro $e--): 37 | ret.remove(typedString(e)); 38 | case (macro ++$e) | (macro $e++): 39 | var s = typedString(e); 40 | while (ret.remove(s)) { } 41 | ret.push(s); 42 | default: 43 | e.reject(); 44 | } 45 | 46 | ret; 47 | } 48 | 49 | } 50 | 51 | static public var readers(default, null) = new Registry('reader', [ 52 | 'application/json' => function (type:Type, pos:Position) { 53 | var ct = type.toComplex({ direct: true }); 54 | return macro @:pos(pos) new tink.json.Parser<$ct>().tryParse; 55 | }, 56 | ]); 57 | static public var writers(default, null) = new Registry('writer', [ 58 | 'application/json' => function (type:Type, pos:Position) { 59 | var ct = type.toComplex( { direct: true } ); 60 | return macro @:pos(pos) new tink.json.Writer<$ct>().write; 61 | }, 62 | 'application/x-www-form-urlencoded' => function (type:Type, pos:Position) { 63 | var ct = type.toComplex( { direct: true } ); 64 | return macro @:pos(pos) new tink.querystring.Builder<$ct>().stringify; 65 | }, 66 | ]); 67 | 68 | } 69 | 70 | private class Registry { 71 | var map:MapPosition->Expr>; 72 | var kind:String; 73 | 74 | public function new(kind, map) { 75 | this.kind = kind; 76 | this.map = map; 77 | } 78 | 79 | public function register(type:MimeType, reader:Type->Expr) 80 | if (map.exists(type)) 81 | throw 'Duplicate registration for type $type'; 82 | 83 | public function get(options:Array, type, pos:Position) { 84 | 85 | for (a in options) 86 | switch map[a] { 87 | case null: 88 | case gen: return { type: a, generator: gen(type, pos) }; 89 | } 90 | 91 | options = options.copy(); 92 | var last = options.pop(); 93 | return pos.error('No $kind available for '+ switch options { 94 | case []: 'mime type $last'; 95 | default: 'any of the mime types ' + options.join(', ') + ' or $last'; 96 | }); 97 | } 98 | } 99 | #end -------------------------------------------------------------------------------- /tests/RawTest.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import deepequal.DeepEqual.compare; 4 | import tink.http.Request; 5 | import tink.http.Response; 6 | import tink.http.Client; 7 | import tink.http.Container; 8 | import tink.http.clients.*; 9 | import tink.http.containers.*; 10 | import tink.url.Host; 11 | import tink.web.proxy.Remote; 12 | import tink.unit.Assert.assert; 13 | 14 | using tink.CoreApi; 15 | 16 | @:asserts 17 | class RawTest { 18 | 19 | var container:LocalContainer; 20 | var client:Client; 21 | 22 | public function new() { 23 | container = new LocalContainer(); 24 | client = new LocalContainerClient(container); 25 | container.run(function (req:IncomingRequest) { 26 | return DispatchTest.exec(req).recover(OutgoingResponse.reportError); 27 | }); 28 | } 29 | 30 | @:variant(POST, 201) 31 | @:variant(GET, 307) 32 | public function statusCode(method, code) { 33 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(method, '/statusCode', []), '')) 34 | .next(function(res) return assert(res.header.statusCode == code)); 35 | } 36 | 37 | public function responseHeader() { 38 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(POST, '/responseHeader', []), '')) 39 | .next(function(res) { 40 | asserts.assert(res.header.byName('tink').match(Success('web'))); 41 | asserts.assert(res.header.byName('tink_web').match(Success('foobar'))); 42 | return asserts.done(); 43 | }); 44 | } 45 | 46 | public function issue114() { 47 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(GET, '/issue114', []), '')) 48 | .next(function(res) { 49 | asserts.assert(res.header.byName('tink').match(Success('web'))); 50 | asserts.assert(res.header.byName('tink_web').match(Success('foobar'))); 51 | asserts.assert(res.header.statusCode == 200); 52 | return asserts.done(); 53 | }); 54 | } 55 | 56 | public function issue114_2() { 57 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(GET, '/issue114_2', []), '')) 58 | .next(function(res) { 59 | asserts.assert(res.header.byName('tink').match(Success('web'))); 60 | asserts.assert(res.header.byName('tink_web').match(Success('foobar'))); 61 | asserts.assert(res.header.statusCode == 418); 62 | return asserts.done(); 63 | }); 64 | } 65 | 66 | public function noise() { 67 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(GET, '/noise', []), '')) 68 | .next(function(res) { 69 | asserts.assert(res.header.statusCode == 200); 70 | return res.body.all(); 71 | }) 72 | .next(function(chunk) { 73 | asserts.assert(chunk.length == 0); 74 | return asserts.done(); 75 | }); 76 | return asserts; 77 | } 78 | 79 | public function noiseWithError() { 80 | return client.request(new OutgoingRequest(new OutgoingRequestHeader(GET, '/noise?error=true', []), '')) 81 | .next(function(res) { 82 | asserts.assert(res.header.statusCode == 500); 83 | return res.body.all(); 84 | }) 85 | .next(function(chunk) { 86 | asserts.assert(chunk.length > 0); 87 | return asserts.done(); 88 | }); 89 | return asserts; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/tink/web/macros/Arguments.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.web.macros.Parameters; 5 | 6 | // hold information extracted from the function argument list 7 | class Arguments { 8 | var list:Array = []; 9 | static var CONTEXT:Lazy = Context.getType.bind('tink.web.routing.Context'); 10 | 11 | public function new(args:Array<{t:Type, opt:Bool, name:String}>, paths:Paths, params:Parameters, pos:Position) { 12 | for(a in args) list.push({ 13 | name: a.name, 14 | type: a.t, 15 | optional: a.opt, 16 | kind: switch [a.name, a.t.reduce()] { 17 | case [_, _] if(a.t.unifiesWith(CONTEXT)): 18 | AKSingle(a.opt, ATContext); 19 | case ['user', _] if(a.name == 'user'): 20 | AKSingle(a.opt, ATUser(a.t)); 21 | case ['query' | 'header' | 'body', t = TAnonymous(_)]: 22 | anon(a.opt, t, function(name) return ATParam(Parameters.LOCATION_FACTORY[a.name](name))); 23 | case ['body', _]: 24 | AKSingle(a.opt, ATParam(PKBody(None))); 25 | case [name, TAnonymous(_.get() => {fields: fields})]: 26 | AKObject(a.opt, [for(field in fields) { 27 | name: field.name, 28 | type: field.type, 29 | optional: field.meta.has(':optional'), 30 | target: getArgTarget(paths, params, Drill({name: name, nullable: field.meta.has(':optional')}, field.name), a.opt, pos), 31 | }]); 32 | case [name, _]: 33 | AKSingle( 34 | a.opt, 35 | getArgTarget(paths, params, Plain(name), a.opt, pos) 36 | ); 37 | } 38 | }); 39 | } 40 | 41 | public inline function iterator() return list.iterator(); 42 | 43 | static function getArgTarget(paths:Paths, params:Parameters, access:ArgAccess, optional:Bool, pos:Position) { 44 | return switch [paths.hasCapture(access), params.get(access)] { 45 | case [true, Some(param)]: 46 | param.source.pos.error('`${stringifyArgAccess(access)}` is both captured in path and specified as parameter with @:params(${param.source.toString()})'); 47 | case [false, Some(param)]: 48 | ATParam(param.kind); 49 | case [true, None]: 50 | ATCapture; 51 | case [false, None]: 52 | if(!optional) 53 | tryQuery(paths, access, pos); 54 | else 55 | ATCapture; 56 | } 57 | } 58 | 59 | static function tryQuery(paths:Paths, access:ArgAccess, pos:Position) { 60 | var access = stringifyArgAccess(access); 61 | for (p in paths) 62 | if (!Lambda.exists(p.query, v -> switch v { 63 | case PCapture(v): stringifyArgAccess(v) == access; 64 | case PConst(_): false; 65 | })) 66 | p.pos.error('${p.expr.toString()} does not capture required parameter `$access`. Please specify its use with the @:params metadata or capture it.'); 67 | 68 | return ATCapture; 69 | } 70 | 71 | static function stringifyArgAccess(access:ArgAccess) { 72 | return switch access { 73 | case Plain(name): name; 74 | case Drill({name: name}, field): '$name.$field'; 75 | } 76 | } 77 | 78 | 79 | static function anon(optional:Bool, type:Type, factory:String->ArgTarget):ArgKind { 80 | return switch type { 81 | case TAnonymous(_.get() => {fields: fields}): 82 | AKObject(optional, [for(field in fields) { 83 | name: field.name, 84 | type: field.type, 85 | optional: field.meta.has(':optional'), 86 | target: factory(Parameters.getParamName(field)), 87 | }]); 88 | case _: 89 | throw 'unreachable'; 90 | } 91 | } 92 | } 93 | 94 | 95 | typedef RouteArg = { 96 | var name(default, null):String; 97 | var type(default, null):Type; 98 | var optional(default, null):Bool; 99 | var kind(default, null):ArgKind; 100 | } 101 | 102 | enum ArgAccess { 103 | Plain(name:String); 104 | Drill(object:{name:String, nullable:Bool}, field:String); 105 | } 106 | 107 | enum ArgKind { 108 | AKSingle(optional:Bool, target:ArgTarget); 109 | AKObject(optional:Bool, fields:Array<{name:String, type:Type, optional:Bool, target:ArgTarget}>); 110 | } 111 | 112 | enum ArgTarget { 113 | ATContext; 114 | ATUser(type:Type); 115 | ATSession(type:Type); 116 | ATCapture; 117 | ATParam(kind:ParamKind); 118 | } 119 | #end -------------------------------------------------------------------------------- /tests/TestRpc.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import tink.web.routing.Context; 4 | import deepequal.DeepEqual.compare; 5 | 6 | @:asserts 7 | class TestRpc { 8 | public function new() {} 9 | @:variant('/?action=foo&bar=123', {path:"/",bar:123,action:"foo"}) 10 | @:variant('/?action=bar&foo=1', {path:"/",foo:true,action:"bar"}) 11 | @:variant('/baz?action=foo&bar=123', {path:"/baz",bar:123,action:"foo"}) 12 | @:variant('/baz?action=bar&foo=1', {path:"/baz",foo:true,action:"bar"}) 13 | @:variant('/baz/tink?action=foo&bar=123', {path:"/baz/tink",bar:123,action:"foo"}) 14 | @:variant('/baz/tink?action=bar&foo=1', {path:"/baz/tink",foo:true,action:"bar"}) 15 | 16 | @:variant('/?action=foo&page=1&bar=123', {path:"/",bar:123,action:"foo",page:1}) 17 | @:variant('/?action=foo&page=2&bar=123', {path:"/",bar:123,action:"foo",page:2}) 18 | @:variant('/?action=bar&page=1&foo=1', {path:"/",foo:true,action:"bar",page:1}) 19 | @:variant('/?action=bar&page=2&foo=1', {path:"/",foo:true,action:"bar",page:2}) 20 | @:variant('/baz?action=foo&page=1&bar=123', {path:"/baz",bar:123,action:"foo",page:1}) 21 | @:variant('/baz?action=foo&page=2&bar=123', {path:"/baz",bar:123,action:"foo",page:2}) 22 | @:variant('/baz?action=bar&page=1&foo=1', {path:"/baz",foo:true,action:"bar",page:1}) 23 | @:variant('/baz?action=bar&page=2&foo=1', {path:"/baz",foo:true,action:"bar",page:2}) 24 | @:variant('/baz/tink?action=foo&page=1&bar=123', {path:"/baz/tink",bar:123,action:"foo",page:1}) 25 | @:variant('/baz/tink?action=foo&page=2&bar=123', {path:"/baz/tink",bar:123,action:"foo",page:2}) 26 | @:variant('/baz/tink?action=bar&page=1&foo=1', {path:"/baz/tink",foo:true,action:"bar",page:1}) 27 | @:variant('/baz/tink?action=bar&page=2&foo=1', {path:"/baz/tink",foo:true,action:"bar",page:2}) 28 | public function rpc(url:String, result:Dynamic) { 29 | var r = new tink.web.routing.Router(new Rpcesque()); 30 | return r.route(tink.web.routing.Context.ofRequest(get(url))) 31 | .next(function(res) return res.body.all()) 32 | .next(function(chunk) { 33 | asserts.assert(compare(result, haxe.Json.parse(chunk))); 34 | return asserts.done(); 35 | }); 36 | } 37 | } 38 | 39 | class Rpcesque { 40 | public function new() {} 41 | 42 | @:get('/?action=foo&page=1') public function foo1(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 1} 43 | @:get('/?action=bar&page=1') public function bar1(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 1} 44 | @:get('/?action=foo&page=2') public function foo2(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 2} 45 | @:get('/?action=bar&page=2') public function bar2(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 2} 46 | @:get('/baz?action=foo&page=1') public function bazFoo1(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 1} 47 | @:get('/baz?action=bar&page=1') public function bazBar1(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 1} 48 | @:get('/baz?action=foo&page=2') public function bazFoo2(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 2} 49 | @:get('/baz?action=bar&page=2') public function bazBar2(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 2} 50 | @:get('/baz/tink?action=foo&page=1') public function bazTinkFoo1(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 1} 51 | @:get('/baz/tink?action=bar&page=1') public function bazTinkBar1(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 1} 52 | @:get('/baz/tink?action=foo&page=2') public function bazTinkFoo2(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo', page: 2} 53 | @:get('/baz/tink?action=bar&page=2') public function bazTinkBar2(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar', page: 2} 54 | 55 | @:get('/?action=foo') public function foo(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo'} 56 | @:get('/?action=bar') public function bar(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar'} 57 | @:get('/baz?action=foo') public function bazFoo(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo'} 58 | @:get('/baz?action=bar') public function bazBar(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar'} 59 | @:get('/baz/tink?action=foo') public function bazTinkFoo(ctx:Context, query:{ bar:Int }) return {path: ctx.getPath().toString(), bar: query.bar, action: 'foo'} 60 | @:get('/baz/tink?action=bar') public function bazTinkBar(ctx:Context, query:{ foo:Bool }) return {path: ctx.getPath().toString(), foo: query.foo, action: 'bar'} 61 | } -------------------------------------------------------------------------------- /src/tink/web/macros/Paths.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.http.Method; 5 | import tink.url.Portion; 6 | import tink.web.macros.Arguments; 7 | 8 | class Paths { 9 | 10 | public static var metas = { 11 | var ret = [for (m in [GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE]) ':$m'.toLowerCase() => Some(m)]; 12 | ret[':all'] = None; 13 | ret; 14 | } 15 | 16 | var list:Array; 17 | 18 | public function new(fieldName:String, args:Array<{t:Type, name:String, opt:Bool}>, meta:MetaAccess) { 19 | var isSub = false; 20 | var isCall = false; 21 | 22 | list = [for(meta in meta.get()) { 23 | 24 | function checkConflict(conflict) if(conflict) meta.pos.error('Cannot have both routing and subrouting on the same field'); 25 | 26 | switch meta.name { 27 | case ':sub': 28 | isSub = true; 29 | checkConflict(isCall); 30 | Path.make(Sub, fieldName, args, meta); 31 | case metas[_] => null: 32 | continue; 33 | case metas[_] => v: 34 | isCall = true; 35 | checkConflict(isSub); 36 | Path.make(Call(v), fieldName, args, meta); 37 | } 38 | }]; 39 | } 40 | 41 | public inline function iterator() return list.iterator(); 42 | 43 | /** 44 | * Return true if the specified capture exists in all declared paths 45 | * @param kind 46 | */ 47 | public function hasCapture(access:ArgAccess) { 48 | for(path in list) 49 | switch path.getCapture(access) { 50 | case Some(_): // ok 51 | case None: return false; 52 | } 53 | return true; 54 | } 55 | } 56 | 57 | 58 | @:structInit 59 | class Path { 60 | public var expr(default, null):Expr; 61 | public var parts(default, null):Array; 62 | public var query(default, null):Map; 63 | public var rest(default, null):PathRest; 64 | public var kind(default, null):PathKind; 65 | public var deviation(default, null):{ 66 | var surplus(default, null):Array; 67 | var missing(default, null):Array; 68 | } 69 | public var pos(default, null):Position; 70 | 71 | public static function make(kind:PathKind, fieldName:String, args:Array<{t:Type, name:String, opt:Bool}>, m:MetadataEntry):Path { 72 | return switch m.params { 73 | case []: 74 | 75 | make(kind, fieldName, args, { pos: m.pos, name: m.name, params: [fieldName.toExpr(m.pos)] }); 76 | 77 | case [v]: 78 | var url = tink.Url.parse(v.getString().sure()); 79 | 80 | var parts = url.path.parts(); 81 | 82 | var last = parts[parts.length - 1].raw; 83 | 84 | var rest = 85 | if(m.name == ':sub') 86 | RIgnore; 87 | else switch last { 88 | case null: 89 | RNotAllowed; 90 | case '*': 91 | parts.pop(); 92 | RIgnore; 93 | // case _.split('*') => ['', v]: 94 | // parts.pop(); 95 | // RCapture(capture(v)); 96 | default: 97 | RNotAllowed; 98 | } 99 | 100 | // TODO: is this still needed? 101 | // if (!Route.metas.exists(m.name)) { 102 | // switch rest { 103 | // case RCapture(_): 104 | // v.reject('cannot capture path rest in @${m.name}'); 105 | // case RIgnore: 106 | // v.pos.warning('Path rest is always allowed for @${m.name}'); 107 | // default: 108 | // rest = RIgnore; 109 | // } 110 | // } 111 | 112 | function part(of:Portion) 113 | // TODO: support drilled ('/${obj.foo}') and mixed ('/$obj:patch') 114 | return switch of { 115 | case _.raw.split('$') => ['', name]: 116 | PCapture(Plain(name)); 117 | default: 118 | PConst(of); 119 | } 120 | 121 | var parts = [for (p in parts) part(p)], 122 | query = [for (q in url.query) q.name => part(q.value)]; 123 | 124 | 125 | // TODO: is this still needed? 126 | // var optional = new Map(); 127 | // var captured = [for (a in sig.args) switch a.kind { 128 | // case ACapture: 129 | // if (a.optional) 130 | // optional[a.name] = true; 131 | // a.name; 132 | // default: 133 | // continue; 134 | // }]; 135 | 136 | // TODO: 137 | // var surplus = [for (c in getCaptured(parts).concat(getCaptured(query))) if (!captured.remove(c)) c]; 138 | // var missing = [for (c in captured) if (!optional[c]) c]; 139 | var surplus = []; 140 | var missing = []; 141 | 142 | { 143 | kind: kind, 144 | expr: v, 145 | pos: v.pos, 146 | parts: parts, 147 | query: query, 148 | deviation: { surplus: surplus, missing: missing }, 149 | rest: rest, 150 | } 151 | 152 | case v: 153 | v[1].reject('only one path per route allowed'); 154 | } 155 | } 156 | 157 | public function getCapture(access:ArgAccess):Option { 158 | for(part in parts) 159 | switch [access, part] { 160 | case [Plain(n1), PCapture(Plain(n2))] if(n1 == n2): return Some(part); 161 | case [Drill({name: n1}, f1), PCapture(Drill({name: n2}, f2))] if(n1 == n2 && f1 == f2): return Some(part); 162 | case _: 163 | } 164 | return None; 165 | } 166 | } 167 | 168 | enum PathKind { 169 | Sub; 170 | Call(method:Option); 171 | } 172 | 173 | enum PathRest { 174 | RIgnore; 175 | // RCapture(name:String); // TODO: re-enable this 176 | RNotAllowed; 177 | } 178 | 179 | enum PathPart { 180 | PConst(s:Portion); 181 | PCapture(access:ArgAccess); 182 | // PMixed(arr:Array); // TODO: support some kind of mixed/advanced capture, see https://github.com/haxetink/tink_web/issues/26 183 | } 184 | #end -------------------------------------------------------------------------------- /src/tink/web/macros/Parameters.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.web.macros.Arguments; 5 | 6 | // hold information extracted from the @:params metadata 7 | class Parameters { 8 | var params:Array = []; 9 | 10 | public static var LOCATION_FACTORY = [ 11 | 'query' => PKQuery, 12 | 'body' => function(name) return PKBody(Some(name)), 13 | 'header' => PKHeader, 14 | ]; 15 | 16 | public function new(meta:MetaAccess, types:Map) { 17 | for (entry in meta.extract(':params')) 18 | for (p in entry.params) { 19 | 20 | function validate(name:String) { 21 | if (reserved(name)) p.reject('`$name` is reserved'); 22 | if (!types.exists(name)) p.reject('`$name` does not appear in the function argument list'); 23 | } 24 | 25 | function isNullable(name:String) { 26 | return types[name].match(TAbstract(_.get() => {name: 'Null', pack: []}, _)); 27 | } 28 | 29 | function hasField(type:Type, name:String) { 30 | return switch type { 31 | case TAnonymous(_.get() => {fields: fields}): fields.exists(function(field) return field.name == name); 32 | case _: false; 33 | } 34 | } 35 | 36 | function add(access, kind) params.push({source: p, access: access, kind: kind}); 37 | 38 | switch p { 39 | case macro $i{name} in $i{pos = 'query' | 'header' | 'body'}: 40 | validate(name); 41 | add(Plain(name), LOCATION_FACTORY[pos](name)); 42 | 43 | case macro $i{name} = $i{pos = 'query' | 'header' | 'body'}: 44 | validate(name); 45 | switch types[name].reduce() { 46 | case TAnonymous(_.get() => {fields: fields}): 47 | for(field in fields) add(Drill({name: name, nullable: isNullable(name)}, field.name), LOCATION_FACTORY[pos](getParamName(field))); 48 | case _: 49 | p.reject('`$name` should be anonymous structure'); 50 | } 51 | 52 | case macro $i{name} = $i{pos = 'query' | 'header' | 'body'}[$v{(native:String)}]: 53 | validate(name); 54 | if(pos == 'header') native = native.toLowerCase(); // TODO: I think we should make the parser case-insensitive instead 55 | add(Plain(name), LOCATION_FACTORY[pos](native)); 56 | 57 | case macro $i{name}.$field in $i{pos = 'query' | 'header' | 'body'}: 58 | validate(name); 59 | if(!hasField(types[name], field)) p.reject('`$name` does not has field "$field"'); 60 | add(Drill({name: name, nullable: isNullable(name)}, field), LOCATION_FACTORY[pos](field)); 61 | 62 | case macro $i{name}.$field = $i{pos = 'query' | 'header' | 'body'}[$v{(native:String)}]: 63 | validate(name); 64 | if(pos == 'header') native = native.toLowerCase(); // TODO: I think we should make the parser case-insensitive instead 65 | if(!hasField(types[name], field)) p.reject('`$name` does not has field "$field"'); 66 | add(Drill({name: name, nullable: isNullable(name)}, field), LOCATION_FACTORY[pos](native)); 67 | 68 | default: 69 | p.reject('Invalid syntax for @:params, only the following are supported: 70 | @:params( in ) 71 | @:params( = ) 72 | @:params( = ["native"]) 73 | @:params( in ) 74 | @:params( = ["native"])'); 75 | 76 | } 77 | } 78 | 79 | checkForConflict(); 80 | } 81 | 82 | public inline function iterator() return params.iterator(); 83 | 84 | function checkForConflict() { 85 | var checked:Array = []; 86 | for(current in params) { 87 | for(prev in checked) { 88 | if(conflictAccess(prev.access, current.access)) 89 | current.source.reject('Conflicting argument access with "${prev.source.toString()}"'); // TODO: print the actual enum in a human-friendly way 90 | if(conflictKind(prev.kind, current.kind)) 91 | current.source.reject('Conflicting param kind with "${prev.source.toString()}"'); // TODO: print the actual enum in a human-friendly way 92 | checked.push(current); 93 | } 94 | } 95 | } 96 | 97 | static function conflictAccess(a1:ArgAccess, a2:ArgAccess) { 98 | return switch [a1, a2] { 99 | case [Plain(n1), Plain(n2)] | [Drill({name: n1}, _), Plain(n2)] | [Plain(n1), Drill({name: n2}, _)]: n1 == n2; 100 | case [Drill({name: n1}, f1), Drill({name: n2}, f2)]: n1 == n2 && f1 == f2; 101 | } 102 | } 103 | 104 | static function conflictKind(k1:ParamKind, k2:ParamKind) { 105 | return switch [k1, k2] { 106 | case [PKBody(None), PKBody(None)]: true; 107 | case [PKQuery(n1), PKQuery(n2)] 108 | | [PKHeader(n1), PKHeader(n2)] 109 | | [PKBody(Some(n1)), PKBody(Some(n2))]: n1 == n2; 110 | case _: false; 111 | } 112 | } 113 | 114 | public function byName(name:String):Array { 115 | return params.filter(function(p) return switch p.access { 116 | case Plain(n) | Drill({name: n}, _): n == name; 117 | }); 118 | } 119 | 120 | public function get(access:ArgAccess):Option { 121 | for(p in params) 122 | switch [access, p.access] { 123 | case [Plain(n1), Plain(n2)] if(n1 == n2): return Some(p); 124 | case [Drill({name: n1}, f1), Drill({name: n2}, f2)] if(n1 == n2 && f1 == f2): return Some(p); 125 | case _: 126 | } 127 | return None; 128 | } 129 | 130 | static function reserved(name:String) { 131 | return switch name { 132 | case 'user' | 'query' | 'header' | 'body': true; 133 | case _: false; 134 | } 135 | } 136 | 137 | public static function getParamName(field:ClassField) { 138 | return switch field.meta.extract(':name') { 139 | case [{params: [macro $v{(name:String)}]}]: name; 140 | case [{params: _, pos: pos}]: pos.error('@:name meta should contain exactly one string literal parameter'); 141 | case _: field.name; 142 | } 143 | } 144 | } 145 | 146 | typedef ParamMapping = { 147 | source:Expr, // original expr specified in `@:params` 148 | access:ArgAccess, 149 | kind:ParamKind, 150 | } 151 | 152 | enum ParamKind { 153 | PKQuery(name:String); 154 | PKHeader(name:String); 155 | PKBody(name:Option); // None denotes the entire body 156 | } 157 | #end -------------------------------------------------------------------------------- /src/tink/web/routing/Context.hx: -------------------------------------------------------------------------------- 1 | package tink.web.routing; 2 | 3 | import haxe.io.Bytes; 4 | import tink.Chunk; 5 | import tink.http.Header; 6 | import tink.http.Request; 7 | import tink.http.StructuredBody; 8 | import tink.querystring.Pairs; 9 | import tink.streams.Stream; 10 | import tink.url.Portion; 11 | import tink.url.Query; 12 | import tink.web.forms.FormField; 13 | 14 | using tink.io.Source; 15 | using StringTools; 16 | using tink.CoreApi; 17 | 18 | abstract Path(Array) from Array to Array { 19 | @:to public function toString():String 20 | return '/'+[for (p in this) (p:String)].join('/'); 21 | } 22 | 23 | class Context { 24 | 25 | var request:IncomingRequest; 26 | 27 | public var depth(default, null):Int; 28 | public var parent(default, null):Context; 29 | 30 | var parts:Array; 31 | var params:Map; 32 | 33 | public var header(get, never):IncomingRequestHeader; 34 | inline function get_header() 35 | return request.header; 36 | 37 | public var accepts(default, null):String->Bool; 38 | 39 | 40 | public function allRaw():Promise 41 | return rawBody.all(); 42 | 43 | public var rawBody(get, never):RealSource; 44 | inline function get_rawBody():RealSource 45 | return switch this.request.body { 46 | case Plain(s): s; 47 | default: new Error(NotImplemented, 'not implemented');//TODO: implement 48 | } 49 | 50 | public function headers():Pairs { 51 | return [for (f in header) new Named(f.name, f.value)]; 52 | } 53 | 54 | static function toCamelCase(header:HeaderName) {//TODO: should go some place else 55 | var header:String = header; 56 | var ret = new StringBuf(), 57 | pos = 0, 58 | max = header.length; 59 | 60 | while (pos < max) { 61 | switch header.fastCodeAt(pos++) { 62 | case '-'.code: 63 | if (pos < max) 64 | ret.add(header.charAt(pos++).toLowerCase()); 65 | case v: 66 | ret.addChar(v); 67 | } 68 | } 69 | 70 | return ret.toString(); 71 | } 72 | 73 | public function parse():Promise>> 74 | return switch this.request.body { 75 | case Parsed(parts): parts; 76 | case Plain(src): 77 | function parseForm() 78 | return 79 | src.all().next( 80 | function (chunk):Array> return [for (part in (chunk.toString() : Query)) new Named(part.name, Value(part.value))]); 81 | #if tink_multipart 82 | switch tink.multipart.Multipart.check(this.request) { 83 | case Some(result): 84 | return Future.async(function(cb:Callback>, Error>>) { 85 | var contentType = result.a; 86 | var body = result.b.idealize(function(e) { 87 | cb.invoke(Failure(e)); 88 | return Source.EMPTY; 89 | }); 90 | var parser:tink.multipart.Parser = // TODO: make this configurable 91 | #if busboy 92 | new tink.multipart.parsers.BusboyParser(contentType.toString()); 93 | #else 94 | new tink.multipart.parsers.TinkParser(contentType.extensions['boundary']); 95 | #end 96 | parser.parse(body).collect().handle(cb); 97 | }); 98 | case None: 99 | parseForm(); 100 | } 101 | #else 102 | parseForm(); 103 | #end 104 | } 105 | 106 | public var pathLength(get, never):Int; 107 | inline function get_pathLength() 108 | return this.parts.length - this.depth; 109 | 110 | public function getPrefix():Path 111 | return this.parts.slice(0, this.depth); 112 | 113 | public function getPath():Path 114 | return this.parts.slice(this.depth); 115 | 116 | public function hasParam(name:String) 117 | return this.params.exists(name); 118 | 119 | public function part(index:Int):Stringly 120 | return if(this.depth + index >= this.parts.length) '' else this.parts[this.depth + index]; 121 | 122 | public function param(name:String):Stringly 123 | return this.params[name]; 124 | 125 | function new(parent, accepts, request, depth, parts, params) { 126 | this.parent = parent; 127 | this.accepts = accepts; 128 | this.request = request; 129 | this.depth = depth; 130 | this.parts = parts; 131 | this.params = params; 132 | } 133 | 134 | public function sub(descend:Int):Context 135 | return new Context(this, this.accepts, this.request, this.depth + descend, this.parts, this.params); 136 | 137 | static public function ofRequest(request:IncomingRequest) 138 | return new Context( 139 | null, 140 | parseAcceptHeader(request.header), 141 | request, 142 | 0, 143 | request.header.url.path.parts(), 144 | request.header.url.query 145 | ); 146 | 147 | static public function authed>(request:IncomingRequest, getSession:IncomingRequestHeader->S) 148 | return new AuthedContext( 149 | null, 150 | parseAcceptHeader(request.header), 151 | request, 152 | 0, 153 | request.header.url.path.parts(), 154 | request.header.url.query, 155 | getSession.bind(request.header) 156 | ); 157 | 158 | static function parseAcceptHeader(h:Header) 159 | return switch h.get(ACCEPT) { 160 | case []: acceptsAll; 161 | case values: 162 | var accepted = [for (v in values) for (part in v.parse()) part.value => true]; 163 | if (accepted['*/*']) acceptsAll; 164 | else function (t) return accepted.exists(t); 165 | } 166 | 167 | static function acceptsAll(s:String) return true; 168 | 169 | } 170 | 171 | @:allow(tink.web.routing) 172 | class AuthedContext> extends Context { 173 | 174 | public var session(default, null):Lazy; 175 | public var user(default, null):Lazy>>; 176 | 177 | function new(parent, accepts, request, depth, parts, params, session, ?user) { 178 | 179 | this.session = session; 180 | this.user = switch user { 181 | case null: 182 | session.map(function (s) return s.getUser()); 183 | case v: v; 184 | } 185 | 186 | super(parent, accepts, request, depth, parts, params); 187 | } 188 | 189 | override public function sub(descend:Int):AuthedContext { 190 | return new AuthedContext(this, accepts, request, depth + descend, parts, params, session, user); 191 | } 192 | } 193 | 194 | abstract RequestReader(Context->Promise) from Context->Promise { 195 | 196 | @:from static function ofStringReader(read:String->Outcome):RequestReader 197 | return 198 | function (ctx:Context):Promise 199 | return 200 | ctx.allRaw().next(function (body) return read(body.toString())); 201 | 202 | @:from static function ofSafeStringReader(read:String->A):RequestReader 203 | return ofStringReader(function (s) return Success(read(s))); 204 | 205 | } 206 | -------------------------------------------------------------------------------- /tests/Fake.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import haxe.ds.Option; 4 | import haxe.io.Bytes; 5 | import tink.core.Either; 6 | import tink.http.Response; 7 | import tink.web.forms.FormFile; 8 | import tink.web.routing.Response; 9 | import tink.web.routing.Context; 10 | 11 | using tink.io.Source; 12 | 13 | typedef Complex = { 14 | foo: Array<{ ?x: String, ?y:Int, z:Float }> 15 | } 16 | 17 | 18 | class Fake { 19 | 20 | public function new() {} 21 | @:sub('/recurse/$id') public function recurse(id:String) return new Fake(); 22 | 23 | @:get public function anonOrNot(user:Option<{ id: Int }>) 24 | return { 25 | id: switch user { 26 | case Some(v): v.id; 27 | case None: -1; 28 | } 29 | } 30 | 31 | @:get public function withUser(user: { admin: Bool } ) 32 | return { admin: user.admin }; 33 | 34 | @:restrict(false) @:get public function noaccess() return 'nope'; 35 | 36 | @:get public var yo(default, null):String = 'yo'; 37 | 38 | @:html(function (u) return 'Yo') 39 | @:params(bar in query) 40 | @:get public function complex(query: Complex, ?bar:String) 41 | return query; 42 | 43 | @:delete('/remove/$id') public function delete(id:Int) 44 | return { deleted: true }; 45 | 46 | @:params(bar.foo in query) 47 | @:get public function temp(bar:{foo:String}) 48 | return bar; 49 | 50 | @:post public function streaming(body:RealSource) 51 | return body; 52 | 53 | @:post public function buffered(body:Bytes) 54 | return body; 55 | 56 | @:post public function textual(body:String) 57 | return body; 58 | 59 | @:get('/queryParam?param=$value') 60 | public function queryParam(value:String) 61 | return { value: value }; 62 | 63 | @:produces('foo') 64 | @:post public function streamingFoo(body:RealSource) 65 | return body; 66 | @:produces('foo') 67 | @:post public function bufferedFoo(body:Bytes) 68 | return body; 69 | @:produces('foo') 70 | @:post public function textualFoo(body:String) 71 | return body; 72 | 73 | @:get public function promiseString():Promise 74 | return 'foo'; 75 | 76 | @:get public function promiseBytes():Promise 77 | return Bytes.ofString('foo'); 78 | 79 | @:statusCode(201) 80 | @:post public function statusCode() 81 | return 'Done'; 82 | 83 | @:header('tink', 'web') 84 | @:header('tink_web', 'foobar') 85 | @:post public function responseHeader() 86 | return 'Done'; 87 | 88 | @:header('tink', 'web') 89 | @:header('tink_web', 'foobar') 90 | @:get public function issue114():Noise 91 | return Noise; 92 | 93 | @:header('tink', 'web') 94 | @:header('tink_web', 'foobar') 95 | @:statusCode(418) 96 | @:get public function issue114_2():Promise 97 | return Promise.NOISE; 98 | 99 | @:params(error in query) 100 | @:get public function noise(?error:Bool):Promise 101 | return error ? new Error('Errored') : Promise.NOISE; 102 | 103 | @:statusCode(307) 104 | @:get('/statusCode') public function redirectStatusCode() 105 | return tink.Url.parse('https://example.com'); 106 | 107 | @:get public function headers(header: { var accept:String; @:name('x-bar') var bar:String; } ) { 108 | return header; 109 | } 110 | 111 | @:get public function typed() { 112 | return new tink.web.Response( 113 | new tink.http.Response.ResponseHeader(200, 'OK', []), 114 | {message: 'This is typed!'} 115 | ); 116 | } 117 | 118 | @:consumes('application/json') 119 | @:post public function enm(body:{ field: Either }) 120 | return 'ok'; 121 | 122 | @:consumes('application/json') 123 | @:post public function array(body:Array) 124 | return body; 125 | 126 | @:consumes('application/json') 127 | @:post public function int(body:Int) 128 | return body; 129 | 130 | @:params(v in query) 131 | @:get public function enumAbstractStringInQuery(v:EStr):EStr 132 | return v; 133 | 134 | @:params(v in query) 135 | @:get public function enumAbstractIntInQuery(v:EInt):EInt 136 | return v; 137 | 138 | @:params(notfoo = query['foo']) 139 | @:params(bar.baz = query['baz']) 140 | @:get public function alias(notfoo:String, bar:{baz:String}, ctx:Context):{foo:String, baz:String, query:String} { 141 | return { 142 | foo: notfoo, 143 | baz: bar.baz, 144 | query: @:privateAccess ctx.request.header.url.query, 145 | } 146 | } 147 | 148 | @:params(obj.foo = query['foo']) 149 | @:params(obj.bar = header['X-Bar']) 150 | @:params(obj.baz = body['baz']) 151 | @:get public function merged(obj:{foo:String, bar:String,baz:String}):{foo:String, bar:String, baz:String} { 152 | return obj; 153 | } 154 | 155 | @:get('enum_abs_str/$v') public function enumAbstractStringInPath(v:EStr):EStr 156 | return v; 157 | 158 | @:get('enum_abs_int/$v') public function enumAbstractIntInPath(v:EInt):EInt 159 | return v; 160 | 161 | @:get('/flag/$flag') 162 | @:get('/flag/') 163 | public function flag(?flag:Bool = true) 164 | return { flag: flag }; 165 | 166 | @:get('/count/$number') 167 | @:get('/count/') 168 | public function count(?number:Int = 123) 169 | return { number: number }; 170 | 171 | @:restrict(true) 172 | @:html(function (o) return '

Hello ${o.hello}

') 173 | @:get('/$who') 174 | @:get('/') 175 | public function hello(?who:String = 'world') { 176 | return { 177 | hello: who 178 | }; 179 | } 180 | 181 | @:post 182 | public function upload(body: { datafile1: FormFile } ) { 183 | return body.datafile1.read().all() 184 | .next(function (chunk) return { 185 | name: body.datafile1.fileName, 186 | content: chunk.toString(), 187 | }); 188 | } 189 | 190 | @:post public function post(body: { foo:String, bar: Int }) 191 | return body; 192 | 193 | @:post public function optional(body: { foo:String, ?bar: Int }) 194 | return {bar:body.bar}; 195 | 196 | 197 | 198 | @:post public function nullableQuery1(?query: { foo:String }) 199 | return {foo: query == null ? null : query.foo}; 200 | 201 | @:params(nullableValue = query) 202 | @:post public function nullableQuery2(?nullableValue: { foo:String }) 203 | return {foo: nullableValue == null ? null : nullableValue.foo}; 204 | 205 | @:restrict(user.id == a) 206 | @:sub('/sub/$a/$b') 207 | public function sub(a, b) { 208 | return new FakeSub(a, b); 209 | } 210 | 211 | } 212 | 213 | @:restrict(this.b > user.id) 214 | class FakeSub { 215 | 216 | var a:Int; 217 | var b:Float; 218 | 219 | public function new(a, b) { 220 | this.a = a; 221 | this.b = b; 222 | } 223 | 224 | @:restrict(user.admin) 225 | @:get('/test/$blargh') 226 | public function foo(blargh:String, /*path:Array,*/ query: { c:String, d:String } ) { 227 | return haxe.Json.stringify({ 228 | a: a, 229 | b: b, 230 | c: query.c, 231 | d: query.d, 232 | blargh: blargh, 233 | //path: path, 234 | }); 235 | } 236 | 237 | @:get public function whatever() 238 | return { foo: 'bar' } 239 | 240 | } 241 | 242 | @:enum 243 | abstract EStr(String) { 244 | var A = 'a'; 245 | var B = 'b'; 246 | 247 | @:to 248 | public inline function toStringly():tink.Stringly return this; 249 | } 250 | 251 | @:enum 252 | abstract EInt(Int) { 253 | var A = 1; 254 | var B = 2; 255 | 256 | @:to 257 | public inline function toStringly():tink.Stringly return this; 258 | } 259 | -------------------------------------------------------------------------------- /src/tink/web/macros/Route.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.web.macros.Arguments; 5 | import tink.web.macros.Parameters; 6 | 7 | class Route { 8 | 9 | public var field(default, null):ClassField; 10 | public var kind(default, null):RouteKind; 11 | public var signature(default, null):Signature; 12 | public var consumes(default, null):Array; 13 | public var produces(default, null):Array; 14 | public var restricts(default, null):Array; 15 | public var payload(get, null):Payload; 16 | 17 | static var id:Int = 0; // use global id counter to dodge https://github.com/haxetink/tink_macro/issues/25, but renders BuildCache useless 18 | 19 | public function new(f, consumes, produces, type) { 20 | field = f; 21 | signature = new Signature(f, type); 22 | switch [hasCall(f), hasSub(f)] { 23 | case [false, false]: 24 | f.pos.error('No routes on this field'); // should not happen actually 25 | case [true, false]: 26 | kind = KCall({ 27 | statusCode: 28 | switch field.meta.extract(':statusCode') { 29 | case []: 30 | macro 200; 31 | case [{params: [v]}]: 32 | v; 33 | case [v]: 34 | v.pos.error('@:statusCode must have one argument exactly'); 35 | case v: 36 | v[1].pos.error('Cannot have multiple @:statusCode directives'); 37 | }, 38 | headers: 39 | [for(meta in field.meta.extract(':header')) 40 | switch meta { 41 | case {params: [name, value]}: 42 | new NamedWith(name, value); 43 | case _: 44 | meta.pos.error('@:header must have two arguments exactly'); 45 | } 46 | ], 47 | html: 48 | switch field.meta.extract(':html') { 49 | case []: 50 | None; 51 | case [{ pos: pos, params: [v] }]: 52 | Some(v); 53 | case [v]: 54 | v.pos.error('@:html must have one argument exactly'); 55 | case v: 56 | v[1].pos.error('Cannot have multiple @:html directives'); 57 | } 58 | }); 59 | case [false, true]: 60 | kind = KSub; 61 | case [true, true]: 62 | f.pos.error('Cannot have both routing and subrouting on the same field'); 63 | } 64 | this.consumes = MimeType.fromMeta(f.meta, 'consumes', consumes); 65 | this.produces = MimeType.fromMeta(f.meta, 'produces', produces); 66 | 67 | restricts = getRestricts([field.meta]); 68 | } 69 | 70 | 71 | function get_payload():Payload { 72 | if(payload == null) { 73 | var arr = []; 74 | // var id = 0; // see https://github.com/haxetink/tink_macro/issues/25 75 | for(arg in signature.args) { 76 | switch arg.kind { 77 | case AKSingle(optional, ATParam(kind)): 78 | arr.push({id: id++, access: Plain(arg.name), type: arg.type, optional: optional, kind: kind}); 79 | case AKObject(optional, fields): 80 | for(field in fields) 81 | switch field.target { 82 | case ATParam(kind): 83 | arr.push({id: id++, access: Drill({name: arg.name, nullable: arg.optional}, field.name), type: field.type, optional: optional || field.optional, kind: kind}); 84 | case _: // skip 85 | } 86 | case _: // skip 87 | } 88 | } 89 | payload = new Payload(field.pos, arr); 90 | } 91 | return payload; 92 | } 93 | 94 | public static function hasWebMeta(f:ClassField) { 95 | return hasSub(f) || hasCall(f); 96 | } 97 | 98 | public static function hasCall(f:ClassField) { 99 | for (m in Paths.metas.keys()) 100 | if (f.meta.has(m)) return true; 101 | return false; 102 | } 103 | 104 | public static function hasSub(f:ClassField) { 105 | return f.meta.has(':sub'); 106 | } 107 | 108 | // TODO: move this to somewhere 109 | public static function getRestricts(meta:Array):Array { 110 | return [for(meta in meta) for (m in meta.extract(':restrict')) 111 | switch m.params { 112 | case [v]: 113 | v; 114 | case _: 115 | m.pos.error('@:restrict must have one parameter'); 116 | } 117 | ]; 118 | } 119 | } 120 | 121 | enum RouteKind { 122 | KSub; 123 | KCall(call:Call); 124 | } 125 | 126 | typedef Call = { 127 | statusCode:Expr, 128 | headers:Array>, 129 | html:Option, 130 | } 131 | 132 | enum RoutePayload { 133 | Empty; 134 | Mixed(separate:Array, compound:Array>, sum:ComplexType); 135 | SingleCompound(name:String, type:Type); 136 | } 137 | 138 | 139 | abstract Payload(Pair>) { 140 | public inline function new(pos, arr) this = new Pair(pos, arr); 141 | 142 | public function toTypes() { 143 | var flat = null; 144 | var body:Array = []; 145 | var query:Array = []; 146 | var header:Array = []; 147 | 148 | var pos = this.a; 149 | var arr = this.b; 150 | 151 | for(item in arr) { 152 | function add(to:Array, name:String) { 153 | var meta = [ 154 | {name: ':json', params: [macro $v{name}], pos: pos}, 155 | {name: ':formField', params: [macro $v{name}], pos: pos}, 156 | ]; 157 | 158 | if(item.optional) 159 | meta.push({name: ':optional', params: [], pos: pos}); 160 | 161 | to.push({ 162 | name: '_${item.id}', 163 | access: [], 164 | meta: meta, 165 | kind: FVar(item.type.toComplex(), null), 166 | pos: pos, 167 | }); 168 | } 169 | 170 | switch item.kind { 171 | case PKBody(None): 172 | if(body.length > 0) pos.error('Body appeared more than once'); 173 | flat = new Pair(item.access, item.type); 174 | case PKBody(Some(name)): 175 | if(flat != null) pos.error('Body appeared more than once'); 176 | add(body, name); 177 | case PKQuery(name): 178 | add(query, name); 179 | case PKHeader(name): 180 | add(header, name); 181 | } 182 | } 183 | 184 | return { 185 | body: flat != null ? Flat(flat.a, flat.b) : Object(TAnonymous(body)), 186 | query: TAnonymous(query), 187 | header: TAnonymous(header), 188 | } 189 | } 190 | 191 | public function toObjectDecls() { 192 | var body = []; var bodyObj = EObjectDecl(body); 193 | var query = []; var queryObj = EObjectDecl(query); 194 | var header = []; var headerObj = EObjectDecl(header); 195 | 196 | var pos = this.a; 197 | var arr = this.b; 198 | 199 | for(item in arr) { 200 | function add(to, expr) { 201 | EObjectDecl(to); // type inference 202 | to.push({field: '_${item.id}', expr: expr}); 203 | } 204 | switch [item.access, item.kind] { 205 | case [_, PKBody(None)]: 206 | case [Plain(name), PKBody(Some(_))]: 207 | add(body, macro $i{name}); 208 | case [Plain(name), PKQuery(_)]: 209 | add(query, macro $i{name}); 210 | case [Plain(name), PKHeader(_)]: 211 | add(header, macro $i{name}); 212 | case [Drill({name: name, nullable: nullable}, field), PKBody(Some(_))]: 213 | final access = macro $p{[name, field]}; 214 | add(body, nullable ? macro ($i{name} == null ? null : $access) : access); 215 | case [Drill({name: name, nullable: nullable}, field), PKQuery(_)]: 216 | final access = macro $p{[name, field]}; 217 | add(query, nullable ? macro ($i{name} == null ? null : $access) : access); 218 | case [Drill({name: name, nullable: nullable}, field), PKHeader(_)]: 219 | final access = macro $p{[name, field]}; 220 | add(header, nullable ? macro ($i{name} == null ? null : $access) : access); 221 | } 222 | } 223 | 224 | return { 225 | body: bodyObj, 226 | query: queryObj, 227 | header: headerObj, 228 | } 229 | } 230 | 231 | public inline function iterator() return this.b.iterator(); 232 | } 233 | 234 | enum BodyType { 235 | Flat(access:ArgAccess, type:Type); 236 | Object(type:ComplexType); 237 | } 238 | #end -------------------------------------------------------------------------------- /src/tink/web/proxy/Remote.hx: -------------------------------------------------------------------------------- 1 | package tink.web.proxy; 2 | 3 | import haxe.io.Bytes; 4 | import tink.url.*; 5 | import tink.querystring.*; 6 | import tink.http.*; 7 | import tink.http.Header; 8 | import tink.http.Request; 9 | import tink.http.Response; 10 | 11 | #if macro 12 | import haxe.macro.Context; 13 | import haxe.macro.Expr; 14 | using tink.MacroApi; 15 | #end 16 | 17 | using tink.io.Source; 18 | using tink.CoreApi; 19 | 20 | #if !macro 21 | @:genericBuild(tink.web.macros.Proxify.remote()) 22 | #end 23 | class Remote { } 24 | 25 | private typedef RemoteEndpointData = { 26 | >Sub, 27 | host:Host, 28 | scheme:Scheme, 29 | ?pathSuffix:String, 30 | } 31 | 32 | private abstract Scheme(String) to String { 33 | inline function new(s) this = s; 34 | @:from static function fromString(s:String) 35 | return new Scheme(switch s { 36 | case null: ''; 37 | case v: 38 | switch v.indexOf(':') { 39 | case -1: v + ':'; 40 | case i: v.substr(0, i + 1); 41 | } 42 | }); 43 | } 44 | 45 | private typedef Sub = { 46 | ?headers: Headers, 47 | ?path: PathFragments, 48 | ?query: QueryParams 49 | } 50 | 51 | @:forward(scheme) 52 | abstract RemoteEndpoint(RemoteEndpointData) from RemoteEndpointData { 53 | 54 | public var host(get, never):Host; 55 | inline function get_host() 56 | return this.host; 57 | 58 | public var pathSuffix(get, never):String; 59 | inline function get_pathSuffix() 60 | return this.pathSuffix == null ? '' : this.pathSuffix; 61 | 62 | public var headers(get, never):Iterable; 63 | inline function get_headers() 64 | return switch this.headers { 65 | case null: NO_HEADERS; 66 | case v: v; 67 | } 68 | 69 | static var NO_HEADERS = []; 70 | 71 | public var path(get, never):Iterable; 72 | inline function get_path() 73 | return switch this.path { 74 | case null: NO_PATH; 75 | case v: v; 76 | } 77 | 78 | static var NO_PATH = []; 79 | 80 | public var query(get, never):QueryParams; 81 | inline function get_query() 82 | return this.query; 83 | 84 | public function new(host, ?pathSuffix, ?scheme:String) 85 | this = { 86 | host: host, 87 | pathSuffix: pathSuffix, 88 | scheme: scheme, 89 | }; 90 | 91 | static function concat(a:Array, b:Array) 92 | return switch [a, b] { 93 | case [null, r] | [r, null]: r; 94 | default: a.concat(b); 95 | } 96 | 97 | public function sub(options:Sub):RemoteEndpoint 98 | return { 99 | host: this.host, 100 | scheme: this.scheme, 101 | pathSuffix: this.pathSuffix, 102 | headers: concat(this.headers, options.headers), 103 | query: concat(this.query, options.query), 104 | path: concat(this.path, options.path), 105 | } 106 | 107 | function uri() 108 | return '/' + (switch this.path { 109 | case null: ''; 110 | case v: Path.normalize(v.join('/')); 111 | }) + pathSuffix + this.query; 112 | 113 | public function request
(client:Client, method, body, reader:ResponseReader):Promise 114 | return 115 | client.request( 116 | new OutgoingRequest( 117 | new OutgoingRequestHeader(method, '${this.scheme}//${this.host}' + uri(), this.headers), 118 | body 119 | ) 120 | ).next(function (response) return reader.withHeader(response.header)(response.body)); 121 | 122 | @:from public static inline function fromHost(host:Host):RemoteEndpoint 123 | return new RemoteEndpoint(host); 124 | 125 | @:from static public function ofUrl(u:Url) { 126 | return new RemoteEndpoint(u.host, u.hash, u.scheme).sub({ 127 | headers: switch u.auth { 128 | case null: null; 129 | case v: [new HeaderField(AUTHORIZATION, HeaderValue.basicAuth(v.user, v.password))]; 130 | }, 131 | path: u.path.parts(), 132 | query: [for (p in u.query) new NamedWith((p.name:Portion), p.value)], 133 | }); 134 | } 135 | 136 | @:from static public macro function ofString(e:ExprOf) 137 | return switch e.getString() { 138 | default: 139 | return macro @:pos(e.pos) tink.web.proxy.Remote.RemoteEndpoint.ofUrl($e); 140 | case Success(s): 141 | 142 | var url = tink.Url.parse(s, function (v) { 143 | e.pos.error(v); 144 | }); 145 | 146 | function interp(s:String) 147 | return 148 | if (s == null) macro null; 149 | else haxe.macro.MacroStringTools.formatString(s, e.pos);//todo: try to adjust position 150 | 151 | var fields = new Array(), 152 | ret = @:pos(e.pos) macro new tink.web.proxy.Remote.RemoteEndpoint(new tink.url.Host(${interp(url.host)}), ${interp(url.hash)}, ${interp(url.scheme)}); 153 | 154 | function add(field, expr) 155 | fields.push({ field: field, expr: expr }); 156 | 157 | switch url.auth { 158 | case null: 159 | case v: 160 | add('headers', macro @:pos(e.pos) [ 161 | new tink.http.Header.HeaderField( 162 | AUTHORIZATION, 163 | tink.http.Header.HeaderValue.basicAuth(${interp(v.user)}, ${interp(v.password)}) 164 | ) 165 | ]); 166 | } 167 | 168 | switch url.path { 169 | case null: 170 | case v: 171 | add('path', [for (p in v.parts()) macro new tink.url.Portion(${interp(p.raw)})].toArray()); 172 | } 173 | 174 | switch url.query { 175 | case null: 176 | case v: 177 | add('query', [for (p in v) macro new tink.core.Named.NamedWith( 178 | new tink.url.Portion(${interp((p.name:Portion).raw)}), 179 | new tink.url.Portion(${interp(p.value.raw)}) 180 | )].toArray()); 181 | } 182 | 183 | if (fields.length != null) 184 | ret = macro @:pos(e.pos) $ret.sub(${EObjectDecl(fields).at(e.pos)}); 185 | 186 | return ret; 187 | } 188 | 189 | } 190 | 191 | abstract ResponseReader(ResponseHeader->RealSource->Promise) from ResponseHeader->RealSource->Promise { 192 | 193 | public function withHeader(header) 194 | return this.bind(header, _); 195 | 196 | @:from static function ofStringReader(read:String->Outcome):ResponseReader 197 | return 198 | function (header:ResponseHeader, body:RealSource):Promise 199 | return 200 | body.all().next(function (chunk:Chunk) return 201 | if (header.statusCode >= 400) 202 | Failure(Error.withData(header.statusCode, header.reason, chunk.toString())); 203 | else 204 | read(chunk.toString()) 205 | ); 206 | 207 | @:from static function ofSafeStringReader(read:String->A):ResponseReader 208 | return ofStringReader(function (s) return Success(read(s))); 209 | 210 | } 211 | 212 | private typedef Headers = Array; 213 | private typedef PathFragments = Array; 214 | 215 | @:forward 216 | abstract QueryParams(Array>) to Array> from Array> { 217 | 218 | public inline function new() 219 | this = []; 220 | 221 | public inline function add(name:Stringly, value:Stringly):QueryParams { 222 | this.push(new NamedWith((name:Portion), (value:Portion))); 223 | return this; 224 | } 225 | 226 | @:to public inline function flush():QueryParams 227 | return this; 228 | 229 | @:to public function toString() 230 | return switch this { 231 | case null | []: ''; 232 | default: 233 | var ret = Query.build(); 234 | for (p in this) 235 | ret.add(p.name, p.value); 236 | '?$ret'; 237 | } 238 | } 239 | 240 | @:forward 241 | abstract HeaderParams(Headers) to Headers from Headers { 242 | 243 | public inline function new() 244 | this = []; 245 | 246 | public inline function add(name:HeaderName, value:HeaderValue):HeaderParams { 247 | this.push(new HeaderField(name, value)); 248 | return this; 249 | } 250 | 251 | @:to public inline function flush():HeaderParams 252 | return this; 253 | 254 | @:to public function toString() 255 | return new Header(this).toString(); 256 | } 257 | 258 | class RemoteBase { 259 | 260 | var client:tink.http.Client; 261 | var endpoint:RemoteEndpoint; 262 | 263 | public function new(client, endpoint) { 264 | this.client = client; 265 | this.endpoint = endpoint; 266 | } 267 | 268 | } 269 | -------------------------------------------------------------------------------- /tests/ProxyTest.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import deepequal.DeepEqual.compare; 4 | import tink.http.Request; 5 | import tink.http.Response; 6 | import tink.http.Client; 7 | import tink.http.Container; 8 | import tink.http.clients.*; 9 | import tink.http.containers.*; 10 | import tink.url.Host; 11 | import tink.web.proxy.Remote; 12 | import tink.unit.Assert.assert; 13 | import haxe.io.Bytes; 14 | 15 | using tink.CoreApi; 16 | 17 | @:asserts 18 | class ProxyTest { 19 | 20 | var container:LocalContainer; 21 | var client:Client; 22 | var fake:Fake; 23 | var proxy:Remote; 24 | 25 | public function new() { 26 | container = new LocalContainer(); 27 | client = new LocalContainerClient(container); 28 | fake = new Fake(); 29 | container.run(function (req:IncomingRequest) { 30 | return DispatchTest.exec(req).recover(OutgoingResponse.reportError); 31 | }); 32 | proxy = new Remote(client, new RemoteEndpoint(new Host('localhost', 80))); 33 | } 34 | 35 | public function complex() { 36 | var c:Fake.Complex = { foo: [ { z: 3, x: '5', y: 6 } ] }; 37 | return proxy.complex(c).map(function (o) return assert(compare(c, o.sure()))); 38 | } 39 | 40 | public function typed() { 41 | return proxy.typed() 42 | .next(function (o) { 43 | asserts.assert(o.header.contentType().sure().fullType == 'application/json'); 44 | asserts.assert(o.body.message == 'This is typed!'); 45 | asserts.assert((o:{message:String}).message == 'This is typed!'); 46 | return asserts.done(); 47 | }); 48 | } 49 | 50 | public function ripUserArg() { 51 | return proxy.anonOrNot() 52 | .next(function (o) return assert(o.id > -2)); 53 | } 54 | 55 | public function noise() { 56 | proxy.noise() 57 | .handle(function (o) switch o { 58 | case Success(o): 59 | asserts.assert(o == Noise); 60 | asserts.done(); 61 | case Failure(e): 62 | asserts.fail('Expected Success(Noise)'); 63 | }); 64 | return asserts; 65 | } 66 | 67 | public function noiseWithError() { 68 | proxy.noise(true) 69 | .handle(function (o) switch o { 70 | case Success(_): 71 | asserts.fail('Expected Failure(error)'); 72 | case Failure(e): 73 | asserts.assert(e.code == 500); 74 | asserts.done(); 75 | }); 76 | return asserts; 77 | } 78 | 79 | public function enumAbstractStringInQuery() { 80 | proxy.enumAbstractStringInQuery(Fake.EStr.A) 81 | .next(function (o) { 82 | asserts.assert(o == Fake.EStr.A); 83 | return Noise; 84 | }) 85 | .handle(asserts.handle); 86 | return asserts; 87 | } 88 | 89 | public function enumAbstractIntInQuery() { 90 | proxy.enumAbstractIntInQuery(Fake.EInt.A) 91 | .next(function (o) { 92 | asserts.assert(o == Fake.EInt.A); 93 | return Noise; 94 | }) 95 | .handle(asserts.handle); 96 | return asserts; 97 | } 98 | 99 | public function enumAbstractStringInPath() { 100 | proxy.enumAbstractStringInPath(Fake.EStr.A) 101 | .next(function (o) { 102 | asserts.assert(o == Fake.EStr.A); 103 | return Noise; 104 | }) 105 | .handle(asserts.handle); 106 | return asserts; 107 | } 108 | 109 | public function enumAbstractIntInPath() { 110 | proxy.enumAbstractIntInPath(Fake.EInt.A) 111 | .next(function (o) { 112 | asserts.assert(o == Fake.EInt.A); 113 | return Noise; 114 | }) 115 | .handle(asserts.handle); 116 | return asserts; 117 | } 118 | 119 | public function alias() { 120 | proxy.alias('f', {baz: 'b'}) 121 | .next(function (o) { 122 | asserts.assert(o.foo == 'f'); 123 | asserts.assert(o.baz == 'b'); 124 | asserts.assert(o.query == 'foo=f&baz=b'); 125 | return Noise; 126 | }) 127 | .handle(asserts.handle); 128 | return asserts; 129 | } 130 | 131 | public function merged() { 132 | proxy.merged({foo: 'foo', bar: 'bar', baz: 'baz'}) 133 | .next(function (o) { 134 | asserts.assert(o.foo == 'foo'); 135 | asserts.assert(o.bar == 'bar'); 136 | asserts.assert(o.baz == 'baz'); 137 | return Noise; 138 | }) 139 | .handle(asserts.handle); 140 | return asserts; 141 | } 142 | 143 | public function delete() { 144 | proxy.delete(42) 145 | .handle(o -> { 146 | asserts.assert(o.match(Success({ deleted: true }))); 147 | asserts.handle(o); 148 | }); 149 | return asserts; 150 | } 151 | 152 | public function header() { 153 | proxy.headers({accept: 'application/json', bar: 'bar'}) 154 | .next(function (o) { 155 | asserts.assert(o.accept == 'application/json'); 156 | asserts.assert(o.bar == 'bar'); 157 | return Noise; 158 | }) 159 | .handle(asserts.handle); 160 | return asserts; 161 | } 162 | 163 | public function string() { 164 | proxy.textual('foo') 165 | .next(function (o) { 166 | asserts.assert(o.header.contentType().match(Success({ fullType: 'text/plain' }))); 167 | return o.body.all(); 168 | }) 169 | .next(function(chunk) { 170 | asserts.assert(chunk.toString() == 'foo'); 171 | return Noise; 172 | }) 173 | .handle(asserts.handle); 174 | return asserts; 175 | } 176 | 177 | public function bytes() { 178 | proxy.buffered(Bytes.ofString('foo')) 179 | .next(function (o) return o.body.all()) 180 | .next(function(chunk) { 181 | asserts.assert(chunk.toString() == 'foo'); 182 | return Noise; 183 | }) 184 | .handle(asserts.handle); 185 | return asserts; 186 | } 187 | 188 | public function source() { 189 | proxy.streaming('foo') 190 | .next(function (o) return o.body.all()) 191 | .next(function(chunk) { 192 | asserts.assert(chunk.toString() == 'foo'); 193 | return Noise; 194 | }) 195 | .handle(asserts.handle); 196 | return asserts; 197 | } 198 | 199 | public function promiseString() { 200 | proxy.promiseString() 201 | .next(function (o) return o.body.all()) 202 | .next(function(chunk) { 203 | asserts.assert(chunk.toString() == 'foo'); 204 | return Noise; 205 | }) 206 | .handle(asserts.handle); 207 | return asserts; 208 | } 209 | 210 | public function promiseBytes() { 211 | proxy.promiseBytes() 212 | .next(function (o) return o.body.all()) 213 | .next(function(chunk) { 214 | asserts.assert(chunk.toString() == 'foo'); 215 | return Noise; 216 | }) 217 | .handle(asserts.handle); 218 | return asserts; 219 | } 220 | 221 | public function array() { 222 | proxy.array([1,2,3]) 223 | .next(function (o) { 224 | for(i in 0...3) asserts.assert(o[i] == i + 1); 225 | return Noise; 226 | }) 227 | .handle(asserts.handle); 228 | return asserts; 229 | } 230 | 231 | public function int() { 232 | proxy.int(1) 233 | .next(function (o) { 234 | asserts.assert(o == 1); 235 | return Noise; 236 | }) 237 | .handle(asserts.handle); 238 | return asserts; 239 | } 240 | 241 | public function nullableQuery1() { 242 | proxy.nullableQuery1() 243 | .next(function (o) { 244 | asserts.assert(o.foo == null); 245 | return Noise; 246 | }) 247 | .handle(asserts.handle); 248 | return asserts; 249 | } 250 | 251 | public function nullableQuery2() { 252 | proxy.nullableQuery2() 253 | .next(function (o) { 254 | asserts.assert(o.foo == null); 255 | return Noise; 256 | }) 257 | .handle(asserts.handle); 258 | return asserts; 259 | } 260 | 261 | public function issue79() { 262 | var remote = new tink.web.proxy.Remote(null, null); // fails 263 | return asserts.done(); 264 | } 265 | 266 | public function issue47() { 267 | var r = new tink.web.routing.Router(null); 268 | var r = new tink.web.proxy.Remote(null, null); 269 | return asserts.done(); 270 | } 271 | 272 | public function issue109() 273 | return 274 | proxy.queryParam('foobar').next( 275 | recv -> assert(recv.value == 'foobar') 276 | ); 277 | } 278 | 279 | interface Issue79Base { 280 | @:get('/') 281 | function get():Promise; 282 | } 283 | interface Issue79 extends Issue79Base<{foo:String}> {} 284 | 285 | interface Issue47 { 286 | @:post 287 | public function post(body:{issue47:String}):Promise<{var issue47(default, never):String;}>; 288 | } -------------------------------------------------------------------------------- /tests/DispatchTest.hx: -------------------------------------------------------------------------------- 1 | package; 2 | 3 | import haxe.Constraints.IMap; 4 | import haxe.PosInfos; 5 | import haxe.Timer; 6 | import haxe.io.Bytes; 7 | import tink.core.Error.ErrorCode; 8 | import tink.http.Header; 9 | import tink.http.Header.HeaderField; 10 | import tink.http.Message; 11 | import tink.http.Request; 12 | import tink.http.Response.OutgoingResponse; 13 | import tink.io.Source; 14 | import tink.web.Session; 15 | import tink.web.routing.Context; 16 | import tink.web.routing.Router; 17 | import tink.testrunner.*; 18 | import tink.unit.Assert.*; 19 | import deepequal.DeepEqual.*; 20 | import haxe.ds.Option; 21 | 22 | using tink.io.Source; 23 | using tink.CoreApi; 24 | 25 | @:asserts 26 | @:allow(tink.unit) 27 | class DispatchTest { 28 | 29 | static function loggedin(admin:Bool, id:Int = 1):Session<{ admin: Bool, id:Int }> 30 | return { 31 | getUser: function () return Some({ admin: admin, id:id }), 32 | } 33 | 34 | static var anon:Session<{ admin: Bool, id:Int }> = { getUser: function () return None }; 35 | 36 | static function logginFail():Session<{ admin: Bool, id:Int }> 37 | return { getUser: function () return new Error('whoops') }; 38 | 39 | static var f = new Fake(); 40 | 41 | public static function exec(req, ?session):Promise { 42 | 43 | if (session == null) 44 | session = loggedin(true); 45 | 46 | return 47 | new Router, Fake>(f) 48 | .route(Context.authed(req, function (_) return session)); 49 | } 50 | 51 | public function new() {} 52 | 53 | @:variant({ flag: true }, get('/flag/')) 54 | @:variant({ number: 123 }, get('/count/')) 55 | @:variant({ number: 321 }, get('/count/321')) 56 | @:variant({ hello: 'world' }, get('/')) 57 | @:variant('

Hello world

', get('/', [])) 58 | @:variant({ hello: 'haxe' }, get('/haxe')) 59 | @:variant("yo", get('/yo')) 60 | @:variant({ foo: 'f', baz: 'b', query: 'foo=f&baz=b'}, 61 | get('/alias?foo=f&baz=b')) 62 | @:variant({ foo: 'foo', bar: 'bar', baz: 'baz'}, 63 | req('/merged?foo=foo', GET, [new HeaderField('x-bar', 'bar')], '{"baz":"baz"}')) 64 | @:variant({ foo: 'hey', bar: 4 }, req('/post', POST, [new tink.http.Header.HeaderField('content-type', 'application/x-www-form-urlencoded')], 'bar=4&foo=hey')) 65 | @:variant({ foo: 'hey', bar: 4 }, req('/post', POST, [new tink.http.Header.HeaderField('content-type', 'application/json')], haxe.Json.stringify({ foo: 'hey', bar: 4 }))) 66 | @:variant('foo', req('/streaming', POST, 'foo')) 67 | @:variant('foo', req('/buffered', POST, 'foo')) 68 | @:variant('foo', req('/textual', POST, 'foo')) 69 | @:variant([1,2,3], req('/array', POST, [new tink.http.Header.HeaderField('content-type', 'application/json')], '[1,2,3]')) 70 | @:variant(1, req('/int', POST, [new tink.http.Header.HeaderField('content-type', 'application/json')], '1')) 71 | @:variant('foo', req('/promiseString', GET)) 72 | @:variant('foo', req('/promiseBytes', GET)) 73 | @:variant({ accept: 'application/json; charset=UTF-8', bar: 'bar' }, 74 | get('/headers', [new tink.http.Header.HeaderField('accept', 'application/json; charset=UTF-8'), new tink.http.Header.HeaderField('x-bar', 'bar')])) 75 | @:variant({ a: 1, b: 2, c: '3', d: '4', blargh: 'yo', /*path: ['sub', '1', '2', 'test', 'yo']*/ }, 76 | get('/sub/1/2/test/yo?c=3&d=4')) 77 | @:variant({ foo: ([ { z: .0 }, { x: 'hey', z: .1 }, { y: 4, z: .2 }, { x: 'yo', y: 5, z: .3 } ]:Array) }, 78 | get('/complex?foo[0].z=.0&foo[1].x=hey&foo[1].z=.1&foo[2].y=4&foo[2].z=.2&foo[3].x=yo&foo[3].y=5&foo[3].z=.3')) 79 | @:variant('{"bar":null}', req('/optional', POST, [], '{"foo":"baz"}')) 80 | @:variant('{"bar":null}', req('/optional', POST, [], '{"foo":"baz","bar":null}')) 81 | @:variant('{"bar":1}', req('/optional', POST, [], '{"foo":"baz","bar":1}')) 82 | public function dispatch(value:Dynamic, req, ?session) 83 | return expect(value, req, session); 84 | 85 | @:variant(UnprocessableEntity, get('/count/foo')) 86 | @:variant(UnprocessableEntity, get('/sub/1/2/test/yo')) 87 | @:variant(UnprocessableEntity, req('/post', POST, [], 'bar=4')) 88 | @:variant(UnprocessableEntity, req('/post', POST, [new tink.http.Header.HeaderField('content-type', 'application/x-www-form-urlencoded')], 'bar=bar&foo=hey')) 89 | @:variant(UnprocessableEntity, req('/post', POST, [], 'bar=5&foo=hey')) 90 | public function dispatchError(code:ErrorCode, req, ?session) 91 | return shouldFail(code, req, session); 92 | 93 | @:variant(req('/streamingFoo', POST, 'foo')) 94 | @:variant(req('/bufferedFoo', POST, 'foo')) 95 | @:variant(req('/textualFoo', POST, 'foo')) 96 | public function issue92(req) { 97 | return 98 | exec(req).next( 99 | function (o) 100 | return assert(o.header.contentType().map(function (c) return c.raw).match(Success('foo'))) 101 | ); 102 | } 103 | 104 | function multipartReq() 105 | return req('/upload', POST, [ 106 | new HeaderField('Content-Type', 'multipart/form-data; boundary=----------287032381131322'), 107 | new HeaderField('Content-Length', 514), 108 | ], 109 | '------------287032381131322\r\nContent-Disposition: form-data; name="datafile1"; filename="r.gif"\r\nContent-Type: image/gif\r\n\r\nGIF87a.............,...........D..;\r\n------------287032381131322\r\nContent-Disposition: form-data; name="datafile2"; filename="g.gif"\r\nContent-Type: image/gif\r\n\r\nGIF87a.............,...........D..;\r\n------------287032381131322\r\nContent-Disposition: form-data; name="datafile3"; filename="b.gif"\r\nContent-Type: image/gif\r\n\r\nGIF87a.............,...........D..;\r\n------------287032381131322--\r\n' 110 | ); 111 | 112 | #if tink_multipart 113 | public function multipart() { 114 | return expect({ 115 | content: 'GIF87a.............,...........D..;', 116 | name: 'r.gif', 117 | }, multipartReq()); 118 | } 119 | #else 120 | public function multipart() 121 | return shouldFail(NotAcceptable, multipartReq()); 122 | #end 123 | 124 | @:variant({ foo: 'bar' }, get('/sub/1/2/whatever') ) 125 | @:variant({ id: -1 }, get('/anonOrNot'), DispatchTest.anon ) 126 | @:variant({ id: 1 }, get('/anonOrNot') ) 127 | @:variant({ id: 4 }, get('/anonOrNot'), DispatchTest.loggedin(true, 4) ) 128 | @:variant({ admin: true }, get('/withUser') ) 129 | @:variant({ admin: false }, get('/withUser'), DispatchTest.loggedin(false, 2) ) 130 | public function auth(value:Dynamic, req, ?session) 131 | return expect(value, req, session); 132 | 133 | @:variant(Unauthorized, get('/withUser'), DispatchTest.anon) 134 | @:variant(Unauthorized, get('/'), DispatchTest.anon) 135 | @:variant(Unauthorized, get('/haxe'), DispatchTest.anon) 136 | @:variant(Forbidden, get('/noaccess') ) 137 | @:variant(Forbidden, get('/sub/2/2/') ) 138 | @:variant(Forbidden, get('/sub/1/1/whatever') ) 139 | public function authError(code:ErrorCode, req, ?session) 140 | return shouldFail(code, req, session); 141 | 142 | 143 | static function expect(value:Dynamic, req, ?session, ?pos:PosInfos) { 144 | return exec(req, session).next(function (o):Promise 145 | return if (o.header.statusCode != 200) 146 | new Assertion(false, 'Request to ${req.header.url} failed because ${o.header.reason} (${o.header.statusCode.toInt()})'); 147 | else 148 | o.body.all().next(function (b) 149 | return if (Std.is(value, String)) 150 | assert(compare(value, b.toString(), pos), null, pos) 151 | else 152 | assert(compare(value, haxe.Json.parse(b.toString()), pos), null, pos) 153 | ) 154 | ); 155 | } 156 | 157 | static function shouldFail(code, req, ?session, ?pos:PosInfos) { 158 | return exec(req, session) 159 | .map(function(o) return switch o { 160 | case Success(_): new Assertion(false, 'Expected Failure but got Success', pos); 161 | case Failure(e): assert(e.code == code, null, pos); 162 | }); 163 | } 164 | 165 | } -------------------------------------------------------------------------------- /src/tink/web/macros/Proxify.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.macro.BuildCache; 5 | import tink.http.Method; 6 | import tink.url.Portion; 7 | import tink.web.macros.Paths; 8 | 9 | class Proxify { 10 | static function makeEndpoint(from:Path, route:Route, ?headers):Expr { 11 | if (headers == null) 12 | headers = []; 13 | 14 | var sig = route.signature; 15 | 16 | function val(p:PathPart) 17 | return switch p { 18 | case PCapture(Plain(name)): macro (($i{name} : tink.Stringly) : tink.url.Portion); 19 | case PCapture(Drill({name: name}, field)): throw 'TODO'; 20 | case PConst(s): macro $s; 21 | } 22 | 23 | var payload = route.payload; 24 | var types = payload.toTypes(); 25 | var decls = payload.toObjectDecls(); 26 | 27 | var path = from.parts.map(val); 28 | 29 | var ct = types.query; 30 | var query = [for (name in from.query.keys()) 31 | macro new tink.CoreApi.NamedWith(${(name:Portion)}, ${val(from.query[name])}) 32 | ].toArray(); 33 | 34 | switch types.query { 35 | case TAnonymous([]): // skip 36 | case ct: 37 | query = macro $query.concat( 38 | new tink.querystring.Builder<$ct->tink.web.proxy.Remote.QueryParams>() 39 | .stringify(${decls.query.at()}) 40 | ); 41 | } 42 | 43 | var paramHeaders = switch types.header { 44 | case TAnonymous([]): 45 | macro []; 46 | case ct: 47 | macro new tink.querystring.Builder<$ct->tink.web.proxy.Remote.HeaderParams>() 48 | .stringify(${decls.header.at()}); 49 | } 50 | 51 | return macro this.endpoint.sub({ 52 | path: $a{path}, 53 | query: $query, 54 | headers: [$a{headers}].concat($paramHeaders) 55 | }); 56 | } 57 | 58 | static function build(ctx:BuildContext):TypeDefinition { 59 | var routes = new RouteCollection(ctx.type, ['application/json'], ['application/json']); 60 | return { 61 | pos: ctx.pos, 62 | pack: ['tink', 'web'], 63 | name: ctx.name, 64 | meta: [{name: ':pure', pos: ctx.pos}], 65 | fields: [for (f in routes) { 66 | pos: f.field.pos, 67 | name: f.field.name, 68 | kind: FFun({ 69 | args: [for (arg in f.signature.args) switch arg.kind { 70 | case AKSingle(_, ATUser(_) | ATContext): continue; 71 | case _: { name: arg.name, type: arg.type.toComplex(), opt: arg.optional }; 72 | }], 73 | expr: { 74 | 75 | var call = []; 76 | 77 | switch f.kind { 78 | case KCall(c): 79 | 80 | var path = Variant.seek(f.signature.paths, f.field.pos); 81 | 82 | var method = switch path.kind { 83 | case Call(Some(m)): m; 84 | case _: GET; 85 | } 86 | 87 | var contentType = None; 88 | 89 | var payload = f.payload; 90 | 91 | var streaming = false; 92 | var body = switch payload.toTypes().body { 93 | case Flat(Plain(name), type) if(Context.getType('tink.io.Source.RealSource').unifiesWith(type)): 94 | streaming = true; 95 | macro tink.io.Source.RealSourceTools.idealize($i{name}, function(_) return tink.io.Source.EMPTY); 96 | 97 | case Flat(Plain(name), type) if(Context.getType('tink.io.Source.IdealSource').unifiesWith(type)): 98 | streaming = true; 99 | macro $i{name}; 100 | 101 | case Flat(Plain(name), type) if(Context.getType('haxe.io.Bytes').unifiesWith(type)): 102 | macro $i{name}; 103 | 104 | case Flat(Plain(name), type) if(Context.getType('String').unifiesWith(type)): 105 | macro $i{name}; 106 | 107 | case Flat(Plain(name), type): 108 | var w = MimeType.writers.get(f.consumes, type, f.field.pos); 109 | contentType = Some(w.type); 110 | var writer = w.generator; 111 | macro ${writer}($i{name}); 112 | 113 | case Flat(Drill({name: name}, field), type): 114 | throw "TODO"; 115 | 116 | case Object(TAnonymous([])): 117 | macro ''; 118 | 119 | case Object(_.toType().sure() => type): 120 | var decl = payload.toObjectDecls().body; 121 | var w = MimeType.writers.get(f.consumes, type, f.field.pos); 122 | contentType = Some(w.type); 123 | var writer = w.generator; 124 | macro ${writer}(${decl.at()}); 125 | } 126 | 127 | var response = f.signature.result.asCallResponse(); 128 | 129 | var reader = switch response { 130 | case RData(t) | ROpaque(OParsed(_, t)): 131 | Some(MimeType.readers.get(f.produces, t, f.field.pos)); 132 | default: None; 133 | } 134 | 135 | var headers = { 136 | var ret = []; 137 | 138 | function add(name, value) 139 | ret.push(macro new tink.http.Header.HeaderField($name, $value)); 140 | 141 | switch contentType { 142 | case Some(v): 143 | add(macro CONTENT_TYPE, macro $v{v}); 144 | default: 145 | } 146 | 147 | if (!streaming) 148 | add(macro CONTENT_LENGTH, macro __body__.length); 149 | 150 | switch reader { 151 | case Some(v): 152 | add(macro ACCEPT, macro $v{v.type}); 153 | default: 154 | } 155 | 156 | ret; 157 | } 158 | var endPoint = makeEndpoint(path, f, headers); 159 | var bodyCt = streaming ? macro:tink.io.IdealSource : macro:tink.Chunk; 160 | 161 | macro @:pos(f.field.pos) { 162 | var __body__:$bodyCt = $body; 163 | return $endPoint.request( 164 | this.client, 165 | cast $v{method}, 166 | __body__, 167 | ${switch response { 168 | case RNoise: 169 | macro function(header, body):tink.core.Promise { 170 | return 171 | if(header.statusCode >= 400) 172 | tink.io.Source.RealSourceTools.all(body) 173 | .next(function(chunk) return new tink.core.Error(header.statusCode, chunk)) 174 | else 175 | tink.core.Promise.NOISE; 176 | } 177 | case RData(t): 178 | reader.force().generator; 179 | 180 | case ROpaque(OParsed(res, t)): 181 | var ct = res.toComplex(); 182 | macro function(header, body) 183 | return tink.io.Source.RealSourceTools.all(body) 184 | .next(function(chunk) return ${reader.force().generator}(chunk)) 185 | .next(function(parsed):$ct return new tink.web.Response(header, parsed)); 186 | 187 | case ROpaque(ORaw(t)): 188 | if (Context.getType('tink.http.Response.IncomingResponse').unifiesWith(t)) { 189 | var ct = t.toComplex(); 190 | macro function (header, body):tink.core.Promise<$ct> return (new tink.http.Response.IncomingResponse(header, body):$ct); 191 | } 192 | else 193 | macro function (header, body) return new tink.http.Response.IncomingResponse(header, body); 194 | 195 | }} 196 | ); 197 | }; 198 | 199 | case KSub: 200 | 201 | var target = f.signature.result.asSubTarget().toComplex(), 202 | path = Variant.seek(f.signature.paths, f.field.pos); 203 | 204 | macro @:pos(f.field.pos) return new tink.web.proxy.Remote<$target>(this.client, ${makeEndpoint(path, f)}); 205 | } 206 | }, 207 | ret: null, 208 | }), 209 | access: [APublic], 210 | }], 211 | kind: TDClass('tink.web.proxy.Remote.RemoteBase'.asTypePath([TPType(ctx.type.toComplex())])), 212 | } 213 | } 214 | 215 | static function remote():Type 216 | return BuildCache.getType('tink.web.proxy.Remote', build); 217 | 218 | } 219 | #end -------------------------------------------------------------------------------- /src/tink/web/macros/Routing.hx: -------------------------------------------------------------------------------- 1 | package tink.web.macros; 2 | 3 | #if macro 4 | import tink.macro.BuildCache; 5 | import tink.web.macros.Paths; 6 | 7 | class Routing { 8 | 9 | var routes:RouteCollection; 10 | var auth:Option<{ user: Type, session: Type }>; 11 | 12 | var cases:Array = []; 13 | var fields:Array = []; 14 | 15 | var depth:Int = 0; 16 | var named:Array = []; 17 | var nameIndex:Map = new Map(); 18 | var ctx:ComplexType; 19 | 20 | function new(routes, auth) { 21 | 22 | this.routes = routes; 23 | this.auth = auth; 24 | firstPass(); 25 | ctx = 26 | switch auth { 27 | case Some(a): 28 | var user = a.user.toComplex(), 29 | session = a.session.toComplex(); 30 | macro : tink.web.routing.Context.AuthedContext<$user, $session>; 31 | case None: 32 | macro : tink.web.routing.Context; 33 | } 34 | } 35 | 36 | function firstPass() { 37 | //during the first pass we skim all routes to map out their depths and named parameters 38 | for (route in routes) { 39 | 40 | function skim(paths:Iterable) 41 | for (path in paths) { 42 | 43 | switch path.parts.length { 44 | case sup if (sup > depth): 45 | depth = sup; 46 | default: 47 | } 48 | 49 | for (name in path.query.keys()) 50 | if (!nameIndex.exists(name)) 51 | nameIndex[name] = named.push(name) - 1; 52 | } 53 | 54 | switch route.kind { 55 | case KSub: 56 | skim(route.signature.paths); 57 | case KCall(c): 58 | skim(route.signature.paths); 59 | } 60 | 61 | } 62 | 63 | } 64 | 65 | function makeCase(field:String, funcArgs:Array, path:Path):Case { 66 | if (path.deviation.missing.length > 0) 67 | path.pos.error('Route does not capture all required variables. See warnings.'); 68 | 69 | var pattern = [ 70 | switch path.kind { 71 | case Call(Some(m)): macro $i{m}; 72 | case _: IGNORE; 73 | }, 74 | ]; 75 | 76 | for (i in 0...depth * 2 + named.length * 2 + 1) 77 | pattern.push(IGNORE); 78 | 79 | for (i in 0...path.parts.length) 80 | pattern[i + 1 + depth] = macro true; 81 | 82 | if (path.rest == RNotAllowed) 83 | pattern[depth + 1 + path.parts.length] = macro false; 84 | 85 | var captured = new Map(); 86 | 87 | function part(p) 88 | return switch p { 89 | case PConst(v): 90 | macro $v{v.toString()}; 91 | case PCapture(Plain(name)): 92 | captured[name] = true; 93 | macro $i{name}; 94 | case PCapture(Drill({name: name}, field)): 95 | throw "TODO"; 96 | } 97 | 98 | for (i in 0...path.parts.length) 99 | pattern[i + 1] = part(path.parts[i]); 100 | 101 | for (name in path.query.keys()) { 102 | 103 | var index = nameIndex[name]; 104 | 105 | pattern[2 + index + depth * 2] = macro true; 106 | pattern[2 + index + depth * 2 + named.length] = part(path.query[name]); 107 | } 108 | 109 | var callArgs = [for (a in funcArgs) 110 | switch a.name { 111 | case '__depth__': 112 | macro $v{path.parts.length}; 113 | case 'user' | 'session': 114 | macro $i{a.name}; 115 | default: 116 | if (a == funcArgs[0] || captured[a.name]) 117 | macro $i{a.name} 118 | else 119 | macro null; 120 | } 121 | ]; 122 | 123 | return { 124 | values: [pattern.toArray(path.pos)], 125 | expr: macro @:pos(path.pos) this.$field($a{callArgs}), 126 | } 127 | } 128 | 129 | function switchTarget() { 130 | var ret = [macro ctx.header.method]; 131 | 132 | for (i in 0...depth) 133 | ret.push(macro ctx.part($v { i } )); 134 | 135 | for (i in 0...depth+1) 136 | ret.push(macro l > $v{i}); 137 | 138 | for (name in named) 139 | ret.push(macro ctx.hasParam($v{name})); 140 | 141 | for (name in named) 142 | ret.push(macro ctx.param($v{name})); 143 | 144 | return ret.toArray(); 145 | } 146 | 147 | function restrict(restricts:Array, e:Expr) 148 | return 149 | switch [restricts, auth] { 150 | case [[], _]: 151 | e; 152 | case [v, None]: 153 | v[0].pos.error('restriction cannot be applied because no session handling is provided'); 154 | case [restricts, Some(_)]: 155 | 156 | for (v in restricts) 157 | e = macro @:pos(v.pos) (${substituteThis(v)} : tink.core.Promise).next( 158 | function (authorized) 159 | return 160 | if (authorized) $e; 161 | else new tink.core.Error(Forbidden, 'forbidden') 162 | ); 163 | 164 | macro ctx.user.get().next(function (o) return switch o { 165 | case Some(user): 166 | $e; 167 | case None: 168 | new tink.core.Error(Unauthorized, 'not authorized'); 169 | }); 170 | } 171 | 172 | function generate(name:String, pos:Position) { 173 | 174 | secondPass(); 175 | 176 | 177 | var theSwitch = ESwitch( 178 | switchTarget(), 179 | cases, 180 | macro @:pos(pos) new tink.core.Error(NotFound, 'Not Found: [' + ctx.header.method + '] ' + ctx.header.url.pathWithQuery) 181 | ).at(pos); 182 | 183 | theSwitch = restrict(routes.restricts, theSwitch); 184 | 185 | var target = routes.type.toComplex(); 186 | 187 | var ret = 188 | macro class $name { 189 | 190 | var target:$target; 191 | 192 | public function new(target) { 193 | this.target = target; 194 | } 195 | 196 | public function route(ctx:$ctx):tink.core.Promise { 197 | var l = ctx.pathLength; 198 | return $theSwitch; 199 | } 200 | }; 201 | 202 | for (f in fields) 203 | ret.fields.push(f); 204 | 205 | ret.pack = ['tink', 'web']; 206 | 207 | return ret; 208 | } 209 | 210 | function routeMethod(route:Route) { 211 | var pos = route.field.pos, 212 | callArgs = [], 213 | funcArgs:Array = [{ 214 | name: 'ctx', 215 | type: ctx, 216 | }]; 217 | 218 | var field = route.field.name; 219 | 220 | var beforeBody = [function (e) return restrict(route.restricts, e)]; 221 | 222 | for (arg in route.signature.args) { 223 | 224 | var argExpr = arg.name.resolve(); 225 | 226 | switch arg.kind { 227 | case AKSingle(_, ATCapture): 228 | 229 | var expected = arg.type.toComplex(); 230 | var enumAbstract = switch arg.type { 231 | case TAbstract(_.get() => {module: module, name: name, type: underlying, meta: meta, impl: impl}, _) if(meta.has(':enum')): 232 | var path = ('$module.$name').split('.'); 233 | Some({ 234 | underlying: underlying, 235 | fields: impl.get().statics.get() 236 | .filter(function(s) return s.meta.has(':enum') && s.meta.has(':impl')) 237 | .map(function(s) return macro $p{path.concat([s.name])}) 238 | }); 239 | case _: 240 | None; 241 | } 242 | 243 | var parsed = switch enumAbstract { 244 | case Some({fields: fields, underlying: underlying}): 245 | var underlyingCt = underlying.toComplex(); 246 | var abstractCt = arg.type.toComplex(); 247 | ESwitch( 248 | macro (cast (s:$underlyingCt):$abstractCt), 249 | [{expr: macro cast s, values: fields}], 250 | macro throw 'Invalid value "' + s + '" for field: ' + $v{arg.name} 251 | ).at(route.field.pos); 252 | case None: 253 | macro @:pos(route.field.pos) s; 254 | } 255 | 256 | argExpr = macro @:pos(route.field.pos) switch $argExpr.parse(function (s:tink.Stringly):$expected return $parsed) { 257 | case Success(v): v; 258 | case Failure(e): return tink.core.Promise.lift(e); 259 | } 260 | 261 | funcArgs.push({ 262 | name: arg.name, 263 | type: macro : tink.Stringly, 264 | opt: arg.optional, 265 | }); 266 | 267 | // case AKObject(fields): 268 | // for(field in fields) { 269 | // switch field.target { 270 | // case ATParam(kind): 271 | // } 272 | 273 | // } 274 | // case AKSingle(ATParam(t, loc, PCompound): 275 | 276 | // if (!compound.exists(field.name)) 277 | // compound[loc] = []; 278 | 279 | // compound[loc].push(new Named(arg.name, t)); 280 | 281 | // case AParam(t, loc, PSeparate): 282 | 283 | // if (!separate.exists(loc)) 284 | // separate[loc] = []; 285 | 286 | // separate[loc].push({ 287 | // name: arg.name, 288 | // pos: route.field.pos, 289 | // kind: FVar(t.toComplex()), 290 | // }); 291 | 292 | case AKSingle(_, ATUser(u)): 293 | 294 | beforeBody.push(function (e:Expr) { 295 | 296 | switch u.getID() { 297 | case 'haxe.ds.Option': 298 | default: 299 | e = macro @:pos(e.pos) switch user { 300 | case Some(user): $e; 301 | case None: new tink.core.Error(Unauthorized, 'unauthorized'); 302 | } 303 | } 304 | 305 | return macro @:pos(e.pos) ctx.user.get().next(function (user) return $e); 306 | }); 307 | case AKSingle(_, ATContext): 308 | var name = arg.name; 309 | beforeBody.push(function (e:Expr) return macro @:pos(e.pos) { 310 | var $name = ctx; 311 | $e; 312 | }); 313 | default: 314 | 315 | // throw 'not implemented: '+arg.kind; 316 | } 317 | 318 | callArgs.push( 319 | if (arg.optional) 320 | macro switch $i{arg.name} { 321 | case null: null; 322 | default: $argExpr; 323 | } 324 | else argExpr 325 | ); 326 | } 327 | 328 | var result = macro @:pos(pos) this.target.$field; 329 | 330 | if (route.field.type.reduce().match(TFun(_, _))) 331 | result = macro @:pos(pos) $result($a{callArgs}); 332 | 333 | result = 334 | switch route.kind { 335 | case KSub: 336 | funcArgs.push({ 337 | name: '__depth__', 338 | type: macro : Int, 339 | }); 340 | 341 | var target = route.signature.result.asSubTarget().toComplex(); 342 | 343 | var router = switch auth { 344 | case None: 345 | macro @:pos(pos) new tink.web.routing.Router<$target>(__target__); 346 | case Some(_.session.toComplex() => s): 347 | macro @:pos(pos) new tink.web.routing.Router<$s, $target>(__target__); 348 | } 349 | 350 | beforeBody.push(function (e) return macro { 351 | var ctx = ctx.sub(__depth__); 352 | $e; 353 | }); 354 | 355 | macro @:pos(pos) { 356 | 357 | tink.core.Promise.lift($result) 358 | .next(function (__target__:$target) 359 | return $router.route(ctx) 360 | ); 361 | } 362 | case KCall({statusCode: statusCode, headers: headers, html: html}): 363 | var headers = [for(h in headers) macro new tink.http.Header.HeaderField(${h.name}, ${h.value})]; 364 | switch route.signature.result.asCallResponse() { 365 | case RNoise: 366 | macro @:pos(pos) tink.core.Promise.lift($result).next( 367 | function (_):tink.core.Promise { 368 | return new tink.http.Response.OutgoingResponse( 369 | new tink.http.Response.ResponseHeader( 370 | $statusCode, 371 | [new tink.http.Header.HeaderField(CONTENT_LENGTH, '0')].concat(${macro $a{headers}}) 372 | ), 373 | Chunk.EMPTY 374 | ); 375 | } 376 | ); 377 | case RData(t): 378 | var ct = t.toComplex(); 379 | var formats = []; 380 | 381 | switch html { 382 | case Some(v): 383 | formats.push( 384 | macro @:pos(v.pos) if (ctx.accepts('text/html')) 385 | return tink.core.Promise.lift(${substituteThis(v)}(__data__)).next( 386 | function (d) return tink.web.routing.Response.textual('text/html', d) 387 | ) 388 | ); 389 | case None: 390 | } 391 | 392 | for (fmt in route.produces) 393 | formats.push( 394 | macro @:pos(pos) if (ctx.accepts($v{fmt})) 395 | return tink.web.routing.Response.textual( 396 | $statusCode, 397 | $v{fmt}, 398 | ${MimeType.writers.get([fmt], t, pos).generator}(__data__), 399 | $a{headers} 400 | ) 401 | ); 402 | 403 | macro @:pos(pos) tink.core.Promise.lift($result).next( 404 | function (__data__:$ct):tink.core.Promise { 405 | $b{formats}; 406 | return new tink.core.Error(UnsupportedMediaType, 'Unsupported Media Type'); 407 | } 408 | ); 409 | 410 | case ROpaque(OParsed(res, t)): 411 | // @:statusCode and @:header is ignored here, we should probably error/warn 412 | var ct = res.toComplex(); 413 | var formats = []; 414 | 415 | switch html { 416 | case Some(v): 417 | formats.push( 418 | macro @:pos(v.pos) if (ctx.accepts('text/html')) 419 | return tink.core.Promise.lift(${substituteThis(v)}(__data__)).next( 420 | function (d) return tink.web.routing.Response.textual('text/html', d) 421 | ) 422 | ); 423 | case None: 424 | } 425 | 426 | for (fmt in route.produces) 427 | formats.push( 428 | macro @:pos(pos) if (ctx.accepts($v{fmt})) return ${{ 429 | macro new tink.http.Response.OutgoingResponse( 430 | __data__.header.concat([new tink.http.Header.HeaderField(CONTENT_TYPE, $v{fmt})]), 431 | ${MimeType.writers.get([fmt], t, pos).generator}(__data__.body) 432 | ); 433 | }}); 434 | 435 | macro @:pos(pos) tink.core.Promise.lift($result).next( 436 | function (__data__:$ct):tink.core.Promise { 437 | $b{formats}; 438 | return new tink.core.Error(UnsupportedMediaType, 'Unsupported Media Type'); 439 | } 440 | ); 441 | 442 | case ROpaque(ORaw(t)): 443 | var ct = t.toComplex(); 444 | function is(name:String) { 445 | var type = Context.getType(name); 446 | return t.unifiesWith(type) && type.unifiesWith(t); 447 | } 448 | 449 | var contentType = 450 | switch route.field.meta.extract(':produces') { 451 | case []: macro null; 452 | case [{ params: [v] }]: v; 453 | case [m], _[1] => m: 454 | m.pos.error('For opaque routes, @:produces must define exactly one constant content type'); 455 | } 456 | 457 | var e = 458 | if (is('tink.io.Source.RealSource')) 459 | macro @:pos(pos) tink.core.Promise.resolve(tink.web.routing.Response.ofRealSource($result, $contentType)); 460 | else if(is('tink.io.Source.IdealSource')) 461 | macro @:pos(pos) tink.core.Promise.resolve(tink.web.routing.Response.ofIdealSource($result, $contentType)); 462 | else { 463 | var ret = 464 | if (is('tink.Chunk') && !contentType.expr.match(EConst(CIdent('null')))) macro tink.web.routing.Response.ofChunk(v, $contentType); 465 | else macro (v : tink.web.routing.Response); 466 | 467 | macro @:pos(pos) tink.core.Promise.lift($result) 468 | .next(function (v:$ct) return $ret); 469 | } 470 | switch [statusCode, headers] { 471 | case [macro 200, []]: 472 | e; 473 | case [macro 200, _]: 474 | macro $e.next(function(res) return new tink.http.Response.OutgoingResponse( 475 | res.header.concat(${macro $a{headers}}), 476 | res.body 477 | )); 478 | case [_, []]: 479 | macro $e.next(function (res) return new tink.http.Response.OutgoingResponse( 480 | new tink.http.Response.ResponseHeader($statusCode, $statusCode, @:privateAccess res.header.fields, res.header.protocol), 481 | res.body 482 | )); 483 | case _: 484 | macro $e.next(function (res) return new tink.http.Response.OutgoingResponse( 485 | new tink.http.Response.ResponseHeader($statusCode, $statusCode, @:privateAccess res.header.fields.concat(${macro $a{headers}}), res.header.protocol), 486 | res.body 487 | )); 488 | } 489 | } 490 | } 491 | 492 | var payload = route.payload; 493 | 494 | // map params into correct arg access 495 | var objects = new Map(); 496 | var vars:Array = []; 497 | 498 | for(item in payload) { 499 | function plain(name:String, from:Expr) { 500 | var source = '_${item.id}'; 501 | vars.push({name: name, type: null, expr: macro $from.$source}); 502 | } 503 | function drill(name:String, field:String, from:Expr, root = false) { 504 | if(!objects.exists(name)) EObjectDecl(objects[name] = []); 505 | objects[name].push({ 506 | field: field, 507 | expr: root ? from : { 508 | var source = '_${item.id}'; 509 | macro $from.$source; 510 | } 511 | }); 512 | } 513 | switch [item.access, item.kind] { 514 | case [Plain(name), PKBody(None)]: 515 | // TODO: not sure yet... 516 | case [Plain(name), PKBody(Some(_))]: 517 | plain(name, macro __body__); 518 | case [Plain(name), PKQuery(_)]: 519 | plain(name, macro __query__); 520 | case [Plain(name), PKHeader(_)]: 521 | plain(name, macro __header__); 522 | case [Drill({name: name}, field), PKBody(None)]: 523 | drill(name, field, macro __body__, true); 524 | case [Drill({name: name}, field), PKBody(Some(_))]: 525 | drill(name, field, macro __body__); 526 | case [Drill({name: name}, field), PKQuery(_)]: 527 | drill(name, field, macro __query__); 528 | case [Drill({name: name}, field), PKHeader(_)]: 529 | drill(name, field, macro __header__); 530 | } 531 | } 532 | 533 | for(key in objects.keys()) { 534 | vars.push({ 535 | name: key, 536 | type: route.signature.args.find(v -> v.name == key).type.toComplex(), 537 | expr: EObjectDecl(objects[key]).at(), 538 | }); 539 | } 540 | 541 | result = macro { 542 | ${EVars(vars).at()} 543 | $result; 544 | } 545 | 546 | // parse params 547 | var types = payload.toTypes(); 548 | 549 | result = switch types.body { 550 | case Flat(Plain(name), t) if(is(t, 'haxe.io.Bytes')): 551 | macro @:pos(pos) ctx.allRaw().next(function ($name:tink.Chunk) return $result); 552 | 553 | case Flat(Plain(name), t) if(is(t, 'String')): 554 | macro @:pos(pos) ctx.allRaw().next(function ($name:tink.Chunk) {var $name = $i{name}.toString(); return $result;}); 555 | 556 | case Flat(Plain(name), t) if(is(t, 'tink.io.Source')): 557 | macro @:pos(pos) {var $name = ctx.rawBody; $result;} 558 | 559 | case Flat(Plain(name), t): 560 | for(type in route.consumes) 561 | if(type != 'application/json') 562 | route.field.pos.error('Non-object body type only supports JSON encoding. Please add @:consumes("application/json") to this route and remove any other @:consumes metadata.'); 563 | 564 | macro @:pos(pos) return ${bodyParser(t.toComplex(), route)}.next(function ($name) return $result); 565 | 566 | case Object(t = TAnonymous([])): 567 | result; 568 | 569 | case Object(t): 570 | macro @:pos(pos) return ${bodyParser(t, route)}.next(function (__body__) return $result); 571 | 572 | case kind: 573 | throw '$kind not implemented'; 574 | } 575 | 576 | for (f in beforeBody) 577 | result = f(result); 578 | 579 | result = switch types.query { 580 | case TAnonymous([]): 581 | result; 582 | 583 | case t: 584 | macro @:pos(route.field.pos) tink.core.Promise.lift(new tink.querystring.Parser<$t>().tryParse(ctx.header.url.query)) 585 | .next(function(__query__) return $result); 586 | } 587 | 588 | result = switch types.header { 589 | case TAnonymous([]): 590 | result; 591 | 592 | case t: 593 | macro @:pos(route.field.pos) tink.core.Promise.lift(new tink.querystring.Parser$t>().tryParse(ctx.headers())) 594 | .next(function(__header__) return $result); 595 | } 596 | 597 | // build and return the function 598 | 599 | var f:Function = { 600 | args: funcArgs, 601 | expr: macro @:pos(result.pos) return $result, 602 | ret: null, 603 | } 604 | 605 | fields.push({ 606 | pos: pos, 607 | name: route.field.name, 608 | kind: FFun(f), 609 | }); 610 | 611 | return funcArgs; 612 | } 613 | 614 | function secondPass() 615 | for (route in routes) { 616 | var args = routeMethod(route); 617 | for (path in route.signature.paths) 618 | cases.push(makeCase(route.field.name, args, path)); 619 | } 620 | 621 | static var IGNORE = macro _; 622 | 623 | static function substituteThis(e:Expr) 624 | return switch e { 625 | case macro this.$field: 626 | macro @:pos(e.pos) (@:privateAccess this.target.$field); 627 | case macro this: 628 | macro @:pos(e.pos) (@:privateAccess this.target); 629 | default: 630 | e.map(substituteThis); 631 | } 632 | 633 | static function is(t:Type, name:String) 634 | return t.unifiesWith(Context.getType(name)); 635 | 636 | static function bodyParser(payload:ComplexType, route:Route) { 637 | var cases:Array = [], 638 | structured = [], 639 | pos = route.field.pos; 640 | 641 | for (type in route.consumes) 642 | switch type { 643 | case 'application/x-www-form-urlencoded' #if tink_multipart | 'multipart/form-data' #end: 644 | structured.push(macro @:pos(pos) $v{type}); 645 | default: 646 | cases.push({ 647 | values: [macro $v{type}], 648 | expr: macro @:pos(pos) ctx.allRaw().next( 649 | function (b) return ${MimeType.readers.get([type], payload.toType(pos).sure(), pos).generator}(b.toString()) 650 | ) 651 | }); 652 | } 653 | 654 | switch structured { 655 | case []: 656 | case v: 657 | cases.unshift({ 658 | values: structured, 659 | expr: macro @:pos(pos) ctx.parse().next(function (pairs) 660 | return new tink.querystring.Parser$payload>().tryParse(pairs) 661 | ), 662 | }); 663 | } 664 | 665 | var contentType = macro @:pos(pos) switch ctx.header.contentType() { 666 | case Success(v): v.fullType; 667 | default: 'application/json'; 668 | } 669 | 670 | cases.push({ 671 | values: [macro invalid], 672 | expr: macro new tink.core.Error(NotAcceptable, 'Cannot process Content-Type '+invalid), 673 | }); 674 | 675 | return macro @:pos(pos) ( 676 | ${ESwitch(contentType, cases, null).at(pos)} 677 | : 678 | tink.core.Promise<$payload> 679 | ); 680 | } 681 | 682 | static function build(ctx:BuildContextN) { 683 | 684 | var auth = None; 685 | 686 | var target = switch ctx.types { 687 | case []: 688 | switch Context.getCallArguments() { 689 | case null | []: 690 | ctx.pos.error('You must either specify a target type as type parameter or a target object as constructor argument'); 691 | case [v]: 692 | v.typeof().sure(); 693 | case _: 694 | ctx.pos.error('too many arguments - only one expected'); 695 | } 696 | case [t]: t; 697 | case [s, t]: 698 | var sc = s.toComplex(); 699 | 700 | var user = 701 | (macro @:pos(ctx.pos) { 702 | var x:$sc = null; 703 | function test(s:tink.web.Session):U { 704 | return null; 705 | } 706 | test(x); 707 | }).typeof().sure(); 708 | 709 | auth = Some({ session: s, user: user }); 710 | t; 711 | default: 712 | ctx.pos.error('Invalid usage'); 713 | } 714 | 715 | var def = new Routing( 716 | new RouteCollection( 717 | target, 718 | [ 719 | #if tink_multipart 'multipart/form-data', #end 720 | 'application/x-www-form-urlencoded', 721 | 'application/json' 722 | ], 723 | ['application/json'] 724 | ), 725 | auth 726 | ).generate(ctx.name, ctx.pos); 727 | // trace(new haxe.macro.Printer().printTypeDefinition(def)); 728 | return def; 729 | } 730 | 731 | static function apply() { 732 | return BuildCache.getTypeN('tink.web.routing.Router', build); 733 | } 734 | 735 | } 736 | #end --------------------------------------------------------------------------------