# Copyright 2017 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//build/config/chromeos/ui_mode.gni")
import("//third_party/node/node.gni")

template("optimize_webui") {
  node(target_name) {
    script = "//ui/webui/resources/tools/optimize_webui.py"

    forward_variables_from(invoker, [ "visibility" ])

    # This depfile is generated by optimize_webui.py
    depfile = "${target_gen_dir}/${target_name}.d"

    inputs = []
    outputs = []
    input_count = 0
    foreach(f, invoker.js_module_in_files) {
      input_count = input_count + 1
      out_file = string_replace(f, ".js", ".rollup.js")
      outputs += [ "$target_gen_dir/$out_file" ]
      if (input_count == 2) {
        folder = get_path_info(f, "dir")
        outputs += [ "$target_gen_dir/$folder/shared.rollup.js" ]
      }
    }

    deps = invoker.deps

    # Note that we have to manually pass the sources to our script if the
    # script needs them as inputs.
    args = [
      "--host",
      invoker.host,
      "--input",
      invoker.input,
      "--out_folder",
      rebase_path(target_gen_dir, root_build_dir),
      "--depfile",
      rebase_path(depfile, root_build_dir),
      "--target_name",
      target_name,
    ]

    if (defined(invoker.excludes)) {
      args += [ "--exclude" ] + invoker.excludes
    }

    polymer_path =
        rebase_path("//third_party/polymer/v3_0/components-chromium/",
                    root_build_dir)
    resources_path =
        rebase_path("$root_gen_dir/ui/webui/resources/tsc/", root_build_dir)

    external_paths = []
    if (is_chromeos_ash) {
      ash_resources_path =
          rebase_path("$root_gen_dir/ash/webui/common/resources/preprocessed/",
                      root_build_dir)
      external_paths += [
        "chrome://resources/ash/common/|$ash_resources_path",
        "//resources/ash/common/|$ash_resources_path",
      ]
    }

    external_paths += [
      "arkweb://resources/polymer/v3_0/|$polymer_path",
      "arkweb://resources/|$resources_path",
      "chrome://resources/polymer/v3_0/|$polymer_path",
      "chrome://resources/|$resources_path",
      # Scheme relative versions to work with chrome-untrusted://
      "//resources/polymer/v3_0/|$polymer_path",
      "//resources/|$resources_path",
    ]

    if (defined(invoker.external_paths)) {
      external_paths += invoker.external_paths
    }
    args += [ "--external_paths" ] + external_paths

    inputs += [ "//ui/webui/resources/tools/rollup_plugin.mjs" ]
    args += [ "--js_module_in_files" ] + invoker.js_module_in_files

    if (defined(invoker.out_manifest)) {
      args += [
        "--out-manifest",
        rebase_path(invoker.out_manifest, root_build_dir),
      ]
      outputs += [ invoker.out_manifest ]
    }
  }
}