[
  {
    "path": ".circleci/config.yml",
    "content": "cache_key: &cache_key tscc-{{ checksum \"yarn.lock\" }}\nsave_cache: &save_cache\n  save_cache:\n    key: *cache_key\n    paths:\n      - \"node_modules\"\n\nversion: 2\n\njobs:\n  build:\n    parallelism: 3\n    docker:\n      - image: circleci/openjdk:9-node\n    working_directory: ~/tscc\n    steps:\n      - checkout\n      - run:\n          name: update node\n          command: |\n            curl -sSL \"https://nodejs.org/dist/v14.17.3/node-v14.17.3-linux-x64.tar.xz\" | sudo tar --strip-components=2 -xJ -C /usr/local/bin/ node-v14.17.3-linux-x64/bin/node\n      - restore_cache:\n          key: *cache_key\n      - run: yarn install\n      - run: yarn lerna bootstrap\n      - run:\n          name: run tests\n          command: yarn jest --ci --runInBand --reporters=default --reporters=jest-junit\n          environment:\n            JEST_JUNIT_OUTPUT: \"reports/junit/results.xml\"\n      - run:\n          name: compile typescript\n          command: yarn lerna exec -- -- tsc --noEmit\n      - *save_cache\n      - store_test_results:\n          path: reports/junit\n      - store_artifacts:\n          path: reports/junit\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nend_of_line = lf\ninsert_final_newline = true\n\n[*.{js,jsx,ts,tsx,css,html,json}]\ncharset = utf-8\nindent_style = tab\nindent_size = 4\ntrim_trailing_whitespace = true\nmax_line_length = 100\n\n[*.md]\ntrim_trailing_whitespace = false\n\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: weekly\n  open-pull-requests-limit: 20\n  ignore:\n  - dependency-name: typescript\n    versions:\n    - \"> 3.9.7\"\n  - dependency-name: tslib\n    versions:\n    - 2.1.0\n"
  },
  {
    "path": ".gitignore",
    "content": "/node_modules\n/packages/*/node_modules\ndist\nlerna-debug.log\njunit.xml\n.tscc_temp\nyarn-error.log\n.vscode/**/*.log\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n\t\"editor.rulers\": [\n\t\t100\n\t],\n\t\"editor.formatOnSave\": true,\n\t\"javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces\": false,\n\t\"javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces\": false,\n\t\"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces\": false,\n\t\"typescript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces\": false,\n\t\"jest.jestCommandLine\": \"jest\"\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 Sean Lee\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# TSCC\n\n[![tscc npm version](https://img.shields.io/npm/v/@tscc/tscc.svg?style=popout&color=blue&label=%40tscc%2Ftscc)](https://www.npmjs.com/package/@tscc/tscc)\n[![rollup-plugin-tscc npm version](https://img.shields.io/npm/v/@tscc/rollup-plugin-tscc.svg?style=popout&color=blue&label=%40tscc%2Frollup-plugin-tscc)](https://www.npmjs.com/package/@tscc/rollup-plugin-tscc)\n[![CircleCI](https://circleci.com/gh/theseanl/tscc.svg?style=svg)](https://circleci.com/gh/theseanl/tscc)\n\nTSCC is a collection of tools to seamlessly bundle and minify Typescript project using Closure Compiler.\n\n## Migrate\n\nIt is easy to migrate an existing Typescript project to TSCC.\nTo get a sense of what it is like, check out [todomvc apps](https://github.com/theseanl/todomvc/) forked from the original [tastejs/todomvc](https://github.com/tastejs/todomvc) and modified to use TSCC.\n\n---\n\n## Features\n\n - Automatically configures settings for [tsickle](https://github.com/angular/tsickle) and [closure compiler](https://github.com/google/closure-compiler), and wires up tsickle js outputs and sourcemaps to closure compiler, sorted in accordence with dependency information, as required by closure compiler.\n - Provides an alternative [rollup](https://rollupjs.org) build using `rollup-plugin-tscc` plugin, emulating the chunking behaviour of closure compiler to get the same set of output files as what closure compiler would produce.\n - External module support: looks up `require`d nodejs modules and wires them so that externs are generated, and transforms any code that uses externally imported variables. Think of it as an analogue of [\"external\" option of webpack](https://webpack.js.org/configuration/externals/#externals) or [\"globals\" option of rollup](https://rollupjs.org/guide/en/#outputglobals) for closure compiler.\n\n## Background\n\nClosure is a wonderful system of tools. The closure compiler is the best javascript minifier and bundler, but it is known to be very difficult to use. Documentations are scarce, and integration with external tools is not well-established.\n\nTsickle is another wonderful tool. It has finally made it ergonomic to write codes that can naturally be consumed by closure compiler — it transforms `.ts` files to well-annotated `.js` files, which would otherwise not even be consumed by the compiler and automatically generates [externs](https://developers.google.com/closure/compiler/docs/api-tutorial3#externs) file from declaration files. However, as in closure compiler, one has to be careful with setting it up, otherwise strange bugs can occur which are not actively worked on as of now. Also, it only performs transpilation — there is no tool to feed transpiled files to closure compiler, which is another painful part.\n\nTSCC aims to encapsulate these tools in a minimal, ergonomic API, and provides a faster and easier alternative bundling method using [Rollup](https://rollupjs.org) via a companion rollup-plugin-tscc plugin, which is great for rapid development. TSCC can be used as a drop-in replacement for rollup in existing projects using rollup, after moving chunk information in `rollup.config.js` to [`tscc.spec.json`](#tscc-spec-files). TSCC spec file is a single source of truth for all of your module bundling information.\n\n## Getting started\n\nSuppose that we have a project with the following directory structure.\n```\nmy_project\n├───tsconfig.json\n├───rollup.config.js\n└───src\n    ├───Components\n    │   ...\n    └───app.ts\n```\n\n1. Install tscc cli:\n    ```\n    yarn global add @tscc/tscc\n    ```\n2. Create a [_spec file_](#tscc-spec-files) `tscc.spec.json` next to `tsconfig.json`.\n    ```jsonc\n    {\n        \"modules\": {\n            \"out\": \"src/app.ts\" // entry file path\n        }\n    }\n    ```\n3. Execute at the project root:\n    ```\n    tscc\n    ```\nIn order to setup an alternative rollup build,\n\n1. In your project's directory, install `@tscc/rollup-plugin-tscc` by executing:\n    ```\n    yarn add -D @tscc/rollup-plugin-tscc\n    ```\n2. Import `rollup-plugin-tscc` plugin in rollup config file.\n    ```js\n    // rollup.config.js\n    import tscc from '@tscc/rollup-plugin-tscc';\n    export default {\n        output: {\n            ...,\n            dir: '.'\n        },\n        plugins: [\n            tscc(),\n            typescript()\n        ]\n    }\n    ```\n3. Execute `rollup` at the project root.\n\n## Usage\n\n### Command line\n\n@tscc/tscc package provides a single command line interface `tscc`.\n\n```\ntscc [--help] [--clean] [--spec <spec_file_path>] [-- <typescript_flags> [-- <closure_compiler_flags>]]\n```\n\nIt will compile & bundle typescript sourced based on module spec described in `spec_file`. Alternatively, one can provide the spec file's key-value pairs via command line arguments, see below. Note that one have to provide a spec file or at least a value for a 'module' - if both are omitted, it will assume that the spec file's path is implicitly set as the current working directory.\n\nArguments passed after the first `--`, if exists, will be passed to the typescript compiler as one would pass to `tsc`, and arguments after the second `--` will be passed to the closure compiler. e.g. `tscc --spec src -- --target ES5 -- --assume_function_wrapper`. Note that `tsc` assumes that the project root (`--project`) is the current working directory when it is omitted, but `tscc` assumes that it is the containing directory of the spec file.\n\n### JS API\n\nSimply provide contents of spec file as an argument:\n\n```js\nimport tscc from 'tscc';\n\ntscc({\n    modules: {\n        bundle: 'entry.ts'\n    },\n    prefix: 'dist/'\n    // ...\n}).then(() => console.log('Done'));\n```\n\nThe default export `tscc` function accepts up to 3 arguments.\n```ts\ntscc(\n    json_content_of_spec_file_or_path_to_spec_file,\n    path_to_search_for_tsconfig?:string,\n    typescript_compiler_option_override?\n):Promise<void>\n```\nThe first argument is either a string representing the path of the spec file or a JSON content of the spec file. The JSON object can additionally have `specFile` property, whose value is a path to a spec file. TSCC will lookup tscc spec file at that path and merge its contents.\n\n```js\ntscc({\n    /* Contents of spec JSON */\n    specFile: \"path_to_spec_file.json\"\n})\n// To load spec file from the path and override it.\n```\n\nThe second argument should be self-explanatory; the third argument is what would you put in tsconfig.json's \"compilerOption\" key, it will override those provided with the second argument.\n\n### Usage with rollup\n\n@tscc/rollup-plugin-tscc package provides a rollup plugin which will provide chunking information in your spec file to rollup.\n\nInstall `rollup-plugin-tscc` by executing `yarn add -D @tscc/rollup-plugin-tscc`.\n```js\n// rollup.config.js\nconst tscc = require('@tscc/rollup-plugin-tscc');\nmodule.exports = {\n    output: {\n        dir: '.' // output.dir option will be provided by the plugin, but\n                 // rollup currently requires something to be present in order to\n                 // work properly.\n    },\n    // ...\n    plugins: [\n        tscc({\n            /* Contents of spec JSON */\n            // or,\n            specFile: \"path_to_spec_file.json\"\n        })\n    ]\n};\n```\nThen it will provide the information in your spec file to rollup, and post-process code-splitting chunks produced by rollup to match the behavior of Closure Compiler, so that you can use `rollup` build interchangeably with `tscc` build.\nThe plugin will control the `input`, `output.dir`, `output.entryFileNames`, `output.chunkFileNames` option.\nNote that it does not transpile TS to JS, one has to provide another plugin manually, such as [rollup-plugin-typescript2](https://github.com/ezolenko/rollup-plugin-typescript2).\n\n## Tscc spec files\n\nTscc spec file is a single source of truth of your bundling information. It describes each of output bundle's entry file and dependencies among them. It also describes which modules imported in your source shall be treated as an external module and aliased with which global variable.\n\n```js\n{\n    modules, /* required */\n    external,\n    prefix,\n    chunkFormat,\n    compilerFlags,\n    jsFiles,\n    debug\n}\n```\n\n### `modules`\n\n```jsonc\n    \"modules\": {\n        \"index\": \"index.ts\",\n        \"dependent_a\": {\n            \"entry\": \"dependent_a_entry_file.ts\",\n            \"dependencies\": [ \"index\" ],\n            \"extraSources\": [ \"css_renaming_map.js\" ]\n        }\n    }\n```\n`modules` option is a key-value pair of module name and module's specification. If a specification only consists of a entry file name, it can simply be a string representing the entry file's path, which is sufficient for most of build situation where no code splitting is applied. In general, module's specification consists of `entry`, `dependencies`, and `extraSources`. `dependencies` is an array of module names that this module depends on. It can be omitted if empty. Module names specified here will be provided to closure compiler via  `--chunk` flags, so check out a more detailed description of it in [Closure Compiler repo](https://github.com/google/closure-compiler/wiki/JS-Modules#code-splitting-output-modules). `extraSources` is an array of file names, which are not included in the Typescript project or not reacheable from a specified entry file via `import`s, but still needed to be provided to the closure compiler, such as css renaming maps generated by [Closure Stylesheets](https://github.com/google/closure-stylesheets). It can be omitted if empty. A module's name is an identifier to be used as a output chunk's name. To control the output directory, use `prefix` option.\n\nCLI equivalent is `--module <module_name>:<entry_file>:<comma_separated_dependencies>:<comma_separated_extra_sources>`.\n\n### `external`\n\n```jsonc\n{\n    \"external\": {\n        \"react\": \"React\",\n        \"react-dom\": \"ReactDOM\",\n    }\n}\n```\n\nIt is mostly identical to the [`output.global` option](https://rollupjs.org/guide/en#core-functionality) of rollup. It is a key-value pair, where key is a module name whose content will not be included in the bundle output, and value is a name of a global variable to which an `module.exports` of the module will be aliased.\n\nIf a module name is a relative path, the file it _resolves to_ will be treated as an external module. This is similar to rollup's case, but is different in that only relative path can be used and absolute paths can't. Such paths are resolved in the same convention how other relative paths in the spec file are resolved, see `prefix` option description.\n\nCLI equivalent is `--external <module_name>:<global_variable_name>`.\n\n### `prefix`\n\n```jsonc\n    \"prefix\": \"dist/\"\n    // or,\n    \"prefix\": { \"rollup\": \"dev/\", \"cc\": \"dist/\" }\n```\nIt is a name that will be prepended to the output chunk's name. It is prepended _as is_, which means that if no trailing path separator was provided, it will modify the output file's name. If it is a relative path starting from the current directory (\".\"), it will be resolved relative to the spec file's location. Otherwise, any relative path will be resolved relative to the current working directory, and absolute paths are used as is.\n\nCLI equivalent is `--prefix dist/` (or `--prefix.rollup dev/ --prefix.cc dist/`).\n\n### `chunkFormat`\n\n```jsonc\n    \"chunkFormat\": \"global\" /* default */ | \"module\"\n```\nIt is a value of `\"global\"` or `\"module\"` designating the output chunks' format. In case of `\"global\"`, which is the default behavior if this key isn't specified, output chunks will be plain Javascript that is suitable for `<script src=\"\">` HTML tag, and cross-chunk references will be done by exposing them to the global scope. In case of `\"module\"`, output chunks will be [Javascript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) which has to be included via `<script type=\"module\" src=\"\">` tags, and cross-chunk references will be done by `import` and `export` statements. Currently, when `\"module\"` option is used, `external` option cannot be used.\n\n### `compilerFlags`\n\n```jsonc\n    \"compilerFlags\": {\n        \"assume_function_wrapper\": true,\n        \"rewrite_polyfills\": true,\n        \"language_out\": \"ECMASCRIPT_2019\",\n        \"variable_renaming_report\": \"out/report.map\"\n    }\n```\nIt is a key-value pair of flags to be passed to the closure compiler. Keys are literally [closure compiler options](https://github.com/google/closure-compiler/wiki/Flags-and-Options) minus the leading `--`. flags which accepts multiple values can be represented as an array of values. TSCC sets default values for many flags, in particular, the compilation works even without the `compilerOptions` key in the spec. Any values provided here will override default flags. TSCC will treat these values as opaque data.\n\n### `jsFiles`\n\n```jsonc\n    \"jsFiles\": [\n        \"./glob/*/for/js/files.js\"\n    ]\n```\n\nIt is a string or an array of string, containing glob expressions of JS files to be provided to closure compiler. In order to import closure-style JS to TS file, use `import \"goog:moduleName\"` in TS, and provide the JS file declaring `goog.module('moduleName')` via this flag. A difference with `extraSources` in module spec is that these files will be included in dependency graph just like other TS files, but extraSources will be included in the compilation even if they are not reachable from entry files.\n\n### `debug`\n\n```jsonc\n    \"debug\": {\n        \"persistArtifacts\": true,\n        \"ignoreWarningsPath\": [\"/node_modules/\", \"/vendor/\"]\n    }\n```\nIt is a key-value pair of debugging options.\n - `persistArtifacts`: writes intermediate tsickle output to a directory `.tscc_temp`.\n - `ignoreWarningsPath`: Paths to ignore warnings produced by tsickle. It uses a simple substring search. This value defaults to `[\"/node_modules/\"]`.\n\n### Importing external libraries from NPM\n\nBest practice is to provide them as a separate script tag instead of bundling it together, as such libraries do not in general safe to be compiled by Closure Compiler. Declare them as external modules in the spec file, and import them like you would usually do. Then you can benefit from IDE's type checking functionality while tscc can lookup their type definitions and include them as closure compiler's externs.\n\n#### Detailed description of external modules handling\n\n 1. Users write `import React from 'react'`, so that users' IDE can find necessary typings.\n 2. TSCC configures tsickle to process type declaration files of module 'react' that Typescript located for us -- usually in node_modules directory.\n 3. TSCC creates a hypothetical \"gluing modules\" for each of external modules that looks like\n    ```javascript\n    goog.module('react')\n    /** Generated by TSCC */\n    exports = React\n    ```\n 4. To inform Closure about such a user-provided global variable name, TSCC generates additional externs for such a global variable, like\n    ```javascript\n    /**\n     * @const\n     * @type {some$file$name$mangled$by$tsickle}\n     */\n    var React = {};\n    ```\n    tsickle writes module-scoped externs to certain mangled namespace like this, so by declaring a global variable to be a type of that namespace, this provides type information of the external module to Closure Compiler.\n\n### How compilation source files are determined\n\nIn order to generate externs for external modules, TSCC has to provide declaration files to tsickle. Which files are provided? Typescript compiler's default behavior is hidden in most of cases, because `.d.ts` files does not anyway affect the compilation output. However, `.d.ts` files are used to generate externs in TSCC, so sometimes you may need to know this for troubleshooting.\n\nThe Typescript compiler's default behavior is to include every type declarations in `./node_modules/@types/`, `../node_modules/@types/`, `../../node_modules/@types/`, ..., and if you specify `\"types\": [\"a\", \"b\", ...]` in compiler options, it instead only includes files in `(../)node_modules/@types/a/` -- See official documentation on [`types`](https://www.typescriptlang.org/tsconfig#types) and [`typeRoots`](https://www.typescriptlang.org/tsconfig#typeRoots).\n\nIn comparison, TSCC will only include a file when it is reachable from _root files_ via transitive `import`s, triple-slash reference directives `///<reference path=\"...\"/>` and `///<reference types=\"...\"/>`. Root files will be the following:\n - module entry points designated in the spec file,\n - external module's base type declaration files,\n - modules included in tsconfig.json `types` key.\n\n### Importing typescript sources in node_modules\n\nIn order for typescript sources in node_modules directory to be compiled, you need to explicitly include those files in your `tsconfig.json`. This is a rule imposed by the typescript compiler; it has some special handling for files in node_modules directory, it won't transpile such files unlike usual transitive dependencies (that is, files not explicitly included in `tsconfig.json` via `\"files\"` or `\"include\"` keys, but is referenced via `import` or `///<reference path=\"...\" />` from a file that is included in `tsconfig.json`). In order to have them compiled, you need to explicitly mention those files in node_modules directory. For instance, if you are using a package `my_package` that contains typescript sources, you can add a key `{\"include\": [\"node_modules/my_package/**/*.ts\"]}` to your tsconfig.\n\n### Using closure compiler primitives\n\nCertain JS expressions, such as `goog.define(...)` or `goog.reflect.objectProperty(...)`, get special treatment from Closure Compiler. In order to use them, you need access to the `goog` variable or the export object of `goog.reflect` closure library module.\n\nIn order to access `goog`, first include a triple slash directive that points to a `base.d.ts` file that comes with the npm package.\n```ts\n///<reference path=\"node_modules/@tscc/tscc/third_party/closure_library/base.d.ts\" >\n```\nThe exact path may differ in your configuration. This file contains a declaration for a module `\"goog:goog\"`, so you can now write \n```ts\nimport * as goog from 'goog:goog'\n```\nto obtain a reference to the `goog` object. In order for this to work, the imported namespace's name should be `goog` as in above. As a matter of good practice, it'd better not to use `goog` as a variable name unless it _is_ the closure compiler's goog object.\n\nSimilarly, to use `goog.reflect`, reference `reflect.d.ts`, and then write\n```ts\nimport * as googReflect from 'goog:goog.reflect';\n```\n\n`rollup-plugin-tscc` will wire these module to an appropriate 'polyfill' modules so that runtime behaviors are unchanged.\n\n### Things to know\n\n#### Closure compiler handles modern javascript natively\n\nClosure compiler is capable of minifying modern javascript up to ECMASCRIPT 2019. If you only support modern environments, you can set closure compiler output langauge to ES6 or higher, it will provide smaller output in general.\n\n#### Use `declare interface` to prevent property name renaming\n\nOften you will need to prevent closure compiler renaming certain property names. Since you are writing typescript, such a property name will be a part of a certain interface. Add `declare` to that `interface` declaration. This does not produce additional meanings in typescript, but it will inform tsickle to create externs for the type so that properties of the interface are not renamed by closure compiler. Check out the tsickle's [documentation](https://github.com/angular/tsickle#declare).\n\n#### Sourcemaps\n\nIn order to enable sourcemaps, enable `compilerOptions.sourceMap` flag in `tsconfig.json`. Then TSCC will configure closure compiler to emit appropriate sourcemaps.\n\n#### Using prebuilt closure compiler images\n\nBy default, `tscc` command will use the java version of the compiler, which requires `java` to exist in `PATH` environment variable. Platform specific binary images are available in npm: [google-closure-compiler-windows](https://www.npmjs.com/package/google-closure-compiler-windows), [google-closure-compiler-osx](https://www.npmjs.com/package/google-closure-compiler-osx), [google-closure-compiler-linux](https://www.npmjs.com/package/google-closure-compiler-linux), and these are optional dependency of @tscc/tscc package. If you install one of them, `tscc` command will use it and it will provide significantly faster compile time in most cases.\n\n#### Rules imposed by closure compiler and tsickle\n\nAlthough TSCC tries to hide closure compiler specifics as much as it can, it's good to have some knowledge on it:\n - Read the [official documentation](https://developers.google.com/closure/compiler/) in order to get used to some notions used.\n - Not all code works directly with closure compiler (even if it is well-annotated). Read about [compiler assumptions](https://github.com/google/closure-compiler/wiki/Compiler-Assumptions) from their wiki; Basically, you should not use some dynamic nature of JS (the bad part!). Below are some common situations.\n   - Do not access an object's property with a string literal, as closure compiler won't try to rename it. If you access `foo.bar` in your code and also do `foo[\"bar\"]` at another part of the code, closure compiler may rename `foo.bar` to something like `foo.a` whereas the latter to `foo.bar`, so it will break the code.\n   - Circular references of Javascript modules are not allowed.\n   - Output module spec must have a single root module, making it a connected tree.[Ref](https://stackoverflow.com/questions/10395810/how-do-i-split-my-javascript-into-modules-using-googles-closure-compiler/10401030#10401030)\n - Tsickle [officially states](https://github.com/angular/tsickle#warning-work-in-progress) that it is still in experimental phase, and there are some caveats.\n   - Tsickle does not support annotation of all typescript types. For example, it does not convert indexed properties of Typescript to closure type, so if an interface is `declare`d with a property, such an interface won't be preserved -- keep an eye on tsickle warnings about unknown types. A good news is that closure compiler is still able to guess unknown types in most of cases, so it does not break the output code often.\n   - TS `namespace`s are not converted to something like those in closure library, so it does not benefit from closure compiler's property flattening. (Apparently google internally prevents use of [namespaces](https://github.com/angular/tsickle/issues/713#issuecomment-358806943).)\n - Some objects are present in Typescript but not in closure compiler, so sometimes you may need to provide externs to those manually.\n\n## Motivation\n\nThis project came out from the experience I have had with developing several Javascript apps,\n as frontend projects, browser extensions, and userscripts injected into client's browsers. In many cases \"content script\" are `eval`ed, so the source holds a string form of a JS code, so there was a rather strong motivation for squizing bundle size as much as one can in order to reduce client's memory footprint. Closure tools, albeit not \"trendy\", was the best tool for it -- the compiler is simply the best, Closure Templates directly compiles into JS and required runtime libraries are extremely small, and Closure Stylesheets provides class name shortening. However, incorporating all of these and at the same time providing an alternative build for debugging required a lot of work due to lack of support and community tooling.\n\nOn the other hand, currently most of available tooling using tsickle and closure compiler is limited to angular community. Tsickle is integrated into Angular's compiler and it provides some angular-specific code transformations (they are not enabled in TSCC). However, after all tsickle is a general-purpose transpiler. It seemed a pity that such a great tooling cannot benefit much broader audiences.\n\nTSCC is meant to provide a framework-agnostic tooling that can be used to bridge this gap.\n\n## Milestones\n\n - Integration with [Closure Templates](https://github.com/google/closure-templates) and [Closure Stylesheets](https://github.com/google/closure-stylesheets). Both tools produce Javascript sources that are meant to be consumed by Closure Compiler. As separate companion packages `tscc-templates` and `tscc-styles`, it will be possible to pipe these intermediate output to closure compiler, and produce typescript module declaration files that will provide type information of templates.\n - Providing an ergonomic API for using closure-annotated JS files together with transpiled TS files.\n - Providing an API for returning gulp stream.\n\n"
  },
  {
    "path": "jest.config.js",
    "content": "const {compilerOptions} = require('./tsconfig.json');\ncompilerOptions.strict = false;\n\nmodule.exports = {\n\tpreset: 'ts-jest',\n\ttestEnvironment: 'node',\n\ttestMatch: [\"**/test/**/*.ts\"],\n\ttestPathIgnorePatterns: ['/node_modules/', \"/sample/\"],\n\treporters: [\"default\", \"jest-junit\"],\n\tglobals: {\n\t\t'ts-jest': {\n\t\t\ttsconfig: compilerOptions\n\t\t}\n\t},\n\tsnapshotFormat: {\n\t\tescapeString: true,\n\t\tprintBasicPrototype: true\n\t}\n};\n"
  },
  {
    "path": "lerna.json",
    "content": "{\n  \"packages\": [\"packages/*\"],\n  \"version\": \"0.9.4\",\n  \"npmClient\": \"yarn\",\n  \"useWorkspaces\": true\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n\t\"name\": \"tscc\",\n\t\"version\": \"1.0.0\",\n\t\"private\": true,\n\t\"workspaces\": [\n\t\t\"packages/*\"\n\t],\n\t\"license\": \"MIT\",\n\t\"scripts\": {\n\t\t\"clean\": \"yarn lerna run clean\",\n\t\t\"tsc\": \"yarn lerna exec -- -- tsc\",\n\t\t\"refresh\": \"yarn lerna clean --yes; yarn clean; yarn lerna bootstrap; yarn tsc; cd packages/tscc; npm remove -g .; npm i -g .; rm -rf node_modules/@tscc; yarn link @tscc/tscc-spec\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/jest\": \"^29.2.0\",\n\t\t\"jest\": \"^29.2.1\",\n\t\t\"jest-junit\": \"^14.0.1\",\n\t\t\"lerna\": \"^6.0.1\",\n\t\t\"prettier\": \"^2.7.1\",\n\t\t\"ts-jest\": \"^29.0.3\",\n\t\t\"typescript\": \"~4.7.2\"\n\t},\n\t\"dependencies\": {}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/.npmignore",
    "content": "index.ts\n/src\ntest\nnode_modules\ntsconfig.json\nyarn.lock\nyarn-error.log\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/README.md",
    "content": "# rollup-plugin-tscc\n\nThis is a companion plugin for tscc which lets you perform an isomorphic build with rollup.\nThe code splitting strategy of Closure Compiler is rather different from any other bundling tools – it relies on providing an exact set of expected chunks and their interdependencies, whereas most of the available bundlers may create dynamic unnamed chunks. In some cases, the rigid approach of Closure Compiler is more suitable.\n\nThis plugin operates solely on the bundling level, and in particular, it does not require Typescript at all, so it can be used in any Javascript projects.\n\n## Usage\n\nFeed the output module dependency to `rollup-plugin-tscc` via [tscc spec file](https://github.com/theseanl/tscc#modules),\n[input files](https://rollupjs.org/guide/en/#input), [external](https://rollupjs.org/guide/en/#external), and output file names will be taken care by the plugin.\n\n```js\n// rollup.config.js\nexport default {\n    plugins: [\n        output: {\n            dir: '.'\n        }\n        require('@tscc/rollup-plugin-tscc')({\n            /* Contents of spec JSON */\n            modules: {\n                \"root-module\": \"./src/root-entry-file.js\",\n                \"deferred-chunk-1\": {\n                    \"entry\": \"./src/unimportant-feature-entry-file.js\",\n                    \"dependencies\": [\n                        \"root-module\"\n                    ]\n                }\n            }\n            // or, you can provide the above contents via a separate file.\n            specFile: \"path_to_spec_file.json\"\n        })\n    ]\n}\n```\n\nThen invoking rollup with the above will produce precisely two files, `root-module.js` and `deferred-chunk-1.js`.\n\n### Chunk format\n\nBy specifying `\"chunkFormat\": \"global\"` or `\"chunkFormat\": \"module\"`, you can designate how the code-splitted output chunks will reference variables and functions in another chunk. `\"global\"` corresponds to rollup's `\"iife\"`, and `\"module\"` corresponds to rollup's `\"es\"`.\n\n### External modules\n\nEspecially in code-splitting builds, it is required to use the spec file's [`external`](https://github.com/theseanl/tscc#external) field instead of the rollup input option's external property, because this information has to be propagated down to the plugin.\n\n### Dynamic imports\n\nIt does not support dynamic imports. It is mostly because Closure Compiler doesn't, and this package's goal is to\nprovide isomorphic build with closure compiler. Closure Compiler's wiki says it supports pass-through handling of `import()`, but it appears to be broken: https://github.com/google/closure-compiler/issues/3941 – apparently this ECMAScript feature is not widely used within Google. Closure Compiler's focus on _sequential_ nature of JS, which makes it extremely robust, doesn't seem to be a good fit with dynamic imports.\n\n---\n\nFor more detailed description, we refer to the [README of the main package](https://github.com/theseanl/tscc).\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/package.json",
    "content": "{\n  \"name\": \"@tscc/rollup-plugin-tscc\",\n  \"author\": \"theseanl\",\n  \"description\": \"A rollup plugin to use tscc module specification\",\n  \"keywords\": [\n    \"typescript\",\n    \"closure-compiler\",\n    \"tree-shaking\",\n    \"minify-javascript\"\n  ],\n  \"version\": \"0.9.4\",\n  \"license\": \"MIT\",\n  \"homepage\": \"https://github.com/theseanl/tscc\",\n  \"repository\": {\n    \"type\": \"url\",\n    \"url\": \"https://github.com/theseanl/tscc.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/theseanl/tscc\"\n  },\n  \"main\": \"./dist/index.js\",\n  \"scripts\": {\n    \"clean\": \"rm -rf dist\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"gitHead\": \"cb605b055c7947989d64daeb3d95c123c27c70c0\",\n  \"dependencies\": {\n    \"@tscc/tscc-spec\": \"^0.9.4\",\n    \"rollup\": \"^2.78.0\",\n    \"upath\": \"^2.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^18.11.2\"\n  }\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/MultiMap.ts",
    "content": "export default class MultiMap<K, V> {\n\tprivate map: Map<K, Set<V>> = new Map();\n\tadd(key: K, value?: V) {\n\t\tlet ar: Set<V>;\n\t\tif (!this.map.has(key)) {\n\t\t\tar = new Set();\n\t\t\tthis.map.set(key, ar);\n\t\t} else {\n\t\t\tar = this.map.get(key)!;\n\t\t}\n\t\tif (arguments.length > 1) {\n\t\t\tar.add(value!);\n\t\t}\n\t}\n\tfind(key: K, value: V): boolean {\n\t\tif (!this.findKey(key)) return false;\n\t\tlet values = this.map.get(key)!;\n\t\treturn values.has(value);\n\t}\n\tfindKey(key: K): boolean {\n\t\treturn this.map.has(key);\n\t}\n\tfindValue(value: V): K | undefined {\n\t\tfor (let [key, values] of this.map) {\n\t\t\tif (values.has(value)) return key;\n\t\t}\n\t}\n\tget(key: K): V[] {\n\t\tif (!this.map.has(key)) return [];\n\t\treturn [...this.map.get(key)!];\n\t}\n\tputAll(key: K, values: Iterable<V>) {\n\t\tthis.map.set(key, new Set(values));\n\t\treturn this;\n\t}\n\t*[Symbol.iterator]() {\n\t\tfor (let [key, values] of this.map) {\n\t\t\tfor (let value of values) {\n\t\t\t\tyield [key, value];\n\t\t\t}\n\t\t}\n\t}\n\titerateValues(key: K): IterableIterator<V> | undefined {\n\t\tlet values = this.map.get(key);\n\t\tif (values) return values.values();\n\t}\n\tkeys() {\n\t\treturn this.map.keys();\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\tstatic fromObject<V>(object: {[key: string]: V[]}): MultiMap<string, V> {\n\t\tconst map = new MultiMap<string, V>();\n\t\tfor (let [key, values] of Object.entries(object)) {\n\t\t\tmap.add(key);\n\t\t\tfor (let value of values) {\n\t\t\t\tmap.add(key, value);\n\t\t\t}\n\t\t}\n\t\treturn map;\n\t}\n\tstatic toObject<K, V>(\n\t\tmap: MultiMap<K, V>,\n\t\tstringifyKey: (k: K) => string = String,\n\t\tstringifyValue: (v: V) => string = String\n\t) {\n\t\tconst out: {[key: string]: string[]} = {};\n\t\tfor (let key of map.keys()) {\n\t\t\tout[stringifyKey(key)] = [...map.iterateValues(key)!].map(stringifyValue);\n\t\t}\n\t\treturn out;\n\t}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/goog_shim_mixin.ts",
    "content": "/**\n * @fileoverview Provides a mixin for Rollup plugins that loads shim files for default libraries.\n * These are goog.goog and goog.reflect, which are always included if one is bundling with\n * @tscc/tscc.\n */\nimport {Plugin, FunctionPluginHooks} from 'rollup';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nconst SHIM_ROOT = path.resolve(__dirname, \"../third_party/closure_library\");\n\nconst moduleNameToShim = new Map([\n\t[\"goog:goog\", fs.readFileSync(path.join(SHIM_ROOT, \"goog_shim.js\"), \"utf8\")],\n\t[\"goog:goog.reflect\", fs.readFileSync(path.join(SHIM_ROOT, \"reflect_shim.js\"), \"utf8\")]\n]);\n\n// Rollup convention, see https://rollupjs.org/guide/en/#conventions\nconst PREFIX = \"\\0tscc\\0\";\n\n// Interlaces a plugin loading shim files with an existing plugin.\nexport function googShimMixin<T extends {resolveId: FunctionPluginHooks[\"resolveId\"], load: FunctionPluginHooks[\"load\"]}>(plugin: T): T {\n\tconst {resolveId, load} = plugin;\n\tplugin.resolveId = function (id, importer) {\n\t\tif (moduleNameToShim.has(id)) return PREFIX + id;\n\t\treturn Reflect.apply(resolveId!, this, arguments);\n\t}\n\tplugin.load = function (id) {\n\t\tif (id.startsWith(PREFIX)) return moduleNameToShim.get(id.substring(PREFIX.length));\n\t\treturn Reflect.apply(load!, this, arguments);\n\t}\n\treturn plugin;\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/index.ts",
    "content": "import {IInputTsccSpecJSON} from '@tscc/tscc-spec';\nimport * as rollup from 'rollup';\nimport {googShimMixin} from './goog_shim_mixin';\nimport {ChunkMergeError, ChunkMerger} from './merge_chunks';\nimport computeChunkAllocation, {ChunkSortError} from './sort_chunks';\nimport ITsccSpecRollupFacade from './spec/ITsccSpecRollupFacade';\nimport TsccSpecRollupFacade from './spec/TsccSpecRollupFacade';\nimport path = require('path');\n\nconst pluginImpl: (options: IInputTsccSpecJSON) => rollup.Plugin = (pluginOptions) => {\n\tconst spec: ITsccSpecRollupFacade = TsccSpecRollupFacade.loadSpec(pluginOptions);\n\n\tconst isManyModuleBuild = spec.getOrderedModuleSpecs().length > 1;\n\tconst globals = spec.getRollupExternalModuleNamesToGlobalMap();\n\n\t/* Plugin methods start */\n\tconst name = \"rollup-plugin-tscc\";\n\tconst options: rollup.Plugin[\"options\"] = (options = {}) => {\n\t\t// Add entry files read fom tsccconfig\n\t\toptions.input = spec.getRollupOutputNameToEntryFileMap();\n\t\toptions.external = spec.getExternalModuleNames();\n\t\treturn options;\n\t};\n\tconst outputOptions: rollup.Plugin[\"outputOptions\"] = (outputOptions = {}) => {\n\t\toutputOptions.dir = '.';\n\t\toutputOptions.entryFileNames = \"[name].js\";\n\t\toutputOptions.chunkFileNames = \"_\"; // rollup makes these unique anyway.\n\t\toutputOptions.globals = globals;\n\t\tif (isManyModuleBuild) {\n\t\t\t// For many-module build, currently only iife builds are available.\n\t\t\t// Intermediate build format is 'es'.\n\t\t\toutputOptions.format = 'es';\n\t\t} else {\n\t\t\toutputOptions.format = spec.getRollupOutputModuleFormat();\n\t\t}\n\t\treturn outputOptions;\n\t};\n\tconst resolveId: rollup.ResolveIdHook = (id, importer) => {\n\t\t/**\n\t\t * Getting absolute paths for external modules working has been pretty tricky. I haven't\n\t\t * tracked down the exact cause, but sometimes external modules' paths are relative to CWD,\n\t\t * sometimes relative to the common demoninator of files (check inputBase of rollup source).\n\t\t * It seems that this is consistent internally, but not when user-provided absolute paths\n\t\t * are involved. In particular the \"external-modules-in-many-module-build\" test case fails.\n\t\t *\n\t\t * Prior to rollup 2.44.0, we have used \"paths\" output option to force rollup to keep use\n\t\t * absolute paths for external modules internally. \"paths\" option is mainly intended to\n\t\t * replace external module paths to 3rd-party CDN urls in the bundle output, so our use is\n\t\t * more like an 'exploit'. One place where one replaces an absolute path to a relative path\n\t\t * is `ExternalModule.setRenderPath` which sets `renderPath` which is later resolved\n\t\t * relatively from certain path to compute final path in import statements. If\n\t\t * outputOption.path function is provided, the value produced by this function is used as\n\t\t * `renderPath` instead, so we are hooking into it so that `renderPath` is set to an\n\t\t * absolute path.\n\t\t *\n\t\t * Since 2.44.0, it has supported returning {external: 'absolute'} value from `resolveId`\n\t\t * hook, which seems to be achieving what we have done using `output.paths` option. In\n\t\t * particular it disables rollup's 'helpful' renormalization of paths, see\n\t\t * https://github.com/rollup/rollup/blob/a8647dac0fe46c86183be8596ef7de25bc5b4e4b/src/ExternalModule.ts#L94,\n\t\t * https://github.com/rollup/rollup/blob/983c0cac83727a13af834fe79dfeef89da4fb84b/src/Chunk.ts#L699.\n\t\t * The related PR is https://github.com/rollup/rollup/pull/4021.\n\t\t *\n\t\t * These paths are then used in intermediate chunks, and will not be emitted in final bundle\n\t\t * due to the helpful renormalization which we do not disable in the secondary bundling.\n\t\t */\n\t\tif (importer) {\n\t\t\tconst resolved = path.resolve(path.dirname(importer), id);\n\t\t\tif (resolved in globals) {\n\t\t\t\treturn {id: resolved, external: \"absolute\"};\n\t\t\t}\n\t\t}\n\t\tlet depsPath = spec.resolveRollupExternalDeps(id);\n\t\tif (depsPath) {\n\t\t\treturn path.resolve(process.cwd(), depsPath);\n\t\t\t// Using 'posix' does not work well with rollup internals\n\t\t}\n\t};\n\t// Returning null defers to other load functions, see https://rollupjs.org/guide/en/#load\n\tconst load: rollup.LoadHook = (id: string) => null;\n\n\tconst generateBundle = handleError<NonNullable<rollup.FunctionPluginHooks[\"generateBundle\"]>>(async function (\n\t\tthis: rollup.PluginContext, options, bundle, isWrite\n\t) {\n\t\t// Quick path for single-module builds\n\t\tif (spec.getOrderedModuleSpecs().length === 1) return;\n\n\t\t// Get entry dependency from spec\n\t\tconst entryDeps = spec.getRollupOutputNameDependencyMap();\n\n\t\t// Get chunk dependency from rollup.OutputBundle\n\t\tconst chunkDeps: {[chunkName: string]: string[]} = {};\n\t\tfor (let [fileName, chunkInfo] of Object.entries(bundle)) {\n\t\t\t// TODO This is a possible source of conflicts with other rollup plugins. Some plugins\n\t\t\t// may add unexpected chunks. In general, it is not clear what TSCC should do in such\n\t\t\t// cases. A safe way would be to strip out such chunks and deal only with chunks that\n\t\t\t// are expected to be emitted. We may trim such chunks here.\n\t\t\tif (!isChunk(chunkInfo)) continue;\n\t\t\tchunkDeps[fileName] = [];\n\t\t\tfor (let imported of chunkInfo.imports) {\n\t\t\t\tchunkDeps[fileName].push(imported);\n\t\t\t}\n\t\t}\n\n\t\t// Compute chunk allocation\n\t\tconst chunkAllocation = computeChunkAllocation(chunkDeps, entryDeps);\n\t\tconst chunkMerger = new ChunkMerger(chunkAllocation, bundle, globals);\n\t\t/**\n\t\t * Hack `bundle` object, as described in {@link https://github.com/rollup/rollup/issues/2938}\n\t\t */\n\t\t// 0. Merge intermediate chunks to appropriate entry chunk\n\t\tconst mergedChunks = spec.getRollupOutputModuleFormat() === 'iife' ?\n\t\t\tawait Promise.all([...entryDeps.keys()]\n\t\t\t\t.map((entry: string) => chunkMerger.performSingleEntryBuild(entry, 'iife'))) :\n\t\t\tawait chunkMerger.performCodeSplittingBuild('es');\n\t\t// 1. Delete keys for intermediate chunks\n\t\tfor (let entry of chunkAllocation.keys()) {\n\t\t\tfor (let chunk of chunkAllocation.iterateValues(entry)!) {\n\t\t\t\tdelete bundle[chunk];\n\t\t\t}\n\t\t}\n\t\t// 2. Add the merged chunks to the bundle object\n\t\tfor (let chunk of mergedChunks) {\n\t\t\tbundle[chunk.fileName] = chunk;\n\t\t}\n\n\t\treturn;\n\t});\n\n\treturn googShimMixin({name, generateBundle, options, outputOptions, resolveId, load});\n};\n\nfunction isChunk(output: rollup.OutputChunk | rollup.OutputAsset): output is rollup.OutputChunk {\n\treturn output.type === 'chunk';\n}\n\nfunction handleError<H extends (this: rollup.PluginContext, ..._: any[]) => unknown>(hook: H): H {\n\treturn <H>async function () {\n\t\ttry {\n\t\t\treturn await Reflect.apply(hook, this, arguments);\n\t\t} catch (e) {\n\t\t\t// Handle known type of errors\n\t\t\tif (e instanceof ChunkSortError || e instanceof ChunkMergeError) {\n\t\t\t\tthis.error(e.message);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport default pluginImpl;\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/merge_chunks.ts",
    "content": "import * as rollup from 'rollup';\nimport {googShimMixin} from './goog_shim_mixin';\nimport MultiMap from './MultiMap';\nimport path = require('path');\nimport upath = require('upath');\n\ntype CodeSplittableModuleFormat = Exclude<rollup.ModuleFormat, 'iife' | 'umd'>;\n\n// Merge chunks to their allocated entry chunk.\n// For each entry module, create a facade module that re-exports everything from chunks\n// allocated to it, and call rollup to create a merged bundle.\n// Each chunk's export object is exported as a separate namespace, whose name is chosen\n// so as not to collide with exported names of the entry module. We pass this namespace\n// as rollup's global option in order to reference those from other chunks.\nexport class ChunkMerger {\n\tprivate entryModuleNamespaces!: Map<string, string> // Initialized in getBundleOutput call.\n\tprivate chunkNamespaces!: Map<string, string>\n\tprivate unresolveChunk!: Map<string, string>;\n\tconstructor(\n\t\tprivate chunkAllocation: MultiMap<string, string>,\n\t\tprivate bundle: Readonly<rollup.OutputBundle>,\n\t\tprivate globals?: {[id: string]: string}\n\t) {\n\t\tthis.populateEntryModuleNamespaces();\n\t\tthis.populateUnresolveChunk();\n\t}\n\tprivate resolveGlobalForPrimaryBuild(id: string) {\n\t\tif (typeof this.globals !== 'object') return;\n\t\tif (!this.globals.hasOwnProperty(id)) return;\n\t\treturn this.globals[id];\n\t}\n\tprivate populateEntryModuleNamespaces() {\n\t\tthis.entryModuleNamespaces = new Map();\n\t\tfor (let entry of this.chunkAllocation.keys()) {\n\t\t\tlet fileName = path.basename(entry, '.js');\n\t\t\tlet fileNamespace = fileName.replace(/[^0-9a-zA-Z_$]/g, '_').replace(/^[^a-zA-Z_$]/, '_');\n\t\t\tthis.entryModuleNamespaces.set(entry, fileNamespace);\n\t\t}\n\t}\n\tprivate populateChunkNamespaces() {\n\t\tconst DOLLAR_SIGN = \"$\";\n\t\tthis.chunkNamespaces = new Map();\n\t\tfor (let entry of this.chunkAllocation.keys()) {\n\t\t\tlet counter = -1;\n\t\t\tfor (let chunk of this.chunkAllocation.iterateValues(entry)!) {\n\t\t\t\tif (entry === chunk) continue;\n\t\t\t\tlet namesExportedByEntry = (this.bundle[entry] as rollup.OutputChunk).exports;\n\t\t\t\tdo {\n\t\t\t\t\tcounter++\n\t\t\t\t} while (namesExportedByEntry.includes(DOLLAR_SIGN + counter))\n\t\t\t\tthis.chunkNamespaces.set(chunk, DOLLAR_SIGN + counter);\n\t\t\t}\n\t\t}\n\t}\n\tprivate populateUnresolveChunk() {\n\t\tthis.unresolveChunk = new Map();\n\t\tfor (let [entry, chunk] of this.chunkAllocation) {\n\t\t\tthis.unresolveChunk.set(path.resolve(chunk), chunk);\n\t\t}\n\t}\n\tstatic readonly FACADE_MODULE_ID = `facade.js`;\n\tprivate createFacadeModuleCode(entry: string): string {\n\t\tconst importStmts: string[] = [];\n\t\tconst exportStmts: string[] = [];\n\t\t// nodejs specification only allows posix-style path separators in module IDs.\n\t\texportStmts.push(`export * from '${upath.toUnix(entry)}'`);\n\t\tfor (let chunk of this.chunkAllocation.iterateValues(entry)!) {\n\t\t\tif (chunk === entry) continue;\n\t\t\tlet chunkNs = this.chunkNamespaces.get(chunk);\n\t\t\timportStmts.push(`import * as ${chunkNs} from '${upath.toUnix(chunk)}'`);\n\t\t\texportStmts.push(`export { ${chunkNs} }`);\n\t\t}\n\t\tconst facadeModuleCode = [...importStmts, ...exportStmts].join('\\n');\n\t\treturn facadeModuleCode;\n\t}\n\tprivate createFacadeModuleLoaderPlugin(entry: string): rollup.Plugin {\n\t\tconst resolveId: rollup.ResolveIdHook = (id, importer) => {\n\t\t\tif (id === ChunkMerger.FACADE_MODULE_ID) return id;\n\t\t};\n\t\tconst load: rollup.LoadHook = (id) => {\n\t\t\tif (id === ChunkMerger.FACADE_MODULE_ID) return this.createFacadeModuleCode(entry);\n\t\t}\n\t\tconst name = \"tscc-facade-loader\";\n\t\treturn {name, resolveId, load};\n\t}\n\tprivate createLoaderPlugin(shouldLoadID: (id: string) => boolean): rollup.Plugin {\n\t\tconst resolveId: rollup.ResolveIdHook = (id, importer) => {\n\t\t\tif (this.resolveGlobalForPrimaryBuild(id)) {return {id, external: true}}\n\t\t\tif (shouldLoadID(id)) return id;\n\t\t\tif (importer) {\n\t\t\t\tconst resolved = path.resolve(path.dirname(importer), id);\n\t\t\t\tlet unresolved = this.unresolveChunk.get(resolved);\n\t\t\t\tif (typeof unresolved === 'string') {\n\t\t\t\t\tif (shouldLoadID(unresolved)) return unresolved;\n\t\t\t\t\treturn {id: resolved, external: \"absolute\"};\n\t\t\t\t}\n\t\t\t}\n\t\t\t// This code path should not be taken.\n\t\t\tChunkMerger.throwUnexpectedModuleError(id, importer);\n\t\t};\n\t\tconst load: rollup.LoadHook = (id) => {\n\t\t\tif (shouldLoadID(id)) {\n\t\t\t\tlet outputChunk = this.bundle[id] as rollup.OutputChunk;\n\t\t\t\treturn {\n\t\t\t\t\tcode: outputChunk.code,\n\t\t\t\t\tmap: toInputSourceMap(outputChunk.map)\n\t\t\t\t};\n\t\t\t}\n\t\t\t// This code path should not be taken.\n\t\t\tChunkMerger.throwUnexpectedModuleError(id);\n\t\t};\n\t\tconst name = \"tscc-merger\";\n\t\treturn googShimMixin({name, resolveId, load});\n\t}\n\tprivate resolveGlobalForSecondaryBuild(id: string): string {\n\t\tif (this.resolveGlobalForPrimaryBuild(id)) return this.globals![id]!;\n\t\tif (path.isAbsolute(id)) {\n\t\t\tid = this.unresolveChunk.get(id) || ChunkMerger.throwUnexpectedModuleError(id);\n\t\t}\n\t\tlet allocated = this.chunkAllocation.findValue(id);\n\t\tif (allocated === undefined) ChunkMerger.throwUnexpectedModuleError(id);\n\t\t// The below case means that the chunk being queried shouldn't be global. Rollup expects\n\t\t// outputOption.globals to return its input unchanged for non-global module ids, but this\n\t\t// code path won't and shouldn't be taken.\n\t\t// if (allocated === this.entry) ChunkMerger.throwUnexpectedModuleError(id);\n\t\t// Resolve to <namespace-of-entry-module-that-our-chunk-is-allocated>.<namespace-of-our-chunk>\n\t\tlet ns = this.entryModuleNamespaces.get(allocated)!;\n\t\tif (allocated !== id) ns += '.' + this.chunkNamespaces.get(id);\n\t\treturn ns;\n\t}\n\t/**\n\t * Merges chunks for a single entry point, making output bundles reference each other by\n\t * variables in global scope. We control global variable names via `output.globals` option.\n\t * TODO: inherit outputOption provided by the caller\n\t */\n\tasync performSingleEntryBuild(entry: string, format: rollup.ModuleFormat): Promise<rollup.OutputChunk> {\n\t\tthis.populateChunkNamespaces();\n\t\tconst myBundle = await rollup.rollup({\n\t\t\tinput: ChunkMerger.FACADE_MODULE_ID,\n\t\t\tplugins: [\n\t\t\t\tthis.createFacadeModuleLoaderPlugin(entry),\n\t\t\t\tthis.createLoaderPlugin(id => this.chunkAllocation.find(entry, id))\n\t\t\t]\n\t\t});\n\t\tconst {output} = await myBundle.generate({\n\t\t\t...ChunkMerger.baseOutputOption,\n\t\t\tname: this.entryModuleNamespaces.get(entry),\n\t\t\tfile: ChunkMerger.FACADE_MODULE_ID,\n\t\t\tformat,\n\t\t\tglobals: (id) => this.resolveGlobalForSecondaryBuild(id),\n\t\t});\n\t\tif (output.length > 1) {\n\t\t\tChunkMerger.throwUnexpectedChunkInSecondaryBundleError(output);\n\t\t}\n\t\tconst mergedBundle = output[0];\n\n\t\t// 0. Fix fileName to that of entry file\n\t\tmergedBundle.fileName = entry;\n\t\t// 1. Remove facadeModuleId, as it would point to our virtual module\n\t\tmergedBundle.facadeModuleId = null;\n\t\t// 2. Fix name to that of entry file\n\t\tconst name = (<rollup.OutputChunk>this.bundle[entry]).name;\n\t\tObject.defineProperty(mergedBundle, 'name', {\n\t\t\tget() {return name;} // TODO: FIXME\n\t\t});\n\t\t// 3. Remove virtual module from .modules\n\t\tdelete mergedBundle.modules[ChunkMerger.FACADE_MODULE_ID];\n\n\t\treturn mergedBundle\n\t}\n\t/**\n\t * We perform the usual rollup bundling which does code splitting. Note that this is unavailable\n\t * for iife and umd builds. In order to control which chunks are emitted, we control them by\n\t * feeding `chunkAllocation` information to rollup via `output.manualChunks` option.\n\t * TODO: inherit outputOption provided by the caller\n\t */\n\tasync performCodeSplittingBuild(format: CodeSplittableModuleFormat) {\n\t\tconst myBundle = await rollup.rollup({\n\t\t\tinput: [...this.chunkAllocation.keys()],\n\t\t\tplugins: [\n\t\t\t\tthis.createLoaderPlugin(id => !!this.bundle[id])\n\t\t\t],\n\t\t\t// If this is not set, rollup may create \"facade modules\" for each of entry modules,\n\t\t\t// which somehow \"leaks\" from `manualChunks`. On the other hand, setting this may make\n\t\t\t// rollup to drop `export` statements in entry files from final chunks. However, Closure\n\t\t\t// Compiler does this anyway, so it is ok in terms of the goal of this plugin, which\n\t\t\t// aims to provide an isomorphic builds.\n\t\t\tpreserveEntrySignatures: false\n\t\t});\n\t\tconst {output} = await myBundle.generate({\n\t\t\t...ChunkMerger.baseOutputOption,\n\t\t\tdir: '.', format,\n\t\t\tmanualChunks: (id: string) => {\n\t\t\t\tlet allocatedEntry = this.chunkAllocation.findValue(id);\n\t\t\t\tif (!allocatedEntry) ChunkMerger.throwUnexpectedModuleError(id);\n\t\t\t\treturn trimExtension(allocatedEntry);\n\t\t\t},\n\t\t});\n\t\tif (output.length > this.chunkAllocation.size) {\n\t\t\tChunkMerger.throwUnexpectedChunkInSecondaryBundleError(output);\n\t\t}\n\t\tfor (let outputChunk of output) {\n\t\t\t// These chunks are treated as non-entry chunks, which are subject to different naming\n\t\t\t// convention. This in particular removes all the paths components and retains only the\n\t\t\t// basename part. This is undesirable, so we restore the fileName from facadeModuleId\n\t\t\t// here.\n\t\t\tlet {facadeModuleId} = outputChunk as rollup.OutputChunk;\n\t\t\tif (!facadeModuleId) throw new ChunkMergeError(`Output file name in unrecoverable for a module ${outputChunk.fileName}`);\n\t\t\toutputChunk.fileName = facadeModuleId;\n\t\t}\n\t\treturn output as rollup.OutputChunk[];\n\t}\n\tprivate static readonly baseOutputOption: rollup.OutputOptions = {\n\t\tinterop: 'esModule',\n\t\tesModule: false,\n\t\tfreeze: false\n\t}\n\tprivate static throwUnexpectedModuleError(id: string, importer = \"\"): never {\n\t\tthrow new ChunkMergeError(`Unexpected module in primary bundle output: ${id} ${importer}`);\n\t}\n\tprivate static throwUnexpectedChunkInSecondaryBundleError(output: (rollup.OutputChunk | rollup.OutputAsset)[]) {\n\t\tthrow new ChunkMergeError(`Unexpected chunk in secondary bundle output: ${output[output.length - 1].name}. Please report this error.`)\n\t}\n}\n\nexport class ChunkMergeError extends Error {}\n\n/**\n * Converts SourceMap type used by OutputChunk type to ExistingRawSourceMap type used by load hooks.\n */\nfunction toInputSourceMap(sourcemap: rollup.SourceMap | undefined): rollup.ExistingRawSourceMap | undefined {\n\tif (!sourcemap) return;\n\treturn {...sourcemap};\n}\n\nfunction trimExtension(name: string) {\n\treturn name.slice(0, name.length - path.extname(name).length)\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/sort_chunks.ts",
    "content": "/**\n * @fileoverview Rollup generates at most one chunk per each combination of entry points. In our case\n * of emulating closure compiler's bundling, entry points are also nodes of a graph.\n * We determine what chunk should included in what output module in which order.\n */\nimport {DirectedTreeWithOrdering, DirectedTreeWithLeafs} from '@tscc/tscc-spec'\nimport MultiMap from './MultiMap';\n\n/**\n * This algorithm is based on an assumption that rollup creates at most one chunk for\n * each combination of entry points.\n */\nexport default function computeChunkAllocation(\n\tchunkImportedMap: {[chunkName: string]: string[] /* imported chunk names */},\n\tentryMap: MultiMap<string, string> /* This is assumed to be sorted, root-to-leaf. */\n): MultiMap<string, string> {\n\tconst chunkMap = MultiMap.fromObject(chunkImportedMap);\n\n\t// ChunkGraph is a directed tree where there is an edge from module A to a module B\n\t// iff B imports A.\n\tconst chunkGraph = new DirectedTreeWithLeafs<string>();\n\tfor (let chunkName of chunkMap.keys()) {\n\t\tchunkGraph.addNodeById(chunkName); // Make sure that chunks without dependencies get added\n\t}\n\tfor (let [chunkName, importedName] of chunkMap) {\n\t\t// Skip dependencies among entry modules\n\t\tif (entryMap.findKey(chunkName) && entryMap.findKey(importedName)) continue;\n\t\tchunkGraph.addEdgeById(importedName, chunkName);\n\t}\n\tchunkGraph.populateLeafs();\n\tconst sortedChunks = chunkGraph.sort();\n\n\tconst leafGraph = new DirectedTreeWithOrdering<string>()\n\tfor (let entry of entryMap.keys()) {\n\t\tleafGraph.addNodeById(entry); // Add nodes by order - root to leaf\n\t}\n\tfor (let [aModule, prerequisiteModule] of entryMap) {\n\t\tleafGraph.addEdgeById(prerequisiteModule, aModule);\n\t}\n\n\tleafGraph.populateDecendents();\n\n\tconst leafToDependents = new MultiMap<string, string>();\n\n\tfor (let chunkName of chunkMap.keys()) {\n\t\tlet infimum = leafGraph.getInfimum(chunkGraph.getLeafsOfNode(chunkName));\n\t\tif (infimum === null) {throw new ChunkSortError(`Cannot find a common root of a chunk`);}\n\t\tleafToDependents.add(infimum, chunkName);\n\t}\n\tfor (let entry of entryMap.keys()) {\n\t\tlet sorted = leafToDependents.get(entry).sort((chunk1, chunk2) => {\n\t\t\t// As the same order as they appear in sortedChunks (root-to-leaf)\n\t\t\treturn sortedChunks.indexOf(chunk1) - sortedChunks.indexOf(chunk2);\n\t\t});\n\t\tleafToDependents.putAll(entry, sorted);\n\t}\n\treturn leafToDependents;\n}\n\nexport class ChunkSortError extends Error {}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/spec/ITsccSpecRollupFacade.ts",
    "content": "import {ITsccSpec} from '@tscc/tscc-spec'\nimport MultiMap from '../MultiMap';\nimport {ModuleFormat} from 'rollup';\n\nexport default interface ITsccSpecRollupFacade extends ITsccSpec {\n\tresolveRollupExternalDeps(id: string): string\n\t/**\n\t * It must respect prefix option of the spec.\n\t */\n\tgetRollupOutputNameToEntryFileMap(): {[name: string]: string}\n\t/**\n\t * Maps an entry module's fileName to other entry module's fileNames which the module\n\t * depends on. Here filenames are those which bundles generated by rollup will be written to.\n\t * This map is supposed to be ordered by an order that is provided by user, or yet topologically\n\t * sorted.\n\t */\n\tgetRollupOutputNameDependencyMap(): MultiMap<string, string>\n\t/**\n\t * Returns a key-value pair that can be directly used to rollup output.globals option.\n\t */\n\tgetRollupExternalModuleNamesToGlobalMap(): {[moduleName: string]: string}\n\t/**\n\t * Returns a module format that final bundles will use, based on spec.chunkFormat.\n\t */\n\tgetRollupOutputModuleFormat(): ModuleFormat\n}\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/src/spec/TsccSpecRollupFacade.ts",
    "content": "import {TsccSpec, TsccSpecError} from '@tscc/tscc-spec';\nimport ITsccSpecRollupFacade from './ITsccSpecRollupFacade'\nimport MultiMap from '../MultiMap';\nimport {ModuleFormat} from 'rollup';\n\nexport default class TsccSpecRollupFacade extends TsccSpec implements ITsccSpecRollupFacade {\n\tresolveRollupExternalDeps(moduleId: string) {\n\t\treturn ''; // Just a stub\n\t}\n\tprotected getOutputPrefix(target: \"cc\" | \"rollup\"): string {\n\t\tlet prefix = this.tsccSpec.prefix;\n\t\tif (typeof prefix === 'undefined') return '';\n\t\tif (typeof prefix === 'string') return prefix;\n\t\treturn prefix[target];\n\t}\n\tprivate getResolvedRollupPrefix() {\n\t\tlet prefix = this.getOutputPrefix(\"rollup\");\n\t\tlet resolvedPrefix = this.relativeFromCwd(prefix);\n\t\tif (resolvedPrefix.startsWith('.')) {\n\t\t\tthrow new TsccSpecError(\n\t\t\t\t`Output file prefix ${resolvedPrefix} escapes the current working directory`\n\t\t\t);\n\t\t}\n\t\treturn resolvedPrefix;\n\t}\n\tprivate rollupPrefix = this.getResolvedRollupPrefix();\n\tprivate addPrefix(name: string) {\n\t\treturn this.rollupPrefix + name;\n\t}\n\tprivate addPrefixAndExtension(name: string) {\n\t\treturn this.rollupPrefix + name + '.js';\n\t}\n\tgetRollupOutputNameToEntryFileMap() {\n\t\tlet out: {[name: string]: string} = {};\n\t\tfor (let {moduleName, entry} of this.getOrderedModuleSpecs()) {\n\t\t\t// If entryFile is a relative path, resolve it relative to the path of tsccSpecJSON.\n\t\t\tout[this.addPrefix(moduleName)] = this.absolute(entry);\n\t\t}\n\t\treturn out;\n\t}\n\tgetRollupOutputNameDependencyMap() {\n\t\tlet out = new MultiMap<string, string>();\n\t\tfor (let {moduleName, dependencies} of this.getOrderedModuleSpecs()) {\n\t\t\t// we set outputOption.entryFileName as [name].js - gotta add .js to match\n\t\t\t// an expected output file name.\n\t\t\tout.putAll(\n\t\t\t\tthis.addPrefixAndExtension(moduleName),\n\t\t\t\tdependencies.map(this.addPrefixAndExtension, this));\n\t\t}\n\t\treturn out\n\t}\n\tgetRollupExternalModuleNamesToGlobalMap() {\n\t\tconst globals: {[moduleName: string]: string} = {};\n\t\tlet external = this.getExternalModuleDataMap();\n\t\tfor (let [moduleName, {globalName}] of external) {\n\t\t\tglobals[moduleName] = globalName;\n\t\t}\n\t\treturn globals;\n\t}\n\tgetRollupOutputModuleFormat(): ModuleFormat {\n\t\tswitch (this.tsccSpec.chunkFormat) {\n\t\t\tcase 'module':\n\t\t\t\treturn 'es';\n\t\t\tcase 'global':\n\t\t\tdefault:\n\t\t\t\treturn 'iife';\n\t\t}\n\t}\n}\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/__snapshots__/golden_test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Golden Tests: external-modules/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/external-modules/golden/generated_entry.js 1`] = `\n\"(function (externalInNodeModules, externalWithFilePaths) {\n\t'use strict';\n\n\tconsole.log(externalInNodeModules.someProperty);\n\tconsole.log(externalWithFilePaths.anotherProperty);\n\n})(externalInNodeModules, externalWithFilePaths);\n\"\n`;\n\nexports[`Golden Tests: external-modules-in-many-module-build/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/golden/generated_dependent.js 1`] = `\n\"(function (_, b) {\n\t'use strict';\n\n\t_.c();\n\t_.e();\n\tconsole.log(b);\n\n})(generated_entry.$0, b);\n\"\n`;\n\nexports[`Golden Tests: external-modules-in-many-module-build/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/golden/generated_entry.js 1`] = `\n\"var generated_entry = (function (exports, c, a) {\n\t'use strict';\n\n\tfunction common(n) {\n\t\tconsole.log(\\\\\"common\\\\\");\n\t}\n\tconsole.log(c.a);\n\n\tfunction entry() {\n\t\tcommon();\n\t\tconsole.log(\\\\\"entry\\\\\");\n\t}\n\n\tentry();\n\tconsole.log(a);\n\n\tvar _ = {\n\t\t__proto__: null,\n\t\tc: common,\n\t\te: entry\n\t};\n\n\texports.$0 = _;\n\texports.entry = entry;\n\n\treturn exports;\n\n})({}, c, a);\n\"\n`;\n\nexports[`Golden Tests: goog-shim/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/goog-shim/golden/generated_dependent.js 1`] = `\n\"(function (_) {\n\t'use strict';\n\n\t/**\n\t * @fileoverview Hand-modified shim file for Closure Library \\`goog/reflect.js\\`. References to the\n\t * global \\`goog\\` variables have been removed.\n\t */\n\n\tfunction objectProperty(prop, object) {\n\t\treturn prop;\n\t}\n\n\tvar dictionary = {\n\t\t\\\\\"key\\\\\": \\\\\"value\\\\\"\n\t};\n\n\tif (_.g.name === objectProperty(\\\\\"key\\\\\")) {\n\t\tconsole.log(dictionary[_.g.name]);\n\t}\n\n})(generated_entry.$0);\n\"\n`;\n\nexports[`Golden Tests: goog-shim/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/goog-shim/golden/generated_entry.js 1`] = `\n\"var generated_entry = (function (exports) {\n\t'use strict';\n\n\t/**\n\t * @fileoverview Hand-modified shim file for Closure Library \\`goog/goog.js\\`. References to the\n\t * global \\`goog\\` variables have been removed.\n\t */\n\tconst global = self; // Use rollup \\\\\"context\\\\\" option to prevent \\`this\\` rewrite\n\n\tlet DEBUG = true;\n\n\tfunction isDebugging() {\n\t\treturn DEBUG;\n\t}\n\n\t{\n\t\tconsole.log(\\\\\"Debugging\\\\\");\n\t}\n\n\tvar _ = {\n\t\t__proto__: null,\n\t\tg: global,\n\t\ti: isDebugging\n\t};\n\n\texports.$0 = _;\n\texports.isDebugging = isDebugging;\n\n\treturn exports;\n\n})({});\n\"\n`;\n\nexports[`Golden Tests: goog-shim/tscc.spec.module.json module: packages/rollup-plugin-tscc/test/sample/goog-shim/golden/generated_dependent.js 1`] = `\n\"import { g as global } from './generated_entry.js';\n\n/**\n * @fileoverview Hand-modified shim file for Closure Library \\`goog/reflect.js\\`. References to the\n * global \\`goog\\` variables have been removed.\n */\n\nfunction objectProperty(prop, object) {\n\treturn prop;\n}\n\nvar dictionary = {\n\t\\\\\"key\\\\\": \\\\\"value\\\\\"\n};\n\nif (global.name === objectProperty(\\\\\"key\\\\\")) {\n\tconsole.log(dictionary[global.name]);\n}\n\"\n`;\n\nexports[`Golden Tests: goog-shim/tscc.spec.module.json module: packages/rollup-plugin-tscc/test/sample/goog-shim/golden/generated_entry.js 1`] = `\n\"/**\n * @fileoverview Hand-modified shim file for Closure Library \\`goog/goog.js\\`. References to the\n * global \\`goog\\` variables have been removed.\n */\nconst global = self; // Use rollup \\\\\"context\\\\\" option to prevent \\`this\\` rewrite\n\n{\n\tconsole.log(\\\\\"Debugging\\\\\");\n}\n\nexport { global as g };\n\"\n`;\n\nexports[`Golden Tests: many-module-build/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/many-module-build/golden/generated_dependent.js 1`] = `\n\"(function (_) {\n\t'use strict';\n\n\tconsole.log(_.s([1, _.b]));\n\n})(generated_entry.$0);\n\"\n`;\n\nexports[`Golden Tests: many-module-build/tscc.spec.json: packages/rollup-plugin-tscc/test/sample/many-module-build/golden/generated_entry.js 1`] = `\n\"var generated_entry = (function (exports) {\n\t'use strict';\n\n\tfunction swap([a, b]) {\n\t\treturn [b, a];\n\t}\n\n\tfunction sort([a, b]) {\n\t\treturn a > b ? [a, b] : swap([a, b]);\n\t}\n\n\tconst a = [1, 2];\n\tconst b = swap(a);\n\n\tconsole.log(b);\n\n\tvar _ = {\n\t\t__proto__: null,\n\t\tb: b,\n\t\ts: sort\n\t};\n\n\texports.$0 = _;\n\texports.b = b;\n\n\treturn exports;\n\n})({});\n\"\n`;\n\nexports[`Golden Tests: many-module-build/tscc.spec.module.json module: packages/rollup-plugin-tscc/test/sample/many-module-build/golden/generated_dependent.js 1`] = `\n\"import { s as sort, b } from './generated_entry.js';\n\nconsole.log(sort([1, b]));\n\"\n`;\n\nexports[`Golden Tests: many-module-build/tscc.spec.module.json module: packages/rollup-plugin-tscc/test/sample/many-module-build/golden/generated_entry.js 1`] = `\n\"function swap([a, b]) {\n\treturn [b, a];\n}\n\nfunction sort([a, b]) {\n\treturn a > b ? [a, b] : swap([a, b]);\n}\n\nconst a = [1, 2];\nconst b = swap(a);\n\nconsole.log(b);\n\nexport { b, sort as s };\n\"\n`;\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/golden_test.ts",
    "content": "///<reference types=\"jest\"/>\nimport tsccPlugin from '../src/index';\nimport * as rollup from 'rollup';\nimport fg = require('fast-glob');\nimport path = require('path');\nimport upath = require('upath');\n\nconst samplesRoot = path.join(__dirname, 'sample');\n// Using cwd as __dirname in order to produce jest snapshots that are independent of cwd.\n// Providing cwd in order to produce jest snapshots that are independent of cwd calling jest\n\nfunction upathGlob(glob: string): string[] {\n\treturn fg.sync(glob, {cwd: samplesRoot})\n\t\t.map(p => upath.toUnix(p)); // Normalize so that snapshots have the same name on Linux and on Windows\n}\n\ndescribe(`Golden Tests:`, () => {\n\tconst bundleSpecs = upathGlob(`*/tscc.spec.json`);\n\tconst moduleBundleSpecs = upathGlob(`*/tscc.spec.module.json`);\n\n\ttest.each(bundleSpecs)(`%s`, testBundle);\n\ttest.each(moduleBundleSpecs)(`%s module`, testBundle);\n})\n\nasync function testBundle(specPath: string) {\n\tconst specFile = path.join(samplesRoot, specPath);\n\tconst bundle = await rollup.rollup({\n\t\tplugins: [\n\t\t\ttsccPlugin({specFile})\n\t\t],\n\t\tonwarn(warning, warn) {\n\t\t\t// Silence warning \"The 'this' keyword is equivalent to 'undefined' at the top level of\n\t\t\t// an ES module, and has been rewritten\"\n\t\t\tif (warning.code === 'THIS_IS_UNDEFINED') return;\n\t\t\twarn(warning);\n\t\t}\n\t});\n\tconst {output} = await bundle.generate({\n\t\tdir: '.',\n\t\tinterop: 'esModule'\n\t});\n\n\tObject.keys(output).sort().forEach(name => {\n\t\tlet chunk = output[name];\n\t\tlet normalizedChunkFileName = upath.toUnix(chunk.fileName);\n\t\texpect(chunk.code).toMatchSnapshot(normalizedChunkFileName);\n\t})\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/merge_chunks.ts",
    "content": "///<reference types=\"jest\"/>\nimport {ChunkMerger} from \"../src/merge_chunks\";\nimport MultiMap from \"../src/MultiMap\";\nimport * as rollup from \"rollup\";\nimport path = require(\"path\");\n\nasync function mergeIIFE(\n\tentry: string,\n\tchunkAllocation: MultiMap<string, string>,\n\tbundle: Readonly<rollup.OutputBundle>,\n\tglobals?: {[id: string]: string}\n) {\n\treturn await new ChunkMerger(chunkAllocation, bundle, globals).performSingleEntryBuild(entry, 'iife');\n}\n\nasync function mergeES(\n\tchunkAllocation: MultiMap<string, string>,\n\tbundle: Readonly<rollup.OutputBundle>,\n\tglobals?: {[id: string]: string}\n) {\n\treturn await new ChunkMerger(chunkAllocation, bundle, globals).performCodeSplittingBuild('es');\n}\n\ndescribe(`mergeChunk`, function () {\n\ttest(`merges chunks for a single entry`, async function () {\n\t\tconst entry = \"entry.js\";\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t\"entry.js\": [\"chunk-0.js\", \"chunk-1.js\", \"entry.js\"],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t\"entry.js\": mockChunk({\n\t\t\t\tfileName: \"entry.js\",\n\t\t\t\tcode: `export const a = 'a'; export const b = 'b';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"entry\",\n\t\t\t}),\n\t\t\t\"chunk-0.js\": mockChunk({\n\t\t\t\tfileName: \"chunk-0.js\",\n\t\t\t\tcode: `export const a = 'c'; export const b = 'd';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-0\",\n\t\t\t}),\n\t\t\t\"chunk-1.js\": mockChunk({\n\t\t\t\tfileName: \"chunk-1.js\",\n\t\t\t\tcode: `export const a = 'e'; export const b = 'f';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-1\",\n\t\t\t}),\n\t\t};\n\t\tconst mergedChunk = await mergeIIFE(entry, chunkAllocation, bundle);\n\n\t\texpect(mergedChunk.name).toBe(\"entry\");\n\t\texpect(mergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var entry = (function (exports) {\n\t\t\t'use strict';\n\n\t\t\tconst a$2 = 'c'; const b$2 = 'd';\n\n\t\t\tvar chunk0 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$2,\n\t\t\t\tb: b$2\n\t\t\t};\n\n\t\t\tconst a$1 = 'e'; const b$1 = 'f';\n\n\t\t\tvar chunk1 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$1,\n\t\t\t\tb: b$1\n\t\t\t};\n\n\t\t\tconst a = 'a'; const b = 'b';\n\n\t\t\texports.$0 = chunk0;\n\t\t\texports.$1 = chunk1;\n\t\t\texports.a = a;\n\t\t\texports.b = b;\n\n\t\t\treturn exports;\n\n\t\t})({});\n\t\t\"\n\t`);\n\t\texpect(mergedChunk.exports).toEqual([\"$0\", \"$1\", \"a\", \"b\"]);\n\t\texpect(mergedChunk.fileName).toBe(entry);\n\t});\n\ttest(`merge chunks for a single entry with relative path imports and conflicting import name`, async function () {\n\t\tconst entry = \"entry.js\";\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t\"entry.js\": [\"a/chunk-0.js\", \"b/c/chunk-1.js\", \"entry.js\"],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t\"entry.js\": mockChunk({\n\t\t\t\tfileName: \"entry.js\",\n\t\t\t\tcode: `import { a as A } from './a/chunk-0.js'; export const a = A; export const b = 'b'; export const $0 = 'c';`,\n\t\t\t\texports: [\"a\", \"b\", \"$0\"],\n\t\t\t\tname: \"entry\",\n\t\t\t}),\n\t\t\t\"a/chunk-0.js\": mockChunk({\n\t\t\t\tfileName: \"a/chunk-0.js\",\n\t\t\t\tcode: `import { b as B } from '../b/c/chunk-1.js'; export const a = 'c'; export const b = B;`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-0\",\n\t\t\t}),\n\t\t\t\"b/c/chunk-1.js\": mockChunk({\n\t\t\t\tfileName: \"b/c/chunk-1.js\",\n\t\t\t\tcode: `export const a = 'e'; export const b = 'f';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-1\",\n\t\t\t}),\n\t\t};\n\t\tconst mergedChunk = await mergeIIFE(entry, chunkAllocation, bundle);\n\n\t\texpect(mergedChunk.name).toBe(\"entry\");\n\t\texpect(mergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var entry = (function (exports) {\n\t\t\t'use strict';\n\n\t\t\tconst a$2 = 'e'; const b$2 = 'f';\n\n\t\t\tvar chunk1 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$2,\n\t\t\t\tb: b$2\n\t\t\t};\n\n\t\t\tconst a$1 = 'c'; const b$1 = b$2;\n\n\t\t\tvar chunk0 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$1,\n\t\t\t\tb: b$1\n\t\t\t};\n\n\t\t\tconst a = a$1; const b = 'b'; const $0 = 'c';\n\n\t\t\texports.$0 = $0;\n\t\t\texports.$1 = chunk0;\n\t\t\texports.$2 = chunk1;\n\t\t\texports.a = a;\n\t\t\texports.b = b;\n\n\t\t\treturn exports;\n\n\t\t})({});\n\t\t\"\n\t`);\n\t\texpect(mergedChunk.exports).toEqual([\"$0\", \"$1\", \"$2\", \"a\", \"b\"]);\n\t\texpect(mergedChunk.fileName).toBe(entry);\n\t});\n\n\ttest(`merge chunks for with imports from external chunks`, async function () {\n\t\tconst entry = \"entry.js\",\n\t\t\tchunk0 = \"a/chunk-0.js\",\n\t\t\tchunk1 = \"b/c/chunk-1.js\",\n\t\t\tanotherEntry = \"d/another-entry.js\",\n\t\t\tchunk2 = \"e/f/chunk-2.js\",\n\t\t\tchunk3 = \"chunk-3.js\",\n\t\t\tchunk4 = \"chunk-4.js\";\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t[entry]: [chunk0, chunk1, entry],\n\t\t\t[anotherEntry]: [chunk2, chunk3, chunk4, anotherEntry],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t[entry]: mockChunk({\n\t\t\t\tfileName: entry,\n\t\t\t\tcode:\n\t\t\t\t\t`import { b as e } from './${chunk3}'; import { c as f } from './${chunk0}';` +\n\t\t\t\t\t`export const a = 'a'; export const b = 'b'; export const c = e; export const d = f;`,\n\t\t\t\texports: [\"a\", \"b\", \"c\", \"d\"],\n\t\t\t\tname: \"entry\",\n\t\t\t}),\n\t\t\t[chunk0]: mockChunk({\n\t\t\t\tfileName: chunk0,\n\t\t\t\tcode: `import { a as c } from '../${chunk2}'; export const a = 'c'; export const b = 'd'; export { c };`,\n\t\t\t\texports: [\"a\", \"b\", \"c\"],\n\t\t\t\tname: \"chunk-0\",\n\t\t\t}),\n\t\t\t[chunk1]: mockChunk({\n\t\t\t\tfileName: chunk1,\n\t\t\t\tcode: `export const a = 'e'; export const b = 'f';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-1\",\n\t\t\t}),\n\t\t\t[anotherEntry]: mockChunk({\n\t\t\t\tfileName: anotherEntry,\n\t\t\t\tcode: `export const a = 'g'; export const b = 'h'; export const $0 = '$0';`,\n\t\t\t\texports: [\"a\", \"b\", \"$0\"],\n\t\t\t\tname: \"another-entry\",\n\t\t\t}),\n\t\t\t[chunk2]: mockChunk({\n\t\t\t\tfileName: chunk2,\n\t\t\t\tcode: `import { a as c } from '../../${chunk4}'; export const a = 'i'; export const b = c;`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-2\",\n\t\t\t}),\n\t\t\t[chunk3]: mockChunk({\n\t\t\t\tfileName: chunk3,\n\t\t\t\tcode: `export const a = 'k'; export const b = 'l';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-3\",\n\t\t\t}),\n\t\t\t[chunk4]: mockChunk({\n\t\t\t\tfileName: chunk4,\n\t\t\t\tcode: `export const a = 'm'; export const b = 'n';`,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t\tname: \"chunk-4\",\n\t\t\t}),\n\t\t};\n\t\tconst mergedChunk = await mergeIIFE(entry, chunkAllocation, bundle);\n\t\tconst anotherMergedChunk = await mergeIIFE(anotherEntry, chunkAllocation, bundle);\n\t\texpect(mergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var entry = (function (exports, chunk2_js, chunk3_js) {\n\t\t\t'use strict';\n\n\t\t\tconst a$2 = 'c'; const b$2 = 'd';\n\n\t\t\tvar chunk0 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$2,\n\t\t\t\tb: b$2,\n\t\t\t\tc: chunk2_js.a\n\t\t\t};\n\n\t\t\tconst a$1 = 'e'; const b$1 = 'f';\n\n\t\t\tvar chunk1 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$1,\n\t\t\t\tb: b$1\n\t\t\t};\n\n\t\t\tconst a = 'a'; const b = 'b'; const c = chunk3_js.b; const d = chunk2_js.a;\n\n\t\t\texports.$0 = chunk0;\n\t\t\texports.$1 = chunk1;\n\t\t\texports.a = a;\n\t\t\texports.b = b;\n\t\t\texports.c = c;\n\t\t\texports.d = d;\n\n\t\t\treturn exports;\n\n\t\t})({}, another_entry.$1, another_entry.$2);\n\t\t\"\n\t`);\n\t\texpect(anotherMergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var another_entry = (function (exports) {\n\t\t\t'use strict';\n\n\t\t\tconst a$3 = 'm'; const b$3 = 'n';\n\n\t\t\tvar chunk4 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$3,\n\t\t\t\tb: b$3\n\t\t\t};\n\n\t\t\tconst a$2 = 'i'; const b$2 = a$3;\n\n\t\t\tvar chunk2 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$2,\n\t\t\t\tb: b$2\n\t\t\t};\n\n\t\t\tconst a$1 = 'k'; const b$1 = 'l';\n\n\t\t\tvar chunk3 = {\n\t\t\t\t__proto__: null,\n\t\t\t\ta: a$1,\n\t\t\t\tb: b$1\n\t\t\t};\n\n\t\t\tconst a = 'g'; const b = 'h'; const $0 = '$0';\n\n\t\t\texports.$0 = $0;\n\t\t\texports.$1 = chunk2;\n\t\t\texports.$2 = chunk3;\n\t\t\texports.$3 = chunk4;\n\t\t\texports.a = a;\n\t\t\texports.b = b;\n\n\t\t\treturn exports;\n\n\t\t})({});\n\t\t\"\n\t`);\n\t\t// Test that bundled code evaluates well when concatenated\n\t\texpect(new Function(anotherMergedChunk.code + mergedChunk.code + `return entry.d`)()).toBe(\n\t\t\t\"i\"\n\t\t);\n\t});\n\ttest(`Correctly merge chunks referencing external modules`, async function () {\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t\"entry.js\": [\"entry.js\"],\n\t\t\t\"entry2.js\": [\"entry2.js\"],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t\"entry.js\": mockChunk({\n\t\t\t\tfileName: \"entry.js\",\n\t\t\t\tcode: `import * as A from 'external'; console.log(A); export const a = 1;`,\n\t\t\t\texports: [\"a\"],\n\t\t\t\tname: \"entry\",\n\t\t\t}),\n\t\t\t\"entry2.js\": mockChunk({\n\t\t\t\tfileName: \"entry2.js\",\n\t\t\t\tcode: `import * as A from 'external'; import { a } from './entry.js'; console.warn(A); console.log(a);`,\n\t\t\t\texports: [],\n\t\t\t\tname: \"entry2\",\n\t\t\t}),\n\t\t};\n\t\tconst globals = {\n\t\t\texternal: \"External\",\n\t\t};\n\t\tconst mergedChunk = await mergeIIFE(\"entry.js\", chunkAllocation, bundle, globals);\n\t\tconst anotherMergedChunk = await mergeIIFE(\"entry2.js\", chunkAllocation, bundle, globals);\n\t\texpect(mergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var entry = (function (exports, A) {\n\t\t\t'use strict';\n\n\t\t\tconsole.log(A); const a = 1;\n\n\t\t\texports.a = a;\n\n\t\t\treturn exports;\n\n\t\t})({}, External);\n\t\t\"\n\t`);\n\t\texpect(anotherMergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"(function (A, entry_js) {\n\t\t\t'use strict';\n\n\t\t\tconsole.warn(A); console.log(entry_js.a);\n\n\t\t})(External, entry);\n\t\t\"\n\t`);\n\t});\n\n\ttest(`Correctly merge chunks referencing external modules via relative paths`, async function () {\n\t\tconst entry = \"entry.js\";\n\t\tconst entry2 = \"entry2.js\";\n\t\tconst chunk1 = \"chunk1.js\";\n\t\tconst externalRelative = \"external_relative\";\n\t\tconst externalAbsolute = path.posix.resolve(\"external/absolute.js\"); // Always use forward slash\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t[entry]: [chunk1, entry],\n\t\t\t[entry2]: [entry2],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t[entry]: mockChunk({\n\t\t\t\tfileName: entry,\n\t\t\t\tcode:\n\t\t\t\t\t`import { C } from \"${externalRelative}\";` +\n\t\t\t\t\t`import { D } from \"${externalAbsolute}\";` +\n\t\t\t\t\t`export const c = C + D;`,\n\t\t\t\texports: [\"c\"],\n\t\t\t\tname: \"entry\",\n\t\t\t}),\n\t\t\t[entry2]: mockChunk({\n\t\t\t\tfileName: entry2,\n\t\t\t\tcode:\n\t\t\t\t\t`import { a } from \"${externalRelative}\";` +\n\t\t\t\t\t`import { e } from \"${chunk1}\";` +\n\t\t\t\t\t`export const d = a;` +\n\t\t\t\t\t`export const f = e;`,\n\t\t\t\texports: [\"d\"],\n\t\t\t\tname: \"entry2\",\n\t\t\t}),\n\t\t\t[chunk1]: mockChunk({\n\t\t\t\tfileName: chunk1,\n\t\t\t\tcode:\n\t\t\t\t\t`import { A } from \"${externalAbsolute}\";` +\n\t\t\t\t\t`import { B } from \"${externalRelative}\";` +\n\t\t\t\t\t`export const e = A + B;`,\n\t\t\t\texports: [\"e\"],\n\t\t\t\tname: \"chunk1\",\n\t\t\t}),\n\t\t};\n\t\tconst globals = {\n\t\t\t[externalRelative]: \"ExternalRelative\",\n\t\t\t[externalAbsolute]: \"ExternalAbsolute\",\n\t\t};\n\n\t\tconst [mergedChunk, mergedChunk2] = await Promise.all([\n\t\t\tmergeIIFE(entry, chunkAllocation, bundle, globals),\n\t\t\tmergeIIFE(entry2, chunkAllocation, bundle, globals),\n\t\t]);\n\t\texpect(mergedChunk.code).toMatchInlineSnapshot(`\n\t\t\"var entry = (function (exports, absolute_js, external_relative) {\n\t\t\t'use strict';\n\n\t\t\tconst e = absolute_js.A + external_relative.B;\n\n\t\t\tvar chunk1 = {\n\t\t\t\t__proto__: null,\n\t\t\t\te: e\n\t\t\t};\n\n\t\t\tconst c = external_relative.C + absolute_js.D;\n\n\t\t\texports.$0 = chunk1;\n\t\t\texports.c = c;\n\n\t\t\treturn exports;\n\n\t\t})({}, ExternalAbsolute, ExternalRelative);\n\t\t\"\n\t`);\n\t\texpect(mergedChunk2.code).toMatchInlineSnapshot(`\n\t\t\"var entry2 = (function (exports, external_relative, chunk1_js) {\n\t\t\t'use strict';\n\n\t\t\tconst d = external_relative.a;const f = chunk1_js.e;\n\n\t\t\texports.d = d;\n\t\t\texports.f = f;\n\n\t\t\treturn exports;\n\n\t\t})({}, ExternalRelative, entry.$0);\n\t\t\"\n\t`);\n\t});\n\n\ttest(`merges chunk without external modules in ES6 modules format`, async function () {\n\t\tconst entry = \"entry.js\";\n\t\tconst entry2 = \"entry2.js\";\n\t\tconst chunk1 = \"chunk1.js\";\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t[entry]: [chunk1, entry],\n\t\t\t[entry2]: [entry2],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t[entry]: mockChunk({\n\t\t\t\tfileName: entry,\n\t\t\t\tcode:\n\t\t\t\t\t`import { a, sum } from '${chunk1}'; ` +\n\t\t\t\t\t`export const c = sum(a, 1); ` +\n\t\t\t\t\t`console.log(sum(c, -1)); `,\n\t\t\t\texports: [\"c\"],\n\t\t\t}),\n\t\t\t[entry2]: mockChunk({\n\t\t\t\tfileName: entry2,\n\t\t\t\tcode:\n\t\t\t\t\t`import { b, sum } from \"${chunk1}\"; ` +\n\t\t\t\t\t`export const d = b + 2; ` +\n\t\t\t\t\t`export function add3(a, b, c) { return sum(sum(a, b), c); } ` +\n\t\t\t\t\t`console.log(add3(1, 2, 3)); `,\n\t\t\t\texports: [\"d\"],\n\t\t\t}),\n\t\t\t[chunk1]: mockChunk({\n\t\t\t\tfileName: chunk1,\n\t\t\t\tcode:\n\t\t\t\t\t`export const a = 3; ` +\n\t\t\t\t\t`export const b = 4; ` +\n\t\t\t\t\t`export function sum(a, b) { return a + b; } `,\n\t\t\t\texports: [\"a\", \"b\"],\n\t\t\t}),\n\t\t};\n\t\tconst [mergedESModuleChunk, mergedESModuleChunk2] = await mergeES(\n\t\t\tchunkAllocation,\n\t\t\tbundle,\n\t\t\t{}\n\t\t);\n\t\texpect(mergedESModuleChunk.code).toMatchInlineSnapshot(`\n\t\t\"const a = 3; function sum(a, b) { return a + b; }\n\n\t\tconst c = sum(a, 1); console.log(sum(c, -1));\n\n\t\texport { sum as s };\n\t\t\"\n\t`);\n\t\texpect(mergedESModuleChunk2.code).toMatchInlineSnapshot(`\n\t\t\"import { s as sum } from './entry.js';\n\n\t\tfunction add3(a, b, c) { return sum(sum(a, b), c); } console.log(add3(1, 2, 3));\n\t\t\"\n\t`);\n\t});\n\ttest(`merges chunk containing external modules in ES6 module format`, async function () {\n\t\tconst entry = \"entry.js\";\n\t\tconst entry2 = \"entry2.js\";\n\t\tconst chunk1 = \"chunk1.js\";\n\t\tconst externalNonAbsolute = \"external\";\n\t\tconst chunkAllocation = MultiMap.fromObject({\n\t\t\t[entry]: [chunk1, entry],\n\t\t\t[entry2]: [entry2],\n\t\t});\n\t\tconst bundle: rollup.OutputBundle = {\n\t\t\t[entry]: mockChunk({\n\t\t\t\tfileName: entry,\n\t\t\t\tcode: `import { sum } from \"${externalNonAbsolute}\";` + `console.log(sum(1, 2));`,\n\t\t\t\texports: [\"c\"],\n\t\t\t}),\n\t\t\t[entry2]: mockChunk({\n\t\t\t\tfileName: entry2,\n\t\t\t\tcode:\n\t\t\t\t\t`import { multiply } from \"${externalNonAbsolute}\";` +\n\t\t\t\t\t`import { sum3 } from \"${chunk1}\";` +\n\t\t\t\t\t`console.log(sum3(1, 2, multiply(3, 4)));`,\n\t\t\t\texports: [\"d\"],\n\t\t\t}),\n\t\t\t[chunk1]: mockChunk({\n\t\t\t\tfileName: chunk1,\n\t\t\t\tcode:\n\t\t\t\t\t`import { sum } from \"${externalNonAbsolute}\";` +\n\t\t\t\t\t`export function sum3(a, b, c) {\n\t\t\t\t\t\treturn sum(a, sum(b, c));\n\t\t\t\t\t};`,\n\t\t\t\texports: [\"e\"],\n\t\t\t}),\n\t\t};\n\t\tconst globals = {\n\t\t\t[externalNonAbsolute]: \"ExternalNonAbsolute\",\n\t\t};\n\t\tconst [mergedESModuleChunk, mergedESModuleChunk2] = await mergeES(\n\t\t\tchunkAllocation,\n\t\t\tbundle,\n\t\t\tglobals\n\t\t);\n\t\texpect(mergedESModuleChunk.code).toMatchInlineSnapshot(`\n\t\t\"import { sum } from 'external';\n\n\t\tconsole.log(sum(1, 2));\n\n\t\tfunction sum3(a, b, c) {\n\t\t\t\t\t\t\t\treturn sum(a, sum(b, c));\n\t\t\t\t\t\t\t}\n\n\t\texport { sum3 as s };\n\t\t\"\n\t`);\n\t\texpect(mergedESModuleChunk2.code).toMatchInlineSnapshot(`\n\t\t\"import { multiply } from 'external';\n\t\timport { s as sum3 } from './entry.js';\n\n\t\tconsole.log(sum3(1, 2, multiply(3, 4)));\n\t\t\"\n\t`);\n\t});\n\ttest.todo(\n\t\t`merges chunk containing external modules referenced via relative path in ES6 module format`\n\t);\n});\n\nfunction mockChunk(chunk: Partial<rollup.OutputChunk>): rollup.OutputChunk {\n\tif (!(\"dynamicImports\" in chunk)) chunk.dynamicImports || [];\n\tif (!(\"isEntry\" in chunk)) chunk.isEntry = true;\n\tif (!(\"modules\" in chunk)) chunk.modules = {};\n\tif (!(\"facadeModuleId\" in chunk)) chunk.facadeModuleId = null;\n\tif (!(\"imports\" in chunk)) chunk.imports = [];\n\tif (!(\"isDynamicEntry\" in chunk)) chunk.isDynamicEntry = false;\n\treturn <rollup.OutputChunk>chunk;\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules/entry.js",
    "content": "import * as externalInNodeModules from 'external';\nimport * as externalWithFilePaths from './external_with_file_paths';\n\nconsole.log(externalInNodeModules.someProperty);\nconsole.log(externalWithFilePaths.anotherProperty);\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\"\n\t},\n\t\"external\": {\n\t\t\"external\": \"externalInNodeModules\",\n\t\t\"./external_with_file_paths\": \"externalWithFilePaths\"\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/common/index.js",
    "content": "import * as c from './external/from/common';\nlet counter = 0;\nexport function common(n) {\n\tconsole.log(\"common\");\n\tcounter += n;\n}\nconsole.log(c.a);\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/dependent.js",
    "content": "import {common} from './common/index';\nimport {entry} from './entry';\nimport * as b from './external-dependent';\ncommon(3);\nentry();\nconsole.log(b);\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/entry.js",
    "content": "import {common} from './common/index';\nimport * as a from './external-entry';\n\nexport function entry() {\n\tcommon(0);\n\tconsole.log(\"entry\");\n}\n\nentry();\nconsole.log(a);\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/external-modules-in-many-module-build/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dependent.js\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"external\": {\n\t\t\"./external-entry\": \"a\",\n\t\t\"./external-dependent\": \"b\",\n\t\t\"./common/external/from/common\": \"c\"\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/goog-shim/dependent.js",
    "content": "import * as entry from './entry';\n\nimport * as goog from 'goog:goog';\n\n// This module is only used in \"dependent\" module, so the corresponding shim file's content should\n// only be included in the \"dependent\" chunk.\nimport * as googReflect from 'goog:goog.reflect';\n\nvar dictionary = {\n\t\"key\": \"value\"\n};\n\nif (entry.isDebugging() && goog.global.name === googReflect.objectProperty(\"key\", dictionary)) {\n\tconsole.log(dictionary[goog.global.name]);\n};\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/goog-shim/entry.js",
    "content": "import * as goog from 'goog:goog';\n\nexport function isDebugging() {\n\treturn goog.DEBUG;\n}\n\nif (isDebugging()) {\n\tconsole.log(\"Debugging\");\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/goog-shim/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dependent.js\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/goog-shim/tscc.spec.module.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dependent.js\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t},\n\t\"chunkFormat\": \"module\"\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/many-module-build/common.js",
    "content": "export function swap([a, b]) {\n\treturn [b, a];\n}\n\nexport function sort([a, b]) {\n\treturn a > b ? [a, b] : swap([a, b]);\n}\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/many-module-build/dir/dependency.js",
    "content": "import * as utils from '../common';\nimport {b} from '../entry';\n\nconsole.log(utils.sort([1, b]));\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/many-module-build/entry.js",
    "content": "import {swap} from './common';\n\nconst a = [1, 2];\nconst b = swap(a);\n\nconsole.log(b);\n\nexport { b };\n\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/many-module-build/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dir/dependency.js\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t}\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sample/many-module-build/tscc.spec.module.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.js\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dir/dependency.js\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": {\n\t\t\"rollup\": \"./golden/generated_\",\n\t\t\"cc\": \".\"\n\t},\n\t\"chunkFormat\": \"module\"\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/test/sort_chunks.ts",
    "content": "///<reference types=\"jest\"/>\nimport computeChunkAllocation from '../src/sort_chunks';\nimport MultiMap from '../src/MultiMap';\n\ndescribe(`computeChunkAllocation`, function () {\n\ttest(`Returns a trivial map when only one chunk is provided`, function () {\n\t\tconst trivialChunkMap = {\"entry.js\": []};\n\t\tconst trivialEntryDep = MultiMap.fromObject({\"entry.js\": []});\n\t\tconst expectedChunkAlloc = {\"entry.js\": [\"entry.js\"]};\n\t\tconst computedChunkAlloc = computeChunkAllocation(trivialChunkMap, trivialEntryDep);\n\t\texpect(MultiMap.toObject(computedChunkAlloc)).toEqual(expectedChunkAlloc);\n\t})\n\ttest(`Returns an expected allocation map for a diamond dependency graph`, function () {\n\t\tconst diamondEntryDep = new MultiMap<string, string>();\n\t\tdiamondEntryDep.putAll(\"a.js\", []);\n\t\tdiamondEntryDep.putAll(\"b.js\", [\"a.js\"]);\n\t\tdiamondEntryDep.putAll(\"c.js\", [\"a.js\"]);\n\t\tdiamondEntryDep.putAll(\"d.js\", [\"b.js\", \"c.js\"]);\n\n\t\tconst chunkDep = {\n\t\t\t\"a.js\": [\"ab.js\", \"ac.js\", \"ad.js\", \"abc.js\", \"abd.js\", \"acd.js\", \"abcd.js\"],\n\t\t\t\"b.js\": [\"ab.js\", \"bc.js\", \"bd.js\", \"abc.js\", \"abd.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"c.js\": [\"ac.js\", \"bc.js\", \"cd.js\", \"abc.js\", \"acd.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"d.js\": [\"ad.js\", \"bd.js\", \"cd.js\", \"abd.js\", \"acd.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"ab.js\": [\"abc.js\", \"abd.js\", \"abcd.js\"],\n\t\t\t\"ac.js\": [\"abc.js\", \"acd.js\", \"abcd.js\"],\n\t\t\t\"ad.js\": [\"abd.js\", \"acd.js\", \"abcd.js\"],\n\t\t\t\"bc.js\": [\"abc.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"bd.js\": [\"abd.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"cd.js\": [\"acd.js\", \"bcd.js\", \"abcd.js\"],\n\t\t\t\"abc.js\": [\"abcd.js\"],\n\t\t\t\"abd.js\": [\"abcd.js\"],\n\t\t\t\"acd.js\": [\"abcd.js\"],\n\t\t\t\"bcd.js\": [\"abcd.js\"],\n\t\t\t\"abcd.js\": []\n\t\t};\n\n\t\tconst expectedAlloc = { // Order may vary\n\t\t\t\"a.js\": [\"abcd.js\", \"abc.js\", \"abd.js\", \"acd.js\", \"bcd.js\", \"ab.js\", \"ac.js\", \"ad.js\", \"bc.js\", \"a.js\"],\n\t\t\t\"b.js\": [\"bd.js\", \"b.js\"],\n\t\t\t\"c.js\": [\"cd.js\", \"c.js\"],\n\t\t\t\"d.js\": [\"d.js\"]\n\t\t}\n\t\tconst computedAlloc = MultiMap.toObject(computeChunkAllocation(chunkDep, diamondEntryDep));\n\t\texpect(new Set(Object.keys(computedAlloc))).toEqual(new Set([\"a.js\", \"b.js\", \"c.js\", \"d.js\"]));\n\t\texpect(computedAlloc[\"b.js\"]).toEqual(expectedAlloc[\"b.js\"]);\n\t\texpect(computedAlloc[\"c.js\"]).toEqual(expectedAlloc[\"c.js\"]);\n\t\texpect(computedAlloc[\"d.js\"]).toEqual(expectedAlloc[\"d.js\"]);\n\t\texpect(computedAlloc[\"a.js\"][0]).toBe(\"abcd.js\"); // This is necessary\n\t\tfor (let [chunk, deps] of Object.entries(chunkDep)) {\n\t\t\tfor (let dep of deps) {\n\t\t\t\tlet dependencyOccurence = computedAlloc[\"a.js\"].indexOf(dep);\n\t\t\t\tlet chunkOccurence = computedAlloc[\"a.js\"].indexOf(chunk);\n\t\t\t\tif (dependencyOccurence !== -1 && chunkOccurence !== -1) {\n\t\t\t\t\texpect(dependencyOccurence).toBeLessThan(chunkOccurence);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\ttest(`Removes dependencies among entry points`, function () {\n\t\tconst entryDep = MultiMap.fromObject(({\n\t\t\t\"entry-1.js\": [],\n\t\t\t\"entry-2.js\": [\"entry-1.js\"]\n\t\t}));\n\t\tconst chunkDep = {\n\t\t\t\"chunk-1.js\": [],\n\t\t\t\"chunk-2.js\": [],\n\t\t\t\"entry-1.js\": [\"chunk-1.js\"],\n\t\t\t\"entry-2.js\": [\"chunk-1.js\", \"chunk-2.js\", \"entry-1.js\"]\n\t\t};\n\t\tconst computedAlloc = MultiMap.toObject(computeChunkAllocation(chunkDep, entryDep));\n\t\texpect(computedAlloc).toEqual({\n\t\t\t\"entry-1.js\": [\"chunk-1.js\", \"entry-1.js\"],\n\t\t\t\"entry-2.js\": [\"chunk-2.js\", \"entry-2.js\"]\n\t\t});\n\t})\n\ttest(`Does not drop entry points that are refrenced in no edge`, function () {\n\t\tconst entryDep = MultiMap.fromObject(({\n\t\t\t\"root.js\": [],\n\t\t\t\"1.js\": []\n\t\t}));\n\t\tconst chunkDep = {\n\t\t\t\"root.js\": [],\n\t\t\t\"1.js\": [\"root.js\"]\n\t\t};\n\t\tconst computedAlloc = MultiMap.toObject(computeChunkAllocation(chunkDep, entryDep));\n\t\texpect(computedAlloc).toEqual({\n\t\t\t\"root.js\": [\"root.js\"],\n\t\t\t\"1.js\": [\"1.js\"]\n\t\t});\n\n\t})\n})\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/third_party/closure_library/README.md",
    "content": "Original source: https://github.com/google/closure-library\nLicense: Apache 2.0\nDescription:\nWhen `rollup-plugin-tscc` bundle files that reference `goog:goog.goog` or `goog:goog.reflect`, the\nplugin will link such modules to files contained in this directory to enable correct runtime\nbehavior.\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/third_party/closure_library/goog_shim.js",
    "content": "/**\n * @fileoverview Hand-modified shim file for Closure Library `goog/goog.js`. References to the\n * global `goog` variables have been removed.\n */\nexport const global = this || self; // Use rollup \"context\" option to prevent `this` rewrite\n\nexport function define(name, value) {\n\tvar uncompiledDefines = global.CLOSURE_UNCOMPILED_DEFINES;\n\tvar defines = global.CLOSURE_DEFINES;\n\tif (uncompiledDefines) value = uncompiledDefines[name];\n\telse if (defines) value = defines[name];\n\treturn value;\n}\n\nexport let DEBUG = true;\n\nexport function typeOf(value) {\n\tvar s = typeof value;\n\tif (s != 'object') return s;\n\tif (!value) return 'null';\n\tif (Array.isArray(value)) return 'array';\n\treturn s;\n};\nexport function isArrayLike(val) {\n\tvar type = typeOf(val);\n\treturn type == 'array' || type == 'object' && typeof val.length == 'number';\n}\nexport function isObject(val) {\n\tvar type = typeof val;\n\treturn type == 'object' && val != null || type == 'function';\n}\nexport function getCssName(className, opt_modifier) {\n\treturn className;\n}\nexport function getMsg(str, opt_values, opt_options) {\n\tif (opt_options && opt_options.html) {\n\t\t// Note that '&' is not replaced because the translation can contain HTML\n\t\t// entities.\n\t\tstr = str.replace(/</g, '&lt;');\n\t}\n\tif (opt_options && opt_options.unescapeHtmlEntities) {\n\t\t// Note that \"&amp;\" must be the last to avoid \"creating\" new entities.\n\t\tstr = str.replace(/&lt;/g, '<')\n\t\t\t.replace(/&gt;/g, '>')\n\t\t\t.replace(/&apos;/g, '\\'')\n\t\t\t.replace(/&quot;/g, '\"')\n\t\t\t.replace(/&amp;/g, '&');\n\t}\n\tif (opt_values) {\n\t\tstr = str.replace(/\\{\\$([^}]+)}/g, function (match, key) {\n\t\t\treturn (opt_values != null && key in opt_values) ? opt_values[key] :\n\t\t\t\tmatch;\n\t\t});\n\t}\n\treturn str;\n}\nexport function exportSymbol(publicPath, object, objectToExportTo) {\n\tvar parts = publicPath.split('.');\n\tvar cur = objectToExportTo || global;\n\tfor (var part; parts.length && (part = parts.shift());) {\n\t\tif (!parts.length && object !== undefined) {\n\t\t\tcur[part] = object;\n\t\t} else if (cur[part] && cur[part] !== Object.prototype[part]) {\n\t\t\tcur = cur[part];\n\t\t} else {\n\t\t\tcur = cur[part] = {};\n\t\t}\n\t}\n}\nexport function exportProperty(object, publicName, symbol) {\n\tobject[publicName] = symbol;\n}\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/third_party/closure_library/reflect_shim.js",
    "content": "/**\n * @fileoverview Hand-modified shim file for Closure Library `goog/reflect.js`. References to the\n * global `goog` variables have been removed.\n */\n\nexport function object(type, object) {\n\treturn object;\n}\n\nexport function objectProperty(prop, object) {\n\treturn prop;\n}\n\nexport function sinkValue(x) {\n\tsinkValue[' '](x);\n\treturn x;\n}\nsinkValue[' '] = function () {};\n\nexport function canAccessProperty(obj, prop) {\n\ttry {\n\t\tsinkValue(obj[prop]);\n\t\treturn true;\n\t} catch (e) {}\n\treturn false;\n}\n\nexport function cache(cacheObj, key, valueFn, opt_keyFn) {\n\tconst storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n\tif (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n\t\treturn cacheObj[storedKey];\n\t}\n\n\treturn (cacheObj[storedKey] = valueFn(key));\n};\n"
  },
  {
    "path": "packages/rollup-plugin-tscc/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../tsconfig.json\",\n\t\"compilerOptions\": {\n\t\t\"outDir\": \"dist\",\n\t\t\"rootDir\": \"src\"\n\t},\n\t\"include\": [\n\t\t\"src/**/*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/.npmignore",
    "content": "index.ts\n/src\ntest\nnode_modules\ntsconfig.json\nyarn.lock\nyarn-error.log\nMakefile\n\n"
  },
  {
    "path": "packages/tscc/Makefile",
    "content": ".PHONY: fetch_tslib clean fetch_closure_lib fetch_tsickle_externs\n\nall: $(shell find dist) fetch_tslib\n\ndist/%.js: src/%.ts\n\ttsc;\n\nWGET=wget --no-check-certificate --content-disposition\nGH_USER_CONTENT=https://raw.githubusercontent.com/\nTHIRD_PARTY=third_party/\nCLOSURE_VER=v20191111\n\nfetch_tslib:\n\tsvn export https://github.com/angular/tsickle/trunk/${THIRD_PARTY}tslib ${THIRD_PARTY}tsickle/third_party/tslib --force\n\nfetch_closure_lib:\n\t${WGET} ${GH_USER_CONTENT}google/closure-library/${CLOSURE_VER}/closure/goog/base.js \\\n\t\t-O ${THIRD_PARTY}closure_library/base.js\n\t${WGET} ${GH_USER_CONTENT}google/closure-library/${CLOSURE_VER}/closure/goog/reflect/reflect.js \\\n\t\t-O ${THIRD_PARTY}closure_library/reflect.js\n\nfetch_tsickle_externs:\n\t${WGET} ${GH_USER_CONTENT}angular/tsickle/master/src/closure_externs.js \\\n\t\t-O ${THIRD_PARTY}tsickle/closure_externs.js\n\nupd_3rd_party: fetch_tslib fetch_tsickle_externs fetch_closure_lib\n\nlocal_install: $(shell find dist) \n\tnpm i -g .\n\nclean:\n\tsudo rm -rf dist\n\n"
  },
  {
    "path": "packages/tscc/README.md",
    "content": "# TSCC\n\nWe refer to the [README of the main package](https://github.com/theseanl/tscc).\n"
  },
  {
    "path": "packages/tscc/package.json",
    "content": "{\n  \"name\": \"@tscc/tscc\",\n  \"author\": \"theseanl\",\n  \"description\": \"A typescript transpiler and bundler that wires up tsickle and closure compiler seamlessly\",\n  \"keywords\": [\n    \"typescript\",\n    \"closure-compiler\",\n    \"tree-shaking\",\n    \"minify-javascript\"\n  ],\n  \"version\": \"0.9.4\",\n  \"main\": \"./dist/tscc.js\",\n  \"bin\": {\n    \"tscc\": \"./dist/main.js\"\n  },\n  \"license\": \"MIT\",\n  \"homepage\": \"https://github.com/theseanl/tscc\",\n  \"repository\": {\n    \"type\": \"url\",\n    \"url\": \"https://github.com/theseanl/tscc\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/theseanl/tscc\"\n  },\n  \"scripts\": {\n    \"clean\": \"rm -rf dist\"\n  },\n  \"engines\": {\n    \"node\": \">=10.3.0\"\n  },\n  \"devDependencies\": {\n    \"@types/fs-extra\": \"^9.0.13\",\n    \"@types/node\": \"^18.11.2\",\n    \"@types/stream-json\": \"^1.7.1\",\n    \"@types/vinyl\": \"^2.0.6\",\n    \"@types/vinyl-fs\": \"^2.4.12\",\n    \"@types/yargs\": \"^17.0.13\",\n    \"magic-string\": \"^0.26.7\"\n  },\n  \"optionalDependencies\": {\n    \"google-closure-compiler-linux\": \"^20221004.0.0\",\n    \"google-closure-compiler-osx\": \"^20221004.0.0\",\n    \"google-closure-compiler-windows\": \"^20221004.0.0\"\n  },\n  \"dependencies\": {\n    \"@tscc/tscc-spec\": \"^0.9.4\",\n    \"chalk\": \"^4.1.1\",\n    \"fs-extra\": \"^10.0.1\",\n    \"google-closure-compiler-java\": \"^20221004.0.0\",\n    \"ora\": \"^5.4.1\",\n    \"resolve-from\": \"^5.0.0\",\n    \"rimraf\": \"^3.0.2\",\n    \"source-map\": \"^0.7.4\",\n    \"stream-json\": \"^1.7.2\",\n    \"tsickle\": \"^0.46.3\",\n    \"tslib\": \"^2.3.0\",\n    \"typescript\": \"~4.7.2\",\n    \"upath\": \"^2.0.1\",\n    \"vinyl\": \"^3.0.0\",\n    \"vinyl-fs\": \"^3.0.3\",\n    \"yargs\": \"^17.6.0\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"gitHead\": \"7d00e4fc6b79ae208622f699a3a59d4d11121562\"\n}\n"
  },
  {
    "path": "packages/tscc/src/default_libs.ts",
    "content": "/**\n * @fileoverview Files described here are provided to closure compiler by default.\n */\nimport fs = require('fs');\nimport path = require('path');\nimport resolve = require('resolve-from');\n\n// Resolves file path relative to tscc package root. Prefers that in node_modules directory\n// of the caller. (Such file paths might be included in sourcemaps if user have it enabled,\n// so if it uses files in the global npm/yarn installation directory, it may expose file structure\n// of the build machine.)\n// TODO consider providing a dummy path.\nfunction resolveTSCCAssets(relPath: string, projectRoot: string): string {\n\t// Below returns `null` when the package is not found.\n\tconst packageRoot = resolve.silent(projectRoot, `@tscc/tscc/package.json`);\n\tif (packageRoot) {\n\t\tconst resolved = path.resolve(packageRoot, '..', relPath);\n\t\tif (fs.existsSync(resolved)) return resolved;\n\t}\n\treturn path.resolve(__dirname, '..', relPath);\n}\n\nconst tsickleDir = 'third_party/tsickle';\nconst tsickleExternsPath = path.join(tsickleDir, 'closure_externs.js');\nconst tsLibDir = path.join(tsickleDir, 'third_party/tslib');\nconst tsLibPath = path.join(tsLibDir, 'tslib.js');\nconst tslibExternsPath = path.join(tsLibDir, 'externs.js');\n\nconst closureLibDir = 'third_party/closure_library';\nconst googBasePath = path.join(closureLibDir, 'base.js');\nconst googReflectPath = path.join(closureLibDir, 'reflect.js');\n\nexport default function (projectRoot: string) {\n\tconst libs = [\n\t\t{id: \"tslib\", path: resolveTSCCAssets(tsLibPath, projectRoot)},\n\t\t{id: \"goog\", path: resolveTSCCAssets(googBasePath, projectRoot)},\n\t\t{id: \"goog.reflect\", path: resolveTSCCAssets(googReflectPath, projectRoot)}\n\t];\n\tconst externs = [\n\t\tresolveTSCCAssets(tslibExternsPath, projectRoot),\n\t\tresolveTSCCAssets(tsickleExternsPath, projectRoot)\n\t]\n\treturn {libs, externs};\n}\n\n"
  },
  {
    "path": "packages/tscc/src/external_module_support.ts",
    "content": "/**\n * @fileoverview Transforms `import localName from \"external_module\"` to\n * `const localName = global_name_for_the_external_module`.\n * Also transforms `import tslib_any from 'tslib'` to `goog.require(\"tslib\")`.\n */\nimport ITsccSpecWithTS from './spec/ITsccSpecWithTS';\nimport {TsickleHost} from 'tsickle';\nimport {moduleNameAsIdentifier} from 'tsickle/out/src/annotator_host';\n\nexport function getExternsForExternalModules(tsccSpec: ITsccSpecWithTS, tsickleHost: TsickleHost): string {\n\tconst header = `\\n/** Generated by TSCC */`\n\tlet out = '';\n\tfor (let [moduleName, {globalName}] of tsccSpec.getExternalModuleDataMap()) {\n\t\t// If a module's type definition is from node_modules, its path is used as a namespace.\n\t\t// otherwise, it comes from declare module '...' in user-provided files, in which the module name string\n\t\t// is used as a namespace.\n\t\tlet typeRefFile = tsccSpec.resolveExternalModuleTypeReference(moduleName) || moduleName;\n\t\tout += `\n/**\n * @type{typeof ${moduleNameAsIdentifier(tsickleHost, typeRefFile)}}\n * @const\n */\nvar ${globalName} = {};\\n`;\n\t}\n\tif (out.length) out = header + out;\n\treturn out;\n}\n\nexport function getGluingModules(tsccSpec: ITsccSpecWithTS, tsickleHost: TsickleHost) {\n\tconst out: {path: string, content: string}[] = [];\n\tfor (let [moduleName, {globalName}] of tsccSpec.getExternalModuleDataMap()) {\n\t\t// This is just no-op for normal external modules.\n\t\tmoduleName = tsickleHost.pathToModuleName('', moduleName);\n\t\tconst content = `goog.module('${moduleName.replace(/([\\\\'])/g, '\\\\$1')}')\\n` +\n\t\t\t`/** Generated by TSCC */\\n` +\n\t\t\t`exports = ${globalName};`;\n\t\t// A hypothetical path of this gluing module.\n\t\t// Note that if the alternative code path is taken, it means that something may be wrong\n\t\t// with the provided typescript project. TODO find a repro which the second code path is\n\t\t// taken and add it as a test case.\n\t\tlet path = tsccSpec.resolveExternalModuleTypeReference(moduleName) || moduleName + `.ts`;\n\t\tpath = path.replace(/(?:\\.d)?\\.ts$/, '.js');\n\t\tout.push({path, content});\n\t}\n\treturn out;\n}\n\n"
  },
  {
    "path": "packages/tscc/src/graph/Cache.ts",
    "content": "import fs = require('fs');\n\nconst fsp = fs.promises;\n\nexport class Cache<T> {\n\tprivate cache: {\n\t\t[key: string]: {\n\t\t\tcontent: T,\n\t\t\tmtime: number\n\t\t}\n\t}\n\tprivate dirty = false;\n\tconstructor(\n\t\tprivate cacheFilePath: string\n\t) {\n\t\ttry {\n\t\t\tthis.cache = JSON.parse(fs.readFileSync(cacheFilePath, 'utf8'));\n\t\t} catch (e) {\n\t\t\tfs.writeFileSync(cacheFilePath, '{}');\n\t\t\tthis.cache = {};\n\t\t}\n\t}\n\tget(key: string): T {\n\t\treturn this.cache[key] && this.cache[key].content;\n\t}\n\tgetMtime(key: string): number {\n\t\treturn this.cache[key] && this.cache[key].mtime;\n\t}\n\tput(key: string, content: T, mtime: number) {\n\t\tthis.dirty = true;\n\t\tthis.cache[key] = {content, mtime};\n\t}\n\tremove(key: string) {\n\t\tdelete this.cache[key];\n\t}\n\tasync commit() {\n\t\tif (!this.dirty) return;\n\t\tawait fsp.writeFile(this.cacheFilePath, JSON.stringify(this.cache));\n\t}\n}\n\nexport class FSCacheAccessor<T> {\n\tconstructor(\n\t\tprivate cache: Cache<T>,\n\t\tprivate dataFactory: (path: string) => Promise<T>\n\t) {}\n\tasync getFileData(path: string) {\n\t\tlet stat: fs.Stats;\n\t\ttry {\n\t\t\tstat = await fsp.stat(path);\n\t\t} catch (e) {\n\t\t\tthis.cache.remove(path);\n\t\t\tthrow new FSCacheAccessError(`${path}: ${(e as NodeJS.ErrnoException).code}`);\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\tthis.cache.remove(path);\n\t\t\tthrow new FSCacheAccessError(`${path}: not a file`);\n\t\t}\n\t\tlet cacheMtime = this.cache.getMtime(path);\n\t\tif (!cacheMtime || stat.mtimeMs > cacheMtime) {\n\t\t\tlet content = await this.dataFactory(path);\n\t\t\tthis.cache.put(path, content, stat.mtimeMs);\n\t\t\treturn content;\n\t\t}\n\t\treturn this.cache.get(path);\n\t}\n\tasync updateCache() {\n\t\tawait this.cache.commit();\n\t}\n}\n\nexport class FSCacheAccessError extends Error {}\n\n"
  },
  {
    "path": "packages/tscc/src/graph/ClosureDependencyGraph.ts",
    "content": "import {FSCacheAccessor} from './Cache';\nimport {ISourceNode} from './ISourceNode';\nimport {sourceNodeFactoryFromContent, ClosureSourceError} from './source_node_factory';\nimport {INamedModuleSpecsWithId} from '@tscc/tscc-spec'\nimport {flatten, riffle} from '../shared/array_utils'\n\n// To be used as arguments of DepsSorter#getDeps\nexport interface IEntryPoint {\n\treadonly moduleId: string | null,\n\treadonly extraSources: ReadonlyArray<string> // Array of file names for extra sources.\n}\n\nexport default class ClosureDependencyGraph {\n\tasync addSourceByFileNames(fileNames: string[], fsCacheAccessor: FSCacheAccessor<ISourceNode>) {\n\t\tawait Promise.all(fileNames.map(async (fileName) => {\n\t\t\ttry {\n\t\t\t\tthis.addSourceNode(await fsCacheAccessor.getFileData(fileName));\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ClosureSourceError && !e.fatal) {\n\t\t\t\t\t// pass\n\t\t\t\t} else throw e;\n\t\t\t}\n\t\t}));\n\t}\n\taddSourceByContent(fileName: string, content: string) {\n\t\ttry {\n\t\t\tthis.addSourceNode(sourceNodeFactoryFromContent(fileName, content));\n\t\t} catch (e) {\n\t\t\tif (e instanceof ClosureSourceError && !e.fatal) {\n\t\t\t\t// pass\n\t\t\t} else throw e;\n\t\t}\n\t}\n\taddSourceNode(sourceNode: ISourceNode) {\n\t\t// Raise error on duplicate module names.\n\t\tfor (let provided of sourceNode.provides) {\n\t\t\tif (this.moduleNameToNode.has(provided)) {\n\t\t\t\tthrow new ClosureDepsError(`Duplicate provides for ${provided}`);\n\t\t\t}\n\t\t}\n\t\tfor (let provided of sourceNode.provides) {\n\t\t\tthis.moduleNameToNode.set(provided, sourceNode);\n\t\t}\n\t\tthis.fileNameToNode.set(sourceNode.fileName, sourceNode);\n\t}\n\n\tprivate fileNameToNode: Map<string, ISourceNode> = new Map();\n\tprivate moduleNameToNode: Map<string, ISourceNode> = new Map();\n\n\thasModule(moduleName: string): boolean {\n\t\treturn this.moduleNameToNode.has(moduleName);\n\t}\n\n\t/**\n\t * Start walker\n\t */\n\tprivate forwardDeclared: Set<ISourceNode> = new Set();\n\tprivate required: Set<ISourceNode> = new Set();\n\tclear() {\n\t\tthis.forwardDeclared.clear();\n\t\tthis.required.clear();\n\t}\n\tprivate getSourceNode(moduleName: string) {\n\t\tlet sourceNode = this.moduleNameToNode.get(moduleName);\n\n\t\tif (!sourceNode) {\n\t\t\tthrow new ClosureDepsError(\n\t\t\t\t`Module name ${moduleName} was not provided as a closure compilation source`\n\t\t\t);\n\t\t} else {\n\t\t\treturn sourceNode;\n\t\t}\n\t}\n\t// Walks the graph, marking type-required nodes and required nodes\n\t// (with DepsSorter#forwardDeclared, DepsSorter#required Sets)\n\t// required-marker has precedence over type-required-marker.\n\t// yields sources which are required by the source it is called with.\n\tprivate *getRequiredNodes(node: string | ISourceNode): IterableIterator<ISourceNode> {\n\t\tif (typeof node === 'string') {\n\t\t\tnode = this.getSourceNode(node);\n\t\t}\n\n\t\tif (this.forwardDeclared.has(node)) {\n\t\t\tthis.forwardDeclared.delete(node);\n\t\t}\n\t\tif (this.required.has(node)) {\n\t\t\treturn;\n\t\t}\n\t\tthis.required.add(node);\n\n\t\tyield node;\n\n\t\t// TODO perf improvement: do not visit forwardDeclared nodes which are known to be required.\n\t\tfor (let forwardDeclared of node.forwardDeclared) {\n\t\t\tlet fwdNode = this.getSourceNode(forwardDeclared);\n\t\t\t// Mark this node and its transitive dependencies as 'forwardDeclare'd.\n\t\t\tthis.walkTypeRequiredNodes(fwdNode);\n\t\t}\n\n\t\tfor (let required of node.required) {\n\t\t\tlet reqNode = this.getSourceNode(required);\n\t\t\tyield* this.getRequiredNodes(reqNode);\n\t\t}\n\t}\n\t// Walks the graph marking required/type-required nodes as forwardDeclared.\n\tprivate walkTypeRequiredNodes(node: ISourceNode) {\n\t\tif (this.forwardDeclared.has(node) || this.required.has(node)) return;\n\n\t\tthis.forwardDeclared.add(node);\n\n\t\tfor (let forwardDeclared of node.forwardDeclared) {\n\t\t\tlet fwdNode = this.getSourceNode(forwardDeclared);\n\t\t\tthis.walkTypeRequiredNodes(fwdNode);\n\t\t}\n\t}\n\n\tprivate static getFileName(sourceNode: ISourceNode) {\n\t\treturn sourceNode.fileName;\n\t}\n\tgetSortedFilesAndFlags(entryPoints: Omit<INamedModuleSpecsWithId, 'entry'>[]): IFilesAndFlags {\n\t\tlet sortedFileNames = entryPoints.map(entryPoint => {\n\t\t\tlet deps: string[];\n\t\t\tif (entryPoint.moduleId === null) {\n\t\t\t\t// For empty chunks included to allow code motion moving into it\n\t\t\t\tdeps = [];\n\t\t\t} else {\n\t\t\t\tdeps = [...this.getRequiredNodes(entryPoint.moduleId)].map(ClosureDependencyGraph.getFileName);\n\t\t\t}\n\t\t\tif (entryPoint.extraSources) {\n\t\t\t\tdeps.push(...entryPoint.extraSources);\n\t\t\t}\n\t\t\treturn deps;\n\t\t});\n\n\t\tlet forwardDeclaredFileNames = [...this.forwardDeclared].map(ClosureDependencyGraph.getFileName);\n\t\t// prepend modules which are only forwardDeclare'd to the very first module.\n\t\tsortedFileNames[0] = [...forwardDeclaredFileNames, ...sortedFileNames[0]];\n\t\tconst flags = entryPoints.length === 1 ?\n\t\t\t// single chunk build uses --js_output_file instead of --chunk, which is set in tsccspecwithts.\n\t\t\t// when --chunk is used, closure compiler generates $weak$.js chunks.\n\t\t\t[] :\n\t\t\triffle(\"--chunk\", sortedFileNames.map((depsOfAModule, index) => {\n\t\t\t\tlet entryPoint = entryPoints[index];\n\t\t\t\tconst args: (string | number)[] = [entryPoint.moduleName, depsOfAModule.length];\n\t\t\t\tif (index !== 0) {\n\t\t\t\t\t// Do not specify dependencies for the very first (root) chunk.\n\t\t\t\t\targs.push(...entryPoint.dependencies!);\n\t\t\t\t}\n\t\t\t\treturn args.join(':');\n\t\t\t}));\n\n\t\treturn {src: flatten(sortedFileNames), flags}\n\t}\n}\n\ninterface IFilesAndFlags {\n\treadonly src: ReadonlyArray<string>,\n\treadonly flags: ReadonlyArray<string>\n}\n\nexport class ClosureDepsError extends Error {};\n\n"
  },
  {
    "path": "packages/tscc/src/graph/ISourceNode.ts",
    "content": "export interface ISourceNode {\n\treadonly fileName: string\n\treadonly provides: ReadonlyArray<string>\n\treadonly required: ReadonlyArray<string>\n\treadonly forwardDeclared: ReadonlyArray<string>\n}\n\n"
  },
  {
    "path": "packages/tscc/src/graph/TypescriptDependencyGraph.ts",
    "content": "/**\n * @fileoverview Starting from a provided set of files, it walks Typescript SourceFiles that are\n * referenced from previous SourceFiles.\n *\n * This information is provided to tsickleHost so that only such referenced files are processed by\n * tsickle. This is mainly concerned with what files to use to generate externs. Why not just feed\n * every `.d.ts` file to generate externs? Currently Typescript's type inclusion often includes \"too\n * many files\" -- If tsconfig.json does not specify `types` compiler option, it will include every\n * type declarations in `./node_modules/@types`, `../node_modules/@types`,\n * `../../node_modules/@types`. Such a behavior is actually OK for usual TS usecase, because types\n * anyway do not affect the Typescript transpilation output. However, in our setup they are all used\n * to generate externs, and the more the type declarations, the more it takes to compile and the\n * more it is prone to errors.\n *\n * An easy way(for me) would be to require users to provide every such package's name. But sometimes\n * a package(A) may implicitly refers to another package(B)'s type declarations, and that package B\n * also needs to be provided to tsickle, so this way requires users to __know__ what other packages\n * this package A refers to, which requires users to inspect its contents, and this is not\n * ergonomic.\n *\n * At the other extreme, we can include every .d.ts that typescript \"sees\". This will lead to the\n * most correct behavior in some sense, because this is something you see in your IDE. But this may\n * potentially lead to enormous amount of externs file and slow down the compilation as it will\n * include everything in `node_modules/@types` directory unless you use types[root] compiler option.\n * This may also cause more bugs coming from incompatibility between typescript and the closure\n * side.\n *\n * Therefore, an intermediate approach is taken here. We use the same module resolution logic to\n * find out which files were explicitly referenced by user-provided file. This requires discovering\n * files that are either (1) imported (2) triple-slash-path-referenced (3)\n * triple-slash-types-referenced. However, some declaration files that augments the global scope may\n * not be discoverable in this way, so we add external modules provided in spec file and any module\n * that is indicated in `compilerOptions.types` tsconfig key to this.\n *\n * There are some work going on from TS's side in a similar vein.\n * {@link https://github.com/microsoft/TypeScript/issues/40124}\n *\n * Currently, this is done using an unexposed API of Typescript. I'm not sure why this is unexposed\n * -- there are APIs such as `getResolvedModuleFileName/setResolvedModuleFileName`, but not\n * something to iterate over resolved module file names.\n */\nimport * as ts from 'typescript';\nimport {getPackageBoundary} from '../tsickle_patches/patch_tsickle_module_resolver';\nimport path = require('path');\n\n\ninterface SourceFileWithInternalAPIs extends ts.SourceFile {\n\t// Internal fields which exists, but not declared in .d.ts. See SourceFile interface declaration\n\t// at Microsoft/Typescript/src/compiler/types.ts.\n\tresolvedModules?: ts.ModeAwareCache<ts.ResolvedModuleFull | undefined>;\n\tresolvedTypeReferenceDirectiveNames: ts.ModeAwareCache<ts.ResolvedTypeReferenceDirective | undefined>;\n}\n\nexport default class TypescriptDependencyGraph {\n\tconstructor(\n\t\tprivate host: ts.ScriptReferenceHost\n\t) {}\n\tprivate visited: Set<string> = new Set();\n\tprivate defaultLibDir = path.normalize(path.dirname(\n\t\tts.getDefaultLibFilePath(this.host.getCompilerOptions())\n\t));\n\tprivate isDefaultLib(fileName: string) {\n\t\treturn fileName.startsWith(this.defaultLibDir);\n\t}\n\tprivate isTslib(fileName: string) {\n\t\treturn getPackageBoundary(fileName).endsWith(path.sep + 'tslib' + path.sep);\n\t}\n\tprivate isTsccAsset(fileName: string) {\n\t\treturn getPackageBoundary(fileName).endsWith(path.sep + '@tscc' + path.sep + 'tscc' + path.sep)\n\t}\n\tprivate walk(fileName: string | undefined | null) {\n\t\tif (typeof fileName !== 'string') return;\n\t\t// Typescript may use unix-style path separators in internal APIs even on Windows environment.\n\t\t// We should normalize it because we use string === match on file names, for example in\n\t\t// shouldSkipTsickleProcessing.\n\t\tfileName = path.normalize(fileName);\n\t\t// Default libraries (lib.*.d.ts) files and tslib.d.ts are not processed by tsickle.\n\t\tif (this.isDefaultLib(fileName) || this.isTslib(fileName) || this.isTsccAsset(fileName)) return;\n\t\t// add file to visited set\n\t\tif (this.visited.has(fileName)) return;\n\t\tthis.visited.add(fileName);\n\t\tconst sf = <SourceFileWithInternalAPIs>this.host.getSourceFile(fileName);\n\t\t/**\n\t\t * Files imported to the current file are available in `resolvedModules` property.\n\t\t * See: Microsoft/Typescript/src/compiler/programs.ts `ts.createProgram > processImportedModules`\n\t\t * function. It calls `setResolvedModule` function for all external module references -->\n\t\t * This is the (only, presumably) place where all the external module references are available.\n\t\t */\n\t\tif (sf.resolvedModules) {\n\t\t\tsf.resolvedModules.forEach(this.walkModeAwareResolvedFileCache);\n\t\t}\n\t\t/**\n\t\t * Files referenced from the current file via /// <reference path=\"....\" /> are available in\n\t\t * `referencedFiles` property. Unlike the previous `resolvedModules`, this is a public API.\n\t\t * See: Microsoft/Typescript/src/compiler/programs.ts `ts.createProgram > processReferencedFiles`\n\t\t * These are always initialized, so no if check is needed: see ts.Parser.parseSourceFile\n\t\t */\n\t\tfor (let ref of sf.referencedFiles) {\n\t\t\t// Unlike the above API, this is not a resolved path, so we have to call TS API\n\t\t\t// to resolve it first. See the function body of `processReferencedFiles`.\n\t\t\tconst resolvedReferencedFileName = ts.resolveTripleslashReference(ref?.fileName, fileName);\n\t\t\tthis.walk(resolvedReferencedFileName);\n\t\t}\n\t\t/**\n\t\t * Files referenced from the current file via /// <reference type=\"...\" /> are available in\n\t\t * `resolvedTypeReferenceDirectiveNames` internal API. This is also available in `typeReferencedFile`,\n\t\t * but it does not contain information about the file path a type reference is resolved to.\n\t\t * See: Microsoft/Typescript/src/compiler/programs.ts `ts.createProgram > processTypeReferenceDirectives`\n\t\t * see how this function calls `setResolvedTypeReferenceDirective` to mutate `sf.resolvedTypeRefernceDirectiveNames`.\n\t\t */\n\t\tif (sf.resolvedTypeReferenceDirectiveNames) {\n\t\t\tsf.resolvedTypeReferenceDirectiveNames.forEach(this.walkModeAwareResolvedFileCache);\n\t\t}\n\t}\n\tprivate walkModeAwareResolvedFileCache = (elem: {resolvedFileName?: string} | undefined) => {\n\t\tthis.walk(elem?.resolvedFileName);\n\t};\n\taddRootFile(fileName: string | undefined | null) {\n\t\tthis.walk(fileName);\n\t}\n\thasFile(fileName: string) {\n\t\treturn this.visited.has(fileName);\n\t}\n\t// Currently this is only used in tests.\n\titerateFiles() {\n\t\treturn this.visited.values();\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/graph/source_node_factory.ts",
    "content": "import {ISourceNode} from './ISourceNode';\nimport fs = require('fs');\nimport readline = require('readline');\n\n/**\n * Uses fast regex search instead of parsing AST, as done in\n * https://github.com/google/closure-library/blob/master/closure/bin/build/source.py\n */\nexport async function sourceNodeFactory(closureSourcePath: string): Promise<ISourceNode> {\n\tconst rl = readline.createInterface({\n\t\tinput: fs.createReadStream(closureSourcePath),\n\t\tcrlfDelay: Infinity\n\t});\n\tconst parser = new ClosureSourceLineParser(closureSourcePath);\n\tfor await (const line of rl) {\n\t\tif (parser.consumeLine(line)) break;\n\t}\n\treturn parser.getSourceNode();\n}\n\nexport function sourceNodeFactoryFromContent(fileName: string, content: string): ISourceNode {\n\tconst lines = content.split('\\n');\n\tconst parser = new ClosureSourceLineParser(fileName);\n\tfor (const line of lines) {\n\t\tif (parser.consumeLine(line)) break;\n\t}\n\treturn parser.getSourceNode();\n}\n\nclass ClosureSourceLineParser {\n\tprivate isInComment = false;\n\tprivate moduleSymbol: string | undefined;\n\tprivate providedSymbols = new Set<string>();\n\tprivate requiredSymbols = new Set<string>();\n\tprivate forwardDeclaredSymbols = new Set<string>();\n\tconstructor(\n\t\tprivate closureSourcePath: string\n\t) {}\n\t// Looking for top-level goog.require,provide,module,forwardDeclare,requireType calls on each line.\n\t// Tsickle now emits goog.requireType instead of forwardDeclare as of Feb 3 2019.\n\t// Returns truthy value when no more line needs to be consumed.\n\tconsumeLine(line: string): boolean {\n\t\t// Heuristic for searching provideGoog in comments\n\t\tif (!this.isInComment && reStartPureComment.test(line)) this.isInComment = true;\n\t\tif (this.isInComment) {\n\t\t\tif (reProvideGoog.test(line)) {\n\t\t\t\tthis.providedSymbols.add('goog');\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (reEndComment.test(line)) this.isInComment = false;\n\t\t}\n\n\t\tif (reGoogModule.exec(line)) {\n\t\t\tif (this.moduleSymbol) {\n\t\t\t\tthrow new ClosureSourceError(`Duplicate module symbols in ${this.closureSourcePath}`);\n\t\t\t}\n\t\t\tthis.moduleSymbol = RegExp.$1;\n\t\t} else if (reGoogProvide.exec(line)) {\n\t\t\tthis.providedSymbols.add(RegExp.$1);\n\t\t} else if (reGoogRequire.exec(line)) {\n\t\t\tthis.requiredSymbols.add(RegExp.$1);\n\t\t} else if (reGoogForwardDeclare.exec(line)) {\n\t\t\tthis.forwardDeclaredSymbols.add(RegExp.$1);\n\t\t} else if (reGoogRequireType.exec(line)) {\n\t\t\tthis.forwardDeclaredSymbols.add(RegExp.$1);\n\t\t}\n\t\treturn false;\n\t}\n\tgetSourceNode(): ISourceNode {\n\t\tif (this.moduleSymbol && this.providedSymbols.size) {\n\t\t\tthrow new ClosureSourceError(\n\t\t\t\t`goog.provide call in goog module ${this.closureSourcePath}`\n\t\t\t);\n\t\t}\n\t\tif (!this.moduleSymbol && this.providedSymbols.size === 0) {\n\t\t\t// Such files can occur naturally while providing bulk of files via glob\n\t\t\tthrow new ClosureSourceError(\n\t\t\t\t`File ${this.closureSourcePath} is not a goog module nor provides anything.`,\n\t\t\t\tfalse /* not harmful */\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tfileName: this.closureSourcePath,\n\t\t\tprovides: this.moduleSymbol ? [this.moduleSymbol] : [...this.providedSymbols],\n\t\t\t// goog is implicitly required by every module\n\t\t\trequired: this.providedSymbols.has('goog') ? [] : ['goog', ...this.requiredSymbols],\n\t\t\tforwardDeclared: [...this.forwardDeclaredSymbols]\n\t\t}\n\t}\n}\n\nfunction toGoogPrimitiveRegex(name: string, assignment: boolean = false) {\n\tlet src = `goog\\\\.${name}\\\\(['\"](.*)['\"]\\\\)`\n\tif (assignment) {\n\t\tsrc = `(?:(?:var|let|const)\\\\s+[a-zA-Z0-9$_,:\\\\{\\\\}\\\\s]*\\\\s*=\\\\s*)?` + src;\n\t}\n\treturn new RegExp(`^\\\\s*` + src);\n}\n\nconst reGoogProvide = toGoogPrimitiveRegex('provide');\nconst reGoogModule = toGoogPrimitiveRegex('module');\nconst reGoogRequire = toGoogPrimitiveRegex('require', true);\nconst reGoogForwardDeclare = toGoogPrimitiveRegex('forwardDeclared', true);\nconst reGoogRequireType = toGoogPrimitiveRegex('requireType', true);\n// base.js of closure library goog.provide's \"goog\", even though it's not declared in it,\n// and is implicitly required by any module/library that access \"goog\" namespace.\n// Such a file is marked by /** @provideGoog */ comment.\nconst reProvideGoog = /@provideGoog/;\nconst reStartPureComment = /^\\s*\\/\\*\\*/;\nconst reEndComment = /\\*\\//;\n\nexport class ClosureSourceError extends Error {\n\tconstructor(msg: string, public fatal = true) {\n\t\tsuper(msg);\n\t}\n}\n\n"
  },
  {
    "path": "packages/tscc/src/log/Logger.ts",
    "content": "/**\n * @fileoverview Creates a logger instance, which provides the following functionalities:\n *  - Adding prefix\n *  - Adding a spinner that sticks at the bottom\n * It should be okay to have multiple instances that are writing to the same tty.\n */\nimport ora = require('ora');\nimport readline = require('readline');\nimport console = require('console');\nimport { hasSpinner } from './spinner'\n\nexport default class Logger {\n\tprivate console: Console\n\tconstructor(\n\t\tprivate prefix: string,\n\t\tprivate out: NodeJS.WritableStream = process.stderr\n\t) {\n\t\tthis.console = new console.Console(this.out);\n\t}\n\t/**\n\t * Analogous to console.log - applies basic formatting, adds a newline at the end.\n\t */\n\t@Logger.eraseSpinner\n\tlog(msg: string, ...args: any[]) {\n\t\tthis.console.log(this.prefix + msg, ...args);\n\t}\n\t/**\n\t * Analogous to process.stdout.write() - no formatting\n\t */\n\t@Logger.eraseSpinner\n\twrite(msg: string) {\n\t\tthis.out.write(msg);\n\t}\n\tprivate static eraseSpinner(target: Object, prop: string, desc: PropertyDescriptor) {\n\t\tlet origMethod = desc.value;\n\t\tdesc.value = function (this: Logger) {\n\t\t\tif (hasSpinner()) {\n\t\t\t\treadline.clearLine(this.out, 0);\n\t\t\t\t/*\n\t\t\t\t * Restore cursor position\n\t\t\t\t * {@link https://stackoverflow.com/questions/10585683/how-do-you-edit-existing-text-and-move-the-cursor-around-in-the-terminal}\n\t\t\t\t */\n\t\t\t\tthis.out.write('\\x1b[u');\n\t\t\t}\n\t\t\tReflect.apply(origMethod, this, arguments);\n\t\t\t// store cursor position & move to the newline\n\t\t\tthis.out.write('\\x1b[s');\n\t\t\tif (hasSpinner()) {\n\t\t\t\tthis.out.write('\\n');\n\t\t\t}\n\t\t}\n\t}\n}\n\n"
  },
  {
    "path": "packages/tscc/src/log/spinner.ts",
    "content": "import ora = require('ora');\n\nlet spinner: ora.Ora | undefined;\nlet timer: NodeJS.Timer | undefined;\n\n/**\n * Attach a spinner that sticks at the bottom of the stream,\n * indicating that a task is running.\n */\nexport function startTask(text: string) {\n\tif (hasSpinner()) unstick();\n\tspinner = ora({\n\t\ttext,\n\t\tstream: process.stderr,\n\t\tspinner: \"dots12\",\n\t\t// See https://github.com/theseanl/tscc/issues/70\n\t\t// If this option is not set, it can lead to very strange behaviors.\n\t\t// 'discarding stdin' does it by overriding globals and it is badly done.\n\t\tdiscardStdin: false\n\t});\n\tspinner.start();\n\tconst start = Date.now();\n\ttimer = setInterval(() => {\n\t\tspinner!.text = text + \" \" + toDDHHMMSS(Date.now() - start);\n\t}, 1000);\n}\n\nexport function succeed(text?: string) {\n\tif (!hasSpinner()) return;\n\tspinner!.succeed(text);\n\tclearInterval(timer!);\n\ttimer = undefined;\n}\n\nexport function fail(text?: string) {\n\tif (!hasSpinner()) return;\n\tspinner!.fail(text);\n\tclearInterval(timer!);\n\ttimer = undefined;\n}\n\n/**\n * Even if a task might have ended (via succeed or fail) the spinner will\n * still stick at the bottom. After calling this method, all subsequent\n * writes will happen below the spinner.\n */\nexport function unstick() {\n\tif (!hasSpinner()) return;\n\tif (spinner!.isSpinning) spinner!.stop();\n\tspinner = undefined;\n\tif (timer) {\n\t\tclearInterval(timer);\n\t\ttimer = undefined;\n\t}\n}\n\nexport function hasSpinner() {\n\treturn typeof spinner !== 'undefined';\n}\n\nfunction toDDHHMMSS(milliseconds: number) {\n\tlet sec_num = Math.floor(milliseconds / 1000);\n\tlet days = Math.floor(sec_num / 86400);\n\tlet hours = Math.floor(sec_num / 3600);\n\tlet minutes = Math.floor((sec_num - (hours * 3600)) / 60);\n\tlet seconds = sec_num - (hours * 3600) - (minutes * 60);\n\n\tlet out = '';\n\tif (days > 0) out += String(days) + \":\";\n\tif (days > 0 || hours > 0) out += String(hours) + \":\";\n\tout += String(minutes).padStart(2, \"0\");\n\tout += \":\";\n\tout += String(seconds).padStart(2, \"0\");\n\treturn out;\n}\n\n"
  },
  {
    "path": "packages/tscc/src/main.ts",
    "content": "#!/usr/bin/env node\n\nimport yargs = require('yargs/yargs');\nimport chalk = require('chalk');\nimport tscc, {TEMP_DIR, CcError, TsccError} from './tscc';\nimport {TsError} from './spec/TsccSpecWithTS'\nimport {IInputTsccSpecJSON, INamedModuleSpecs, TsccSpecError, primitives} from '@tscc/tscc-spec'\nimport {ClosureDepsError} from './graph/ClosureDependencyGraph'\nimport Logger from './log/Logger';\nimport console = require('console');\n\n/**\n * example: tscc -s src/tscc.spec.json -- --experimentalDecorators -- --assume_function_wrapper\n */\nasync function main(args: any) {\n\tif (args.clean) {\n\t\trequire('rimraf').sync(TEMP_DIR);\n\t\tconsole.log(`Removed ${TEMP_DIR}.`);\n\t\treturn 0;\n\t}\n\n\tif (args['module'] === undefined && args['spec'] === undefined) {\n\t\t// Assumes that --spec was set to the current working directory implicitly.\n\t\targs['spec'] = '.';\n\t}\n\n\tconst {tsccSpecJSON, tsArgs} = buildTsccSpecJSONAndTsArgsFromArgs(args);\n\tawait tscc(<IInputTsccSpecJSON>tsccSpecJSON, tsArgs);\n\n\treturn 0;\n}\n\nexport function parseTsccCommandLineArgs(args: string[], strict = true): {[key: string]: primitives | primitives[]} {\n\treturn <any>yargs()\n\t\t.scriptName('tscc')\n\t\t.usage(`tscc [--help] [--clean] [--spec <spec_file_path>] [-- <typescript_flags> [-- <closure_compiler_flags>]]`)\n\t\t.describe(\n\t\t\t'spec',\n\t\t\t`Perform compilation with tscc spec file at the specified path. ` +\n\t\t\t`Defaults to the current working directory.`\n\t\t)\n\t\t.string('spec')\n\t\t.describe(\n\t\t\t'module',\n\t\t\t`Module spec descriptions. ` +\n\t\t\t`Format: <name>:<entry_file>[:<dependency_name>[,<dependency2_name>[...]][:<extra_source>[,...]]]`\n\t\t)\n\t\t.string('module')\n\t\t.array('module')\n\t\t.describe(\n\t\t\t'external',\n\t\t\t'External module descriptions. Format: <module_name>:<global_name>'\n\t\t)\n\t\t.string('external')\n\t\t.array('external')\n\t\t.describe(\n\t\t\t'prefix',\n\t\t\t`Directory names to emit outputs in, or prefixes for output file names. ` +\n\t\t\t`It will just be prepended to module names, so if its last character is not a path separator, ` +\n\t\t\t`it will modify the output file's name. Sub-flags --prefix.cc and --prefix.rollup are available.`\n\t\t)\n\t\t.describe(\n\t\t\t'prefix.cc',\n\t\t\t`Prefix to be used only by closure compiler build.`\n\t\t)\n\t\t.describe(\n\t\t\t'prefix.rollup',\n\t\t\t`Prefix to be used only by rollup build.`\n\t\t)\n\t\t.describe(\n\t\t\t'debug',\n\t\t\t`A namespace for debugging options.`\n\t\t)\n\t\t.describe(\n\t\t\t'debug.persistArtifacts',\n\t\t\t`Writes intermediate tsickle outputs to .tscc_temp directory.`\n\t\t)\n\t\t.describe(\n\t\t\t'debug.ignoreWarningsPath',\n\t\t\t`Prevents tsickle warnings for files whose path contains substrings provided by this flag.`\n\t\t)\n\t\t.array('debug.ignoreWarningsPath')\n\t\t.describe(\n\t\t\t'clean',\n\t\t\t`Clear temporary files in .tscc_temp directory.`\n\t\t)\n\t\t.describe(\n\t\t\t'-',\n\t\t\t`Any flags after the first \"--\" and before the second \"--\" (if exists) ` +\n\t\t\t`will be provided to the typescript compiler.`\n\t\t)\n\t\t.describe(\n\t\t\t'{2}',\n\t\t\t`Any flags after the second \"--\" will be provided to the closure compiler.`\n\t\t)\n\t\t.epilogue(\n\t\t\t`For more information or bug reports, please visit https://github.com/theseanl/tscc.`\n\t\t)\n\t\t.alias({\n\t\t\t\"spec\": \"s\",\n\t\t\t\"h\": \"help\",\n\t\t\t\"v\": \"version\",\n\t\t})\n\t\t.parserConfiguration({\n\t\t\t'populate--': true,\n\t\t\t'camel-case-expansion': false\n\t\t})\n\t\t.strict(strict)\n\t\t.help('h')\n\t\t.version()\n\t\t.parse(args);\n}\n\nexport function buildTsccSpecJSONAndTsArgsFromArgs(args: any) {\n\tconst tsArgs = <string[]>args[\"--\"] || [];\n\tconst closureCompilerArgs: string[] = (<any>yargs()\n\t\t.parserConfiguration({'populate--': true})\n\t\t.parse(tsArgs))[\"--\"] || [];\n\n\tlet i = tsArgs.indexOf('--');\n\tif (i !== -1) {\n\t\ttsArgs.splice(i);\n\t}\n\n\tconst out: Partial<IInputTsccSpecJSON> = {};\n\n\t// module flags\n\t// Using \"--module\" instead of \"--modules\" looks more natural for a command line interface.\n\tlet moduleFlags: string[] = args[\"module\"];\n\tif (moduleFlags) {\n\t\tconst moduleFlagValue: INamedModuleSpecs[] = [];\n\t\tfor (let moduleFlag of moduleFlags) {\n\t\t\t// --modules chunk2:./src/chunk2.ts:chunk0,chunk1:css_renaming_map.js\n\t\t\tlet [moduleName, entry, dependenciesStr, extraSourcesStr] = moduleFlag.split(':');\n\t\t\tlet dependencies: string[] | undefined, extraSources: string[] | undefined;\n\t\t\tif (dependenciesStr) dependencies = dependenciesStr.split(',');\n\t\t\tif (extraSourcesStr) extraSources = extraSourcesStr.split(',');\n\t\t\tmoduleFlagValue.push({moduleName, entry, dependencies, extraSources})\n\t\t}\n\t\tout.modules = moduleFlagValue;\n\t}\n\n\t// external flags\n\t// --external react-dom:ReactDOM\n\tlet external: string[] = args[\"external\"]\n\tif (external) {\n\t\tconst externalValue: {[moduleName: string]: string} = {};\n\t\tfor (let externalEntry of external) {\n\t\t\tlet [moduleName, globalName] = externalEntry.split(':');\n\t\t\texternalValue[moduleName] = globalName;\n\t\t}\n\t\tout.external = externalValue;\n\t}\n\n\t// prefix flags\n\tif (args[\"prefix\"]) {\n\t\tout.prefix = args[\"prefix\"];\n\t}\n\n\t// compilerFlags flags\n\tif (closureCompilerArgs.length) {\n\t\tlet compilerFlags: any = yargs().parse(closureCompilerArgs);\n\t\t// delete special args produced by yargs\n\t\tdelete compilerFlags[\"_\"];\n\t\tdelete compilerFlags[\"$0\"];\n\t\tout.compilerFlags = <any>compilerFlags;\n\t}\n\n\t// debug flags\n\tlet debugArgs = args[\"debug\"];\n\tif (debugArgs && typeof debugArgs === 'object') {\n\t\tout.debug = debugArgs;\n\t}\n\n\t// spec file\n\tif (args[\"spec\"]) {\n\t\tout.specFile = args[\"spec\"];\n\t}\n\n\treturn {tsccSpecJSON: <IInputTsccSpecJSON>out, tsArgs}\n}\n\nif (require.main === module) {\n\tconst tsccWarning = new Logger(chalk.green('TSCC: '));\n\tconst tsWarning = new Logger(chalk.blue('TS: '));\n\n\tconst parsedArgs = parseTsccCommandLineArgs(process.argv.slice(2));\n\n\tmain(parsedArgs)\n\t\t.then(code => process.exit(code))\n\t\t.catch(e => {\n\t\t\tif (e instanceof TsccSpecError || e instanceof TsccError) {\n\t\t\t\ttsccWarning.log(chalk.red(e.message));\n\t\t\t} else if (e instanceof TsError) {\n\t\t\t\ttsWarning.log(chalk.red(e.message));\n\t\t\t} else if (e instanceof ClosureDepsError) {\n\t\t\t\ttsccWarning.log(chalk.red(e.message));\n\t\t\t} else if (e instanceof CcError) {\n\t\t\t\ttsccWarning.log(chalk.red(e.message));\n\t\t\t} else {\n\t\t\t\ttsccWarning.log(chalk.red(`The compilation has terminated with an unexpected error.`));\n\t\t\t\ttsccWarning.log(e.stack);\n\t\t\t\treturn process.exit(1);\n\t\t\t}\n\t\t\ttsccWarning.log(`The compilation has terminated with an error.`)\n\t\t\treturn process.exit(1);\n\t\t});\n}\n\n"
  },
  {
    "path": "packages/tscc/src/shared/PartialMap.ts",
    "content": "export default class PartialMap<K, V extends {}> extends Map<K, Partial<V>> {\n\tset(key: K, value: Partial<V>) {\n\t\tif (!this.has(key)) {\n\t\t\tsuper.set(key, value);\n\t\t} else {\n\t\t\tlet prevValue = this.get(key)!;\n\t\t\tObject.assign(prevValue, value);\n\t\t}\n\t\treturn this;\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/shared/array_utils.ts",
    "content": "export function riffle<T>(x: T, array: T[]): T[] {\n\tlet out: T[] = [];\n\tfor (let i = 0, l = array.length; i < l; i++) {\n\t\tout.push(x, array[i]);\n\t}\n\treturn out;\n}\n\nexport function flatten<T>(array: T[][]): T[] {\n\tlet out: T[] = [];\n\tfor (let i = 0, l = array.length; i < l; i++) {\n\t\tout.push(...array[i]);\n\t}\n\treturn out;\n}\n\nexport function union<T>(array1: T[], array2: T[]): T[] {\n\tlet out: T[] = array1.slice();\n\tfor (let i = 0, l = array2.length; i < l; i++) {\n\t\tlet el = array2[i];\n\t\tif (out.includes(el)) continue;\n\t\tout.push(el);\n\t}\n\treturn out;\n}\n"
  },
  {
    "path": "packages/tscc/src/shared/escape_goog_identifier.ts",
    "content": "/**\n * @fileoverview A valid goog.module name is a dot-separated sequence of legal property. Legal\n * property is a name that consists only of [a-zA-Z0-9._$]. Trailing, leading dots, or consecutive\n * dots are not allowed. Source: com.google.javascript.jscomp.GatherModuleMetadata.java error\n * message for JSC_INVALID_NAMESPACE_OR_MODULE_ID.\n *\n * This file provides an analogue of Javascript escape/unescape function pair for string identifiers\n * for goog.module, goog.provide, etc. One does not lose information after escaping so that we can\n * faithfully map converted module names to the original TS source file's name.\n */\nimport path = require('path');\n\nfunction codePoint(char: string) {return char.codePointAt(0)!;}\n/**************************************************************************************************/\nconst LOWERCASE_A_CODE_POINT = codePoint('a');\nconst LOWERCASE_Z_CODE_POINT = codePoint('z');\nconst UPPERCASE_A_CODE_POINT = codePoint('A');\nconst UPPERCASE_Z_CODE_POINT = codePoint('Z');\nconst PERIOD_CODE_POINT = codePoint('.');\nconst LOWER_DASH_CODE_POINT = codePoint('_');\nconst DOLLAR_SIGN_CODE_POINT = codePoint('$');\nconst ZERO_CODE_POINT = codePoint('0');\nconst NINE_CODE_POINT = codePoint('9');\nconst SEP = path.sep;\n/**************************************************************************************************/\nfunction isLatin(code: number) {\n\treturn ((LOWERCASE_A_CODE_POINT <= code && code <= LOWERCASE_Z_CODE_POINT) ||\n\t\t(UPPERCASE_A_CODE_POINT <= code && code <= UPPERCASE_Z_CODE_POINT));\n}\nfunction isNumber(code: number) {\n\treturn ZERO_CODE_POINT <= code && code <= NINE_CODE_POINT;\n}\nfunction isLowerDash(code: number) {\n\treturn code === LOWER_DASH_CODE_POINT;\n}\nfunction isPeriod(code: number) {\n\treturn code === PERIOD_CODE_POINT;\n}\nfunction isDollarSign(code: number) {\n\treturn code === DOLLAR_SIGN_CODE_POINT;\n}\n/**************************************************************************************************/\n/**\n *                   Latin  ⟹  Latin\n *                  number  ⟹  number\n *                     \"_\"  ⟹  \"_\"\n *          path separator  ⟹  \".\" (for ergonomical reason)\n *                     \".\"  ⟹  \"$_\"\n *     Any other character  ⟹  \"$\" followed by length 4 base36 representation of its code point,\n *                              left-padded with 0.\n *\n * This requires that the first character is not a path separator, in order to make sure that\n * the resulting escaped name does not start with \".\", which is disallowed in goog.module. One should\n * always feed relative paths.\n */\nexport function escapeGoogAdmissibleName(name: string): string {\n\tlet out = \"\";\n\tif (name[0] === SEP) throw new TypeError(\"Name cannot start with a path separator\");\n\tfor (let char of name) {\n\t\tlet code = codePoint(char);\n\t\tif (isLatin(code) || isNumber(code) || isLowerDash(code)) {\n\t\t\tout += char;\n\t\t} else if (char === SEP) {\n\t\t\tout += \".\";\n\t\t} else if (isPeriod(code)) {\n\t\t\tout += \"$_\";\n\t\t} else {\n\t\t\tout += \"$\" + code.toString(36).padStart(4, \"0\");\n\t\t}\n\t}\n\treturn out;\n}\nexport function unescapeGoogAdmissibleName(escapedName: string): string {\n\tlet out = \"\";\n\tlet i = 0;\n\tlet code: number;\n\t// charCodeAt returns NaN when an index is out of range.\n\twhile (!isNaN(code = escapedName.charCodeAt(i))) {\n\t\tif (isLatin(code) || isNumber(code) || isLowerDash(code)) {\n\t\t\tout += escapedName[i];\n\t\t\ti++;\n\t\t} else if (isPeriod(code)) {\n\t\t\tout += SEP;\n\t\t\ti++;\n\t\t} else if (isDollarSign(code)) {\n\t\t\t// If the next character is \"_\", add \".\"\n\t\t\tif (isLowerDash(escapedName.charCodeAt(i + 1))) {\n\t\t\t\tout += \".\";\n\t\t\t\ti += 2;\n\t\t\t} else {\n\t\t\t\t// Read next 4 chars\n\t\t\t\ttry {\n\t\t\t\t\tlet base32Codes = parseInt(escapedName.substr(i + 1, 4), 36);\n\t\t\t\t\tout += String.fromCodePoint(base32Codes);\n\t\t\t\t\ti += 5;\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new RangeError(`Invalid characters between position ${i + 1} and ${i + 4}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new RangeError(`Invalid character at position ${i}`);\n\t\t}\n\t}\n\treturn out;\n}\nexport function escapedGoogNameIsDts(escapedName: string) {\n\treturn escapedName.endsWith(\"$_d$_ts\");\n}\n"
  },
  {
    "path": "packages/tscc/src/shared/sourcemap_splice.ts",
    "content": "import {SourceMapConsumer, SourceMapGenerator, Mapping, RawSourceMap} from 'source-map';\n\n/**\n * From a file with sourcemap, splice intervals specified with the third argument\n * and translate sourcemaps accordingly.\n * @param content\n * @param map\n * @param spliceIntervals sorted, non-overlapping intervals to splice.\n */\nexport default async function spliceSourceMap(content: string, map: RawSourceMap, spliceIntervals: [number, number][]): Promise<RawSourceMap> {\n\tconst consumer = await new SourceMapConsumer(map);\n\tconst generator = new SourceMapGenerator({file: map.file});\n\n\tconst seeker = new Seeker(content, spliceIntervals);\n\n\tconsumer.eachMapping(({source, generatedLine, generatedColumn, originalLine, originalColumn, name}) => {\n\t\t// line numbers in mozilla/source-map are 1-based. column numbers are 0-based.\n\t\tseeker.seek(generatedLine - 1, generatedColumn);\n\t\tif (seeker.isInInterval()) return;\n\t\tlet transformedLine = seeker.getTransformedLine();\n\t\tlet transformedColumn = seeker.getTransformedColumn();\n\t\tconst mapping = getMapping(\n\t\t\tsource, transformedLine + 1, transformedColumn,\n\t\t\toriginalLine, originalColumn, name\n\t\t);\n\t\tgenerator.addMapping(mapping);\n\t});\n\n\treturn generator.toJSON();\n}\n\nconst placeholderString = undefined as any as string;\nconst placeholderNumber = undefined as any as number;\n\nconst mapping = {\n\tsource: placeholderString,\n\tgenerated: {\n\t\tline: placeholderNumber,\n\t\tcolumn: placeholderNumber\n\t},\n\toriginal: {\n\t\tline: placeholderNumber,\n\t\tcolumn: placeholderNumber\n\t},\n\tname: placeholderString\n};\n\nconst mappingWithoutOriginal = {\n\tsource: placeholderString,\n\tgenerated: {\n\t\tline: placeholderNumber,\n\t\tcolumn: placeholderNumber\n\t}\n};\n\nfunction getMapping(\n\tsource: string, generatedLine: number, generatedColumn: number,\n\toriginalLine: number, originalColumn: number, name: string\n): Mapping {\n\tif (typeof originalLine !== 'number' && typeof originalLine !== 'number') {\n\t\tmappingWithoutOriginal.source = source;\n\t\tmappingWithoutOriginal.generated.line = generatedLine;\n\t\tmappingWithoutOriginal.generated.column = generatedColumn;\n\t\treturn mappingWithoutOriginal as Mapping;\n\t}\n\tmapping.source = source;\n\tmapping.generated.line = generatedLine;\n\tmapping.generated.column = generatedColumn;\n\tmapping.original.line = originalLine;\n\tmapping.original.column = originalColumn;\n\tmapping.name = name;\n\treturn mapping;\n}\n\nexport function splitWithRegex(contents: string, regex: RegExp) {\n\tconst intervals: [number, number][] = [];\n\tlet prevEnd = 0;\n\tlet replacedContent = '';\n\tlet execRes: RegExpExecArray | null\n\twhile ((execRes = regex.exec(contents)) !== null) {\n\t\tlet removeStart = execRes.index;\n\t\tlet removeEnd = removeStart + execRes[0].length;\n\t\treplacedContent += contents.substring(prevEnd, removeStart);\n\t\tprevEnd = removeEnd;\n\t\tintervals.push([removeStart, removeEnd])\n\t}\n\treplacedContent += contents.substring(prevEnd);\n\treturn {contents: replacedContent, intervals}\n}\n\nexport class Seeker {\n\tconstructor(\n\t\tprivate contents: string,\n\t\tprivate intervals: [number, number][]\n\t) {}\n\t/*************** State machine state *****************/\n\t// Current cursor position descriptors\n\tprivate line = 0;\n\tprivate column = 0;\n\tprivate index = 0;\n\tprivate lineStart = 0; // Index of current line's start\n\tprivate intervalIndex = -1; // Index of last interval whose start comes before then or at the same point with the current index\n\tprivate accLine = 0;\n\tprivate accColumn = 0;\n\t/************* State machine state end ***************/\n\n\t/**\n\t * Seeks the last interval that intersects with the interval [0, index], starting from the current interval.\n\t * Returns a contribution of lengths occupied by intervals in [this.Index, index).\n\t * (Beware the parentheses)\n\t */\n\tprivate seekInterval(index: number) {\n\t\tlet {intervalIndex, index: prevIndex} = this;\n\t\tlet occupied = 0;\n\t\tif (intervalIndex === -1) intervalIndex = 0;\n\t\tlet interval = this.getInterval(intervalIndex);\n\t\twhile (interval && interval[0] <= index) {\n\t\t\tif (interval[1] > prevIndex) {\n\t\t\t\toccupied += min(interval[1], index) - max(interval[0], prevIndex);\n\t\t\t}\n\t\t\tinterval = this.getInterval(++intervalIndex);\n\t\t}\n\t\tthis.intervalIndex = intervalIndex - 1;\n\t\treturn occupied;\n\t}\n\tprivate seekWithinLine(nextColumn: number) {\n\t\tlet increment = nextColumn - this.column;\n\t\tlet nextIndex = this.index + increment;\n\n\t\t// Update column (line and lineStart stays the same)\n\t\tlet lineEnd = this.nextLineBreak();\n\t\tif (lineEnd !== -1 && nextIndex > lineEnd)\n\t\t\tthrow new Error('EOL');\n\t\tif (nextIndex >= this.contents.length) throw new Error('EOF');\n\n\t\tthis.column = nextColumn;\n\n\t\t// Update intervalIndex, accColumn (accLine stays the same)\n\t\tlet occupied = this.seekInterval(nextIndex);\n\t\tthis.accColumn += increment - occupied;\n\t\tthis.index = nextIndex;\n\t}\n\tprivate nextLine() {\n\t\t// Update line,column,lineStart\n\t\tlet lineStart = this.nextLineBreak() + 1;\n\t\tif (lineStart > 0 && this.contents.length <= lineStart)\n\t\t\tthrow new Error(`EOF`);\n\n\t\tthis.lineStart = lineStart;\n\t\tthis.line++;\n\t\tthis.column = 0;\n\t\tlet increment = lineStart - this.index;\n\n\t\t// Update interavlIndex, accLine, accColumn\n\t\t// Check if there is an interval containing lineStart - 1 (index of '\\n')\n\t\tlet occupied = this.seekInterval(lineStart - 1);\n\t\tlet interval = this.getInterval(this.intervalIndex);\n\n\t\tthis.index = lineStart; // Setting it after seekInterval call, as it requires prev index.\n\n\t\tif (!interval || interval[1] <= lineStart - 1) {\n\t\t\t// No interval contains the previous line break character - accLine will be increased.\n\t\t\tthis.accLine++;\n\t\t\tthis.accColumn = 0;\n\t\t\t// intervalIndex may need to proceed one step further,\n\t\t\t// as we are looking for the latest interval s.t. interval[0] <= lineStart\n\t\t\t// See test \"when interval ends with \\n\".\n\t\t\tlet nextInterval = this.getInterval(this.intervalIndex + 1);\n\t\t\tif (nextInterval && nextInterval[0] === lineStart) this.intervalIndex++;\n\t\t} else {\n\t\t\t// This interval contains the line break character.\n\t\t\t// In order to get # of occupied positions before the lineStart, we need to increase\n\t\t\t// occupied by 1, since the line break character is occupied by the current interval.\n\t\t\tthis.accColumn += increment - occupied - 1;\n\t\t}\n\t}\n\tseek(nextLine: number, nextColumn: number) {\n\t\twhile (nextLine > this.line) {\n\t\t\tthis.nextLine();\n\t\t}\n\t\tthis.seekWithinLine(nextColumn);\n\t}\n\n\t// Querying methods\n\tisInInterval(): boolean {\n\t\tlet currentInterval = this.getInterval(this.intervalIndex);\n\t\treturn currentInterval && currentInterval[1] > this.index;\n\t}\n\tgetTransformedLine(): number {\n\t\treturn this.accLine;\n\t}\n\tgetTransformedColumn(): number {\n\t\treturn this.accColumn;\n\t}\n\n\tprivate nextLineBreak(): number {\n\t\treturn this.contents.indexOf('\\n', this.index) || this.contents.length;\n\t}\n\tprivate getInterval(intervalIndex: number): [number, number] {\n\t\treturn this.intervals[intervalIndex];\n\t}\n}\n\nfunction max(a: number, b: number) {\n\treturn a > b ? a : b;\n}\n\nfunction min(a: number, b: number) {\n\treturn a > b ? b : a;\n}\n"
  },
  {
    "path": "packages/tscc/src/shared/vinyl_utils.ts",
    "content": "import stream = require('stream')\nimport Vinyl = require('vinyl');\nimport Logger from '../log/Logger';\nimport chalk = require('chalk');\nimport spliceSourceMap, {splitWithRegex} from './sourcemap_splice';\n\nimport {RawSourceMap} from 'source-map';\n\n// Custom property augmenting Vinyl interface used by gulp-sourcemaps\nconst SOURCE_MAP = 'sourceMap'\n\n/**\n * JSON file format that Closure Compiler accepts.\n * See `AbstractCommandLineRunner#JsonFileSpec`\n */\nexport declare interface IClosureCompilerInputJson {\n\tpath: string,\n\tsrc: string,\n\tsourceMap?: string\n}\n\n/**\n * JSON file format that Closure Compiler produces.\n * See `AbstractCommandLineRunner#outputJsonStream`\n * {@link https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java#L1517}\n * It is extremely weird that it accepts `sourceMap` as input but produces `source_map` as output.\n */\nexport declare interface IClosureCompilerOutputJson {\n\tpath: string,\n\tsrc: string,\n\tsource_map?: string\n}\n\n/**\n * Object produced by stream-json package\n */\ninterface ArrayStreamItem<T> {\n\tkey: number,\n\tvalue: T\n}\n\nabstract class LoggingTransformStream extends stream.Transform {\n\tabstract _rawTransform(data: any, encoding: BufferEncoding): any\n\tconstructor(\n\t\tprotected logger: Logger\n\t) {super({objectMode: true});}\n\tasync _transform(data: any, encoding: BufferEncoding, callback: stream.TransformCallback) {\n\t\tlet transformed: any;\n\t\ttry {\n\t\t\ttransformed = await this._rawTransform(data, encoding);\n\t\t} catch (e) {\n\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\tthis.logger.log(chalk.red('Error during post-transformation: '));\n\t\t\tthis.logger.log(error.stack!);\n\t\t\tcallback(error);\n\t\t\treturn;\n\t\t}\n\t\tcallback(null, transformed);\n\t}\n}\n\nexport class ClosureJsonToVinyl extends LoggingTransformStream {\n\tconstructor(\n\t\tprivate applySourceMap: boolean | undefined,\n\t\tlogger: Logger\n\t) {super(logger)}\n\t_rawTransform(data: ArrayStreamItem<IClosureCompilerOutputJson>, encoding: BufferEncoding) {\n\t\tif (!data) return data;\n\t\tconst json = data.value;\n\t\tconst vinyl = new Vinyl({\n\t\t\tpath: json.path,\n\t\t\tcontents: Buffer.from(json.src)\n\t\t});\n\t\tif (this.applySourceMap && json.source_map) {\n\t\t\t// Custom property used by gulp-sourcemaps and plugins supporting it\n\t\t\tvinyl[SOURCE_MAP] = JSON.parse(json.source_map);\n\t\t}\n\t\treturn vinyl;\n\t}\n}\n\nexport class RemoveTempGlobalAssignments extends LoggingTransformStream {\n\tasync _rawTransform(data: Vinyl, encoding: BufferEncoding) {\n\t\tif (data.isNull()) return data;\n\t\tconst origContents = data.contents!.toString(encoding);\n\t\t// Fast path\n\t\tif (!origContents.includes('__tscc_export_start__')) return data;\n\t\tif (!data[SOURCE_MAP]) { // Simple regex replace\n\t\t\tdata.contents = Buffer.from(origContents.replace(RemoveTempGlobalAssignments.reCcExport, ''));\n\t\t} else { // Perform sourcemap-aware replace\n\t\t\tconst origMap: RawSourceMap = data[SOURCE_MAP];\n\t\t\tconst {contents: replacedContents, intervals}\n\t\t\t\t= splitWithRegex(origContents, RemoveTempGlobalAssignments.reCcExport);\n\t\t\tconst replacedMap = await spliceSourceMap(origContents, origMap, intervals);\n\t\t\t// Modify data\n\t\t\tdata.contents = Buffer.from(replacedContents);\n\t\t\tdata[SOURCE_MAP] = replacedMap;\n\t\t}\n\t\treturn data;\n\t}\n\tprivate static reCcExport = /;?\\s*[\"']__tscc_export_start__[\"'][\\s\\S]*[\"']__tscc_export_end__[\"']\\s*/g;\n}\n\n"
  },
  {
    "path": "packages/tscc/src/spawn_compiler.ts",
    "content": "import Logger from './log/Logger';\nimport chalk = require('chalk');\nimport childProcess = require('child_process');\n\nexport default function spawnCompiler(providedArgs: string[], logger: Logger, debug?: boolean) {\n\tconst {bin, args} = getSupportedCompiler();\n\targs.push(...providedArgs);\n\n\tif (debug) logger.log(`args: ${bin} ` + args.join(' '));\n\n\tconst compilerProcess = childProcess.spawn(bin, args);\n\n\t// TODO consider moving this to tscc.ts.\n\tcompilerProcess.stderr.on('data', (data) => {\n\t\tlogger.log(data);\n\t})\n\tcompilerProcess.on('error', (err) => {\n\t\tlogger.log(chalk.red(`Closure compiler spawn error, Is java in your path?\\n${err.message}`));\n\t\t//\tonClose(1);\n\t});\n\treturn compilerProcess;\n}\n\nfunction getSupportedCompiler(): {bin: string, args: string[]} {\n\tconst pkgName = PlatformToCompilerPackageName[process.platform];\n\tif (pkgName) {\n\t\ttry {\n\t\t\t// Try resolving optional dependencies\n\t\t\treturn {bin: require(pkgName), args: []};\n\t\t} catch (e) {}\n\t}\n\t// Not found, defaults to JAVA version.\n\treturn {bin: 'java', args: ['-jar', require('google-closure-compiler-java')]};\n}\n\nenum PlatformToCompilerPackageName {\n\t'darwin' = 'google-closure-compiler-osx',\n\t'win32' = 'google-closure-compiler-windows',\n\t'linux' = 'google-closure-compiler-linux',\n\t'aix' = '',\n\t'android' = '',\n\t'freebsd' = '',\n\t'openbsd' = '',\n\t'sunos' = '',\n\t'cygwin' = '',\n\t'netbsd' = '',\n\t'haiku' = '',\n}\n"
  },
  {
    "path": "packages/tscc/src/spec/ITsccSpecWithTS.ts",
    "content": "import {ITsccSpec} from '@tscc/tscc-spec';\nimport * as ts from 'typescript'\n\nexport default interface ITsccSpecWithTS extends ITsccSpec {\n\tgetTSRoot(): string\n\tgetCompilerOptions(): Readonly<ts.CompilerOptions>\n\tgetCompilerHost(): ts.CompilerHost\n\tgetOutputFileNames(): string[]\n\t/**\n\t * --compilation_level: defaults to ADVANCED\n\t * --language_in: Derived from tsconfig's `target`\n\t * --language_out: defaults to ECMASCRIPT_NEXT\n\t * --chunk_output_prefix: determined from `prefix` key of tscc spec.\n\t */\n\tgetBaseCompilerFlags(): string[]\n\t/**\n\t * Returns a list of file names included in the TS project.\n\t */\n\tgetAbsoluteFileNamesSet(): Set<string>\n\t/**\n\t * For a given module name as used in import ... from ${moduleName}, returns a type reference file's\n\t * file name. Returns null if it cannot find a type definition for a module's name.\n\t */\n\tresolveExternalModuleTypeReference(moduleName: string): string | null;\n\t/**\n\t * Create a unique hash for a project, consisting of the absolute path of tsconfig,\n\t * absolute path of tsccspec, and their contents.\n\t */\n\tgetProjectHash(): string\n}\n\n"
  },
  {
    "path": "packages/tscc/src/spec/TsccSpecWithTS.ts",
    "content": "import {IInputTsccSpecJSON, ITsccSpecJSON, closureCompilerFlags, TsccSpec, TsccSpecError} from '@tscc/tscc-spec';\nimport * as ts from 'typescript';\nimport ITsccSpecWithTS from './ITsccSpecWithTS';\nimport path = require('path');\n\n\nexport class TsError extends Error {\n\tconstructor(\n\t\tpublic diagnostics: ReadonlyArray<ts.Diagnostic>\n\t) {\n\t\tsuper(ts.formatDiagnostics(diagnostics, ts.createCompilerHost({})));\n\t}\n}\n\ntype TWarningCallback = (msg: string) => void;\n\nexport default class TsccSpecWithTS extends TsccSpec implements ITsccSpecWithTS {\n\tstatic loadTsConfigFromArgs(tsArgs: string[], specRoot: string, onWarning: TWarningCallback) {\n\t\tconst {options, fileNames, errors} = ts.parseCommandLine(tsArgs);\n\t\tif (errors.length) {\n\t\t\tthrow new TsError(errors);\n\t\t}\n\t\tif (fileNames.length) {\n\t\t\tonWarning(`Files provided via TS args are ignored.`);\n\t\t}\n\t\t// If \"--project\" argument is supplied - load tsconfig from there, merge things with this.\n\t\t// Otherwise, we lookup from tsccSpecPath - this is what is different to \"tsc\" (which looks up\n\t\t// the current working directory).\n\t\t// I think this is a more reasonable behavior, since many users will just put spec.json and\n\t\t// tsconfig.json at the same directory, they will otherwise have to provide the same information\n\t\t// twice, once for tscc and once for tsc.\n\t\tconst configFileName = TsccSpecWithTS.findConfigFileAndThrow(options.project, specRoot);\n\t\treturn TsccSpecWithTS.loadTsConfigFromResolvedPath(configFileName, options);\n\t}\n\t// compilerOptions is a JSON object in the form of tsconfig.json's compilerOption value.\n\t// Its value will override compiler options.\n\tstatic loadTsConfigFromPath(tsConfigPath?: string, specRoot?: string, compilerOptions?: object) {\n\t\tconst configFileName = TsccSpecWithTS.findConfigFileAndThrow(tsConfigPath, specRoot);\n\t\tlet options: ts.CompilerOptions = {}, errors: ts.Diagnostic[];\n\t\tif (compilerOptions) {\n\t\t\t({options, errors} = ts.convertCompilerOptionsFromJson(\n\t\t\t\tcompilerOptions, path.dirname(configFileName)\n\t\t\t));\n\t\t\tif (errors.length) {\n\t\t\t\tthrow new TsError(errors);\n\t\t\t}\n\t\t}\n\t\treturn TsccSpecWithTS.loadTsConfigFromResolvedPath(configFileName, options);\n\t}\n\t// At least one among searchPath and defaultLocation must be non-null.\n\tprivate static findConfigFileAndThrow(searchPath?: string, defaultLocation?: string) {\n\t\tconst configFileName =\n\t\t\tTsccSpecWithTS.resolveSpecFile(searchPath, 'tsconfig.json', defaultLocation);\n\t\tif (configFileName === undefined) {\n\t\t\tthrow new TsccSpecError(\n\t\t\t\t`Cannot find tsconfig at ${TsccSpecWithTS.toDisplayedPath(searchPath ?? defaultLocation!)}.`\n\t\t\t)\n\t\t}\n\t\treturn configFileName;\n\t}\n\tprivate static loadTsConfigFromResolvedPath(configFileName: string, options: ts.CompilerOptions) {\n\t\tconst compilerHost: ts.ParseConfigFileHost = Object.create(ts.sys);\n\t\tcompilerHost.onUnRecoverableConfigFileDiagnostic = (diagnostic) => {throw new TsError([diagnostic]);}\n\t\tconst parsedConfig = ts.getParsedCommandLineOfConfigFile(configFileName, options, compilerHost)!;\n\t\tif (parsedConfig.errors.length) {\n\t\t\tthrow new TsError(parsedConfig!.errors);\n\t\t}\n\t\tconst projectRoot = path.dirname(configFileName);\n\t\treturn {projectRoot, parsedConfig};\n\t}\n\tstatic loadSpecWithTS(\n\t\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON,\n\t\ttsConfigPathOrTsArgs?: string | string[],\n\t\tcompilerOptionsOverride?: object,\n\t\tonTsccWarning: (msg: string) => void = noop\n\t) {\n\t\t// When TS project root is not provided, it will be assumed to be the location of tscc spec file.\n\t\tlet {tsccSpecJSON, tsccSpecJSONPath} = TsccSpecWithTS.loadSpecRaw(tsccSpecJSONOrItsPath);\n\t\tlet specRoot = path.dirname(tsccSpecJSONPath);\n\t\tlet {projectRoot, parsedConfig} = Array.isArray(tsConfigPathOrTsArgs) ?\n\t\t\tTsccSpecWithTS.loadTsConfigFromArgs(tsConfigPathOrTsArgs, specRoot, onTsccWarning) :\n\t\t\tTsccSpecWithTS.loadTsConfigFromPath(tsConfigPathOrTsArgs, specRoot, compilerOptionsOverride);\n\n\t\tTsccSpecWithTS.pruneCompilerOptions(parsedConfig.options, onTsccWarning);\n\t\treturn new TsccSpecWithTS(tsccSpecJSON, tsccSpecJSONPath, parsedConfig, projectRoot);\n\t}\n\t/**\n\t * Prune compiler options\n\t *  - \"module\" to \"commonjs\"\n\t *  - Warn when rootDir or outDir is used - these options are about `tsc` output directory structure,\n\t *    which is of no use with tscc.\n\t *  - Warn when target language is ES3 – Tsickle does not assume that the output can be lower than ES5,\n\t */\n\tstatic pruneCompilerOptions(options: ts.CompilerOptions, onWarning: TWarningCallback) {\n\t\tif (options.module !== ts.ModuleKind.CommonJS) {\n\t\t\tif (typeof options.module !== 'undefined') {\n\t\t\t\tonWarning(`Module option is set. tsickle converts TypeScript modules to Closure modules`\n\t\t\t\t\t+ `via CommonJS internally, so it will be overridden to \"commonjs\".`);\n\t\t\t}\n\t\t\toptions.module = ts.ModuleKind.CommonJS;\n\t\t}\n\t\tif (options.outDir) {\n\t\t\tonWarning(`--outDir option is set, but it is no-op for tscc.` +\n\t\t\t\t`Use prefix option in spec file to control output directory.`);\n\t\t\toptions.outDir = undefined;\n\t\t}\n\t\t/**\n\t\t * {@link https://github.com/angular/tsickle/commit/2050e902ea0fa59aa36f414cab192155167a9b06}\n\t\t * tsickle throws if `rootDir` is not provided, for presumably \"internal\" reasons. In tscc,\n\t\t * it normalizes paths to absolute paths, so the presence of `rootDir` does not have any\n\t\t * visible effect. If it is not supplied, we provide a default value of the config file's\n\t\t * containing root directory. Note that ts.CompilerOptions.configFilePath is an internal\n\t\t * property.\n\t\t */\n\t\tconst {configFilePath} = options;\n\t\tconst rootDir = configFilePath ? path.parse(configFilePath as string).root : '/';\n\t\tif (options.rootDir) {\n\t\t\tonWarning(`--rootDir is set, but it is no-op for tscc. It will internally set to ${rootDir}.`);\n\t\t}\n\t\toptions.rootDir = rootDir;\n\n\t\t// See https://github.com/angular/tsickle/commit/c0123da31e2924ad45c3f0a02d536e750028de7b,\n\t\t// where a check to emit `const` declaration is done by target === ScriptTarget.ES5.\n\t\tif (options.target === ts.ScriptTarget.ES3) {\n\t\t\tonWarning(`tsickle does not support targetting ES3, and it will be overridden to ES5`\n\t\t\t\t+ `Consider setting compilationFlags.language_out to ECMASCRIPT3`);\n\t\t\toptions.target = ts.ScriptTarget.ES5;\n\t\t} else if (typeof options.target === 'undefined') {\n\t\t\t// Prevent TS from treating unspecified target as a default value ES3.\n\t\t\toptions.target = ts.ScriptTarget.ES5;\n\t\t}\n\t\tif (!options.importHelpers) {\n\t\t\tonWarning(`tsickle uses a custom tslib optimized for closure compiler. importHelpers flag is set.`);\n\t\t\toptions.importHelpers = true;\n\t\t}\n\t\tif (options.removeComments) {\n\t\t\tonWarning(`Closure compiler relies on type annotations, removeComments flag is unset.`);\n\t\t\toptions.removeComments = false;\n\t\t}\n\t\tif (options.inlineSourceMap) {\n\t\t\tonWarning(`Inlining sourcemap is not supported. inlineSourceMap flag is unset.`);\n\t\t\toptions.inlineSourceMap = false;\n\t\t\t// inlineSource option depends on sourceMap or inlineSourceMap being enabled\n\t\t\t// so enabling sourceMap in order not to break tsc.\n\t\t\toptions.sourceMap = true;\n\t\t}\n\t\tif (options.incremental) {\n\t\t\t// Incremental compilation produces an additional .tsbuildinfo file. This triggers\n\t\t\t// unrecognized file extension error, so we disable it.\n\t\t\t// Currently I'm not sure that among typescript and closure compiler, which impacts the\n\t\t\t// compilation time more. If it is closure compiler, there would not be much sense to\n\t\t\t// support incremental compilation, for closure compiler does not support it. Otherwise,\n\t\t\t// I may try to attempt implementing it. To do so, we have to write intermediate output\n\t\t\t// like what we do with --debug.persistArtifacts.\n\t\t\tonWarning(`Incremental compilation is not supported. incremental flag is unset.`);\n\t\t\toptions.incremental = false;\n\t\t}\n\t\t// Silently unset flags related to declaration\n\t\toptions.declaration &&= false;\n\t\toptions.declarationMap &&= false;\n\t}\n\tprivate tsCompilerHost: ts.CompilerHost = ts.createCompilerHost(this.parsedConfig.options);\n\tprivate constructor(\n\t\ttsccSpec: ITsccSpecJSON,\n\t\tbasePath: string,\n\t\tprivate parsedConfig: ts.ParsedCommandLine,\n\t\tprivate projectRoot: string\n\t) {\n\t\tsuper(tsccSpec, basePath);\n\t\tthis.validateSpecWithTS();\n\t}\n\tprivate validateSpecWithTS() {\n\t\t// Checks that each of entry files is provided in tsConfig.\n\t\tconst fileNames = this.getAbsoluteFileNamesSet();\n\t\tconst modules = this.getOrderedModuleSpecs();\n\t\tfor (let module of modules) {\n\t\t\tif (!fileNames.has(module.entry)) {\n\t\t\t\tthrow new TsccSpecError(\n\t\t\t\t\t`An entry file ${module.entry} is not provided ` +\n\t\t\t\t\t`in a typescript project ${this.projectRoot}.`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tgetTSRoot() {\n\t\treturn this.projectRoot;\n\t}\n\tgetCompilerOptions() {\n\t\treturn this.parsedConfig.options;\n\t}\n\tgetCompilerHost() {\n\t\treturn this.tsCompilerHost;\n\t}\n\tprivate static readonly tsTargetToCcTarget = {\n\t\t[ts.ScriptTarget.ES5]: \"ECMASCRIPT5_STRICT\",\n\t\t[ts.ScriptTarget.ES2015]: \"ECMASCRIPT_2015\",\n\t\t[ts.ScriptTarget.ES2016]: \"ECMASCRIPT_2016\",\n\t\t[ts.ScriptTarget.ES2017]: \"ECMASCRIPT_2017\",\n\t\t[ts.ScriptTarget.ES2018]: \"ECMASCRIPT_2018\",\n\t\t[ts.ScriptTarget.ES2019]: \"ECMASCRIPT_2019\",\n\t\t[ts.ScriptTarget.ES2020]: \"ECMASCRIPT_2020\",\n\t\t[ts.ScriptTarget.ES2021]: \"ECMASCRIPT_2021\",\n\t\t[ts.ScriptTarget.ES2022]: \"ECMASCRIPT_NEXT\",\n\t\t[ts.ScriptTarget.ESNext]: \"ECMASCRIPT_NEXT\"\n\t}\n\tprivate static readonly chunkFormatToCcType = {\n\t\t['global']: \"GLOBAL_NAMESPACE\",\n\t\t['module']: \"ES_MODULES\"\n\t}\n\tgetOutputFileNames(): string[] {\n\t\treturn this.getOrderedModuleSpecs()\n\t\t\t.map(moduleSpec => {\n\t\t\t\tconst {moduleName} = moduleSpec;\n\t\t\t\treturn this.absolute(this.getOutputPrefix('cc')) + moduleName + '.js';\n\t\t\t});\n\t}\n\tprivate getDefaultFlags(): closureCompilerFlags {\n\t\t// Certain compiler options are guarded in pruneCompilerOptions method.\n\t\ttype PrunedCompilerOptions = ts.CompilerOptions & {\n\t\t\t// Typescript accepts an undocumented compilation target \"json\".\n\t\t\ttarget: Exclude<Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON>, ts.ScriptTarget.ES3>\n\t\t}\n\t\tlet {target, sourceMap, inlineSources} = this.parsedConfig.options as PrunedCompilerOptions;\n\n\t\tconst defaultFlags: closureCompilerFlags = {};\n\t\tdefaultFlags[\"language_in\"] = TsccSpecWithTS.tsTargetToCcTarget[target];\n\t\t// Closure compiler's default behavior is to output ECMASCRIPT_NEXT so that transpilation is\n\t\t// applied only when users explicitly request it. See:\n\t\t// https://github.com/google/closure-compiler/wiki/Releases#november-7-2021-v20211107\n\t\t// In version <=0.7.5, we had this set to ECMASCRIPT5.\n\t\tdefaultFlags[\"language_out\"] = \"ECMASCRIPT_NEXT\";\n\t\tdefaultFlags[\"compilation_level\"] = \"ADVANCED\";\n\t\tif (this.getOrderedModuleSpecs().length > 1) {\n\t\t\t// Multi-chunk build uses --chunk and --chunk_output_path_prefix.\n\t\t\t// This path will appear in a sourcemap that closure compiler generates - need to use\n\t\t\t// relative path in order not to leak global directory structure.\n\t\t\tdefaultFlags[\"chunk_output_path_prefix\"] = this.relativeFromCwd(this.getOutputPrefix('cc'));\n\t\t} else {\n\t\t\t// Single-chunk build uses --js_output_file.\n\t\t\tdefaultFlags[\"js_output_file\"] =\n\t\t\t\tthis.relativeFromCwd(this.getOutputPrefix('cc')) +\n\t\t\t\tthis.getOrderedModuleSpecs()[0].moduleName + '.js';\n\t\t}\n\t\tdefaultFlags[\"chunk_output_type\"] =\n\t\t\tthis.tsccSpec.chunkFormat && TsccSpecWithTS.chunkFormatToCcType[this.tsccSpec.chunkFormat] ||\n\t\t\t\"GLOBAL_NAMESPACE\";\n\t\tdefaultFlags[\"generate_exports\"] = true;\n\t\tdefaultFlags[\"export_local_property_definitions\"] = true;\n\n\t\tif (sourceMap) {\n\t\t\tdefaultFlags[\"create_source_map\"] = \"%outname%.map\";\n\t\t\tdefaultFlags[\"apply_input_source_maps\"] = true;\n\t\t}\n\t\tif (inlineSources) {\n\t\t\tdefaultFlags[\"source_map_include_content\"] = true;\n\t\t}\n\n\t\treturn defaultFlags;\n\t}\n\tgetBaseCompilerFlags() {\n\t\tconst baseFlags = this.tsccSpec.compilerFlags || {};\n\t\tconst defaultFlags = this.getDefaultFlags();\n\t\tconst flagsMap = Object.assign(defaultFlags, baseFlags);\n\n\t\tconst outFlags: string[] = [];\n\t\tconst pushFlag = (key: string, value: string | number | boolean) => {\n\t\t\tif (typeof value === 'boolean') {\n\t\t\t\tif (value === true) outFlags.push('--' + key);\n\t\t\t} else {\n\t\t\t\toutFlags.push('--' + key, String(value));\n\t\t\t}\n\t\t}\n\t\tfor (let [key, value] of Object.entries(flagsMap)) {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\tfor (let val of value) {\n\t\t\t\t\tpushFlag(key, val);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpushFlag(key, value);\n\t\t\t}\n\t\t}\n\t\treturn outFlags;\n\t}\n\tgetAbsoluteFileNamesSet() {\n\t\treturn new Set(\n\t\t\tthis.parsedConfig.fileNames\n\t\t\t\t.map(fileName => path.resolve(this.projectRoot, fileName))\n\t\t);\n\t}\n\tresolveExternalModuleTypeReference(moduleName: string) {\n\t\tconst resolved = ts.resolveTypeReferenceDirective(\n\t\t\tmoduleName,\n\t\t\t// Following convention of Typescript source code\n\t\t\tpath.join(this.projectRoot, '__inferred type names__.ts'),\n\t\t\tthis.getCompilerOptions(),\n\t\t\tthis.getCompilerHost()\n\t\t);\n\t\tif (resolved && resolved.resolvedTypeReferenceDirective &&\n\t\t\tresolved.resolvedTypeReferenceDirective.isExternalLibraryImport) {\n\t\t\treturn resolved.resolvedTypeReferenceDirective.resolvedFileName ?? null;\n\t\t}\n\t\treturn null;\n\t}\n\tgetProjectHash(): string {\n\t\treturn require('crypto').createHash('sha256')\n\t\t\t.update(\n\t\t\t\tthis.basePath + JSON.stringify(this.tsccSpec) +\n\t\t\t\tthis.projectRoot + JSON.stringify(this.parsedConfig.options)\n\t\t\t)\n\t\t\t.digest('hex');\n\t}\n}\n\nfunction noop() {}\n\n"
  },
  {
    "path": "packages/tscc/src/transformer/decorator_property_transformer.ts",
    "content": "/**\n * @fileoverview Decorators in TS is not compatible with Closure Compiler, as it generates\n * code that access a class' prototype property by string literals.\n * decoratorPropertyTransformer lookup occurence of such string literal property names,\n * and replaces it with appropriate `goog.reflect.objectProperty(<prop_name>, <target>)` call.\n *\n * Tsickle may at some point implement a similar feature. Currently it only implements some\n * other kinds of tranformation that is only made to make Angular work.\n *\n * Usage of goog.reflect.objectProperty is based on the following article:\n * {@link http://closuretools.blogspot.com/2016/06/using-polymer-with-closure-compiler-part-2.html}.\n *\n * In addition, we have to prevent this DevirtualizeMethods pass of closure compiler. However, there is\n * seem to be no stable way; see\n * nocollapse does not work - {@link https://github.com/google/closure-compiler/issues/2420}\n * sinkValue prevents inlining but does not prevent devirtualization\n * {@link https://github.com/google/closure-compiler/issues/2599}\n *\n * The pass is prevented when the property is accessed in a global scope, so we are creating\n * aaccesses of those and remove those via regex replace after the compilation. This is hacky and\n * not guaranteed to work but was the only way to make this work. Also has to be careful about\n * accessor decorators.\n */\nimport * as ts from 'typescript';\nimport {TsickleHost} from 'tsickle';\nimport TsHelperTransformer from './ts_helper_transformer';\n\nexport default function decoratorPropertyTransformer(tsickleHost: TsickleHost):\n\t(context: ts.TransformationContext) => ts.Transformer<ts.SourceFile> {\n\treturn (context: ts.TransformationContext) => {\n\t\treturn (sf: ts.SourceFile) => {\n\t\t\treturn new DecoratorTransformer(tsickleHost, context, sf).transformSourceFile();\n\t\t};\n\t};\n}\n\nclass DecoratorTransformer extends TsHelperTransformer {\n\tprotected HELPER_NAME = \"__decorate\";\n\n\tprivate tempGlobalAssignments: ts.Statement[] = [];\n\tprivate getId() {\n\t\treturn `tscc_global_access_name_${this.counter++}`;\n\t}\n\tprivate counter = 1;\n\n\tprotected onHelperCall(node: ts.CallExpression, googReflectImport: ts.Identifier) {\n\t\t// Found a candidate. Decorator helper call signature:\n\t\t// __decorate([decoratorsArray], <target>, <propertyName>, <desc>)\n\t\t// Note that class decorator only has 2 arguments.\n\t\tlet propNameLiteral = node.arguments[2];\n\t\tif (!propNameLiteral || !ts.isStringLiteral(propNameLiteral)) return;\n\t\tlet propName = propNameLiteral.text;\n\n\t\t// Create goog.reflect.objectProperty\n\t\tconst target = node.arguments[1];\n\t\tconst googReflectObjectProperty = ts.setTextRange(\n\t\t\tthis.factory.createCallExpression(\n\t\t\t\tthis.factory.createPropertyAccessExpression(\n\t\t\t\t\tgoogReflectImport,\n\t\t\t\t\tthis.factory.createIdentifier('objectProperty')\n\t\t\t\t),\n\t\t\t\tundefined,\n\t\t\t\t[\n\t\t\t\t\tthis.factory.createStringLiteral(propName),\n\t\t\t\t\tts.getMutableClone(target)\n\t\t\t\t]\n\t\t\t),\n\t\t\tpropNameLiteral\n\t\t);\n\t\t// Replace third argument of __decorate call to goog.reflect.objectProperty.\n\t\t// If TS output is in ES3 mode, there will be 3 arguments in __decorate call.\n\t\t// if its higher than or equal to ES5 mode, there will be 4 arguments.\n\t\t// The number of arguments must be preserved.\n\t\tconst caller = node.expression;\n\t\tconst decorateArgs = node.arguments.slice();\n\t\tdecorateArgs.splice(2, 1, googReflectObjectProperty);\n\t\tconst newCallExpression = this.factory.createCallExpression(caller, undefined, decorateArgs);\n\t\tconst globalAssignment = this.factory.createBinaryExpression(\n\t\t\tthis.factory.createElementAccessExpression(\n\t\t\t\tthis.factory.createIdentifier(\"self\"),\n\t\t\t\tthis.factory.createStringLiteral(this.getId())\n\t\t\t),\n\t\t\tthis.factory.createToken(ts.SyntaxKind.FirstAssignment),\n\t\t\tthis.factory.createPropertyAccessExpression(\n\t\t\t\tthis.factory.createParenthesizedExpression(ts.getMutableClone(target)),\n\t\t\t\tthis.factory.createIdentifier(propName)\n\t\t\t)\n\t\t);\n\t\tthis.tempGlobalAssignments.push(\n\t\t\tts.setEmitFlags(\n\t\t\t\tthis.factory.createExpressionStatement(globalAssignment),\n\t\t\t\tts.EmitFlags.NoSourceMap | ts.EmitFlags.NoTokenSourceMaps | ts.EmitFlags.NoNestedSourceMaps\n\t\t\t)\n\t\t);\n\t\treturn newCallExpression;\n\t}\n\n\tprotected combineStatements(stmts: ts.Statement[], googReflectImport: ts.Identifier) {\n\t\tsuper.combineStatements(stmts, googReflectImport);\n\t\tstmts.push(\n\t\t\tthis.factory.createExpressionStatement(this.factory.createStringLiteral(\"__tscc_export_start__\")),\n\t\t\tthis.factory.createBlock(this.tempGlobalAssignments),\n\t\t\tthis.factory.createExpressionStatement(this.factory.createStringLiteral('__tscc_export_end__'))\n\t\t);\n\t\treturn stmts;\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/transformer/dts_requiretype_transformer.ts",
    "content": "/**\n * @fileoverview Transforms `const tsickle_aaaa = goog.requireType(.....)` calls to external modules\n * into const tsickle_aaaa = mangled$namespace$declared$in$externs. When certain external module's\n * main type declaration file merely reexports some other file,\n *\n * (details to be tested, some other file or some other file in another module?)\n *\n * tsickle inserts such requireType statements referencing that file directly.\n *\n * Type declarations in such files are already declared in externs, so we can just alias that variable\n * with a namespace on which the file's declarations are written.\n *\n * This code was mostly same as the one we've used to transform goog.require(\"a-external_module\")\n * before we've switched to gluing module method.\n *\n * Codes are copied from commit\n * 1c9824461fcb71814466729b9c1424c4a60ef4ce (feat: use gluing modules for external module support)\n *\n * TODO: improve comment here and documentation.\n */\nimport * as ts from 'typescript';\nimport ITsccSpecWithTS from '../spec/ITsccSpecWithTS';\nimport {TsickleHost} from 'tsickle';\nimport {moduleNameAsIdentifier} from 'tsickle/out/src/annotator_host';\nimport {isGoogRequireLikeStatement, topLevelStatementTransformerFactory} from './transformer_utils';\nimport {escapedGoogNameIsDts, unescapeGoogAdmissibleName} from '../shared/escape_goog_identifier';\nimport path = require('path');\n\n/**\n * This is a transformer run after ts transformation, before googmodule transformation.\n *\n * In order to wire imports of external modules to their global symbols, we replace\n * top-level `require`s of external modules to an assignment of a local variable to\n * a global symbol. This results in no `goog.require` or `goog.requireType` emit.\n */\nexport default function dtsRequireTypeTransformer(spec: ITsccSpecWithTS, tsickleHost: TsickleHost)\n\t: (context: ts.TransformationContext) => ts.Transformer<ts.SourceFile> {\n\tconst externalModuleNames = spec.getExternalModuleNames();\n\n\treturn topLevelStatementTransformerFactory((node, fh) => {\n\t\tlet _ = isGoogRequireLikeStatement(node, \"requireType\");\n\t\tif (!_) return node;\n\t\tlet {importedUrl, newIdent} = _;\n\n\t\t// We are only interested in `requireType`ing .d.ts files.\n\t\tif (!escapedGoogNameIsDts(importedUrl)) return node;\n\t\t// If imported url is external module, no need to handle it further.\n\t\tif (externalModuleNames.includes(importedUrl)) return node;\n\t\t// origUrl will be a file path relative to the ts project root.\n\t\tlet origUrl = unescapeGoogAdmissibleName(importedUrl);\n\t\tlet absoluteOrigUrl = path.resolve(spec.getTSRoot(), origUrl);\n\t\t// We must figure out on what namespace the extern for this module is defined.\n\t\t// See tsickle/src/externs.js for precise logic. In our case, goog.requireType(....d.ts)\n\t\t// will be emitted for \"module .d.ts\", in which case a mangled name derived from a\n\t\t// .d.ts file's path is used. See how `moduleNamespace`, `rootNamespace` is constructed\n\t\t// in tsickle/src/externs.js.\n\t\t// This relies on the heuristic of tsickle, so must be carefully validated whenever tsickle updates.\n\t\tlet mangledNamespace = moduleNameAsIdentifier(tsickleHost, absoluteOrigUrl);\n\t\tif (newIdent.escapedText === mangledNamespace) {\n\t\t\t// Name of the introduced identifier coincides with the global identifier,\n\t\t\t// no need to emit things.\n\t\t\treturn setOriginalNode(fh.factory.createEmptyStatement(), node);\n\t\t}\n\t\t// Convert `const importedName = goog.requireType(\"module d.ts\")` to:\n\t\t// `const importedName = mangledNamespace;`\n\t\treturn setOriginalNode(\n\t\t\tfh.createVariableAssignment(\n\t\t\t\tnewIdent, fh.namespaceToQualifiedName(mangledNamespace),\n\t\t\t\t/* useConst */ tsickleHost.options.target !== ts.ScriptTarget.ES5\n\t\t\t),\n\t\t\tnode\n\t\t);\n\t});\n}\n\nfunction setOriginalNode<T extends ts.Node>(range: T, node: ts.Statement): T {\n\treturn ts.setOriginalNode<T>(ts.setTextRange(range, node), node);\n}\n"
  },
  {
    "path": "packages/tscc/src/transformer/goog_namespace_transformer.ts",
    "content": "import {isVariableRequireStatement, isGoogRequireLikeStatement, topLevelStatementTransformerFactory} from './transformer_utils';\n\nexport const googNamespaceTransformer = topLevelStatementTransformerFactory((stmt, fh) => {\n\t// Before googmodule transformer of tsickle, import statements we are looking for looks like\n\t// var goog = require('goog:goog').\n\tlet _ = isVariableRequireStatement(stmt);\n\tif (_) {\n\t\tlet {importedUrl, newIdent} = _;\n\t\tif (importedUrl === \"goog:goog\" && newIdent.text === \"goog\") {\n\t\t\treturn fh.factory.createNotEmittedStatement(stmt);\n\t\t}\n\t} else {\n\t\t_ = isGoogRequireLikeStatement(stmt, \"requireType\");\n\t\tif (_) {\n\t\t\tlet {importedUrl, newIdent} = _;\n\t\t\tif (importedUrl === \"goog\") {\n\t\t\t\treturn fh.createVariableAssignment(newIdent, fh.factory.createIdentifier(\"goog\"));\n\t\t\t}\n\t\t}\n\t}\n});\n"
  },
  {
    "path": "packages/tscc/src/transformer/rest_property_transformer.ts",
    "content": "import * as ts from 'typescript';\nimport {TsickleHost} from 'tsickle';\nimport TsHelperTransformer from './ts_helper_transformer';\n\nexport default function decoratorPropertyTransformer(tsickleHost: TsickleHost):\n\t(context: ts.TransformationContext) => ts.Transformer<ts.SourceFile> {\n\treturn (context: ts.TransformationContext) => {\n\t\treturn (sf: ts.SourceFile) => {\n\t\t\treturn new RestHelperTransformer(tsickleHost, context, sf).transformSourceFile();\n\t\t};\n\t};\n}\n\nclass RestHelperTransformer extends TsHelperTransformer {\n\tprotected HELPER_NAME = \"__rest\";\n\t/**\n\t * Rest helper call signature:\n\t * __rest(<target>, [propertiesArray])\n\t */\n\tprotected onHelperCall(node: ts.CallExpression, googReflectImport: ts.Identifier) {\n\t\tlet caller = node.expression;\n\t\tlet target = node.arguments[0];\n\t\tlet propertiesArray = <ts.ArrayLiteralExpression>node.arguments[1];\n\n\t\t// Create new array with goog.reflect.objectProperty\n\t\t// Note that for computed properties, Typescript creates a temp variable\n\t\t// that stores the computed value (_p), and put\n\t\t// ```\n\t\t// typeof _p === 'symbol' ? _c : _c + \"\"\n\t\t// ```\n\t\tconst convertedArray = ts.setTextRange(\n\t\t\tthis.factory.createArrayLiteralExpression(\n\t\t\t\tpropertiesArray.elements.map((propNameLiteral: ts.Expression) => {\n\t\t\t\t\tif (!ts.isStringLiteral(propNameLiteral)) return propNameLiteral;\n\t\t\t\t\tconst googReflectObjectProperty = ts.setTextRange(\n\t\t\t\t\t\tthis.factory.createCallExpression(\n\t\t\t\t\t\t\tthis.factory.createPropertyAccessExpression(\n\t\t\t\t\t\t\t\tgoogReflectImport,\n\t\t\t\t\t\t\t\tthis.factory.createIdentifier('objectProperty')\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tthis.factory.createStringLiteral(propNameLiteral.text),\n\t\t\t\t\t\t\t\tts.getMutableClone(target)\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t),\n\t\t\t\t\t\tpropNameLiteral\n\t\t\t\t\t);\n\t\t\t\t\treturn googReflectObjectProperty;\n\t\t\t\t})\n\t\t\t),\n\t\t\tpropertiesArray\n\t\t);\n\t\tconst restArgs = node.arguments.slice();\n\t\trestArgs.splice(1, 1, convertedArray);\n\t\tconst newCallExpression = this.factory.createCallExpression(caller, undefined, restArgs);\n\t\treturn newCallExpression;\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/transformer/transformer_utils.ts",
    "content": "import * as ts from 'typescript';\n\n/**\n * Returns the string argument if call is of the form\n * require('foo')\n */\nfunction extractRequire(call: ts.CallExpression): string | null {\n\t// Verify that the call is a call of a form require(...).\n\tconst ident = call.expression;\n\tif (!ts.isIdentifier(ident)) return null;\n\tif (ident.escapedText !== 'require') return null;\n\n\treturn getRequiredModuleName(call);\n}\n\ntype TGoogRequireLike = \"require\" | \"requireType\";\n\n/**\n * Verify that the call is a call of a form goog.require(...).\n * @param requireLike require, requireType, provides, ...\n */\nfunction extractGoogRequireLike(call: ts.CallExpression, requireLike: TGoogRequireLike): string | null {\n\tlet exp = call.expression;\n\tif (!ts.isPropertyAccessExpression(exp)) return null;\n\tif (!ts.isIdentifier(exp.expression) || exp.expression.escapedText !== 'goog') return null;\n\tif (exp.name.escapedText !== requireLike) return null;\n\n\treturn getRequiredModuleName(call);\n}\n\nfunction getRequiredModuleName(call: ts.CallExpression): string | null {\n\tif (call.arguments.length !== 1) return null;\n\n\t// Verify the call takes a single string argument and grab it.\n\tconst arg = call.arguments[0];\n\tif (!ts.isStringLiteral(arg)) return null;\n\treturn arg.text;\n}\n\ninterface IImportedVariable {\n\timportedUrl: string,\n\tnewIdent: ts.Identifier\n}\n\nexport function isVariableRequireStatement(stmt: ts.Statement): IImportedVariable | undefined {\n\tif (!ts.isVariableStatement(stmt)) return;\n\t// Verify it's a single decl (and not \"var x = ..., y = ...;\").\n\tif (stmt.declarationList.declarations.length !== 1) return;\n\tconst decl = stmt.declarationList.declarations[0];\n\n\t// Grab the variable name (avoiding things like destructuring binds).\n\tif (decl.name.kind !== ts.SyntaxKind.Identifier) return;\n\tif (!decl.initializer || !ts.isCallExpression(decl.initializer)) {\n\t\treturn;\n\t}\n\tconst importedUrl = extractRequire(decl.initializer);\n\tif (!importedUrl) return;\n\treturn {importedUrl, newIdent: decl.name};\n}\n\nexport function isGoogRequireLikeStatement(stmt: ts.Statement, requireLike: TGoogRequireLike): IImportedVariable | undefined {\n\tif (!ts.isVariableStatement(stmt)) return;\n\t// Verify it's a single decl (and not \"var x = ..., y = ...;\").\n\tif (stmt.declarationList.declarations.length !== 1) return;\n\tconst decl = stmt.declarationList.declarations[0];\n\n\t// Grab the variable name (avoiding things like destructuring binds).\n\tif (decl.name.kind !== ts.SyntaxKind.Identifier) return;\n\tif (!decl.initializer || !ts.isCallExpression(decl.initializer)) {\n\t\treturn;\n\t}\n\tconst importedUrl = extractGoogRequireLike(decl.initializer, requireLike);\n\tif (!importedUrl) return;\n\treturn {importedUrl, newIdent: decl.name};\n}\n\nexport function findImportedVariable(sf: ts.SourceFile, moduleName: string): ts.Identifier | undefined {\n\tfor (let stmt of sf.statements) {\n\t\tlet _ = isVariableRequireStatement(stmt);\n\t\tif (!_) continue;\n\t\tif (_.importedUrl !== moduleName) continue;\n\t\treturn _.newIdent\n\t}\n}\n\nexport function findGoogRequiredVariable(sf: ts.SourceFile, moduleName: string): ts.Identifier | undefined {\n\tfor (let stmt of sf.statements) {\n\t\tlet _ = isGoogRequireLikeStatement(stmt, \"require\");\n\t\tif (!_) continue;\n\t\tif (_.importedUrl !== moduleName) continue;\n\t\treturn _.newIdent;\n\t}\n}\n\n/**\n * The transformer needs to discern \"tslib\" function calls (called EmitHelpers in TS),\n * but they are simply identifiers of name `__decorate` and such, all the difference\n * lies in their `emitNode` internal property. Any functionality related to this is\n * under internal and is not available in public API.\n * This function currently access Node.emitNode.flags to achieve this\n */\nexport function identifierIsEmitHelper(ident: ts.Identifier): boolean {\n\tlet emitNode = (ident as any)[\"emitNode\"];\n\tif (emitNode === undefined) return false;\n\tlet flags = emitNode[\"flags\"];\n\tif (typeof flags !== \"number\") return false;\n\treturn (flags & ts.EmitFlags.HelperName) !== 0;\n}\n\n/**\n * A helper class that provides methods related to TS node factory functions. In body of TS\n * transformers, TS recommends to use ts.Factory object available as a property of a transformer\n * context object.\n */\nexport class NodeFactoryHelper {\n\tconstructor(\n\t\tpublic readonly factory: ts.NodeFactory\n\t) {}\n\t/** Creates a call expression corresponding to `goog.${methodName}(${literal})`. */\n\tcreateGoogCall(methodName: string, literal: ts.StringLiteral): ts.CallExpression {\n\t\treturn this.factory.createCallExpression(\n\t\t\tthis.factory.createPropertyAccessExpression(\n\t\t\t\tthis.factory.createIdentifier('goog'), methodName\n\t\t\t),\n\t\t\tundefined,\n\t\t\t[literal]\n\t\t);\n\t}\n\t// Creates a variable assignment var ${newIdent} = ${initializer}. Set constant = true to have\n\t// const instead of var.\n\tcreateVariableAssignment(newIdent: ts.Identifier, initializer: ts.Expression, useConst: boolean = false) {\n\t\treturn this.factory.createVariableStatement(\n\t\t\tundefined,\n\t\t\tthis.factory.createVariableDeclarationList(\n\t\t\t\t[\n\t\t\t\t\tthis.factory.createVariableDeclaration(\n\t\t\t\t\t\tnewIdent,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tinitializer\n\t\t\t\t\t)\n\t\t\t\t],\n\t\t\t\tuseConst ? ts.NodeFlags.Const : undefined\n\t\t\t)\n\t\t)\n\t}\n\tcreateSingleQuoteStringLiteral(text: string): ts.StringLiteral {\n\t\tconst stringLiteral = this.factory.createStringLiteral(text);\n\t\t(stringLiteral as any)['singleQuote'] = true;\n\t\treturn stringLiteral;\n\t}\n\tnamespaceToQualifiedName(namespace: string): ts.Expression {\n\t\tlet names = namespace.split('.');\n\t\tlet l = names.length;\n\t\tlet qualifiedName: ts.Expression = this.factory.createIdentifier(names[0]);\n\t\tfor (let i = 1; i < l; i++) {\n\t\t\tqualifiedName = this.factory.createPropertyAccessExpression(\n\t\t\t\tqualifiedName, this.factory.createIdentifier(names[i])\n\t\t\t);\n\t\t}\n\t\treturn qualifiedName;\n\t}\n}\n\n/**\n * A factory function that produces ts.TransformerFactory which iterates over a ts.SourceFile's\n * statements and replacing it if needed.\n */\nexport function topLevelStatementTransformerFactory(\n\ttransformStatement: (stmt: ts.Statement, fh: NodeFactoryHelper) => ts.Statement | void\n): ts.TransformerFactory<ts.SourceFile> {\n\treturn (context) => {\n\t\tconst factoryHelper = new NodeFactoryHelper(context.factory);\n\t\treturn (sf) => {\n\t\t\tconst stmts: ts.Statement[] = [];\n\t\t\tfor (const stmt of sf.statements) {\n\t\t\t\tlet newStmt = transformStatement(stmt, factoryHelper);\n\t\t\t\tstmts.push((newStmt ?? stmt) as ts.Statement);\n\t\t\t}\n\t\t\treturn context.factory.updateSourceFile(\n\t\t\t\tsf,\n\t\t\t\tts.setTextRange(\n\t\t\t\t\tcontext.factory.createNodeArray(stmts),\n\t\t\t\t\tsf.statements\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/transformer/ts_helper_transformer.ts",
    "content": "/**\n * @fileoverview Contains a common logic that is used to typescript transformers that transforms\n * ts helper (those in tslib) emits.\n */\nimport * as ts from 'typescript';\nimport {TsickleHost} from 'tsickle';\nimport {findImportedVariable, findGoogRequiredVariable, identifierIsEmitHelper, NodeFactoryHelper} from './transformer_utils'\n\nexport default abstract class TsHelperTransformer {\n\tconstructor(\n\t\tprivate tsickleHost: TsickleHost,\n\t\tprivate context: ts.TransformationContext,\n\t\tprivate sf: ts.SourceFile\n\t) {}\n\tprotected factory = this.context.factory;\n\tprotected abstract readonly HELPER_NAME: string;\n\n\t/**\n\t * Determines whether the given node is a tslib helper call. Such a call expression looks similar\n\t * to usual `__decorate(...)` function calls, except that the identifier node __decorate has\n\t * a hidden emitNode property. This is encoded in `identifierIsEmitHelper` call and this method\n\t * uses it.\n\t */\n\tprotected isTsGeneratedHelperCall(node: ts.Node): node is ts.CallExpression {\n\t\tif (!ts.isCallExpression(node)) return false;\n\t\tconst caller = node.expression;\n\t\tif (!ts.isIdentifier(caller)) return false;\n\t\tif (caller.escapedText !== ts.escapeLeadingUnderscores(this.HELPER_NAME)) return false;\n\t\tif (!identifierIsEmitHelper(caller)) return false;\n\t\treturn true;\n\t}\n\n\t/**\n\t * Queries whether a visiting node is a call to tslib helper functions, such as\n\t * `tslib_1.__decorate(...)` that is generated by the TS compiler, and if so, returns a new node.\n\t * Otherwise, return undefined.\n\t */\n\tprotected abstract onHelperCall(node: ts.CallExpression, googReflectImport: ts.Identifier): ts.CallExpression | undefined\n\n\tprivate maybeTsGeneratedHelperCall(node: ts.Node, googReflectImport: ts.Identifier): ts.Node | undefined {\n\t\tif (!this.isTsGeneratedHelperCall(node)) return;\n\t\treturn this.onHelperCall(node, googReflectImport);\n\t}\n\n\ttransformSourceFile(): ts.SourceFile {\n\t\tconst sf = this.sf;\n\t\t// There's nothing to do when tslib was not imported to the module.\n\t\tif (!findImportedVariable(sf, 'tslib')) return sf;\n\t\tconst existingGoogReflectImport =\n\t\t\tfindImportedVariable(sf, 'goog:goog.reflect') ||\n\t\t\tfindGoogRequiredVariable(sf, 'goog.reflect');\n\t\tconst googReflectImport =\n\t\t\texistingGoogReflectImport ||\n\t\t\tthis.factory.createIdentifier(`tscc_goog_reflect_injected`);\n\n\t\tlet foundTransformedDecorateCall = false;\n\t\tconst visitor = (node: ts.Node): ts.Node => {\n\t\t\tlet transformed = this.maybeTsGeneratedHelperCall(node, googReflectImport);\n\t\t\tif (transformed) {\n\t\t\t\tfoundTransformedDecorateCall = true;\n\t\t\t\treturn transformed;\n\t\t\t}\n\t\t\treturn ts.visitEachChild(node, visitor, this.context);\n\t\t};\n\n\t\tconst newSf = visitor(sf) as ts.SourceFile;\n\t\tif (!foundTransformedDecorateCall) return newSf;\n\t\tconst stmts = this.combineStatements(\n\t\t\tnewSf.statements.slice(),\n\t\t\texistingGoogReflectImport ? undefined : googReflectImport\n\t\t);\n\n\t\treturn this.factory.updateSourceFile(\n\t\t\tnewSf, ts.setTextRange(this.factory.createNodeArray(stmts), newSf.statements)\n\t\t);\n\t}\n\n\tprotected combineStatements(stmts: ts.Statement[], googReflectImport?: ts.Identifier) {\n\t\tif (!googReflectImport) return stmts;\n\t\tconst requireReflect = this.createGoogReflectRequire(googReflectImport);\n\t\tstmts.unshift(requireReflect);\n\t\treturn stmts;\n\t}\n\n\tprivate createGoogReflectRequire(ident: ts.Identifier) {\n\t\tconst fh = new NodeFactoryHelper(this.factory);\n\t\treturn fh.createVariableAssignment(\n\t\t\tident,\n\t\t\tfh.createGoogCall(\"require\", this.factory.createStringLiteral('goog.reflect')),\n\t\t\tthis.tsickleHost.options.target !== ts.ScriptTarget.ES5\n\t\t);\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/tscc.ts",
    "content": "import {IInputTsccSpecJSON} from '@tscc/tscc-spec';\nimport * as StreamArray from 'stream-json/streamers/StreamArray';\nimport * as tsickle from \"tsickle\";\nimport * as ts from \"typescript\";\nimport getDefaultLibs from './default_libs';\nimport ClosureDependencyGraph from './graph/ClosureDependencyGraph';\nimport TypescriptDependencyGraph from './graph/TypescriptDependencyGraph';\nimport Logger from './log/Logger';\nimport * as spinner from './log/spinner';\nimport {applyPatches, restorePatches} from './tsickle_patches/facade'\nimport {riffle, union} from './shared/array_utils';\nimport PartialMap from './shared/PartialMap';\nimport {ClosureJsonToVinyl, IClosureCompilerInputJson, RemoveTempGlobalAssignments} from './shared/vinyl_utils';\nimport {escapeGoogAdmissibleName} from './shared/escape_goog_identifier'\nimport spawnCompiler from './spawn_compiler';\nimport ITsccSpecWithTS from \"./spec/ITsccSpecWithTS\";\nimport TsccSpecWithTS, {TsError} from \"./spec/TsccSpecWithTS\";\nimport decoratorPropertyTransformer from './transformer/decorator_property_transformer';\nimport restPropertyTransformer from './transformer/rest_property_transformer';\nimport dtsRequireTypeTransformer from './transformer/dts_requiretype_transformer';\nimport {googNamespaceTransformer} from './transformer/goog_namespace_transformer';\nimport {getExternsForExternalModules, getGluingModules} from './external_module_support';\nimport fs = require('fs');\nimport path = require('path');\nimport stream = require('stream');\nimport {promisify} from 'util';\nimport fsExtra = require('fs-extra');\nimport vfs = require('vinyl-fs');\nimport upath = require('upath');\nimport chalk = require('chalk');\n\n\nexport const TEMP_DIR = \".tscc_temp\";\n\n/**\n * If the first argument is a string, it will try to lookup tscc.spec.json with the following priority:\n *  - The path itself\n *  - Files named tscc.spec.json or tscc.spec.js in a directory, regarding the path as a directory\n * If it is an object, it will treated as a JSON format object of the spec from a file located in\n * the current working directory. If no argument was passed, it will lookup the spec file on the\n * current working directory.\n * The second argument indicates the path to the tsconfig.json file.\n * The third argument is what would you put in tsconfig.json's compilerOptions. Options specified there\n * will override those of tsconfig.json.\n */\nexport default async function tscc(\n\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON,\n\ttsConfigPathOrTsArgs?: string,\n\tcompilerOptionsOverride?: object\n): Promise<void>\n/** @internal */\nexport default async function tscc(\n\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON,\n\ttsConfigPathOrTsArgs: string[],\n\tcompilerOptionsOverride?: object\n): Promise<void>\n/** @internal */\nexport default async function tscc(\n\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON,\n\ttsConfigPathOrTsArgs?: string | string[],\n\tcompilerOptionsOverride?: object\n): Promise<void> {\n\tconst tsccLogger = new Logger(chalk.green(\"TSCC: \"), process.stderr);\n\tconst tsLogger = new Logger(chalk.blue(\"TS: \"), process.stderr);\n\n\tconst tsccSpec = TsccSpecWithTS.loadSpecWithTS(\n\t\ttsccSpecJSONOrItsPath,\n\t\ttsConfigPathOrTsArgs,\n\t\tcompilerOptionsOverride,\n\t\t(msg: string) => {tsccLogger.log(msg)}\n\t);\n\n\tconst program = ts.createProgram(\n\t\t[...tsccSpec.getAbsoluteFileNamesSet()],\n\t\ttsccSpec.getCompilerOptions(),\n\t\ttsccSpec.getCompilerHost()\n\t);\n\tconst diagnostics = ts.getPreEmitDiagnostics(program);\n\tif (diagnostics.length) throw new TsError(diagnostics);\n\n\tconst tsDepsGraph = new TypescriptDependencyGraph(program)\n\ttsccSpec.getOrderedModuleSpecs().forEach(moduleSpec => tsDepsGraph.addRootFile(moduleSpec.entry));\n\tunion(tsccSpec.getExternalModuleNames(), tsccSpec.getCompilerOptions().types ?? [])\n\t\t.map(tsccSpec.resolveExternalModuleTypeReference, tsccSpec)\n\t\t.map(tsDepsGraph.addRootFile, tsDepsGraph);\n\t// If user explicitly provided `types` compiler option, it is more likely that its type is actually\n\t// used in user code.\n\n\tconst transformerHost = getTsickleHost(tsccSpec, tsDepsGraph, tsLogger);\n\n\t/**\n\t * Ideally, the dependency graph should be determined from ts sourceFiles, and the compiler\n\t * process can be spawned asynchronously before calling tsickle.\n\t * Then, we will be able to set `tsickleHost.shouldSkipTsickleProcessing` and the order of\n\t * files that are transpiled by tsickle. This has an advantage in that we can stream JSONs\n\t * in order that they came out from tsickle, cuz Closure compiler requires JSON files to be\n\t * sorted exactly as how js files would be sorted.\n\t *\n\t * As I recall, it was unsafe to use ModuleManifest returned from tsickle, cuz it does\n\t * not include forwardDeclares or something.\n\t * For now, we are computing the graph from the tsickle output in order to reuse\n\t * codes from closure-tools-helper.\n\t */\n\tconst closureDepsGraph = new ClosureDependencyGraph();\n\tconst tsickleOutput: PartialMap<string, IClosureCompilerInputJson> = new PartialMap();\n\n\tconst {writeFile, writeExterns, externPath} =\n\t\tgetWriteFileImpl(tsccSpec, tsickleOutput, closureDepsGraph);\n\n\tconst stdInStream = new stream.Readable({read: function () {}});\n\tconst pushImmediately = (arg: string | null) => setImmediate(pushToStream, stdInStream, arg);\n\n\t// ----- start tsickle call -----\n\tpushImmediately(\"[\")\n\n\t// Manually push tslib, goog(base.js), goog.reflect, which are required in compilation\n\tconst defaultLibsProvider = getDefaultLibs(tsccSpec.getTSRoot());\n\tdefaultLibsProvider.libs.forEach(({path, id}) => {\n\t\t// ..only when user-provided sources do not provide such modules\n\t\tif (closureDepsGraph.hasModule(id)) return;\n\t\twriteFile(path, fs.readFileSync(path, 'utf8'))\n\t})\n\n\t// Manually push gluing modules\n\tgetGluingModules(tsccSpec, transformerHost).forEach(({path, content}) => {\n\t\twriteFile(path, content)\n\t})\n\n\t// Manually push jsFiles, if there are any\n\tconst jsFiles = tsccSpec.getJsFiles();\n\tif (jsFiles.length) {\n\t\tjsFiles.forEach(path => {\n\t\t\twriteFile(path, fs.readFileSync(path, 'utf8'));\n\t\t})\n\t}\n\n\tlet result: tsickle.EmitResult;\n\ttry {\n\t\tapplyPatches();\n\t\tresult = tsickle.emit(program, transformerHost, writeFile, undefined, undefined, false, {\n\t\t\tafterTs: [\n\t\t\t\tgoogNamespaceTransformer,\n\t\t\t\tdtsRequireTypeTransformer(tsccSpec, transformerHost),\n\t\t\t\tdecoratorPropertyTransformer(transformerHost),\n\t\t\t\trestPropertyTransformer(transformerHost)\n\t\t\t]\n\t\t});\n\t} finally {\n\t\trestorePatches(); // Make sure that our patches are removed even if tsickle.emit throws.\n\t}\n\n\t// If tsickle errors, print diagnostics and exit.\n\tif (result.diagnostics.length) throw new TsError(result.diagnostics);\n\n\tconst {src, flags} = closureDepsGraph.getSortedFilesAndFlags(\n\t\ttsccSpec.getOrderedModuleSpecs().map(entry => ({\n\t\t\tmoduleId: transformerHost.pathToModuleName('', entry.entry),\n\t\t\t...entry\n\t\t}))\n\t);\n\n\tpushTsickleOutputToStream(src, tsccSpec, tsickleOutput, stdInStream, tsccLogger);\n\n\t// Write externs to a temp file.\n\t// ..only after attaching tscc's generated externs\n\tconst externs = tsickle.getGeneratedExterns(result.externs, tsccSpec.getTSRoot()) +\n\t\tgetExternsForExternalModules(tsccSpec, transformerHost);\n\twriteExterns(externs);\n\n\tpushImmediately(\"]\");\n\tpushImmediately(null);\n\t/// ----- end tsickle call -----\n\n\t/**\n\t * Spawn compiler process with module dependency information\n\t */\n\tconst ccLogger = new Logger(chalk.redBright(\"ClosureCompiler: \"), process.stderr);\n\tspinner.startTask(\"Closure Compiler\");\n\n\tconst compilerProcess = spawnCompiler([\n\t\t...tsccSpec.getBaseCompilerFlags(),\n\t\t...flags,\n\t\t'--json_streams', \"BOTH\",\n\t\t'--externs', externPath,\n\t\t...riffle('--externs', defaultLibsProvider.externs)\n\t], ccLogger, tsccSpec.debug().persistArtifacts);\n\n\tconst compilerProcessClose = new Promise<void>((resolve, reject) => {\n\t\tfunction onCompilerProcessClose(code: number) {\n\t\t\tif (code === 0) {\n\t\t\t\tspinner.succeed();\n\t\t\t\tspinner.unstick();\n\t\t\t\ttsccLogger.log(`Compilation success.`)\n\t\t\t\tif (tsccSpec.debug().persistArtifacts) {\n\t\t\t\t\ttsccLogger.log(tsccSpec.getOutputFileNames().join('\\n'));\n\t\t\t\t}\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\tspinner.fail(`Closure compiler error`);\n\t\t\t\tspinner.unstick();\n\t\t\t\treject(new CcError(`Closure compiler has exited with code ${code}`));\n\t\t\t}\n\t\t}\n\t\tcompilerProcess.on(\"close\", onCompilerProcessClose);\n\t});\n\n\tstdInStream\n\t\t.pipe(compilerProcess.stdin);\n\n\t// Use gulp-style transform streams to post-process cc output - see shared/vinyl_utils.ts.\n\t// TODO support returning gulp stream directly\n\tconst useSourceMap: boolean | undefined = tsccSpec.getCompilerOptions().sourceMap;\n\n\tconst writeCompilationOutput = promisify(stream.pipeline)(\n\t\tcompilerProcess.stdout,\n\t\t// jsonStreaming: true option makes the Parser of the stream-json package to fail gracefully\n\t\t// when no data is streamed. Currently this is not included in @types/stream-json. TODO make a\n\t\t// PR in Definitelytyped about this.\n\t\tStreamArray.withParser(<any>{jsonStreaming: true}),\n\t\tnew ClosureJsonToVinyl(useSourceMap, tsccLogger),\n\t\tnew RemoveTempGlobalAssignments(tsccLogger),\n\t\tvfs.dest('.', {sourcemaps: '.'})\n\t);\n\n\tawait Promise.all([compilerProcessClose, writeCompilationOutput])\n}\n\nexport class CcError extends Error {}\nexport class TsccError extends Error {}\nclass UnexpectedFileError extends TsccError {}\n\n/**\n * Remove `//# sourceMappingURL=...` from source TS output which typescript generates when\n * sourceMap is enabled. Closure Compiler does not recognize attached sourcemaps in Vinyl\n * if this comment is present.\n * TODO if closure is actually looking for sourcemaps within that url, check that if we can provide\n * sourcemap in such a way that closure can find it, and remove this workaround.\n */\nfunction removeSourceMappingUrl(tsOutput: string): string {\n\treturn tsOutput.replace(reSourceMappingURL, '');\n}\nconst reSourceMappingURL = /^\\/\\/[#@]\\s*sourceMappingURL\\s*=\\s*.*?\\s*$/mi;\n\nfunction getWriteFileImpl(spec: ITsccSpecWithTS, tsickleVinylOutput: PartialMap<string, IClosureCompilerInputJson>, closureDepsGraph: ClosureDependencyGraph) {\n\tconst tempFileDir = path.join(process.cwd(), TEMP_DIR, spec.getProjectHash());\n\tfsExtra.mkdirpSync(tempFileDir);\n\t// Closure compiler produces an error if output file's name is the same as one of\n\t// input files, which are in this case .js files. However, if such a file is an intermediate file\n\t// generated by TS, it is a legitimate usage. So we make file paths coming from TS virtual by\n\t// appending '.tsickle' to it.\n\t// See GH issue #82: When Windows-style path is used as a 'path' property of input, the Compiler\n\t// does not recognize path separators and fails to resolve paths in sourcemaps. Hence we replace\n\t// paths to unix-style paths just before we add it to input JSON object.\n\tconst toVirtualPath = (filePath: string) => {\n\t\tif (tsOutputs.includes(filePath)) filePath += '.tsickle';\n\t\tlet relPath = path.relative(spec.getTSRoot(), filePath);\n\t\tif (process.platform === 'win32') {\n\t\t\t// Convert to unix-style path only on Windows; on Unix, Windows-style path separator\n\t\t\t// is a valid directory/file name.\n\t\t\trelPath = upath.normalize(relPath);\n\t\t}\n\t\treturn relPath;\n\t};\n\tconst tsOutputs = [...spec.getAbsoluteFileNamesSet()].map(fileName => {\n\t\tlet ext = path.extname(fileName);\n\t\treturn fileName.slice(0, -ext.length) + '.js';\n\t});\n\tconst writeFile = (filePath: string, contents: string) => {\n\t\t// Typescript calls writeFile with not normalized path. 'spec.getAbsoluteFileNamesSet' returns\n\t\t// normalized paths. Fixes GH issue #81.\n\t\tfilePath = path.normalize(filePath);\n\t\t// Typescript calls writeFileCallback with absolute path.\n\t\t// On the contrary, \"file\" property of sourcemaps are relative path from ts project root.\n\t\t// For consistency, we convert absolute paths here to path relative to ts project root.\n\t\tif (spec.debug().persistArtifacts) {\n\t\t\t// filePath may contain colons which are not allowed in the middle of a path\n\t\t\t// such colons are a part of 'root', we are merely stripping it out.\n\t\t\tlet filePathMinusRoot = filePath.substring(path.parse(filePath).root.length);\n\t\t\tfsExtra.outputFileSync(path.join(tempFileDir, filePathMinusRoot), contents);\n\t\t}\n\t\tswitch (path.extname(filePath)) {\n\t\t\tcase '.js': {\n\t\t\t\tif (spec.getCompilerOptions().sourceMap) {\n\t\t\t\t\tcontents = removeSourceMappingUrl(contents)\n\t\t\t\t}\n\t\t\t\tclosureDepsGraph.addSourceByContent(filePath, contents);\n\t\t\t\ttsickleVinylOutput.set(filePath, {\n\t\t\t\t\tsrc: contents,\n\t\t\t\t\tpath: toVirtualPath(filePath)\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase '.map': {\n\t\t\t\tlet sourceFilePath = filePath.slice(0, -4);\n\t\t\t\ttsickleVinylOutput.set(sourceFilePath, {\n\t\t\t\t\tsourceMap: contents\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new UnexpectedFileError(`Unrecognized file emitted from tsc: ${filePath}.`)\n\t\t}\n\t}\n\n\tconst writeExterns = (contents: string) => {\n\t\tfs.writeFileSync(externPath, contents);\n\t}\n\tconst externPath = path.join(tempFileDir, \"externs_generated.js\");\n\treturn {writeFile, writeExterns, externPath}\n}\n\nfunction pushToStream(stream: stream.Readable, ...args: (string | null)[]) {\n\tfor (let arg of args) stream.push(arg);\n}\n\nfunction pushTsickleOutputToStream(\n\tsrc: ReadonlyArray<string>, // file names, ordered to be pushed to compiler sequentially\n\ttsccSpec: ITsccSpecWithTS,\n\ttsickleVinylOutput: PartialMap<string, IClosureCompilerInputJson>,\n\tstdInStream: stream.Readable,\n\tlogger: Logger\n) {\n\tlet isFirstFile = true;\n\tconst pushToStdInStream = (...args: string[]) => {\n\t\tpushToStream(stdInStream, ...args);\n\t};\n\tconst pushVinylToStdInStream = (json: IClosureCompilerInputJson) => {\n\t\tif (isFirstFile) isFirstFile = false;\n\t\telse pushToStdInStream(\",\");\n\t\tpushToStdInStream(JSON.stringify(json));\n\t}\n\tif (tsccSpec.debug().persistArtifacts) {\n\t\tlogger.log(`File orders:`);\n\t\tsrc.forEach(sr => logger.log(sr));\n\t}\n\tsetImmediate(() => {\n\t\tsrc.forEach(name => {\n\t\t\tlet out = <IClosureCompilerInputJson>tsickleVinylOutput.get(name);\n\t\t\tif (!out) {\n\t\t\t\tlogger.log(`File not emitted from tsickle: ${name}`);\n\t\t\t} else {\n\t\t\t\tpushVinylToStdInStream(out);\n\t\t\t}\n\t\t})\n\t});\n}\n\nfunction getTsickleHost(tsccSpec: ITsccSpecWithTS, tsDependencyGraph: TypescriptDependencyGraph, logger: Logger): tsickle.TsickleHost {\n\tconst options = tsccSpec.getCompilerOptions();\n\tconst compilerHost = tsccSpec.getCompilerHost();\n\t// Non-absolute file names are resolved from the TS project root.\n\tconst fileNamesSet = tsccSpec.getAbsoluteFileNamesSet();\n\tconst externalModuleData = tsccSpec.getExternalModuleDataMap();\n\n\tconst ignoreWarningsPath = tsccSpec.debug().ignoreWarningsPath || [\"/node_modules/\"];\n\n\tconst transformerHost: tsickle.TsickleHost = {\n\t\t// required since tsickle 0.41.0, currently only used in transpiling `goog.tsMigration*ExportsShim`.\n\t\trootDirsRelative(filename: string) {\n\t\t\treturn filename;\n\t\t},\n\t\tshouldSkipTsickleProcessing(fileName: string) {\n\t\t\t// Non-absolute files are resolved relative to a typescript project root.\n\t\t\tconst absFileName = path.resolve(tsccSpec.getTSRoot(), fileName);\n\t\t\t// This may include script(non-module) files that is specified in tsconfig. Such files\n\t\t\t// are not discoverable by dependency checking.\n\t\t\tif (fileNamesSet.has(absFileName)) return false;\n\t\t\t// Previously, we've processed all files that are in the same node_modules directory of type\n\t\t\t// declaration file for external modules. The current behavior with including transitive\n\t\t\t// dependencies only will have the same effect on such files, because `ts.createProgram`\n\t\t\t// anyway adds only such files to the program. So this update will in effect include strictly\n\t\t\t// larger set of files.\n\t\t\treturn !tsDependencyGraph.hasFile(absFileName);\n\t\t},\n\t\tshouldIgnoreWarningsForPath(fileName: string) {\n\t\t\treturn true; // Just a stub, maybe add configuration later.\n\t\t\t// controls whether a warning will cause compilation failure.\n\t\t},\n\t\tgoogmodule: true,\n\t\ttransformDecorators: true,\n\t\ttransformTypesToClosure: true,\n\t\t// This controlls whether @suppress annotation will be added to fileoverview comments or\n\t\t// not. https://github.com/angular/tsickle/commit/e83542d20cfabb17b2012013917d8c6df35fd227\n\t\t// Prior to this commit, tsickle had added @suppress annotations unconditionally.\n\t\tgenerateExtraSuppressions: true,\n\t\ttypeBlackListPaths: new Set(),\n\t\tuntyped: false,\n\t\tlogWarning(warning) {\n\t\t\tif (warning.file) {\n\t\t\t\tlet {fileName} = warning.file;\n\t\t\t\tfor (let i = 0, l = ignoreWarningsPath.length; i < l; i++) {\n\t\t\t\t\tif (fileName.indexOf(ignoreWarningsPath[i]) !== -1) return;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.log(ts.formatDiagnostic(warning, compilerHost));\n\t\t},\n\t\toptions,\n\t\t/**\n\t\t * The name suggests that it supports import from './dir' that resolves to './dir/index.ts'.\n\t\t * In effect, enabling this make `pathToModuleName` to be fed with\n\t\t */\n\t\tconvertIndexImportShorthand: true,\n\t\tmoduleResolutionHost: compilerHost,\n\t\tfileNameToModuleId: (fileName) => path.relative(process.cwd(), fileName),\n\t\t/**\n\t\t * Unlike the default function that tsickle uses, here we are actually resolving\n\t\t * the imported name with typescript's API. This is safer for consumers may use\n\t\t * custom path mapping using \"baseUrl\", \"paths\" , but at the cost of relinquishing\n\t\t * deterministic output based on a single file.\n\t\t */\n\t\tpathToModuleName: (context: string, fileName: string) => {\n\t\t\t// 'tslib' is always considered as an external module.\n\t\t\tif (fileName === 'tslib') return 'tslib';\n\t\t\tif (externalModuleData.has(fileName)) {\n\t\t\t\tlet data = externalModuleData.get(fileName)!;\n\t\t\t\t// Module names specified as external are not resolved, which in effect cause\n\t\t\t\t// googmodule transformer to emit module names verbatim in `goog.require()`.\n\t\t\t\tif (!data.isFilePath) return escapeGoogAdmissibleName(fileName);\n\t\t\t}\n\t\t\t// Resolve module via ts API\n\t\t\tconst resolved = ts.resolveModuleName(fileName, context, options, compilerHost);\n\t\t\tif (resolved && resolved.resolvedModule) {\n\t\t\t\tfileName = resolved.resolvedModule.resolvedFileName;\n\t\t\t}\n\t\t\t// resolve relative to the ts project root.\n\t\t\tfileName = path.relative(tsccSpec.getTSRoot(), fileName);\n\t\t\treturn escapeGoogAdmissibleName(fileName);\n\t\t}\n\t}\n\n\treturn transformerHost;\n}\n"
  },
  {
    "path": "packages/tscc/src/tsickle_patches/facade.ts",
    "content": "/**\n * @fileoverview This contains functions to apply various patches to tsickle. For more details, see\n * each modules. This must be applied and restored synchronously before and after tsickle runs.\n */\n\nimport {patchTsickleResolveModule, restoreTsickleResolveModule} from './patch_tsickle_module_resolver';\nimport {patchTsickleDecoratorTransformer, restoreTsickleDecoratorTransformer} from './patch_tsickle_decorator_transformer';\n\nexport function applyPatches() {\n\tpatchTsickleResolveModule();\n\tpatchTsickleDecoratorTransformer();\n}\n\nexport function restorePatches() {\n\trestoreTsickleResolveModule();\n\trestoreTsickleDecoratorTransformer();\n}\n"
  },
  {
    "path": "packages/tscc/src/tsickle_patches/patch_tsickle_decorator_transformer.ts",
    "content": "/**\n * @fileoverview This patches tsickle's decorator transformer exported from `decorator.ts` module\n * into a no-op transformer, see {@link https://github.com/angular/tsickle/issues/1164}. what\n * tsickle's transformer does is logical copy of what we have been doing, which chronologically\n * came later. In tscc, we in addition adds property access statements that is going to be removed\n * after closure compilation. Tsickle's transformation loses some information -- we need to know\n * what _decorate call is the ones we are concerned with, but for example, after tsickle's\n * transformation, one cannot distinguish [__tsickle_googReflect(...)]() { ... } with the one\n * generated by tsickle. Also, there are subtle differences concerning es3 output (which is ts's\n * default target).\n */\n\nlet original: typeof import('tsickle/out/src/decorators').transformDecoratorsOutputForClosurePropertyRenaming | undefined;\n\nexport function patchTsickleDecoratorTransformer() {\n\tif (!original) {\n\t\tconst decorators: typeof import('tsickle/out/src/decorators') = require('tsickle/out/src/decorators');\n\t\tlet original = decorators.transformDecoratorsOutputForClosurePropertyRenaming;\n\t\tdecorators.transformDecoratorsOutputForClosurePropertyRenaming = () => {\n\t\t\treturn (context) => (x => x);\n\t\t};\n\t}\n}\n\nexport function restoreTsickleDecoratorTransformer() {\n\tif (original) {\n\t\trequire('tsickle/src/decorators').transformDecoratorsOutputForClosurePropertyRenaming = original;\n\t\toriginal = undefined;\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/src/tsickle_patches/patch_tsickle_module_resolver.ts",
    "content": "/**\n * @fileoverview This patches tsickle's `resolveModuleName` function exported from `googmodule.ts`\n * in order to work around angular/tsickle#1039. {@link https://github.com/angular/tsickle/issues/1039}\n * Main goal is to make tsickle generates correct externs for lodash in that it does not cause Closure Compiler error.\n * In order to do so, we need to resolve relative paths in `declare module \"../..\"` to a file path.\n */\nimport * as ts from 'typescript';\nimport path = require('path');\n\n/**\n * From an absolute file name, extract its containing folder in node_modules.\n * Maps\n * /.../my-package/node_modules/external-package/a/b/c/d.js\n * to /.../my-package/node_modules/external-package\n */\nexport function getPackageBoundary(fileName: string): string {\n\tlet segments = path.normalize(fileName).split(path.sep);\n\tlet i = segments.lastIndexOf(\"node_modules\");\n\tlet packageName = segments[i + 1];\n\tif (typeof packageName === 'string' && packageName.startsWith(\"@\")) {\n\t\t/**\n\t\t * Scoped packages, see\n\t\t * {@link https://nodejs.org/api/modules.html#modules_all_together}, LOAD_PACKAGE_EXPORTS\n\t\t */\n\t\ti++;\n\t}\n\tlet moduleDir = segments.slice(0, i + 2).join(path.sep);\n\treturn moduleDir + path.sep; // Note that this becomes '/' when node_modules is not found.\n}\n\nfunction resolveModuleName(\n\thost: {\n\t\toptions: ts.CompilerOptions,\n\t\tmoduleResolutionHost: ts.ModuleResolutionHost\n\t},\n\tpathOfImportingFile: string,\n\timported: string\n): string {\n\tconst resolved = ts.resolveModuleName(\n\t\timported,\n\t\tpathOfImportingFile,\n\t\thost.options,\n\t\thost.moduleResolutionHost\n\t);\n\tif (!resolved || !resolved.resolvedModule) {\n\t\treturn imported;\n\t}\n\tconst resolvedModule = resolved.resolvedModule.resolvedFileName;\n\t// check if resolvedModule pierces node_modules package boundary of pathOfImportingFile\n\tconst importingFileBoundary = getPackageBoundary(pathOfImportingFile);\n\tconst resolvedFileBoundary = getPackageBoundary(resolvedModule);\n\tif (importingFileBoundary !== resolvedFileBoundary) {\n\t\t// Do not resolve it, \"must specially be handled by loaders anyway\"\n\t\treturn imported;\n\t}\n\treturn resolvedModule;\n}\n\nlet original: typeof import('tsickle/out/src/googmodule').resolveModuleName | undefined;\nexport function patchTsickleResolveModule() {\n\tif (!original) {\n\t\tconst googmodule: typeof import('tsickle/out/src/googmodule') = require('tsickle/out/src/googmodule');\n\t\toriginal = googmodule.resolveModuleName;\n\t\tgoogmodule.resolveModuleName = resolveModuleName;\n\t}\n}\n\nexport function restoreTsickleResolveModule() {\n\tif (original) {\n\t\trequire('tsickle/out/src/googmodule').resolveModuleName = original;\n\t\toriginal = undefined;\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/__snapshots__/golden_test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`tscc e2e case_1: case_1 1`] = `\nArray [\n  \"a.js\",\n  \"b.js\",\n  \"c.js\",\n]\n`;\n\nexports[`tscc e2e case_1: case_1/a.js 1`] = `\n\"var b=new (function(){function a(){}a.prototype.g=function(){console.log(\\\\\"methodUsedByA\\\\\")};a.prototype.h=function(){console.log(\\\\\"methodUsedByB\\\\\")};return a}());b.g();console.log(\\\\\"ac\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_1: case_1/b.js 1`] = `\n\"b.h();console.log(\\\\\"bba\\\\\");console.log(\\\\\"bc\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_1: case_1/c.js 1`] = `\n\"console.log(\\\\\"ac\\\\\");console.log(\\\\\"bc\\\\\");console.log(\\\\\"cc\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_2_sourcemaps: case_2_sourcemaps 1`] = `\nArray [\n  \"a.js\",\n  \"a.js.map\",\n]\n`;\n\nexports[`tscc e2e case_2_sourcemaps: case_2_sourcemaps/a.js 1`] = `\n\"console.log(\\\\\"Hello world!\\\\\");\n//# sourceMappingURL=a.js.map\n\"\n`;\n\nexports[`tscc e2e case_2_sourcemaps: case_2_sourcemaps/a.js.map 1`] = `\"{\\\\\"version\\\\\":3,\\\\\"file\\\\\":\\\\\".tscc_temp/case_2_sourcemaps/a.js\\\\\",\\\\\"lineCount\\\\\":1,\\\\\"mappings\\\\\":\\\\\"AACCA,OAAQC,CAAAA,GAAR,CAECC,cAFD;\\\\\",\\\\\"sources\\\\\":[\\\\\"a.ts\\\\\"],\\\\\"names\\\\\":[\\\\\"console\\\\\",\\\\\"log\\\\\",\\\\\"b\\\\\"]}\"`;\n\nexports[`tscc e2e case_3_sourcemaps_with_decorators: case_3_sourcemaps_with_decorators 1`] = `\nArray [\n  \"a.js\",\n  \"a.js.map\",\n]\n`;\n\nexports[`tscc e2e case_3_sourcemaps_with_decorators: case_3_sourcemaps_with_decorators/a.js 1`] = `\n\"var h=class{b(){console.log(\\\\\"a\\\\\")}};(function(d,b,c,e){var f=arguments.length,a=3>f?b:null===e?e=Object.getOwnPropertyDescriptor(b,c):e,g;if(\\\\\"object\\\\\"===typeof Reflect&&Reflect&&\\\\\"function\\\\\"===typeof Reflect.decorate)a=Reflect.decorate(d,b,c,e);else for(var k=d.length-1;0<=k;k--)if(g=d[k])a=(3>f?g(a):3<f?g(b,c,a):g(b,c))||a;return 3<f&&a&&Object.defineProperty(b,c,a),a})([function(d,b,c){return c}],h.prototype,\\\\\"b\\\\\",null);(new h).b();\n//# sourceMappingURL=a.js.map\n\"\n`;\n\nexports[`tscc e2e case_3_sourcemaps_with_decorators: case_3_sourcemaps_with_decorators/a.js.map 1`] = `\"{\\\\\"version\\\\\":3,\\\\\"sources\\\\\":[\\\\\"a.ts\\\\\",\\\\\"../../../../third_party/tsickle/third_party/tslib/tslib.js\\\\\"],\\\\\"names\\\\\":[\\\\\"module$exports$a$_ts.A\\\\\",\\\\\"b\\\\\",\\\\\"console\\\\\",\\\\\"log\\\\\",\\\\\"exports.__decorate\\\\\",\\\\\"decorators\\\\\",\\\\\"target\\\\\",\\\\\"key\\\\\",\\\\\"desc\\\\\",\\\\\"c\\\\\",\\\\\"arguments\\\\\",\\\\\"length\\\\\",\\\\\"r\\\\\",\\\\\"Object\\\\\",\\\\\"getOwnPropertyDescriptor\\\\\",\\\\\"d\\\\\",\\\\\"Reflect\\\\\",\\\\\"i\\\\\",\\\\\"defineProperty\\\\\",\\\\\"decorator\\\\\",\\\\\"prop\\\\\",\\\\\"prototype\\\\\"],\\\\\"mappings\\\\\":\\\\\"AAIA,IAAAA,EAAA,KAAA,CAECC,CAAC,EAAA,CAAIC,OAAQC,CAAAA,GAAR,CAAY,GAAZ,CAAJ,CAFF,CCsDqBC,UAAS,CAACC,CAAD,CAAaC,CAAb,CAAqBC,CAArB,CAA0BC,CAA1B,CAAgC,CAAA,IACtDC,EAAIC,SAAUC,CAAAA,MADwC,CAChCC,EAAQ,CAAJ,CAAAH,CAAA,CAAQH,CAAR,CAA0B,IAAT,GAAAE,CAAA,CAAgBA,CAAhB,CAAuBK,MAAOC,CAAAA,wBAAP,CAAgCR,CAAhC,CAAwCC,CAAxC,CAAvB,CAAsEC,CAD3D,CACiEO,CAG3H,IAAuB,QAAvB,GAAI,MAAOC,QAAX,EAAmCA,OAAnC,EAA6E,UAA7E,GAA8C,MAAOA,QAAA,CAAA,QAArD,CAAyFJ,CAAA,CAAII,OAAA,CAAA,QAAA,CAAoBX,CAApB,CAAgCC,CAAhC,CAAwCC,CAAxC,CAA6CC,CAA7C,CAA7F,KACK,KAAK,IAAIS,EAAIZ,CAAWM,CAAAA,MAAfM,CAAwB,CAAjC,CAAyC,CAAzC,EAAoCA,CAApC,CAA4CA,CAAA,EAA5C,CAAiD,GAAIF,CAAJ,CAAQV,CAAA,CAAWY,CAAX,CAAR,CAAuBL,CAAA,EAAS,CAAJ,CAAAH,CAAA,CAAQM,CAAA,CAAEH,CAAF,CAAR,CAAmB,CAAJ,CAAAH,CAAA,CAAQM,CAAA,CAAET,CAAF,CAAUC,CAAV,CAAeK,CAAf,CAAR,CAA4BG,CAAA,CAAET,CAAF,CAAUC,CAAV,CAAhD,GAAmEK,CAChJ,OAAW,EAAJ,CAAAH,CAAA,EAASG,CAAT,EAAcC,MAAOK,CAAAA,cAAP,CAAsBZ,CAAtB,CAA8BC,CAA9B,CAAmCK,CAAnC,CAAd,CAAqDA,CANF,CAAzCR,CDnDpB,CAAA,CAPDe,QAAkB,CAACb,CAAD,CAASc,CAAT,CAA2BZ,CAA3B,CAAkD,CACnE,MAAOA,EAD4D,CAOnE,CAAA,CAFUR,CAAAqB,CAAAA,SAEV,CAFU,GAEV,CAFU,IAEV,CAEOpB,EAAP,IAAID,CAAGC,EAAAA,CAAR\\\\\",\\\\\"file\\\\\":\\\\\".tscc_temp/case_3_sourcemaps_with_decorators/a.js\\\\\"}\"`;\n\nexports[`tscc e2e case_4_external: case_4_external 1`] = `\nArray [\n  \"a.js\",\n]\n`;\n\nexports[`tscc e2e case_4_external: case_4_external/a.js 1`] = `\n\"var a=CollidesWithGlobalName;anExternalModule.a();window.this_should_survive=!0;a.b();\n\"\n`;\n\nexports[`tscc e2e case_5_object_spread: case_5_object_spread 1`] = `\nArray [\n  \"a.js\",\n]\n`;\n\nexports[`tscc e2e case_5_object_spread: case_5_object_spread/a.js 1`] = `\n\"function h(a,c){var e={},b;for(b in a)Object.prototype.hasOwnProperty.call(a,b)&&0>c.indexOf(b)&&(e[b]=a[b]);if(null!=a&&\\\\\"function\\\\\"===typeof Object.getOwnPropertySymbols){var f=0;for(b=Object.getOwnPropertySymbols(a);f<b.length;f++)0>c.indexOf(b[f])&&Object.prototype.propertyIsEnumerable.call(a,b[f])&&(e[b[f]]=a[b[f]])}return e};class l{g(a,c){({b:a}=c);h(c,[\\\\\"b\\\\\"]);c=h(a,[\\\\\"d\\\\\"]);console.log(c)}}(function(a,c,e,b){var f=arguments.length,g=3>f?c:null===b?b=Object.getOwnPropertyDescriptor(c,e):b,k;if(\\\\\"object\\\\\"===typeof Reflect&&Reflect&&\\\\\"function\\\\\"===typeof Reflect.decorate)g=Reflect.decorate(a,c,e,b);else for(var m=a.length-1;0<=m;m--)if(k=a[m])g=(3>f?k(g):3<f?k(c,e,g):k(c,e))||g;return 3<f&&g&&Object.defineProperty(c,e,g),g})([function(a,c,e){a=h(e,[\\\\\"value\\\\\"]);console.log(a);e.value={}}],l.prototype,\\\\\"g\\\\\",null);\n(new l).g({},{b:{c:{},d:{}},e:{},f:{},h:{}});const n={a:{},b:{},c:{}},p=h(n,[\\\\\"c\\\\\"]);window.d=p;\n\"\n`;\n\nexports[`tscc e2e case_6_type_only_references: case_6_type_only_references 1`] = `\nArray [\n  \"1.js\",\n  \"2.js\",\n]\n`;\n\nexports[`tscc e2e case_6_type_only_references: case_6_type_only_references/1.js 1`] = `\n\"window.b=a=>{a({b(){}})};\n\"\n`;\n\nexports[`tscc e2e case_6_type_only_references: case_6_type_only_references/2.js 1`] = `\n\"(new class{b(){console.log(\\\\\"boo\\\\\")}}).b();\n\"\n`;\n\nexports[`tscc e2e case_7_lodash_style_external_module_declaration: case_7_lodash_style_external_module_declaration 1`] = `\nArray [\n  \"a.js\",\n]\n`;\n\nexports[`tscc e2e case_7_lodash_style_external_module_declaration: case_7_lodash_style_external_module_declaration/a.js 1`] = `\n\"var a=lodash;window.exported=a.exported;window.exported_from_augment=a.exported_from_augment;\n\"\n`;\n\nexports[`tscc e2e case_8_dts_requiretype: case_8_dts_requiretype 1`] = `\nArray [\n  \"module.js\",\n]\n`;\n\nexports[`tscc e2e case_8_dts_requiretype: case_8_dts_requiretype/module.js 1`] = `\n\"var c=external;window.a=imported.b();window.b=c.a;\n\"\n`;\n\nexports[`tscc e2e case_9_ts_in_node_modules: case_9_ts_in_node_modules 1`] = `\nArray [\n  \"index.js\",\n]\n`;\n\nexports[`tscc e2e case_9_ts_in_node_modules: case_9_ts_in_node_modules/index.js 1`] = `\n\"console.log(1);\n\"\n`;\n\nexports[`tscc e2e case_10_unsafe_module_name_and_script_dts: case_10_unsafe_module_name_and_script_dts 1`] = `\nArray [\n  \"index.js\",\n]\n`;\n\nexports[`tscc e2e case_10_unsafe_module_name_and_script_dts: case_10_unsafe_module_name_and_script_dts/index.js 1`] = `\n\"console.log(unsafeModuleName.variableNameThatShouldntBeMangled.propertyNameThatShouldntBeMangled);\n\"\n`;\n\nexports[`tscc e2e case_11_referencing_goog: case_11_referencing_goog 1`] = `\nArray [\n  \"dependent.js\",\n  \"entry.js\",\n]\n`;\n\nexports[`tscc e2e case_11_referencing_goog: case_11_referencing_goog/dependent.js 1`] = `\n\"var b={key:\\\\\"value\\\\\"};\\\\\"key\\\\\"===a[\\\\\" \\\\\"]&&console.log(b[a[\\\\\" \\\\\"]]);\n\"\n`;\n\nexports[`tscc e2e case_11_referencing_goog: case_11_referencing_goog/entry.js 1`] = `\n\"var goog=goog||{},a=this||self;console.log(\\\\\"Debugging\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_12_using_jsFiles: case_12_using_jsFiles 1`] = `\nArray [\n  \"entry.js\",\n]\n`;\n\nexports[`tscc e2e case_12_using_jsFiles: case_12_using_jsFiles/entry.js 1`] = `\n\"console.log(1);\n\"\n`;\n\nexports[`tscc e2e case_13_chunk_format_global: case_13_chunk_format_global 1`] = `\nArray [\n  \"a.js\",\n  \"b.js\",\n  \"c.js\",\n]\n`;\n\nexports[`tscc e2e case_13_chunk_format_global: case_13_chunk_format_global/a.js 1`] = `\n\"var b=new (function(){function a(){}a.prototype.g=function(){console.log(\\\\\"methodUsedByA\\\\\")};a.prototype.h=function(){console.log(\\\\\"methodUsedByB\\\\\")};return a}());b.g();console.log(\\\\\"ac\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_13_chunk_format_global: case_13_chunk_format_global/b.js 1`] = `\n\"b.h();console.log(\\\\\"bba\\\\\");console.log(\\\\\"bc\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_13_chunk_format_global: case_13_chunk_format_global/c.js 1`] = `\n\"console.log(\\\\\"ac\\\\\");console.log(\\\\\"bc\\\\\");console.log(\\\\\"cc\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_14_chunk_format_module: case_14_chunk_format_module 1`] = `\nArray [\n  \"a.js\",\n  \"b.js\",\n  \"c.js\",\n]\n`;\n\nexports[`tscc e2e case_14_chunk_format_module: case_14_chunk_format_module/a.js 1`] = `\n\"var b=new (function(){function a(){}a.prototype.g=function(){console.log(\\\\\"methodUsedByA\\\\\")};a.prototype.h=function(){console.log(\\\\\"methodUsedByB\\\\\")};return a}());b.g();console.log(\\\\\"ac\\\\\");export{b};\n\"\n`;\n\nexports[`tscc e2e case_14_chunk_format_module: case_14_chunk_format_module/b.js 1`] = `\n\"import{b}from\\\\\"./a.js\\\\\";b.h();console.log(\\\\\"bba\\\\\");console.log(\\\\\"bc\\\\\");\n\"\n`;\n\nexports[`tscc e2e case_14_chunk_format_module: case_14_chunk_format_module/c.js 1`] = `\n\"import\\\\\"./a.js\\\\\";console.log(\\\\\"ac\\\\\");console.log(\\\\\"bc\\\\\");console.log(\\\\\"cc\\\\\");\n\"\n`;\n"
  },
  {
    "path": "packages/tscc/test/e2e/golden_test.ts",
    "content": "///<reference types=\"jest\"/>\nimport tscc, {TEMP_DIR} from '../../src/tscc';\nimport path = require('path');\nimport upath = require('upath');\nimport fs = require('fs');\n\nconst fsp = fs.promises;\n\ndescribe(`tscc e2e`, function () {\n\t// Create output in temp directory, compare its contents with golden files\n\tconst samplesRoot = path.join(__dirname, './sample/');\n\tconst directories = fs.readdirSync(samplesRoot, {withFileTypes: true})\n\t\t.filter(dirent => dirent.isDirectory())\n\t\t.map(dirent => dirent.name);\n\n\tconst TIMEOUT = 30 * 1000; // 20 seconds\n\n\ttest.each(directories)(`%s`, async function (dirName) {\n\t\tconst projectRoot = path.join(samplesRoot, dirName);\n\n\t\tawait tscc(projectRoot);\n\n\t\tconst generatedFiles = (await fsp.readdir(path.join(TEMP_DIR, dirName), {withFileTypes: true}))\n\t\t\t.filter(dirent => dirent.isFile())\n\t\t\t.map(dirent => dirent.name)\n\t\t\t.sort();\n\n\t\texpect(generatedFiles).toMatchSnapshot(dirName);\n\t\tawait Promise.all(generatedFiles.map(async (fileName) => {\n\t\t\tlet content = await fsp.readFile(path.join(TEMP_DIR, dirName, fileName), 'utf8')\n\t\t\t// Apparently Closure Compiler is emitting OS-style paths in output sourcemap. Here we\n\t\t\t// pick up sourcemaps, and normalize path in its `file` property to make snapshots\n\t\t\t// indepent of the OS.\n\t\t\tif (path.extname(fileName) === '.map') {\n\t\t\t\tlet sourceMap = JSON.parse(content);\n\t\t\t\tsourceMap.file = upath.toUnix(sourceMap.file);\n\t\t\t\tcontent = JSON.stringify(sourceMap);\n\t\t\t}\n\t\t\texpect(content).toMatchSnapshot(dirName + '/' + fileName);\n\t\t}))\n\t}, TIMEOUT)\n})\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/a.ts",
    "content": "import {IAmUsedByAandB} from './ab'\n\nclass ClassUsedByAandB implements IAmUsedByAandB {\n\tmethodUsedByA() {\n\t\tconsole.log('methodUsedByA');\n\t}\n\tmethodUsedByB() {\n\t\tconsole.log('methodUsedByB');\n\t}\n}\n\nexport const a = new ClassUsedByAandB();\nexport function callA(a: IAmUsedByAandB) {\n\ta.methodUsedByA();\n}\n\na.methodUsedByA();\n\nexport function ac() {\n\tconsole.log('ac');\n}\n\nac();\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/ab.ts",
    "content": "export interface IAmUsedByAandB {\n\tmethodUsedByA(): void\n\tmethodUsedByB(): void\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/b.ts",
    "content": "import {a, callA} from './a';\nimport {bb} from './bb';\nimport {bc} from './bc';\n\na.methodUsedByB();\ncallA(bb);\nbc();\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/bb.ts",
    "content": "import {IAmUsedByAandB} from './ab'\nexport const bb: IAmUsedByAandB = {\n\tmethodUsedByA: function () {\n\t\tconsole.log('bba');\n\t},\n\tmethodUsedByB: function () {\n\t\tconsole.log('bbb');\n\t}\n}\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/bc.ts",
    "content": "export function bc() {\n\tconsole.log('bc');\n}\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/c.ts",
    "content": "import {ac} from './a'\nimport {bc} from './bc';\nimport { cc } from './cc';\n\nac();\nbc();\ncc();\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/cc.ts",
    "content": "export function cc() {\n\tconsole.log('cc');\n}\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"./a.ts\",\n\t\t\"b\": {\n\t\t\t\"entry\": \"./b.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t},\n\t\t\"c\": {\n\t\t\t\"entry\": \"./c.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": \".tscc_temp/case_1/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_1/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"target\": \"es5\"\n\t},\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_10_unsafe_module_name_and_script_dts/index.ts",
    "content": "import * as unsafe from '@unsafe/module-name';\n\nconsole.log(unsafe.variableNameThatShouldntBeMangled.propertyNameThatShouldntBeMangled);\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_10_unsafe_module_name_and_script_dts/script_dts.d.ts",
    "content": "declare module \"@unsafe/module-name\" {\n\tinterface interfaceName {\n\t\tpropertyNameThatShouldntBeMangled: number;\n\t}\n\tconst variableNameThatShouldntBeMangled: interfaceName;\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_10_unsafe_module_name_and_script_dts/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"index\": \"./index.ts\"\n\t},\n\t\"external\": {\n\t\t\"@unsafe/module-name\": \"unsafeModuleName\"\n\t},\n\t\"prefix\": \".tscc_temp/case_10_unsafe_module_name_and_script_dts/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_10_unsafe_module_name_and_script_dts/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_11_referencing_goog/dependent.ts",
    "content": "///<reference path=\"../../../../third_party/closure_library/base.d.ts\"/>\n///<reference path=\"../../../../third_party/closure_library/reflect.d.ts\"/>\nimport * as entry from './entry';\nimport * as goog from 'goog:goog';\n\n// This module is only used in \"dependent\" module, so the corresponding shim file's content should\n// only be included in the \"dependent\" chunk.\nimport * as googReflect from 'goog:goog.reflect';\n\n\nvar name = ' ';\n\nvar dictionary = {\n\tkey: \"value\"\n};\n\nif (entry.isDebugging() && goog.global[name] === googReflect.objectProperty(\"key\", dictionary)) {\n\tconsole.log(dictionary[goog.global[name]]);\n};\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_11_referencing_goog/entry.ts",
    "content": "///<reference path=\"../../../../third_party/closure_library/base.d.ts\"/>\nimport * as goog from 'goog:goog';\n\nexport function isDebugging() {\n\treturn goog.DEBUG;\n}\n\nif (isDebugging()) {\n\tconsole.log(\"Debugging\");\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_11_referencing_goog/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.ts\",\n\t\t\"dependent\": {\n\t\t\t\"entry\": \"./dependent.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"entry\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": \".tscc_temp/case_11_referencing_goog/\"\n}"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_11_referencing_goog/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_12_using_jsFiles/entry.ts",
    "content": "import {someVariable} from 'goog:manual';\n\nconsole.log(someVariable);\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_12_using_jsFiles/jsfile.d.ts",
    "content": "declare module 'goog:manual' {\n\texport var someVariable: number;\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_12_using_jsFiles/jsfile.js",
    "content": "goog.module(\"manual\");\n\n/** @type {number} */\nexports.someVariable = 1;\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_12_using_jsFiles/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"entry\": \"./entry.ts\"\n\t},\n\t\"prefix\": \".tscc_temp/case_12_using_jsFiles/\",\n\t\"jsFiles\": [\n\t\t\"./*.js\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_12_using_jsFiles/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_13_chunk_format_global/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"../case_1/a.ts\",\n\t\t\"b\": {\n\t\t\t\"entry\": \"../case_1/b.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t},\n\t\t\"c\": {\n\t\t\t\"entry\": \"../case_1/c.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": \".tscc_temp/case_13_chunk_format_global/\",\n\t\"chunkFormat\": \"global\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_13_chunk_format_global/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"target\": \"es5\"\n\t},\n\t\"include\": [\n\t\t\"../case_1/*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_14_chunk_format_module/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"../case_1/a.ts\",\n\t\t\"b\": {\n\t\t\t\"entry\": \"../case_1/b.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t},\n\t\t\"c\": {\n\t\t\t\"entry\": \"../case_1/c.ts\",\n\t\t\t\"dependencies\": [\n\t\t\t\t\"a\"\n\t\t\t]\n\t\t}\n\t},\n\t\"prefix\": \".tscc_temp/case_14_chunk_format_module/\",\n\t\"chunkFormat\": \"module\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_14_chunk_format_module/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"target\": \"es5\"\n\t},\n\t\"include\": [\n\t\t\"../case_1/*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_2_sourcemaps/a.ts",
    "content": "function a(b) {\n\tconsole.log(b);\n}\na(\"Hello world!\");\n\nexport {};\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_2_sourcemaps/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"./a.ts\"\n\t},\n\t\"prefix\": \".tscc_temp/case_2_sourcemaps/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_2_sourcemaps/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"sourceMap\": true\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_3_sourcemaps_with_decorators/a.ts",
    "content": "function decorator(target, prop:PropertyKey, desc:PropertyDescriptor) {\n\treturn desc;\n}\n\nclass A {\n\t@decorator\n\tb() {console.log('a')}\n}\n\n(new A).b();\n\nexport {A}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_3_sourcemaps_with_decorators/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"./a.ts\"\n\t},\n\t\"prefix\": \".tscc_temp/case_3_sourcemaps_with_decorators/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_3_sourcemaps_with_decorators/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"experimentalDecorators\": true,\n\t\t\"target\": \"es2016\",\n\t\t\"sourceMap\": true,\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_4_external/a.ts",
    "content": "import * as thing from 'an-external-module'\nimport * as CollidesWithGlobalName from 'another-external-module';\n\nthing.a();\n\n(function() {\n\t// Shadowed variable, just in case\n\tvar thing = {\n\t\ta: function() { window[\"this_should_survive\"] = true; }\n\t};\n\tthing.a();\n})();\n\nCollidesWithGlobalName.b();\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_4_external/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"./a.ts\"\n\t},\n\t\"external\": {\n\t\t\"an-external-module\": \"anExternalModule\",\n\t\t\"another-external-module\": \"CollidesWithGlobalName\"\n\t},\n\t\"prefix\": \".tscc_temp/case_4_external/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_4_external/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_5_object_spread/a.ts",
    "content": "function myDecorator(target, prop, desc) {\n\tlet {value, ...rest} = desc;\n\tconsole.log(rest);\n\tdesc.value = {};\n}\n\nclass A {\n\t@myDecorator\n\tpublic myMethod(a, {b, ...c}) {\n\t\tconst {d, ...e} = b;\n\t\tconsole.log(e);\n\t}\n}\n\nconst b = new A();\nb.myMethod({}, {b: {c: {}, d: {}}, e: {}, f: {}, g: {}});\nconst {c, ...rest} = {a: {}, b: {}, c: {}};\nwindow[\"d\"] = rest;\nexport {};\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_5_object_spread/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"a\": \"./a.ts\"\n\t},\n\t\"prefix\": \".tscc_temp/case_5_object_spread/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_5_object_spread/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"experimentalDecorators\": true,\n\t\t\"target\": \"es2016\"\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/a.ts",
    "content": "export interface a {\n\tb():void\n}\n\nexport class b implements a {\n\tb() {\n\t\tconsole.log('boo');\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/b.ts",
    "content": "import { a } from './a' // type-only import\n\nexport type b = (x:a)=>void;\n\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/c.ts",
    "content": "import * as b from './b' // type-only import\n\n\nwindow['b'] = (x: b.b) => {x({b() {} })}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/d.ts",
    "content": "import {b} from './a';\n\nnew b().b();\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"1\": \"./c.ts\",\n\t\t\"2\": {\n\t\t\t\"entry\": \"./d.ts\",\n\t\t\t\"dependencies\": [\"1\"]\n\t\t}\n\t},\n\t\"prefix\": \".tscc_temp/case_6_type_only_references/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_6_type_only_references/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_7_lodash_style_external_module_declaration/a.ts",
    "content": "/**\n * @fileoverview This test case makes sure that module names appearing in external module type\n * declarations are correctly resolved so that several declaration files that contributes to the\n * same module declarations are defined on the same namespace.\n * Such a practice is not common and is not indicated in typescript documentations, but is used\n * by a popular library lodash. This caused the default tsickle implementation, now a \"demo\", to\n * generate externs that produces error when it is consumed by closure compiler.\n * All of these are illustrated in {@link https://github.com/angular/tsickle/issues/1039}, and a\n * demo repo is available at {@link https://github.com/theseanl/ts-declare-module-test}. This test\n * case is almost identical to the one in the demo repo.\n */\nimport * as lodash from 'lodash_style_module';\n\nwindow[\"exported\"] = lodash.exported;\nwindow[\"exported_from_augment\"] = lodash.exported_from_augment;\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_7_lodash_style_external_module_declaration/tscc.spec.json",
    "content": "{\n    \"modules\": {\n        \"a\": \"./a.ts\"\n    },\n    \"external\": {\n        \"lodash_style_module\": \"lodash\"\n    },\n    \"prefix\": \".tscc_temp/case_7_lodash_style_external_module_declaration/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_7_lodash_style_external_module_declaration/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_8_dts_requiretype/imported.d.ts",
    "content": "import {a} from './transtively_imported';\nexport function b():a;\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_8_dts_requiretype/module.ts",
    "content": "import * as i from './imported';\nimport * as e from 'external';\nwindow[\"a\"] = i.b();\nwindow[\"b\"] = e.a;\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_8_dts_requiretype/transtively_imported.d.ts",
    "content": "import {number} from \"yargs\"\n\nexport type a = ()=>number;\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_8_dts_requiretype/tscc.spec.json",
    "content": "{\n    \"modules\": {\n        \"module\": \"./module.ts\"\n    },\n    \"external\": {\n        \"external\": \"external\",\n        \"./imported\": \"imported\"\n    },\n    \"prefix\": \".tscc_temp/case_8_dts_requiretype/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_8_dts_requiretype/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_9_ts_in_node_modules/index.ts",
    "content": "import {a} from './node_modules/non-external/index';\nconsole.log(a);\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_9_ts_in_node_modules/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"index\": \"./index.ts\"\n\t},\n\t\"prefix\": \".tscc_temp/case_9_ts_in_node_modules/\"\n}\n"
  },
  {
    "path": "packages/tscc/test/e2e/sample/case_9_ts_in_node_modules/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../../tsconfig.test_files.json\",\n\t\"include\": [\n\t\t\"./*.ts\",\n\t\t\"./node_modules/non-external/index.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc/test/graph/ClosureDependencyGraph.ts",
    "content": "///<reference types=\"jest\"/>\nimport ClosureDependencyGraph from '../../src/graph/ClosureDependencyGraph'\nimport {ISourceNode} from '../../src/graph/ISourceNode';\n\ndescribe(`ClosureDependencyGraph`, () => {\n\tdescribe(`getSortedFilesAndFlags`, () => {\n\t\ttest(`includes transitive type-references`, () => {\n\t\t\tconst nodes: ISourceNode[] = [\n\t\t\t\t{\n\t\t\t\t\tfileName: '0',\n\t\t\t\t\tprovides: ['z'],\n\t\t\t\t\trequired: ['a'],\n\t\t\t\t\tforwardDeclared: ['a']\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfileName: '1',\n\t\t\t\t\tprovides: ['a'],\n\t\t\t\t\trequired: [],\n\t\t\t\t\tforwardDeclared: ['b']\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfileName: '2',\n\t\t\t\t\tprovides: ['b'],\n\t\t\t\t\trequired: [],\n\t\t\t\t\tforwardDeclared: ['c']\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfileName: '3',\n\t\t\t\t\tprovides: ['c'],\n\t\t\t\t\trequired: [],\n\t\t\t\t\tforwardDeclared: []\n\t\t\t\t}\n\t\t\t];\n\t\t\tconst graph = new ClosureDependencyGraph();\n\t\t\tnodes.forEach(node => graph.addSourceNode(node));\n\t\t\tconst {src} = graph.getSortedFilesAndFlags([\n\t\t\t\t{\n\t\t\t\t\tmoduleName: 'moduleName',\n\t\t\t\t\tmoduleId: 'z',\n\t\t\t\t\tdependencies: [],\n\t\t\t\t\textraSources: []\n\t\t\t\t}\n\t\t\t]);\n\t\t\texpect(src.length).toBe(4);\n\t\t})\n\t})\n\n})\n"
  },
  {
    "path": "packages/tscc/test/graph/TypescriptDependencyGraph.ts",
    "content": "///<reference types=\"jest\"/>\nimport TypescriptDependencyGraph from '../../src/graph/TypescriptDependencyGraph';\nimport * as ts from 'typescript';\nimport path = require('path');\n\ndescribe(`TypescriptDependencyGraph`, () => {\n\tit(`discovers transitive dependencies`, () => {\n\t\tconst testProjectRoot = path.resolve(__dirname, '../sample/tsdepsgraph');\n\t\tconst program = createProgramFromConfigFile(path.join(testProjectRoot, 'tsconfig.json'));\n\t\tconst graph = new TypescriptDependencyGraph(program);\n\t\tgraph.addRootFile(\n\t\t\tpath.join(testProjectRoot, 'entry.ts')\n\t\t);\n\t\t// Typescript seems to be using unix-style path separators internally even on windows,\n\t\t// so we are normalizing those in order for the test meaning is invariant regardless of os.\n\t\texpect(new Set(\n\t\t\t[...graph.iterateFiles()].map(path.normalize)\n\t\t)).toEqual(new Set([\n\t\t\t\"entry.ts\",\n\t\t\t\"a.ts\",\n\t\t\t\"node_modules/aa/types2.d.ts\",\n\t\t\t\"ab.d.ts\",\n\t\t\t\"node_modules/ac/ac.d.ts\",\n\t\t\t\"b.d.ts\",\n\t\t\t\"bb.d.ts\",\n\t\t\t\"node_modules/bc/types3.d.ts\",\n\t\t\t\"node_modules/c/types.d.ts\",\n\t\t\t\"node_modules/c/cb.d.ts\",\n\t\t\t\"node_modules/c/node_modules/cc/cc.d.ts\"\n\t\t].map(relPath => path.join(testProjectRoot, relPath))));\n\t});\n});\n\nfunction createProgramFromConfigFile(configFilePath: string): ts.Program {\n\tconst {fileNames, options} = ts.getParsedCommandLineOfConfigFile(\n\t\tpath.resolve(__dirname, configFilePath),\n\t\t{},\n\t\t<any>ts.sys\n\t);\n\tconst compilerHost = ts.createCompilerHost(options);\n\treturn ts.createProgram(\n\t\tfileNames,\n\t\toptions,\n\t\tcompilerHost\n\t);\n}\n"
  },
  {
    "path": "packages/tscc/test/graph/source_node_factory.ts",
    "content": "///<reference types=\"jest\" />\nimport {sourceNodeFactory, sourceNodeFactoryFromContent} from '../../src/graph/source_node_factory';\nimport path = require('path');\nimport fs = require('fs');\n\ndescribe(\"sourceNodeFactory\", function () {\n\ttest(`produces objects matching source node interface`, async function () {\n\t\tconst node = await sourceNodeFactory(sample(\"goog_module.js\"));\n\t\texpect(node.fileName).toBe(sample(\"goog_module.js\"));\n\t\texpect(node.provides).toEqual([\"this.is.a.goog.module\"]);\n\t\texpect(node.required.slice().sort()).toEqual([\"another.module\", \"goog\"]);\n\t\texpect(node.forwardDeclared.slice().sort()).toEqual([\"another.module\", \"type.only.module\"]);\n\t})\n})\n\ndescribe(\"sourceNodeFactoryFromContent\", function () {\n\ttest(`produces objects matching source node interface`, function () {\n\t\tconst node = sourceNodeFactoryFromContent(sample(\"goog_module.js\"), readSample(\"goog_module.js\"));\n\t\texpect(node.fileName).toBe(sample(\"goog_module.js\"));\n\t\texpect(node.provides).toEqual([\"this.is.a.goog.module\"]);\n\t\texpect(node.required.slice().sort()).toEqual([\"another.module\", \"goog\"]);\n\t\texpect(node.forwardDeclared.slice().sort()).toEqual([\"another.module\", \"type.only.module\"]);\n\t});\n\ttest(`produces goog base from @provideGoog`, function () {\n\t\tconst content1 = `\n/**\n * @provideGoog\n */`;\n\t\tconst node1 = sourceNodeFactoryFromContent('virtual_file_name', content1);\n\t\texpect(node1.provides).toEqual([\"goog\"]);\n\t\texpect(node1.required).toEqual([]);\n\n\t\tconst content2 = `/** @provideGoog */`;\n\t\tconst node2 = sourceNodeFactoryFromContent('virtual_file_name', content2);\n\t\texpect(node2.provides).toEqual([\"goog\"]);\n\t\texpect(node2.required).toEqual([]);\n\t})\n})\n\nfunction sample(name: string) {\n\treturn path.resolve(__dirname, '..', 'sample', name);\n}\n\nfunction readSample(name: string) {\n\treturn fs.readFileSync(sample(name), 'utf8');\n}\n\n"
  },
  {
    "path": "packages/tscc/test/main.ts",
    "content": "///<reference types=\"jest\" />\nimport {parseTsccCommandLineArgs, buildTsccSpecJSONAndTsArgsFromArgs} from '../src/main'\n\n\ndescribe(`buildTsccSpecJSONAndTsArgsFromArgs`, () => {\n\ttest(`transforms --module flag to \"modules\" property of spec JSON`, () => {\n\t\tconst testArgs = [\n\t\t\t'--module', 'entry:entry.ts',\n\t\t\t'--module', 'dependency:dependency.ts:entry:',\n\t\t\t'--module', 'dependency2:dependency2.ts:entry,dependency:css_renaming_map.js'\n\t\t]\n\t\tconst {tsccSpecJSON} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsccSpecJSON.modules).toEqual([\n\t\t\t{\n\t\t\t\tmoduleName: 'entry',\n\t\t\t\tentry: 'entry.ts'\n\t\t\t}, {\n\t\t\t\tmoduleName: 'dependency',\n\t\t\t\tentry: 'dependency.ts',\n\t\t\t\tdependencies: ['entry']\n\t\t\t}, {\n\t\t\t\tmoduleName: 'dependency2',\n\t\t\t\tentry: 'dependency2.ts',\n\t\t\t\tdependencies: ['entry', 'dependency'],\n\t\t\t\textraSources: ['css_renaming_map.js']\n\t\t\t}\n\t\t])\n\t})\n\ttest(`transforms --spec flag to \"specFile\" property of spec JSON`, () => {\n\t\tconst testArgs = [\n\t\t\t'--spec', 'src'\n\t\t];\n\t\tconst {tsccSpecJSON} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsccSpecJSON.specFile).toEqual('src');\n\t})\n\ttest(`transforms nested --prefix flags to a nested object of spec JSON`, () => {\n\t\tconst testArgs = [\n\t\t\t\"--prefix.rollup\", \"gen/dev/\",\n\t\t\t\"--prefix.cc\", \"gen/prod/\"\n\t\t];\n\t\tconst {tsccSpecJSON} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsccSpecJSON.prefix).toEqual({\n\t\t\t\"rollup\": \"gen/dev/\",\n\t\t\t\"cc\": \"gen/prod/\"\n\t\t})\n\t})\n\ttest(`transforms nested --debug flags to a nested object of spec JSON`, () => {\n\t\tconst testArgs = [\n\t\t\t\"--debug.persistArtifacts\",\n\t\t\t\"--debug.ignoreWarningsPath\", \"/node_modules/\",\n\t\t];\n\t\tconst {tsccSpecJSON} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsccSpecJSON.debug).toEqual({\n\t\t\t\"persistArtifacts\": true,\n\t\t\t\"ignoreWarningsPath\": [\"/node_modules/\"]\n\t\t})\n\t})\n\ttest(`transforms closure compiler arguments to \"compilerFlags\" property of spec json`, () => {\n\t\tconst testArgs = [\n\t\t\t'--',\n\t\t\t'--project', '.',\n\t\t\t'--',\n\t\t\t'--externs', 'extern1.js',\n\t\t\t'--externs', 'extern2.js',\n\t\t\t'--assume_function_wrapper'\n\t\t];\n\t\tconst {tsccSpecJSON} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsccSpecJSON.compilerFlags).toEqual({\n\t\t\t'externs': ['extern1.js', 'extern2.js'],\n\t\t\t'assume_function_wrapper': true\n\t\t})\n\t})\n\ttest(`slices ts arguments part`, () => {\n\t\tconst testArgs = [\n\t\t\t'--spec', '.',\n\t\t\t'--',\n\t\t\t'--project', 'src',\n\t\t\t'--downlevelIteration',\n\t\t\t'--target', 'ES2016',\n\t\t\t'--',\n\t\t\t'--rewrite_polyfills', 'false'\n\t\t];\n\t\tconst {tsArgs} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsArgs).toEqual(['--project', 'src', '--downlevelIteration', '--target', 'ES2016'])\n\t})\n\ttest(`slices ts arguments part when cc arguments are not present`, () => {\n\t\tconst testArgs = [\n\t\t\t'--spec', '.',\n\t\t\t'--',\n\t\t\t'--project', 'src'\n\t\t];\n\t\tconst {tsArgs} = buildTsccSpecJSONAndTsArgsFromArgs(parseTsccCommandLineArgs(testArgs));\n\t\texpect(tsArgs).toEqual(['--project', 'src'])\n\t})\n})\n\n"
  },
  {
    "path": "packages/tscc/test/sample/decorator/decorates.ts",
    "content": "const adornClass: ClassDecorator = (target) => target\nconst adornProperty: PropertyDecorator = (target, prop) => {}\nconst adornMethod: MethodDecorator = (target, prop, desc) => desc;\nconst adornParameter: ParameterDecorator = (target, prop, paramIndex) => {}\n\n@adornClass\nclass A {\n\t@adornMethod\n\taMethod() {\n\n\t}\n\n\t@adornProperty\n\taProperty\t\n\n\t@adornMethod\n\tget anAccessor() {\n\t\treturn NaN;\n\t}\n\tset anAccessor(v: number) {\n\n\t}\n\taMethodWithParams(@adornParameter param) {\n\n\t}\n}\n\n// Make it a module\nexport {};\n\n"
  },
  {
    "path": "packages/tscc/test/sample/dts_requiretype/entry.ts",
    "content": "import * as required from './required';\n\nvar a = required.func();\n"
  },
  {
    "path": "packages/tscc/test/sample/dts_requiretype/required.d.ts",
    "content": "interface I {\n\tproperty: SVGPathSegCurvetoQuadraticAbs\n}\n\nexport function func(): I;\n"
  },
  {
    "path": "packages/tscc/test/sample/goog_module.js",
    "content": "goog.module(\"this.is.a.goog.module\");\n\nconst a_type = goog.requireType(\"another.module\");\nconst a = goog.require(\"another.module\");\n\nconst type_only = goog.requireType(\"type.only.module\");\n\n"
  },
  {
    "path": "packages/tscc/test/sample/rest/case_1.ts",
    "content": "var o = {\n\ta: {},\n\tb: {},\n\t\"c\": {},\n\t[\"d\"]: {},\n\t[Symbol('foo')]: {},\n\t[Math.random() > .5 ? \"foo\" : \"bar\"]: {}\n};\n\nvar {a, c, d, foo, ...rest} = o;\n\nfunction A(a, {b, c, ...d}) {\n\tconsole.log(d);\n}\n\n// From what's new in Typescript 2.1\n(function () {\n\tvar original = {a: {}, b: {}, c: {}};\n\tlet copy = {...original};\n})();\n\n(function () {\n\tvar foo = {}, bar = {}, baz = {};\n\tlet merged = {...foo, ...bar, ...baz};\n})();\n\n(function () {\n\tlet obj = {x: 1, y: \"string\"};\n\tvar newObj = {...obj, z: 3, y: 4}; // { x: number, y: number, z: number }\n})();\n(function () {\n\tlet obj = {x: 1, y: 1, z: 1};\n\tlet {z, ...obj1} = obj;\n\tobj1; // {x: number, y:number};\n})();\n// make it to a module\nexport {};\n"
  },
  {
    "path": "packages/tscc/test/sample/rest/combined_with_decorators.ts",
    "content": "function myDecorator(target, prop, desc) {\n\tlet {value, ...rest} = desc;\n\tconsole.log(rest);\n\tdesc.value = {};\n}\n\nclass A {\n\t@myDecorator\n\tpublic myMethod() {}\n}\n\nconst b = new A();\nwindow.a = b.myMethod();\nconst {c, ...rest} = {a: {}, b: {}, c: {}};\nwindow.d = rest;\nexport {};\n"
  },
  {
    "path": "packages/tscc/test/sample/tsconfig.json",
    "content": "{\n\t\"extends\": \"../tsconfig.test_files.json\",\n\t\"compilerOptions\": {\n\t\t\"experimentalDecorators\": true,\n\t\t\"rootDir\": \".\"\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/a.ts",
    "content": "///<reference path=\"./ab.d.ts\"/>\n///<reference types=\"ac\"/>\nexport * from 'aa';\nexport const a = 1;\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/ab.d.ts",
    "content": "declare var ab:PromiseLike<any>;\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/b.d.ts",
    "content": "///<reference path=\"./bb.d.ts\"/>\n///<reference types=\"bc\"/>\ndeclare const b:WeakSet<WindowOrWorkerGlobalScope>;\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/bb.d.ts",
    "content": "declare namespace bb {\n\tconst $: Atomics;\n}\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/entry.ts",
    "content": "/// <reference path=\"./b.d.ts\" />\n/// <reference types=\"c\"/>\nimport * as a from './a';\n\na.a;\na.aa;\nab;\nac;\n\nb;\nbb.$;\nbc;\n\nc;\n"
  },
  {
    "path": "packages/tscc/test/sample/tsdepsgraph/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"moduleResolution\": \"node\",\n        \"importHelpers\": true\n    },\n    \"includes\": [\n        \"entry.ts\"\n    ]\n}\n"
  },
  {
    "path": "packages/tscc/test/shared/escape_goog_identifier.ts",
    "content": "///<reference types=\"jest\"/>\nimport {escapedGoogNameIsDts, escapeGoogAdmissibleName, unescapeGoogAdmissibleName} from '../../src/shared/escape_goog_identifier'\n\ndescribe(`escape_goog_identifier`, () => {\n\tdescribe(`escapeGoogAdmissibleName, unescapeGoogAdmissiblename`, () => {\n\t\ttest(\n\t\t\t`it defines a one-to-one correspondence between the set of strings`\n\t\t\t+ `and the set of valid goog identifiers`,\n\t\t\t() => {\n\t\t\t\tconst testStrings = [\n\t\t\t\t\t`gXKDrQ5KkuKyjWBNHToI`,\n\t\t\t\t\t`ಠ_ಠಠ~ಠಠoಠಠxಠಠ.ಠಥ_ಥಠ益ಠ(⚆_⚆)( ͡ಠ ʖ̯ ͡ಠ)(¬_¬)( ಠل͟ಠ)┌∩┐(ಠ_ಠ)┌∩┐¯\\_(ツ)_/¯( ͡° ͜ʖ ͡°)`,\n\t\t\t\t\t`asdf🈳asdfasdf🌧⛽⛪34etrtfgh#$%YTEDF🦎`\n\t\t\t\t];\n\t\t\t\tfor (let testString of testStrings) {\n\t\t\t\t\texpect(unescapeGoogAdmissibleName(escapeGoogAdmissibleName(testString)))\n\t\t\t\t\t\t.toBe(testString);\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\ttest(`it converts periods and path separators to a string that does not contain consecutive periods`,\n\t\t\t() => {\n\t\t\t\tlet escaped = escapeGoogAdmissibleName(\n\t\t\t\t\t`./../.../..../...../..`.replace(/\\//g, require('path').sep)\n\t\t\t\t);\n\t\t\t\texpect(escaped.includes('..')).toBe(false);\n\t\t\t}\n\t\t)\n\t});\n\tdescribe(`escapedGoogNameIsDts`, () => {\n\t\ttest(`detects if an original(unescaped) string ends with .d.ts.`, () => {\n\t\t\texpect(escapedGoogNameIsDts(escapeGoogAdmissibleName(\n\t\t\t\t`🔴 🚈 ♊️ 🐏 🎁 🍻 🎺 😁 ❎ 🚾 ↪️ 🔵 ⏳ 🌯 🙏 🚣 💱 👂 ☹ 0️⃣.d.ts`\n\t\t\t))).toBe(true);\n\t\t})\n\t});\n});\n"
  },
  {
    "path": "packages/tscc/test/shared/sourcemap_splice.ts",
    "content": "///<reference types=\"jest\" />\r\nimport spliceSourceMap, {Seeker, splitWithRegex} from '../../src/shared/sourcemap_splice';\r\nimport {SourceMapConsumer} from 'source-map';\r\nimport MagicString from 'magic-string';\r\n\r\n\r\n\r\nconst testString =\r\n\t`0123456789\r\n01###2345678\r\n0123#####45%%%%%678##9\r\n%%%%%%01234##567%%%\r\n%%%%89\r\n####%%0123#########\r\n###%%%%%%####%%%##%%%%\r\n4567#####8\r\n####012%%%3456\r\n\r\n##0123\r\n\r\n0123%%%%`;\r\nconst expected =\r\n\t`0123456789\r\n012345678\r\n0123456789\r\n0123456789\r\n012345678\r\n0123456\r\n\r\n0123\r\n\r\n0123`\r\n\r\ndescribe(`spliceWithRegex`, function () {\r\n\ttest(`produces expected output`, function () {\r\n\t\tconst {contents, intervals} = splitTestString(testString);\r\n\t\texpect(contents).toBe(expected);\r\n\t\texpect(intervals).toEqual([\r\n\t\t\t[13, 16], [28, 33],\r\n\t\t\t[35, 40], [43, 45],\r\n\t\t\t[47, 53], [58, 60],\r\n\t\t\t[63, 71], [74, 78],\r\n\t\t\t[78, 80], [84, 97],\r\n\t\t\t[97, 103], [103, 107],\r\n\t\t\t[107, 110], [110, 112],\r\n\t\t\t[112, 117], [121, 126],\r\n\t\t\t[128, 132], [135, 138],\r\n\t\t\t[144, 146], [156, 160]\r\n\t\t]);\r\n\t});\r\n})\r\n\r\ndescribe(`Seeker`, function () {\r\n\ttest(`correctly maps positions when it is queried multiple times within a line`, function () {\r\n\t\tconst testString = `012###34####5####67##89##`;\r\n\t\tconst {intervals} = splitTestString(testString);\r\n\t\tconst seeker = new Seeker(testString, intervals);\r\n\t\tconst t = new TestSupport(seeker);\r\n\r\n\t\texpect(t.pos(0, 2)).toEqual([0, 2]);\r\n\t\texpect(t.pos(0, 5)).toBeUndefined();\r\n\t\texpect(t.pos(0, 6)).toEqual([0, 3]);\r\n\t\texpect(t.pos(0, 13)).toBeUndefined();\r\n\t\texpect(t.pos(0, 16)).toBeUndefined();\r\n\t\texpect(t.pos(0, 21)).toEqual([0, 8]);\r\n\t});\r\n\r\n\ttest(`correctly maps positions when it skips quering several lines`, function () {\r\n\t\tconst {intervals} = splitTestString(testString);\r\n\t\tconst seeker = new Seeker(testString, intervals);\r\n\t\tconst t = new TestSupport(seeker);\r\n\r\n\t\texpect(t.pos(4, 4)).toEqual([3, 8]);\r\n\t\texpect(t.pos(8, 10)).toEqual([5, 3]);\r\n\t\texpect(t.pos(12, 4)).toBeUndefined();\r\n\t})\r\n\r\n\ttest(`correctly maps positions when there are intervals ending with line break characters`, function () {\r\n\t\tconst testString = [\r\n\t\t\t\"01234\",\r\n\t\t\t\"###01234\",\r\n\t\t\t\"01234\"\r\n\t\t].join('\\n');\r\n\t\tconst {intervals} = splitTestString(testString);\r\n\t\tconst seeker = new Seeker(testString, intervals);\r\n\t\tconst t = new TestSupport(seeker);\r\n\t\texpect(t.pos(0, 3)).toEqual([0, 3]);\r\n\t\texpect(t.pos(1, 4)).toEqual([1, 1]);\r\n\t\texpect(t.pos(2, 2)).toEqual([2, 2])\r\n\t})\r\n\r\n\ttest(`correctly maps positions with a contrived example`, function () {\r\n\t\tconst {intervals} = splitTestString(testString);\r\n\t\tconst seeker = new Seeker(testString, intervals);\r\n\t\tconst t = new TestSupport(seeker);\r\n\r\n\t\texpect(t.pos(0, 4)).toEqual([0, 4]);\r\n\t\texpect(t.pos(0, 9)).toEqual([0, 9]);\r\n\t\texpect(t.pos(0, 10)).toEqual([0, 10]);\r\n\r\n\t\texpect(t.pos(1, 1)).toEqual([1, 1]);\r\n\t\texpect(t.pos(1, 2)).toBeUndefined();\r\n\t\texpect(t.pos(1, 4)).toBeUndefined();\r\n\t\texpect(t.pos(1, 5)).toEqual([1, 2]);\r\n\t\texpect(t.pos(1, 12)).toEqual([1, 9]);\r\n\r\n\t\texpect(t.pos(2, 16)).toEqual([2, 6]);\r\n\r\n\t\texpect(t.pos(3, 15)).toEqual([3, 7]);\r\n\t\texpect(t.pos(4, 5)).toEqual([3, 9]);\r\n\r\n\t\texpect(t.pos(5, 7)).toEqual([4, 1]);\r\n\t\texpect(t.pos(6, 14)).toBeUndefined();\r\n\t\texpect(t.pos(7, 0)).toEqual([4, 4]);\r\n\t\texpect(t.pos(7, 9)).toEqual([4, 8]);\r\n\r\n\t\texpect(t.pos(9, 0)).toEqual([6, 0])\r\n\t\texpect(t.pos(10, 0)).toBeUndefined();\r\n\t\texpect(t.pos(10, 2)).toEqual([7, 0]);\r\n\r\n\t\texpect(t.pos(12, 3)).toEqual([9, 3]);\r\n\t\texpect(t.pos(12, 7)).toBeUndefined();\r\n\t\texpect(() => {t.pos(12, 8)}).toThrow();\r\n\t})\r\n\r\n\tclass TestSupport {\r\n\t\tconstructor(\r\n\t\t\tprivate seeker: Seeker\r\n\t\t) {}\r\n\t\tpos(line: number, column: number) {\r\n\t\t\tthis.seeker.seek(line, column);\r\n\t\t\tif (this.seeker.isInInterval()) return;\r\n\t\t\tline = this.seeker.getTransformedLine();\r\n\t\t\tcolumn = this.seeker.getTransformedColumn();\r\n\t\t\treturn [line, column];\r\n\t\t}\r\n\t}\r\n})\r\n\r\nfunction splitTestString(string: string, regex: RegExp = /(?:#[#\\s]+|%[%\\s]+)/g) {\r\n\treturn splitWithRegex(string, regex)\r\n}\r\n\r\ndescribe(`spliceSourceMap`, function () {\r\n\ttest(`Does expected things`, async () => {\r\n\t\tconst testString = Array.from({length: 20}, () => '#').join('');\r\n\t\tconst ms = new MagicString(testString);\r\n\t\tconst map = JSON.parse(ms.generateMap({hires: true}).toString());\r\n\t\tconst map2 = JSON.parse(ms.remove(3, 5).remove(11, 13).generateMap({hires: true}).toString());\r\n\t\texpect(new Set(Object.keys(map))).toEqual(new Set(Object.keys(map2)));\r\n\t\tfor (let key in map) {\r\n\t\t\tif (key === 'mappings') continue;\r\n\t\t\texpect(map[key]).toEqual(map2[key]);\r\n\t\t}\r\n\t\tconst splicedMap = await spliceSourceMap(testString, map, [[3, 5], [11, 13]]);\r\n\r\n\t\tconst consumer = await SourceMapConsumer.with(splicedMap, null, async function (consumer) {\r\n\t\t\tconst consumer2 = await SourceMapConsumer.with(map2, null, async function (consumer2) {\r\n\t\t\t\tconsumer.eachMapping(mapping => {\r\n\t\t\t\t\tconst origPos = consumer.originalPositionFor({\r\n\t\t\t\t\t\tline: mapping.generatedLine,\r\n\t\t\t\t\t\tcolumn: mapping.generatedColumn\r\n\t\t\t\t\t});\r\n\t\t\t\t\tconst origPos2 = consumer2.originalPositionFor({\r\n\t\t\t\t\t\tline: mapping.generatedLine,\r\n\t\t\t\t\t\tcolumn: mapping.generatedColumn\r\n\t\t\t\t\t});\r\n\t\t\t\t\texpect(origPos).toEqual(origPos2)\r\n\t\t\t\t})\r\n\t\t\t});\r\n\t\t});\r\n\t})\r\n})\r\n\r\n"
  },
  {
    "path": "packages/tscc/test/spec/TsccSpecWithTS.ts",
    "content": "///<reference types=\"jest\"/>\nimport TsccSpecWithTS from '../../src/spec/TsccSpecWithTS';\nimport * as ts from 'typescript';\nimport path = require('path');\nimport {TsccSpecError} from '@tscc/tscc-spec';\n\ndescribe(`TsccSpecWithTS`, () => {\n\tdescribe(`loadTsConfigFromArgs`, () => {\n\t\ttest(`searches tsconfig from a directory provided by --project flag`, () => {\n\t\t\tconst projectInNestedDirectory = path.join(__dirname, 'sample/nested_directory');\n\t\t\tconst {projectRoot, parsedConfig} = TsccSpecWithTS.loadTsConfigFromArgs(\n\t\t\t\t['--project', projectInNestedDirectory],\n\t\t\t\tundefined,\n\t\t\t\t() => {}\n\t\t\t);\n\t\t\texpect(projectRoot).toBe(projectInNestedDirectory);\n\t\t\texpect(parsedConfig.options.moduleResolution).toBe(ts.ModuleResolutionKind.NodeJs);\n\t\t});\n\t})\n\tdescribe(`loadTsConfigFromPath`, () => {\n\t\ttest(`searches tsconfig from ancestor directories of specFile when tsconfig path is undefined`, () => {\n\t\t\tconst directoryNestedInProject = path.join(\n\t\t\t\t__dirname,\n\t\t\t\t'sample/nested_directory/nested_nested_directory'\n\t\t\t);\n\t\t\tconst {projectRoot, parsedConfig} = TsccSpecWithTS.loadTsConfigFromPath(\n\t\t\t\tundefined,\n\t\t\t\tdirectoryNestedInProject\n\t\t\t);\n\t\t\texpect(projectRoot).toBe(path.dirname(directoryNestedInProject));\n\t\t\texpect(parsedConfig.options.downlevelIteration).toBe(true);\n\t\t});\n\t\ttest(`merges compilerOptions override provided as a second argument`, () => {\n\t\t\tconst {projectRoot, parsedConfig} = TsccSpecWithTS.loadTsConfigFromPath(\n\t\t\t\tpath.join(__dirname, 'sample/tsconfig.1.json'),\n\t\t\t\t'/',\n\t\t\t\t{\n\t\t\t\t\ttarget: 'ES2016',\n\t\t\t\t\tdownlevelIteration: false\n\t\t\t\t}\n\t\t\t);\n\t\t\texpect(projectRoot).toBe(path.join(__dirname, 'sample'));\n\t\t\texpect(parsedConfig.options.moduleResolution).toBe(ts.ModuleResolutionKind.NodeJs);\n\t\t\texpect(parsedConfig.options.target).toBe(ts.ScriptTarget.ES2016);\n\t\t\texpect(parsedConfig.options.downlevelIteration).toBe(false);\n\t\t})\n\t})\n\tdescribe(`validateSpecWithTS`, () => {\n\t\ttest(`throws an error when entry files in the spec isn't included in tsconfig`, () => {\n\t\t\texpect(() => {\n\t\t\t\tTsccSpecWithTS.loadSpecWithTS({\n\t\t\t\t\tmodules: {\n\t\t\t\t\t\t\"entry\": \"./non_existing_file.ts\"\n\t\t\t\t\t}\n\t\t\t\t}, path.join(__dirname, 'sample/tsconfig.1.json'))\n\t\t\t}).toThrowError(TsccSpecError);\n\t\t})\n\t})\n\tdescribe(`pruneCompilerOptions`, () => {\n\t\ttest(`Overrides \"module\" to \"commonjs\"`, () => {\n\t\t\t{\n\t\t\t\tconst options: ts.CompilerOptions = {\n\t\t\t\t\tmodule: ts.ModuleKind.ESNext\n\t\t\t\t};\n\t\t\t\tTsccSpecWithTS.pruneCompilerOptions(options, noop);\n\t\t\t\texpect(options.module).toBe(ts.ModuleKind.CommonJS);\n\t\t\t}\n\t\t\t{\n\t\t\t\tconst options2: ts.CompilerOptions = {\n\t\t\t\t\tmodule: undefined\n\t\t\t\t};\n\t\t\t\tTsccSpecWithTS.pruneCompilerOptions(options2, noop);\n\t\t\t\texpect(options2.module).toBe(ts.ModuleKind.CommonJS);\n\t\t\t}\n\t\t});\n\t\ttest(`Make sure \"target\" is greater than ES3`, () => {\n\t\t\t{\n\t\t\t\tconst options: ts.CompilerOptions = {\n\t\t\t\t\ttarget: ts.ScriptTarget.ES3\n\t\t\t\t};\n\t\t\t\tTsccSpecWithTS.pruneCompilerOptions(options, noop);\n\t\t\t\texpect(options.target).not.toBe(ts.ScriptTarget.ES3);\n\t\t\t}\n\t\t\t{\n\t\t\t\tconst options2: ts.CompilerOptions = {\n\t\t\t\t\ttarget: undefined\n\t\t\t\t};\n\t\t\t\tTsccSpecWithTS.pruneCompilerOptions(options2, noop);\n\t\t\t\texpect(options2.target).toBeDefined();\n\t\t\t}\n\t\t});\n\t\ttest(`Unsets declaration and declarationMap`, () => {\n\t\t\t{\n\t\t\t\tconst options: ts.CompilerOptions = {\n\t\t\t\t\tdeclaration: true,\n\t\t\t\t\tdeclarationMap: true\n\t\t\t\t};\n\t\t\t\tTsccSpecWithTS.pruneCompilerOptions(options, noop);\n\t\t\t\texpect(options.declaration).toBeFalsy();\n\t\t\t\texpect(options.declarationMap).toBeFalsy();\n\t\t\t}\n\t\t})\n\t})\n});\n\nfunction noop() {}\n"
  },
  {
    "path": "packages/tscc/test/spec/sample/empty.ts",
    "content": ""
  },
  {
    "path": "packages/tscc/test/spec/sample/nested_directory/empty.ts",
    "content": ""
  },
  {
    "path": "packages/tscc/test/spec/sample/nested_directory/tsconfig.json",
    "content": "{\n\t\"compilerOptions\": {\n\t\t\"target\": \"ES5\",\n\t\t\"moduleResolution\": \"Node\",\n\t\t\"downlevelIteration\": true\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/spec/sample/tsconfig.1.json",
    "content": "{\n\t\"compilerOptions\": {\n\t\t\"target\": \"ES5\",\n\t\t\"moduleResolution\": \"Node\",\n\t\t\"downlevelIteration\": true\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/transformer/__snapshots__/transformers.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`decoratorPropertyTransformer modifies property name access to goog.reflect.objectProperty, add @nocollapse to jsdoc: decorator/decorates.ts - es5 1`] = `\n\"var tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nvar tslib_1 = require(\\\\\"tslib\\\\\");\nvar adornClass = function (target) { return target; };\nvar adornProperty = function (target, prop) { };\nvar adornMethod = function (target, prop, desc) { return desc; };\nvar adornParameter = function (target, prop, paramIndex) { };\nvar A = /** @class */ (function () {\n    function A() {\n    }\n    A.prototype.aMethod = function () {\n    };\n    Object.defineProperty(A.prototype, \\\\\"anAccessor\\\\\", {\n        get: function () {\n            return NaN;\n        },\n        set: function (v) {\n        },\n        enumerable: false,\n        configurable: true\n    });\n    A.prototype.aMethodWithParams = function (param) {\n    };\n    tslib_1.__decorate([\n        adornMethod\n    ], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aMethod\\\\\", A.prototype), null);\n    tslib_1.__decorate([\n        adornProperty\n    ], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aProperty\\\\\", A.prototype), void 0);\n    tslib_1.__decorate([\n        adornMethod\n    ], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"anAccessor\\\\\", A.prototype), null);\n    tslib_1.__decorate([\n        tslib_1.__param(0, adornParameter)\n    ], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aMethodWithParams\\\\\", A.prototype), null);\n    A = tslib_1.__decorate([\n        adornClass\n    ], A);\n    return A;\n}());\n\\\\\"__tscc_export_start__\\\\\";\n{\n    self[\\\\\"tscc_global_access_name_1\\\\\"] = (A.prototype).aMethod;\n    self[\\\\\"tscc_global_access_name_2\\\\\"] = (A.prototype).aProperty;\n    self[\\\\\"tscc_global_access_name_3\\\\\"] = (A.prototype).anAccessor;\n    self[\\\\\"tscc_global_access_name_4\\\\\"] = (A.prototype).aMethodWithParams;\n}\n\\\\\"__tscc_export_end__\\\\\";\n\"\n`;\n\nexports[`decoratorPropertyTransformer modifies property name access to goog.reflect.objectProperty, add @nocollapse to jsdoc: decorator/decorates.ts 1`] = `\n\"const tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nconst tslib_1 = require(\\\\\"tslib\\\\\");\nconst adornClass = (target) => target;\nconst adornProperty = (target, prop) => { };\nconst adornMethod = (target, prop, desc) => desc;\nconst adornParameter = (target, prop, paramIndex) => { };\nlet A = class A {\n    aMethod() {\n    }\n    get anAccessor() {\n        return NaN;\n    }\n    set anAccessor(v) {\n    }\n    aMethodWithParams(param) {\n    }\n};\ntslib_1.__decorate([\n    adornMethod\n], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aMethod\\\\\", A.prototype), null);\ntslib_1.__decorate([\n    adornProperty\n], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aProperty\\\\\", A.prototype), void 0);\ntslib_1.__decorate([\n    adornMethod\n], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"anAccessor\\\\\", A.prototype), null);\ntslib_1.__decorate([\n    tslib_1.__param(0, adornParameter)\n], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"aMethodWithParams\\\\\", A.prototype), null);\nA = tslib_1.__decorate([\n    adornClass\n], A);\n\\\\\"__tscc_export_start__\\\\\";\n{\n    self[\\\\\"tscc_global_access_name_1\\\\\"] = (A.prototype).aMethod;\n    self[\\\\\"tscc_global_access_name_2\\\\\"] = (A.prototype).aProperty;\n    self[\\\\\"tscc_global_access_name_3\\\\\"] = (A.prototype).anAccessor;\n    self[\\\\\"tscc_global_access_name_4\\\\\"] = (A.prototype).aMethodWithParams;\n}\n\\\\\"__tscc_export_end__\\\\\";\n\"\n`;\n\nexports[`dts_requiretype_transformer modifies requireType calls to a global variable: dts_requiretype/entry.ts 1`] = `\n\"/**\n * @fileoverview added by tsickle\n * Generated from: dts_requiretype/entry.ts\n * @suppress {checkTypes,const,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode}\n */\ngoog.module('dts_requiretype.entry$_ts');\nvar module = module || { id: '' };\ngoog.require('tslib');\nconst tsickle_required_1 = dts_requiretype$required$_d$_ts;\nconst required = goog.require('dts_requiretype.required');\n/** @type {!tsickle_required_1.I} */\nvar a = required.func();\n\"\n`;\n\nexports[`restPropertyTransformer modifies property name access to goog.reflect.objectProperty: rest/case_1.ts - es5 1`] = `\n\"var tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nvar _a;\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nvar tslib_1 = require(\\\\\"tslib\\\\\");\nvar o = (_a = {\n        a: {},\n        b: {},\n        \\\\\"c\\\\\": {}\n    },\n    _a[\\\\\"d\\\\\"] = {},\n    _a[Symbol('foo')] = {},\n    _a[Math.random() > .5 ? \\\\\"foo\\\\\" : \\\\\"bar\\\\\"] = {},\n    _a);\nvar a = o.a, c = o.c, d = o.d, foo = o.foo, rest = tslib_1.__rest(o, [tscc_goog_reflect_injected.objectProperty(\\\\\"a\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"d\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"foo\\\\\", o)]);\nfunction A(a, _a) {\n    var b = _a.b, c = _a.c, d = tslib_1.__rest(_a, [tscc_goog_reflect_injected.objectProperty(\\\\\"b\\\\\", _a), tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", _a)]);\n    console.log(d);\n}\n// From what's new in Typescript 2.1\n(function () {\n    var original = { a: {}, b: {}, c: {} };\n    var copy = tslib_1.__assign({}, original);\n})();\n(function () {\n    var foo = {}, bar = {}, baz = {};\n    var merged = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, foo), bar), baz);\n})();\n(function () {\n    var obj = { x: 1, y: \\\\\"string\\\\\" };\n    var newObj = tslib_1.__assign(tslib_1.__assign({}, obj), { z: 3, y: 4 }); // { x: number, y: number, z: number }\n})();\n(function () {\n    var obj = { x: 1, y: 1, z: 1 };\n    var z = obj.z, obj1 = tslib_1.__rest(obj, [tscc_goog_reflect_injected.objectProperty(\\\\\"z\\\\\", obj)]);\n    obj1; // {x: number, y:number};\n})();\n\"\n`;\n\nexports[`restPropertyTransformer modifies property name access to goog.reflect.objectProperty: rest/case_1.ts 1`] = `\n\"const tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nconst tslib_1 = require(\\\\\"tslib\\\\\");\nvar o = {\n    a: {},\n    b: {},\n    \\\\\"c\\\\\": {},\n    [\\\\\"d\\\\\"]: {},\n    [Symbol('foo')]: {},\n    [Math.random() > .5 ? \\\\\"foo\\\\\" : \\\\\"bar\\\\\"]: {}\n};\nvar { a, c, d, foo } = o, rest = tslib_1.__rest(o, [tscc_goog_reflect_injected.objectProperty(\\\\\"a\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"d\\\\\", o), tscc_goog_reflect_injected.objectProperty(\\\\\"foo\\\\\", o)]);\nfunction A(a, _a) {\n    var { b, c } = _a, d = tslib_1.__rest(_a, [tscc_goog_reflect_injected.objectProperty(\\\\\"b\\\\\", _a), tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", _a)]);\n    console.log(d);\n}\n// From what's new in Typescript 2.1\n(function () {\n    var original = { a: {}, b: {}, c: {} };\n    let copy = Object.assign({}, original);\n})();\n(function () {\n    var foo = {}, bar = {}, baz = {};\n    let merged = Object.assign(Object.assign(Object.assign({}, foo), bar), baz);\n})();\n(function () {\n    let obj = { x: 1, y: \\\\\"string\\\\\" };\n    var newObj = Object.assign(Object.assign({}, obj), { z: 3, y: 4 }); // { x: number, y: number, z: number }\n})();\n(function () {\n    let obj = { x: 1, y: 1, z: 1 };\n    let { z } = obj, obj1 = tslib_1.__rest(obj, [tscc_goog_reflect_injected.objectProperty(\\\\\"z\\\\\", obj)]);\n    obj1; // {x: number, y:number};\n})();\n\"\n`;\n\nexports[`restPropertyTransformer works well when combined with decorators: rest/combined_with_decorators.ts - es5 1`] = `\n\"var tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nvar tslib_1 = require(\\\\\"tslib\\\\\");\nfunction myDecorator(target, prop, desc) {\n    var value = desc.value, rest = tslib_1.__rest(desc, [tscc_goog_reflect_injected.objectProperty(\\\\\"value\\\\\", desc)]);\n    console.log(rest);\n    desc.value = {};\n}\nvar A = /** @class */ (function () {\n    function A() {\n    }\n    A.prototype.myMethod = function () { };\n    tslib_1.__decorate([\n        myDecorator\n    ], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"myMethod\\\\\", A.prototype), null);\n    return A;\n}());\nvar b = new A();\nwindow.a = b.myMethod();\nvar _a = { a: {}, b: {}, c: {} }, c = _a.c, rest = tslib_1.__rest(_a, [tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", _a)]);\nwindow.d = rest;\n\\\\\"__tscc_export_start__\\\\\";\n{\n    self[\\\\\"tscc_global_access_name_1\\\\\"] = (A.prototype).myMethod;\n}\n\\\\\"__tscc_export_end__\\\\\";\n\"\n`;\n\nexports[`restPropertyTransformer works well when combined with decorators: rest/combined_with_decorators.ts 1`] = `\n\"const tscc_goog_reflect_injected = goog.require(\\\\\"goog.reflect\\\\\");\n\\\\\"use strict\\\\\";\nObject.defineProperty(exports, \\\\\"__esModule\\\\\", { value: true });\nconst tslib_1 = require(\\\\\"tslib\\\\\");\nfunction myDecorator(target, prop, desc) {\n    let { value } = desc, rest = tslib_1.__rest(desc, [tscc_goog_reflect_injected.objectProperty(\\\\\"value\\\\\", desc)]);\n    console.log(rest);\n    desc.value = {};\n}\nclass A {\n    myMethod() { }\n}\ntslib_1.__decorate([\n    myDecorator\n], A.prototype, tscc_goog_reflect_injected.objectProperty(\\\\\"myMethod\\\\\", A.prototype), null);\nconst b = new A();\nwindow.a = b.myMethod();\nconst _a = { a: {}, b: {}, c: {} }, { c } = _a, rest = tslib_1.__rest(_a, [tscc_goog_reflect_injected.objectProperty(\\\\\"c\\\\\", _a)]);\nwindow.d = rest;\n\\\\\"__tscc_export_start__\\\\\";\n{\n    self[\\\\\"tscc_global_access_name_1\\\\\"] = (A.prototype).myMethod;\n}\n\\\\\"__tscc_export_end__\\\\\";\n\"\n`;\n"
  },
  {
    "path": "packages/tscc/test/transformer/transformers.ts",
    "content": "///<reference types=\"jest\" />\nimport * as ts from 'typescript';\nimport * as tsickle from 'tsickle';\nimport TsccSpecWithTS from '../../src/spec/TsccSpecWithTS';\nimport decoratorPropertyTransformer from '../../src/transformer/decorator_property_transformer';\nimport restPropertyTransformer from '../../src/transformer/rest_property_transformer';\nimport dtsRequireTypeTransformer from '../../src/transformer/dts_requiretype_transformer';\nimport ITsccSpecWithTS from '../../src/spec/ITsccSpecWithTS';\nimport {escapeGoogAdmissibleName} from '../../src/shared/escape_goog_identifier';\nimport path = require('path');\nimport upath = require('upath');\n\nconst samplesRoot = path.resolve(__dirname, '../sample');\n\ndescribe(`decoratorPropertyTransformer`, function () {\n\ttest(`modifies property name access to goog.reflect.objectProperty, add @nocollapse to jsdoc`, () => {\n\t\tconst testFiles = [\n\t\t\t\"decorator/decorates.ts\"\n\t\t];\n\n\t\tconst emitWithDecoratorTransformations = (override?: Partial<ts.CompilerOptions>) => {\n\t\t\treturn emit(testFiles, (transformerHost) => ({\n\t\t\t\tafterTs: [decoratorPropertyTransformer(transformerHost)]\n\t\t\t}), override);\n\t\t}\n\n\t\tconst {out} = emitWithDecoratorTransformations();\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(out.get(testFile)).toMatchSnapshot(testFile);\n\t\t}\n\n\t\tconst {out: es5Out} = emitWithDecoratorTransformations({target: ts.ScriptTarget.ES5});\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(es5Out.get(testFile)).toMatchSnapshot(testFile + ' - es5');\n\t\t}\n\t})\n})\n\ndescribe(`restPropertyTransformer`, function () {\n\ttest(`modifies property name access to goog.reflect.objectProperty`, () => {\n\t\tconst testFiles = [\n\t\t\t\"rest/case_1.ts\"\n\t\t];\n\n\t\tconst emitWithRestTransformations = (override?: Partial<ts.CompilerOptions>) => {\n\t\t\treturn emit(testFiles, (transformerHost) => ({\n\t\t\t\tafterTs: [restPropertyTransformer(transformerHost)]\n\t\t\t}), override);\n\t\t};\n\n\t\tconst {out} = emitWithRestTransformations();\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(out.get(testFile)).toMatchSnapshot(testFile);\n\t\t}\n\n\t\tconst {out: es5Out} = emitWithRestTransformations({target: ts.ScriptTarget.ES5});\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(es5Out.get(testFile)).toMatchSnapshot(testFile + ' - es5');\n\t\t}\n\t});\n\n\ttest(`works well when combined with decorators`, () => {\n\t\tconst testFiles = [\n\t\t\t\"rest/combined_with_decorators.ts\"\n\t\t];\n\n\t\tconst emitWithRestTransformations = (override?: Partial<ts.CompilerOptions>) => {\n\t\t\treturn emit(testFiles, (transformerHost) => ({\n\t\t\t\tafterTs: [\n\t\t\t\t\tdecoratorPropertyTransformer(transformerHost),\n\t\t\t\t\trestPropertyTransformer(transformerHost)\n\t\t\t\t]\n\t\t\t}), override);\n\t\t};\n\n\t\tconst {out} = emitWithRestTransformations();\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(out.get(testFile)).toMatchSnapshot(testFile);\n\t\t}\n\n\t\tconst {out: es5Out} = emitWithRestTransformations({target: ts.ScriptTarget.ES5});\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(es5Out.get(testFile)).toMatchSnapshot(testFile + ' - es5');\n\t\t}\n\t})\n});\n\ndescribe(`dts_requiretype_transformer`, () => {\n\ttest(`modifies requireType calls to a global variable`, () => {\n\t\tconst testFiles = [\n\t\t\t\"dts_requiretype/entry.ts\"\n\t\t];\n\t\tconst mockSpec = <ITsccSpecWithTS><unknown>{\n\t\t\tgetTSRoot() {\n\t\t\t\treturn samplesRoot;\n\t\t\t},\n\t\t\tgetExternalModuleNames() {\n\t\t\t\treturn []\n\t\t\t}\n\t\t};\n\t\tconst tsickleHostOverride: Partial<tsickle.TsickleHost> = {\n\t\t\tgoogmodule: true,\n\t\t\ttransformTypesToClosure: true,\n\t\t\tpathToModuleName(context, fileName) {\n\t\t\t\t// TODO: Having to depend on actual escapeGoog function here looks bad.\n\t\t\t\t// We have to decouple this test from an actual implementation. Maybe introduce a\n\t\t\t\t// tsccHost object that contains escapeGoog** and instantiate tsickleHost using that.\n\t\t\t\t// Currently\n\t\t\t\tif (/tslib/.test(fileName)) return 'tslib';\n\t\t\t\tif (context.length > 0) fileName = path.resolve(path.dirname(context), fileName);\n\t\t\t\tconst rel = path.relative(samplesRoot, fileName);\n\t\t\t\treturn escapeGoogAdmissibleName(rel);\n\t\t\t},\n\t\t\tfileNameToModuleId: x => \"\"\n\t\t};\n\n\t\tconst {out} = emit(testFiles, (transformerHost) => ({\n\t\t\tafterTs: [dtsRequireTypeTransformer(mockSpec, transformerHost)]\n\t\t}), {}, tsickleHostOverride);\n\t\tfor (let testFile of testFiles) {\n\t\t\texpect(out.get(testFile)).toMatchSnapshot(testFile);\n\t\t}\n\t})\n});\n\ntype EmitTransformerFactory = (host: tsickle.TsickleHost) => tsickle.EmitTransformers;\n\nfunction emit(\n\tfiles: string[], transformerFactory: EmitTransformerFactory,\n\toverride: Partial<ts.CompilerOptions> = {}, tsickleHostOverride: Partial<tsickle.TsickleHost> = {}\n) {\n\tconst {parsedConfig} = TsccSpecWithTS.loadTsConfigFromPath(samplesRoot);\n\tconst {options} = parsedConfig;\n\tObject.assign(options, override);\n\tconst host = ts.createCompilerHost(options);\n\tfiles = files.map(file => path.resolve(samplesRoot, file));\n\tconst program = ts.createProgram(files, options, host);\n\tconst transformerHost = Object.assign({\n\t\tshouldSkipTsickleProcessing: () => false,\n\t\tshouldIgnoreWarningsForPath: () => true,\n\t\tgoogmodule: false,\n\t\tpathToModuleName: x => x,\n\t\tfileNameToModuleId: x => x,\n\t\trootDirsRelative: x => x,\n\t\tmoduleResolutionHost: ts.createCompilerHost(parsedConfig.options),\n\t\toptions,\n\t\tgenerateExtraSuppressions: true\n\t}, tsickleHostOverride);\n\n\tconst out = new Map<string, string>();\n\n\tconst {externs} = tsickle.emit(program, transformerHost, (fileName, data) => {\n\t\tfileName = path.relative(samplesRoot, fileName);\n\t\tfileName = fileName.slice(0, -path.extname(fileName).length) + '.ts';\n\t\tfileName = upath.toUnix(fileName); // so that test outputs are independent of platforms\n\t\tout.set(fileName, data);\n\t}, /* targetSourceFile */ undefined, /* cancellationToken */ undefined, false,\n\t\ttransformerFactory(transformerHost));\n\treturn {out, externs}\n}\n"
  },
  {
    "path": "packages/tscc/test/tsconfig.test_files.json",
    "content": "{\n\t\"compilerOptions\": {\n\t\t\"types\": [],\n\t\t\"target\": \"es6\",\n\t\t\"module\": \"commonjs\",\n\t\t\"declaration\": false,\n\t\t\"importHelpers\": true,\n\t\t\"moduleResolution\": \"node\",\n\t\t\"forceConsistentCasingInFileNames\": true\n\t}\n}\n"
  },
  {
    "path": "packages/tscc/test/tsickle_patches/patch_tsickle_module_resolver.ts",
    "content": "///<reference types=\"jest\" />\nimport {getPackageBoundary} from '../../src/tsickle_patches/patch_tsickle_module_resolver';\nimport path = require('path');\n\ndescribe(`getPackageBoundary`, () => {\n\ttest(`extracts the latest (closest) directory when multiple node_modules are present in the path`, () => {\n\t\texpect(getPackageBoundary(`/a/b/c/d/e/node_modules/f/g/h/node_modules/i/j/k`))\n\t\t\t.toBe(path.normalize(`/a/b/c/d/e/node_modules/f/g/h/node_modules/i/`));\n\t})\n\ttest(`extracts scoped package boundaries correctly`, () => {\n\t\texpect(getPackageBoundary(`/a/b/c/d/node_modules/@e/f/g/h`))\n\t\t\t.toBe(path.normalize(`/a/b/c/d/node_modules/@e/f/`));\n\t})\n})\n"
  },
  {
    "path": "packages/tscc/third_party/closure_library/base.d.ts",
    "content": "/**\n * @fileoverview this is a hand-written, non-exhaustive d.ts file for closure library's base.js.\n * Instead of automatically generating this using clutz, we provide here a few definitions\n * written in hand, as in many cases one can refine type information than what clutz provides.\n *  - closure annotation {Object} incompatible with Typescript: dict-type object cannot be assigned\n *    to Object in Typescript.\n *  - One may use type predicates to provide a better user experience\n */\n\ndeclare namespace goog {\n\n\t/**\n\t * Reference to the global object.\n\t * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n\t *\n\t * More info on this implementation here:\n\t * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n\t *\n\t * @const\n\t * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n\t * @type {!Global}\n\t */\n\tconst global: typeof globalThis;\n\n\t/**\n\t * Handles strings that are intended to be used as CSS class names.\n\t *\n\t * This function works in tandem with @see goog.setCssNameMapping.\n\t *\n\t * Without any mapping set, the arguments are simple joined with a hyphen and\n\t * passed through unaltered.\n\t *\n\t * When there is a mapping, there are two possible styles in which these\n\t * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n\t * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n\t * style, the full css name is looked up in the map directly. If a rewrite is\n\t * not specified by the map, the compiler will output a warning.\n\t *\n\t * When the mapping is passed to the compiler, it will replace calls to\n\t * goog.getCssName with the strings from the mapping, e.g.\n\t *     var x = goog.getCssName('foo');\n\t *     var y = goog.getCssName(this.baseClass, 'active');\n\t *  becomes:\n\t *     var x = 'foo';\n\t *     var y = this.baseClass + '-active';\n\t *\n\t * If one argument is passed it will be processed, if two are passed only the\n\t * modifier will be processed, as it is assumed the first argument was generated\n\t * as a result of calling goog.getCssName.\n\t *\n\t * @param {string} className The class name.\n\t * @param {string=} opt_modifier A modifier to be appended to the class name.\n\t * @return {string} The class name or the concatenation of the class name and\n\t *     the modifier.\n\t */\n\tfunction getCssName(className: string, opt_modifier?: string): string\n\n\t/**\n\t * Sets the map to check when returning a value from goog.getCssName(). Example:\n\t * <pre>\n\t * goog.setCssNameMapping({\n\t *   \"goog\": \"a\",\n\t *   \"disabled\": \"b\",\n\t * });\n\t *\n\t * var x = goog.getCssName('goog');\n\t * // The following evaluates to: \"a a-b\".\n\t * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n\t * </pre>\n\t * When declared as a map of string literals to string literals, the JSCompiler\n\t * will replace all calls to goog.getCssName() using the supplied map if the\n\t * --process_closure_primitives flag is set.\n\t *\n\t * @param {!Object} mapping A map of strings to strings where keys are possible\n\t *     arguments to goog.getCssName() and values are the corresponding values\n\t *     that should be returned.\n\t * @param {string=} opt_style The style of css name mapping. There are two valid\n\t *     options: 'BY_PART', and 'BY_WHOLE'.\n\t * @see goog.getCssName for a description.\n\t */\n\tfunction setCssNameMapping(mapping: {[key: string]: string}, opt_style: 'BY_PART' | 'BY_WHOLE'): void\n\n\t/**\n\t * Gets a localized message.\n\t *\n\t * This function is a compiler primitive. If you give the compiler a localized\n\t * message bundle, it will replace the string at compile-time with a localized\n\t * version, and expand goog.getMsg call to a concatenated string.\n\t *\n\t * Messages must be initialized in the form:\n\t * <code>\n\t * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n\t * </code>\n\t *\n\t * This function produces a string which should be treated as plain text. Use\n\t * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n\t * produce SafeHtml.\n\t *\n\t * @param {string} str Translatable string, places holders in the form {$foo}.\n\t * @param {Object<string, string>=} opt_values Maps place holder name to value.\n\t * @param {{html: boolean}=} opt_options Options:\n\t *     html: Escape '<' in str to '&lt;'. Used by Closure Templates where the\n\t *     generated code size and performance is critical which is why {@link\n\t *     goog.html.SafeHtmlFormatter} is not used. The value must be literal true\n\t *     or false.\n\t * @return {string} message with placeholders filled.\n\t */\n\tfunction getMsg(str: string, opt_values?: {[key: string]: string}, opt_options?: {html: boolean}): string\n\n\t/**\n\t * Gets a localized message. If the message does not have a translation, gives a\n\t * fallback message.\n\t *\n\t * This is useful when introducing a new message that has not yet been\n\t * translated into all languages.\n\t *\n\t * This function is a compiler primitive. Must be used in the form:\n\t * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n\t * where MSG_A and MSG_B were initialized with goog.getMsg.\n\t *\n\t * @param {string} a The preferred message.\n\t * @param {string} b The fallback message.\n\t * @return {string} The best translated message.\n\t */\n\tfunction getMsgWithFallback(a: string, b: string): string\n\n\t/**\n\t * Exposes an unobfuscated global namespace path for the given object.\n\t * Note that fields of the exported object *will* be obfuscated, unless they are\n\t * exported in turn via this function or goog.exportProperty.\n\t *\n\t * Also handy for making public items that are defined in anonymous closures.\n\t *\n\t * ex. goog.exportSymbol('public.path.Foo', Foo);\n\t *\n\t * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n\t *     public.path.Foo.staticFunction();\n\t *\n\t * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n\t *                       Foo.prototype.myMethod);\n\t *     new public.path.Foo().myMethod();\n\t *\n\t * @param {string} publicPath Unobfuscated name to export.\n\t * @param {*} object Object the name should point to.\n\t * @param {Object=} opt_objectToExportTo The object to add the path to; default\n\t *     is goog.global.\n\t */\n\tfunction exportSymbol(publicPath: string, object: any, opt_objectToExportTo?: {}): void\n\n\t/**\n\t * Exports a property unobfuscated into the object's namespace.\n\t * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n\t * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n\t * @param {Object} object Object whose static property is being exported.\n\t * @param {string} publicName Unobfuscated name to export.\n\t * @param {*} symbol Object the name should point to.\n\t */\n\tfunction exportProperty(object: {}, publicName: string, symbol: any): void\n\n\t/**\n\t * Defines a named value. In uncompiled mode, the value is retrieved from\n\t * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n\t * has the property specified, and otherwise used the defined defaultValue.\n\t * When compiled the default can be overridden using the compiler options or the\n\t * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n\t * can be used safely in modules. Note that the value type MUST be either\n\t * boolean, number, or string.\n\t *\n\t * @param {string} name The distinguished name to provide.\n\t * @param {T} defaultValue\n\t * @return {T} The defined value.\n\t * @template T\n\t */\n\tfunction define<T extends string | number | boolean>(name: string, defaultValue: T): T\n\n\t/**\n\t * @define {boolean} DEBUG is provided as a convenience so that debugging code\n\t * that should not be included in a production. It can be easily stripped\n\t * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n\t * JSCompiler. For example, most toString() methods should be declared inside an\n\t * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n\t * purposes and it is difficult for the JSCompiler to statically determine\n\t * whether they are used.\n\t */\n\tvar DEBUG: boolean;\n\n\n\t//==============================================================================\n\t// Language Enhancements\n\t//==============================================================================\n\n\t/**\n\t * This is a \"fixed\" version of the typeof operator.  It differs from the typeof\n\t * operator in such a way that null returns 'null' and arrays return 'array'.\n\t * @param {?} value The value to get the type of.\n\t * @return {string} The name of the type.\n\t */\n\tfunction typeOf(value: any): \"undefined\" | \"null\" | \"boolean\" | \"number\" | \"string\" | \"object\" | \"function\" | \"array\"\n\n\t/**\n\t * Returns true if the specified value is not undefined.\n\t *\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is defined.\n\t */\n\tfunction isDef<T>(x: T): x is T extends undefined ? never : T;\n\n\t/**\n\t * Returns true if the specified value is a string.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is a string.\n\t */\n\tfunction isString(x: any): x is string\n\n\t/**\n\t * Returns true if the specified value is a boolean.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is boolean.\n\t */\n\tfunction isBoolean(x: any): x is boolean\n\n\t/**\n\t * Returns true if the specified value is a number.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is a number.\n\t */\n\tfunction isNumber(x: any): x is number\n\n\t/**\n\t * Returns true if the specified value is null.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is null.\n\t */\n\tfunction isNull(x: any): x is null\n\n\t/**\n\t * Returns true if the specified value is defined and not null.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is defined and not null.\n\t */\n\tfunction isDefAndNotNull<T>(x: T): x is NonNullable<T>\n\t/**\n\t * Returns true if the specified value is an array.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is an array.\n\t */\n\tfunction isArray(x: any): x is Array<any>\n\n\t/**\n\t * Returns true if the object looks like an array. To qualify as array like\n\t * the value needs to be either a NodeList or an object with a Number length\n\t * property. Note that for this function neither strings nor functions are\n\t * considered \"array-like\".\n\t *\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is an array.\n\t */\n\tfunction isArrayLike(x: any): x is ArrayLike<any>\n\n\n\t/**\n\t * Returns true if the object looks like a Date. To qualify as Date-like the\n\t * value needs to be an object and have a getFullYear() function.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is a like a Date.\n\t */\n\tfunction isDateLike(x: any): x is Date\n\n\t/**\n\t * Returns true if the specified value is a function.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is a function.\n\t */\n\tfunction isFunction(x: any): x is Function\n\n\n\t/**\n\t * Returns true if the specified value is an object.  This includes arrays and\n\t * functions.\n\t * @param {?} val Variable to test.\n\t * @return {boolean} Whether variable is an object.\n\t */\n\tfunction isObject(x: any): x is NonNullable<object> | Function;\n}\n\n// This module name is a tsickle primitive, see `googmodule.ts` of tsickle. Instead of exposing\n// `goog` to the global scope, we let users to write (precisely)\n//\n// import * as goog from 'goog:google3.javascript.closure.goog';\n//\n// to get a handle of a goog namespace.\ndeclare module \"goog:goog\" {\n\texport = goog;\n}\n"
  },
  {
    "path": "packages/tscc/third_party/closure_library/base.js",
    "content": "// Copyright 2006 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true.  This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library.  Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n    // Check `this` first for backwards compatibility.\n    // Valid unless running as an ES module or in a function wrapper called\n    //   without setting `this` properly.\n    // Note that base.js can't usefully be imported as an ES module, but it may\n    // be compiled into bundles that are loadable as ES modules.\n    this ||\n    // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n    // For in-page browser environments and workers.\n    self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js.  If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value.  This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n *   var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code.  In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n *   var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Returns true if the specified value is not undefined.\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is defined.\n * @deprecated Use `val !== undefined` instead.\n */\ngoog.isDef = function(val) {\n  // void 0 always evaluates to undefined and hence we do not need to depend on\n  // the definition of the global variable named 'undefined'.\n  return val !== void 0;\n};\n\n/**\n * Returns true if the specified value is a string.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a string.\n * @deprecated Use `typeof val === 'string'` instead.\n */\ngoog.isString = function(val) {\n  return typeof val == 'string';\n};\n\n\n/**\n * Returns true if the specified value is a boolean.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is boolean.\n * @deprecated Use `typeof val === 'boolean'` instead.\n */\ngoog.isBoolean = function(val) {\n  return typeof val == 'boolean';\n};\n\n\n/**\n * Returns true if the specified value is a number.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a number.\n * @deprecated Use `typeof val === 'number'` instead.\n */\ngoog.isNumber = function(val) {\n  return typeof val == 'number';\n};\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name name of the object that this file defines.\n * @param {*=} opt_object the object to expose at the end of the path.\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\n *     is `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {\n  var parts = name.split('.');\n  var cur = opt_objectToExportTo || goog.global;\n\n  // Internet Explorer exhibits strange behavior when throwing errors from\n  // methods externed in this manner.  See the testExportSymbolExceptions in\n  // base_test.html for an example.\n  if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n    cur.execScript('var ' + parts[0]);\n  }\n\n  for (var part; parts.length && (part = parts.shift());) {\n    if (!parts.length && opt_object !== undefined) {\n      // last part and we have an object; use it\n      cur[part] = opt_object;\n    } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n      cur = cur[part];\n    } else {\n      cur = cur[part] = {};\n    }\n  }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n  var value = defaultValue;\n  if (!COMPILED) {\n    var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n    var defines = goog.global.CLOSURE_DEFINES;\n    if (uncompiledDefines &&\n        // Anti DOM-clobbering runtime check (b/37736576).\n        /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n        Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n      value = uncompiledDefines[name];\n    } else if (\n        defines &&\n        // Anti DOM-clobbering runtime check (b/37736576).\n        /** @type {?} */ (defines).nodeType === undefined &&\n        Object.prototype.hasOwnProperty.call(defines, name)) {\n      value = defines[name];\n    }\n  }\n  return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present.  This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year.  For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n *   // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n *   // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n *     goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en');  // default to en\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether a project is expected to be running in strict mode.\n *\n * This define can be used to trigger alternate implementations compatible with\n * running in EcmaScript Strict mode or warn about unavailable functionality.\n * @see https://goo.gl/PudQ4y\n *\n */\ngoog.STRICT_MODE_COMPATIBLE = goog.define('goog.STRICT_MODE_COMPATIBLE', false);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n *     be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n    goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n *     loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n    goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n *     \"goog.package.part\".\n */\ngoog.provide = function(name) {\n  if (goog.isInModuleLoader_()) {\n    throw new Error('goog.provide cannot be used within a module.');\n  }\n  if (!COMPILED) {\n    // Ensure that the same namespace isn't provided twice.\n    // A goog.module/goog.provide maps a goog.require to a specific file\n    if (goog.isProvided_(name)) {\n      throw new Error('Namespace \"' + name + '\" already declared.');\n    }\n  }\n\n  goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n *     \"goog.package.part\".\n * @param {Object=} opt_obj The object to embed in the namespace.\n * @private\n */\ngoog.constructNamespace_ = function(name, opt_obj) {\n  if (!COMPILED) {\n    delete goog.implicitNamespaces_[name];\n\n    var namespace = name;\n    while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n      if (goog.getObjectByName(namespace)) {\n        break;\n      }\n      goog.implicitNamespaces_[namespace] = true;\n    }\n  }\n\n  goog.exportPath_(name, opt_obj);\n};\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n *     Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n */\ngoog.getScriptNonce = function(opt_window) {\n  if (opt_window && opt_window != goog.global) {\n    return goog.getScriptNonce_(opt_window.document);\n  }\n  if (goog.cspNonce_ === null) {\n    goog.cspNonce_ = goog.getScriptNonce_(goog.global.document);\n  }\n  return goog.cspNonce_;\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * @private {?string}\n */\ngoog.cspNonce_ = null;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {!Document} doc\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(doc) {\n  var script = doc.querySelector && doc.querySelector('script[nonce]');\n  if (script) {\n    // Try to get the nonce from the IDL property first, because browsers that\n    // implement additional nonce protection features (currently only Chrome) to\n    // prevent nonce stealing via CSS do not expose the nonce via attributes.\n    // See https://github.com/whatwg/html/issues/2369\n    var nonce = script['nonce'] || script.getAttribute('nonce');\n    if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n      return nonce;\n    }\n  }\n  return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n *   the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n *   restrictions are intended to leave the door open for using goog.require\n *   with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n *     \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n  if (typeof name !== 'string' || !name ||\n      name.search(goog.VALID_MODULE_RE_) == -1) {\n    throw new Error('Invalid module identifier');\n  }\n  if (!goog.isInGoogModuleLoader_()) {\n    throw new Error(\n        'Module ' + name + ' has been loaded incorrectly. Note, ' +\n        'modules cannot be loaded as normal scripts. They require some kind of ' +\n        'pre-processing step. You\\'re likely trying to load a module via a ' +\n        'script tag or as a part of a concatenated bundle without rewriting the ' +\n        'module. For more info see: ' +\n        'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n  }\n  if (goog.moduleLoaderState_.moduleName) {\n    throw new Error('goog.module may only be called once per module.');\n  }\n\n  // Store the module name for the loader.\n  goog.moduleLoaderState_.moduleName = name;\n  if (!COMPILED) {\n    // Ensure that the same namespace isn't provided twice.\n    // A goog.module/goog.provide maps a goog.require to a specific file\n    if (goog.isProvided_(name)) {\n      throw new Error('Namespace \"' + name + '\" already declared.');\n    }\n    delete goog.implicitNamespaces_[name];\n  }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n  return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n  if (!COMPILED) {\n    if (name in goog.loadedModules_) {\n      return goog.loadedModules_[name].exports;\n    } else if (!goog.implicitNamespaces_[name]) {\n      var ns = goog.getObjectByName(name);\n      return ns != null ? ns : null;\n    }\n  }\n  return null;\n};\n\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n  ES6: 'es6',\n  GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n *   moduleName: (string|undefined),\n *   declareLegacyNamespace:boolean,\n *   type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n *     initialized.\n */\ngoog.isInModuleLoader_ = function() {\n  return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n  return !!goog.moduleLoaderState_ &&\n      goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n  var inLoader = !!goog.moduleLoaderState_ &&\n      goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n  if (inLoader) {\n    return true;\n  }\n\n  var jscomp = goog.global['$jscomp'];\n\n  if (jscomp) {\n    // jscomp may not have getCurrentModulePath if this is a compiled bundle\n    // that has some of the runtime, but not all of it. This can happen if\n    // optimizations are turned on so the unused runtime is removed but renaming\n    // and Closure pass are off (so $jscomp is still named $jscomp and the\n    // goog.provide/require calls still exist).\n    if (typeof jscomp.getCurrentModulePath != 'function') {\n      return false;\n    }\n\n    // Bundled ES6 module.\n    return !!jscomp.getCurrentModulePath();\n  }\n\n  return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name.  This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n  if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n    throw new Error(\n        'goog.module.declareLegacyNamespace must be called from ' +\n        'within a goog.module');\n  }\n  if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n    throw new Error(\n        'goog.module must be called prior to ' +\n        'goog.module.declareLegacyNamespace.');\n  }\n  goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID  acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n  if (!COMPILED) {\n    if (!goog.isInEs6ModuleLoader_()) {\n      throw new Error(\n          'goog.declareModuleId may only be called from ' +\n          'within an ES6 module');\n    }\n    if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n      throw new Error(\n          'goog.declareModuleId may only be called once per module.');\n    }\n    if (namespace in goog.loadedModules_) {\n      throw new Error(\n          'Module with namespace \"' + namespace + '\" already exists.');\n    }\n  }\n  if (goog.moduleLoaderState_) {\n    // Not bundled - debug loading.\n    goog.moduleLoaderState_.moduleName = namespace;\n  } else {\n    // Bundled - not debug loading, no module loader state.\n    var jscomp = goog.global['$jscomp'];\n    if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n      throw new Error(\n          'Module with namespace \"' + namespace +\n          '\" has been loaded incorrectly.');\n    }\n    var exports = jscomp.require(jscomp.getCurrentModulePath());\n    goog.loadedModules_[namespace] = {\n      exports: exports,\n      type: goog.ModuleType.ES6,\n      moduleId: namespace\n    };\n  }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n *     raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n  if (goog.DISALLOW_TEST_ONLY_CODE) {\n    opt_message = opt_message || '';\n    throw new Error(\n        'Importing test-only code into non-debug environment' +\n        (opt_message ? ': ' + opt_message : '.'));\n  }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n *     \"goog.package.part\".\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n  /**\n   * Check if the given name has been goog.provided. This will return false for\n   * names that are available only as implicit namespaces.\n   * @param {string} name name of the object to look for.\n   * @return {boolean} Whether the name has been provided.\n   * @private\n   */\n  goog.isProvided_ = function(name) {\n    return (name in goog.loadedModules_) ||\n        (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n  };\n\n  /**\n   * Namespaces implicitly defined by goog.provide. For example,\n   * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n   * 'goog.events' must be namespaces.\n   *\n   * @type {!Object<string, (boolean|undefined)>}\n   * @private\n   */\n  goog.implicitNamespaces_ = {'goog.module': true};\n\n  // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n  // here and because the existing module package has not been moved yet out of\n  // the goog.module namespace. This satisifies both the debug loader and\n  // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name.  The object\n * is not found if null or undefined.  If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n *     |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n  var parts = name.split('.');\n  var cur = opt_obj || goog.global;\n  for (var i = 0; i < parts.length; i++) {\n    cur = cur[parts[i]];\n    if (cur == null) {\n      return null;\n    }\n  }\n  return cur;\n};\n\n\n/**\n * Globalizes a whole namespace, such as goog or goog.lang.\n *\n * @param {!Object} obj The namespace to globalize.\n * @param {Object=} opt_global The object to add the properties to.\n * @deprecated Properties may be explicitly exported to the global scope, but\n *     this should no longer be done in bulk.\n */\ngoog.globalize = function(obj, opt_global) {\n  var global = opt_global || goog.global;\n  for (var x in obj) {\n    global[x] = obj[x];\n  }\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n *     the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n *     the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n *     how the file must be loaded.  The boolean 'true' is equivalent\n *     to {'module': 'goog'} for backwards-compatibility.  Valid properties\n *     and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n  if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n    goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n  }\n};\n\n\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development.  The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script.  If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js.  Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n  if (goog.global.console) {\n    goog.global.console['error'](msg);\n  }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n *     goog.module, or goog.declareModuleId) in the form\n *     \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n *     namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n  if (!COMPILED) {\n    // Might need to lazy load on old IE.\n    if (goog.ENABLE_DEBUG_LOADER) {\n      goog.debugLoader_.requested(namespace);\n    }\n\n    // If the object already exists we do not need to do anything.\n    if (goog.isProvided_(namespace)) {\n      if (goog.isInModuleLoader_()) {\n        return goog.module.getInternal_(namespace);\n      }\n    } else if (goog.ENABLE_DEBUG_LOADER) {\n      var moduleLoaderState = goog.moduleLoaderState_;\n      goog.moduleLoaderState_ = null;\n      try {\n        goog.debugLoader_.load_(namespace);\n      } finally {\n        goog.moduleLoaderState_ = moduleLoaderState;\n      }\n    }\n\n    return null;\n  }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n *     goog.module, or goog.declareModuleId) in the form\n *     \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n  // Return an empty object so that single-level destructuring of the return\n  // value doesn't crash at runtime when using the debug loader. Multi-level\n  // destructuring isn't supported.\n  return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * Null function used for default values of callbacks, etc.\n * @return {void} Nothing.\n */\ngoog.nullFunction = function() {};\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n *     code. See\n *     https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n  throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n *     method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n *     but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n  // instance_ is immediately set to prevent issues with sealed constructors\n  // such as are encountered when a constructor is returned as the export object\n  // of a goog.module in unoptimized code.\n  // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n  /** @type {undefined|!Object} @suppress {underscore} */\n  ctor.instance_ = undefined;\n  ctor.getInstance = function() {\n    if (ctor.instance_) {\n      return ctor.instance_;\n    }\n    if (goog.DEBUG) {\n      // NOTE: JSCompiler can't optimize away Array#push.\n      goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n    }\n    // Cast to avoid conformance violations that ctor.instance_ is unknown\n    return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n  };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader.  This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile.  Valid values\n * are 'always', 'never', and 'detect'.  The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n    goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} If a file needs to be transpiled what the output language\n * should be. By default this is the highest language level this file detects\n * the current environment supports. Generally this flag should not be set, but\n * it could be useful to override. Example: If the current environment supports\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\n * overridden.\n *\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\n * is treated as es3.\n *\n * Note that setting this value does not force transpilation. Just if\n * transpilation occurs this will be the output. So this is most useful when\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\n * something lower than what the environment detects.\n */\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\n\n\n/**\n * @define {string} Path to the transpiler.  Executing the script at this\n * path (relative to base.js) should define a function $jscomp.transpile.\n */\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @return {boolean}\n * @package Visible for testing.\n */\ngoog.useSafari10Workaround = function() {\n  if (goog.hasBadLetScoping == null) {\n    var hasBadLetScoping;\n    try {\n      hasBadLetScoping = !eval(\n          '\"use strict\";' +\n          'let x = 1; function f() { return typeof x; };' +\n          'f() == \"number\";');\n    } catch (e) {\n      // Assume that ES6 syntax isn't supported.\n      hasBadLetScoping = false;\n    }\n    goog.hasBadLetScoping = hasBadLetScoping;\n  }\n  return goog.hasBadLetScoping;\n};\n\n\n/**\n * @param {string} moduleDef\n * @return {string}\n * @package Visible for testing.\n */\ngoog.workaroundSafari10EvalBug = function(moduleDef) {\n  return '(function(){' + moduleDef +\n      '\\n' +  // Terminate any trailing single line comment.\n      ';' +   // Terminate any trailing expression.\n      '})();\\n';\n};\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n  // NOTE: we allow function definitions to be either in the from\n  // of a string to eval (which keeps the original source intact) or\n  // in a eval forbidden environment (CSP) we allow a function definition\n  // which in its body must call `goog.module`, and return the exports\n  // of the module.\n  var previousState = goog.moduleLoaderState_;\n  try {\n    goog.moduleLoaderState_ = {\n      moduleName: '',\n      declareLegacyNamespace: false,\n      type: goog.ModuleType.GOOG\n    };\n    var exports;\n    if (goog.isFunction(moduleDef)) {\n      exports = moduleDef.call(undefined, {});\n    } else if (typeof moduleDef === 'string') {\n      if (goog.useSafari10Workaround()) {\n        moduleDef = goog.workaroundSafari10EvalBug(moduleDef);\n      }\n\n      exports = goog.loadModuleFromSource_.call(undefined, moduleDef);\n    } else {\n      throw new Error('Invalid module definition');\n    }\n\n    var moduleName = goog.moduleLoaderState_.moduleName;\n    if (typeof moduleName === 'string' && moduleName) {\n      // Don't seal legacy namespaces as they may be used as a parent of\n      // another namespace\n      if (goog.moduleLoaderState_.declareLegacyNamespace) {\n        goog.constructNamespace_(moduleName, exports);\n      } else if (\n          goog.SEAL_MODULE_EXPORTS && Object.seal &&\n          typeof exports == 'object' && exports != null) {\n        Object.seal(exports);\n      }\n\n      var data = {\n        exports: exports,\n        type: goog.ModuleType.GOOG,\n        moduleId: goog.moduleLoaderState_.moduleName\n      };\n      goog.loadedModules_[moduleName] = data;\n    } else {\n      throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n    }\n  } finally {\n    goog.moduleLoaderState_ = previousState;\n  }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {\n  // NOTE: we avoid declaring parameters or local variables here to avoid\n  // masking globals or leaking values into the module definition.\n  'use strict';\n  var exports = {};\n  eval(arguments[0]);\n  return exports;\n});\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n  var components = path.split('/');\n  var i = 0;\n  while (i < components.length) {\n    if (components[i] == '.') {\n      components.splice(i, 1);\n    } else if (\n        i && components[i] == '..' && components[i - 1] &&\n        components[i - 1] != '..') {\n      components.splice(--i, 2);\n    } else {\n      i++;\n    }\n  }\n  return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules.  In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n  if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n    return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n  } else {\n    try {\n      /** @type {XMLHttpRequest} */\n      var xhr = new goog.global['XMLHttpRequest']();\n      xhr.open('get', src, false);\n      xhr.send();\n      // NOTE: Successful http: requests have a status of 200, but successful\n      // file: requests may have a status of zero.  Any other status, or a\n      // thrown exception (particularly in case of file: requests) indicates\n      // some sort of error, which we treat as a missing or unavailable file.\n      return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n    } catch (err) {\n      // No need to rethrow or log, since errors should show up on their own.\n      return null;\n    }\n  }\n};\n\n\n/**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @param {string} target Language level output.\n * @return {string} The transpiled code.\n * @private\n */\ngoog.transpile_ = function(code, path, target) {\n  var jscomp = goog.global['$jscomp'];\n  if (!jscomp) {\n    goog.global['$jscomp'] = jscomp = {};\n  }\n  var transpile = jscomp.transpile;\n  if (!transpile) {\n    var transpilerPath = goog.basePath + goog.TRANSPILER;\n    var transpilerCode = goog.loadFileSync_(transpilerPath);\n    if (transpilerCode) {\n      // This must be executed synchronously, since by the time we know we\n      // need it, we're about to load and write the ES6 code synchronously,\n      // so a normal script-tag load will be too slow. Wrapped in a function\n      // so that code is eval'd in the global scope.\n      (function() {\n        (0, eval)(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\n      }).call(goog.global);\n      // Even though the transpiler is optional, if $gwtExport is found, it's\n      // a sign the transpiler was loaded and the $jscomp.transpile *should*\n      // be there.\n      if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\n          !goog.global['$gwtExport']['$jscomp']['transpile']) {\n        throw new Error(\n            'The transpiler did not properly export the \"transpile\" ' +\n            'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\n      }\n      // transpile.js only exports a single $jscomp function, transpile. We\n      // grab just that and add it to the existing definition of $jscomp which\n      // contains the polyfills.\n      goog.global['$jscomp'].transpile =\n          goog.global['$gwtExport']['$jscomp']['transpile'];\n      jscomp = goog.global['$jscomp'];\n      transpile = jscomp.transpile;\n    }\n  }\n  if (!transpile) {\n    // The transpiler is an optional component.  If it's not available then\n    // replace it with a pass-through function that simply logs.\n    var suffix = ' requires transpilation but no transpiler was found.';\n    transpile = jscomp.transpile = function(code, path) {\n      // TODO(sdh): figure out some way to get this error to show up\n      // in test results, noting that the failure may occur in many\n      // different ways, including in loadModule() before the test\n      // runner even comes up.\n      goog.logToConsole_(path + suffix);\n      return code;\n    };\n  }\n  // Note: any transpilation errors/warnings will be logged to the console.\n  return transpile(code, path, target);\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator.  It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n  var s = typeof value;\n  if (s == 'object') {\n    if (value) {\n      // Check these first, so we can avoid calling Object.prototype.toString if\n      // possible.\n      //\n      // IE improperly marshals typeof across execution contexts, but a\n      // cross-context object will still return false for \"instanceof Object\".\n      if (value instanceof Array) {\n        return 'array';\n      } else if (value instanceof Object) {\n        return s;\n      }\n\n      // HACK: In order to use an Object prototype method on the arbitrary\n      //   value, the compiler requires the value be cast to type Object,\n      //   even though the ECMA spec explicitly allows it.\n      var className = Object.prototype.toString.call(\n          /** @type {!Object} */ (value));\n      // In Firefox 3.6, attempting to access iframe window objects' length\n      // property throws an NS_ERROR_FAILURE, so we need to special-case it\n      // here.\n      if (className == '[object Window]') {\n        return 'object';\n      }\n\n      // We cannot always use constructor == Array or instanceof Array because\n      // different frames have different Array objects. In IE6, if the iframe\n      // where the array was created is destroyed, the array loses its\n      // prototype. Then dereferencing val.splice here throws an exception, so\n      // we can't use goog.isFunction. Calling typeof directly returns 'unknown'\n      // so that will work. In this case, this function will return false and\n      // most array functions will still work because the array is still\n      // array-like (supports length and []) even though it has lost its\n      // prototype.\n      // Mark Miller noticed that Object.prototype.toString\n      // allows access to the unforgeable [[Class]] property.\n      //  15.2.4.2 Object.prototype.toString ( )\n      //  When the toString method is called, the following steps are taken:\n      //      1. Get the [[Class]] property of this object.\n      //      2. Compute a string value by concatenating the three strings\n      //         \"[object \", Result(1), and \"]\".\n      //      3. Return Result(2).\n      // and this behavior survives the destruction of the execution context.\n      if ((className == '[object Array]' ||\n           // In IE all non value types are wrapped as objects across window\n           // boundaries (not iframe though) so we have to do object detection\n           // for this edge case.\n           typeof value.length == 'number' &&\n               typeof value.splice != 'undefined' &&\n               typeof value.propertyIsEnumerable != 'undefined' &&\n               !value.propertyIsEnumerable('splice')\n\n               )) {\n        return 'array';\n      }\n      // HACK: There is still an array case that fails.\n      //     function ArrayImpostor() {}\n      //     ArrayImpostor.prototype = [];\n      //     var impostor = new ArrayImpostor;\n      // this can be fixed by getting rid of the fast path\n      // (value instanceof Array) and solely relying on\n      // (value && Object.prototype.toString.vall(value) === '[object Array]')\n      // but that would require many more function calls and is not warranted\n      // unless closure code is receiving objects from untrusted sources.\n\n      // IE in cross-window calls does not correctly marshal the function type\n      // (it appears just as an object) so we cannot use just typeof val ==\n      // 'function'. However, if the object has a call property, it is a\n      // function.\n      if ((className == '[object Function]' ||\n           typeof value.call != 'undefined' &&\n               typeof value.propertyIsEnumerable != 'undefined' &&\n               !value.propertyIsEnumerable('call'))) {\n        return 'function';\n      }\n\n    } else {\n      return 'null';\n    }\n\n  } else if (s == 'function' && typeof value.call == 'undefined') {\n    // In Safari typeof nodeList returns 'function', and on Firefox typeof\n    // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We\n    // would like to return object for those and we can detect an invalid\n    // function by making sure that the function object has a call method.\n    return 'object';\n  }\n  return s;\n};\n\n\n/**\n * Returns true if the specified value is null.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is null.\n * @deprecated Use `val === null` instead.\n */\ngoog.isNull = function(val) {\n  return val === null;\n};\n\n\n/**\n * Returns true if the specified value is defined and not null.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is defined and not null.\n * @deprecated Use `val != null` instead.\n */\ngoog.isDefAndNotNull = function(val) {\n  // Note that undefined == null.\n  return val != null;\n};\n\n\n/**\n * Returns true if the specified value is an array.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArray = function(val) {\n  return goog.typeOf(val) == 'array';\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n  var type = goog.typeOf(val);\n  // We do not use goog.isObject here in order to exclude function values.\n  return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n  return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is a function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.isFunction = function(val) {\n  return goog.typeOf(val) == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object.  This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n  var type = typeof val;\n  return type == 'object' && val != null || type == 'function';\n  // return Object(val) === val also works, but is slower, especially if val is\n  // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n  // TODO(arv): Make the type stricter, do not accept null.\n\n  // In Opera window.hasOwnProperty exists but always returns false so we avoid\n  // using it. As a consequence the unique ID generated for BaseClass.prototype\n  // and SubClass.prototype will be the same.\n  // TODO(b/141512323): UUIDs are broken for ctors with class-side inheritance.\n  return obj[goog.UID_PROPERTY_] ||\n      (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n  return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n  // TODO(arv): Make the type stricter, do not accept null.\n\n  // In IE, DOM nodes are not instances of Object and throw an exception if we\n  // try to delete.  Instead we try to use removeAttribute.\n  if (obj !== null && 'removeAttribute' in obj) {\n    obj.removeAttribute(goog.UID_PROPERTY_);\n  }\n\n  try {\n    delete obj[goog.UID_PROPERTY_];\n  } catch (ex) {\n  }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Adds a hash code field to an object. The hash code is unique for the\n * given object.\n * @param {Object} obj The object to get the hash code for.\n * @return {number} The hash code for the object.\n * @deprecated Use goog.getUid instead.\n */\ngoog.getHashCode = goog.getUid;\n\n\n/**\n * Removes the hash code field from an object.\n * @param {Object} obj The object to remove the field from.\n * @deprecated Use goog.removeUid instead.\n */\ngoog.removeHashCode = goog.removeUid;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n  var type = goog.typeOf(obj);\n  if (type == 'object' || type == 'array') {\n    if (typeof obj.clone === 'function') {\n      return obj.clone();\n    }\n    var clone = type == 'array' ? [] : {};\n    for (var key in obj) {\n      clone[key] = goog.cloneObject(obj[key]);\n    }\n    return clone;\n  }\n\n  return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n *     function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n *     function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n *     invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n  return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n *     function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n *     function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n *     invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n  if (!fn) {\n    throw new Error();\n  }\n\n  if (arguments.length > 2) {\n    var boundArgs = Array.prototype.slice.call(arguments, 2);\n    return function() {\n      // Prepend the bound arguments to the current arguments.\n      var newArgs = Array.prototype.slice.call(arguments);\n      Array.prototype.unshift.apply(newArgs, boundArgs);\n      return fn.apply(selfObj, newArgs);\n    };\n\n  } else {\n    return function() {\n      return fn.apply(selfObj, arguments);\n    };\n  }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n *     function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n *     function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n *     invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n  // TODO(nicksantos): narrow the type signature.\n  if (Function.prototype.bind &&\n      // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n      // extension environment. This means that for Chrome extensions, they get\n      // the implementation of Function.prototype.bind that calls goog.bind\n      // instead of the native one. Even worse, we don't want to introduce a\n      // circular dependency between goog.bind and Function.prototype.bind, so\n      // we have to hack this to make sure it works correctly.\n      Function.prototype.bind.toString().indexOf('native code') != -1) {\n    goog.bind = goog.bindNative_;\n  } else {\n    goog.bind = goog.bindJs_;\n  }\n  return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n *     was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n  var args = Array.prototype.slice.call(arguments, 1);\n  return function() {\n    // Clone the array (with slice()) and append additional arguments\n    // to the existing arguments.\n    var newArgs = args.slice();\n    newArgs.push.apply(newArgs, arguments);\n    return fn.apply(/** @type {?} */ (this), newArgs);\n  };\n};\n\n\n/**\n * Copies all the members of a source object to a target object. This method\n * does not work on all browsers for all objects that contain keys such as\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\n *\n * NOTE: Some have advocated for the use of goog.mixin to setup classes\n * with multiple inheritence (traits, mixins, etc).  However, as it simply\n * uses \"for in\", this is not compatible with ES6 classes whose methods are\n * non-enumerable.  Changing this, would break cases where non-enumerable\n * properties are not expected.\n *\n * @param {Object} target Target.\n * @param {Object} source Source.\n * @deprecated Prefer Object.assign\n */\ngoog.mixin = function(target, source) {\n  for (var x in source) {\n    target[x] = source[x];\n  }\n\n  // For IE7 or lower, the for-in-loop does not contain any properties that are\n  // not enumerable on the prototype object (for example, isPrototypeOf from\n  // Object.prototype) but also it will not include 'replace' on objects that\n  // extend String and change 'replace' (not that it is common for anyone to\n  // extend anything except Object).\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n *     between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = (goog.TRUSTED_SITE && Date.now) || (function() {\n             // Unary plus operator converts its operand to a number which in\n             // the case of\n             // a date is done by calling getTime().\n             return +new Date();\n           });\n\n\n/**\n * Evals JavaScript in the global scope.  In IE this uses execScript, other\n * browsers use goog.global.eval. If goog.global.eval does not evaluate in the\n * global scope (for example, in Safari), appends a script tag instead.\n * Throws an exception if neither execScript or eval is defined.\n * @param {string} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n  if (goog.global.execScript) {\n    goog.global.execScript(script, 'JavaScript');\n  } else if (goog.global.eval) {\n    // Test to see if eval works\n    if (goog.evalWorksForGlobals_ == null) {\n      try {\n        goog.global.eval('var _evalTest_ = 1;');\n      } catch (ignore) {\n      }\n      if (typeof goog.global['_evalTest_'] != 'undefined') {\n        try {\n          delete goog.global['_evalTest_'];\n        } catch (ignore) {\n          // Microsoft edge fails the deletion above in strict mode.\n        }\n        goog.evalWorksForGlobals_ = true;\n      } else {\n        goog.evalWorksForGlobals_ = false;\n      }\n    }\n\n    if (goog.evalWorksForGlobals_) {\n      goog.global.eval(script);\n    } else {\n      /** @type {!Document} */\n      var doc = goog.global.document;\n      var scriptElt =\n          /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n      scriptElt.type = 'text/javascript';\n      scriptElt.defer = false;\n      // Note(user): can't use .innerHTML since \"t('<test>')\" will fail and\n      // .text doesn't work in Safari 2.  Therefore we append a text node.\n      scriptElt.appendChild(doc.createTextNode(script));\n      doc.head.appendChild(scriptElt);\n      doc.head.removeChild(scriptElt);\n    }\n  } else {\n    throw new Error('goog.globalEval not available');\n  }\n};\n\n\n/**\n * Indicates whether or not we can call 'eval' directly to eval code in the\n * global scope. Set to a Boolean by the first call to goog.globalEval (which\n * empirically tests whether eval works for globals). @see goog.globalEval\n * @type {?boolean}\n * @private\n */\ngoog.evalWorksForGlobals_ = null;\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n *     var x = goog.getCssName('foo');\n *     var y = goog.getCssName(this.baseClass, 'active');\n *  becomes:\n *     var x = 'foo';\n *     var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n *     the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n  // String() is used for compatibility with compiled soy where the passed\n  // className can be non-string objects.\n  if (String(className).charAt(0) == '.') {\n    throw new Error(\n        'className passed in goog.getCssName must not start with \".\".' +\n        ' You passed: ' + className);\n  }\n\n  var getMapping = function(cssName) {\n    return goog.cssNameMapping_[cssName] || cssName;\n  };\n\n  var renameByParts = function(cssName) {\n    // Remap all the parts individually.\n    var parts = cssName.split('-');\n    var mapped = [];\n    for (var i = 0; i < parts.length; i++) {\n      mapped.push(getMapping(parts[i]));\n    }\n    return mapped.join('-');\n  };\n\n  var rename;\n  if (goog.cssNameMapping_) {\n    rename =\n        goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n  } else {\n    rename = function(a) {\n      return a;\n    };\n  }\n\n  var result =\n      opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n  // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n  // processing of the class name.\n  if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n    return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n  }\n\n  return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n *   \"goog\": \"a\",\n *   \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n *     arguments to goog.getCssName() and values are the corresponding values\n *     that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n *     options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n  goog.cssNameMapping_ = mapping;\n  goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n  // This does not call goog.setCssNameMapping() because the JSCompiler\n  // requires that goog.setCssNameMapping() be called with an object literal.\n  goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\n * @param {{html: boolean}=} opt_options Options:\n *     html: Escape '<' in str to '&lt;'. Used by Closure Templates where the\n *     generated code size and performance is critical which is why {@link\n *     goog.html.SafeHtmlFormatter} is not used. The value must be literal true\n *     or false.\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n  if (opt_options && opt_options.html) {\n    // Note that '&' is not replaced because the translation can contain HTML\n    // entities.\n    str = str.replace(/</g, '&lt;');\n  }\n  if (opt_values) {\n    str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n      return (opt_values != null && key in opt_values) ? opt_values[key] :\n                                                         match;\n    });\n  }\n  return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n  return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n *     public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n *                       Foo.prototype.myMethod);\n *     new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\n *     is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {\n  goog.exportPath_(publicPath, object, opt_objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n  object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n *   ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n *    Function.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n  /** @constructor */\n  function tempCtor() {}\n  tempCtor.prototype = parentCtor.prototype;\n  childCtor.superClass_ = parentCtor.prototype;\n  childCtor.prototype = new tempCtor();\n  /** @override */\n  childCtor.prototype.constructor = childCtor;\n\n  /**\n   * Calls superclass constructor/method.\n   *\n   * This function is only available if you use goog.inherits to\n   * express inheritance relationships between classes.\n   *\n   * NOTE: This is a replacement for goog.base and for superClass_\n   * property defined in childCtor.\n   *\n   * @param {!Object} me Should always be \"this\".\n   * @param {string} methodName The method name to call. Calling\n   *     superclass constructor can be done with the special string\n   *     'constructor'.\n   * @param {...*} var_args The arguments to pass to superclass\n   *     method/constructor.\n   * @return {*} The return value of the superclass method/constructor.\n   */\n  childCtor.base = function(me, methodName, var_args) {\n    // Copying using loop to avoid deop due to passing arguments object to\n    // function. This is faster in many JS engines as of late 2014.\n    var args = new Array(arguments.length - 2);\n    for (var i = 2; i < arguments.length; i++) {\n      args[i - 2] = arguments[i];\n    }\n    return parentCtor.prototype[methodName].apply(me, args);\n  };\n};\n\n\n/**\n * Call up to the superclass.\n *\n * If this is called from a constructor, then this calls the superclass\n * constructor with arguments 1-N.\n *\n * If this is called from a prototype method, then you must pass the name of the\n * method as the second argument to this function. If you do not, you will get a\n * runtime error. This calls the superclass' method with arguments 2-N.\n *\n * This function only works if you use goog.inherits to express inheritance\n * relationships between your classes.\n *\n * This function is a compiler primitive. At compile-time, the compiler will do\n * macro expansion to remove a lot of the extra overhead that this function\n * introduces. The compiler will also enforce a lot of the assumptions that this\n * function makes, and treat it as a compiler error if you break them.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {*=} opt_methodName The method name if calling a super method.\n * @param {...*} var_args The rest of the arguments.\n * @return {*} The return value of the superclass method.\n * @suppress {es5Strict} This method can not be used in strict mode, but\n *     all Closure Library consumers must depend on this file.\n * @deprecated goog.base is not strict mode compatible.  Prefer the static\n *     \"base\" method added to the constructor by goog.inherits\n *     or ES6 classes and the \"super\" keyword.\n */\ngoog.base = function(me, opt_methodName, var_args) {\n  var caller = arguments.callee.caller;\n\n  if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {\n    throw new Error(\n        'arguments.caller not defined.  goog.base() cannot be used ' +\n        'with strict mode code. See ' +\n        'http://www.ecma-international.org/ecma-262/5.1/#sec-C');\n  }\n\n  if (typeof caller.superClass_ !== 'undefined') {\n    // Copying using loop to avoid deop due to passing arguments object to\n    // function. This is faster in many JS engines as of late 2014.\n    var ctorArgs = new Array(arguments.length - 1);\n    for (var i = 1; i < arguments.length; i++) {\n      ctorArgs[i - 1] = arguments[i];\n    }\n    // This is a constructor. Call the superclass constructor.\n    return /** @type {!Function} */ (caller.superClass_)\n        .constructor.apply(me, ctorArgs);\n  }\n\n  if (typeof opt_methodName != 'string' && typeof opt_methodName != 'symbol') {\n    throw new Error(\n        'method names provided to goog.base must be a string or a symbol');\n  }\n\n  // Copying using loop to avoid deop due to passing arguments object to\n  // function. This is faster in many JS engines as of late 2014.\n  var args = new Array(arguments.length - 2);\n  for (var i = 2; i < arguments.length; i++) {\n    args[i - 2] = arguments[i];\n  }\n  var foundCaller = false;\n  for (var proto = me.constructor.prototype; proto;\n       proto = Object.getPrototypeOf(proto)) {\n    if (proto[opt_methodName] === caller) {\n      foundCaller = true;\n    } else if (foundCaller) {\n      return proto[opt_methodName].apply(me, args);\n    }\n  }\n\n  // If we did not find the caller in the prototype chain, then one of two\n  // things happened:\n  // 1) The caller is an instance method.\n  // 2) This method was not called by the right caller.\n  if (me[opt_methodName] === caller) {\n    return me.constructor.prototype[opt_methodName].apply(me, args);\n  } else {\n    throw new Error(\n        'goog.base called from a method of one name ' +\n        'to a method of a different name');\n  }\n};\n\n\n/**\n * Allow for aliasing within scope functions.  This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied.  In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call.  This function can contain aliases\n *     to namespaces (e.g. \"var dom = goog.dom\") or classes\n *     (e.g. \"var Timer = goog.Timer\").\n */\ngoog.scope = function(fn) {\n  if (goog.isInModuleLoader_()) {\n    throw new Error('goog.scope is not supported within a module.');\n  }\n  fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n *    eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n  goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n *   - from the compiler's perspective, the instance returned from the\n *     constructor is sealed (no new properties may be added).  This enables\n *     better checks.\n *   - the compiler will rewrite this definition to a form that is optimal\n *     for type checking and optimization (initially this will be a more\n *     traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n *     An object literal describing\n *     the class.  It may have the following properties:\n *     \"constructor\": the constructor function\n *     \"statics\": an object literal containing methods to add to the constructor\n *        as \"static\" methods or a function that will receive the constructor\n *        function as its only parameter to which static properties can\n *        be added.\n *     all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ES6 class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n  // TODO(johnlenz): consider making the superClass an optional parameter.\n  var constructor = def.constructor;\n  var statics = def.statics;\n  // Wrap the constructor prior to setting up the prototype and static methods.\n  if (!constructor || constructor == Object.prototype.constructor) {\n    constructor = function() {\n      throw new Error(\n          'cannot instantiate an interface (no constructor defined).');\n    };\n  }\n\n  var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n  if (superClass) {\n    goog.inherits(cls, superClass);\n  }\n\n  // Remove all the properties that should not be copied to the prototype.\n  delete def.constructor;\n  delete def.statics;\n\n  goog.defineClass.applyProperties_(cls.prototype, def);\n  if (statics != null) {\n    if (statics instanceof Function) {\n      statics(cls);\n    } else {\n      goog.defineClass.applyProperties_(cls, statics);\n    }\n  }\n\n  return cls;\n};\n\n\n/**\n * @typedef {{\n *   constructor: (!Function|undefined),\n *   statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n *     be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n    goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n  if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n    // Do now wrap the constructor when sealing is disabled. Angular code\n    // depends on this for injection to work properly.\n    return ctr;\n  }\n\n  // Compute whether the constructor is sealable at definition time, rather\n  // than when the instance is being constructed.\n  var superclassSealable = !goog.defineClass.isUnsealable_(superClass);\n\n  /**\n   * @this {Object}\n   * @return {?}\n   */\n  var wrappedCtr = function() {\n    // Don't seal an instance of a subclass when it calls the constructor of\n    // its super class as there is most likely still setup to do.\n    var instance = ctr.apply(this, arguments) || this;\n    instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n    if (this.constructor === wrappedCtr && superclassSealable &&\n        Object.seal instanceof Function) {\n      Object.seal(instance);\n    }\n    return instance;\n  };\n\n  return wrappedCtr;\n};\n\n\n/**\n * @param {Function} ctr The constructor to test.\n * @return {boolean} Whether the constructor has been tagged as unsealable\n *     using goog.tagUnsealableClass.\n * @private\n */\ngoog.defineClass.isUnsealable_ = function(ctr) {\n  return ctr && ctr.prototype &&\n      ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];\n};\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n  'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n  'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n  // TODO(johnlenz): update this to support ES5 getters/setters\n\n  var key;\n  for (key in source) {\n    if (Object.prototype.hasOwnProperty.call(source, key)) {\n      target[key] = source[key];\n    }\n  }\n\n  // For IE the for-in-loop does not contain any properties that are not\n  // enumerable on the prototype object (for example isPrototypeOf from\n  // Object.prototype) and it will also not include 'replace' on objects that\n  // extend String and change 'replace' (not that it is common for anyone to\n  // extend anything except Object).\n  for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n    key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n    if (Object.prototype.hasOwnProperty.call(source, key)) {\n      target[key] = source[key];\n    }\n  }\n};\n\n\n/**\n * Sealing classes breaks the older idiom of assigning properties on the\n * prototype rather than in the constructor. As such, goog.defineClass\n * must not seal subclasses of these old-style classes until they are fixed.\n * Until then, this marks a class as \"broken\", instructing defineClass\n * not to seal subclasses.\n * @param {!Function} ctr The legacy constructor to tag as unsealable.\n */\ngoog.tagUnsealableClass = function(ctr) {\n  if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {\n    ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;\n  }\n};\n\n\n/**\n * Name for unsealable tag property.\n * @const @private {string}\n */\ngoog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';\n\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n  /**\n   * Tries to detect whether is in the context of an HTML document.\n   * @return {boolean} True if it looks like HTML document.\n   * @private\n   */\n  goog.inHtmlDocument_ = function() {\n    /** @type {!Document} */\n    var doc = goog.global.document;\n    return doc != null && 'write' in doc;  // XULDocument misses write.\n  };\n\n\n  /**\n   * We'd like to check for if the document readyState is 'loading'; however\n   * there are bugs on IE 10 and below where the readyState being anything other\n   * than 'complete' is not reliable.\n   * @return {boolean}\n   * @private\n   */\n  goog.isDocumentLoading_ = function() {\n    // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n    // detect those browsers.\n    /** @type {!HTMLDocument} */\n    var doc = goog.global.document;\n    return doc.attachEvent ? doc.readyState != 'complete' :\n                             doc.readyState == 'loading';\n  };\n\n\n  /**\n   * Tries to detect the base path of base.js script that bootstraps Closure.\n   * @private\n   */\n  goog.findBasePath_ = function() {\n    if (goog.global.CLOSURE_BASE_PATH != undefined &&\n        // Anti DOM-clobbering runtime check (b/37736576).\n        typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n      goog.basePath = goog.global.CLOSURE_BASE_PATH;\n      return;\n    } else if (!goog.inHtmlDocument_()) {\n      return;\n    }\n    /** @type {!Document} */\n    var doc = goog.global.document;\n    // If we have a currentScript available, use it exclusively.\n    var currentScript = doc.currentScript;\n    if (currentScript) {\n      var scripts = [currentScript];\n    } else {\n      var scripts = doc.getElementsByTagName('SCRIPT');\n    }\n    // Search backwards since the current script is in almost all cases the one\n    // that has base.js.\n    for (var i = scripts.length - 1; i >= 0; --i) {\n      var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n      var src = script.src;\n      var qmark = src.lastIndexOf('?');\n      var l = qmark == -1 ? src.length : qmark;\n      if (src.substr(l - 7, 7) == 'base.js') {\n        goog.basePath = src.substr(0, l - 7);\n        return;\n      }\n    }\n  };\n\n  goog.findBasePath_();\n\n  /** @struct @constructor @final */\n  goog.Transpiler = function() {\n    /** @private {?Object<string, boolean>} */\n    this.requiresTranspilation_ = null;\n    /** @private {string} */\n    this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\n  };\n\n\n  /**\n   * Returns a newly created map from language mode string to a boolean\n   * indicating whether transpilation should be done for that mode as well as\n   * the highest level language that this environment supports.\n   *\n   * Guaranteed invariant:\n   * For any two modes, l1 and l2 where l2 is a newer mode than l1,\n   * `map[l1] == true` implies that `map[l2] == true`.\n   *\n   * Note this method is extracted and used elsewhere, so it cannot rely on\n   * anything external (it should easily be able to be transformed into a\n   * standalone, top level function).\n   *\n   * @private\n   * @return {{\n   *   target: string,\n   *   map: !Object<string, boolean>\n   * }}\n   */\n  goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\n    var transpilationTarget = 'es3';\n    var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\n    var transpilationRequiredForAllLaterModes = false;\n\n    /**\n     * Adds an entry to requiresTranspliation for the given language mode.\n     *\n     * IMPORTANT: Calls must be made in order from oldest to newest language\n     * mode.\n     * @param {string} modeName\n     * @param {function(): boolean} isSupported Returns true if the JS engine\n     *     supports the given mode.\n     */\n    function addNewerLanguageTranspilationCheck(modeName, isSupported) {\n      if (transpilationRequiredForAllLaterModes) {\n        requiresTranspilation[modeName] = true;\n      } else if (isSupported()) {\n        transpilationTarget = modeName;\n        requiresTranspilation[modeName] = false;\n      } else {\n        requiresTranspilation[modeName] = true;\n        transpilationRequiredForAllLaterModes = true;\n      }\n    }\n\n    /**\n     * Does the given code evaluate without syntax errors and return a truthy\n     * result?\n     */\n    function /** boolean */ evalCheck(/** string */ code) {\n      try {\n        return !!eval(code);\n      } catch (ignored) {\n        return false;\n      }\n    }\n\n    var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n        goog.global.navigator.userAgent :\n        '';\n\n    // Identify ES3-only browsers by their incorrect treatment of commas.\n    addNewerLanguageTranspilationCheck('es5', function() {\n      return evalCheck('[1,].length==1');\n    });\n    addNewerLanguageTranspilationCheck('es6', function() {\n      // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\n      // https://github.com/Microsoft/ChakraCore/issues/1496.\n      var re = /Edge\\/(\\d+)(\\.\\d)*/i;\n      var edgeUserAgent = userAgent.match(re);\n      if (edgeUserAgent) {\n        // The Reflect.construct test below is flaky on Edge. It can sometimes\n        // pass or fail on 40 15.15063, so just exit early for Edge and treat\n        // it as ES5. Until we're on a more up to date version just always use\n        // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\n        return false;\n      }\n      // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\n      //   (a) default params (specifically shadowing locals),\n      //   (b) destructuring, (c) block-scoped functions,\n      //   (d) for-of (const), (e) new.target/Reflect.construct\n      var es6fullTest =\n          'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\n          'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\n          'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\n          'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\n          '==3}';\n\n      return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\n    });\n    // ** and **= are the only new features in 'es7'\n    addNewerLanguageTranspilationCheck('es7', function() {\n      return evalCheck('2 ** 2 == 4');\n    });\n    // async functions are the only new features in 'es8'\n    addNewerLanguageTranspilationCheck('es8', function() {\n      return evalCheck('async () => 1, true');\n    });\n    addNewerLanguageTranspilationCheck('es9', function() {\n      return evalCheck('({...rest} = {}), true');\n    });\n    addNewerLanguageTranspilationCheck('es_next', function() {\n      return false;  // assume it always need to transpile\n    });\n    return {target: transpilationTarget, map: requiresTranspilation};\n  };\n\n\n  /**\n   * Determines whether the given language needs to be transpiled.\n   * @param {string} lang\n   * @param {string|undefined} module\n   * @return {boolean}\n   */\n  goog.Transpiler.prototype.needsTranspile = function(lang, module) {\n    if (goog.TRANSPILE == 'always') {\n      return true;\n    } else if (goog.TRANSPILE == 'never') {\n      return false;\n    } else if (!this.requiresTranspilation_) {\n      var obj = this.createRequiresTranspilation_();\n      this.requiresTranspilation_ = obj.map;\n      this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\n    }\n    if (lang in this.requiresTranspilation_) {\n      if (this.requiresTranspilation_[lang]) {\n        return true;\n      } else if (\n          goog.inHtmlDocument_() && module == 'es6' &&\n          !('noModule' in goog.global.document.createElement('script'))) {\n        return true;\n      } else {\n        return false;\n      }\n    } else {\n      throw new Error('Unknown language mode: ' + lang);\n    }\n  };\n\n\n  /**\n   * Lazily retrieves the transpiler and applies it to the source.\n   * @param {string} code JS code.\n   * @param {string} path Path to the code.\n   * @return {string} The transpiled code.\n   */\n  goog.Transpiler.prototype.transpile = function(code, path) {\n    // TODO(johnplaisted): We should delete goog.transpile_ and just have this\n    // function. But there's some compile error atm where goog.global is being\n    // stripped incorrectly without this.\n    return goog.transpile_(code, path, this.transpilationTarget_);\n  };\n\n\n  /** @private @final {!goog.Transpiler} */\n  goog.transpiler_ = new goog.Transpiler();\n\n  /**\n   * Rewrites closing script tags in input to avoid ending an enclosing script\n   * tag.\n   *\n   * @param {string} str\n   * @return {string}\n   * @private\n   */\n  goog.protectScriptTag_ = function(str) {\n    return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n  };\n\n\n  /**\n   * A debug loader is responsible for downloading and executing javascript\n   * files in an unbundled, uncompiled environment.\n   *\n   * This can be custimized via the setDependencyFactory method, or by\n   * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n   *\n   * @struct @constructor @final @private\n   */\n  goog.DebugLoader_ = function() {\n    /** @private @const {!Object<string, !goog.Dependency>} */\n    this.dependencies_ = {};\n    /** @private @const {!Object<string, string>} */\n    this.idToPath_ = {};\n    /** @private @const {!Object<string, boolean>} */\n    this.written_ = {};\n    /** @private @const {!Array<!goog.Dependency>} */\n    this.loadingDeps_ = [];\n    /** @private {!Array<!goog.Dependency>} */\n    this.depsToLoad_ = [];\n    /** @private {boolean} */\n    this.paused_ = false;\n    /** @private {!goog.DependencyFactory} */\n    this.factory_ = new goog.DependencyFactory(goog.transpiler_);\n    /** @private @const {!Object<string, !Function>} */\n    this.deferredCallbacks_ = {};\n    /** @private @const {!Array<string>} */\n    this.deferredQueue_ = [];\n  };\n\n  /**\n   * @param {!Array<string>} namespaces\n   * @param {function(): undefined} callback Function to call once all the\n   *     namespaces have loaded.\n   */\n  goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n    var cb = callback;\n    function resolve() {\n      if (cb) {\n        goog.global.setTimeout(cb, 0);\n        cb = null;\n      }\n    }\n\n    if (!namespaces.length) {\n      resolve();\n      return;\n    }\n\n    var deps = [];\n    for (var i = 0; i < namespaces.length; i++) {\n      var path = this.getPathFromDeps_(namespaces[i]);\n      if (!path) {\n        throw new Error('Unregonized namespace: ' + namespaces[i]);\n      }\n      deps.push(this.dependencies_[path]);\n    }\n\n    var require = goog.require;\n    var loaded = 0;\n    for (var i = 0; i < namespaces.length; i++) {\n      require(namespaces[i]);\n      deps[i].onLoad(function() {\n        if (++loaded == namespaces.length) {\n          resolve();\n        }\n      });\n    }\n  };\n\n\n  /**\n   * Loads the Closure Dependency file.\n   *\n   * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n   * loaded, setDependencyFactory called, and then this called. i.e. allows\n   * custom loading of the deps file.\n   */\n  goog.DebugLoader_.prototype.loadClosureDeps = function() {\n    // Circumvent addDependency, which would try to transpile deps.js if\n    // transpile is set to always.\n    var relPath = 'deps.js';\n    this.depsToLoad_.push(this.factory_.createDependency(\n        goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\n        false));\n    this.loadDeps_();\n  };\n\n\n  /**\n   * Notifies the debug loader when a dependency has been requested.\n   *\n   * @param {string} absPathOrId Path of the dependency or goog id.\n   * @param {boolean=} opt_force\n   */\n  goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n    var path = this.getPathFromDeps_(absPathOrId);\n    if (path &&\n        (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n      var callback = this.deferredCallbacks_[path];\n      if (callback) {\n        delete this.deferredCallbacks_[path];\n        callback();\n      }\n    }\n  };\n\n\n  /**\n   * Sets the dependency factory, which can be used to create custom\n   * goog.Dependency implementations to control how dependencies are loaded.\n   *\n   * @param {!goog.DependencyFactory} factory\n   */\n  goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n    this.factory_ = factory;\n  };\n\n\n  /**\n   * Travserses the dependency graph and queues the given dependency, and all of\n   * its transitive dependencies, for loading and then starts loading if not\n   * paused.\n   *\n   * @param {string} namespace\n   * @private\n   */\n  goog.DebugLoader_.prototype.load_ = function(namespace) {\n    if (!this.getPathFromDeps_(namespace)) {\n      var errorMessage = 'goog.require could not find: ' + namespace;\n\n      goog.logToConsole_(errorMessage);\n      throw Error(errorMessage);\n    } else {\n      var loader = this;\n\n      var deps = [];\n\n      /** @param {string} namespace */\n      var visit = function(namespace) {\n        var path = loader.getPathFromDeps_(namespace);\n\n        if (!path) {\n          throw new Error('Bad dependency path or symbol: ' + namespace);\n        }\n\n        if (loader.written_[path]) {\n          return;\n        }\n\n        loader.written_[path] = true;\n\n        var dep = loader.dependencies_[path];\n        for (var i = 0; i < dep.requires.length; i++) {\n          if (!goog.isProvided_(dep.requires[i])) {\n            visit(dep.requires[i]);\n          }\n        }\n\n        deps.push(dep);\n      };\n\n      visit(namespace);\n\n      var wasLoading = !!this.depsToLoad_.length;\n      this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n      if (!this.paused_ && !wasLoading) {\n        this.loadDeps_();\n      }\n    }\n  };\n\n\n  /**\n   * Loads any queued dependencies until they are all loaded or paused.\n   *\n   * @private\n   */\n  goog.DebugLoader_.prototype.loadDeps_ = function() {\n    var loader = this;\n    var paused = this.paused_;\n\n    while (this.depsToLoad_.length && !paused) {\n      (function() {\n        var loadCallDone = false;\n        var dep = loader.depsToLoad_.shift();\n\n        var loaded = false;\n        loader.loading_(dep);\n\n        var controller = {\n          pause: function() {\n            if (loadCallDone) {\n              throw new Error('Cannot call pause after the call to load.');\n            } else {\n              paused = true;\n            }\n          },\n          resume: function() {\n            if (loadCallDone) {\n              loader.resume_();\n            } else {\n              // Some dep called pause and then resume in the same load call.\n              // Just keep running this same loop.\n              paused = false;\n            }\n          },\n          loaded: function() {\n            if (loaded) {\n              throw new Error('Double call to loaded.');\n            }\n\n            loaded = true;\n            loader.loaded_(dep);\n          },\n          pending: function() {\n            // Defensive copy.\n            var pending = [];\n            for (var i = 0; i < loader.loadingDeps_.length; i++) {\n              pending.push(loader.loadingDeps_[i]);\n            }\n            return pending;\n          },\n          /**\n           * @param {goog.ModuleType} type\n           */\n          setModuleState: function(type) {\n            goog.moduleLoaderState_ = {\n              type: type,\n              moduleName: '',\n              declareLegacyNamespace: false\n            };\n          },\n          /** @type {function(string, string, string=)} */\n          registerEs6ModuleExports: function(\n              path, exports, opt_closureNamespace) {\n            if (opt_closureNamespace) {\n              goog.loadedModules_[opt_closureNamespace] = {\n                exports: exports,\n                type: goog.ModuleType.ES6,\n                moduleId: opt_closureNamespace || ''\n              };\n            }\n          },\n          /** @type {function(string, ?)} */\n          registerGoogModuleExports: function(moduleId, exports) {\n            goog.loadedModules_[moduleId] = {\n              exports: exports,\n              type: goog.ModuleType.GOOG,\n              moduleId: moduleId\n            };\n          },\n          clearModuleState: function() {\n            goog.moduleLoaderState_ = null;\n          },\n          defer: function(callback) {\n            if (loadCallDone) {\n              throw new Error(\n                  'Cannot register with defer after the call to load.');\n            }\n            loader.defer_(dep, callback);\n          },\n          areDepsLoaded: function() {\n            return loader.areDepsLoaded_(dep.requires);\n          }\n        };\n\n        try {\n          dep.load(controller);\n        } finally {\n          loadCallDone = true;\n        }\n      })();\n    }\n\n    if (paused) {\n      this.pause_();\n    }\n  };\n\n\n  /** @private */\n  goog.DebugLoader_.prototype.pause_ = function() {\n    this.paused_ = true;\n  };\n\n\n  /** @private */\n  goog.DebugLoader_.prototype.resume_ = function() {\n    if (this.paused_) {\n      this.paused_ = false;\n      this.loadDeps_();\n    }\n  };\n\n\n  /**\n   * Marks the given dependency as loading (load has been called but it has not\n   * yet marked itself as finished). Useful for dependencies that want to know\n   * what else is loading. Example: goog.modules cannot eval if there are\n   * loading dependencies.\n   *\n   * @param {!goog.Dependency} dep\n   * @private\n   */\n  goog.DebugLoader_.prototype.loading_ = function(dep) {\n    this.loadingDeps_.push(dep);\n  };\n\n\n  /**\n   * Marks the given dependency as having finished loading and being available\n   * for require.\n   *\n   * @param {!goog.Dependency} dep\n   * @private\n   */\n  goog.DebugLoader_.prototype.loaded_ = function(dep) {\n    for (var i = 0; i < this.loadingDeps_.length; i++) {\n      if (this.loadingDeps_[i] == dep) {\n        this.loadingDeps_.splice(i, 1);\n        break;\n      }\n    }\n\n    for (var i = 0; i < this.deferredQueue_.length; i++) {\n      if (this.deferredQueue_[i] == dep.path) {\n        this.deferredQueue_.splice(i, 1);\n        break;\n      }\n    }\n\n    if (this.loadingDeps_.length == this.deferredQueue_.length &&\n        !this.depsToLoad_.length) {\n      // Something has asked to load these, but they may not be directly\n      // required again later, so load them now that we know we're done loading\n      // everything else. e.g. a goog module entry point.\n      while (this.deferredQueue_.length) {\n        this.requested(this.deferredQueue_.shift(), true);\n      }\n    }\n\n    dep.loaded();\n  };\n\n\n  /**\n   * @param {!Array<string>} pathsOrIds\n   * @return {boolean}\n   * @private\n   */\n  goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n    for (var i = 0; i < pathsOrIds.length; i++) {\n      var path = this.getPathFromDeps_(pathsOrIds[i]);\n      if (!path ||\n          (!(path in this.deferredCallbacks_) &&\n           !goog.isProvided_(pathsOrIds[i]))) {\n        return false;\n      }\n    }\n\n    return true;\n  };\n\n\n  /**\n   * @param {string} absPathOrId\n   * @return {?string}\n   * @private\n   */\n  goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n    if (absPathOrId in this.idToPath_) {\n      return this.idToPath_[absPathOrId];\n    } else if (absPathOrId in this.dependencies_) {\n      return absPathOrId;\n    } else {\n      return null;\n    }\n  };\n\n\n  /**\n   * @param {!goog.Dependency} dependency\n   * @param {!Function} callback\n   * @private\n   */\n  goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n    this.deferredCallbacks_[dependency.path] = callback;\n    this.deferredQueue_.push(dependency.path);\n  };\n\n\n  /**\n   * Interface for goog.Dependency implementations to have some control over\n   * loading of dependencies.\n   *\n   * @record\n   */\n  goog.LoadController = function() {};\n\n\n  /**\n   * Tells the controller to halt loading of more dependencies.\n   */\n  goog.LoadController.prototype.pause = function() {};\n\n\n  /**\n   * Tells the controller to resume loading of more dependencies if paused.\n   */\n  goog.LoadController.prototype.resume = function() {};\n\n\n  /**\n   * Tells the controller that this dependency has finished loading.\n   *\n   * This causes this to be removed from pending() and any load callbacks to\n   * fire.\n   */\n  goog.LoadController.prototype.loaded = function() {};\n\n\n  /**\n   * List of dependencies on which load has been called but which have not\n   * called loaded on their controller. This includes the current dependency.\n   *\n   * @return {!Array<!goog.Dependency>}\n   */\n  goog.LoadController.prototype.pending = function() {};\n\n\n  /**\n   * Registers an object as an ES6 module's exports so that goog.modules may\n   * require it by path.\n   *\n   * @param {string} path Full path of the module.\n   * @param {?} exports\n   * @param {string=} opt_closureNamespace Closure namespace to associate with\n   *     this module.\n   */\n  goog.LoadController.prototype.registerEs6ModuleExports = function(\n      path, exports, opt_closureNamespace) {};\n\n\n  /**\n   * Sets the current module state.\n   *\n   * @param {goog.ModuleType} type Type of module.\n   */\n  goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n  /**\n   * Clears the current module state.\n   */\n  goog.LoadController.prototype.clearModuleState = function() {};\n\n\n  /**\n   * Registers a callback to call once the dependency is actually requested\n   * via goog.require + all of the immediate dependencies have been loaded or\n   * all other files have been loaded. Allows for lazy loading until\n   * require'd without pausing dependency loading, which is needed on old IE.\n   *\n   * @param {!Function} callback\n   */\n  goog.LoadController.prototype.defer = function(callback) {};\n\n\n  /**\n   * @return {boolean}\n   */\n  goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n  /**\n   * Basic super class for all dependencies Closure Library can load.\n   *\n   * This default implementation is designed to load untranspiled, non-module\n   * scripts in a web broswer.\n   *\n   * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\n   * For goog.modules see {@see goog.GoogModuleDependency}.\n   * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n   *\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides goog.provided or goog.module symbols\n   *     in this file.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @struct @constructor\n   */\n  goog.Dependency = function(\n      path, relativePath, provides, requires, loadFlags) {\n    /** @const */\n    this.path = path;\n    /** @const */\n    this.relativePath = relativePath;\n    /** @const */\n    this.provides = provides;\n    /** @const */\n    this.requires = requires;\n    /** @const */\n    this.loadFlags = loadFlags;\n    /** @private {boolean} */\n    this.loaded_ = false;\n    /** @private {!Array<function()>} */\n    this.loadCallbacks_ = [];\n  };\n\n\n  /**\n   * @return {string} The pathname part of this dependency's path if it is a\n   *     URI.\n   */\n  goog.Dependency.prototype.getPathName = function() {\n    var pathName = this.path;\n    var protocolIndex = pathName.indexOf('://');\n    if (protocolIndex >= 0) {\n      pathName = pathName.substring(protocolIndex + 3);\n      var slashIndex = pathName.indexOf('/');\n      if (slashIndex >= 0) {\n        pathName = pathName.substring(slashIndex + 1);\n      }\n    }\n    return pathName;\n  };\n\n\n  /**\n   * @param {function()} callback Callback to fire as soon as this has loaded.\n   * @final\n   */\n  goog.Dependency.prototype.onLoad = function(callback) {\n    if (this.loaded_) {\n      callback();\n    } else {\n      this.loadCallbacks_.push(callback);\n    }\n  };\n\n\n  /**\n   * Marks this dependency as loaded and fires any callbacks registered with\n   * onLoad.\n   * @final\n   */\n  goog.Dependency.prototype.loaded = function() {\n    this.loaded_ = true;\n    var callbacks = this.loadCallbacks_;\n    this.loadCallbacks_ = [];\n    for (var i = 0; i < callbacks.length; i++) {\n      callbacks[i]();\n    }\n  };\n\n\n  /**\n   * Whether or not document.written / appended script tags should be deferred.\n   *\n   * @private {boolean}\n   */\n  goog.Dependency.defer_ = false;\n\n\n  /**\n   * Map of script ready / state change callbacks. Old IE cannot handle putting\n   * these properties on goog.global.\n   *\n   * @private @const {!Object<string, function(?):undefined>}\n   */\n  goog.Dependency.callbackMap_ = {};\n\n\n  /**\n   * @param {function(...?):?} callback\n   * @return {string}\n   * @private\n   */\n  goog.Dependency.registerCallback_ = function(callback) {\n    var key = Math.random().toString(32);\n    goog.Dependency.callbackMap_[key] = callback;\n    return key;\n  };\n\n\n  /**\n   * @param {string} key\n   * @private\n   */\n  goog.Dependency.unregisterCallback_ = function(key) {\n    delete goog.Dependency.callbackMap_[key];\n  };\n\n\n  /**\n   * @param {string} key\n   * @param {...?} var_args\n   * @private\n   * @suppress {unusedPrivateMembers}\n   */\n  goog.Dependency.callback_ = function(key, var_args) {\n    if (key in goog.Dependency.callbackMap_) {\n      var callback = goog.Dependency.callbackMap_[key];\n      var args = [];\n      for (var i = 1; i < arguments.length; i++) {\n        args.push(arguments[i]);\n      }\n      callback.apply(undefined, args);\n    } else {\n      var errorMessage = 'Callback key ' + key +\n          ' does not exist (was base.js loaded more than once?).';\n      throw Error(errorMessage);\n    }\n  };\n\n\n  /**\n   * Starts loading this dependency. This dependency can pause loading if it\n   * needs to and resume it later via the controller interface.\n   *\n   * When this is loaded it should call controller.loaded(). Note that this will\n   * end up calling the loaded method of this dependency; there is no need to\n   * call it explicitly.\n   *\n   * @param {!goog.LoadController} controller\n   */\n  goog.Dependency.prototype.load = function(controller) {\n    if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n      if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n        controller.loaded();\n      } else {\n        controller.pause();\n      }\n      return;\n    }\n\n    if (!goog.inHtmlDocument_()) {\n      goog.logToConsole_(\n          'Cannot use default debug loader outside of HTML documents.');\n      if (this.relativePath == 'deps.js') {\n        // Some old code is relying on base.js auto loading deps.js failing with\n        // no error before later setting CLOSURE_IMPORT_SCRIPT.\n        // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n        // CLOSURE_NO_DEPS set to true.\n        goog.logToConsole_(\n            'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n            'or setting CLOSURE_NO_DEPS to true.');\n        controller.loaded();\n      } else {\n        controller.pause();\n      }\n      return;\n    }\n\n    /** @type {!HTMLDocument} */\n    var doc = goog.global.document;\n\n    // If the user tries to require a new symbol after document load,\n    // something has gone terribly wrong. Doing a document.write would\n    // wipe out the page. This does not apply to the CSP-compliant method\n    // of writing script tags.\n    if (doc.readyState == 'complete' &&\n        !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n      // Certain test frameworks load base.js multiple times, which tries\n      // to write deps.js each time. If that happens, just fail silently.\n      // These frameworks wipe the page between each load of base.js, so this\n      // is OK.\n      var isDeps = /\\bdeps.js$/.test(this.path);\n      if (isDeps) {\n        controller.loaded();\n        return;\n      } else {\n        throw Error('Cannot write \"' + this.path + '\" after document load');\n      }\n    }\n\n    if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n        goog.isDocumentLoading_()) {\n      var key = goog.Dependency.registerCallback_(function(script) {\n        if (!goog.DebugLoader_.IS_OLD_IE_ || script.readyState == 'complete') {\n          goog.Dependency.unregisterCallback_(key);\n          controller.loaded();\n        }\n      });\n      var nonceAttr = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ?\n          ' nonce=\"' + goog.getScriptNonce() + '\"' :\n          '';\n      var event =\n          goog.DebugLoader_.IS_OLD_IE_ ? 'onreadystatechange' : 'onload';\n      var defer = goog.Dependency.defer_ ? 'defer' : '';\n      var script = '<script src=\"' + this.path + '\" ' + event +\n          '=\"goog.Dependency.callback_(\\'' + key +\n          '\\', this)\" type=\"text/javascript\" ' + defer + nonceAttr + '><' +\n          '/script>';\n      doc.write(\n          goog.TRUSTED_TYPES_POLICY_ ?\n              goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n              script);\n    } else {\n      var scriptEl =\n          /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n      scriptEl.defer = goog.Dependency.defer_;\n      scriptEl.async = false;\n      scriptEl.type = 'text/javascript';\n\n      // If CSP nonces are used, propagate them to dynamically created scripts.\n      // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n      var nonce = goog.getScriptNonce();\n      if (nonce) {\n        scriptEl.setAttribute('nonce', nonce);\n      }\n\n      if (goog.DebugLoader_.IS_OLD_IE_) {\n        // Execution order is not guaranteed on old IE, halt loading and write\n        // these scripts one at a time, after each loads.\n        controller.pause();\n        scriptEl.onreadystatechange = function() {\n          if (scriptEl.readyState == 'loaded' ||\n              scriptEl.readyState == 'complete') {\n            controller.loaded();\n            controller.resume();\n          }\n        };\n      } else {\n        scriptEl.onload = function() {\n          scriptEl.onload = null;\n          controller.loaded();\n        };\n      }\n\n      scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n          goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n          this.path;\n      doc.head.appendChild(scriptEl);\n    }\n  };\n\n\n  /**\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides Should be an empty array.\n   *     TODO(johnplaisted) add support for adding closure namespaces to ES6\n   *     modules for interop purposes.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @struct @constructor\n   * @extends {goog.Dependency}\n   */\n  goog.Es6ModuleDependency = function(\n      path, relativePath, provides, requires, loadFlags) {\n    goog.Es6ModuleDependency.base(\n        this, 'constructor', path, relativePath, provides, requires, loadFlags);\n  };\n  goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n  /** @override */\n  goog.Es6ModuleDependency.prototype.load = function(controller) {\n    if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n      if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n        controller.loaded();\n      } else {\n        controller.pause();\n      }\n      return;\n    }\n\n    if (!goog.inHtmlDocument_()) {\n      goog.logToConsole_(\n          'Cannot use default debug loader outside of HTML documents.');\n      controller.pause();\n      return;\n    }\n\n    /** @type {!HTMLDocument} */\n    var doc = goog.global.document;\n\n    var dep = this;\n\n    // TODO(johnplaisted): Does document.writing really speed up anything? Any\n    // difference between this and just waiting for interactive mode and then\n    // appending?\n    function write(src, contents) {\n      if (contents) {\n        var script = '<script type=\"module\" crossorigin>' + contents + '</' +\n            'script>';\n        doc.write(\n            goog.TRUSTED_TYPES_POLICY_ ?\n                goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n                script);\n      } else {\n        var script = '<script type=\"module\" crossorigin src=\"' + src + '\"></' +\n            'script>';\n        doc.write(\n            goog.TRUSTED_TYPES_POLICY_ ?\n                goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n                script);\n      }\n    }\n\n    function append(src, contents) {\n      var scriptEl =\n          /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n      scriptEl.defer = true;\n      scriptEl.async = false;\n      scriptEl.type = 'module';\n      scriptEl.setAttribute('crossorigin', true);\n\n      // If CSP nonces are used, propagate them to dynamically created scripts.\n      // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n      var nonce = goog.getScriptNonce();\n      if (nonce) {\n        scriptEl.setAttribute('nonce', nonce);\n      }\n\n      if (contents) {\n        scriptEl.textContent = goog.TRUSTED_TYPES_POLICY_ ?\n            goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n            contents;\n      } else {\n        scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n            goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n            src;\n      }\n\n      doc.head.appendChild(scriptEl);\n    }\n\n    var create;\n\n    if (goog.isDocumentLoading_()) {\n      create = write;\n      // We can ONLY call document.write if we are guaranteed that any\n      // non-module script tags document.written after this are deferred.\n      // Small optimization, in theory document.writing is faster.\n      goog.Dependency.defer_ = true;\n    } else {\n      create = append;\n    }\n\n    // Write 4 separate tags here:\n    // 1) Sets the module state at the correct time (just before execution).\n    // 2) A src node for this, which just hopefully lets the browser load it a\n    //    little early (no need to parse #3).\n    // 3) Import the module and register it.\n    // 4) Clear the module state at the correct time. Guaranteed to run even\n    //    if there is an error in the module (#3 will not run if there is an\n    //    error in the module).\n    var beforeKey = goog.Dependency.registerCallback_(function() {\n      goog.Dependency.unregisterCallback_(beforeKey);\n      controller.setModuleState(goog.ModuleType.ES6);\n    });\n    create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n    // TODO(johnplaisted): Does this really speed up anything?\n    create(this.path, undefined);\n\n    var registerKey = goog.Dependency.registerCallback_(function(exports) {\n      goog.Dependency.unregisterCallback_(registerKey);\n      controller.registerEs6ModuleExports(\n          dep.path, exports, goog.moduleLoaderState_.moduleName);\n    });\n    create(\n        undefined,\n        'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n            registerKey + '\", m)');\n\n    var afterKey = goog.Dependency.registerCallback_(function() {\n      goog.Dependency.unregisterCallback_(afterKey);\n      controller.clearModuleState();\n      controller.loaded();\n    });\n    create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n  };\n\n\n  /**\n   * Superclass of any dependency that needs to be loaded into memory,\n   * transformed, and then eval'd (goog.modules and transpiled files).\n   *\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides goog.provided or goog.module symbols\n   *     in this file.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @struct @constructor @abstract\n   * @extends {goog.Dependency}\n   */\n  goog.TransformedDependency = function(\n      path, relativePath, provides, requires, loadFlags) {\n    goog.TransformedDependency.base(\n        this, 'constructor', path, relativePath, provides, requires, loadFlags);\n    /** @private {?string} */\n    this.contents_ = null;\n\n    /**\n     * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n     * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n     * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n     * it does then no other ES6 modules will load after).\n     *\n     * tl;dr we lazy load due to bugs on older browsers and eager load due to\n     * bugs on newer ones.\n     *\n     * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n     *\n     * @private @const {boolean}\n     */\n    this.lazyFetch_ = !goog.inHtmlDocument_() ||\n        !('noModule' in goog.global.document.createElement('script'));\n  };\n  goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n  /** @override */\n  goog.TransformedDependency.prototype.load = function(controller) {\n    var dep = this;\n\n    function fetch() {\n      dep.contents_ = goog.loadFileSync_(dep.path);\n\n      if (dep.contents_) {\n        dep.contents_ = dep.transform(dep.contents_);\n        if (dep.contents_) {\n          dep.contents_ += '\\n//# sourceURL=' + dep.path;\n        }\n      }\n    }\n\n    if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n      fetch();\n      if (this.contents_ &&\n          goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n        this.contents_ = null;\n        controller.loaded();\n      } else {\n        controller.pause();\n      }\n      return;\n    }\n\n\n    var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n    if (!this.lazyFetch_) {\n      fetch();\n    }\n\n    function load() {\n      if (dep.lazyFetch_) {\n        fetch();\n      }\n\n      if (!dep.contents_) {\n        // loadFileSync_ or transform are responsible. Assume they logged an\n        // error.\n        return;\n      }\n\n      if (isEs6) {\n        controller.setModuleState(goog.ModuleType.ES6);\n      }\n\n      var namespace;\n\n      try {\n        var contents = dep.contents_;\n        dep.contents_ = null;\n        goog.globalEval(contents);\n        if (isEs6) {\n          namespace = goog.moduleLoaderState_.moduleName;\n        }\n      } finally {\n        if (isEs6) {\n          controller.clearModuleState();\n        }\n      }\n\n      if (isEs6) {\n        // Due to circular dependencies this may not be available for require\n        // right now.\n        goog.global['$jscomp']['require']['ensure'](\n            [dep.getPathName()], function() {\n              controller.registerEs6ModuleExports(\n                  dep.path,\n                  goog.global['$jscomp']['require'](dep.getPathName()),\n                  namespace);\n            });\n      }\n\n      controller.loaded();\n    }\n\n    // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n    // events. If we fetched now and then document.write'd the contents the\n    // document.write would be an eval and would execute too soon! Instead write\n    // a script tag to fetch and eval synchronously at the correct time.\n    function fetchInOwnScriptThenLoad() {\n      /** @type {!HTMLDocument} */\n      var doc = goog.global.document;\n\n      var key = goog.Dependency.registerCallback_(function() {\n        goog.Dependency.unregisterCallback_(key);\n        load();\n      });\n\n      var script = '<script type=\"text/javascript\">' +\n          goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n          '</' +\n          'script>';\n      doc.write(\n          goog.TRUSTED_TYPES_POLICY_ ?\n              goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n              script);\n    }\n\n    // If one thing is pending it is this.\n    var anythingElsePending = controller.pending().length > 1;\n\n    // If anything else is loading we need to lazy load due to bugs in old IE.\n    // Specifically script tags with src and script tags with contents could\n    // execute out of order if document.write is used, so we cannot use\n    // document.write. Do not pause here; it breaks old IE as well.\n    var useOldIeWorkAround =\n        anythingElsePending && goog.DebugLoader_.IS_OLD_IE_;\n\n    // Additionally if we are meant to defer scripts but the page is still\n    // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n    // meant to defer and anything else is pending then defer (those may be\n    // scripts that did not need transformation and are just script tags with\n    // defer set to true, and we need to evaluate after that deferred script).\n    var needsAsyncLoading = goog.Dependency.defer_ &&\n        (anythingElsePending || goog.isDocumentLoading_());\n\n    if (useOldIeWorkAround || needsAsyncLoading) {\n      // Note that we only defer when we have to rather than 100% of the time.\n      // Always defering would work, but then in theory the order of\n      // goog.require calls would then matter. We want to enforce that most of\n      // the time the order of the require calls does not matter.\n      controller.defer(function() {\n        load();\n      });\n      return;\n    }\n    // TODO(johnplaisted): Externs are missing onreadystatechange for\n    // HTMLDocument.\n    /** @type {?} */\n    var doc = goog.global.document;\n\n    var isInternetExplorer =\n        goog.inHtmlDocument_() && 'ActiveXObject' in goog.global;\n\n    // Don't delay in any version of IE. There's bug around this that will\n    // cause out of order script execution. This means that on older IE ES6\n    // modules will load too early (while the document is still loading + the\n    // dom is not available). The other option is to load too late (when the\n    // document is complete and the onload even will never fire). This seems\n    // to be the lesser of two evils as scripts already act like the former.\n    if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n        !isInternetExplorer) {\n      goog.Dependency.defer_ = true;\n      // Transpiled ES6 modules still need to load like regular ES6 modules,\n      // aka only after the document is interactive.\n      controller.pause();\n      var oldCallback = doc.onreadystatechange;\n      doc.onreadystatechange = function() {\n        if (doc.readyState == 'interactive') {\n          doc.onreadystatechange = oldCallback;\n          load();\n          controller.resume();\n        }\n        if (goog.isFunction(oldCallback)) {\n          oldCallback.apply(undefined, arguments);\n        }\n      };\n    } else {\n      // Always eval on old IE.\n      if (goog.DebugLoader_.IS_OLD_IE_ || !goog.inHtmlDocument_() ||\n          !goog.isDocumentLoading_()) {\n        load();\n      } else {\n        fetchInOwnScriptThenLoad();\n      }\n    }\n  };\n\n\n  /**\n   * @param {string} contents\n   * @return {string}\n   * @abstract\n   */\n  goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n  /**\n   * Any non-goog.module dependency which needs to be transpiled before eval.\n   *\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides goog.provided or goog.module symbols\n   *     in this file.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @param {!goog.Transpiler} transpiler\n   * @struct @constructor\n   * @extends {goog.TransformedDependency}\n   */\n  goog.TranspiledDependency = function(\n      path, relativePath, provides, requires, loadFlags, transpiler) {\n    goog.TranspiledDependency.base(\n        this, 'constructor', path, relativePath, provides, requires, loadFlags);\n    /** @protected @const*/\n    this.transpiler = transpiler;\n  };\n  goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\n\n\n  /** @override */\n  goog.TranspiledDependency.prototype.transform = function(contents) {\n    // Transpile with the pathname so that ES6 modules are domain agnostic.\n    return this.transpiler.transpile(contents, this.getPathName());\n  };\n\n\n  /**\n   * An ES6 module dependency that was transpiled to a jscomp module outside\n   * of the debug loader, e.g. server side.\n   *\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides goog.provided or goog.module symbols\n   *     in this file.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @struct @constructor\n   * @extends {goog.TransformedDependency}\n   */\n  goog.PreTranspiledEs6ModuleDependency = function(\n      path, relativePath, provides, requires, loadFlags) {\n    goog.PreTranspiledEs6ModuleDependency.base(\n        this, 'constructor', path, relativePath, provides, requires, loadFlags);\n  };\n  goog.inherits(\n      goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n  /** @override */\n  goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n      contents) {\n    return contents;\n  };\n\n\n  /**\n   * A goog.module, transpiled or not. Will always perform some minimal\n   * transformation even when not transpiled to wrap in a goog.loadModule\n   * statement.\n   *\n   * @param {string} path Absolute path of this script.\n   * @param {string} relativePath Path of this script relative to goog.basePath.\n   * @param {!Array<string>} provides goog.provided or goog.module symbols\n   *     in this file.\n   * @param {!Array<string>} requires goog symbols or relative paths to Closure\n   *     this depends on.\n   * @param {!Object<string, string>} loadFlags\n   * @param {boolean} needsTranspile\n   * @param {!goog.Transpiler} transpiler\n   * @struct @constructor\n   * @extends {goog.TransformedDependency}\n   */\n  goog.GoogModuleDependency = function(\n      path, relativePath, provides, requires, loadFlags, needsTranspile,\n      transpiler) {\n    goog.GoogModuleDependency.base(\n        this, 'constructor', path, relativePath, provides, requires, loadFlags);\n    /** @private @const */\n    this.needsTranspile_ = needsTranspile;\n    /** @private @const */\n    this.transpiler_ = transpiler;\n  };\n  goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n  /** @override */\n  goog.GoogModuleDependency.prototype.transform = function(contents) {\n    if (this.needsTranspile_) {\n      contents = this.transpiler_.transpile(contents, this.getPathName());\n    }\n\n    if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n      return '' +\n          'goog.loadModule(function(exports) {' +\n          '\"use strict\";' + contents +\n          '\\n' +  // terminate any trailing single line comment.\n          ';return exports' +\n          '});' +\n          '\\n//# sourceURL=' + this.path + '\\n';\n    } else {\n      return '' +\n          'goog.loadModule(' +\n          goog.global.JSON.stringify(\n              contents + '\\n//# sourceURL=' + this.path + '\\n') +\n          ');';\n    }\n  };\n\n\n  /**\n   * Whether the browser is IE9 or earlier, which needs special handling\n   * for deferred modules.\n   * @const @private {boolean}\n   */\n  goog.DebugLoader_.IS_OLD_IE_ = !!(\n      !goog.global.atob && goog.global.document && goog.global.document['all']);\n\n\n  /**\n   * @param {string} relPath\n   * @param {!Array<string>|undefined} provides\n   * @param {!Array<string>} requires\n   * @param {boolean|!Object<string>=} opt_loadFlags\n   * @see goog.addDependency\n   */\n  goog.DebugLoader_.prototype.addDependency = function(\n      relPath, provides, requires, opt_loadFlags) {\n    provides = provides || [];\n    relPath = relPath.replace(/\\\\/g, '/');\n    var path = goog.normalizePath_(goog.basePath + relPath);\n    if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n      opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n    }\n    var dep = this.factory_.createDependency(\n        path, relPath, provides, requires, opt_loadFlags,\n        goog.transpiler_.needsTranspile(\n            opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\n    this.dependencies_[path] = dep;\n    for (var i = 0; i < provides.length; i++) {\n      this.idToPath_[provides[i]] = path;\n    }\n    this.idToPath_[relPath] = path;\n  };\n\n\n  /**\n   * Creates goog.Dependency instances for the debug loader to load.\n   *\n   * Should be overridden to have the debug loader use custom subclasses of\n   * goog.Dependency.\n   *\n   * @param {!goog.Transpiler} transpiler\n   * @struct @constructor\n   */\n  goog.DependencyFactory = function(transpiler) {\n    /** @protected @const */\n    this.transpiler = transpiler;\n  };\n\n\n  /**\n   * @param {string} path Absolute path of the file.\n   * @param {string} relativePath Path relative to closure’s base.js.\n   * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n   * @param {!Array<string>} requires Array of required goog.provide/module /\n   *     relative ES6 module paths.\n   * @param {!Object<string, string>} loadFlags\n   * @param {boolean} needsTranspile True if the file needs to be transpiled\n   *     per the goog.Transpiler.\n   * @return {!goog.Dependency}\n   */\n  goog.DependencyFactory.prototype.createDependency = function(\n      path, relativePath, provides, requires, loadFlags, needsTranspile) {\n\n    if (loadFlags['module'] == goog.ModuleType.GOOG) {\n      return new goog.GoogModuleDependency(\n          path, relativePath, provides, requires, loadFlags, needsTranspile,\n          this.transpiler);\n    } else if (needsTranspile) {\n      return new goog.TranspiledDependency(\n          path, relativePath, provides, requires, loadFlags, this.transpiler);\n    } else {\n      if (loadFlags['module'] == goog.ModuleType.ES6) {\n        if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\n          return new goog.PreTranspiledEs6ModuleDependency(\n              path, relativePath, provides, requires, loadFlags);\n        } else {\n          return new goog.Es6ModuleDependency(\n              path, relativePath, provides, requires, loadFlags);\n        }\n      } else {\n        return new goog.Dependency(\n            path, relativePath, provides, requires, loadFlags);\n      }\n    }\n  };\n\n\n  /** @private @const */\n  goog.debugLoader_ = new goog.DebugLoader_();\n\n\n  /**\n   * Loads the Closure Dependency file.\n   *\n   * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n   * loaded, setDependencyFactory called, and then this called. i.e. allows\n   * custom loading of the deps file.\n   */\n  goog.loadClosureDeps = function() {\n    goog.debugLoader_.loadClosureDeps();\n  };\n\n\n  /**\n   * Sets the dependency factory, which can be used to create custom\n   * goog.Dependency implementations to control how dependencies are loaded.\n   *\n   * Note: if you wish to call this function and provide your own implemnetation\n   * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n   * file and all of its goog.addDependency calls will use the default factory.\n   * You can call goog.loadClosureDeps to load the Closure dependency file\n   * later, after your factory is injected.\n   *\n   * @param {!goog.DependencyFactory} factory\n   */\n  goog.setDependencyFactory = function(factory) {\n    goog.debugLoader_.setDependencyFactory(factory);\n  };\n\n\n  if (!goog.global.CLOSURE_NO_DEPS) {\n    goog.debugLoader_.loadClosureDeps();\n  }\n\n\n  /**\n   * Bootstraps the given namespaces and calls the callback once they are\n   * available either via goog.require. This is a replacement for using\n   * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n   * in an HTML file would guarantee that the require'd namespace was available\n   * in the next immediate script tag. With ES6 modules this no longer a\n   * guarantee.\n   *\n   * @param {!Array<string>} namespaces\n   * @param {function(): ?} callback Function to call once all the namespaces\n   *     have loaded. Always called asynchronously.\n   */\n  goog.bootstrap = function(namespaces, callback) {\n    goog.debugLoader_.bootstrap(namespaces, callback);\n  };\n}\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n    goog.define('goog.TRUSTED_TYPES_POLICY_NAME', '');\n\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n  return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call TrustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n  var policy = null;\n  // TODO(koto): Remove window.TrustedTypes variant when the newer API ships.\n  var policyFactory = goog.global.trustedTypes || goog.global.TrustedTypes;\n  if (!policyFactory || !policyFactory.createPolicy) {\n    return policy;\n  }\n  // TrustedTypes.createPolicy throws if called with a name that is already\n  // registered, even in report-only mode. Until the API changes, catch the\n  // error not to break the applications functionally. In such case, the code\n  // will fall back to using regular Safe Types.\n  // TODO(koto): Remove catching once createPolicy API stops throwing.\n  try {\n    policy = policyFactory.createPolicy(name, {\n      createHTML: goog.identity_,\n      createScript: goog.identity_,\n      createScriptURL: goog.identity_,\n      createURL: goog.identity_\n    });\n  } catch (e) {\n    goog.logToConsole_(e.message);\n  }\n  return policy;\n};\n\n\n/** @private @const {?TrustedTypePolicy} */\ngoog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n    goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n    null;\n"
  },
  {
    "path": "packages/tscc/third_party/closure_library/reflect.d.ts",
    "content": "/**\n * @fileoverview this is a hand-written d.ts file for goog.reflect.\n */\ndeclare module \"goog:goog.reflect\" {\n\tnamespace goog_reflect {\n\t\t/**\n\t\t * Syntax for object literal casts.\n\t\t * @see http://go/jscompiler-renaming\n\t\t * @see https://goo.gl/CRs09P\n\t\t *\n\t\t * Use this if you have an object literal whose keys need to have the same names\n\t\t * as the properties of some class even after they are renamed by the compiler.\n\t\t *\n\t\t * @param {!Function} type Type to cast to.\n\t\t * @param {Object} object Object literal to cast.\n\t\t * @return {Object} The object literal.\n\t\t */\n\t\tfunction object<T extends {}>(type: object, literal: T): T\n\n\t\t/**\n\t\t * Syntax for renaming property strings.\n\t\t * @see http://go/jscompiler-renaming\n\t\t * @see https://goo.gl/CRs09P\n\t\t *\n\t\t * Use this if you have an need to access a property as a string, but want\n\t\t * to also have the property renamed by the compiler. In contrast to\n\t\t * goog.reflect.object, this method takes an instance of an object.\n\t\t *\n\t\t * Properties must be simple names (not qualified names).\n\t\t *\n\t\t * @param {string} prop Name of the property\n\t\t * @param {!Object} object Instance of the object whose type will be used\n\t\t *     for renaming\n\t\t * @return {string} The renamed property.\n\t\t */\n\t\tfunction objectProperty<T>(prop: keyof T & string, object: T): string\n\n\t\t/**\n\t\t * To assert to the compiler that an operation is needed when it would\n\t\t * otherwise be stripped. For example:\n\t\t * <code>\n\t\t *     // Force a layout\n\t\t *     goog.reflect.sinkValue(dialog.offsetHeight);\n\t\t * </code>\n\t\t * @param {T} x\n\t\t * @return {T}\n\t\t * @template T\n\t\t */\n\t\tfunction sinkValue<T>(value: T): T\n\n\t\t/**\n\t\t * Check if a property can be accessed without throwing an exception.\n\t\t * @param {Object} obj The owner of the property.\n\t\t * @param {string} prop The property name.\n\t\t * @return {boolean} Whether the property is accessible. Will also return true\n\t\t *     if obj is null.\n\t\t */\n\t\tfunction canAccessProperty<T>(obj: T, prop: keyof T): boolean\n\n\t\t/**\n\t\t * Retrieves a value from a cache given a key. The compiler provides special\n\t\t * consideration for this call such that it is generally considered side-effect\n\t\t * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n\t\t * then the entire call is considered to have side-effects.\n\t\t *\n\t\t * Conventionally storing the value on the cache would be considered a\n\t\t * side-effect and preclude unused calls from being pruned, ie. even if\n\t\t * the value was never used, it would still always be stored in the cache.\n\t\t *\n\t\t * Providing a side-effect free `valueFn` and `opt_keyFn`\n\t\t * allows unused calls to `goog.reflect.cache` to be pruned.\n\t\t *\n\t\t * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n\t\t * @param {?} key The key to lookup in the cache. If it is not string or number\n\t\t *     then a `opt_keyFn` should be provided. The key is also used as the\n\t\t *     parameter to the `valueFn`.\n\t\t * @param {function(?):V} valueFn The value provider to use to calculate the\n\t\t *     value to store in the cache. This function should be side-effect free\n\t\t *     to take advantage of the optimization.\n\t\t * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n\t\t *     map key. This should be used if the given key is not a string or number.\n\t\t *     If not provided then the given key is used. This function should be\n\t\t *     side-effect free to take advantage of the optimization.\n\t\t * @return {V} The cached or calculated value.\n\t\t * @template K\n\t\t * @template V\n\t\t */\n\t\tfunction cache<K extends string | number, V>(cacheObj: {[key: string]: V}, key: K, valueFn: (key: K) => V): V\n\t\tfunction cache<K extends string | number, V, L>(cacheObj: {[key: string]: V}, key: L, valueFn: (key: L) => V, opt_keyFn?: (key: L) => K): V\n\t}\n\texport = goog_reflect;\n}\n"
  },
  {
    "path": "packages/tscc/third_party/closure_library/reflect.js",
    "content": "// Copyright 2009 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n  return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n *     for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n  return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n *     // Force a layout\n *     goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n  goog.reflect.sinkValue[' '](x);\n  return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n *     if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n\n  try {\n    goog.reflect.sinkValue(obj[prop]);\n    return true;\n  } catch (e) {\n  }\n  return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n *     then a `opt_keyFn` should be provided. The key is also used as the\n *     parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n *     value to store in the cache. This function should be side-effect free\n *     to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n *     map key. This should be used if the given key is not a string or number.\n *     If not provided then the given key is used. This function should be\n *     side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n  const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n  if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n    return cacheObj[storedKey];\n  }\n\n  return (cacheObj[storedKey] = valueFn(key));\n};\n"
  },
  {
    "path": "packages/tscc/third_party/tsickle/closure_externs.js",
    "content": "/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n/**\n * @fileoverview Extern definitions for types missing in the Closure externs,\n * but used in TypeScript platform `.d.ts`.\n * We suppress checkTypes to handle the scenario where a user doesn't use the\n * Closure externs (e.g. in a service worker).\n * @externs\n * @suppress {checkTypes}\n */\n\n/** @typedef {!IArrayLike} */\nvar ArrayLike;\n\n/** @typedef {!IteratorIterable} */\nvar IterableIterator;\n\n/** @typedef {!IIterableResult} */\nvar IteratorYieldResult;\n/** @typedef {!IIterableResult} */\nvar IteratorReturnResult;\n\n/** @typedef {!HTMLCollection} */\nvar HTMLCollectionOf;\n\n/** @typedef {!HTMLTableCellElement} */\nvar HTMLTableDataCellElement;\n\n/**\n * Does not have an equivalent in Closure's externs.\n * @typedef {!HTMLTableCellElement}\n */\nvar HTMLTableHeaderCellElement;\n\n/**\n * Closure's NodeList is parameterized itself, there is no NodeListOf.\n * @constructor\n * @template T\n * @extends {NodeList<T>}\n */\nvar NodeListOf;\n\n/**\n * Closure models this as a plain Array.\n * @typedef {!IArrayLike<string>|null}\n */\nvar RegExpExecArray;\n\n/** @typedef {!Map} */\nvar ReadonlyMap;\n\n/** @typedef {!Set} */\nvar ReadonlySet;\n\n/**\n * @record\n * @template T\n * @extends {IThenable<T>}\n */\nfunction PromiseLike() {};\n\n/** @typedef {function(new:Promise)} */\nvar PromiseConstructor;\n\n/** @typedef {function(new:Promise, function(function(*=), function(*=)))} */\nvar PromiseConstructorLike;\n\n/** @typedef {?} */\nvar SymbolConstructor;\n\n/** @typedef {!Object} */\nvar GlobalFetch;\n\n/**\n * @interface\n * @extends {WorkerGlobalScope}\n * @extends {Window}\n */\nvar WindowOrWorkerGlobalScope;\n\n/** @record */\nfunction CanvasDrawImage() {}\n\n/** @constructor */\nfunction CryptoKey() {};\n/** @constructor */\nfunction CryptoKeyPair() {};\n\n/** @typedef {!{handleEvent: function(Event):void}} */\nvar EventListenerObject;\n\n/** @typedef {!ITemplateArray} */\nvar TemplateStringsArray;\n\n/** @typedef {!RegExpResult} */\nvar RegExpMatchArray;\n\n/** @record */\nfunction ImportMeta() {};\n\n// Representations for TS' EventMap objects.\n// These are types that contain a mapping from event names to event object\n// types. User code can augment them, which produces externs.js files that then\n// reference the EventMap types - even though they are not defined in Closure.\n// Defining them here works around the problem.\n\n// Modification made for TSCC: classes were replaced with functions for compatibility with ES5\n\n/** @interface */\nfunction HTMLElementEventMap() {}\n/** @interface */\nfunction ElementEventMap() {}\n/** @interface */\nfunction DocumentEventMap() {}\n/** @interface */\nfunction WindowEventMap() {}\n/** @interface */\nfunction GlobalEventHandlersEventMap() {}\n/** @interface */\nfunction DocumentAndElementEventHandlersEventMap() {}\n/** @interface */\nfunction EventSourceEventMap() {}\n"
  },
  {
    "path": "packages/tscc/third_party/tsickle/third_party/tslib/LICENSE.txt",
    "content": "Apache License\r\n\r\nVersion 2.0, January 2004\r\n\r\nhttp://www.apache.org/licenses/ \r\n\r\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\r\n\r\n1. Definitions.\r\n\r\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\r\n\r\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\r\n\r\n\"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\r\n\r\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\r\n\r\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\r\n\r\n\"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\r\n\r\n\"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\r\n\r\n\"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\r\n\r\n\"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\r\n\r\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\r\n\r\n2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\r\n\r\n3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\r\n\r\n4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\r\n\r\nYou must give any other recipients of the Work or Derivative Works a copy of this License; and\r\n\r\nYou must cause any modified files to carry prominent notices stating that You changed the files; and\r\n\r\nYou must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\r\n\r\nIf the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\r\n\r\n5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\r\n\r\n6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\r\n\r\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\r\n\r\n8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\r\n\r\n9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\r\n\r\nEND OF TERMS AND CONDITIONS\r\n"
  },
  {
    "path": "packages/tscc/third_party/tsickle/third_party/tslib/README.google",
    "content": "URL: https://github.com/Microsoft/tslib\nLicense: Apache 2.0\nDescription:\ntslib.js contains a version of the 'tslib' library, modified to work with\nthe Closure compiler.\n\nWhen building using tsickle, we pass --importHelpers to the TypeScript compiler\nso it uses this module instead.\n"
  },
  {
    "path": "packages/tscc/third_party/tsickle/third_party/tslib/externs.js",
    "content": "/** @externs */\n\nSymbol.asyncIterator;\n"
  },
  {
    "path": "packages/tscc/third_party/tsickle/third_party/tslib/tslib.js",
    "content": "/**\n * @fileoverview\n * Hand-modified Closure version of tslib.js.\n * These use the literal space optimized code from TypeScript for\n * compatibility.\n *\n * @suppress {undefinedVars}\n */\n\ngoog.module('tslib');\n\n/**\n * @param {?} d\n * @param {?} b\n */\nexports.__extends = function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    // LOCAL MODIFICATION: Add jsdoc annotation here:\n    /**\n     * @constructor\n     */\n    function __() {\n      (/** @type {?} */ (this)).constructor = d;\n    }\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};\n\nexports.__assign = Object.assign || /** @return {?} */ function (/** ? */ t) {\n    for (var s, i = 1, n = arguments.length; i < n; i++) {\n        s = arguments[i];\n        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n    }\n    return t;\n};\n\n/**\n * @param {?} s\n * @param {?} e\n * @return {?}\n */\nexports.__rest = function (s, e) {\n    var t = {};\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n        t[p] = s[p];\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0 && (/** @type {function((string|symbol)):boolean} */ (Object.prototype.propertyIsEnumerable)).call(s, p[i]))\n            t[p[i]] = s[p[i]];\n    return t;\n};\n\n/**\n * @param {?} decorators\n * @param {T} target\n * @param {?=} key\n * @param {?=} desc\n * @return {T}\n * @template T\n */\nexports.__decorate = function (decorators, target, key, desc) {\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n    // google3 local modification: use quoted property access to work around\n    // https://b.corp.google.com/issues/77140019.\n    if (typeof Reflect === \"object\" && Reflect && typeof Reflect['decorate'] === \"function\") r = Reflect['decorate'](decorators, target, key, desc);\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\n\n/**\n * @param {?} metadataKey\n * @param {?} metadataValue\n * @return {?}\n */\nexports.__metadata = function (metadataKey, metadataValue) {\n  // google3 local modification: use quoted property access to work around\n  // https://b.corp.google.com/issues/77140019.\n  if (typeof Reflect === \"object\" && Reflect && typeof Reflect['metadata'] === \"function\") return Reflect['metadata'](metadataKey, metadataValue);\n};\n\n/**\n * @param {?} paramIndex\n * @param {?} decorator\n * @return {?}\n */\nexports.__param = function (paramIndex, decorator) {\n    return function (target, key) { decorator(target, key, paramIndex); };\n};\n\n/**\n * @template T\n * @param {T} thisArg\n * @param {?} _arguments\n * @param {?} P\n * @param {function(this:T)} generator\n * @return {?}\n */\nexports.__awaiter = function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        // LOCAL MODIFICATION: Cannot express the function + keys pattern in\n        // closure, so we escape generator.next with ? type.\n        function fulfilled(value) { try { step((/** @type {?} */ (generator)).next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments)).next());\n    });\n};\n\n/**\n * @param {?} thisArg\n * @param {?} body\n * @return {?}\n */\nexports.__generator = function(thisArg, body) {\n  var _ = {\n    label: 0,\n    sent: function() {\n      if (t[0] & 1) throw (/** @type {!Error} */ (t[1]));\n      return t[1];\n    },\n    trys: [],\n    ops: []\n  },\n      f, y, t, g;\n  // LOCAL MODIFICATION: Originally iterator body was \"return this\", but it\n  // doesn't compile as this is unknown. Changed to g, which is equivalent.\n  return g = {next: verb(0), \"throw\": verb(1), \"return\": verb(2)},\n         typeof Symbol === \"function\" && (g[Symbol.iterator] = function() {\n           return g;\n         }), g;\n  function verb(n) {\n    return function(v) {\n      return step([n, v]);\n    };\n  }\n  function step(op) {\n    if (f) throw new TypeError(\"Generator is already executing.\");\n    while (_) try {\n        if (f = 1,\n            y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) &&\n                !(t = t.call(y, op[1])).done)\n          return t;\n        if (y = 0, t) op = [0, t.value];\n        switch (op[0]) {\n          case 0:\n          case 1:\n            t = op;\n            break;\n          case 4:\n            _.label++;\n            return {value: op[1], done: false};\n          case 5:\n            _.label++;\n            y = op[1];\n            op = [0];\n            continue;\n          case 7:\n            op = _.ops.pop();\n            _.trys.pop();\n            continue;\n          default:\n            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) &&\n                (op[0] === 6 || op[0] === 2)) {\n              _ = 0;\n              continue;\n            }\n            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {\n              _.label = op[1];\n              break;\n            }\n            if (op[0] === 6 && _.label < t[1]) {\n              _.label = t[1];\n              t = op;\n              break;\n            }\n            if (t && _.label < t[2]) {\n              _.label = t[2];\n              _.ops.push(op);\n              break;\n            }\n            if (t[2]) _.ops.pop();\n            _.trys.pop();\n            continue;\n        }\n        op = body.call(thisArg, _);\n      } catch (e) {\n        op = [6, e];\n        y = 0;\n      } finally {\n        f = t = 0;\n      }\n    if (op[0] & 5) throw (/** @type {!Error} */ (op[1]));\n    return {value: op[0] ? op[1] : void 0, done: true};\n  }\n};\n\n/**\n * @param {?} m\n * @param {?} e\n */\nexports.__exportStar = function (m, e) {\n    for (var p in m) if (!e.hasOwnProperty(p)) e[p] = m[p];\n};\n\n/**\n * @param {?} o\n * @return {?}\n */\nexports.__values = function (o) {\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n    if (m) return m.call(o);\n    return {\n        next: function () {\n            if (o && i >= o.length) o = void 0;\n            return { value: o && o[i++], done: !o };\n        }\n    };\n};\n\n/**\n * @param {?} o\n * @param {?=} n\n * @return {?}\n */\nexports.__read = function(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  } catch (error) {\n    e = {error: error};\n  } finally {\n    try {\n      if (r && !r.done && (m = i[\"return\"])) m.call(i);\n    } finally {\n      if (e) throw (/** @type {!Error} */ (e.error));\n    }\n  }\n  return ar;\n};\n\n/**\n * @type {function(...?):!Array}\n */\nexports.__spread = function() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n    ar = ar.concat(exports.__read(arguments[i]));\n  return ar;\n};\n\n/**\n * @type {function(...!Array):!Array}\n */\nexports.__spreadArrays = function() {\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n            r[k] = a[j];\n    return r;\n};\n\n/**\n * @constructor\n * LOCAL MODIFICATION: Originally used \"this\" in function body,\n * @this {?}\n * END LOCAL MODIFICATION\n * @param {?} v\n * @return {?}\n */\nexports.__await = function(v) {\n  return this instanceof exports.__await ? (this.v = v, this) :\n                                           new exports.__await(v);\n};\n\n/**\n * @param {?} thisArg\n * @param {?=} _arguments\n * @param {?=} generator\n * @return {?}\n */\nexports.__asyncGenerator = function __asyncGenerator(\n    thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator)\n    throw new TypeError('Symbol.asyncIterator is not defined.');\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = {}, verb('next'), verb('throw'), verb('return'),\n         i[Symbol.asyncIterator] = function() {\n           return (/** @type {?} */ (this));\n         }, i;\n  function verb(n) {\n    if (g[n])\n      i[n] = function(v) {\n        return new Promise(function(a, b) {\n          q.push([n, v, a, b]) > 1 || resume(n, v);\n        });\n      };\n  }\n  function resume(n, v) {\n    try {\n      step(g[n](v));\n    } catch (e) {\n      settle(q[0][3], e);\n    }\n  }\n  function step(r) {\n    r.value instanceof exports.__await ?\n        Promise.resolve(/** @type {?} */ (r.value).v).then(fulfill, reject) :\n        settle(q[0][2], r);\n  }\n  function fulfill(value) {\n    resume('next', value);\n  }\n  function reject(value) {\n    resume('throw', value);\n  }\n  function settle(f, v) {\n    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);\n  }\n};\n\n/**\n * @param {?} o\n * @return {?}\n */\nexports.__asyncDelegator = function(o) {\n  var i, p;\n  // LOCAL MODIFICATION: Originally iterator body was \"return this\", but it\n  // doesn't compile in some builds, as this is unknown. Changed to i, which is\n  // equivalent.\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return i; }, i;\n  /**\n   * @param {?} n\n   * @param {?=} f\n   * @return {?}\n   */\n  function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n};\n\n/**\n * @param {?} o\n * @return {?}\n */\nexports.__asyncValues = function(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator];\n  return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n};\n\n/**\n * @param {?=} cooked\n * @param {?=} raw\n * @return {?}\n */\nexports.__makeTemplateObject = function(cooked, raw) {\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n    return cooked;\n};\n\n/**\n * @param {?} receiver\n * @param {?} privateMap\n * @return {?}\n */\nexports.__classPrivateFieldGet = function (receiver, privateMap) {\n  if (!privateMap.has(receiver)) {\n      throw new TypeError(\"attempted to get private field on non-instance\");\n  }\n  return privateMap.get(receiver);\n};\n\n/**\n * @param {?} receiver\n * @param {?} privateMap\n * @param {?} value\n * @return {?}\n */\nexports.__classPrivateFieldSet = function (receiver, privateMap, value) {\n  if (!privateMap.has(receiver)) {\n      throw new TypeError(\"attempted to set private field on non-instance\");\n  }\n  privateMap.set(receiver, value);\n  return value;\n}\n"
  },
  {
    "path": "packages/tscc/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../tsconfig.json\",\n\t\"compilerOptions\": {\n\t\t\"outDir\": \"dist\",\n\t\t\"rootDir\": \"src\"\n\t},\n\t\"include\": [\n\t\t\"src/**/*.ts\"\n\t]\n}\n"
  },
  {
    "path": "packages/tscc-spec/.npmignore",
    "content": "index.ts\n/src\ntest\nnode_modules\ntsconfig.json\nyarn.lock\nyarn-error.log\n"
  },
  {
    "path": "packages/tscc-spec/index.ts",
    "content": "export * from './src/TsccSpec';\nexport * from './src/ITsccSpec';\nexport * from './src/ITsccSpecJSON';\nexport * from './src/shared/Graph';\n\nimport TsccSpec from './src/TsccSpec';\nimport ITsccSpec from './src/ITsccSpec';\nimport ITsccSpecJSON from './src/ITsccSpecJSON';\nexport {TsccSpec, ITsccSpec, ITsccSpecJSON};\n\n"
  },
  {
    "path": "packages/tscc-spec/package.json",
    "content": "{\n  \"name\": \"@tscc/tscc-spec\",\n  \"author\": \"theseanl\",\n  \"version\": \"0.9.4\",\n  \"main\": \"dist/index.js\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"clean\": \"rm -rf dist\"\n  },\n  \"dependencies\": {\n    \"fast-glob\": \"^3.2.12\",\n    \"fs-extra\": \"^10.1.0\",\n    \"upath\": \"^2.0.1\"\n  }\n}\n"
  },
  {
    "path": "packages/tscc-spec/src/ITsccSpec.ts",
    "content": "import {INamedModuleSpecs, IDebugOptions} from './ITsccSpecJSON';\n\nexport interface INamedModuleSpecsWithId extends INamedModuleSpecs {\n\tmoduleId: string\n}\n\n/**\n * All methods are expected to return absolute paths everywhere.\n * Relative paths in `tscc.spec.json` will be resolved relative to\n * the containing directory of the `tscc.spec.json`.\n */\nexport default interface ITsccSpec {\n\tgetOrderedModuleSpecs(): Required<INamedModuleSpecs>[]\n\t/**\n\t * Returns an array of external module names.\n\t */\n\tgetExternalModuleNames(): string[]\n\t/**\n\t * Returns an object that maps external module names to its assumed global names.\n\t */\n\tgetExternalModuleDataMap(): ReadonlyMap<string, Readonly<ExternalModuleData>>\n\t/**\n\t * Returns a list of file names provided by the jsFiles key.\n\t */\n\tgetJsFiles(): string[]\n\t/**\n\t * Get debugging options.\n\t */\n\tdebug(): Readonly<IDebugOptions>\n}\n\nexport interface ExternalModuleData {\n\tglobalName: string,\n\tisFilePath: boolean\n}\n"
  },
  {
    "path": "packages/tscc-spec/src/ITsccSpecJSON.ts",
    "content": "/**\n * @fileoverview All paths in values are resolved from the parent directory of the JSON file.\n */\nexport declare interface IModule {\n\t/**\n\t * The entry file of the module.\n\t */\n\tentry: string\n\t/**\n\t * An array of module names, which the current module depends on.\n\t */\n\tdependencies?: ReadonlyArray<string>\n\t/**\n\t * An array of file paths, which may not be reachable via `goog.require`s but\n\t * still need to be provided to the closure compiler.\n\t */\n\textraSources?: ReadonlyArray<string>\n}\n\nexport interface INamedModuleSpecs extends IModule {\n\t/**\n\t * The name of this module, to be used as the name of the output file, and to\n\t * refer modules in IModules.dependencies key.\n\t */\n\tmoduleName: string\n}\n\ndeclare interface ITsccSpecJSON {\n\tmodules: {\n\t\t/**\n\t\t * moduleName is a name of the module, to be used as the name of the output file,\n\t\t * and to refer modules in IModule.dependencies key.\n\t\t * It supports path delimiters.\n\t\t */\n\t\treadonly [moduleName: string]: string | Readonly<IModule>\n\t} |\n\t/**\n\t * Or alternatively, provide then in a custom order with module's name as a key as well,\n\t * it must be topologically sorted\n\t */\n\tINamedModuleSpecs[]\n\t/**\n\t * Similar to rollup's input option \"external\", maps module IDs to global names that's assumed\n\t * to be present in the global scope. Type declaration files must be available in the respective\n\t * npm modules or one must provide them manually with `declare module \"moduleName\" { }` statements.\n\t */\n\texternal?: {\n\t\treadonly [moduleName: string]: string\n\t}\n\t/**\n\t * Glob of js source files.\n\t */\n\tjsFiles?: string | string[]\n\t/**\n\t * Directory names to emit outputs in, or prefixes for output file names.\n\t * It will just be prepended to module names, so if its last character is not a path separator,\n\t * it will modify the output file's name.\n\t */\n\tprefix?: string | {readonly rollup: string, readonly cc: string}\n\t/**\n\t * Indicates what format should the output chunks be in. In `global`, chunks will reference\n\t * other chunks' values via global scope. In `module`, chunks will use ES6 import and export\n\t * statements to reference other chunk's values. This mirrors --chunk_output_type option of\n\t * closure compiler. Default is `global`.\n\t */\n\tchunkFormat?: 'global' | 'module'\n\t/**\n\t * Compiler flags to be passed to closure compiler. Tscc treats it as an opaque data.\n\t * \"js\", \"chunk\", \"entry_point\": computed from <modules>\n\t * \"chunk_output_path_prefix\": computed from <prefix>\n\t * \"language_in\": computed from \"compilerOption.target\" of tsconfig\n\t * \"language_out:; defaults to \"ECMASCRIPT_NEXT\".\n\t * \"compilation_level\": defaults to \"ADVANCED\".\n\t * Input files, output files, input language, and so on are inferred from other settings,\n\t * and if provided here, it will override the inferred values.\n\t */\n\tcompilerFlags?: closureCompilerFlags\n\t/**\n\t * Array of paths of soy files.\n\t */\n\ttemplates?: ReadonlyArray<string>\n\tdebug?: IDebugOptions\n}\n\nexport interface IDebugOptions {\n\t/**\n\t * Write intermediate tsickle output to disk. Prints closure compiler arguments to stderr.\n\t */\n\tpersistArtifacts?: boolean,\n\t/**\n\t * Ignore tsickle warnings for specified paths. Default: [\"node_modules\"]\n\t */\n\tignoreWarningsPath?: string[]\n}\n\nexport type primitives = string | boolean | number;\nexport type closureCompilerFlags = {[flag: string]: primitives | primitives[]}\n\nexport default ITsccSpecJSON;\n\n"
  },
  {
    "path": "packages/tscc-spec/src/TsccSpec.ts",
    "content": "import ITsccSpec, {ExternalModuleData} from './ITsccSpec';\nimport ITsccSpecJSON, {IModule, INamedModuleSpecs, IDebugOptions} from './ITsccSpecJSON';\nimport {DirectedTree, CycleError} from './shared/Graph';\nimport path = require('path');\nimport fs = require('fs');\nimport process = require('process');\nimport {readJsonSync} from 'fs-extra';\nimport fg = require('fast-glob');\nimport upath = require('upath');\n\n// \"modules\" key is no longer required\ninterface IInputTsccSpecJSONWithSpecFile extends Partial<ITsccSpecJSON> {\n\t/**\n\t * If exists, the plugin will first load the spec from the specified path,\n\t * and then override it with properties provided in this object.\n\t */\n\tspecFile: string\n}\n\ninterface IInputTsccSpecJSONWithOptionalSpecFile extends ITsccSpecJSON {\n\tspecFile?: string\n}\n\nexport type IInputTsccSpecJSON = IInputTsccSpecJSONWithOptionalSpecFile | IInputTsccSpecJSONWithSpecFile;\n\nfunction hasSpecFileKey(json: IInputTsccSpecJSON): json is IInputTsccSpecJSONWithSpecFile {\n\treturn typeof json.specFile === 'string';\n}\n\nexport default class TsccSpec implements ITsccSpec {\n\tprotected static readonly SPEC_FILE = 'tscc.spec.json';\n\n\tprivate static PATH_SEP = '[\\\\\\/' +\n\t\t(path.sep === '/' ? '' : '\\\\\\\\') + // backword-slashes are path separators in win32\n\t\t']';\n\tprivate static readonly RE_DOT_PATH = new RegExp('^[\\\\.]{1,2}' + TsccSpec.PATH_SEP);\n\tprivate static readonly RE_ENDS_WITH_SEP = new RegExp(TsccSpec.PATH_SEP + '$');\n\tprivate static isDotPath(p: string) {return TsccSpec.RE_DOT_PATH.test(p);}\n\tprivate static endsWithSep(p: string) {return TsccSpec.RE_ENDS_WITH_SEP.test(p);}\n\t/**\n\t * Follows the behavior of Typescript CLI.\n\t * 1. If --project argument is supplied,\n\t *   1-1. If it is a file, use it.\n\t *   1-2. If it is a directory, use directory/tsconfig.json.\n\t *   1-3. If it is not a file nor a directory, throw an error.\n\t * 2. If it is not supplied (and file arguments are not supplied which is always the case for\n\t *    tscc) it calls ts.findConfigFile to search for tsconfig.json from the current working\n\t *    directory.\n\t */\n\t/**\n\t * At least one among searchPath and defaultLocation must be non-null. This cannot be expressed\n\t * well with function overloads, because for example when one tries to call it with variables\n\t * satisfying the same contract, TS thinks that the call signature is not visible.\n\t */\n\tprotected static resolveSpecFile(\n\t\tsearchPath: string | undefined,\n\t\tspecFileName: string,\n\t\tdefaultLocation?: string\n\t): string | undefined {\n\t\tif (typeof searchPath === 'string') { // 1\n\t\t\ttry {\n\t\t\t\tlet stat = fs.statSync(searchPath); // Throws if does not exist\n\t\t\t\tif (stat.isFile()) return path.resolve(searchPath); // 1-1;\n\t\t\t\tif (stat.isDirectory()) { // 1-2;\n\t\t\t\t\tlet specPath = path.resolve(searchPath, specFileName);\n\t\t\t\t\tlet specStat = fs.statSync(specPath); // Throws if does not exist\n\t\t\t\t\tif (specStat.isFile()) return specPath;\n\t\t\t\t}\n\t\t\t} catch (e) {}\n\t\t\treturn; // 1-3\n\t\t}\n\t\t// Search ancestor directories starting from defaultLocation, similar to ts.findConfigFile\n\t\tlet nextPath = defaultLocation!;\n\t\twhile (nextPath !== searchPath) {\n\t\t\tsearchPath = nextPath;\n\t\t\ttry {\n\t\t\t\tlet specPath = path.resolve(searchPath, specFileName);\n\t\t\t\tlet stat = fs.statSync(specPath);\n\t\t\t\tif (stat.isFile()) return specPath;\n\t\t\t} catch (e) {}\n\t\t\tnextPath = path.dirname(searchPath);\n\t\t}\n\t\treturn;\n\t}\n\t// A helper function for creating path strings to display in terminal environments\n\tprotected static toDisplayedPath(p: string): string {\n\t\tconst relPath = path.relative('.', p);\n\t\tif (TsccSpec.isDotPath(relPath)) return path.resolve(p); // use an absolute path\n\t\tif (relPath === '.') return \"the current working directory\";\n\t\treturn relPath;\n\t}\n\tprivate static findTsccSpecAndThrow(root: string | undefined): string {\n\t\tconst specPath = TsccSpec.resolveSpecFile(root, TsccSpec.SPEC_FILE, process.cwd());\n\t\tif (specPath === undefined) {\n\t\t\tlet displayedPath = TsccSpec.toDisplayedPath(root || process.cwd());\n\t\t\tthrow new TsccSpecError(`No spec file was found from ${displayedPath}.`);\n\t\t}\n\t\treturn specPath;\n\t}\n\tprotected static loadSpecRaw(\n\t\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON\n\t) {\n\t\tconst tsccSpecJSONPath: string =\n\t\t\ttypeof tsccSpecJSONOrItsPath === 'string' ?\n\t\t\t\tTsccSpec.findTsccSpecAndThrow(tsccSpecJSONOrItsPath) :\n\t\t\t\ttypeof tsccSpecJSONOrItsPath === 'object' ?\n\t\t\t\t\thasSpecFileKey(tsccSpecJSONOrItsPath) ?\n\t\t\t\t\t\tTsccSpec.findTsccSpecAndThrow(tsccSpecJSONOrItsPath.specFile) :\n\t\t\t\t\t\tpath.join(process.cwd(), TsccSpec.SPEC_FILE) : // Just a dummy path\n\t\t\t\t\tTsccSpec.findTsccSpecAndThrow(undefined); // Searches in ancestor directories\n\n\t\tconst readSpecJSON = (): ITsccSpecJSON => {\n\t\t\ttry {\n\t\t\t\treturn readJsonSync(tsccSpecJSONPath);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new TsccSpecError(\n\t\t\t\t\t`Spec file is an invalid JSON: ${TsccSpec.toDisplayedPath(tsccSpecJSONPath)}.`\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\n\t\tconst tsccSpecJSON: ITsccSpecJSON =\n\t\t\ttypeof tsccSpecJSONOrItsPath === 'object' ?\n\t\t\t\thasSpecFileKey(tsccSpecJSONOrItsPath) ?\n\t\t\t\t\tObject.assign(readSpecJSON(), tsccSpecJSONOrItsPath) :\n\t\t\t\t\ttsccSpecJSONOrItsPath :\n\t\t\t\treadSpecJSON();\n\n\t\treturn {tsccSpecJSON, tsccSpecJSONPath};\n\t}\n\tstatic loadSpec<T extends typeof TsccSpec>(\n\t\tthis: T,\n\t\ttsccSpecJSONOrItsPath: string | IInputTsccSpecJSON\n\t): InstanceType<T> {\n\t\tlet {tsccSpecJSON, tsccSpecJSONPath} = TsccSpec.loadSpecRaw(tsccSpecJSONOrItsPath);\n\t\treturn <InstanceType<T>>new this(tsccSpecJSON, tsccSpecJSONPath);\n\t}\n\tconstructor(\n\t\tprotected readonly tsccSpec: ITsccSpecJSON,\n\t\tprotected basePath: string\n\t) {\n\t\tthis.computeOrderedModuleSpecs();\n\t\tthis.resolveRelativeExternalModuleNames();\n\t\tthis.validateSpec();\n\t}\n\tprivate validateSpec() {\n\t\t// Validates chunkFormat field.\n\t\tconst {chunkFormat} = this.tsccSpec;\n\t\tif (typeof chunkFormat === 'string') {\n\t\t\tif (chunkFormat !== 'global' && chunkFormat !== 'module') {\n\t\t\t\tthrow new TsccSpecError(`Invalid value of \"chunkFormat\": ${chunkFormat}, only \"global\" or \"module\" is allowed.`);\n\t\t\t}\n\t\t\t/**\n\t\t\t * {@link https://github.com/theseanl/tscc/issues/724} External module support for\n\t\t\t * \"chunkFormat\": \"module\" is incomplete. TODO: implement it and remove the validation here.\n\t\t\t */\n\t\t\tif (chunkFormat === 'module' && this.tsccSpec.external) {\n\t\t\t\tthrow new TsccSpecError(`External modules support is not implemented for \"chunkFormat\": \"module\".`);\n\t\t\t}\n\t\t}\n\t}\n\tprivate orderedModuleSpecs!: Required<INamedModuleSpecs>[];\n\tprivate computeOrderedModuleSpecs() {\n\t\tconst modules = this.tsccSpec.modules;\n\t\tif (Array.isArray(modules)) {\n\t\t\t// Use it as is, TODO but check whether it is sorted\n\t\t\tthis.orderedModuleSpecs =\n\t\t\t\tmodules.map(module => this.interopModuleSpecs(module.moduleName, module))\n\t\t\treturn;\n\t\t}\n\t\t// TODO Closure compiler requires modules to have a single common root.\n\t\t// We may validate it and produce error here.\n\t\tconst graph = new DirectedTree<string>();\n\t\tfor (let moduleName in modules) {\n\t\t\tgraph.addNodeById(moduleName);\n\t\t\t// Can be a string literal or IModule\n\t\t\tlet moduleSpecOrModuleEntryFile = modules[moduleName];\n\t\t\tif (typeof moduleSpecOrModuleEntryFile === 'string') continue;\n\t\t\tlet deps = moduleSpecOrModuleEntryFile.dependencies;\n\t\t\tif (!deps) continue;\n\t\t\tfor (let dep of deps) {\n\t\t\t\tgraph.addEdgeById(dep, moduleName);\n\t\t\t}\n\t\t}\n\t\tlet sorted: ReadonlyArray<string>;\n\t\ttry {\n\t\t\tsorted = graph.sort();\n\t\t} catch (e) {\n\t\t\tif (e instanceof CycleError) {\n\t\t\t\tthrow new TsccSpecError(`Circular dependency in modules ${[...e.cycle]}`);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tthis.orderedModuleSpecs = sorted.map(moduleName => {\n\t\t\treturn this.interopModuleSpecs(moduleName, modules[moduleName]);\n\t\t})\n\t}\n\tgetOrderedModuleSpecs() {\n\t\treturn this.orderedModuleSpecs;\n\t}\n\tprivate interopModuleSpecs(moduleName: string, moduleSpec: IModule | string): Required<INamedModuleSpecs> {\n\t\tlet spec: Partial<INamedModuleSpecs> & {entry: string} =\n\t\t\ttypeof moduleSpec === 'string' ? {entry: moduleSpec} : moduleSpec;\n\t\tif (!('dependencies' in spec)) spec.dependencies = [];\n\t\tif (!('extraSources' in spec)) spec.extraSources = [];\n\t\tspec.moduleName = moduleName;\n\t\t// Resolve entry file name to absolute path\n\t\tspec.entry = this.absolute(spec.entry);\n\t\treturn <Required<INamedModuleSpecs>>spec;\n\t}\n\t/**\n\t * Paths specified in TSCC spec are resolved with following strategy:\n\t *  - If starts with \"./\" or \"../\", resolve relative to the spec file's path.\n\t *  - If it is still not an absolute path, resolve relative to the current working directory.\n\t *    as if cwd is in the PATH.\n\t *  - Otherwise, use the absolute path as is.\n\t *  Also, it preserves the trailing path separator. This, for example, has semantic difference\n\t *  in closure compiler's 'chunk_output_path_prefix' option.\n\t */\n\tprotected absolute(filePath: string): string {\n\t\tif (path.isAbsolute(filePath)) return path.normalize(filePath);\n\t\t// Special handling for '' - treat it as if it ends with a separator\n\t\tlet endsWithSep = TsccSpec.endsWithSep(filePath) || filePath.length === 0;\n\t\tlet base = TsccSpec.isDotPath(filePath) ?\n\t\t\tpath.dirname(this.basePath) :\n\t\t\tprocess.cwd();\n\t\t// path.resolve trims trailing separators.\n\t\treturn path.resolve(base, filePath) + (endsWithSep ? path.sep : '');\n\t}\n\t/**\n\t * Resolves with TSCC's convention, but as a relative path from current working directory.\n\t */\n\tprotected relativeFromCwd(filePath: string): string {\n\t\tlet absolute = this.absolute(filePath);\n\t\tlet endsWithSep = absolute.endsWith(path.sep);\n\t\tconst relative = path.relative(process.cwd(), absolute);\n\t\t// Special handling for '' - do not add a separator at the end\n\t\treturn relative + (endsWithSep && relative.length > 0 ? path.sep : '');\n\t}\n\tprotected getOutputPrefix(target: \"cc\" | \"rollup\"): string {\n\t\tlet prefix = this.tsccSpec.prefix;\n\t\tif (typeof prefix === 'undefined') return '';\n\t\tif (typeof prefix === 'string') return prefix;\n\t\treturn prefix[target];\n\t}\n\tprivate external: Map<string, ExternalModuleData> = new Map();\n\tprivate resolveRelativeExternalModuleNames() {\n\t\tif (!('external' in this.tsccSpec)) return;\n\t\tfor (let [moduleName, globalName] of Object.entries(this.tsccSpec.external!)) {\n\t\t\tif (TsccSpec.isDotPath(moduleName)) {\n\t\t\t\tthis.external.set(this.absolute(moduleName), {globalName, isFilePath: true});\n\t\t\t} else {\n\t\t\t\tthis.external.set(moduleName, {globalName, isFilePath: false});\n\t\t\t}\n\t\t}\n\t}\n\tgetExternalModuleNames() {\n\t\treturn [...this.external.keys()];\n\t}\n\tgetExternalModuleDataMap(): ReadonlyMap<string, Readonly<ExternalModuleData>> {\n\t\treturn this.external;\n\t}\n\tgetJsFiles() {\n\t\tlet jsFiles = this.tsccSpec.jsFiles;\n\t\tif (!jsFiles) return [];\n\t\tif (typeof jsFiles === 'string') {\n\t\t\tjsFiles = [jsFiles];\n\t\t}\n\t\t/**\n\t\t * Resolve globs following TSCC's convention of using the spec file's path as a base path.\n\t\t * fast-glob expects Unix-style paths. See:\n\t\t * {@link https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows}\n\t\t */\n\t\tjsFiles = jsFiles.map(jsFile => upath.toUnix(this.absolute(jsFile)));\n\t\treturn <string[]>fg.sync(jsFiles)\n\t}\n\tdebug(): Readonly<IDebugOptions> {\n\t\treturn this.tsccSpec.debug || {};\n\t}\n}\n\nexport class TsccSpecError extends Error {}\n\n"
  },
  {
    "path": "packages/tscc-spec/src/shared/Graph.ts",
    "content": "class AssociativeArrayLink<V> {\n\tpublic prev: this\n\tpublic next: this\n\tconstructor(\n\t\tpublic value: V\n\t) {\n\t\tthis.prev = this;\n\t\tthis.next = this;\n\t}\n\tinsertBefore(item: this) {\n\t\tconst prev = item.prev = this.prev;\n\t\tconst next = item.next = this;\n\t\tnext.prev = item;\n\t\tprev.next = item;\n\t}\n\tremove() {\n\t\tconst prev = this.prev;\n\t\tconst next = this.next;\n\t\tnext.prev = prev;\n\t\tprev.next = next;\n\t}\n}\n\nclass AssociativeArray<K, V> {\n\tprivate $keys: Map<K, AssociativeArrayLink<[K, V]>> = new Map();\n\tprivate $values: Map<V, AssociativeArrayLink<[K, V]>> = new Map();\n\tprivate pivot = new AssociativeArrayLink<[K, V]>(<any>null);\n\thasKey(key: K): boolean {\n\t\treturn this.$keys.has(key);\n\t}\n\thasValue(value: V): boolean {\n\t\treturn this.$values.has(value)\n\t}\n\tgetValue(key: K): V | null {\n\t\tlet link = this.$keys.get(key);\n\t\tif (!link) return null;\n\t\treturn link.value[1];\n\t}\n\tgetKey(value: V): K | null {\n\t\tlet link = this.$values.get(value);\n\t\tif (!link) return null;\n\t\treturn link.value[0];\n\t}\n\tdeleteKey(key: K): this {\n\t\tlet link = this.$keys.get(key);\n\t\tif (!link) return this;\n\t\tthis.$keys.delete(key);\n\t\tthis.$values.delete(link.value[1]);\n\t\tlink.remove();\n\t\treturn this;\n\t}\n\tdeleteValue(value: V): this {\n\t\tlet link = this.$values.get(value);\n\t\tif (!link) return this;\n\t\tthis.$keys.delete(link.value[0]);\n\t\tthis.$values.delete(value);\n\t\tlink.remove();\n\t\treturn this;\n\t}\n\tset(key: K, value: V) {\n\t\tthis.deleteKey(key);\n\t\tthis.deleteValue(value);\n\t\tlet link = new AssociativeArrayLink<[K, V]>([key, value]);\n\t\tthis.$keys.set(key, link);\n\t\tthis.$values.set(value, link);\n\t\tthis.pivot.insertBefore(link);\n\t}\n\tget size() {\n\t\treturn this.$keys.size;\n\t}\n\tkeys() {\n\t\treturn this.$keys.keys();\n\t}\n\tvalues() {\n\t\treturn this.$values.keys();\n\t}\n\t*reversedKeys() {\n\t\tlet link = this.pivot.prev;\n\t\twhile (link !== this.pivot) {\n\t\t\tyield link.value[0];\n\t\t\tlink = link.prev;\n\t\t}\n\t}\n\t*reversedValues() {\n\t\tlet link = this.pivot.prev;\n\t\twhile (link !== this.pivot) {\n\t\t\tyield link.value[1];\n\t\t\tlink = link.prev;\n\t\t}\n\t}\n\tclear() {\n\t\tthis.$keys.clear();\n\t\tthis.$values.clear();\n\t\tthis.pivot.next = this.pivot.prev = this.pivot;\n\t}\n}\n\nclass Node {\n\tprotected inbound: DirectedEdge[] = [];\n\tprotected outbound: DirectedEdge[] = [];\n\taddInbound(edge: DirectedEdge) {\n\t\tthis.inbound.push(edge);\n\t}\n\taddOutbound(edge: DirectedEdge) {\n\t\tthis.outbound.push(edge);\n\t}\n\tdeleteInbound(edge: DirectedEdge) {\n\t\tlet i = this.inbound.indexOf(edge);\n\t\tif (i === -1) return;\n\t\tthis.inbound.splice(i, 1);\n\t}\n\tdeleteOutbound(edge: DirectedEdge) {\n\t\tlet i = this.outbound.indexOf(edge);\n\t\tif (i === -1) return;\n\t\tthis.outbound.splice(i, 1);\n\t}\n\tisRoot(): boolean {\n\t\treturn this.inbound.length === 0;\n\t}\n\tisLeaf(): boolean {\n\t\treturn this.outbound.length === 0;\n\t}\n\titerateInboundEdges() {\n\t\treturn this.inbound[Symbol.iterator]();\n\t}\n\titerateOutboundEdges() {\n\t\treturn this.outbound[Symbol.iterator]();\n\t}\n\t*iterateAncestors<T extends Node>(this: T): Iterable<T> {\n\t\tyield this;\n\t\tfor (let inboundEdge of this.inbound) {\n\t\t\tyield* (inboundEdge.source as T).iterateAncestors();\n\t\t\t// Classes derived from Node is expected to refine `inbound` and `outbound` fields so\n\t\t\t// that edges' source and target fields have the type of the derived class.\n\t\t}\n\t}\n}\n\nclass DirectedEdge {\n\tconstructor(\n\t\tpublic readonly source: Node,\n\t\tpublic readonly target: Node\n\t) {\n\t\tsource.addOutbound(this);\n\t\ttarget.addInbound(this);\n\t}\n}\n\nclass NodeToVisit extends Node {\n\tdeclare protected inbound: EdgeToVisit[];\n\tdeclare protected outbound: EdgeToVisit[];\n\tprotected visitedOutbound: EdgeToVisit[] = [];\n\tsetAsVisited(edge: EdgeToVisit) {\n\t\tlet index = this.outbound.indexOf(edge);\n\t\tif (index !== -1) {\n\t\t\tthis.outbound.splice(index, 1);\n\t\t\tthis.visitedOutbound.push(edge);\n\t\t}\n\t}\n\tresetVisited() {\n\t\tArray.prototype.push.apply(this.outbound, this.visitedOutbound);\n\t\tthis.visitedOutbound = [];\n\t}\n\tprotected decendents: Set<NodeToVisit> = new Set();\n\tisDecendent(node: NodeToVisit | null) {\n\t\tif (!node) return false;\n\t\treturn this.decendents.has(node);\n\t}\n\tcollectDecendentsFromVisitedEdges() {\n\t\tthis.decendents.add(this);\n\t\tfor (let edge of this.visitedOutbound) {\n\t\t\tlet target = edge.target;\n\t\t\tfor (let decendent of target.decendents) {\n\t\t\t\tthis.decendents.add(decendent);\n\t\t\t}\n\t\t}\n\t}\n}\n\nclass EdgeToVisit extends DirectedEdge {\n\tdeclare public readonly source: NodeToVisit;\n\tdeclare public readonly target: NodeToVisit;\n\tsetAsVisited() {\n\t\tthis.source.setAsVisited(this);\n\t}\n}\n\nclass NodeWithLeaf extends Node {\n\tprotected leafs: Set<NodeWithLeaf> = new Set();\n\taddLeaf(leaf: NodeWithLeaf) {\n\t\tthis.leafs.add(leaf);\n\t}\n\tgetLeafs(): ReadonlyArray<NodeWithLeaf> {\n\t\treturn [...this.leafs];\n\t}\n}\n\nexport class CycleError<I> extends Error {\n\tconstructor(\n\t\tpublic cycle: IterableIterator<I>,\n\t) {super();}\n}\n\nexport abstract class DirectedTreeBase<I, N extends Node, E extends DirectedEdge> {\n\tprotected map: AssociativeArray<I, N> = new AssociativeArray();\n\tprotected iterateNodes() {\n\t\treturn this.map.values();\n\t}\n\tprotected reverseIterateNodes() {\n\t\treturn this.map.reversedValues();\n\t}\n\tprotected abstract createNode(): N\n\tprotected abstract createEdge(source: N, target: N): E\n\taddNodeById(id: I) {\n\t\tif (this.map.hasKey(id)) return null;\n\t\tlet node = this.createNode();\n\t\tthis.map.set(id, node);\n\t\treturn node;\n\t}\n\taddEdgeById(source: I, target: I) {\n\t\tlet sourceNode = this.getNodeById(source);\n\t\tlet targetNode = this.getNodeById(target);\n\t\tif (sourceNode === null || targetNode === null) return;\n\t\tthis.createEdge(sourceNode, targetNode);\n\t}\n\tgetNodeById(id: I): N | null {\n\t\tif (this.map.hasKey(id)) return this.map.getValue(id);\n\t\treturn this.addNodeById(id);\n\t}\n\tgetIdOfNode(node: N): I | null {\n\t\treturn this.map.getKey(node);\n\t}\n\tprotected static filterLeafs<N extends Node>(node: N): boolean {\n\t\treturn node.isLeaf();\n\t}\n\tprivate getALeaf() {\n\t\tfor (let node of this.iterateNodes()) {\n\t\t\tif (node.isLeaf()) return node;\n\t\t}\n\t}\n\tprivate getARoot() {\n\t\tfor (let node of this.iterateNodes()) {\n\t\t\tif (node.isRoot()) return node;\n\t\t}\n\t}\n\t// Kahn's algorithm, sorting nodes from roots to leafs\n\tsort() {\n\t\tconst size = this.map.size;\n\t\tconst map = new AssociativeArray<I, N>();\n\t\tconst out: I[] = [];\n\t\tlet root: N | undefined;\n\t\twhile (root = this.getARoot()) {\n\t\t\tlet id = this.getIdOfNode(root)!;\n\t\t\tmap.set(id, root);\n\t\t\tout.push(id);\n\t\t\tthis.map.deleteValue(root);\n\t\t\tfor (let edge of root.iterateOutboundEdges()) {\n\t\t\t\tedge.target.deleteInbound(edge);\n\t\t\t}\n\t\t}\n\t\tif (map.size !== size) {\n\t\t\tthrow new CycleError(this.map.keys());\n\t\t}\n\t\t// Reset deleted outbounds\n\t\tfor (let node of map.values()) {\n\t\t\tfor (let edge of node.iterateOutboundEdges()) {\n\t\t\t\tedge.target.addInbound(edge);\n\t\t\t}\n\t\t}\n\t\tthis.map = map;\n\t\treturn out;\n\t}\n}\n\nexport class DirectedTree<I> extends DirectedTreeBase<I, Node, DirectedEdge> {\n\tprotected createNode() {\n\t\treturn new Node();\n\t}\n\tprotected createEdge(source: Node, target: Node) {\n\t\treturn new DirectedEdge(source, target);\n\t}\n}\n\n// Methods of this class is supposed to be called only after\n// its nodes are topologically sorted leaf-to-node, in particular calling sort() shall not change anything\nexport class DirectedTreeWithOrdering<I> extends DirectedTreeBase<I, NodeToVisit, EdgeToVisit> {\n\tprotected createNode() {\n\t\treturn new NodeToVisit();\n\t}\n\tprotected createEdge(source: NodeToVisit, target: NodeToVisit) {\n\t\treturn new EdgeToVisit(source, target);\n\t}\n\tpopulateDecendents() {\n\t\t// Iterating over a topologically sorted nodes, from leafs to roots\n\t\tfor (let node of this.reverseIterateNodes()) {\n\t\t\tnode.collectDecendentsFromVisitedEdges();\n\t\t\tfor (let edge of node.iterateInboundEdges()) {\n\t\t\t\t(edge as EdgeToVisit).setAsVisited();\n\t\t\t}\n\t\t}\n\t\t// reset\n\t\tfor (let node of this.iterateNodes()) {\n\t\t\tnode.resetVisited();\n\t\t}\n\t}\n\tgetInfimum(idArray: I[]): I | null {\n\t\t// Iterating over a topologically sorted nodes\n\t\t// Every edge goes from later nodes to earlier nodes.\n\t\tfor (let node of this.reverseIterateNodes()) {\n\t\t\tif (idArray.every(id => node.isDecendent(this.getNodeById(id)))) {\n\t\t\t\treturn this.getIdOfNode(node)!;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n\nexport class DirectedTreeWithLeafs<I> extends DirectedTreeBase<I, NodeWithLeaf, DirectedEdge> {\n\tprotected createNode() {\n\t\treturn new NodeWithLeaf();\n\t}\n\tprotected createEdge(source: NodeWithLeaf, target: NodeWithLeaf) {\n\t\treturn new DirectedEdge(source, target);\n\t}\n\tprivate *iterateLeafs() {\n\t\tfor (let node of this.iterateNodes()) {\n\t\t\tif (node.isLeaf()) yield node;\n\t\t}\n\t}\n\tpopulateLeafs() {\n\t\tfor (let leaf of this.iterateLeafs()) {\n\t\t\tfor (let node of leaf.iterateAncestors()) {\n\t\t\t\tnode.addLeaf(leaf);\n\t\t\t}\n\t\t}\n\t}\n\tgetLeafsOfNode(id: I): I[] {\n\t\treturn this.getNodeById(id)!.getLeafs().map(this.getIdOfNode, this) as I[];\n\t}\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/TsccSpec.ts",
    "content": "///<reference types=\"jest\"/>\nimport TsccSpec, {TsccSpecError} from '../src/TsccSpec';\nimport path = require('path');\nimport process = require('process');\n\ndescribe(`TsccSpec`, () => {\n\tdescribe(`loadSpec`, () => {\n\t\tconst testSpecDir = path.join(__dirname, 'sample');\n\n\t\ttest(`loads spec file from a specified directory`, () => {\n\t\t\tconst spec = TsccSpec.loadSpec(testSpecDir);\n\t\t\texpect(spec.getOrderedModuleSpecs().length).toBe(1);\n\t\t});\n\n\t\ttest(`loads spec from a directory specified via specFile key`, () => {\n\t\t\tconst spec = TsccSpec.loadSpec({specFile: testSpecDir});\n\t\t\texpect(spec.getOrderedModuleSpecs().length).toBe(1);\n\t\t});\n\n\t\ttest(`loads spec by searching on ancestor directories starting from CWD`, () => {\n\t\t\tconst done = mockCurrentWorkingDirectory(path.join(testSpecDir, 'nested_directory'));\n\n\t\t\tconst spec = TsccSpec.loadSpec(undefined);\n\t\t\texpect(spec.getOrderedModuleSpecs().length).toBe(1);\n\n\t\t\tdone();\n\t\t});\n\n\t\ttest(`ancestor directory search stops at the root directory`, () => {\n\t\t\tconst nonExistentPath = path.sep + new Array(5).fill(1).map(() => {\n\t\t\t\treturn Math.random().toString(36).substring(2);\n\t\t\t}).join(path.sep);\n\n\t\t\tconst done = mockCurrentWorkingDirectory(nonExistentPath);\n\n\t\t\texpect(() => {\n\t\t\t\tTsccSpec.loadSpec(undefined)\n\t\t\t}).toThrow(TsccSpecError);\n\t\t\t// ancestor directory search eventually stops at and throws\n\t\t\t// a not found error.\n\n\t\t\tdone();\n\t\t});\n\n\t\ttest(`when it cannot find a spec file at a path referenced via specFile key, throws an error with meaningful error message`, () => {\n\t\t\tlet errorThrown: Error;\n\t\t\ttry {\n\t\t\t\tTsccSpec.loadSpec({specFile: '/'});\n\t\t\t} catch (e) {\n\t\t\t\terrorThrown = e;\n\t\t\t}\n\t\t\texpect(errorThrown).toBeTruthy();\n\t\t\texpect(errorThrown.message).toMatch(/^No spec file was found from /);\n\t\t});\n\n\t\tconst invalidSpecJSONPath = path.join(__dirname, 'sample/invalid_json.json');\n\n\t\ttest(`throws when the spec file content is an invalid JSON.`, () => {\n\t\t\texpect(() => {\n\t\t\t\tTsccSpec.loadSpec(invalidSpecJSONPath)\n\t\t\t}).toThrowError(TsccSpecError);\n\t\t});\n\n\t\ttest(`throws when the spec file referenced via \"specFile\" key is an invalid JSON.`, () => {\n\t\t\texpect(() => {\n\t\t\t\tTsccSpec.loadSpec({specFile: invalidSpecJSONPath})\n\t\t\t}).toThrowError(TsccSpecError);\n\t\t});\n\n\t\tconst unsupportedJSONPath = path.join(__dirname, 'sample/unsupported_spec.json');\n\n\t\ttest(`throws when \"chunkFormat\" value is \"module\" and \"external\" option is used.`, () => {\n\t\t\texpect(() => {\n\t\t\t\tTsccSpec.loadSpec({specFile: unsupportedJSONPath})\n\t\t\t}).toThrowError(TsccSpecError);\n\t\t})\n\t});\n\tdescribe(`getExternalModulenames`, () => {\n\t\tconst externalModuleSpecPath = path.join(__dirname, 'sample/spec_with_relative_external.json');\n\t\ttest(`it resolves dot-path like external module names (those starting with ./ or ../) to an absolute path`, () => {\n\t\t\tconst spec = TsccSpec.loadSpec({specFile: externalModuleSpecPath});\n\t\t\texpect(new Set(spec.getExternalModuleNames())).toEqual(\n\t\t\t\tnew Set([\"non-relative\", path.resolve(__dirname, \"sample/external/containing/relative/path\")])\n\t\t\t);\n\t\t})\n\t})\n});\n\nfunction mockCurrentWorkingDirectory(mockValue: string) {\n\tconst spy = jest.spyOn(process, 'cwd');\n\tspy.mockReturnValue(mockValue);\n\treturn () => {spy.mockRestore();}\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/sample/invalid_json.json",
    "content": "{\n\t\"module\": {\n\t\t\"out : \"index.ts\"\n\t}\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/sample/spec_with_relative_external.json",
    "content": "{\n    \"modules\": {\n        \"out\": \"index.ts\"\n    },\n    \"external\": {\n        \"non-relative\": \"nonRelative\",\n        \"./external/containing/relative/path\": \"relative\"\n    }\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/sample/tscc.spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"out\": \"index.ts\"\n\t}\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/sample/unsupported_spec.json",
    "content": "{\n\t\"modules\": {\n\t\t\"out\": \"index.ts\"\n\t},\n\t\"external\": {\n\t\t\"vendor\": \"vendor\"\n\t},\n\t\"chunkFormat\": \"module\"\n}\n"
  },
  {
    "path": "packages/tscc-spec/test/shared/Graph.ts",
    "content": "///<reference types=\"jest\"/>\nimport {DirectedTreeBase, DirectedTree, DirectedTreeWithOrdering, DirectedTreeWithLeafs} from \"@tscc/tscc-spec\"\n\nfunction compareGraphStructure(nodes, edges, poset) {\n\tfor (let id of nodes) {\n\t\tlet node = poset.getNodeById(id);\n\t\tlet expectedTargets = edges.filter(([a, b]) => a === id).map(([a, b]) => b);\n\t\tlet expectedSources = edges.filter(([a, b]) => b === id).map(([a, b]) => a);\n\t\tlet targets = [...node.iterateOutboundEdges()]\n\t\t\t.map(edge => edge.target)\n\t\t\t.map(poset.getIdOfNode, poset);\n\t\tlet sources = [...node.iterateInboundEdges()]\n\t\t\t.map(edge => edge.source)\n\t\t\t.map(poset.getIdOfNode, poset);\n\t\texpect(new Set(expectedTargets)).toEqual(new Set(targets));\n\t\texpect(new Set(expectedSources)).toEqual(new Set(sources));\n\t}\n}\n\nfunction posetFromEdges<I>(poset: DirectedTreeBase<I, any, any>, edges: [I, I][]) {\n\tfor (let [a, b] of edges) {\n\t\tposet.addEdgeById(a, b);\n\t}\n}\n\ndescribe(`DirectedTree`, function () {\n\ttest(`can set a node via ID`, function () {\n\t\tconst poset = new DirectedTree<string>();\n\t\tposet.addNodeById(\"myNodeId\");\n\t\texpect(poset.getNodeById(\"myNodeId\")).not.toBeUndefined();\n\t\texpect(poset.getIdOfNode(poset.getNodeById(\"myNodeId\"))).toBe(\"myNodeId\");\n\t})\n\ttest(`creates nodes when it creates an edge`, function () {\n\t\tconst poset = new DirectedTree<string>();\n\t\tposet.addEdgeById(\"a\", \"b\");\n\t\texpect(poset.getNodeById(\"a\")).not.toBeUndefined();\n\t\texpect(poset.getNodeById(\"b\")).not.toBeUndefined()\n\t})\n\tdescribe(`sort`, function () {\n\t\tlet poset: DirectedTree<number>;\n\t\tlet nodes: number[]\n\t\tlet edges: [number, number][];\n\t\tbeforeEach(() => {\n\t\t\tposet = new DirectedTree<number>();\n\t\t\tnodes = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n\t\t\tedges = [\n\t\t\t\t[5, 4], [2, 3], [9, 1], [7, 8],\n\t\t\t\t[6, 2], [5, 3], [4, 8], [7, 9],\n\t\t\t\t[6, 5], [2, 7], [3, 1], [2, 5]\n\t\t\t];\n\t\t\tposetFromEdges(poset, edges);\n\t\t})\n\t\ttest(`topologically sorts the provided tree`, function () {\n\t\t\tconst sorted = poset.sort();\n\t\t\tfor (let [a, b] of edges) {\n\t\t\t\texpect(sorted.indexOf(a)).toBeLessThan(sorted.indexOf(b))\n\t\t\t}\n\t\t})\n\t\ttest(`throws on a graph with cycle`, function () {\n\t\t\tlet poset = new DirectedTreeWithOrdering<number>();\n\t\t\tlet edges: [number, number][] = [[0, 1], [1, 2], [2, 1], [2, 3], [1, 4], [2, 5]];\n\t\t\tposetFromEdges(poset, edges);\n\t\t\texpect(() => {poset.sort()}).toThrow();\n\t\t})\n\t\ttest(`preserves the graph structure`, function () {\n\t\t\tposet.sort();\n\t\t\tcompareGraphStructure(nodes, edges, poset);\n\t\t})\n\t\ttest(`is idempotent`, function () {\n\t\t\tconst sorted = poset.sort();\n\t\t\tconst sorted2 = poset.sort();\n\t\t\texpect(sorted).toEqual(sorted2);\n\t\t})\n\t})\n})\ndescribe(`DirectedTreeWithOrdering`, function () {\n\tlet poset: DirectedTreeWithOrdering<number>;\n\tlet nodes: number[];\n\tlet edges: [number, number][];\n\tbeforeEach(() => {\n\t\tposet = new DirectedTreeWithOrdering<number>();\n\t\tnodes = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n\t\tedges = [\n\t\t\t[5, 4], [2, 3], [9, 1], [7, 8],\n\t\t\t[6, 2], [5, 3], [4, 8], [7, 9],\n\t\t\t[6, 5], [2, 7], [3, 1], [2, 5]\n\t\t];\n\t\tposetFromEdges(poset, edges);\n\t})\n\tdescribe(`populateDependents`, function () {\n\t\ttest(`preserves the graph structure`, function () {\n\t\t\tposet.sort();\n\t\t\tposet.populateDecendents();\n\t\t\tcompareGraphStructure(nodes, edges, poset);\n\t\t})\n\t\ttest(`enables isDescendent method`, function () {\n\t\t\tposet.sort();\n\t\t\tposet.populateDecendents();\n\t\t\tfunction secondArgIsADescendentOfFirstArg(a: number, b: number) {\n\t\t\t\treturn poset.getNodeById(a).isDecendent(poset.getNodeById(b));\n\t\t\t}\n\t\t\texpect(secondArgIsADescendentOfFirstArg(7, 7)).toBe(true);\n\t\t\texpect(secondArgIsADescendentOfFirstArg(2, 3)).toBe(true);\n\t\t\texpect(secondArgIsADescendentOfFirstArg(6, 1)).toBe(true);\n\t\t\texpect(secondArgIsADescendentOfFirstArg(4, 6)).toBe(false);\n\t\t})\n\t})\n})\ndescribe(`DirectedTreeWithLeafs`, function () {\n\ttest(`populates nodes with leafs that are reachable from it`, function () {\n\t\tconst edges = [\n\t\t\t[5, 1], [5, 2], [6, 3], [6, 4], [7, 5], [7, 3], [8, 2], [8, 6], [9, 7], [9, 8]\n\t\t];\n\t\tconst expectedLeafs = {\n\t\t\t1: [1],\n\t\t\t2: [2],\n\t\t\t3: [3],\n\t\t\t4: [4],\n\t\t\t5: [1, 2],\n\t\t\t6: [3, 4],\n\t\t\t7: [1, 2, 3],\n\t\t\t8: [2, 3, 4],\n\t\t\t9: [1, 2, 3, 4]\n\t\t};\n\t\tconst poset = new DirectedTreeWithLeafs();\n\t\tposetFromEdges(poset, [\n\t\t\t[5, 1], [5, 2], [6, 3], [6, 4], [7, 5], [7, 3], [8, 2], [8, 6], [9, 7], [9, 8]\n\t\t])\n\t\tposet.populateLeafs();\n\t\tfor (let id = 1; id < 10; id++) {\n\t\t\texpect(new Set(poset.getLeafsOfNode(id))).toEqual(new Set(expectedLeafs[id]));\n\t\t}\n\t})\n})\n\n"
  },
  {
    "path": "packages/tscc-spec/tsconfig.json",
    "content": "{\n\t\"extends\": \"../../tsconfig.json\",\n\t\"compilerOptions\": {\n\t\t\"outDir\": \"dist\"\n\t},\n\t\"include\": [\n\t\t\"index.ts\",\n\t\t\"src/**/*.ts\"\n\t]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n\t\"compilerOptions\": {\n\t\t\"lib\": [\n\t\t\t\"es7\"\n\t\t],\n\t\t\"types\": [\n\t\t\t\"node\"\n\t\t],\n\t\t\"target\": \"es2017\",\n\t\t\"module\": \"commonjs\",\n\t\t\"strict\": true,\n\t\t\"newLine\": \"lf\",\n\t\t\"declaration\": true,\n\t\t\"stripInternal\": true,\n\t\t\"experimentalDecorators\": true,\n\t\t\"forceConsistentCasingInFileNames\": true\n\t}\n}\n"
  }
]