load("@npm//@bazel/typescript:index.bzl", "ts_library")
load("//tools/node_tools/node_modules_licenses:node_modules_licenses.bzl", "node_modules_licenses")

filegroup(
    name = "licenses-texts",
    srcs = glob(["licenses/*.txt"]),
)

ts_library(
    name = "licenses-config",
    srcs = [
        "licenses.ts",
    ],
    compiler = "//tools/node_tools:tsc_wrapped-bin",
    tsconfig = "tsconfig.json",
    deps = [
        "//tools/node_tools/node_modules_licenses:licenses-map",
        "@tools_npm//@bazel/typescript",
        "@tools_npm//@types/node",
    ],
)

# (TODO)dmfilippov Find a better way to fix it (another workaround or submit a bug to
# plugin's authors or to a ts_config rule author).
# The following genrule is a workaround for a bazel intellij plugin's bug.
# According to the documentation, the ts_config_rules section should be added
# to a .bazelproject file if a project uses typescript
# (https://ij.bazel.build/docs/dynamic-languages-typescript.html)
# Unfortunately, this doesn't work. It seems, that the plugin expects some output from
# the ts_config rule, but the rule doesn't produce any output.
# To workaround the issue, the tsconfig_editor genrule was added. The genrule only copies
# input file to the output file, but this is enough to make bazel plugins works.
# So, if you have any problem a typescript editor (import errors, types not found, etc...) -
# try to build this rule from the command line
# (bazel build tools/node_tools/node_modules/licenses:tsconfig_editor) and then sync bazel project
# in intellij.
genrule(
    name = "tsconfig_editor",
    srcs = [":tsconfig.json"],
    outs = ["tsconfig_editor.json"],
    cmd = "cp $< $@",
)

# filegroup is enough (instead of rollup-bundle), because we are not going to run licenses.ts file
filegroup(
    name = "licenses-config-js",
    srcs = [":licenses-config"],
    output_group = "es5_sources",
)

# Generate polygerrit-licenses.json for files in @ui_npm workspace.
# For details - see comments for node_modules_licenses rule and
# tools/node_tools/node_modules_licenses/license-map-generator.ts file
node_modules_licenses(
    name = "polygerrit-licenses",
    licenses_config = "licenses-config-js",
    licenses_texts = [":licenses-texts"],
    node_modules = "@ui_npm//:node_modules",
    visibility = ["//visibility:public"],
)
