summaryrefslogtreecommitdiff
path: root/examples/scala-js/tools/shared/src/main/scala/scala/scalajs/tools/jsdep/JSDependency.scala
blob: 2e6f8d1a013b43a7d51a8f16a2d16deb2c7afacc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package scala.scalajs.tools.jsdep

import scala.scalajs.tools.json._

import scala.scalajs.ir.Trees.isValidIdentifier

/** Expresses a dependency on a raw JS library and the JS libraries this library
 *  itself depends on.
 *
 *  Both the [[resourceName]] and each element of [[dependencies]] is the
 *  unqualified filename of the library (e.g. "jquery.js").
 *
 *  @param resourceName Filename of the JavaScript file to include
 *      (e.g. "jquery.js")
 *  @param dependencies Filenames of JavaScript files that must be included
 *      before this JavaScript file.
 *  @param commonJSName A JavaScript variable name this dependency should be
 *      required in a commonJS environment (n.b. Node.js). Should only be set if
 *      the JavaScript library will register its exports.
 */
final class JSDependency(
    val resourceName: String,
    val dependencies: List[String] = Nil,
    val commonJSName: Option[String] = None) {

  require(commonJSName.forall(isValidIdentifier),
    "commonJSName must be a valid JavaScript identifier")

  def dependsOn(names: String*): JSDependency =
    copy(dependencies = dependencies ++ names)
  def commonJSName(name: String): JSDependency =
    copy(commonJSName = Some(name))
  def withOrigin(origin: Origin): FlatJSDependency =
    new FlatJSDependency(origin, resourceName, dependencies, commonJSName)

  private def copy(
      resourceName: String = this.resourceName,
      dependencies: List[String] = this.dependencies,
      commonJSName: Option[String] = this.commonJSName) = {
    new JSDependency(resourceName, dependencies, commonJSName)
  }
}

object JSDependency {

  implicit object JSDepJSONSerializer extends JSONSerializer[JSDependency] {
    def serialize(x: JSDependency): JSON = {
      new JSONObjBuilder()
        .fld("resourceName", x.resourceName)
        .opt("dependencies",
            if (x.dependencies.nonEmpty) Some(x.dependencies) else None)
        .opt("commonJSName", x.commonJSName)
        .toJSON
    }
  }

  implicit object JSDepJSONDeserializer extends JSONDeserializer[JSDependency] {
    def deserialize(x: JSON): JSDependency = {
      val obj = new JSONObjExtractor(x)
      new JSDependency(
          obj.fld[String]      ("resourceName"),
          obj.opt[List[String]]("dependencies").getOrElse(Nil),
          obj.opt[String]      ("commonJSName"))
    }
  }
}