packages feed

jsaddle-wasm (empty) → 0.0.0.0

raw patch · 7 files changed

+379/−0 lines, 7 filesdep +aesondep +asyncdep +base

Dependencies added: aeson, async, base, bytestring, ghc-experimental, jsaddle, stm

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for jsaddle-wasm++## 0.0.0.0 -- 2024-10-20++ * First version.
+ LICENSE view
@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+    HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++  i. the right to reproduce, adapt, distribute, perform, display,+     communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+     likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+     subject to the limitations in paragraph 4(a), below;+  v. rights protecting the extraction, dissemination, use and reuse of data+     in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+     European Parliament and of the Council of 11 March 1996 on the legal+     protection of databases, and under any national implementation+     thereof, including any amended or successor version of such+     directive); and+vii. other similar, equivalent or corresponding rights throughout the+     world based on applicable law or treaty, and any national+     implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+    surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+    warranties of any kind concerning the Work, express, implied,+    statutory or otherwise, including without limitation warranties of+    title, merchantability, fitness for a particular purpose, non+    infringement, or the absence of latent or other defects, accuracy, or+    the present or absence of errors, whether or not discoverable, all to+    the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+    that may apply to the Work or any use thereof, including without+    limitation any person's Copyright and Related Rights in the Work.+    Further, Affirmer disclaims responsibility for obtaining any necessary+    consents, permissions or other rights required for any use of the+    Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+    party to this document and has no duty or obligation with respect to+    this CC0 or use of the Work.
+ README.md view
@@ -0,0 +1,91 @@+# jsaddle-wasm+[![CI](https://github.com/amesgen/jsaddle-wasm/workflows/ci-wasm/badge.svg)](https://github.com/amesgen/jsaddle-wasm/actions)+[![Hackage](https://img.shields.io/hackage/v/jsaddle-wasm)](https://hackage.haskell.org/package/jsaddle-wasm+[![Haddocks](https://img.shields.io/badge/documentation-Haddocks-purple)](https://hackage.haskell.org/package/jsaddle-wasm/docs/Language-Javascript-JSaddle-Wasm.html))++Run [JSaddle][] `JSM` actions with the [GHC WASM backend][].++This can for example be used to compile and run [Miso][] or [Reflex][] apps in the browser.++> [!IMPORTANT]+> This project is in an early stage.++## Examples++### Miso++Several Miso examples: https://github.com/tweag/ghc-wasm-miso-examples++## How to use++Install a WASM-enabled GHC with support for the WASM JSFFI from [ghc-wasm-meta][] (GHC 9.10 or newer).++Assuming you built your application as an `app :: JSM ()`:++```haskell+import Language.Javascript.JSaddle.Wasm qualified as JSaddle.Wasm++foreign export javascript "hs_start" main :: IO ()++main :: IO ()+main = JSaddle.Wasm.run app+```++Build the WASM binary with the following GHC options:+```cabal+ghc-options: -no-hs-main -optl-mexec-model=reactor "-optl-Wl,--export=hs_start"+```++Now, run the post-linker script as described in the [GHC User's Guide][ghc-users-guide-js-api]; we will call the resulting JavaScript file `ghc_wasm_jsffi.js`.++Then, following the [GHC User's Guide][ghc-users-guide-js-api], you can run the WASM binary in the browser via e.g. [browser_wasi_shim][]:+```javascript+import { WASI, OpenFile, File, ConsoleStdout } from "@bjorn3/browser_wasi_shim";+import ghc_wasm_jsffi from "./ghc_wasm_jsffi.js";++const fds = [+  new OpenFile(new File([])), // stdin+  ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),+  ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),+];+const options = { debug: false };+const wasi = new WASI([], [], fds, options);++const instance_exports = {};+const { instance } = await WebAssembly.instantiateStreaming(fetch("app.wasm"), {+  wasi_snapshot_preview1: wasi.wasiImport,+  ghc_wasm_jsffi: ghc_wasm_jsffi(instance_exports),+});+Object.assign(instance_exports, instance.exports);++wasi.initialize(instance);+await instance.exports.hs_start();+```++## Potential future work++ - Take a closer look at synchronous callbacks (no special handling currently, but basic things like `stopPropagation` already seem to work fine).+ - Testing (e.g. via Selenium).+ - Add logging/stats.+ - Performance/benchmarking (not clear that this is actually a bottleneck for most applications).+    - Optimize existing command-based implementation.+       - Reuse buffers+       - Use a serialization format more efficient than JSON.+    - Implement `ghcjs-dom` API directly via the WASM JS FFI.++      This would involve creating a `ghcjs-dom-wasm` package by adapting the FFI import syntax from `ghcjs-dom-jsffi`/`ghcjs-dom-javascript` appropriately.++      Currently, the generic `ghcjs-dom-jsaddle` seems to work fine, so it seems sensible to wait with this until benchmarks or other concerns motivate this.++## Related projects++ - [WebGHC/jsaddle-wasm](https://github.com/WebGHC/jsaddle-wasm) for the analogue for [WebGHC][] instead of the [GHC WASM backend][].++[JSaddle]: https://github.com/ghcjs/jsaddle+[GHC WASM backend]: https://www.tweag.io/blog/2022-11-22-wasm-backend-merged-in-ghc+[Miso]: https://github.com/dmjio/miso+[Reflex]: https://github.com/reflex-frp/reflex+[ghc-wasm-meta]: https://gitlab.haskell.org/ghc/ghc-wasm-meta+[browser_wasi_shim]: https://github.com/bjorn3/browser_wasi_shim+[ghc-users-guide-js-api]: https://ghc.gitlab.haskell.org/ghc/doc/users_guide/wasm.html#the-javascript-api+[WebGHC]: https://webghc.github.io
+ jsaddle-wasm.cabal view
@@ -0,0 +1,54 @@+cabal-version: 3.0+name: jsaddle-wasm+version: 0.0.0.0+synopsis: Run JSaddle @JSM@ with the GHC WASM backend+description: Run JSaddle @JSM@ with the GHC WASM backend.+category: Web, Javascript+homepage: https://github.com/amesgen/jsaddle-wasm+bug-reports: https://github.com/amesgen/jsaddle-wasm/issues+license: CC0-1.0+license-file: LICENSE+extra-source-files: README.md+author: amesgen+maintainer: amesgen@amesgen.de+extra-doc-files: CHANGELOG.md++source-repository head+  location: https://github.com/amesgen/jsaddle-wasm+  type: git++common common+  ghc-options:+    -Wall+    -Wunused-packages+    -Wredundant-constraints++  default-language: GHC2021+  default-extensions:+    BlockArguments+    OverloadedStrings++library+  import: common+  hs-source-dirs: src+  exposed-modules:+    Language.Javascript.JSaddle.Wasm++  other-modules:+    Language.Javascript.JSaddle.Wasm.Internal++  build-depends:+    base >=4.16 && <5,+    jsaddle ^>=0.9,++  if arch(wasm32)+    build-depends:+      aeson >=2 && <2.3,+      async ^>=2.2,+      bytestring >=0.11 && <0.13,+      ghc-experimental ^>=0.1,+      stm ^>=2.5,++    hs-source-dirs: src-wasm+  else+    hs-source-dirs: src-native
+ src-native/Language/Javascript/JSaddle/Wasm/Internal.hs view
@@ -0,0 +1,6 @@+module Language.Javascript.JSaddle.Wasm.Internal (run) where++import Language.Javascript.JSaddle.Types (JSM)++run :: JSM () -> IO ()+run _ = fail "Language.Javascript.JSaddle.Wasm.run: only works on WASM backend"
+ src-wasm/Language/Javascript/JSaddle/Wasm/Internal.hs view
@@ -0,0 +1,89 @@+module Language.Javascript.JSaddle.Wasm.Internal (run) where++import Control.Concurrent.Async qualified as Async+import Control.Concurrent.STM+import Control.Exception (evaluate)+import Data.Aeson qualified as A+import Data.ByteString (ByteString)+import Data.ByteString.Internal qualified as BI+import Data.ByteString.Lazy.Char8 qualified as BLC8+import Data.ByteString.Unsafe qualified as BU+import Foreign.Ptr (Ptr)+import GHC.Wasm.Prim (JSString, JSVal)+import GHC.Wasm.Prim qualified+import Language.Javascript.JSaddle.Run (runJavaScript)+import Language.Javascript.JSaddle.Run.Files qualified as JSaddle.Files+import Language.Javascript.JSaddle.Types (Batch, JSM)++run :: JSM () -> IO ()+run entryPoint = do+  -- TODO rather use a bounded (even size 1) queue?+  batchQueue :: TQueue Batch <- newTQueueIO++  let sendBatch :: Batch -> IO ()+      sendBatch = atomically . writeTQueue batchQueue++  (processResult, _processSyncResult, start) <-+    runJavaScript sendBatch entryPoint++  processResultCallback <- mkPullCallback \s -> do+    bs <- jsStringToByteString s+    case A.eitherDecodeStrict bs of+      Left e -> fail $ "jsaddle: received invalid JSON: " <> show e+      Right r -> processResult r++  readBatchCallback <- mkPushCallback do+    batch <- atomically $ readTQueue batchQueue+    byteStringToJSString $ BLC8.toStrict $ A.encode batch++  let jsaddleRunner :: IO ()+      jsaddleRunner = do+        s <-+          byteStringToJSString . BLC8.toStrict . BLC8.unlines $+            [ JSaddle.Files.ghcjsHelpers,+              JSaddle.Files.initState,+              "(async () => {",+              "  while (true) {",+              "    const batch = JSON.parse(await readBatch());",+              JSaddle.Files.runBatch+                (\r -> "processResult(JSON.stringify(" <> r <> "));")+                -- TODO handle synchronous stuff (see processSyncResult)+                Nothing,+              "  }",+              "})();"+            ]+        evaluate =<< js_eval s processResultCallback readBatchCallback++  Async.concurrently_ start jsaddleRunner++-- Utilities:++foreign import javascript "wrapper" mkPullCallback :: (JSString -> IO ()) -> IO JSVal++foreign import javascript "wrapper" mkPushCallback :: IO JSString -> IO JSVal++foreign import javascript safe "new Function('processResult','readBatch',`(()=>{${$1}})()`)($2, $3)"+  js_eval :: JSString -> JSVal -> JSVal -> IO ()++-- Conversion JSString <-> ByteString++foreign import javascript unsafe "$1.length"+  js_stringLength :: JSString -> IO Int++foreign import javascript unsafe "(new TextEncoder()).encodeInto($1, new Uint8Array(__exports.memory.buffer, $2, $3)).written"+  js_encodeInto :: JSString -> Ptr a -> Int -> IO Int++jsStringToByteString :: JSString -> IO ByteString+jsStringToByteString s = do+  len <- js_stringLength s+  -- see https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/encodeInto#buffer_sizing+  -- (could also use another strategy described there)+  let lenMax = len * 3+  BI.createUptoN lenMax \buf -> js_encodeInto s buf lenMax++foreign import javascript unsafe "(new TextDecoder('utf-8', {fatal: true})).decode(new Uint8Array(__exports.memory.buffer, $1, $2))"+  js_toJSString :: Ptr a -> Int -> IO JSString++byteStringToJSString :: ByteString -> IO JSString+byteStringToJSString bs =+  BU.unsafeUseAsCStringLen bs $ uncurry js_toJSString
+ src/Language/Javascript/JSaddle/Wasm.hs view
@@ -0,0 +1,13 @@+module Language.Javascript.JSaddle.Wasm (run) where++import Language.Javascript.JSaddle.Types (JSM)+import Language.Javascript.JSaddle.Wasm.Internal qualified as Internal++-- | Run a 'JSM' action via the WASM JavaScript FFI.+--+-- See the [README](https://github.com/amesgen/jsaddle-wasm) for more details.+--+-- While this package also compiles on non-WASM GHCs for convenience, running+-- this function will immediately fail.+run :: JSM () -> IO ()+run = Internal.run