This workspace showcases two distinct methodologies for interacting with JavaScript libraries from Scala.js 3,
using TensorFlow.js (@tensorflow/tfjs v4.22.0) as the underlying engine.
It has been structured as a multi-project aggregate SBT build, splitting the strategies into two modules:
handcrafted: Manually designed, type-safe facade encapsulated inside a package-private boundary, exposing a 100% pure-Scala API. Trains a Feedforward Neural Network to solve the classic non-linear XOR gate problem.scalablytyped: Automatically generates extensive, ultra-precise Scala.js facades from TypeScript definition files (.d.ts) using the ScalablyTyped toolchain.
To compile and run both subprojects, you need:
- Java JDK (recommended: JDK 11, 17, or 21)
- SBT (Scala Build Tool)
- Node.js (v18+) and npm
This submodule demonstrates the Private Raw Facade + Pure Scala Wrapper architectural pattern.
Inside Network.scala,
we define package-private (private[network]) raw JS facades mapping directly to @tensorflow/tfjs imports and classes.
The public Network class acts as a clean barrier,
wrapping all JS promises into Scala Futures, translating nested standard Scala sequences into multi-dimensional typed JS arrays, and automatically managing C++ tensor allocations via .dispose() to ensure zero memory leaks.
Launch the handcrafted XOR neural network directly via SBT:
sbt "handcrafted/run"- Builds a Feedforward Neural Network using sequential layers (ReLU hidden layer, Sigmoid output layer).
- Translates pure Scala datasets (
inputsandoutputslists) into 2D tensors. - Trains the model over
1000epochs using theadamoptimizer andbinaryCrossentropyloss. - Performs predictions on the standard inputs, showing the trained XOR output (approaching
0and1correctly). - Disposes of all input, output, and prediction tensors.
This submodule leverages the ScalablyTyped sbt plugin to parse @tensorflow/tfjs type definitions and automatically output Scala.js types under the custom package customtypings.
It uses a custom webpack.config.js specifying target node.
You can run the automatic facade generation, Webpack bundling, and execution in one single command without setting any shell environment options (like NODE_OPTIONS):
sbt -J-Xmx4G "scalablytyped/run"- Imports and utilizes auto-generated facades from
customtypings.tensorflowTfjs.modand associated core math libraries. - Creates a 1D tensor representing elements
[1.0, 2.0, 3.0, 4.0]. - Performs a typed squaring operation calling the standalone
squarefunction fromcustomtypings.tensorflowTfjsCore.distOpsSquareMod. - Outputs the original and squared tensors via native
.print()calls inside the Node console. - Safely deallocates tensor memory via
.dispose().