billstclair/elm-dev-random/1.1.4

NOTE: this package is not compatible with Elm 0.19.1

DevRandom

The DevRandom module provides a way to generate cryptographically-secure random numbers. It does this by using two ports to communicate with JavaScript code that calls window.crypto.getRandomValues().

There are two ways to call the generator, depending on the Config parameter to generate. One way works in a pure Elm environment, and uses the normal Elm Random module, which is not cryptographically secure. The other way requires you to use ports to communicate with JavaScript code, most of which is provided with the example.

See the example readme for instructions on creating the ports and using the included JavaScript code.

Generate random bytes

type alias SendPort msg =
Int -> Cmd msg

Signature of send port for dev-random-port.js

The Int arg is the number of bytes (8-bit integers) to generate.

type alias ReceiveMsgWrapper msg =
( Bool, List Int ) -> msg

Message wrapper for receive port of dev-random-port.js

(isSecure, bytes) -> msg

If isSecure is True, then the random number generation was cryptographically secure.

type alias Config msg =
{ sendPort : Maybe (SendPort msg)
, receiveMsgWrapper : Maybe (ReceiveMsgWrapper msg)
}

Parameter to generate that determines whether to use the Elm Random module or ports to the JavaScript code that calls window.crypto.getRandomValues().

If sendPort is not Nothing, will use the ports.

If sendPort is Nothing, and receiveMsgWrapper is not Nothing, will use the Elm Random module.

generate : Int -> Config msg -> Cmd msg

Generate a number of random bytes (integers between 0 and 255, inclusive).

generate bytes config

If config.sendPort is not Nothing, return a Cmd that sends bytes through the port. Otherwise, if config.receiveMsgWrapper is not Nothing, use it to wrap the result of Random.generate() as a message for your update function.

Generate random integers

type alias ReceiveIntMsgWrapper msg =
( Bool, Int ) -> msg

Message wrapper for receiveInt port of dev-random-port.js

(isSecure, integer) -> msg

If isSecure is True, then the random number generation was cryptographically secure.

type alias IntConfig msg =
{ sendPort : Maybe (SendPort msg)
, receiveIntMsgWrapper : Maybe (ReceiveIntMsgWrapper msg)
}

Parameter to generateInt that determines whether to use the Elm Random module or ports to the JavaScript code that calls window.crypto.getRandomValues().

If sendPort is not Nothing, will use the ports.

If sendPort is Nothing, and receiveIntMsgWrapper is not Nothing, will use the Elm Random module.

generateInt : Int -> IntConfig msg -> Cmd msg

Generate a random x uniformly distributed in the range 0 <= x < ceiling.

generateInt ceiling config

If config.sendPort is not Nothing, return a Cmd that sends bytes through the port. Otherwise, if config.receiveIntMsgWrapper is not Nothing, use it to wrap the result of Random.generate() as a message for your update function.