diff --git a/.gitattributes b/.gitattributes index 70c45d4e..761f9dc4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,6 @@ -dist/index* -diff linguist-generated=true -dist/licenses* -diff linguist-generated=true -dist/sourcemap* -diff linguist-generated=true +[attr]generated-code-file text eol=lf -diff linguist-generated=true +[attr]generated-binary-file -text -diff linguist-generated=true + +dist/index* generated-code-file +dist/licenses* generated-code-file +dist/sourcemap* generated-code-file diff --git a/.gitignore b/.gitignore index 6d0f09f8..bc20e914 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ coverage/ lib/ .vsconfig yarn-error.log +.orig diff --git a/.husky/.gitignore b/.husky/.gitignore deleted file mode 100644 index 31354ec1..00000000 --- a/.husky/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_ diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100644 index c599cab8..00000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -yarn lint-staged -yarn lint -yarn test -yarn build diff --git a/dist/index.js b/dist/index.js index 198cbb01..c0d506de 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,82 +5,82 @@ require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const model_1 = __nccwpck_require__(41359); -const cli_1 = __nccwpck_require__(55651); -const mac_builder_1 = __importDefault(__nccwpck_require__(39364)); -const platform_setup_1 = __importDefault(__nccwpck_require__(64423)); -function runMain() { - return __awaiter(this, void 0, void 0, function* () { - try { - if (cli_1.CLI.InitCliMode()) { - yield cli_1.CLI.RunCli(); - return; - } - model_1.Action.checkCompatibility(); - model_1.Cache.verify(); - const { dockerfile, workspace, actionFolder } = model_1.Action; - const buildParameters = yield model_1.BuildParameters.create(); - const baseImage = new model_1.ImageTag(buildParameters); - let builtImage; - if (buildParameters.cloudRunnerCluster && - buildParameters.cloudRunnerCluster !== '' && - buildParameters.cloudRunnerCluster !== 'local') { - yield model_1.CloudRunner.run(buildParameters, baseImage.toString()); - } - else { - core.info('Building locally'); - yield platform_setup_1.default.setup(buildParameters, actionFolder); - if (process.platform === 'darwin') { - mac_builder_1.default.run(actionFolder, workspace, buildParameters); - } - else { - builtImage = yield model_1.Docker.build({ path: actionFolder, dockerfile, baseImage }); - yield model_1.Docker.run(builtImage, Object.assign({ workspace }, buildParameters)); - } - } - // Set output - yield model_1.Output.setBuildVersion(buildParameters.buildVersion); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -runMain(); + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +const model_1 = __nccwpck_require__(41359); +const cli_1 = __nccwpck_require__(55651); +const mac_builder_1 = __importDefault(__nccwpck_require__(39364)); +const platform_setup_1 = __importDefault(__nccwpck_require__(64423)); +function runMain() { + return __awaiter(this, void 0, void 0, function* () { + try { + if (cli_1.CLI.InitCliMode()) { + yield cli_1.CLI.RunCli(); + return; + } + model_1.Action.checkCompatibility(); + model_1.Cache.verify(); + const { dockerfile, workspace, actionFolder } = model_1.Action; + const buildParameters = yield model_1.BuildParameters.create(); + const baseImage = new model_1.ImageTag(buildParameters); + let builtImage; + if (buildParameters.cloudRunnerCluster && + buildParameters.cloudRunnerCluster !== '' && + buildParameters.cloudRunnerCluster !== 'local') { + yield model_1.CloudRunner.run(buildParameters, baseImage.toString()); + } + else { + core.info('Building locally'); + yield platform_setup_1.default.setup(buildParameters, actionFolder); + if (process.platform === 'darwin') { + mac_builder_1.default.run(actionFolder, workspace, buildParameters); + } + else { + builtImage = yield model_1.Docker.build({ path: actionFolder, dockerfile, baseImage }); + yield model_1.Docker.run(builtImage, Object.assign({ workspace }, buildParameters)); + } + } + // Set output + yield model_1.Output.setBuildVersion(buildParameters.buildVersion); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +runMain(); /***/ }), @@ -89,58 +89,58 @@ runMain(); /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const path_1 = __importDefault(__nccwpck_require__(71017)); -class Action { - static get supportedPlatforms() { - return ['linux', 'win32', 'darwin']; - } - static get isRunningLocally() { - return process.env.RUNNER_WORKSPACE === undefined; - } - static get isRunningFromSource() { - return path_1.default.basename(__dirname) === 'model'; - } - static get canonicalName() { - return 'unity-builder'; - } - static get rootFolder() { - if (Action.isRunningFromSource) { - return path_1.default.dirname(path_1.default.dirname(path_1.default.dirname(__filename))); - } - return path_1.default.dirname(path_1.default.dirname(__filename)); - } - static get actionFolder() { - return `${Action.rootFolder}/dist`; - } - static get dockerfile() { - const currentPlatform = process.platform; - switch (currentPlatform) { - case 'linux': - return `${Action.actionFolder}/platforms/ubuntu/Dockerfile`; - case 'win32': - return `${Action.actionFolder}/platforms/windows/Dockerfile`; - case 'darwin': - return 'unused'; //Mac doesn't use a container - default: - throw new Error(`No Dockerfile for currently unsupported platform: ${currentPlatform}`); - } - } - static get workspace() { - return process.env.GITHUB_WORKSPACE; - } - static checkCompatibility() { - const currentPlatform = process.platform; - if (!Action.supportedPlatforms.includes(currentPlatform)) { - throw new Error(`Currently ${currentPlatform}-platform is not supported`); - } - } -} -exports["default"] = Action; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const path_1 = __importDefault(__nccwpck_require__(71017)); +class Action { + static get supportedPlatforms() { + return ['linux', 'win32', 'darwin']; + } + static get isRunningLocally() { + return process.env.RUNNER_WORKSPACE === undefined; + } + static get isRunningFromSource() { + return path_1.default.basename(__dirname) === 'model'; + } + static get canonicalName() { + return 'unity-builder'; + } + static get rootFolder() { + if (Action.isRunningFromSource) { + return path_1.default.dirname(path_1.default.dirname(path_1.default.dirname(__filename))); + } + return path_1.default.dirname(path_1.default.dirname(__filename)); + } + static get actionFolder() { + return `${Action.rootFolder}/dist`; + } + static get dockerfile() { + const currentPlatform = process.platform; + switch (currentPlatform) { + case 'linux': + return `${Action.actionFolder}/platforms/ubuntu/Dockerfile`; + case 'win32': + return `${Action.actionFolder}/platforms/windows/Dockerfile`; + case 'darwin': + return 'unused'; //Mac doesn't use a container + default: + throw new Error(`No Dockerfile for currently unsupported platform: ${currentPlatform}`); + } + } + static get workspace() { + return process.env.GITHUB_WORKSPACE; + } + static checkCompatibility() { + const currentPlatform = process.platform; + if (!Action.supportedPlatforms.includes(currentPlatform)) { + throw new Error(`Currently ${currentPlatform}-platform is not supported`); + } + } +} +exports["default"] = Action; /***/ }), @@ -149,61 +149,61 @@ exports["default"] = Action; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const semver = __importStar(__nccwpck_require__(11383)); -class AndroidVersioning { - static determineVersionCode(version, inputVersionCode) { - if (!inputVersionCode) { - return AndroidVersioning.versionToVersionCode(version); - } - return inputVersionCode; - } - static versionToVersionCode(version) { - if (version === 'none') { - core.info(`Versioning strategy is set to ${version}, so android version code should not be applied.`); - return 0; - } - const parsedVersion = semver.parse(version); - if (!parsedVersion) { - core.warning(`Could not parse "${version}" to semver, defaulting android version code to 1`); - return 1; - } - // The greatest value Google Plays allows is 2100000000. - // Allow for 3 patch digits, 3 minor digits and 3 major digits. - const versionCode = parsedVersion.major * 1000000 + parsedVersion.minor * 1000 + parsedVersion.patch; - if (versionCode >= 2050000000) { - throw new Error(`Generated versionCode ${versionCode} is dangerously close to the maximum allowed number 2100000000. Consider a different versioning scheme to be able to continue updating your application.`); - } - core.info(`Using android versionCode ${versionCode}`); - return versionCode; - } - static determineSdkManagerParameters(targetSdkVersion) { - const parsedVersion = Number.parseInt(targetSdkVersion.slice(-2), 10); - return Number.isNaN(parsedVersion) ? '' : `platforms;android-${parsedVersion}`; - } -} -exports["default"] = AndroidVersioning; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +const semver = __importStar(__nccwpck_require__(11383)); +class AndroidVersioning { + static determineVersionCode(version, inputVersionCode) { + if (!inputVersionCode) { + return AndroidVersioning.versionToVersionCode(version); + } + return inputVersionCode; + } + static versionToVersionCode(version) { + if (version === 'none') { + core.info(`Versioning strategy is set to ${version}, so android version code should not be applied.`); + return 0; + } + const parsedVersion = semver.parse(version); + if (!parsedVersion) { + core.warning(`Could not parse "${version}" to semver, defaulting android version code to 1`); + return 1; + } + // The greatest value Google Plays allows is 2100000000. + // Allow for 3 patch digits, 3 minor digits and 3 major digits. + const versionCode = parsedVersion.major * 1000000 + parsedVersion.minor * 1000 + parsedVersion.patch; + if (versionCode >= 2050000000) { + throw new Error(`Generated versionCode ${versionCode} is dangerously close to the maximum allowed number 2100000000. Consider a different versioning scheme to be able to continue updating your application.`); + } + core.info(`Using android versionCode ${versionCode}`); + return versionCode; + } + static determineSdkManagerParameters(targetSdkVersion) { + const parsedVersion = Number.parseInt(targetSdkVersion.slice(-2), 10); + return Number.isNaN(parsedVersion) ? '' : `platforms;android-${parsedVersion}`; + } +} +exports["default"] = AndroidVersioning; /***/ }), @@ -212,155 +212,155 @@ exports["default"] = AndroidVersioning; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const nanoid_1 = __nccwpck_require__(17592); -const core = __importStar(__nccwpck_require__(42186)); -const android_versioning_1 = __importDefault(__nccwpck_require__(43059)); -const cloud_runner_constants_1 = __importDefault(__nccwpck_require__(91311)); -const cloud_runner_namespace_1 = __importDefault(__nccwpck_require__(63287)); -const input_1 = __importDefault(__nccwpck_require__(91933)); -const platform_1 = __importDefault(__nccwpck_require__(9707)); -const unity_versioning_1 = __importDefault(__nccwpck_require__(17146)); -const versioning_1 = __importDefault(__nccwpck_require__(88729)); -const git_repo_1 = __nccwpck_require__(24271); -const github_cli_1 = __nccwpck_require__(44990); -class BuildParameters { - static create() { - return __awaiter(this, void 0, void 0, function* () { - const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidAppBundle); - const unityVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); - const buildVersion = yield versioning_1.default.determineVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); - const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); - const androidSdkManagerParameters = android_versioning_1.default.determineSdkManagerParameters(input_1.default.androidTargetSdkVersion); - let unitySerial = ''; - if (!process.env.UNITY_SERIAL && input_1.default.githubInputEnabled && input_1.default.cliOptions === undefined) { - //No serial was present so it is a personal license that we need to convert - if (!process.env.UNITY_LICENSE) { + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const nanoid_1 = __nccwpck_require__(17592); +const core = __importStar(__nccwpck_require__(42186)); +const android_versioning_1 = __importDefault(__nccwpck_require__(43059)); +const cloud_runner_constants_1 = __importDefault(__nccwpck_require__(91311)); +const cloud_runner_namespace_1 = __importDefault(__nccwpck_require__(63287)); +const input_1 = __importDefault(__nccwpck_require__(91933)); +const platform_1 = __importDefault(__nccwpck_require__(9707)); +const unity_versioning_1 = __importDefault(__nccwpck_require__(17146)); +const versioning_1 = __importDefault(__nccwpck_require__(88729)); +const git_repo_1 = __nccwpck_require__(24271); +const github_cli_1 = __nccwpck_require__(44990); +class BuildParameters { + static create() { + return __awaiter(this, void 0, void 0, function* () { + const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidAppBundle); + const unityVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); + const buildVersion = yield versioning_1.default.determineVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); + const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); + const androidSdkManagerParameters = android_versioning_1.default.determineSdkManagerParameters(input_1.default.androidTargetSdkVersion); + let unitySerial = ''; + if (!process.env.UNITY_SERIAL && input_1.default.githubInputEnabled && input_1.default.cliOptions === undefined) { + //No serial was present so it is a personal license that we need to convert + if (!process.env.UNITY_LICENSE) { throw new Error(`Missing Unity License File and no Serial was found. If this is a personal license, make sure to follow the activation steps and set the UNITY_LICENSE GitHub secret or enter a Unity - serial number inside the UNITY_SERIAL GitHub secret.`); - } - unitySerial = this.getSerialFromLicenseFile(process.env.UNITY_LICENSE); - } - else { - unitySerial = process.env.UNITY_SERIAL; - } - if (!input_1.default.cliMode) { - core.setSecret(unitySerial); - } - return { - version: unityVersion, - customImage: input_1.default.customImage, - unitySerial, - runnerTempPath: process.env.RUNNER_TEMP, - platform: input_1.default.targetPlatform, - projectPath: input_1.default.projectPath, - buildName: input_1.default.buildName, - buildPath: `${input_1.default.buildsPath}/${input_1.default.targetPlatform}`, - buildFile, - buildMethod: input_1.default.buildMethod, - buildVersion, - androidVersionCode, - androidKeystoreName: input_1.default.androidKeystoreName, - androidKeystoreBase64: input_1.default.androidKeystoreBase64, - androidKeystorePass: input_1.default.androidKeystorePass, - androidKeyaliasName: input_1.default.androidKeyaliasName, - androidKeyaliasPass: input_1.default.androidKeyaliasPass, - androidTargetSdkVersion: input_1.default.androidTargetSdkVersion, - androidSdkManagerParameters, - customParameters: input_1.default.customParameters, - sshAgent: input_1.default.sshAgent, - gitPrivateToken: input_1.default.gitPrivateToken || (yield github_cli_1.GithubCliReader.GetGitHubAuthToken()), - chownFilesTo: input_1.default.chownFilesTo, - cloudRunnerCluster: input_1.default.cloudRunnerCluster, - cloudRunnerBuilderPlatform: input_1.default.cloudRunnerBuilderPlatform, - awsBaseStackName: input_1.default.awsBaseStackName, - kubeConfig: input_1.default.kubeConfig, - cloudRunnerMemory: input_1.default.cloudRunnerMemory, - cloudRunnerCpu: input_1.default.cloudRunnerCpu, - kubeVolumeSize: input_1.default.kubeVolumeSize, - kubeVolume: input_1.default.kubeVolume, - postBuildSteps: input_1.default.postBuildSteps, - preBuildSteps: input_1.default.preBuildSteps, - customJob: input_1.default.customJob, - runNumber: input_1.default.runNumber, - branch: input_1.default.branch || (yield git_repo_1.GitRepoReader.GetBranch()), - cloudRunnerBranch: input_1.default.cloudRunnerBranch.split('/').reverse()[0], - cloudRunnerIntegrationTests: input_1.default.cloudRunnerTests, - githubRepo: input_1.default.githubRepo || (yield git_repo_1.GitRepoReader.GetRemote()) || 'game-ci/unity-builder', - remoteBuildCluster: input_1.default.cloudRunnerCluster, - cliMode: input_1.default.cliMode, - awsStackName: input_1.default.awsBaseStackName, - gitSha: input_1.default.gitSha, - logId: nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 9)(), - buildGuid: cloud_runner_namespace_1.default.generateBuildName(input_1.default.runNumber, input_1.default.targetPlatform), - customJobHooks: input_1.default.customJobHooks(), - cachePullOverrideCommand: input_1.default.cachePullOverrideCommand(), - cachePushOverrideCommand: input_1.default.cachePushOverrideCommand(), - readInputOverrideCommand: input_1.default.readInputOverrideCommand(), - readInputFromOverrideList: input_1.default.readInputFromOverrideList(), - kubeStorageClass: input_1.default.kubeStorageClass, - checkDependencyHealthOverride: input_1.default.checkDependencyHealthOverride, - startDependenciesOverride: input_1.default.startDependenciesOverride, - cacheKey: input_1.default.cacheKey, - }; - }); - } - static parseBuildFile(filename, platform, androidAppBundle) { - if (platform_1.default.isWindows(platform)) { - return `${filename}.exe`; - } - if (platform_1.default.isAndroid(platform)) { - return androidAppBundle ? `${filename}.aab` : `${filename}.apk`; - } - return filename; - } - static getSerialFromLicenseFile(license) { - const startKey = ``; - const startIndex = license.indexOf(startKey) + startKey.length; - if (startIndex < 0) { - throw new Error(`License File was corrupted, unable to locate serial`); - } - const endIndex = license.indexOf(endKey, startIndex); - // Slice off the first 4 characters as they are garbage values - return Buffer.from(license.slice(startIndex, endIndex), 'base64').toString('binary').slice(4); - } -} -exports["default"] = BuildParameters; + serial number inside the UNITY_SERIAL GitHub secret.`); + } + unitySerial = this.getSerialFromLicenseFile(process.env.UNITY_LICENSE); + } + else { + unitySerial = process.env.UNITY_SERIAL; + } + if (!input_1.default.cliMode) { + core.setSecret(unitySerial); + } + return { + version: unityVersion, + customImage: input_1.default.customImage, + unitySerial, + runnerTempPath: process.env.RUNNER_TEMP, + platform: input_1.default.targetPlatform, + projectPath: input_1.default.projectPath, + buildName: input_1.default.buildName, + buildPath: `${input_1.default.buildsPath}/${input_1.default.targetPlatform}`, + buildFile, + buildMethod: input_1.default.buildMethod, + buildVersion, + androidVersionCode, + androidKeystoreName: input_1.default.androidKeystoreName, + androidKeystoreBase64: input_1.default.androidKeystoreBase64, + androidKeystorePass: input_1.default.androidKeystorePass, + androidKeyaliasName: input_1.default.androidKeyaliasName, + androidKeyaliasPass: input_1.default.androidKeyaliasPass, + androidTargetSdkVersion: input_1.default.androidTargetSdkVersion, + androidSdkManagerParameters, + customParameters: input_1.default.customParameters, + sshAgent: input_1.default.sshAgent, + gitPrivateToken: input_1.default.gitPrivateToken || (yield github_cli_1.GithubCliReader.GetGitHubAuthToken()), + chownFilesTo: input_1.default.chownFilesTo, + cloudRunnerCluster: input_1.default.cloudRunnerCluster, + cloudRunnerBuilderPlatform: input_1.default.cloudRunnerBuilderPlatform, + awsBaseStackName: input_1.default.awsBaseStackName, + kubeConfig: input_1.default.kubeConfig, + cloudRunnerMemory: input_1.default.cloudRunnerMemory, + cloudRunnerCpu: input_1.default.cloudRunnerCpu, + kubeVolumeSize: input_1.default.kubeVolumeSize, + kubeVolume: input_1.default.kubeVolume, + postBuildSteps: input_1.default.postBuildSteps, + preBuildSteps: input_1.default.preBuildSteps, + customJob: input_1.default.customJob, + runNumber: input_1.default.runNumber, + branch: input_1.default.branch || (yield git_repo_1.GitRepoReader.GetBranch()), + cloudRunnerBranch: input_1.default.cloudRunnerBranch.split('/').reverse()[0], + cloudRunnerIntegrationTests: input_1.default.cloudRunnerTests, + githubRepo: input_1.default.githubRepo || (yield git_repo_1.GitRepoReader.GetRemote()) || 'game-ci/unity-builder', + remoteBuildCluster: input_1.default.cloudRunnerCluster, + cliMode: input_1.default.cliMode, + awsStackName: input_1.default.awsBaseStackName, + gitSha: input_1.default.gitSha, + logId: nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 9)(), + buildGuid: cloud_runner_namespace_1.default.generateBuildName(input_1.default.runNumber, input_1.default.targetPlatform), + customJobHooks: input_1.default.customJobHooks(), + cachePullOverrideCommand: input_1.default.cachePullOverrideCommand(), + cachePushOverrideCommand: input_1.default.cachePushOverrideCommand(), + readInputOverrideCommand: input_1.default.readInputOverrideCommand(), + readInputFromOverrideList: input_1.default.readInputFromOverrideList(), + kubeStorageClass: input_1.default.kubeStorageClass, + checkDependencyHealthOverride: input_1.default.checkDependencyHealthOverride, + startDependenciesOverride: input_1.default.startDependenciesOverride, + cacheKey: input_1.default.cacheKey, + }; + }); + } + static parseBuildFile(filename, platform, androidAppBundle) { + if (platform_1.default.isWindows(platform)) { + return `${filename}.exe`; + } + if (platform_1.default.isAndroid(platform)) { + return androidAppBundle ? `${filename}.aab` : `${filename}.apk`; + } + return filename; + } + static getSerialFromLicenseFile(license) { + const startKey = ``; + const startIndex = license.indexOf(startKey) + startKey.length; + if (startIndex < 0) { + throw new Error(`License File was corrupted, unable to locate serial`); + } + const endIndex = license.indexOf(endKey, startIndex); + // Slice off the first 4 characters as they are garbage values + return Buffer.from(license.slice(startIndex, endIndex), 'base64').toString('binary').slice(4); + } +} +exports["default"] = BuildParameters; /***/ }), @@ -369,52 +369,52 @@ exports["default"] = BuildParameters; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const action_1 = __importDefault(__nccwpck_require__(89088)); -const project_1 = __importDefault(__nccwpck_require__(88666)); -class Cache { - static verify() { - if (!fs_1.default.existsSync(project_1.default.libraryFolder)) { - this.notifyAboutCachingPossibility(); - } - } - static notifyAboutCachingPossibility() { - if (action_1.default.isRunningLocally) { - return; - } + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const action_1 = __importDefault(__nccwpck_require__(89088)); +const project_1 = __importDefault(__nccwpck_require__(88666)); +class Cache { + static verify() { + if (!fs_1.default.existsSync(project_1.default.libraryFolder)) { + this.notifyAboutCachingPossibility(); + } + } + static notifyAboutCachingPossibility() { + if (action_1.default.isRunningLocally) { + return; + } core.warning(` Library folder does not exist. Consider setting up caching to speed up your workflow, if this is not your first build. - `); - } -} -exports["default"] = Cache; + `); + } +} +exports["default"] = Cache; /***/ }), @@ -423,39 +423,39 @@ exports["default"] = Cache; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetAllCliModes = exports.GetCliFunctions = exports.CliFunction = void 0; -const targets = new Array(); -function CliFunction(key, description) { - return function (target, propertyKey, descriptor) { - targets.push({ - target, - propertyKey, - descriptor, - key, - description, - }); - }; -} -exports.CliFunction = CliFunction; -function GetCliFunctions(key) { - const results = targets.find((x) => x.key === key); - if (results === undefined || results.length === 0) { - throw new Error('no CLI mode found'); - } - return results; -} -exports.GetCliFunctions = GetCliFunctions; -function GetAllCliModes() { - return targets.map((x) => { - return { - key: x.key, - description: x.description, - }; - }); -} -exports.GetAllCliModes = GetAllCliModes; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetAllCliModes = exports.GetCliFunctions = exports.CliFunction = void 0; +const targets = new Array(); +function CliFunction(key, description) { + return function (target, propertyKey, descriptor) { + targets.push({ + target, + propertyKey, + descriptor, + key, + description, + }); + }; +} +exports.CliFunction = CliFunction; +function GetCliFunctions(key) { + const results = targets.find((x) => x.key === key); + if (results === undefined || results.length === 0) { + throw new Error('no CLI mode found'); + } + return results; +} +exports.GetCliFunctions = GetCliFunctions; +function GetAllCliModes() { + return targets.map((x) => { + return { + key: x.key, + description: x.description, + }; + }); +} +exports.GetAllCliModes = GetAllCliModes; /***/ }), @@ -464,147 +464,147 @@ exports.GetAllCliModes = GetAllCliModes; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - 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; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CLI = void 0; -const commander_ts_1 = __nccwpck_require__(40451); -const __1 = __nccwpck_require__(41359); -const core = __importStar(__nccwpck_require__(42186)); -const action_yaml_1 = __nccwpck_require__(11091); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const cli_decorator_1 = __nccwpck_require__(8731); -const remote_client_logger_1 = __nccwpck_require__(28082); -const setup_cloud_runner_repository_1 = __nccwpck_require__(39656); -const SDK = __importStar(__nccwpck_require__(71786)); -class CLI { - static InitCliMode() { - const program = new commander_ts_1.Command(); - program.version('0.0.1'); - const properties = Object.getOwnPropertyNames(__1.Input); - const actionYamlReader = new action_yaml_1.ActionYamlReader(); - for (const element of properties) { - program.option(`--${element} <${element}>`, actionYamlReader.GetActionYamlValue(element)); - } - program.option('-m, --mode ', cli_decorator_1.GetAllCliModes() - .map((x) => `${x.key} (${x.description})`) - .join(` | `)); - program.parse(process.argv); - CLI.options = program.opts(); - __1.Input.cliOptions = CLI.options; - return __1.Input.cliMode; - } - static RunCli() { - return __awaiter(this, void 0, void 0, function* () { - __1.Input.githubInputEnabled = false; - yield __1.Input.PopulateQueryOverrideInput(); - CLI.logInput(); - const results = cli_decorator_1.GetCliFunctions(CLI.options.mode); - cloud_runner_logger_1.default.log(`Entrypoint: ${results.key}`); - CLI.options.versioning = 'None'; - return yield results.target[results.propertyKey](); - }); - } - static logInput() { - core.info(`\n`); - core.info(`INPUT:`); - const properties = Object.getOwnPropertyNames(__1.Input); - for (const element of properties) { - if (__1.Input[element] !== undefined && - __1.Input[element] !== '' && - typeof __1.Input[element] !== `function` && - element !== 'length' && - element !== 'cliOptions' && - element !== 'prototype') { - core.info(`${element} ${__1.Input[element]}`); - } - } - core.info(`\n`); - } - static CLIBuild() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - const baseImage = new __1.ImageTag(buildParameter); - return yield __1.CloudRunner.run(buildParameter, baseImage.toString()); - }); - } - static runRemoteClientJob() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + 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; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CLI = void 0; +const commander_ts_1 = __nccwpck_require__(40451); +const __1 = __nccwpck_require__(41359); +const core = __importStar(__nccwpck_require__(42186)); +const action_yaml_1 = __nccwpck_require__(11091); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const cli_decorator_1 = __nccwpck_require__(8731); +const remote_client_logger_1 = __nccwpck_require__(28082); +const setup_cloud_runner_repository_1 = __nccwpck_require__(39656); +const SDK = __importStar(__nccwpck_require__(71786)); +class CLI { + static InitCliMode() { + const program = new commander_ts_1.Command(); + program.version('0.0.1'); + const properties = Object.getOwnPropertyNames(__1.Input); + const actionYamlReader = new action_yaml_1.ActionYamlReader(); + for (const element of properties) { + program.option(`--${element} <${element}>`, actionYamlReader.GetActionYamlValue(element)); + } + program.option('-m, --mode ', cli_decorator_1.GetAllCliModes() + .map((x) => `${x.key} (${x.description})`) + .join(` | `)); + program.parse(process.argv); + CLI.options = program.opts(); + __1.Input.cliOptions = CLI.options; + return __1.Input.cliMode; + } + static RunCli() { + return __awaiter(this, void 0, void 0, function* () { + __1.Input.githubInputEnabled = false; + yield __1.Input.PopulateQueryOverrideInput(); + CLI.logInput(); + const results = cli_decorator_1.GetCliFunctions(CLI.options.mode); + cloud_runner_logger_1.default.log(`Entrypoint: ${results.key}`); + CLI.options.versioning = 'None'; + return yield results.target[results.propertyKey](); + }); + } + static logInput() { + core.info(`\n`); + core.info(`INPUT:`); + const properties = Object.getOwnPropertyNames(__1.Input); + for (const element of properties) { + if (__1.Input[element] !== undefined && + __1.Input[element] !== '' && + typeof __1.Input[element] !== `function` && + element !== 'length' && + element !== 'cliOptions' && + element !== 'prototype') { + core.info(`${element} ${__1.Input[element]}`); + } + } + core.info(`\n`); + } + static CLIBuild() { + return __awaiter(this, void 0, void 0, function* () { + const buildParameter = yield __1.BuildParameters.create(); + const baseImage = new __1.ImageTag(buildParameter); + return yield __1.CloudRunner.run(buildParameter, baseImage.toString()); + }); + } + static runRemoteClientJob() { + return __awaiter(this, void 0, void 0, function* () { + const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); remote_client_logger_1.RemoteClientLogger.log(`Build Params: ${JSON.stringify(buildParameter, undefined, 4)} - `); - __1.CloudRunner.buildParameters = buildParameter; - yield setup_cloud_runner_repository_1.SetupCloudRunnerRepository.run(); - }); - } - static cachePush() { - return __awaiter(this, void 0, void 0, function* () { }); - } - static cachePull() { - return __awaiter(this, void 0, void 0, function* () { }); - } - static garbageCollectAws() { - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = __1.Input.region; - const CF = new SDK.CloudFormation(); - const stacks = yield CF.listStacks().promise(); - cloud_runner_logger_1.default.log(JSON.stringify(stacks, undefined, 4)); - }); - } -} -__decorate([ - cli_decorator_1.CliFunction(`cli`, `runs a cloud runner build`) -], CLI, "CLIBuild", null); -__decorate([ - cli_decorator_1.CliFunction(`remote-cli`, `sets up a repository, usually before a game-ci build`) -], CLI, "runRemoteClientJob", null); -__decorate([ - cli_decorator_1.CliFunction(`cach-push`, `push to cache`) -], CLI, "cachePush", null); -__decorate([ - cli_decorator_1.CliFunction(`cach-pull`, `pull from cache`) -], CLI, "cachePull", null); -__decorate([ - cli_decorator_1.CliFunction(`garbage-collect-aws`, `garbage collect aws`) -], CLI, "garbageCollectAws", null); -exports.CLI = CLI; + `); + __1.CloudRunner.buildParameters = buildParameter; + yield setup_cloud_runner_repository_1.SetupCloudRunnerRepository.run(); + }); + } + static cachePush() { + return __awaiter(this, void 0, void 0, function* () { }); + } + static cachePull() { + return __awaiter(this, void 0, void 0, function* () { }); + } + static garbageCollectAws() { + return __awaiter(this, void 0, void 0, function* () { + process.env.AWS_REGION = __1.Input.region; + const CF = new SDK.CloudFormation(); + const stacks = yield CF.listStacks().promise(); + cloud_runner_logger_1.default.log(JSON.stringify(stacks, undefined, 4)); + }); + } +} +__decorate([ + cli_decorator_1.CliFunction(`cli`, `runs a cloud runner build`) +], CLI, "CLIBuild", null); +__decorate([ + cli_decorator_1.CliFunction(`remote-cli`, `sets up a repository, usually before a game-ci build`) +], CLI, "runRemoteClientJob", null); +__decorate([ + cli_decorator_1.CliFunction(`cach-push`, `push to cache`) +], CLI, "cachePush", null); +__decorate([ + cli_decorator_1.CliFunction(`cach-pull`, `pull from cache`) +], CLI, "cachePull", null); +__decorate([ + cli_decorator_1.CliFunction(`garbage-collect-aws`, `garbage collect aws`) +], CLI, "garbageCollectAws", null); +exports.CLI = CLI; /***/ }), @@ -613,140 +613,140 @@ exports.CLI = CLI; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Caching = void 0; -const console_1 = __nccwpck_require__(96206); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const cloud_runner_folders_1 = __nccwpck_require__(13527); -const cloud_runner_system_1 = __nccwpck_require__(66879); -const lfs_hashing_1 = __nccwpck_require__(31938); -const remote_client_logger_1 = __nccwpck_require__(28082); -class Caching { - static PushToCache(cacheFolder, sourceFolder, cacheKey) { - return __awaiter(this, void 0, void 0, function* () { - cacheKey = cacheKey.replace(' ', ''); - const startPath = process.cwd(); - try { - if (!fs_1.default.existsSync(cacheFolder)) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cacheFolder}`); - } - process.chdir(path_1.default.resolve(sourceFolder, '..')); - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - cloud_runner_logger_1.default.log(`Hashed cache folder ${yield lfs_hashing_1.LFSHashing.hashAllFiles(sourceFolder)} ${sourceFolder} ${path_1.default.basename(sourceFolder)}`); - } - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${path_1.default.basename(sourceFolder)}`); - } - // eslint-disable-next-line func-style - const formatFunction = function (format) { - const arguments_ = Array.prototype.slice.call([path_1.default.resolve(sourceFolder, '..'), cacheFolder, cacheKey], 1); - return format.replace(/{(\d+)}/g, function (match, number) { - return typeof arguments_[number] != 'undefined' ? arguments_[number] : match; - }); - }; - yield cloud_runner_system_1.CloudRunnerSystem.Run(`zip ${cacheKey}.zip ${path_1.default.basename(sourceFolder)}`); - console_1.assert(fs_1.default.existsSync(`${cacheKey}.zip`), 'cache zip exists'); - console_1.assert(fs_1.default.existsSync(path_1.default.basename(sourceFolder)), 'source folder exists'); - if (cloud_runner_1.default.buildParameters.cachePushOverrideCommand) { - cloud_runner_system_1.CloudRunnerSystem.Run(formatFunction(cloud_runner_1.default.buildParameters.cachePushOverrideCommand)); - } - cloud_runner_system_1.CloudRunnerSystem.Run(`mv ${cacheKey}.zip ${cacheFolder}`); - remote_client_logger_1.RemoteClientLogger.log(`moved ${cacheKey}.zip to ${cacheFolder}`); - console_1.assert(fs_1.default.existsSync(`${path_1.default.join(cacheFolder, cacheKey)}.zip`), 'cache zip exists inside cache folder'); - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${cacheFolder}`); - } - } - catch (error) { - process.chdir(`${startPath}`); - throw error; - } - process.chdir(`${startPath}`); - }); - } - static PullFromCache(cacheFolder, destinationFolder, cacheKey = ``) { - return __awaiter(this, void 0, void 0, function* () { - cacheKey = cacheKey.replace(' ', ''); - const startPath = process.cwd(); - remote_client_logger_1.RemoteClientLogger.log(`Caching for ${path_1.default.basename(destinationFolder)}`); - try { - if (!fs_1.default.existsSync(cacheFolder)) { - fs_1.default.mkdirSync(cacheFolder); - } - if (!fs_1.default.existsSync(destinationFolder)) { - fs_1.default.mkdirSync(destinationFolder); - } - const latestInBranch = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -t "${cacheFolder}" | grep .zip$ | head -1`)) - .replace(/\n/g, ``) - .replace('.zip', ''); - process.chdir(cacheFolder); - const cacheSelection = cacheKey !== `` && fs_1.default.existsSync(`${cacheKey}.zip`) ? cacheKey : latestInBranch; - yield cloud_runner_logger_1.default.log(`cache key ${cacheKey} selection ${cacheSelection}`); - // eslint-disable-next-line func-style - const formatFunction = function (format) { - const arguments_ = Array.prototype.slice.call([path_1.default.resolve(destinationFolder, '..'), cacheFolder, cacheKey], 1); - return format.replace(/{(\d+)}/g, function (match, number) { - return typeof arguments_[number] != 'undefined' ? arguments_[number] : match; - }); - }; - if (cloud_runner_1.default.buildParameters.cachePullOverrideCommand) { - cloud_runner_system_1.CloudRunnerSystem.Run(formatFunction(cloud_runner_1.default.buildParameters.cachePullOverrideCommand)); - } - if (fs_1.default.existsSync(`${cacheSelection}.zip`)) { - const resultsFolder = `results${cloud_runner_1.default.buildParameters.buildGuid}`; - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${resultsFolder}`); - remote_client_logger_1.RemoteClientLogger.log(`cache item exists ${cacheFolder}/${cacheSelection}.zip`); - console_1.assert(`${fs_1.default.existsSync(destinationFolder)}`); - console_1.assert(`${fs_1.default.existsSync(`${cacheSelection}.zip`)}`); - const fullResultsFolder = path_1.default.join(cacheFolder, resultsFolder); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`unzip ${cacheSelection}.zip -d ${path_1.default.basename(resultsFolder)}`); - remote_client_logger_1.RemoteClientLogger.log(`cache item extracted to ${fullResultsFolder}`); - console_1.assert(`${fs_1.default.existsSync(fullResultsFolder)}`); - const destinationParentFolder = path_1.default.resolve(destinationFolder, '..'); - if (fs_1.default.existsSync(destinationFolder)) { - fs_1.default.rmSync(destinationFolder, { recursive: true, force: true }); - } - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mv "${fullResultsFolder}/${path_1.default.basename(destinationFolder)}" "${destinationParentFolder}"`); - } - else { - remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheKey} doesn't exist ${destinationFolder}`); - if (cacheSelection !== ``) { - remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheKey}.zip doesn't exist ${destinationFolder}`); - throw new Error(`Failed to get cache item, but cache hit was found: ${cacheSelection}`); - } - } - } - catch (error) { - process.chdir(`${startPath}`); - throw error; - } - process.chdir(`${startPath}`); - }); - } - static handleCachePurging() { - if (process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined) { - remote_client_logger_1.RemoteClientLogger.log(`purging ${cloud_runner_folders_1.CloudRunnerFolders.purgeRemoteCaching}`); - fs_1.default.rmdirSync(cloud_runner_folders_1.CloudRunnerFolders.cacheFolder, { recursive: true }); - } - } -} -exports.Caching = Caching; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Caching = void 0; +const console_1 = __nccwpck_require__(96206); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const cloud_runner_folders_1 = __nccwpck_require__(13527); +const cloud_runner_system_1 = __nccwpck_require__(66879); +const lfs_hashing_1 = __nccwpck_require__(31938); +const remote_client_logger_1 = __nccwpck_require__(28082); +class Caching { + static PushToCache(cacheFolder, sourceFolder, cacheKey) { + return __awaiter(this, void 0, void 0, function* () { + cacheKey = cacheKey.replace(' ', ''); + const startPath = process.cwd(); + try { + if (!fs_1.default.existsSync(cacheFolder)) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cacheFolder}`); + } + process.chdir(path_1.default.resolve(sourceFolder, '..')); + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + cloud_runner_logger_1.default.log(`Hashed cache folder ${yield lfs_hashing_1.LFSHashing.hashAllFiles(sourceFolder)} ${sourceFolder} ${path_1.default.basename(sourceFolder)}`); + } + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${path_1.default.basename(sourceFolder)}`); + } + // eslint-disable-next-line func-style + const formatFunction = function (format) { + const arguments_ = Array.prototype.slice.call([path_1.default.resolve(sourceFolder, '..'), cacheFolder, cacheKey], 1); + return format.replace(/{(\d+)}/g, function (match, number) { + return typeof arguments_[number] != 'undefined' ? arguments_[number] : match; + }); + }; + yield cloud_runner_system_1.CloudRunnerSystem.Run(`zip ${cacheKey}.zip ${path_1.default.basename(sourceFolder)}`); + console_1.assert(fs_1.default.existsSync(`${cacheKey}.zip`), 'cache zip exists'); + console_1.assert(fs_1.default.existsSync(path_1.default.basename(sourceFolder)), 'source folder exists'); + if (cloud_runner_1.default.buildParameters.cachePushOverrideCommand) { + cloud_runner_system_1.CloudRunnerSystem.Run(formatFunction(cloud_runner_1.default.buildParameters.cachePushOverrideCommand)); + } + cloud_runner_system_1.CloudRunnerSystem.Run(`mv ${cacheKey}.zip ${cacheFolder}`); + remote_client_logger_1.RemoteClientLogger.log(`moved ${cacheKey}.zip to ${cacheFolder}`); + console_1.assert(fs_1.default.existsSync(`${path_1.default.join(cacheFolder, cacheKey)}.zip`), 'cache zip exists inside cache folder'); + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${cacheFolder}`); + } + } + catch (error) { + process.chdir(`${startPath}`); + throw error; + } + process.chdir(`${startPath}`); + }); + } + static PullFromCache(cacheFolder, destinationFolder, cacheKey = ``) { + return __awaiter(this, void 0, void 0, function* () { + cacheKey = cacheKey.replace(' ', ''); + const startPath = process.cwd(); + remote_client_logger_1.RemoteClientLogger.log(`Caching for ${path_1.default.basename(destinationFolder)}`); + try { + if (!fs_1.default.existsSync(cacheFolder)) { + fs_1.default.mkdirSync(cacheFolder); + } + if (!fs_1.default.existsSync(destinationFolder)) { + fs_1.default.mkdirSync(destinationFolder); + } + const latestInBranch = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -t "${cacheFolder}" | grep .zip$ | head -1`)) + .replace(/\n/g, ``) + .replace('.zip', ''); + process.chdir(cacheFolder); + const cacheSelection = cacheKey !== `` && fs_1.default.existsSync(`${cacheKey}.zip`) ? cacheKey : latestInBranch; + yield cloud_runner_logger_1.default.log(`cache key ${cacheKey} selection ${cacheSelection}`); + // eslint-disable-next-line func-style + const formatFunction = function (format) { + const arguments_ = Array.prototype.slice.call([path_1.default.resolve(destinationFolder, '..'), cacheFolder, cacheKey], 1); + return format.replace(/{(\d+)}/g, function (match, number) { + return typeof arguments_[number] != 'undefined' ? arguments_[number] : match; + }); + }; + if (cloud_runner_1.default.buildParameters.cachePullOverrideCommand) { + cloud_runner_system_1.CloudRunnerSystem.Run(formatFunction(cloud_runner_1.default.buildParameters.cachePullOverrideCommand)); + } + if (fs_1.default.existsSync(`${cacheSelection}.zip`)) { + const resultsFolder = `results${cloud_runner_1.default.buildParameters.buildGuid}`; + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${resultsFolder}`); + remote_client_logger_1.RemoteClientLogger.log(`cache item exists ${cacheFolder}/${cacheSelection}.zip`); + console_1.assert(`${fs_1.default.existsSync(destinationFolder)}`); + console_1.assert(`${fs_1.default.existsSync(`${cacheSelection}.zip`)}`); + const fullResultsFolder = path_1.default.join(cacheFolder, resultsFolder); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`unzip ${cacheSelection}.zip -d ${path_1.default.basename(resultsFolder)}`); + remote_client_logger_1.RemoteClientLogger.log(`cache item extracted to ${fullResultsFolder}`); + console_1.assert(`${fs_1.default.existsSync(fullResultsFolder)}`); + const destinationParentFolder = path_1.default.resolve(destinationFolder, '..'); + if (fs_1.default.existsSync(destinationFolder)) { + fs_1.default.rmSync(destinationFolder, { recursive: true, force: true }); + } + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mv "${fullResultsFolder}/${path_1.default.basename(destinationFolder)}" "${destinationParentFolder}"`); + } + else { + remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheKey} doesn't exist ${destinationFolder}`); + if (cacheSelection !== ``) { + remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheKey}.zip doesn't exist ${destinationFolder}`); + throw new Error(`Failed to get cache item, but cache hit was found: ${cacheSelection}`); + } + } + } + catch (error) { + process.chdir(`${startPath}`); + throw error; + } + process.chdir(`${startPath}`); + }); + } + static handleCachePurging() { + if (process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined) { + remote_client_logger_1.RemoteClientLogger.log(`purging ${cloud_runner_folders_1.CloudRunnerFolders.purgeRemoteCaching}`); + fs_1.default.rmdirSync(cloud_runner_folders_1.CloudRunnerFolders.cacheFolder, { recursive: true }); + } + } +} +exports.Caching = Caching; /***/ }), @@ -755,65 +755,65 @@ exports.Caching = Caching; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunnerSystem = void 0; -const child_process_1 = __nccwpck_require__(32081); -const remote_client_logger_1 = __nccwpck_require__(28082); -class CloudRunnerSystem { - static Run(command, suppressError = false, suppressLogs = false) { - return __awaiter(this, void 0, void 0, function* () { - for (const element of command.split(`\n`)) { - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(element); - } - } - return yield new Promise((promise) => { - let output = ''; - const child = child_process_1.exec(command, (error, stdout, stderr) => { - if (error && !suppressError) { - throw error; - } - if (stderr) { - const diagnosticOutput = `${stderr.toString()}`; - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.logCliDiagnostic(diagnosticOutput); - } - output += diagnosticOutput; - return; - } - const outputChunk = `${stdout}`; - output += outputChunk; - }); - child.on('close', function (code) { - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(`[Exit code ${code}]`); - } - if (code !== 0 && !suppressError) { - throw new Error(output); - } - const outputLines = output.split(`\n`); - for (const element of outputLines) { - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(element); - } - } - promise(output); - }); - }); - }); - } -} -exports.CloudRunnerSystem = CloudRunnerSystem; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunnerSystem = void 0; +const child_process_1 = __nccwpck_require__(32081); +const remote_client_logger_1 = __nccwpck_require__(28082); +class CloudRunnerSystem { + static Run(command, suppressError = false, suppressLogs = false) { + return __awaiter(this, void 0, void 0, function* () { + for (const element of command.split(`\n`)) { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(element); + } + } + return yield new Promise((promise) => { + let output = ''; + const child = child_process_1.exec(command, (error, stdout, stderr) => { + if (error && !suppressError) { + throw error; + } + if (stderr) { + const diagnosticOutput = `${stderr.toString()}`; + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.logCliDiagnostic(diagnosticOutput); + } + output += diagnosticOutput; + return; + } + const outputChunk = `${stdout}`; + output += outputChunk; + }); + child.on('close', function (code) { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(`[Exit code ${code}]`); + } + if (code !== 0 && !suppressError) { + throw new Error(output); + } + const outputLines = output.split(`\n`); + for (const element of outputLines) { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(element); + } + } + promise(output); + }); + }); + }); + } +} +exports.CloudRunnerSystem = CloudRunnerSystem; /***/ }), @@ -822,63 +822,63 @@ exports.CloudRunnerSystem = CloudRunnerSystem; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LFSHashing = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -const cloud_runner_folders_1 = __nccwpck_require__(13527); -const cloud_runner_system_1 = __nccwpck_require__(66879); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const console_1 = __nccwpck_require__(96206); -class LFSHashing { - static createLFSHashFiles() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs ls-files -l | cut -d ' ' -f1 | sort > .lfs-assets-guid`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`md5sum .lfs-assets-guid > .lfs-assets-guid-sum`); - console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid-sum`)); - console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid`)); - const lfsHashes = { - lfsGuid: fs_1.default - .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull, `.lfs-assets-guid`)}`, 'utf8') - .replace(/\n/g, ``), - lfsGuidSum: fs_1.default - .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull, `.lfs-assets-guid-sum`)}`, 'utf8') - .replace(' .lfs-assets-guid', '') - .replace(/\n/g, ``), - }; - return lfsHashes; - } - catch (error) { - throw error; - } - }); - } - static hashAllFiles(folder) { - return __awaiter(this, void 0, void 0, function* () { - const startPath = process.cwd(); - process.chdir(folder); - const result = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`find -type f -exec md5sum "{}" + | sort | md5sum`)) - .replace(/\n/g, '') - .split(` `)[0]; - process.chdir(startPath); - return result; - }); - } -} -exports.LFSHashing = LFSHashing; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LFSHashing = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +const cloud_runner_folders_1 = __nccwpck_require__(13527); +const cloud_runner_system_1 = __nccwpck_require__(66879); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const console_1 = __nccwpck_require__(96206); +class LFSHashing { + static createLFSHashFiles() { + return __awaiter(this, void 0, void 0, function* () { + try { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs ls-files -l | cut -d ' ' -f1 | sort > .lfs-assets-guid`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`md5sum .lfs-assets-guid > .lfs-assets-guid-sum`); + console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid-sum`)); + console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid`)); + const lfsHashes = { + lfsGuid: fs_1.default + .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull, `.lfs-assets-guid`)}`, 'utf8') + .replace(/\n/g, ``), + lfsGuidSum: fs_1.default + .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull, `.lfs-assets-guid-sum`)}`, 'utf8') + .replace(' .lfs-assets-guid', '') + .replace(/\n/g, ``), + }; + return lfsHashes; + } + catch (error) { + throw error; + } + }); + } + static hashAllFiles(folder) { + return __awaiter(this, void 0, void 0, function* () { + const startPath = process.cwd(); + process.chdir(folder); + const result = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`find -type f -exec md5sum "{}" + | sort | md5sum`)) + .replace(/\n/g, '') + .split(` `)[0]; + process.chdir(startPath); + return result; + }); + } +} +exports.LFSHashing = LFSHashing; /***/ }), @@ -887,28 +887,28 @@ exports.LFSHashing = LFSHashing; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RemoteClientLogger = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -class RemoteClientLogger { - static log(message) { - cloud_runner_logger_1.default.log(`[Client] ${message}`); - } - static logCliError(message) { - cloud_runner_logger_1.default.log(`[Client][Error] ${message}`); - } - static logCliDiagnostic(message) { - cloud_runner_logger_1.default.log(`[Client][Diagnostic] ${message}`); - } - static logWarning(message) { - cloud_runner_logger_1.default.logWarning(message); - } -} -exports.RemoteClientLogger = RemoteClientLogger; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoteClientLogger = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +class RemoteClientLogger { + static log(message) { + cloud_runner_logger_1.default.log(`[Client] ${message}`); + } + static logCliError(message) { + cloud_runner_logger_1.default.log(`[Client][Error] ${message}`); + } + static logCliDiagnostic(message) { + cloud_runner_logger_1.default.log(`[Client][Diagnostic] ${message}`); + } + static logWarning(message) { + cloud_runner_logger_1.default.logWarning(message); + } +} +exports.RemoteClientLogger = RemoteClientLogger; /***/ }), @@ -917,94 +917,94 @@ exports.RemoteClientLogger = RemoteClientLogger; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SetupCloudRunnerRepository = void 0; -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -const cloud_runner_folders_1 = __nccwpck_require__(13527); -const caching_1 = __nccwpck_require__(38759); -const lfs_hashing_1 = __nccwpck_require__(31938); -const cloud_runner_system_1 = __nccwpck_require__(66879); -const remote_client_logger_1 = __nccwpck_require__(28082); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const console_1 = __nccwpck_require__(96206); -class SetupCloudRunnerRepository { - static run() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.buildPathFull}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.repoPathFull}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull}`); - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull); - yield SetupCloudRunnerRepository.cloneRepoWithoutLFSFiles(); - const lfsHashes = yield lfs_hashing_1.LFSHashing.createLFSHashFiles(); - if (fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderFull)) { - remote_client_logger_1.RemoteClientLogger.logWarning(`!Warning!: The Unity library was included in the git repository`); - } - yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull, `${lfsHashes.lfsGuidSum}`); - yield SetupCloudRunnerRepository.pullLatestLFS(); - yield caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull, `${lfsHashes.lfsGuidSum}`); - yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.libraryCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.libraryFolderFull); - caching_1.Caching.handleCachePurging(); - } - catch (error) { - throw error; - } - }); - } - static cloneRepoWithoutLFSFiles() { - return __awaiter(this, void 0, void 0, function* () { - try { - process.chdir(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathFull}`); - remote_client_logger_1.RemoteClientLogger.log(`Initializing source repository for cloning with caching of LFS files`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global advice.detachedHead false`); - remote_client_logger_1.RemoteClientLogger.log(`Cloning the repository being built:`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process --skip"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs install`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git clone ${cloud_runner_folders_1.CloudRunnerFolders.targetBuildRepoUrl} ${path_1.default.resolve(`..`, path_1.default.basename(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull))}`); - console_1.assert(fs_1.default.existsSync(`.git`)); - remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_1.default.buildParameters.branch}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.branch}`); - console_1.assert(fs_1.default.existsSync(path_1.default.join(`.git`, `lfs`)), 'LFS folder should not exist before caching'); - remote_client_logger_1.RemoteClientLogger.log(`Checked out ${process.env.GITHUB_SHA}`); - } - catch (error) { - throw error; - } - }); - } - static pullLatestLFS() { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -lh ${cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull}/..`); - } - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge -- %f"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs pull`); - remote_client_logger_1.RemoteClientLogger.log(`pulled latest LFS files`); - console_1.assert(fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull)); - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -lh ${cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull}/..`); - } - }); - } -} -exports.SetupCloudRunnerRepository = SetupCloudRunnerRepository; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SetupCloudRunnerRepository = void 0; +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +const cloud_runner_folders_1 = __nccwpck_require__(13527); +const caching_1 = __nccwpck_require__(38759); +const lfs_hashing_1 = __nccwpck_require__(31938); +const cloud_runner_system_1 = __nccwpck_require__(66879); +const remote_client_logger_1 = __nccwpck_require__(28082); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const console_1 = __nccwpck_require__(96206); +class SetupCloudRunnerRepository { + static run() { + return __awaiter(this, void 0, void 0, function* () { + try { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.buildPathFull}`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.repoPathFull}`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull}`); + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull); + yield SetupCloudRunnerRepository.cloneRepoWithoutLFSFiles(); + const lfsHashes = yield lfs_hashing_1.LFSHashing.createLFSHashFiles(); + if (fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderFull)) { + remote_client_logger_1.RemoteClientLogger.logWarning(`!Warning!: The Unity library was included in the git repository`); + } + yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull, `${lfsHashes.lfsGuidSum}`); + yield SetupCloudRunnerRepository.pullLatestLFS(); + yield caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull, `${lfsHashes.lfsGuidSum}`); + yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.libraryCacheFolderFull, cloud_runner_folders_1.CloudRunnerFolders.libraryFolderFull); + caching_1.Caching.handleCachePurging(); + } + catch (error) { + throw error; + } + }); + } + static cloneRepoWithoutLFSFiles() { + return __awaiter(this, void 0, void 0, function* () { + try { + process.chdir(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathFull}`); + remote_client_logger_1.RemoteClientLogger.log(`Initializing source repository for cloning with caching of LFS files`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global advice.detachedHead false`); + remote_client_logger_1.RemoteClientLogger.log(`Cloning the repository being built:`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process --skip"`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs install`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git clone ${cloud_runner_folders_1.CloudRunnerFolders.targetBuildRepoUrl} ${path_1.default.resolve(`..`, path_1.default.basename(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull))}`); + console_1.assert(fs_1.default.existsSync(`.git`)); + remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_1.default.buildParameters.branch}`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.branch}`); + console_1.assert(fs_1.default.existsSync(path_1.default.join(`.git`, `lfs`)), 'LFS folder should not exist before caching'); + remote_client_logger_1.RemoteClientLogger.log(`Checked out ${process.env.GITHUB_SHA}`); + } + catch (error) { + throw error; + } + }); + } + static pullLatestLFS() { + return __awaiter(this, void 0, void 0, function* () { + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -lh ${cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull}/..`); + } + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathFull); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge -- %f"`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process"`); + yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs pull`); + remote_client_logger_1.RemoteClientLogger.log(`pulled latest LFS files`); + console_1.assert(fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull)); + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -lh ${cloud_runner_folders_1.CloudRunnerFolders.lfsDirectoryFull}/..`); + } + }); + } +} +exports.SetupCloudRunnerRepository = SetupCloudRunnerRepository; /***/ }), @@ -1013,143 +1013,143 @@ exports.SetupCloudRunnerRepository = SetupCloudRunnerRepository; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AWSBaseStack = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const core = __importStar(__nccwpck_require__(42186)); -const fs = __importStar(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const crypto = __nccwpck_require__(6113); -class AWSBaseStack { - constructor(baseStackName) { - this.baseStackName = baseStackName; - } - setupBaseStack(CF) { - var _a, _b, _c, _d, _e; - return __awaiter(this, void 0, void 0, function* () { - const baseStackName = this.baseStackName; - const baseStack = fs.readFileSync(path_1.default.join(__dirname, 'cloud-formations', 'base-setup.yml'), 'utf8'); - // Cloud Formation Input - const describeStackInput = { - StackName: baseStackName, - }; - const parametersWithoutHash = [ - { ParameterKey: 'EnvironmentName', ParameterValue: baseStackName }, - ]; - const parametersHash = crypto - .createHash('md5') - .update(baseStack + JSON.stringify(parametersWithoutHash)) - .digest('hex'); - const parameters = [ - ...parametersWithoutHash, - ...[{ ParameterKey: 'Version', ParameterValue: parametersHash }], - ]; - const updateInput = { - StackName: baseStackName, - TemplateBody: baseStack, - Parameters: parameters, - Capabilities: ['CAPABILITY_IAM'], - }; - const createStackInput = { - StackName: baseStackName, - TemplateBody: baseStack, - Parameters: parameters, - Capabilities: ['CAPABILITY_IAM'], - }; - const stacks = yield CF.listStacks({ - StackStatusFilter: ['UPDATE_COMPLETE', 'CREATE_COMPLETE', 'ROLLBACK_COMPLETE'], - }).promise(); - const stackNames = ((_a = stacks.StackSummaries) === null || _a === void 0 ? void 0 : _a.map((x) => x.StackName)) || []; - const stackExists = stackNames.includes(baseStackName) || false; - const describeStack = () => __awaiter(this, void 0, void 0, function* () { - return yield CF.describeStacks(describeStackInput).promise(); - }); - try { - if (!stackExists) { - cloud_runner_logger_1.default.log(`${baseStackName} stack does not exist (${JSON.stringify(stackNames)})`); - yield CF.createStack(createStackInput).promise(); - cloud_runner_logger_1.default.log(`created stack (version: ${parametersHash})`); - } - const CFState = yield describeStack(); - let stack = (_b = CFState.Stacks) === null || _b === void 0 ? void 0 : _b[0]; - if (!stack) { - throw new Error(`Base stack doesn't exist, even after creation, stackExists check: ${stackExists}`); - } - const stackVersion = (_d = (_c = stack.Parameters) === null || _c === void 0 ? void 0 : _c.find((x) => x.ParameterKey === 'Version')) === null || _d === void 0 ? void 0 : _d.ParameterValue; - if (stack.StackStatus === 'CREATE_IN_PROGRESS') { - yield CF.waitFor('stackCreateComplete', describeStackInput).promise(); - } - if (stackExists) { - cloud_runner_logger_1.default.log(`Base stack exists (version: ${stackVersion}, local version: ${parametersHash})`); - if (parametersHash !== stackVersion) { - cloud_runner_logger_1.default.log(`Attempting update of base stack`); - try { - yield CF.updateStack(updateInput).promise(); - } - catch (error) { - if (error['message'].includes('No updates are to be performed')) { - cloud_runner_logger_1.default.log(`No updates are to be performed`); - } - else { - cloud_runner_logger_1.default.log(`Update Failed (Stack name: ${baseStackName})`); - cloud_runner_logger_1.default.log(error['message']); - } - cloud_runner_logger_1.default.log(`Continuing...`); - } - } - else { - cloud_runner_logger_1.default.log(`No update required`); - } - stack = (_e = (yield describeStack()).Stacks) === null || _e === void 0 ? void 0 : _e[0]; - if (!stack) { - throw new Error(`Base stack doesn't exist, even after updating and creation, stackExists check: ${stackExists}`); - } - if (stack.StackStatus === 'UPDATE_IN_PROGRESS') { - yield CF.waitFor('stackUpdateComplete', describeStackInput).promise(); - } - } - cloud_runner_logger_1.default.log('base stack is now ready'); - } - catch (error) { - core.error(JSON.stringify(yield describeStack(), undefined, 4)); - throw error; - } - }); - } -} -exports.AWSBaseStack = AWSBaseStack; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AWSBaseStack = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const core = __importStar(__nccwpck_require__(42186)); +const fs = __importStar(__nccwpck_require__(57147)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const crypto = __nccwpck_require__(6113); +class AWSBaseStack { + constructor(baseStackName) { + this.baseStackName = baseStackName; + } + setupBaseStack(CF) { + var _a, _b, _c, _d, _e; + return __awaiter(this, void 0, void 0, function* () { + const baseStackName = this.baseStackName; + const baseStack = fs.readFileSync(path_1.default.join(__dirname, 'cloud-formations', 'base-setup.yml'), 'utf8'); + // Cloud Formation Input + const describeStackInput = { + StackName: baseStackName, + }; + const parametersWithoutHash = [ + { ParameterKey: 'EnvironmentName', ParameterValue: baseStackName }, + ]; + const parametersHash = crypto + .createHash('md5') + .update(baseStack + JSON.stringify(parametersWithoutHash)) + .digest('hex'); + const parameters = [ + ...parametersWithoutHash, + ...[{ ParameterKey: 'Version', ParameterValue: parametersHash }], + ]; + const updateInput = { + StackName: baseStackName, + TemplateBody: baseStack, + Parameters: parameters, + Capabilities: ['CAPABILITY_IAM'], + }; + const createStackInput = { + StackName: baseStackName, + TemplateBody: baseStack, + Parameters: parameters, + Capabilities: ['CAPABILITY_IAM'], + }; + const stacks = yield CF.listStacks({ + StackStatusFilter: ['UPDATE_COMPLETE', 'CREATE_COMPLETE', 'ROLLBACK_COMPLETE'], + }).promise(); + const stackNames = ((_a = stacks.StackSummaries) === null || _a === void 0 ? void 0 : _a.map((x) => x.StackName)) || []; + const stackExists = stackNames.includes(baseStackName) || false; + const describeStack = () => __awaiter(this, void 0, void 0, function* () { + return yield CF.describeStacks(describeStackInput).promise(); + }); + try { + if (!stackExists) { + cloud_runner_logger_1.default.log(`${baseStackName} stack does not exist (${JSON.stringify(stackNames)})`); + yield CF.createStack(createStackInput).promise(); + cloud_runner_logger_1.default.log(`created stack (version: ${parametersHash})`); + } + const CFState = yield describeStack(); + let stack = (_b = CFState.Stacks) === null || _b === void 0 ? void 0 : _b[0]; + if (!stack) { + throw new Error(`Base stack doesn't exist, even after creation, stackExists check: ${stackExists}`); + } + const stackVersion = (_d = (_c = stack.Parameters) === null || _c === void 0 ? void 0 : _c.find((x) => x.ParameterKey === 'Version')) === null || _d === void 0 ? void 0 : _d.ParameterValue; + if (stack.StackStatus === 'CREATE_IN_PROGRESS') { + yield CF.waitFor('stackCreateComplete', describeStackInput).promise(); + } + if (stackExists) { + cloud_runner_logger_1.default.log(`Base stack exists (version: ${stackVersion}, local version: ${parametersHash})`); + if (parametersHash !== stackVersion) { + cloud_runner_logger_1.default.log(`Attempting update of base stack`); + try { + yield CF.updateStack(updateInput).promise(); + } + catch (error) { + if (error['message'].includes('No updates are to be performed')) { + cloud_runner_logger_1.default.log(`No updates are to be performed`); + } + else { + cloud_runner_logger_1.default.log(`Update Failed (Stack name: ${baseStackName})`); + cloud_runner_logger_1.default.log(error['message']); + } + cloud_runner_logger_1.default.log(`Continuing...`); + } + } + else { + cloud_runner_logger_1.default.log(`No update required`); + } + stack = (_e = (yield describeStack()).Stacks) === null || _e === void 0 ? void 0 : _e[0]; + if (!stack) { + throw new Error(`Base stack doesn't exist, even after updating and creation, stackExists check: ${stackExists}`); + } + if (stack.StackStatus === 'UPDATE_IN_PROGRESS') { + yield CF.waitFor('stackUpdateComplete', describeStackInput).promise(); + } + } + cloud_runner_logger_1.default.log('base stack is now ready'); + } + catch (error) { + core.error(JSON.stringify(yield describeStack(), undefined, 4)); + throw error; + } + }); + } +} +exports.AWSBaseStack = AWSBaseStack; /***/ }), @@ -1158,57 +1158,57 @@ exports.AWSBaseStack = AWSBaseStack; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AWSError = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const core = __importStar(__nccwpck_require__(42186)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class AWSError { - static handleStackCreationFailure(error, CF, taskDefStackName) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('aws error: '); - core.error(JSON.stringify(error, undefined, 4)); - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - cloud_runner_logger_1.default.log('Getting events and resources for task stack'); - const events = (yield CF.describeStackEvents({ StackName: taskDefStackName }).promise()).StackEvents; - cloud_runner_logger_1.default.log(JSON.stringify(events, undefined, 4)); - } - }); - } -} -exports.AWSError = AWSError; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AWSError = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const core = __importStar(__nccwpck_require__(42186)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class AWSError { + static handleStackCreationFailure(error, CF, taskDefStackName) { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.log('aws error: '); + core.error(JSON.stringify(error, undefined, 4)); + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + cloud_runner_logger_1.default.log('Getting events and resources for task stack'); + const events = (yield CF.describeStackEvents({ StackName: taskDefStackName }).promise()).StackEvents; + cloud_runner_logger_1.default.log(JSON.stringify(events, undefined, 4)); + } + }); + } +} +exports.AWSError = AWSError; /***/ }), @@ -1217,122 +1217,122 @@ exports.AWSError = AWSError; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AWSJobStack = void 0; -const aws_templates_1 = __nccwpck_require__(6436); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const aws_error_1 = __nccwpck_require__(83683); -class AWSJobStack { - constructor(baseStackName) { - this.baseStackName = baseStackName; - } - setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets) { - return __awaiter(this, void 0, void 0, function* () { - const taskDefStackName = `${this.baseStackName}-${buildGuid}`; - let taskDefCloudFormation = aws_templates_1.AWSTemplates.readTaskCloudFormationTemplate(); - for (const secret of secrets) { - secret.ParameterKey = `${buildGuid.replace(/[^\dA-Za-z]/g, '')}${secret.ParameterKey.replace(/[^\dA-Za-z]/g, '')}`; - if (typeof secret.ParameterValue == 'number') { - secret.ParameterValue = `${secret.ParameterValue}`; - } - if (!secret.ParameterValue || secret.ParameterValue === '') { - secrets = secrets.filter((x) => x !== secret); - continue; - } - taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p1 - input', aws_templates_1.AWSTemplates.getParameterTemplate(secret.ParameterKey)); - taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p2 - secret', aws_templates_1.AWSTemplates.getSecretTemplate(`${secret.ParameterKey}`)); - taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p3 - container def', aws_templates_1.AWSTemplates.getSecretDefinitionTemplate(secret.EnvironmentVariable, secret.ParameterKey)); - } - const secretsMappedToCloudFormationParameters = secrets.map((x) => { - return { ParameterKey: x.ParameterKey.replace(/[^\dA-Za-z]/g, ''), ParameterValue: x.ParameterValue }; - }); - const parameters = [ - { - ParameterKey: 'EnvironmentName', - ParameterValue: this.baseStackName, - }, - { - ParameterKey: 'ImageUrl', - ParameterValue: image, - }, - { - ParameterKey: 'ServiceName', - ParameterValue: taskDefStackName, - }, - { - ParameterKey: 'Command', - ParameterValue: 'echo "this template should be overwritten when running a task"', - }, - { - ParameterKey: 'EntryPoint', - ParameterValue: entrypoint.join(','), - }, - { - ParameterKey: 'WorkingDirectory', - ParameterValue: workingdir, - }, - { - ParameterKey: 'EFSMountDirectory', - ParameterValue: mountdir, - }, - ...secretsMappedToCloudFormationParameters, - ]; - let previousStackExists = true; - while (previousStackExists) { - previousStackExists = false; - const stacks = yield CF.listStacks().promise(); - if (!stacks.StackSummaries) { - throw new Error('Faild to get stacks'); - } - for (let index = 0; index < stacks.StackSummaries.length; index++) { - const element = stacks.StackSummaries[index]; - if (element.StackName === taskDefStackName && element.StackStatus !== 'DELETE_COMPLETE') { - previousStackExists = true; - cloud_runner_logger_1.default.log(`Previous stack still exists: ${JSON.stringify(element)}`); - } - } - } - try { - yield CF.createStack({ - StackName: taskDefStackName, - TemplateBody: taskDefCloudFormation, - Capabilities: ['CAPABILITY_IAM'], - Parameters: parameters, - }).promise(); - cloud_runner_logger_1.default.log('Creating cloud runner job'); - yield CF.waitFor('stackCreateComplete', { StackName: taskDefStackName }).promise(); - } - catch (error) { - yield aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); - throw error; - } - const taskDefResources = (yield CF.describeStackResources({ - StackName: taskDefStackName, - }).promise()).StackResources; - const baseResources = (yield CF.describeStackResources({ StackName: this.baseStackName }).promise()).StackResources; - return { - taskDefStackName, - taskDefCloudFormation, - taskDefResources, - baseResources, - }; - }); - } -} -exports.AWSJobStack = AWSJobStack; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AWSJobStack = void 0; +const aws_templates_1 = __nccwpck_require__(6436); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const aws_error_1 = __nccwpck_require__(83683); +class AWSJobStack { + constructor(baseStackName) { + this.baseStackName = baseStackName; + } + setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets) { + return __awaiter(this, void 0, void 0, function* () { + const taskDefStackName = `${this.baseStackName}-${buildGuid}`; + let taskDefCloudFormation = aws_templates_1.AWSTemplates.readTaskCloudFormationTemplate(); + for (const secret of secrets) { + secret.ParameterKey = `${buildGuid.replace(/[^\dA-Za-z]/g, '')}${secret.ParameterKey.replace(/[^\dA-Za-z]/g, '')}`; + if (typeof secret.ParameterValue == 'number') { + secret.ParameterValue = `${secret.ParameterValue}`; + } + if (!secret.ParameterValue || secret.ParameterValue === '') { + secrets = secrets.filter((x) => x !== secret); + continue; + } + taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p1 - input', aws_templates_1.AWSTemplates.getParameterTemplate(secret.ParameterKey)); + taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p2 - secret', aws_templates_1.AWSTemplates.getSecretTemplate(`${secret.ParameterKey}`)); + taskDefCloudFormation = aws_templates_1.AWSTemplates.insertAtTemplate(taskDefCloudFormation, 'p3 - container def', aws_templates_1.AWSTemplates.getSecretDefinitionTemplate(secret.EnvironmentVariable, secret.ParameterKey)); + } + const secretsMappedToCloudFormationParameters = secrets.map((x) => { + return { ParameterKey: x.ParameterKey.replace(/[^\dA-Za-z]/g, ''), ParameterValue: x.ParameterValue }; + }); + const parameters = [ + { + ParameterKey: 'EnvironmentName', + ParameterValue: this.baseStackName, + }, + { + ParameterKey: 'ImageUrl', + ParameterValue: image, + }, + { + ParameterKey: 'ServiceName', + ParameterValue: taskDefStackName, + }, + { + ParameterKey: 'Command', + ParameterValue: 'echo "this template should be overwritten when running a task"', + }, + { + ParameterKey: 'EntryPoint', + ParameterValue: entrypoint.join(','), + }, + { + ParameterKey: 'WorkingDirectory', + ParameterValue: workingdir, + }, + { + ParameterKey: 'EFSMountDirectory', + ParameterValue: mountdir, + }, + ...secretsMappedToCloudFormationParameters, + ]; + let previousStackExists = true; + while (previousStackExists) { + previousStackExists = false; + const stacks = yield CF.listStacks().promise(); + if (!stacks.StackSummaries) { + throw new Error('Faild to get stacks'); + } + for (let index = 0; index < stacks.StackSummaries.length; index++) { + const element = stacks.StackSummaries[index]; + if (element.StackName === taskDefStackName && element.StackStatus !== 'DELETE_COMPLETE') { + previousStackExists = true; + cloud_runner_logger_1.default.log(`Previous stack still exists: ${JSON.stringify(element)}`); + } + } + } + try { + yield CF.createStack({ + StackName: taskDefStackName, + TemplateBody: taskDefCloudFormation, + Capabilities: ['CAPABILITY_IAM'], + Parameters: parameters, + }).promise(); + cloud_runner_logger_1.default.log('Creating cloud runner job'); + yield CF.waitFor('stackCreateComplete', { StackName: taskDefStackName }).promise(); + } + catch (error) { + yield aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); + throw error; + } + const taskDefResources = (yield CF.describeStackResources({ + StackName: taskDefStackName, + }).promise()).StackResources; + const baseResources = (yield CF.describeStackResources({ StackName: this.baseStackName }).promise()).StackResources; + return { + taskDefStackName, + taskDefCloudFormation, + taskDefResources, + baseResources, + }; + }); + } +} +exports.AWSJobStack = AWSJobStack; /***/ }), @@ -1341,225 +1341,225 @@ exports.AWSJobStack = AWSJobStack; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const AWS = __importStar(__nccwpck_require__(71786)); -const core = __importStar(__nccwpck_require__(42186)); -const zlib = __importStar(__nccwpck_require__(59796)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const __1 = __nccwpck_require__(41359); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -const cloud_runner_statics_1 = __nccwpck_require__(90828); -const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); -class AWSTaskRunner { - static runTask(taskDef, ECS, CF, environment, buildGuid, commands) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; - return __awaiter(this, void 0, void 0, function* () { - const cluster = ((_b = (_a = taskDef.baseResources) === null || _a === void 0 ? void 0 : _a.find((x) => x.LogicalResourceId === 'ECSCluster')) === null || _b === void 0 ? void 0 : _b.PhysicalResourceId) || ''; - const taskDefinition = ((_d = (_c = taskDef.taskDefResources) === null || _c === void 0 ? void 0 : _c.find((x) => x.LogicalResourceId === 'TaskDefinition')) === null || _d === void 0 ? void 0 : _d.PhysicalResourceId) || ''; - const SubnetOne = ((_f = (_e = taskDef.baseResources) === null || _e === void 0 ? void 0 : _e.find((x) => x.LogicalResourceId === 'PublicSubnetOne')) === null || _f === void 0 ? void 0 : _f.PhysicalResourceId) || ''; - const SubnetTwo = ((_h = (_g = taskDef.baseResources) === null || _g === void 0 ? void 0 : _g.find((x) => x.LogicalResourceId === 'PublicSubnetTwo')) === null || _h === void 0 ? void 0 : _h.PhysicalResourceId) || ''; - const ContainerSecurityGroup = ((_k = (_j = taskDef.baseResources) === null || _j === void 0 ? void 0 : _j.find((x) => x.LogicalResourceId === 'ContainerSecurityGroup')) === null || _k === void 0 ? void 0 : _k.PhysicalResourceId) || ''; - const streamName = ((_m = (_l = taskDef.taskDefResources) === null || _l === void 0 ? void 0 : _l.find((x) => x.LogicalResourceId === 'KinesisStream')) === null || _m === void 0 ? void 0 : _m.PhysicalResourceId) || ''; - const task = yield ECS.runTask({ - cluster, - taskDefinition, - platformVersion: '1.4.0', - overrides: { - containerOverrides: [ - { - name: taskDef.taskDefStackName, - environment, - command: ['-c', cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.ProcessCommands(commands, cloud_runner_1.default.buildParameters)], - }, - ], - }, - launchType: 'FARGATE', - networkConfiguration: { - awsvpcConfiguration: { - subnets: [SubnetOne, SubnetTwo], - assignPublicIp: 'ENABLED', - securityGroups: [ContainerSecurityGroup], - }, - }, - }).promise(); - const taskArn = ((_o = task.tasks) === null || _o === void 0 ? void 0 : _o[0].taskArn) || ''; - cloud_runner_logger_1.default.log('Cloud runner job is starting'); - yield AWSTaskRunner.waitUntilTaskRunning(ECS, taskArn, cluster); - cloud_runner_logger_1.default.log(`Cloud runner job status is running ${(_p = (yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn))) === null || _p === void 0 ? void 0 : _p.lastStatus}`); - const output = yield this.streamLogsUntilTaskStops(ECS, CF, taskDef, cluster, taskArn, streamName); - const taskData = yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn); - const exitCode = (_q = taskData.containers) === null || _q === void 0 ? void 0 : _q[0].exitCode; - const wasSuccessful = exitCode === 0 || (exitCode === undefined && taskData.lastStatus === 'RUNNING'); - if (wasSuccessful) { - cloud_runner_logger_1.default.log(`Cloud runner job has finished successfully`); - return output; - } - else { - const message = `Cloud runner job exit code ${exitCode}`; - taskData.overrides = undefined; - taskData.attachments = undefined; - cloud_runner_logger_1.default.log(`${message} ${JSON.stringify(taskData, undefined, 4)}`); - throw new Error(message); - } - }); - } - static waitUntilTaskRunning(ECS, taskArn, cluster) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - try { - yield ECS.waitFor('tasksRunning', { tasks: [taskArn], cluster }).promise(); - } - catch (error_) { - const error = error_; - yield new Promise((resolve) => setTimeout(resolve, 3000)); - cloud_runner_logger_1.default.log(`Cloud runner job has ended ${(_a = (yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn)).containers) === null || _a === void 0 ? void 0 : _a[0].lastStatus}`); - core.setFailed(error); - core.error(error); - } - }); - } - static describeTasks(ECS, clusterName, taskArn) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const tasks = yield ECS.describeTasks({ - cluster: clusterName, - tasks: [taskArn], - }).promise(); - if ((_a = tasks.tasks) === null || _a === void 0 ? void 0 : _a[0]) { - return (_b = tasks.tasks) === null || _b === void 0 ? void 0 : _b[0]; - } - else { - throw new Error('No task found'); - } - }); - } - static streamLogsUntilTaskStops(ECS, CF, taskDef, clusterName, taskArn, kinesisStreamName) { - return __awaiter(this, void 0, void 0, function* () { - const kinesis = new AWS.Kinesis(); - const stream = yield AWSTaskRunner.getLogStream(kinesis, kinesisStreamName); - let iterator = yield AWSTaskRunner.getLogIterator(kinesis, stream); - const logBaseUrl = `https://${__1.Input.region}.console.aws.amazon.com/cloudwatch/home?region=${CF.config.region}#logsV2:log-groups/log-group/${taskDef.taskDefStackName}`; - cloud_runner_logger_1.default.log(`You can also see the logs at AWS Cloud Watch: ${logBaseUrl}`); - let shouldReadLogs = true; - let timestamp = 0; - let output = ''; - while (shouldReadLogs) { - yield new Promise((resolve) => setTimeout(resolve, 1500)); - const taskData = yield AWSTaskRunner.describeTasks(ECS, clusterName, taskArn); - ({ timestamp, shouldReadLogs } = AWSTaskRunner.checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs)); - ({ iterator, shouldReadLogs, output } = yield AWSTaskRunner.handleLogStreamIteration(kinesis, iterator, shouldReadLogs, taskDef, output)); - } - return output; - }); - } - static handleLogStreamIteration(kinesis, iterator, shouldReadLogs, taskDef, output) { - return __awaiter(this, void 0, void 0, function* () { - const records = yield kinesis - .getRecords({ - ShardIterator: iterator, - }) - .promise(); - iterator = records.NextShardIterator || ''; - ({ shouldReadLogs, output } = AWSTaskRunner.logRecords(records, iterator, taskDef, shouldReadLogs, output)); - return { iterator, shouldReadLogs, output }; - }); - } - static checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs) { - if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) === 'UNKNOWN') { - cloud_runner_logger_1.default.log('## Cloud runner job unknwon'); - } - if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) !== 'RUNNING') { - if (timestamp === 0) { - cloud_runner_logger_1.default.log('## Cloud runner job stopped, streaming end of logs'); - timestamp = Date.now(); - } - if (timestamp !== 0 && Date.now() - timestamp > 30000) { - cloud_runner_logger_1.default.log('## Cloud runner status is not RUNNING for 30 seconds, last query for logs'); - shouldReadLogs = false; - } - cloud_runner_logger_1.default.log(`## Status of job: ${taskData.lastStatus}`); - } - return { timestamp, shouldReadLogs }; - } - static logRecords(records, iterator, taskDef, shouldReadLogs, output) { - if (records.Records.length > 0 && iterator) { - for (let index = 0; index < records.Records.length; index++) { - const json = JSON.parse(zlib.gunzipSync(Buffer.from(records.Records[index].Data, 'base64')).toString('utf8')); - if (json.messageType === 'DATA_MESSAGE') { - for (let logEventsIndex = 0; logEventsIndex < json.logEvents.length; logEventsIndex++) { - let message = json.logEvents[logEventsIndex].message; - if (json.logEvents[logEventsIndex].message.includes(`---${cloud_runner_1.default.buildParameters.logId}`)) { - cloud_runner_logger_1.default.log('End of log transmission received'); - shouldReadLogs = false; - } - else if (message.includes('Rebuilding Library because the asset database could not be found!')) { - core.warning('LIBRARY NOT FOUND!'); - } - message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - output += message; - } - cloud_runner_logger_1.default.log(message); - } - } - } - } - return { shouldReadLogs, output }; - } - static getLogStream(kinesis, kinesisStreamName) { - return __awaiter(this, void 0, void 0, function* () { - return yield kinesis - .describeStream({ - StreamName: kinesisStreamName, - }) - .promise(); - }); - } - static getLogIterator(kinesis, stream) { - return __awaiter(this, void 0, void 0, function* () { - return ((yield kinesis - .getShardIterator({ - ShardIteratorType: 'TRIM_HORIZON', - StreamName: stream.StreamDescription.StreamName, - ShardId: stream.StreamDescription.Shards[0].ShardId, - }) - .promise()).ShardIterator || ''); - }); - } -} -exports["default"] = AWSTaskRunner; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const AWS = __importStar(__nccwpck_require__(71786)); +const core = __importStar(__nccwpck_require__(42186)); +const zlib = __importStar(__nccwpck_require__(59796)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const __1 = __nccwpck_require__(41359); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +const cloud_runner_statics_1 = __nccwpck_require__(90828); +const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); +class AWSTaskRunner { + static runTask(taskDef, ECS, CF, environment, buildGuid, commands) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; + return __awaiter(this, void 0, void 0, function* () { + const cluster = ((_b = (_a = taskDef.baseResources) === null || _a === void 0 ? void 0 : _a.find((x) => x.LogicalResourceId === 'ECSCluster')) === null || _b === void 0 ? void 0 : _b.PhysicalResourceId) || ''; + const taskDefinition = ((_d = (_c = taskDef.taskDefResources) === null || _c === void 0 ? void 0 : _c.find((x) => x.LogicalResourceId === 'TaskDefinition')) === null || _d === void 0 ? void 0 : _d.PhysicalResourceId) || ''; + const SubnetOne = ((_f = (_e = taskDef.baseResources) === null || _e === void 0 ? void 0 : _e.find((x) => x.LogicalResourceId === 'PublicSubnetOne')) === null || _f === void 0 ? void 0 : _f.PhysicalResourceId) || ''; + const SubnetTwo = ((_h = (_g = taskDef.baseResources) === null || _g === void 0 ? void 0 : _g.find((x) => x.LogicalResourceId === 'PublicSubnetTwo')) === null || _h === void 0 ? void 0 : _h.PhysicalResourceId) || ''; + const ContainerSecurityGroup = ((_k = (_j = taskDef.baseResources) === null || _j === void 0 ? void 0 : _j.find((x) => x.LogicalResourceId === 'ContainerSecurityGroup')) === null || _k === void 0 ? void 0 : _k.PhysicalResourceId) || ''; + const streamName = ((_m = (_l = taskDef.taskDefResources) === null || _l === void 0 ? void 0 : _l.find((x) => x.LogicalResourceId === 'KinesisStream')) === null || _m === void 0 ? void 0 : _m.PhysicalResourceId) || ''; + const task = yield ECS.runTask({ + cluster, + taskDefinition, + platformVersion: '1.4.0', + overrides: { + containerOverrides: [ + { + name: taskDef.taskDefStackName, + environment, + command: ['-c', cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.ProcessCommands(commands, cloud_runner_1.default.buildParameters)], + }, + ], + }, + launchType: 'FARGATE', + networkConfiguration: { + awsvpcConfiguration: { + subnets: [SubnetOne, SubnetTwo], + assignPublicIp: 'ENABLED', + securityGroups: [ContainerSecurityGroup], + }, + }, + }).promise(); + const taskArn = ((_o = task.tasks) === null || _o === void 0 ? void 0 : _o[0].taskArn) || ''; + cloud_runner_logger_1.default.log('Cloud runner job is starting'); + yield AWSTaskRunner.waitUntilTaskRunning(ECS, taskArn, cluster); + cloud_runner_logger_1.default.log(`Cloud runner job status is running ${(_p = (yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn))) === null || _p === void 0 ? void 0 : _p.lastStatus}`); + const output = yield this.streamLogsUntilTaskStops(ECS, CF, taskDef, cluster, taskArn, streamName); + const taskData = yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn); + const exitCode = (_q = taskData.containers) === null || _q === void 0 ? void 0 : _q[0].exitCode; + const wasSuccessful = exitCode === 0 || (exitCode === undefined && taskData.lastStatus === 'RUNNING'); + if (wasSuccessful) { + cloud_runner_logger_1.default.log(`Cloud runner job has finished successfully`); + return output; + } + else { + const message = `Cloud runner job exit code ${exitCode}`; + taskData.overrides = undefined; + taskData.attachments = undefined; + cloud_runner_logger_1.default.log(`${message} ${JSON.stringify(taskData, undefined, 4)}`); + throw new Error(message); + } + }); + } + static waitUntilTaskRunning(ECS, taskArn, cluster) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + try { + yield ECS.waitFor('tasksRunning', { tasks: [taskArn], cluster }).promise(); + } + catch (error_) { + const error = error_; + yield new Promise((resolve) => setTimeout(resolve, 3000)); + cloud_runner_logger_1.default.log(`Cloud runner job has ended ${(_a = (yield AWSTaskRunner.describeTasks(ECS, cluster, taskArn)).containers) === null || _a === void 0 ? void 0 : _a[0].lastStatus}`); + core.setFailed(error); + core.error(error); + } + }); + } + static describeTasks(ECS, clusterName, taskArn) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const tasks = yield ECS.describeTasks({ + cluster: clusterName, + tasks: [taskArn], + }).promise(); + if ((_a = tasks.tasks) === null || _a === void 0 ? void 0 : _a[0]) { + return (_b = tasks.tasks) === null || _b === void 0 ? void 0 : _b[0]; + } + else { + throw new Error('No task found'); + } + }); + } + static streamLogsUntilTaskStops(ECS, CF, taskDef, clusterName, taskArn, kinesisStreamName) { + return __awaiter(this, void 0, void 0, function* () { + const kinesis = new AWS.Kinesis(); + const stream = yield AWSTaskRunner.getLogStream(kinesis, kinesisStreamName); + let iterator = yield AWSTaskRunner.getLogIterator(kinesis, stream); + const logBaseUrl = `https://${__1.Input.region}.console.aws.amazon.com/cloudwatch/home?region=${CF.config.region}#logsV2:log-groups/log-group/${taskDef.taskDefStackName}`; + cloud_runner_logger_1.default.log(`You can also see the logs at AWS Cloud Watch: ${logBaseUrl}`); + let shouldReadLogs = true; + let timestamp = 0; + let output = ''; + while (shouldReadLogs) { + yield new Promise((resolve) => setTimeout(resolve, 1500)); + const taskData = yield AWSTaskRunner.describeTasks(ECS, clusterName, taskArn); + ({ timestamp, shouldReadLogs } = AWSTaskRunner.checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs)); + ({ iterator, shouldReadLogs, output } = yield AWSTaskRunner.handleLogStreamIteration(kinesis, iterator, shouldReadLogs, taskDef, output)); + } + return output; + }); + } + static handleLogStreamIteration(kinesis, iterator, shouldReadLogs, taskDef, output) { + return __awaiter(this, void 0, void 0, function* () { + const records = yield kinesis + .getRecords({ + ShardIterator: iterator, + }) + .promise(); + iterator = records.NextShardIterator || ''; + ({ shouldReadLogs, output } = AWSTaskRunner.logRecords(records, iterator, taskDef, shouldReadLogs, output)); + return { iterator, shouldReadLogs, output }; + }); + } + static checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs) { + if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) === 'UNKNOWN') { + cloud_runner_logger_1.default.log('## Cloud runner job unknwon'); + } + if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) !== 'RUNNING') { + if (timestamp === 0) { + cloud_runner_logger_1.default.log('## Cloud runner job stopped, streaming end of logs'); + timestamp = Date.now(); + } + if (timestamp !== 0 && Date.now() - timestamp > 30000) { + cloud_runner_logger_1.default.log('## Cloud runner status is not RUNNING for 30 seconds, last query for logs'); + shouldReadLogs = false; + } + cloud_runner_logger_1.default.log(`## Status of job: ${taskData.lastStatus}`); + } + return { timestamp, shouldReadLogs }; + } + static logRecords(records, iterator, taskDef, shouldReadLogs, output) { + if (records.Records.length > 0 && iterator) { + for (let index = 0; index < records.Records.length; index++) { + const json = JSON.parse(zlib.gunzipSync(Buffer.from(records.Records[index].Data, 'base64')).toString('utf8')); + if (json.messageType === 'DATA_MESSAGE') { + for (let logEventsIndex = 0; logEventsIndex < json.logEvents.length; logEventsIndex++) { + let message = json.logEvents[logEventsIndex].message; + if (json.logEvents[logEventsIndex].message.includes(`---${cloud_runner_1.default.buildParameters.logId}`)) { + cloud_runner_logger_1.default.log('End of log transmission received'); + shouldReadLogs = false; + } + else if (message.includes('Rebuilding Library because the asset database could not be found!')) { + core.warning('LIBRARY NOT FOUND!'); + } + message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + output += message; + } + cloud_runner_logger_1.default.log(message); + } + } + } + } + return { shouldReadLogs, output }; + } + static getLogStream(kinesis, kinesisStreamName) { + return __awaiter(this, void 0, void 0, function* () { + return yield kinesis + .describeStream({ + StreamName: kinesisStreamName, + }) + .promise(); + }); + } + static getLogIterator(kinesis, stream) { + return __awaiter(this, void 0, void 0, function* () { + return ((yield kinesis + .getShardIterator({ + ShardIteratorType: 'TRIM_HORIZON', + StreamName: stream.StreamDescription.StreamName, + ShardId: stream.StreamDescription.Shards[0].ShardId, + }) + .promise()).ShardIterator || ''); + }); + } +} +exports["default"] = AWSTaskRunner; /***/ }), @@ -1568,62 +1568,62 @@ exports["default"] = AWSTaskRunner; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AWSTemplates = void 0; -const fs = __importStar(__nccwpck_require__(57147)); -class AWSTemplates { - static getParameterTemplate(p1) { + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AWSTemplates = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +class AWSTemplates { + static getParameterTemplate(p1) { return ` ${p1}: Type: String Default: '' -`; - } - static getSecretTemplate(p1) { +`; + } + static getSecretTemplate(p1) { return ` ${p1}Secret: Type: AWS::SecretsManager::Secret Properties: Name: '${p1}' SecretString: !Ref ${p1} -`; - } - static getSecretDefinitionTemplate(p1, p2) { +`; + } + static getSecretDefinitionTemplate(p1, p2) { return ` - Name: '${p1}' ValueFrom: !Ref ${p2}Secret -`; - } - static insertAtTemplate(template, insertionKey, insertion) { - const index = template.search(insertionKey) + insertionKey.length + '\n'.length; - template = [template.slice(0, index), insertion, template.slice(index)].join(''); - return template; - } - static readTaskCloudFormationTemplate() { - return fs.readFileSync(`${__dirname}/cloud-formations/task-def-formation.yml`, 'utf8'); - } -} -exports.AWSTemplates = AWSTemplates; +`; + } + static insertAtTemplate(template, insertionKey, insertion) { + const index = template.search(insertionKey) + insertionKey.length + '\n'.length; + template = [template.slice(0, index), insertion, template.slice(index)].join(''); + return template; + } + static readTaskCloudFormationTemplate() { + return fs.readFileSync(`${__dirname}/cloud-formations/task-def-formation.yml`, 'utf8'); + } +} +exports.AWSTemplates = AWSTemplates; /***/ }), @@ -1632,114 +1632,114 @@ exports.AWSTemplates = AWSTemplates; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const SDK = __importStar(__nccwpck_require__(71786)); -const aws_task_runner_1 = __importDefault(__nccwpck_require__(74668)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const aws_job_stack_1 = __nccwpck_require__(85819); -const aws_base_stack_1 = __nccwpck_require__(28730); -const __1 = __nccwpck_require__(41359); -class AWSBuildEnvironment { - constructor(buildParameters) { - this.baseStackName = buildParameters.awsBaseStackName; - } - cleanupSharedResources( - // eslint-disable-next-line no-unused-vars - buildGuid, - // eslint-disable-next-line no-unused-vars - buildParameters, - // eslint-disable-next-line no-unused-vars - branchName, - // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { }); - } - setupSharedResources( - // eslint-disable-next-line no-unused-vars - buildGuid, - // eslint-disable-next-line no-unused-vars - buildParameters, - // eslint-disable-next-line no-unused-vars - branchName, - // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { }); - } - runTask(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = __1.Input.region; - const ECS = new SDK.ECS(); - const CF = new SDK.CloudFormation(); - cloud_runner_logger_1.default.log(`AWS Region: ${CF.config.region}`); - const entrypoint = ['/bin/sh']; - const startTimeMs = Date.now(); - yield new aws_base_stack_1.AWSBaseStack(this.baseStackName).setupBaseStack(CF); - const taskDef = yield new aws_job_stack_1.AWSJobStack(this.baseStackName).setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets); - let postRunTaskTimeMs; - let output = ''; - try { - const postSetupStacksTimeMs = Date.now(); - cloud_runner_logger_1.default.log(`Setup job time: ${Math.floor((postSetupStacksTimeMs - startTimeMs) / 1000)}s`); - output = yield aws_task_runner_1.default.runTask(taskDef, ECS, CF, environment, buildGuid, commands); - postRunTaskTimeMs = Date.now(); - cloud_runner_logger_1.default.log(`Run job time: ${Math.floor((postRunTaskTimeMs - postSetupStacksTimeMs) / 1000)}s`); - } - finally { - yield this.cleanupResources(CF, taskDef); - const postCleanupTimeMs = Date.now(); - if (postRunTaskTimeMs !== undefined) - cloud_runner_logger_1.default.log(`Cleanup job time: ${Math.floor((postCleanupTimeMs - postRunTaskTimeMs) / 1000)}s`); - } - return output; - }); - } - cleanupResources(CF, taskDef) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('Cleanup starting'); - yield CF.deleteStack({ - StackName: taskDef.taskDefStackName, - }).promise(); - yield CF.waitFor('stackDeleteComplete', { - StackName: taskDef.taskDefStackName, - }).promise(); - cloud_runner_logger_1.default.log(`Deleted Stack: ${taskDef.taskDefStackName}`); - cloud_runner_logger_1.default.log('Cleanup complete'); - }); - } -} -exports["default"] = AWSBuildEnvironment; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const SDK = __importStar(__nccwpck_require__(71786)); +const aws_task_runner_1 = __importDefault(__nccwpck_require__(74668)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const aws_job_stack_1 = __nccwpck_require__(85819); +const aws_base_stack_1 = __nccwpck_require__(28730); +const __1 = __nccwpck_require__(41359); +class AWSBuildEnvironment { + constructor(buildParameters) { + this.baseStackName = buildParameters.awsBaseStackName; + } + cleanupSharedResources( + // eslint-disable-next-line no-unused-vars + buildGuid, + // eslint-disable-next-line no-unused-vars + buildParameters, + // eslint-disable-next-line no-unused-vars + branchName, + // eslint-disable-next-line no-unused-vars + defaultSecretsArray) { + return __awaiter(this, void 0, void 0, function* () { }); + } + setupSharedResources( + // eslint-disable-next-line no-unused-vars + buildGuid, + // eslint-disable-next-line no-unused-vars + buildParameters, + // eslint-disable-next-line no-unused-vars + branchName, + // eslint-disable-next-line no-unused-vars + defaultSecretsArray) { + return __awaiter(this, void 0, void 0, function* () { }); + } + runTask(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { + return __awaiter(this, void 0, void 0, function* () { + process.env.AWS_REGION = __1.Input.region; + const ECS = new SDK.ECS(); + const CF = new SDK.CloudFormation(); + cloud_runner_logger_1.default.log(`AWS Region: ${CF.config.region}`); + const entrypoint = ['/bin/sh']; + const startTimeMs = Date.now(); + yield new aws_base_stack_1.AWSBaseStack(this.baseStackName).setupBaseStack(CF); + const taskDef = yield new aws_job_stack_1.AWSJobStack(this.baseStackName).setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets); + let postRunTaskTimeMs; + let output = ''; + try { + const postSetupStacksTimeMs = Date.now(); + cloud_runner_logger_1.default.log(`Setup job time: ${Math.floor((postSetupStacksTimeMs - startTimeMs) / 1000)}s`); + output = yield aws_task_runner_1.default.runTask(taskDef, ECS, CF, environment, buildGuid, commands); + postRunTaskTimeMs = Date.now(); + cloud_runner_logger_1.default.log(`Run job time: ${Math.floor((postRunTaskTimeMs - postSetupStacksTimeMs) / 1000)}s`); + } + finally { + yield this.cleanupResources(CF, taskDef); + const postCleanupTimeMs = Date.now(); + if (postRunTaskTimeMs !== undefined) + cloud_runner_logger_1.default.log(`Cleanup job time: ${Math.floor((postCleanupTimeMs - postRunTaskTimeMs) / 1000)}s`); + } + return output; + }); + } + cleanupResources(CF, taskDef) { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.log('Cleanup starting'); + yield CF.deleteStack({ + StackName: taskDef.taskDefStackName, + }).promise(); + yield CF.waitFor('stackDeleteComplete', { + StackName: taskDef.taskDefStackName, + }).promise(); + cloud_runner_logger_1.default.log(`Deleted Stack: ${taskDef.taskDefStackName}`); + cloud_runner_logger_1.default.log('Cleanup complete'); + }); + } +} +exports["default"] = AWSBuildEnvironment; /***/ }), @@ -1748,13 +1748,13 @@ exports["default"] = AWSBuildEnvironment; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunnerStatics = void 0; -class CloudRunnerStatics { -} -exports.CloudRunnerStatics = CloudRunnerStatics; -CloudRunnerStatics.logPrefix = `Cloud-Runner-System`; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunnerStatics = void 0; +class CloudRunnerStatics { +} +exports.CloudRunnerStatics = CloudRunnerStatics; +CloudRunnerStatics.logPrefix = `Cloud-Runner-System`; /***/ }), @@ -1763,17 +1763,17 @@ CloudRunnerStatics.logPrefix = `Cloud-Runner-System`; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunnerStepState = void 0; -class CloudRunnerStepState { - constructor(image, environmentVariables, secrets) { - this.image = image; - this.environment = environmentVariables; - this.secrets = secrets; - } -} -exports.CloudRunnerStepState = CloudRunnerStepState; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunnerStepState = void 0; +class CloudRunnerStepState { + constructor(image, environmentVariables, secrets) { + this.image = image; + this.environment = environmentVariables; + this.secrets = secrets; + } +} +exports.CloudRunnerStepState = CloudRunnerStepState; /***/ }), @@ -1782,100 +1782,100 @@ exports.CloudRunnerStepState = CloudRunnerStepState; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const aws_1 = __importDefault(__nccwpck_require__(37569)); -const k8s_1 = __importDefault(__nccwpck_require__(25107)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const cloud_runner_step_state_1 = __nccwpck_require__(50121); -const workflow_composition_root_1 = __nccwpck_require__(54204); -const cloud_runner_error_1 = __nccwpck_require__(91477); -const task_parameter_serializer_1 = __nccwpck_require__(35346); -const core = __importStar(__nccwpck_require__(42186)); -class CloudRunner { - static setup(buildParameters) { - cloud_runner_logger_1.default.setup(); - CloudRunner.buildParameters = buildParameters; - CloudRunner.setupBuildPlatform(); - const parameters = task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(); - if (!buildParameters.cliMode) { - for (const element of parameters) { - core.setOutput(element.name, element.value); - } - } - } - static setupBuildPlatform() { - switch (CloudRunner.buildParameters.cloudRunnerCluster) { - case 'k8s': - cloud_runner_logger_1.default.log('Cloud Runner platform selected Kubernetes'); - CloudRunner.CloudRunnerProviderPlatform = new k8s_1.default(CloudRunner.buildParameters); - break; - default: - case 'aws': - cloud_runner_logger_1.default.log('Cloud Runner platform selected AWS'); - CloudRunner.CloudRunnerProviderPlatform = new aws_1.default(CloudRunner.buildParameters); - break; - } - } - static run(buildParameters, baseImage) { - return __awaiter(this, void 0, void 0, function* () { - CloudRunner.setup(buildParameters); - try { - if (!CloudRunner.buildParameters.cliMode) - core.startGroup('Setup remote runner'); - yield CloudRunner.CloudRunnerProviderPlatform.setupSharedResources(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); - if (!CloudRunner.buildParameters.cliMode) - core.endGroup(); - const output = yield new workflow_composition_root_1.WorkflowCompositionRoot().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), CloudRunner.defaultSecrets)); - if (!CloudRunner.buildParameters.cliMode) - core.startGroup('Cleanup'); - yield CloudRunner.CloudRunnerProviderPlatform.cleanupSharedResources(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); - cloud_runner_logger_1.default.log(`Cleanup complete`); - if (!CloudRunner.buildParameters.cliMode) - core.endGroup(); - return output; - } - catch (error) { - if (!CloudRunner.buildParameters.cliMode) - core.endGroup(); - yield cloud_runner_error_1.CloudRunnerError.handleException(error); - throw error; - } - }); - } -} -exports["default"] = CloudRunner; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const aws_1 = __importDefault(__nccwpck_require__(37569)); +const k8s_1 = __importDefault(__nccwpck_require__(25107)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const cloud_runner_step_state_1 = __nccwpck_require__(50121); +const workflow_composition_root_1 = __nccwpck_require__(54204); +const cloud_runner_error_1 = __nccwpck_require__(91477); +const task_parameter_serializer_1 = __nccwpck_require__(35346); +const core = __importStar(__nccwpck_require__(42186)); +class CloudRunner { + static setup(buildParameters) { + cloud_runner_logger_1.default.setup(); + CloudRunner.buildParameters = buildParameters; + CloudRunner.setupBuildPlatform(); + const parameters = task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(); + if (!buildParameters.cliMode) { + for (const element of parameters) { + core.setOutput(element.name, element.value); + } + } + } + static setupBuildPlatform() { + switch (CloudRunner.buildParameters.cloudRunnerCluster) { + case 'k8s': + cloud_runner_logger_1.default.log('Cloud Runner platform selected Kubernetes'); + CloudRunner.CloudRunnerProviderPlatform = new k8s_1.default(CloudRunner.buildParameters); + break; + default: + case 'aws': + cloud_runner_logger_1.default.log('Cloud Runner platform selected AWS'); + CloudRunner.CloudRunnerProviderPlatform = new aws_1.default(CloudRunner.buildParameters); + break; + } + } + static run(buildParameters, baseImage) { + return __awaiter(this, void 0, void 0, function* () { + CloudRunner.setup(buildParameters); + try { + if (!CloudRunner.buildParameters.cliMode) + core.startGroup('Setup remote runner'); + yield CloudRunner.CloudRunnerProviderPlatform.setupSharedResources(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); + if (!CloudRunner.buildParameters.cliMode) + core.endGroup(); + const output = yield new workflow_composition_root_1.WorkflowCompositionRoot().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), CloudRunner.defaultSecrets)); + if (!CloudRunner.buildParameters.cliMode) + core.startGroup('Cleanup'); + yield CloudRunner.CloudRunnerProviderPlatform.cleanupSharedResources(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); + cloud_runner_logger_1.default.log(`Cleanup complete`); + if (!CloudRunner.buildParameters.cliMode) + core.endGroup(); + return output; + } + catch (error) { + if (!CloudRunner.buildParameters.cliMode) + core.endGroup(); + yield cloud_runner_error_1.CloudRunnerError.handleException(error); + throw error; + } + }); + } +} +exports["default"] = CloudRunner; /***/ }), @@ -1884,53 +1884,53 @@ exports["default"] = CloudRunner; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunnerError = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const core = __importStar(__nccwpck_require__(42186)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class CloudRunnerError { - static handleException(error) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.error(JSON.stringify(error, undefined, 4)); - core.setFailed('Cloud Runner failed'); - yield cloud_runner_1.default.CloudRunnerProviderPlatform.cleanupSharedResources(cloud_runner_1.default.buildParameters.buildGuid, cloud_runner_1.default.buildParameters, cloud_runner_1.default.buildParameters.branch, cloud_runner_1.default.defaultSecrets); - }); - } -} -exports.CloudRunnerError = CloudRunnerError; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunnerError = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const core = __importStar(__nccwpck_require__(42186)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class CloudRunnerError { + static handleException(error) { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.error(JSON.stringify(error, undefined, 4)); + core.setFailed('Cloud Runner failed'); + yield cloud_runner_1.default.CloudRunnerProviderPlatform.cleanupSharedResources(cloud_runner_1.default.buildParameters.buildGuid, cloud_runner_1.default.buildParameters, cloud_runner_1.default.buildParameters.branch, cloud_runner_1.default.defaultSecrets); + }); + } +} +exports.CloudRunnerError = CloudRunnerError; /***/ }), @@ -1939,197 +1939,197 @@ exports.CloudRunnerError = CloudRunnerError; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const k8s = __importStar(__nccwpck_require__(89679)); -const __1 = __nccwpck_require__(41359); -const core = __importStar(__nccwpck_require__(42186)); -const kubernetes_storage_1 = __importDefault(__nccwpck_require__(43951)); -const kubernetes_task_runner_1 = __importDefault(__nccwpck_require__(7181)); -const kubernetes_secret_1 = __importDefault(__nccwpck_require__(71586)); -const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); -const kubernetes_job_spec_factory_1 = __importDefault(__nccwpck_require__(1739)); -const kubernetes_service_account_1 = __importDefault(__nccwpck_require__(42915)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const kubernetes_rook_1 = __importDefault(__nccwpck_require__(20859)); -const depdency_override_service_1 = __importDefault(__nccwpck_require__(69862)); -class Kubernetes { - constructor(buildParameters) { - this.buildGuid = ''; - this.pvcName = ''; - this.secretName = ''; - this.jobName = ''; - this.podName = ''; - this.containerName = ''; - this.cleanupCronJobName = ''; - this.serviceAccountName = ''; - this.kubeConfig = new k8s.KubeConfig(); - this.kubeConfig.loadFromDefault(); - this.kubeClient = this.kubeConfig.makeApiClient(k8s.CoreV1Api); - this.kubeClientBatch = this.kubeConfig.makeApiClient(k8s.BatchV1Api); - cloud_runner_logger_1.default.log('Loaded default Kubernetes configuration for this environment'); - this.namespace = 'default'; - this.buildParameters = buildParameters; - } - setupSharedResources(buildGuid, buildParameters, - // eslint-disable-next-line no-unused-vars - branchName, - // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { - try { - this.pvcName = `unity-builder-pvc-${buildGuid}`; - this.cleanupCronJobName = `unity-builder-cronjob-${buildGuid}`; - this.serviceAccountName = `service-account-${buildGuid}`; - yield kubernetes_rook_1.default.InitRook(buildParameters.kubeStorageClass); - if (yield depdency_override_service_1.default.CheckHealth()) { - yield depdency_override_service_1.default.TryStartDependencies(); - } - yield kubernetes_storage_1.default.createPersistentVolumeClaim(buildParameters, this.pvcName, this.kubeClient, this.namespace); - yield kubernetes_service_account_1.default.createServiceAccount(this.serviceAccountName, this.namespace, this.kubeClient); - } - catch (error) { - throw error; - } - }); - } - runTask(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { - return __awaiter(this, void 0, void 0, function* () { - try { - // setup - this.buildGuid = buildGuid; - this.secretName = `build-credentials-${buildGuid}`; - this.jobName = `unity-builder-job-${buildGuid}`; - this.containerName = `main`; - yield kubernetes_secret_1.default.createSecret(secrets, this.secretName, this.namespace, this.kubeClient); - const jobSpec = kubernetes_job_spec_factory_1.default.getJobSpec(commands, image, mountdir, workingdir, environment, secrets, this.buildGuid, this.buildParameters, this.secretName, this.pvcName, this.jobName, k8s); - //run - const jobResult = yield this.kubeClientBatch.createNamespacedJob(this.namespace, jobSpec); - cloud_runner_logger_1.default.log(`Creating build job ${JSON.stringify(jobResult.body.metadata, undefined, 4)}`); - yield new Promise((promise) => setTimeout(promise, 5000)); - cloud_runner_logger_1.default.log('Job created'); - this.setPodNameAndContainerName(yield Kubernetes.findPodFromJob(this.kubeClient, this.jobName, this.namespace)); - cloud_runner_logger_1.default.log('Watching pod until running'); - let output = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - try { - yield kubernetes_task_runner_1.default.watchUntilPodRunning(this.kubeClient, this.podName, this.namespace); - cloud_runner_logger_1.default.log('Pod running, streaming logs'); - output = yield kubernetes_task_runner_1.default.runTask(this.kubeConfig, this.kubeClient, this.jobName, this.podName, 'main', this.namespace, cloud_runner_logger_1.default.log); - break; - } - catch (error) { - if (error.message.includes(`HTTP`)) { - continue; - } - else { - throw error; - } - } - } - yield this.cleanupTaskResources(); - return output; - } - catch (error) { - cloud_runner_logger_1.default.log('Running job failed'); - core.error(JSON.stringify(error, undefined, 4)); - yield this.cleanupTaskResources(); - throw error; - } - }); - } - setPodNameAndContainerName(pod) { - var _a, _b, _c; - this.podName = ((_a = pod.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; - this.containerName = ((_c = (_b = pod.status) === null || _b === void 0 ? void 0 : _b.containerStatuses) === null || _c === void 0 ? void 0 : _c[0].name) || ''; - } - cleanupTaskResources() { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('cleaning up'); - try { - yield this.kubeClientBatch.deleteNamespacedJob(this.jobName, this.namespace); - yield this.kubeClient.deleteNamespacedPod(this.podName, this.namespace); - yield this.kubeClient.deleteNamespacedSecret(this.secretName, this.namespace); - yield new Promise((promise) => setTimeout(promise, 5000)); - } - catch (error) { - cloud_runner_logger_1.default.log('Failed to cleanup, error:'); - core.error(JSON.stringify(error, undefined, 4)); - cloud_runner_logger_1.default.log('Abandoning cleanup, build error:'); - throw error; - } - try { - yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { - var _b; - const jobBody = (yield this.kubeClientBatch.readNamespacedJob(this.jobName, this.namespace)).body; - const podBody = (yield this.kubeClient.readNamespacedPod(this.podName, this.namespace)).body; - return (jobBody === null || ((_b = jobBody.status) === null || _b === void 0 ? void 0 : _b.active) === 0) && podBody === null; - }), { - timeout: 500000, - intervalBetweenAttempts: 15000, - }); - // eslint-disable-next-line no-empty - } - catch (_a) { } - }); - } - cleanupSharedResources(buildGuid, buildParameters, - // eslint-disable-next-line no-unused-vars - branchName, - // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(`deleting PVC`); - yield this.kubeClient.deleteNamespacedPersistentVolumeClaim(this.pvcName, this.namespace); - yield __1.Output.setBuildVersion(buildParameters.buildVersion); - // eslint-disable-next-line unicorn/no-process-exit - process.exit(); - }); - } - static findPodFromJob(kubeClient, jobName, namespace) { - return __awaiter(this, void 0, void 0, function* () { - const namespacedPods = yield kubeClient.listNamespacedPod(namespace); - const pod = namespacedPods.body.items.find((x) => { var _a, _b; return ((_b = (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b['job-name']) === jobName; }); - if (pod === undefined) { - throw new Error("pod with job-name label doesn't exist"); - } - return pod; - }); - } -} -exports["default"] = Kubernetes; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const k8s = __importStar(__nccwpck_require__(89679)); +const __1 = __nccwpck_require__(41359); +const core = __importStar(__nccwpck_require__(42186)); +const kubernetes_storage_1 = __importDefault(__nccwpck_require__(43951)); +const kubernetes_task_runner_1 = __importDefault(__nccwpck_require__(7181)); +const kubernetes_secret_1 = __importDefault(__nccwpck_require__(71586)); +const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); +const kubernetes_job_spec_factory_1 = __importDefault(__nccwpck_require__(1739)); +const kubernetes_service_account_1 = __importDefault(__nccwpck_require__(42915)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const kubernetes_rook_1 = __importDefault(__nccwpck_require__(20859)); +const depdency_override_service_1 = __importDefault(__nccwpck_require__(69862)); +class Kubernetes { + constructor(buildParameters) { + this.buildGuid = ''; + this.pvcName = ''; + this.secretName = ''; + this.jobName = ''; + this.podName = ''; + this.containerName = ''; + this.cleanupCronJobName = ''; + this.serviceAccountName = ''; + this.kubeConfig = new k8s.KubeConfig(); + this.kubeConfig.loadFromDefault(); + this.kubeClient = this.kubeConfig.makeApiClient(k8s.CoreV1Api); + this.kubeClientBatch = this.kubeConfig.makeApiClient(k8s.BatchV1Api); + cloud_runner_logger_1.default.log('Loaded default Kubernetes configuration for this environment'); + this.namespace = 'default'; + this.buildParameters = buildParameters; + } + setupSharedResources(buildGuid, buildParameters, + // eslint-disable-next-line no-unused-vars + branchName, + // eslint-disable-next-line no-unused-vars + defaultSecretsArray) { + return __awaiter(this, void 0, void 0, function* () { + try { + this.pvcName = `unity-builder-pvc-${buildGuid}`; + this.cleanupCronJobName = `unity-builder-cronjob-${buildGuid}`; + this.serviceAccountName = `service-account-${buildGuid}`; + yield kubernetes_rook_1.default.InitRook(buildParameters.kubeStorageClass); + if (yield depdency_override_service_1.default.CheckHealth()) { + yield depdency_override_service_1.default.TryStartDependencies(); + } + yield kubernetes_storage_1.default.createPersistentVolumeClaim(buildParameters, this.pvcName, this.kubeClient, this.namespace); + yield kubernetes_service_account_1.default.createServiceAccount(this.serviceAccountName, this.namespace, this.kubeClient); + } + catch (error) { + throw error; + } + }); + } + runTask(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { + return __awaiter(this, void 0, void 0, function* () { + try { + // setup + this.buildGuid = buildGuid; + this.secretName = `build-credentials-${buildGuid}`; + this.jobName = `unity-builder-job-${buildGuid}`; + this.containerName = `main`; + yield kubernetes_secret_1.default.createSecret(secrets, this.secretName, this.namespace, this.kubeClient); + const jobSpec = kubernetes_job_spec_factory_1.default.getJobSpec(commands, image, mountdir, workingdir, environment, secrets, this.buildGuid, this.buildParameters, this.secretName, this.pvcName, this.jobName, k8s); + //run + const jobResult = yield this.kubeClientBatch.createNamespacedJob(this.namespace, jobSpec); + cloud_runner_logger_1.default.log(`Creating build job ${JSON.stringify(jobResult.body.metadata, undefined, 4)}`); + yield new Promise((promise) => setTimeout(promise, 5000)); + cloud_runner_logger_1.default.log('Job created'); + this.setPodNameAndContainerName(yield Kubernetes.findPodFromJob(this.kubeClient, this.jobName, this.namespace)); + cloud_runner_logger_1.default.log('Watching pod until running'); + let output = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + try { + yield kubernetes_task_runner_1.default.watchUntilPodRunning(this.kubeClient, this.podName, this.namespace); + cloud_runner_logger_1.default.log('Pod running, streaming logs'); + output = yield kubernetes_task_runner_1.default.runTask(this.kubeConfig, this.kubeClient, this.jobName, this.podName, 'main', this.namespace, cloud_runner_logger_1.default.log); + break; + } + catch (error) { + if (error.message.includes(`HTTP`)) { + continue; + } + else { + throw error; + } + } + } + yield this.cleanupTaskResources(); + return output; + } + catch (error) { + cloud_runner_logger_1.default.log('Running job failed'); + core.error(JSON.stringify(error, undefined, 4)); + yield this.cleanupTaskResources(); + throw error; + } + }); + } + setPodNameAndContainerName(pod) { + var _a, _b, _c; + this.podName = ((_a = pod.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; + this.containerName = ((_c = (_b = pod.status) === null || _b === void 0 ? void 0 : _b.containerStatuses) === null || _c === void 0 ? void 0 : _c[0].name) || ''; + } + cleanupTaskResources() { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.log('cleaning up'); + try { + yield this.kubeClientBatch.deleteNamespacedJob(this.jobName, this.namespace); + yield this.kubeClient.deleteNamespacedPod(this.podName, this.namespace); + yield this.kubeClient.deleteNamespacedSecret(this.secretName, this.namespace); + yield new Promise((promise) => setTimeout(promise, 5000)); + } + catch (error) { + cloud_runner_logger_1.default.log('Failed to cleanup, error:'); + core.error(JSON.stringify(error, undefined, 4)); + cloud_runner_logger_1.default.log('Abandoning cleanup, build error:'); + throw error; + } + try { + yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { + var _b; + const jobBody = (yield this.kubeClientBatch.readNamespacedJob(this.jobName, this.namespace)).body; + const podBody = (yield this.kubeClient.readNamespacedPod(this.podName, this.namespace)).body; + return (jobBody === null || ((_b = jobBody.status) === null || _b === void 0 ? void 0 : _b.active) === 0) && podBody === null; + }), { + timeout: 500000, + intervalBetweenAttempts: 15000, + }); + // eslint-disable-next-line no-empty + } + catch (_a) { } + }); + } + cleanupSharedResources(buildGuid, buildParameters, + // eslint-disable-next-line no-unused-vars + branchName, + // eslint-disable-next-line no-unused-vars + defaultSecretsArray) { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.log(`deleting PVC`); + yield this.kubeClient.deleteNamespacedPersistentVolumeClaim(this.pvcName, this.namespace); + yield __1.Output.setBuildVersion(buildParameters.buildVersion); + // eslint-disable-next-line unicorn/no-process-exit + process.exit(); + }); + } + static findPodFromJob(kubeClient, jobName, namespace) { + return __awaiter(this, void 0, void 0, function* () { + const namespacedPods = yield kubeClient.listNamespacedPod(namespace); + const pod = namespacedPods.body.items.find((x) => { var _a, _b; return ((_b = (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b['job-name']) === jobName; }); + if (pod === undefined) { + throw new Error("pod with job-name label doesn't exist"); + } + return pod; + }); + } +} +exports["default"] = Kubernetes; /***/ }), @@ -2138,152 +2138,152 @@ exports["default"] = Kubernetes; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const client_node_1 = __nccwpck_require__(89679); -const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class KubernetesJobSpecFactory { - static getJobSpec(command, image, mountdir, workingDirectory, environment, secrets, buildGuid, buildParameters, secretName, pvcName, jobName, k8s) { - environment.push(...[ - { - name: 'GITHUB_SHA', - value: buildGuid, - }, - { - name: 'GITHUB_WORKSPACE', - value: '/data/repo', - }, - { - name: 'PROJECT_PATH', - value: buildParameters.projectPath, - }, - { - name: 'BUILD_PATH', - value: buildParameters.buildPath, - }, - { - name: 'BUILD_FILE', - value: buildParameters.buildFile, - }, - { - name: 'BUILD_NAME', - value: buildParameters.buildName, - }, - { - name: 'BUILD_METHOD', - value: buildParameters.buildMethod, - }, - { - name: 'CUSTOM_PARAMETERS', - value: buildParameters.customParameters, - }, - { - name: 'CHOWN_FILES_TO', - value: buildParameters.chownFilesTo, - }, - { - name: 'BUILD_TARGET', - value: buildParameters.platform, - }, - { - name: 'ANDROID_VERSION_CODE', - value: buildParameters.androidVersionCode.toString(), - }, - { - name: 'ANDROID_KEYSTORE_NAME', - value: buildParameters.androidKeystoreName, - }, - { - name: 'ANDROID_KEYALIAS_NAME', - value: buildParameters.androidKeyaliasName, - }, - ]); - const job = new k8s.V1Job(); - job.apiVersion = 'batch/v1'; - job.kind = 'Job'; - job.metadata = { - name: jobName, - labels: { - app: 'unity-builder', - buildGuid, - }, - }; - job.spec = { - backoffLimit: 0, - template: { - spec: { - volumes: [ - { - name: 'build-mount', - persistentVolumeClaim: { - claimName: pvcName, - }, - }, - ], - containers: [ - { - name: 'main', - image, - command: ['/bin/sh'], - args: ['-c', cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.ProcessCommands(command, cloud_runner_1.default.buildParameters)], - workingDir: `${workingDirectory}`, - resources: { - requests: { - memory: buildParameters.cloudRunnerMemory, - cpu: buildParameters.cloudRunnerCpu, - }, - }, - env: [ - ...environment.map((x) => { - const environmentVariable = new client_node_1.V1EnvVar(); - environmentVariable.name = x.name; - environmentVariable.value = x.value; - return environmentVariable; - }), - ...secrets.map((x) => { - const secret = new client_node_1.V1EnvVarSource(); - secret.secretKeyRef = new client_node_1.V1SecretKeySelector(); - secret.secretKeyRef.key = x.ParameterKey; - secret.secretKeyRef.name = secretName; - const environmentVariable = new client_node_1.V1EnvVar(); - environmentVariable.name = x.EnvironmentVariable; - environmentVariable.valueFrom = secret; - return environmentVariable; - }), - ], - volumeMounts: [ - { - name: 'build-mount', - mountPath: `/${mountdir}`, - }, - ], - lifecycle: { - preStop: { - exec: { - command: [ - 'bin/bash', - '-c', + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const client_node_1 = __nccwpck_require__(89679); +const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class KubernetesJobSpecFactory { + static getJobSpec(command, image, mountdir, workingDirectory, environment, secrets, buildGuid, buildParameters, secretName, pvcName, jobName, k8s) { + environment.push(...[ + { + name: 'GITHUB_SHA', + value: buildGuid, + }, + { + name: 'GITHUB_WORKSPACE', + value: '/data/repo', + }, + { + name: 'PROJECT_PATH', + value: buildParameters.projectPath, + }, + { + name: 'BUILD_PATH', + value: buildParameters.buildPath, + }, + { + name: 'BUILD_FILE', + value: buildParameters.buildFile, + }, + { + name: 'BUILD_NAME', + value: buildParameters.buildName, + }, + { + name: 'BUILD_METHOD', + value: buildParameters.buildMethod, + }, + { + name: 'CUSTOM_PARAMETERS', + value: buildParameters.customParameters, + }, + { + name: 'CHOWN_FILES_TO', + value: buildParameters.chownFilesTo, + }, + { + name: 'BUILD_TARGET', + value: buildParameters.platform, + }, + { + name: 'ANDROID_VERSION_CODE', + value: buildParameters.androidVersionCode.toString(), + }, + { + name: 'ANDROID_KEYSTORE_NAME', + value: buildParameters.androidKeystoreName, + }, + { + name: 'ANDROID_KEYALIAS_NAME', + value: buildParameters.androidKeyaliasName, + }, + ]); + const job = new k8s.V1Job(); + job.apiVersion = 'batch/v1'; + job.kind = 'Job'; + job.metadata = { + name: jobName, + labels: { + app: 'unity-builder', + buildGuid, + }, + }; + job.spec = { + backoffLimit: 0, + template: { + spec: { + volumes: [ + { + name: 'build-mount', + persistentVolumeClaim: { + claimName: pvcName, + }, + }, + ], + containers: [ + { + name: 'main', + image, + command: ['/bin/sh'], + args: ['-c', cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.ProcessCommands(command, cloud_runner_1.default.buildParameters)], + workingDir: `${workingDirectory}`, + resources: { + requests: { + memory: buildParameters.cloudRunnerMemory, + cpu: buildParameters.cloudRunnerCpu, + }, + }, + env: [ + ...environment.map((x) => { + const environmentVariable = new client_node_1.V1EnvVar(); + environmentVariable.name = x.name; + environmentVariable.value = x.value; + return environmentVariable; + }), + ...secrets.map((x) => { + const secret = new client_node_1.V1EnvVarSource(); + secret.secretKeyRef = new client_node_1.V1SecretKeySelector(); + secret.secretKeyRef.key = x.ParameterKey; + secret.secretKeyRef.name = secretName; + const environmentVariable = new client_node_1.V1EnvVar(); + environmentVariable.name = x.EnvironmentVariable; + environmentVariable.valueFrom = secret; + return environmentVariable; + }), + ], + volumeMounts: [ + { + name: 'build-mount', + mountPath: `/${mountdir}`, + }, + ], + lifecycle: { + preStop: { + exec: { + command: [ + 'bin/bash', + '-c', `cd /data/builder/action/steps; chmod +x /return_license.sh; - /return_license.sh;`, - ], - }, - }, - }, - }, - ], - restartPolicy: 'Never', - }, - }, - }; - return job; - } -} -exports["default"] = KubernetesJobSpecFactory; + /return_license.sh;`, + ], + }, + }, + }, + }, + ], + restartPolicy: 'Never', + }, + }, + }; + return job; + } +} +exports["default"] = KubernetesJobSpecFactory; /***/ }), @@ -2292,35 +2292,35 @@ exports["default"] = KubernetesJobSpecFactory; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const cloud_runner_system_1 = __nccwpck_require__(66879); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -class KubernetesRook { - static InitRook(storageName) { - return __awaiter(this, void 0, void 0, function* () { - if (storageName === '' && (yield cloud_runner_system_1.CloudRunnerSystem.Run(`kubectl`))) { - storageName = KubernetesRook.rookStorageName; - cloud_runner_logger_1.default.log('Using rook storage as no kubeStorageClass provided'); + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const cloud_runner_system_1 = __nccwpck_require__(66879); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +class KubernetesRook { + static InitRook(storageName) { + return __awaiter(this, void 0, void 0, function* () { + if (storageName === '' && (yield cloud_runner_system_1.CloudRunnerSystem.Run(`kubectl`))) { + storageName = KubernetesRook.rookStorageName; + cloud_runner_logger_1.default.log('Using rook storage as no kubeStorageClass provided'); yield cloud_runner_system_1.CloudRunnerSystem.Run(` git clone --single-branch --branch v1.8.6 https://github.com/rook/rook.git cd rook/deploy/examples kubectl apply -f crds.yaml -f common.yaml -f operator.yaml kubectl apply -f cluster.yaml - `); + `); fs_1.default.writeFileSync('filesystem.yaml', ` apiVersion: ceph.rook.io/v1 kind: CephFilesystem @@ -2339,7 +2339,7 @@ class KubernetesRook { metadataServer: activeCount: 1 activeStandby: true - `); + `); fs_1.default.writeFileSync('storageclass.yaml', ` apiVersion: storage.k8s.io/v1 kind: StorageClass @@ -2368,19 +2368,19 @@ class KubernetesRook { csi.storage.k8s.io/node-stage-secret-name: rook-csi-cephfs-node csi.storage.k8s.io/node-stage-secret-namespace: rook-ceph reclaimPolicy: Delete - `); + `); yield cloud_runner_system_1.CloudRunnerSystem.Run(` kubectl apply -f storageclass.yaml -f filesystem.yaml - `); - } - else { - cloud_runner_logger_1.default.log(`Using kubeStorageClass ${storageName}`); - } - }); - } -} -KubernetesRook.rookStorageName = 'rook-cephfs-game-ci'; -exports["default"] = KubernetesRook; + `); + } + else { + cloud_runner_logger_1.default.log(`Using kubeStorageClass ${storageName}`); + } + }); + } +} +KubernetesRook.rookStorageName = 'rook-cephfs-game-ci'; +exports["default"] = KubernetesRook; /***/ }), @@ -2389,57 +2389,57 @@ exports["default"] = KubernetesRook; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const k8s = __importStar(__nccwpck_require__(89679)); -const base64 = __nccwpck_require__(85848); -class KubernetesSecret { - static createSecret(secrets, secretName, namespace, kubeClient) { - return __awaiter(this, void 0, void 0, function* () { - const secret = new k8s.V1Secret(); - secret.apiVersion = 'v1'; - secret.kind = 'Secret'; - secret.type = 'Opaque'; - secret.metadata = { - name: secretName, - }; - secret.data = {}; - for (const buildSecret of secrets) { - secret.data[buildSecret.ParameterKey] = base64.encode(buildSecret.ParameterValue); - } - return kubeClient.createNamespacedSecret(namespace, secret); - }); - } -} -exports["default"] = KubernetesSecret; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const k8s = __importStar(__nccwpck_require__(89679)); +const base64 = __nccwpck_require__(85848); +class KubernetesSecret { + static createSecret(secrets, secretName, namespace, kubeClient) { + return __awaiter(this, void 0, void 0, function* () { + const secret = new k8s.V1Secret(); + secret.apiVersion = 'v1'; + secret.kind = 'Secret'; + secret.type = 'Opaque'; + secret.metadata = { + name: secretName, + }; + secret.data = {}; + for (const buildSecret of secrets) { + secret.data[buildSecret.ParameterKey] = base64.encode(buildSecret.ParameterValue); + } + return kubeClient.createNamespacedSecret(namespace, secret); + }); + } +} +exports["default"] = KubernetesSecret; /***/ }), @@ -2448,52 +2448,52 @@ exports["default"] = KubernetesSecret; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const k8s = __importStar(__nccwpck_require__(89679)); -class KubernetesServiceAccount { - static createServiceAccount(serviceAccountName, namespace, kubeClient) { - return __awaiter(this, void 0, void 0, function* () { - const serviceAccount = new k8s.V1ServiceAccount(); - serviceAccount.apiVersion = 'v1'; - serviceAccount.kind = 'ServiceAccount'; - serviceAccount.metadata = { - name: serviceAccountName, - }; - serviceAccount.automountServiceAccountToken = false; - return kubeClient.createNamespacedServiceAccount(namespace, serviceAccount); - }); - } -} -exports["default"] = KubernetesServiceAccount; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const k8s = __importStar(__nccwpck_require__(89679)); +class KubernetesServiceAccount { + static createServiceAccount(serviceAccountName, namespace, kubeClient) { + return __awaiter(this, void 0, void 0, function* () { + const serviceAccount = new k8s.V1ServiceAccount(); + serviceAccount.apiVersion = 'v1'; + serviceAccount.kind = 'ServiceAccount'; + serviceAccount.metadata = { + name: serviceAccountName, + }; + serviceAccount.automountServiceAccountToken = false; + return kubeClient.createNamespacedServiceAccount(namespace, serviceAccount); + }); + } +} +exports["default"] = KubernetesServiceAccount; /***/ }), @@ -2502,137 +2502,137 @@ exports["default"] = KubernetesServiceAccount; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); -const core = __importStar(__nccwpck_require__(42186)); -const k8s = __importStar(__nccwpck_require__(89679)); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const yaml_1 = __importDefault(__nccwpck_require__(44603)); -const kubernetes_rook_1 = __importDefault(__nccwpck_require__(20859)); -class KubernetesStorage { - static createPersistentVolumeClaim(buildParameters, pvcName, kubeClient, namespace) { - return __awaiter(this, void 0, void 0, function* () { - if (buildParameters.kubeVolume) { - cloud_runner_logger_1.default.log(buildParameters.kubeVolume); - pvcName = buildParameters.kubeVolume; - return; - } - const pvcList = (yield kubeClient.listNamespacedPersistentVolumeClaim(namespace)).body.items.map((x) => { var _a; return (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name; }); - cloud_runner_logger_1.default.log(`Current PVCs in namespace ${namespace}`); - cloud_runner_logger_1.default.log(JSON.stringify(pvcList, undefined, 4)); - if (pvcList.includes(pvcName)) { - cloud_runner_logger_1.default.log(`pvc ${pvcName} already exists`); - if (!buildParameters.cliMode) { - core.setOutput('volume', pvcName); - } - return; - } - cloud_runner_logger_1.default.log(`Creating PVC ${pvcName} (does not exist)`); - const result = yield KubernetesStorage.createPVC(pvcName, buildParameters, kubeClient, namespace); - yield KubernetesStorage.handleResult(result, kubeClient, namespace, pvcName); - }); - } - static getPVCPhase(kubeClient, name, namespace) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - try { - return (_a = (yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body.status) === null || _a === void 0 ? void 0 : _a.phase; - } - catch (error) { - core.error('Failed to get PVC phase'); - core.error(JSON.stringify(error, undefined, 4)); - throw error; - } - }); - } - static watchUntilPVCNotPending(kubeClient, name, namespace) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`watch Until PVC Not Pending ${name} ${namespace}`); - cloud_runner_logger_1.default.log(`${yield this.getPVCPhase(kubeClient, name, namespace)}`); - yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { - return (yield this.getPVCPhase(kubeClient, name, namespace)) !== 'Pending'; - }), { - timeout: 750000, - intervalBetweenAttempts: 15000, - }); - } - catch (error) { - core.error('Failed to watch PVC'); - core.error(error.toString()); - core.error(`PVC Body: ${JSON.stringify((yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body, undefined, 4)}`); - throw error; - } - }); - } - static createPVC(pvcName, buildParameters, kubeClient, namespace) { - return __awaiter(this, void 0, void 0, function* () { - const pvc = new k8s.V1PersistentVolumeClaim(); - pvc.apiVersion = 'v1'; - pvc.kind = 'PersistentVolumeClaim'; - pvc.metadata = { - name: pvcName, - }; - pvc.spec = { - accessModes: ['ReadWriteOnce'], - storageClassName: buildParameters.kubeStorageClass === '' ? kubernetes_rook_1.default.rookStorageName : buildParameters.kubeStorageClass, - resources: { - requests: { - storage: buildParameters.kubeVolumeSize, - }, - }, - }; - if (process.env.K8s_STORAGE_PVC_SPEC) { - yaml_1.default.parse(process.env.K8s_STORAGE_PVC_SPEC); - } - const result = yield kubeClient.createNamespacedPersistentVolumeClaim(namespace, pvc); - return result; - }); - } - static handleResult(result, kubeClient, namespace, pvcName) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const name = ((_a = result.body.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; - cloud_runner_logger_1.default.log(`PVC ${name} created`); - yield this.watchUntilPVCNotPending(kubeClient, name, namespace); - cloud_runner_logger_1.default.log(`PVC ${name} is ready and not pending`); - core.setOutput('volume', pvcName); - }); - } -} -exports["default"] = KubernetesStorage; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); +const core = __importStar(__nccwpck_require__(42186)); +const k8s = __importStar(__nccwpck_require__(89679)); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const yaml_1 = __importDefault(__nccwpck_require__(44603)); +const kubernetes_rook_1 = __importDefault(__nccwpck_require__(20859)); +class KubernetesStorage { + static createPersistentVolumeClaim(buildParameters, pvcName, kubeClient, namespace) { + return __awaiter(this, void 0, void 0, function* () { + if (buildParameters.kubeVolume) { + cloud_runner_logger_1.default.log(buildParameters.kubeVolume); + pvcName = buildParameters.kubeVolume; + return; + } + const pvcList = (yield kubeClient.listNamespacedPersistentVolumeClaim(namespace)).body.items.map((x) => { var _a; return (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name; }); + cloud_runner_logger_1.default.log(`Current PVCs in namespace ${namespace}`); + cloud_runner_logger_1.default.log(JSON.stringify(pvcList, undefined, 4)); + if (pvcList.includes(pvcName)) { + cloud_runner_logger_1.default.log(`pvc ${pvcName} already exists`); + if (!buildParameters.cliMode) { + core.setOutput('volume', pvcName); + } + return; + } + cloud_runner_logger_1.default.log(`Creating PVC ${pvcName} (does not exist)`); + const result = yield KubernetesStorage.createPVC(pvcName, buildParameters, kubeClient, namespace); + yield KubernetesStorage.handleResult(result, kubeClient, namespace, pvcName); + }); + } + static getPVCPhase(kubeClient, name, namespace) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + try { + return (_a = (yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body.status) === null || _a === void 0 ? void 0 : _a.phase; + } + catch (error) { + core.error('Failed to get PVC phase'); + core.error(JSON.stringify(error, undefined, 4)); + throw error; + } + }); + } + static watchUntilPVCNotPending(kubeClient, name, namespace) { + return __awaiter(this, void 0, void 0, function* () { + try { + cloud_runner_logger_1.default.log(`watch Until PVC Not Pending ${name} ${namespace}`); + cloud_runner_logger_1.default.log(`${yield this.getPVCPhase(kubeClient, name, namespace)}`); + yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { + return (yield this.getPVCPhase(kubeClient, name, namespace)) !== 'Pending'; + }), { + timeout: 750000, + intervalBetweenAttempts: 15000, + }); + } + catch (error) { + core.error('Failed to watch PVC'); + core.error(error.toString()); + core.error(`PVC Body: ${JSON.stringify((yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body, undefined, 4)}`); + throw error; + } + }); + } + static createPVC(pvcName, buildParameters, kubeClient, namespace) { + return __awaiter(this, void 0, void 0, function* () { + const pvc = new k8s.V1PersistentVolumeClaim(); + pvc.apiVersion = 'v1'; + pvc.kind = 'PersistentVolumeClaim'; + pvc.metadata = { + name: pvcName, + }; + pvc.spec = { + accessModes: ['ReadWriteOnce'], + storageClassName: buildParameters.kubeStorageClass === '' ? kubernetes_rook_1.default.rookStorageName : buildParameters.kubeStorageClass, + resources: { + requests: { + storage: buildParameters.kubeVolumeSize, + }, + }, + }; + if (process.env.K8s_STORAGE_PVC_SPEC) { + yaml_1.default.parse(process.env.K8s_STORAGE_PVC_SPEC); + } + const result = yield kubeClient.createNamespacedPersistentVolumeClaim(namespace, pvc); + return result; + }); + } + static handleResult(result, kubeClient, namespace, pvcName) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const name = ((_a = result.body.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; + cloud_runner_logger_1.default.log(`PVC ${name} created`); + yield this.watchUntilPVCNotPending(kubeClient, name, namespace); + cloud_runner_logger_1.default.log(`PVC ${name} is ready and not pending`); + core.setOutput('volume', pvcName); + }); + } +} +exports["default"] = KubernetesStorage; /***/ }), @@ -2641,124 +2641,124 @@ exports["default"] = KubernetesStorage; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const client_node_1 = __nccwpck_require__(89679); -const stream_1 = __nccwpck_require__(12781); -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const core = __importStar(__nccwpck_require__(42186)); -const cloud_runner_statics_1 = __nccwpck_require__(90828); -const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class KubernetesTaskRunner { - static runTask(kubeConfig, kubeClient, jobName, podName, containerName, namespace, logCallback) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(`Streaming logs from pod: ${podName} container: ${containerName} namespace: ${namespace}`); - const stream = new stream_1.Writable(); - let output = ''; - let didStreamAnyLogs = false; - stream._write = (chunk, encoding, next) => { - didStreamAnyLogs = true; - let message = chunk.toString().trimRight(`\n`); - message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; - if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { - output += message; - } - logCallback(message); - next(); - }; - const logOptions = { - follow: true, - pretty: false, - previous: false, - }; - try { - const resultError = yield new Promise((resolve) => new client_node_1.Log(kubeConfig).log(namespace, podName, containerName, stream, resolve, logOptions)); - stream.destroy(); - if (resultError) { - throw resultError; - } - if (!didStreamAnyLogs) { - core.error('Failed to stream any logs, listing namespace events, check for an error with the container'); - core.error(JSON.stringify({ - events: (yield kubeClient.listNamespacedEvent(namespace)).body.items - .filter((x) => { - return x.involvedObject.name === podName || x.involvedObject.name === jobName; - }) - .map((x) => { - return { - type: x.involvedObject.kind, - name: x.involvedObject.name, - message: x.message, - }; - }), - }, undefined, 4)); - throw new Error(`No logs streamed from k8s`); - } - } - catch (error) { - if (stream) { - stream.destroy(); - } - throw error; - } - cloud_runner_logger_1.default.log('end of log stream'); - return output; - }); - } - static watchUntilPodRunning(kubeClient, podName, namespace) { - return __awaiter(this, void 0, void 0, function* () { - let success = false; - cloud_runner_logger_1.default.log(`Watching ${podName} ${namespace}`); - yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { - var _a, _b, _c, _d, _e, _f; - const status = yield kubeClient.readNamespacedPodStatus(podName, namespace); - const phase = (_a = status === null || status === void 0 ? void 0 : status.body.status) === null || _a === void 0 ? void 0 : _a.phase; - success = phase === 'Running'; - cloud_runner_logger_1.default.log(`${(_b = status.body.status) === null || _b === void 0 ? void 0 : _b.phase} ${((_d = (_c = status.body.status) === null || _c === void 0 ? void 0 : _c.conditions) === null || _d === void 0 ? void 0 : _d[0].reason) || ''} ${((_f = (_e = status.body.status) === null || _e === void 0 ? void 0 : _e.conditions) === null || _f === void 0 ? void 0 : _f[0].message) || ''}`); - if (success || phase !== 'Pending') - return true; - return false; - }), { - timeout: 2000000, - intervalBetweenAttempts: 15000, - }); - return success; - }); - } -} -exports["default"] = KubernetesTaskRunner; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const client_node_1 = __nccwpck_require__(89679); +const stream_1 = __nccwpck_require__(12781); +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const core = __importStar(__nccwpck_require__(42186)); +const cloud_runner_statics_1 = __nccwpck_require__(90828); +const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class KubernetesTaskRunner { + static runTask(kubeConfig, kubeClient, jobName, podName, containerName, namespace, logCallback) { + return __awaiter(this, void 0, void 0, function* () { + cloud_runner_logger_1.default.log(`Streaming logs from pod: ${podName} container: ${containerName} namespace: ${namespace}`); + const stream = new stream_1.Writable(); + let output = ''; + let didStreamAnyLogs = false; + stream._write = (chunk, encoding, next) => { + didStreamAnyLogs = true; + let message = chunk.toString().trimRight(`\n`); + message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; + if (cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests) { + output += message; + } + logCallback(message); + next(); + }; + const logOptions = { + follow: true, + pretty: false, + previous: false, + }; + try { + const resultError = yield new Promise((resolve) => new client_node_1.Log(kubeConfig).log(namespace, podName, containerName, stream, resolve, logOptions)); + stream.destroy(); + if (resultError) { + throw resultError; + } + if (!didStreamAnyLogs) { + core.error('Failed to stream any logs, listing namespace events, check for an error with the container'); + core.error(JSON.stringify({ + events: (yield kubeClient.listNamespacedEvent(namespace)).body.items + .filter((x) => { + return x.involvedObject.name === podName || x.involvedObject.name === jobName; + }) + .map((x) => { + return { + type: x.involvedObject.kind, + name: x.involvedObject.name, + message: x.message, + }; + }), + }, undefined, 4)); + throw new Error(`No logs streamed from k8s`); + } + } + catch (error) { + if (stream) { + stream.destroy(); + } + throw error; + } + cloud_runner_logger_1.default.log('end of log stream'); + return output; + }); + } + static watchUntilPodRunning(kubeClient, podName, namespace) { + return __awaiter(this, void 0, void 0, function* () { + let success = false; + cloud_runner_logger_1.default.log(`Watching ${podName} ${namespace}`); + yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { + var _a, _b, _c, _d, _e, _f; + const status = yield kubeClient.readNamespacedPodStatus(podName, namespace); + const phase = (_a = status === null || status === void 0 ? void 0 : status.body.status) === null || _a === void 0 ? void 0 : _a.phase; + success = phase === 'Running'; + cloud_runner_logger_1.default.log(`${(_b = status.body.status) === null || _b === void 0 ? void 0 : _b.phase} ${((_d = (_c = status.body.status) === null || _c === void 0 ? void 0 : _c.conditions) === null || _d === void 0 ? void 0 : _d[0].reason) || ''} ${((_f = (_e = status.body.status) === null || _e === void 0 ? void 0 : _e.conditions) === null || _f === void 0 ? void 0 : _f[0].message) || ''}`); + if (success || phase !== 'Pending') + return true; + return false; + }), { + timeout: 2000000, + intervalBetweenAttempts: 15000, + }); + return success; + }); + } +} +exports["default"] = KubernetesTaskRunner; /***/ }), @@ -2767,17 +2767,17 @@ exports["default"] = KubernetesTaskRunner; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Hook = exports.CloudRunnerBuildCommandProcessor = void 0; -const yaml_1 = __importDefault(__nccwpck_require__(44603)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class CloudRunnerBuildCommandProcessor { - static ProcessCommands(commands, buildParameters) { - const hooks = CloudRunnerBuildCommandProcessor.getHooks(buildParameters.customJobHooks).filter((x) => x.step.includes(`all`)); + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Hook = exports.CloudRunnerBuildCommandProcessor = void 0; +const yaml_1 = __importDefault(__nccwpck_require__(44603)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class CloudRunnerBuildCommandProcessor { + static ProcessCommands(commands, buildParameters) { + const hooks = CloudRunnerBuildCommandProcessor.getHooks(buildParameters.customJobHooks).filter((x) => x.step.includes(`all`)); return `echo "---" echo "start cloud runner init" ${cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests ? '' : '#'} printenv @@ -2787,29 +2787,29 @@ class CloudRunnerBuildCommandProcessor { ${hooks.filter((x) => x.hook.includes(`after`)).map((x) => x.commands) || ' '} echo "end of cloud runner job" ---${buildParameters.logId}" - `; - } - static getHooks(customJobHooks) { - const experimentHooks = customJobHooks; - let output = new Array(); - if (experimentHooks && experimentHooks !== '') { - try { - output = yaml_1.default.parse(experimentHooks); - } - catch (error) { - throw error; - } - } - return output.filter((x) => x.step !== undefined && x.hook !== undefined && x.hook.length > 0); - } -} -exports.CloudRunnerBuildCommandProcessor = CloudRunnerBuildCommandProcessor; -class Hook { - constructor() { - this.secrets = new Array(); - } -} -exports.Hook = Hook; + `; + } + static getHooks(customJobHooks) { + const experimentHooks = customJobHooks; + let output = new Array(); + if (experimentHooks && experimentHooks !== '') { + try { + output = yaml_1.default.parse(experimentHooks); + } + catch (error) { + throw error; + } + } + return output.filter((x) => x.step !== undefined && x.hook !== undefined && x.hook.length > 0); + } +} +exports.CloudRunnerBuildCommandProcessor = CloudRunnerBuildCommandProcessor; +class Hook { + constructor() { + this.secrets = new Array(); + } +} +exports.Hook = Hook; /***/ }), @@ -2818,12 +2818,12 @@ exports.Hook = Hook; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class CloudRunnerConstants { -} -CloudRunnerConstants.alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; -exports["default"] = CloudRunnerConstants; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class CloudRunnerConstants { +} +CloudRunnerConstants.alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; +exports["default"] = CloudRunnerConstants; /***/ }), @@ -2832,64 +2832,64 @@ exports["default"] = CloudRunnerConstants; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunnerFolders = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -const __1 = __nccwpck_require__(41359); -class CloudRunnerFolders { - // only the following paths that do not start a path.join with another "Full" suffixed property need to start with an absolute / - static get buildPathFull() { - return path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, __1.CloudRunner.buildParameters.buildGuid); - } - static get cacheFolderFull() { - return path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder, CloudRunnerFolders.cacheKey); - } - static get cacheKey() { - return __1.CloudRunner.buildParameters.cacheKey || __1.CloudRunner.buildParameters.branch; - } - static get builderPathFull() { - return path_1.default.join(CloudRunnerFolders.buildPathFull, `builder`); - } - static get repoPathFull() { - return path_1.default.join(CloudRunnerFolders.buildPathFull, CloudRunnerFolders.repositoryFolder); - } - static get projectPathFull() { - return path_1.default.join(CloudRunnerFolders.repoPathFull, __1.CloudRunner.buildParameters.projectPath); - } - static get libraryFolderFull() { - return path_1.default.join(CloudRunnerFolders.projectPathFull, `Library`); - } - static get lfsDirectoryFull() { - return path_1.default.join(CloudRunnerFolders.repoPathFull, `.git`, `lfs`); - } - static get purgeRemoteCaching() { - return process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined; - } - static get lfsCacheFolderFull() { - return path_1.default.join(CloudRunnerFolders.cacheFolderFull, `lfs`); - } - static get libraryCacheFolderFull() { - return path_1.default.join(CloudRunnerFolders.cacheFolderFull, `Library`); - } - static get unityBuilderRepoUrl() { - return `https://${__1.CloudRunner.buildParameters.gitPrivateToken}@github.com/game-ci/unity-builder.git`; - } - static get targetBuildRepoUrl() { - return `https://${__1.CloudRunner.buildParameters.gitPrivateToken}@github.com/${__1.CloudRunner.buildParameters.githubRepo}.git`; - } - static get buildVolumeFolder() { - return 'data'; - } - static get cacheFolder() { - return 'cache'; - } -} -exports.CloudRunnerFolders = CloudRunnerFolders; -CloudRunnerFolders.repositoryFolder = 'repo'; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunnerFolders = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +const __1 = __nccwpck_require__(41359); +class CloudRunnerFolders { + // only the following paths that do not start a path.join with another "Full" suffixed property need to start with an absolute / + static get buildPathFull() { + return path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, __1.CloudRunner.buildParameters.buildGuid); + } + static get cacheFolderFull() { + return path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder, CloudRunnerFolders.cacheKey); + } + static get cacheKey() { + return __1.CloudRunner.buildParameters.cacheKey || __1.CloudRunner.buildParameters.branch; + } + static get builderPathFull() { + return path_1.default.join(CloudRunnerFolders.buildPathFull, `builder`); + } + static get repoPathFull() { + return path_1.default.join(CloudRunnerFolders.buildPathFull, CloudRunnerFolders.repositoryFolder); + } + static get projectPathFull() { + return path_1.default.join(CloudRunnerFolders.repoPathFull, __1.CloudRunner.buildParameters.projectPath); + } + static get libraryFolderFull() { + return path_1.default.join(CloudRunnerFolders.projectPathFull, `Library`); + } + static get lfsDirectoryFull() { + return path_1.default.join(CloudRunnerFolders.repoPathFull, `.git`, `lfs`); + } + static get purgeRemoteCaching() { + return process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined; + } + static get lfsCacheFolderFull() { + return path_1.default.join(CloudRunnerFolders.cacheFolderFull, `lfs`); + } + static get libraryCacheFolderFull() { + return path_1.default.join(CloudRunnerFolders.cacheFolderFull, `Library`); + } + static get unityBuilderRepoUrl() { + return `https://${__1.CloudRunner.buildParameters.gitPrivateToken}@github.com/game-ci/unity-builder.git`; + } + static get targetBuildRepoUrl() { + return `https://${__1.CloudRunner.buildParameters.gitPrivateToken}@github.com/${__1.CloudRunner.buildParameters.githubRepo}.git`; + } + static get buildVolumeFolder() { + return 'data'; + } + static get cacheFolder() { + return 'cache'; + } +} +exports.CloudRunnerFolders = CloudRunnerFolders; +CloudRunnerFolders.repositoryFolder = 'repo'; /***/ }), @@ -2898,58 +2898,58 @@ CloudRunnerFolders.repositoryFolder = 'repo'; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -class CloudRunnerLogger { - static setup() { - this.timestamp = this.createTimestamp(); - this.globalTimestamp = this.timestamp; - } - static log(message) { - core.info(message); - } - static logWarning(message) { - core.warning(message); - } - static logLine(message) { - core.info(`${message}\n`); - } - static error(message) { - core.error(message); - } - static logWithTime(message) { - const newTimestamp = this.createTimestamp(); - core.info(`${message} (Since previous: ${this.calculateTimeDiff(newTimestamp, this.timestamp)}, Total time: ${this.calculateTimeDiff(newTimestamp, this.globalTimestamp)})`); - this.timestamp = newTimestamp; - } - static calculateTimeDiff(x, y) { - return Math.floor((x - y) / 1000); - } - static createTimestamp() { - return Date.now(); - } -} -exports["default"] = CloudRunnerLogger; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +class CloudRunnerLogger { + static setup() { + this.timestamp = this.createTimestamp(); + this.globalTimestamp = this.timestamp; + } + static log(message) { + core.info(message); + } + static logWarning(message) { + core.warning(message); + } + static logLine(message) { + core.info(`${message}\n`); + } + static error(message) { + core.error(message); + } + static logWithTime(message) { + const newTimestamp = this.createTimestamp(); + core.info(`${message} (Since previous: ${this.calculateTimeDiff(newTimestamp, this.timestamp)}, Total time: ${this.calculateTimeDiff(newTimestamp, this.globalTimestamp)})`); + this.timestamp = newTimestamp; + } + static calculateTimeDiff(x, y) { + return Math.floor((x - y) / 1000); + } + static createTimestamp() { + return Date.now(); + } +} +exports["default"] = CloudRunnerLogger; /***/ }), @@ -2958,20 +2958,20 @@ exports["default"] = CloudRunnerLogger; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const nanoid_1 = __nccwpck_require__(17592); -const cloud_runner_constants_1 = __importDefault(__nccwpck_require__(91311)); -class CloudRunnerNamespace { - static generateBuildName(runNumber, platform) { - const nanoid = nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 4); - return `${runNumber}-${platform.toLowerCase().replace('standalone', '')}-${nanoid()}`; - } -} -exports["default"] = CloudRunnerNamespace; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const nanoid_1 = __nccwpck_require__(17592); +const cloud_runner_constants_1 = __importDefault(__nccwpck_require__(91311)); +class CloudRunnerNamespace { + static generateBuildName(runNumber, platform) { + const nanoid = nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 4); + return `${runNumber}-${platform.toLowerCase().replace('standalone', '')}-${nanoid()}`; + } +} +exports["default"] = CloudRunnerNamespace; /***/ }), @@ -2980,45 +2980,45 @@ exports["default"] = CloudRunnerNamespace; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const cloud_runner_system_1 = __nccwpck_require__(66879); -const input_1 = __importDefault(__nccwpck_require__(91933)); -class DependencyOverrideService { - static CheckHealth() { - return __awaiter(this, void 0, void 0, function* () { - if (input_1.default.checkDependencyHealthOverride) { - try { - yield cloud_runner_system_1.CloudRunnerSystem.Run(input_1.default.checkDependencyHealthOverride); - } - catch (_a) { - return false; - } - } - return true; - }); - } - static TryStartDependencies() { - return __awaiter(this, void 0, void 0, function* () { - if (input_1.default.startDependenciesOverride) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(input_1.default.startDependenciesOverride); - } - }); - } -} -exports["default"] = DependencyOverrideService; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const cloud_runner_system_1 = __nccwpck_require__(66879); +const input_1 = __importDefault(__nccwpck_require__(91933)); +class DependencyOverrideService { + static CheckHealth() { + return __awaiter(this, void 0, void 0, function* () { + if (input_1.default.checkDependencyHealthOverride) { + try { + yield cloud_runner_system_1.CloudRunnerSystem.Run(input_1.default.checkDependencyHealthOverride); + } + catch (_a) { + return false; + } + } + return true; + }); + } + static TryStartDependencies() { + return __awaiter(this, void 0, void 0, function* () { + if (input_1.default.startDependenciesOverride) { + yield cloud_runner_system_1.CloudRunnerSystem.Run(input_1.default.startDependenciesOverride); + } + }); + } +} +exports["default"] = DependencyOverrideService; /***/ }), @@ -3027,87 +3027,87 @@ exports["default"] = DependencyOverrideService; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TaskParameterSerializer = void 0; -const __1 = __nccwpck_require__(41359); -const image_environment_factory_1 = __importDefault(__nccwpck_require__(25145)); -const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); -class TaskParameterSerializer { - static readBuildEnvironmentVariables() { - TaskParameterSerializer.setupDefaultSecrets(); - return [ - { - name: 'ContainerMemory', - value: __1.CloudRunner.buildParameters.cloudRunnerMemory, - }, - { - name: 'ContainerCpu', - value: __1.CloudRunner.buildParameters.cloudRunnerCpu, - }, - { - name: 'BUILD_TARGET', - value: __1.CloudRunner.buildParameters.platform, - }, - ...TaskParameterSerializer.serializeBuildParamsAndInput, - ]; - } - static get serializeBuildParamsAndInput() { - let array = new Array(); - array = TaskParameterSerializer.readBuildParameters(array); - array = TaskParameterSerializer.readInput(array); - const configurableHooks = cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.getHooks(__1.CloudRunner.buildParameters.customJobHooks); - const secrets = configurableHooks.map((x) => x.secrets).filter((x) => x !== undefined && x.length > 0); - if (secrets.length > 0) { - // eslint-disable-next-line unicorn/no-array-reduce - array.push(secrets.reduce((x, y) => [...x, ...y])); - } - array = array.filter((x) => x.value !== undefined && x.name !== '0' && x.value !== '' && x.name !== 'prototype' && x.name !== 'length'); - array = array.map((x) => { - x.name = __1.Input.ToEnvVarFormat(x.name); - x.value = `${x.value}`; - return x; - }); - return array; - } - static readBuildParameters(array) { - const keys = Object.keys(__1.CloudRunner.buildParameters); - for (const element of keys) { - array.push({ - name: element, - value: __1.CloudRunner.buildParameters[element], - }); - } - array.push({ name: 'buildParameters', value: JSON.stringify(__1.CloudRunner.buildParameters) }); - return array; - } - static readInput(array) { - const input = Object.getOwnPropertyNames(__1.Input); - for (const element of input) { - if (typeof __1.Input[element] !== 'function' && array.filter((x) => x.name === element).length === 0) { - array.push({ - name: element, - value: `${__1.Input[element]}`, - }); - } - } - return array; - } - static setupDefaultSecrets() { - if (__1.CloudRunner.defaultSecrets === undefined) - __1.CloudRunner.defaultSecrets = image_environment_factory_1.default.getEnvironmentVariables(__1.CloudRunner.buildParameters).map((x) => { - return { - ParameterKey: x.name, - EnvironmentVariable: x.name, - ParameterValue: x.value, - }; - }); - } -} -exports.TaskParameterSerializer = TaskParameterSerializer; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TaskParameterSerializer = void 0; +const __1 = __nccwpck_require__(41359); +const image_environment_factory_1 = __importDefault(__nccwpck_require__(25145)); +const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); +class TaskParameterSerializer { + static readBuildEnvironmentVariables() { + TaskParameterSerializer.setupDefaultSecrets(); + return [ + { + name: 'ContainerMemory', + value: __1.CloudRunner.buildParameters.cloudRunnerMemory, + }, + { + name: 'ContainerCpu', + value: __1.CloudRunner.buildParameters.cloudRunnerCpu, + }, + { + name: 'BUILD_TARGET', + value: __1.CloudRunner.buildParameters.platform, + }, + ...TaskParameterSerializer.serializeBuildParamsAndInput, + ]; + } + static get serializeBuildParamsAndInput() { + let array = new Array(); + array = TaskParameterSerializer.readBuildParameters(array); + array = TaskParameterSerializer.readInput(array); + const configurableHooks = cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.getHooks(__1.CloudRunner.buildParameters.customJobHooks); + const secrets = configurableHooks.map((x) => x.secrets).filter((x) => x !== undefined && x.length > 0); + if (secrets.length > 0) { + // eslint-disable-next-line unicorn/no-array-reduce + array.push(secrets.reduce((x, y) => [...x, ...y])); + } + array = array.filter((x) => x.value !== undefined && x.name !== '0' && x.value !== '' && x.name !== 'prototype' && x.name !== 'length'); + array = array.map((x) => { + x.name = __1.Input.ToEnvVarFormat(x.name); + x.value = `${x.value}`; + return x; + }); + return array; + } + static readBuildParameters(array) { + const keys = Object.keys(__1.CloudRunner.buildParameters); + for (const element of keys) { + array.push({ + name: element, + value: __1.CloudRunner.buildParameters[element], + }); + } + array.push({ name: 'buildParameters', value: JSON.stringify(__1.CloudRunner.buildParameters) }); + return array; + } + static readInput(array) { + const input = Object.getOwnPropertyNames(__1.Input); + for (const element of input) { + if (typeof __1.Input[element] !== 'function' && array.filter((x) => x.name === element).length === 0) { + array.push({ + name: element, + value: `${__1.Input[element]}`, + }); + } + } + return array; + } + static setupDefaultSecrets() { + if (__1.CloudRunner.defaultSecrets === undefined) + __1.CloudRunner.defaultSecrets = image_environment_factory_1.default.getEnvironmentVariables(__1.CloudRunner.buildParameters).map((x) => { + return { + ParameterKey: x.name, + EnvironmentVariable: x.name, + ParameterValue: x.value, + }; + }); + } +} +exports.TaskParameterSerializer = TaskParameterSerializer; /***/ }), @@ -3116,118 +3116,118 @@ exports.TaskParameterSerializer = TaskParameterSerializer; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BuildAutomationWorkflow = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const task_parameter_serializer_1 = __nccwpck_require__(35346); -const cloud_runner_folders_1 = __nccwpck_require__(13527); -const custom_workflow_1 = __nccwpck_require__(3786); -const core = __importStar(__nccwpck_require__(42186)); -const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class BuildAutomationWorkflow { - run(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield BuildAutomationWorkflow.standardBuildAutomation(cloudRunnerStepState.image); - } - catch (error) { - throw error; - } - }); - } - static standardBuildAutomation(baseImage) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`Cloud Runner is running standard build automation`); - if (!cloud_runner_1.default.buildParameters.cliMode) - core.startGroup('pre build steps'); - let output = ''; - if (cloud_runner_1.default.buildParameters.preBuildSteps !== '') { - output += yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.preBuildSteps); - } - if (!cloud_runner_1.default.buildParameters.cliMode) - core.endGroup(); - cloud_runner_logger_1.default.logWithTime('Configurable pre build step(s) time'); - // core.startGroup('setup'); - // output += await new SetupStep().run( - // new CloudRunnerStepState( - // 'alpine/git', - // TaskParameterSerializer.readBuildEnvironmentVariables(), - // CloudRunnerState.defaultSecrets, - // ), - // ); - // core.endGroup(); - // CloudRunnerLogger.logWithTime('Download repository step time'); - if (!cloud_runner_1.default.buildParameters.cliMode) - core.startGroup('build'); - cloud_runner_logger_1.default.log(baseImage.toString()); - cloud_runner_logger_1.default.logLine(` `); - cloud_runner_logger_1.default.logLine('Starting build automation job'); - output += yield cloud_runner_1.default.CloudRunnerProviderPlatform.runTask(cloud_runner_1.default.buildParameters.buildGuid, baseImage.toString(), BuildAutomationWorkflow.FullWorkflow, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.projectPathFull}`, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), cloud_runner_1.default.defaultSecrets); - if (!cloud_runner_1.default.buildParameters.cliMode) - core.endGroup(); - cloud_runner_logger_1.default.logWithTime('Build time'); - if (!cloud_runner_1.default.buildParameters.cliMode) - core.startGroup('post build steps'); - if (cloud_runner_1.default.buildParameters.postBuildSteps !== '') { - output += yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.postBuildSteps); - } - if (!cloud_runner_1.default.buildParameters.cliMode) - core.endGroup(); - cloud_runner_logger_1.default.logWithTime('Configurable post build step(s) time'); - cloud_runner_logger_1.default.log(`Cloud Runner finished running standard build automation`); - return output; - } - catch (error) { - throw error; - } - }); - } - static get FullWorkflow() { - const hooks = cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.getHooks(cloud_runner_1.default.buildParameters.customJobHooks).filter((x) => x.step.includes(`setup`)); + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BuildAutomationWorkflow = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const task_parameter_serializer_1 = __nccwpck_require__(35346); +const cloud_runner_folders_1 = __nccwpck_require__(13527); +const custom_workflow_1 = __nccwpck_require__(3786); +const core = __importStar(__nccwpck_require__(42186)); +const cloud_runner_build_command_process_1 = __nccwpck_require__(71899); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class BuildAutomationWorkflow { + run(cloudRunnerStepState) { + return __awaiter(this, void 0, void 0, function* () { + try { + return yield BuildAutomationWorkflow.standardBuildAutomation(cloudRunnerStepState.image); + } + catch (error) { + throw error; + } + }); + } + static standardBuildAutomation(baseImage) { + return __awaiter(this, void 0, void 0, function* () { + try { + cloud_runner_logger_1.default.log(`Cloud Runner is running standard build automation`); + if (!cloud_runner_1.default.buildParameters.cliMode) + core.startGroup('pre build steps'); + let output = ''; + if (cloud_runner_1.default.buildParameters.preBuildSteps !== '') { + output += yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.preBuildSteps); + } + if (!cloud_runner_1.default.buildParameters.cliMode) + core.endGroup(); + cloud_runner_logger_1.default.logWithTime('Configurable pre build step(s) time'); + // core.startGroup('setup'); + // output += await new SetupStep().run( + // new CloudRunnerStepState( + // 'alpine/git', + // TaskParameterSerializer.readBuildEnvironmentVariables(), + // CloudRunnerState.defaultSecrets, + // ), + // ); + // core.endGroup(); + // CloudRunnerLogger.logWithTime('Download repository step time'); + if (!cloud_runner_1.default.buildParameters.cliMode) + core.startGroup('build'); + cloud_runner_logger_1.default.log(baseImage.toString()); + cloud_runner_logger_1.default.logLine(` `); + cloud_runner_logger_1.default.logLine('Starting build automation job'); + output += yield cloud_runner_1.default.CloudRunnerProviderPlatform.runTask(cloud_runner_1.default.buildParameters.buildGuid, baseImage.toString(), BuildAutomationWorkflow.FullWorkflow, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.projectPathFull}`, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), cloud_runner_1.default.defaultSecrets); + if (!cloud_runner_1.default.buildParameters.cliMode) + core.endGroup(); + cloud_runner_logger_1.default.logWithTime('Build time'); + if (!cloud_runner_1.default.buildParameters.cliMode) + core.startGroup('post build steps'); + if (cloud_runner_1.default.buildParameters.postBuildSteps !== '') { + output += yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.postBuildSteps); + } + if (!cloud_runner_1.default.buildParameters.cliMode) + core.endGroup(); + cloud_runner_logger_1.default.logWithTime('Configurable post build step(s) time'); + cloud_runner_logger_1.default.log(`Cloud Runner finished running standard build automation`); + return output; + } + catch (error) { + throw error; + } + }); + } + static get FullWorkflow() { + const hooks = cloud_runner_build_command_process_1.CloudRunnerBuildCommandProcessor.getHooks(cloud_runner_1.default.buildParameters.customJobHooks).filter((x) => x.step.includes(`setup`)); return `apt-get update apt-get install -y -q zip tree nodejs git-lfs jq unzip ${hooks.filter((x) => x.hook.includes(`before`)).map((x) => x.commands) || ' '} export GITHUB_WORKSPACE="${cloud_runner_folders_1.CloudRunnerFolders.repoPathFull}" ${BuildAutomationWorkflow.SetupCommands} ${hooks.filter((x) => x.hook.includes(`after`)).map((x) => x.commands) || ' '} - ${BuildAutomationWorkflow.BuildCommands}`; - } - static get SetupCommands() { + ${BuildAutomationWorkflow.BuildCommands}`; + } + static get SetupCommands() { return `export GIT_DISCOVERY_ACROSS_FILESYSTEM=1 echo "cloning" mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.builderPathFull.replace(/\\/g, `/`)} @@ -3236,17 +3236,17 @@ class BuildAutomationWorkflow { chmod +x ${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`).replace(/\\/g, `/`)} echo "caching" node --version - node ${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`).replace(/\\/g, `/`)} -m remote-cli`; - } - static get BuildCommands() { - return `cp -r "${path_1.default - .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'default-build-script') + node ${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`).replace(/\\/g, `/`)} -m remote-cli`; + } + static get BuildCommands() { + return `cp -r "${path_1.default + .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'default-build-script') .replace(/\\/g, `/`)}" "/UnityBuilderAction" - cp -r "${path_1.default - .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'platforms', 'ubuntu', 'entrypoint.sh') + cp -r "${path_1.default + .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'platforms', 'ubuntu', 'entrypoint.sh') .replace(/\\/g, `/`)}" "/entrypoint.sh" - cp -r "${path_1.default - .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'platforms', 'ubuntu', 'steps') + cp -r "${path_1.default + .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', 'platforms', 'ubuntu', 'steps') .replace(/\\/g, `/`)}" "/steps" chmod -R +x "/entrypoint.sh" chmod -R +x "/steps" @@ -3258,13 +3258,13 @@ class BuildAutomationWorkflow { zip -r "build-${cloud_runner_1.default.buildParameters.buildGuid}.zip" "build" mv "build-${cloud_runner_1.default.buildParameters.buildGuid}.zip" "${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull.replace(/\\/g, `/`)}" chmod +x ${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`).replace(/\\/g, `/`)} - node ${path_1.default - .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`) + node ${path_1.default + .join(cloud_runner_folders_1.CloudRunnerFolders.builderPathFull, 'dist', `index.js`) .replace(/\\/g, `/`)} -m cache-push "Library" "lib-${cloud_runner_1.default.buildParameters.buildGuid}.zip" "${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull.replace(/\\/g, `/`)}/Library" - ${cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests ? '' : '#'} tree -lh "${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull}"`; - } -} -exports.BuildAutomationWorkflow = BuildAutomationWorkflow; + ${cloud_runner_1.default.buildParameters.cloudRunnerIntegrationTests ? '' : '#'} tree -lh "${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderFull}"`; + } +} +exports.BuildAutomationWorkflow = BuildAutomationWorkflow; /***/ }), @@ -3273,62 +3273,62 @@ exports.BuildAutomationWorkflow = BuildAutomationWorkflow; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CustomWorkflow = void 0; -const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const cloud_runner_folders_1 = __nccwpck_require__(13527); -const yaml_1 = __importDefault(__nccwpck_require__(44603)); -const __1 = __nccwpck_require__(41359); -const task_parameter_serializer_1 = __nccwpck_require__(35346); -class CustomWorkflow { - static runCustomJob(buildSteps) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`Cloud Runner is running in custom job mode`); - if (__1.CloudRunner.buildParameters.cloudRunnerIntegrationTests) { - cloud_runner_logger_1.default.log(`Parsing build steps: ${buildSteps}`); - } - try { - buildSteps = yaml_1.default.parse(buildSteps); - let output = ''; - for (const step of buildSteps) { - const stepSecrets = step.secrets.map((x) => { - const secret = { - ParameterKey: x.name, - EnvironmentVariable: __1.Input.ToEnvVarFormat(x.name), - ParameterValue: x.value, - }; - return secret; - }); - output += yield __1.CloudRunner.CloudRunnerProviderPlatform.runTask(__1.CloudRunner.buildParameters.buildGuid, step['image'], step['commands'], `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}/`, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), [...__1.CloudRunner.defaultSecrets, ...stepSecrets]); - } - return output; - } - catch (error) { - cloud_runner_logger_1.default.log(`failed to parse a custom job "${buildSteps}"`); - throw error; - } - } - catch (error) { - throw error; - } - }); - } -} -exports.CustomWorkflow = CustomWorkflow; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CustomWorkflow = void 0; +const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); +const cloud_runner_folders_1 = __nccwpck_require__(13527); +const yaml_1 = __importDefault(__nccwpck_require__(44603)); +const __1 = __nccwpck_require__(41359); +const task_parameter_serializer_1 = __nccwpck_require__(35346); +class CustomWorkflow { + static runCustomJob(buildSteps) { + return __awaiter(this, void 0, void 0, function* () { + try { + cloud_runner_logger_1.default.log(`Cloud Runner is running in custom job mode`); + if (__1.CloudRunner.buildParameters.cloudRunnerIntegrationTests) { + cloud_runner_logger_1.default.log(`Parsing build steps: ${buildSteps}`); + } + try { + buildSteps = yaml_1.default.parse(buildSteps); + let output = ''; + for (const step of buildSteps) { + const stepSecrets = step.secrets.map((x) => { + const secret = { + ParameterKey: x.name, + EnvironmentVariable: __1.Input.ToEnvVarFormat(x.name), + ParameterValue: x.value, + }; + return secret; + }); + output += yield __1.CloudRunner.CloudRunnerProviderPlatform.runTask(__1.CloudRunner.buildParameters.buildGuid, step['image'], step['commands'], `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}/`, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), [...__1.CloudRunner.defaultSecrets, ...stepSecrets]); + } + return output; + } + catch (error) { + cloud_runner_logger_1.default.log(`failed to parse a custom job "${buildSteps}"`); + throw error; + } + } + catch (error) { + throw error; + } + }); + } +} +exports.CustomWorkflow = CustomWorkflow; /***/ }), @@ -3337,52 +3337,52 @@ exports.CustomWorkflow = CustomWorkflow; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WorkflowCompositionRoot = void 0; -const cloud_runner_step_state_1 = __nccwpck_require__(50121); -const custom_workflow_1 = __nccwpck_require__(3786); -const build_automation_workflow_1 = __nccwpck_require__(94655); -const task_parameter_serializer_1 = __nccwpck_require__(35346); -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -class WorkflowCompositionRoot { - run(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield WorkflowCompositionRoot.runJob(cloudRunnerStepState.image.toString()); - } - catch (error) { - throw error; - } - }); - } - static runJob(baseImage) { - return __awaiter(this, void 0, void 0, function* () { - try { - if (cloud_runner_1.default.buildParameters.customJob !== '') { - return yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.customJob); - } - return yield new build_automation_workflow_1.BuildAutomationWorkflow().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), cloud_runner_1.default.defaultSecrets)); - } - catch (error) { - throw error; - } - }); - } -} -exports.WorkflowCompositionRoot = WorkflowCompositionRoot; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WorkflowCompositionRoot = void 0; +const cloud_runner_step_state_1 = __nccwpck_require__(50121); +const custom_workflow_1 = __nccwpck_require__(3786); +const build_automation_workflow_1 = __nccwpck_require__(94655); +const task_parameter_serializer_1 = __nccwpck_require__(35346); +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +class WorkflowCompositionRoot { + run(cloudRunnerStepState) { + return __awaiter(this, void 0, void 0, function* () { + try { + return yield WorkflowCompositionRoot.runJob(cloudRunnerStepState.image.toString()); + } + catch (error) { + throw error; + } + }); + } + static runJob(baseImage) { + return __awaiter(this, void 0, void 0, function* () { + try { + if (cloud_runner_1.default.buildParameters.customJob !== '') { + return yield custom_workflow_1.CustomWorkflow.runCustomJob(cloud_runner_1.default.buildParameters.customJob); + } + return yield new build_automation_workflow_1.BuildAutomationWorkflow().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, task_parameter_serializer_1.TaskParameterSerializer.readBuildEnvironmentVariables(), cloud_runner_1.default.defaultSecrets)); + } + catch (error) { + throw error; + } + }); + } +} +exports.WorkflowCompositionRoot = WorkflowCompositionRoot; /***/ }), @@ -3391,61 +3391,61 @@ exports.WorkflowCompositionRoot = WorkflowCompositionRoot; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const exec_1 = __nccwpck_require__(71514); -const image_tag_1 = __importDefault(__nccwpck_require__(57648)); -const image_environment_factory_1 = __importDefault(__nccwpck_require__(25145)); -const fs_1 = __nccwpck_require__(57147); -const path_1 = __importDefault(__nccwpck_require__(71017)); -class Docker { - static build(buildParameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - const { path: buildPath, dockerfile, baseImage } = buildParameters; - const { version, platform } = baseImage; - const tag = new image_tag_1.default({ repository: '', name: 'unity-builder', version, platform }); + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const exec_1 = __nccwpck_require__(71514); +const image_tag_1 = __importDefault(__nccwpck_require__(57648)); +const image_environment_factory_1 = __importDefault(__nccwpck_require__(25145)); +const fs_1 = __nccwpck_require__(57147); +const path_1 = __importDefault(__nccwpck_require__(71017)); +class Docker { + static build(buildParameters, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + const { path: buildPath, dockerfile, baseImage } = buildParameters; + const { version, platform } = baseImage; + const tag = new image_tag_1.default({ repository: '', name: 'unity-builder', version, platform }); const command = `docker build ${buildPath} \ --file ${dockerfile} \ --build-arg IMAGE=${baseImage} \ - --tag ${tag}`; - yield exec_1.exec(command, undefined, { silent }); - return tag; - }); - } - static run(image, parameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - const { workspace, unitySerial, runnerTempPath, sshAgent } = parameters; - const baseOsSpecificArguments = this.getBaseOsSpecificArguments(process.platform, workspace, unitySerial, runnerTempPath, sshAgent); + --tag ${tag}`; + yield exec_1.exec(command, undefined, { silent }); + return tag; + }); + } + static run(image, parameters, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + const { workspace, unitySerial, runnerTempPath, sshAgent } = parameters; + const baseOsSpecificArguments = this.getBaseOsSpecificArguments(process.platform, workspace, unitySerial, runnerTempPath, sshAgent); const runCommand = `docker run \ --workdir /github/workspace \ --rm \ ${image_environment_factory_1.default.getEnvVarString(parameters)} \ ${baseOsSpecificArguments} \ - ${image}`; - yield exec_1.exec(runCommand, undefined, { silent }); - }); - } - static getBaseOsSpecificArguments(baseOs, workspace, unitySerial, runnerTemporaryPath, sshAgent) { - switch (baseOs) { - case 'linux': { - const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); - if (!fs_1.existsSync(githubHome)) - fs_1.mkdirSync(githubHome); - const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); - if (!fs_1.existsSync(githubWorkflow)) - fs_1.mkdirSync(githubWorkflow); + ${image}`; + yield exec_1.exec(runCommand, undefined, { silent }); + }); + } + static getBaseOsSpecificArguments(baseOs, workspace, unitySerial, runnerTemporaryPath, sshAgent) { + switch (baseOs) { + case 'linux': { + const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); + if (!fs_1.existsSync(githubHome)) + fs_1.mkdirSync(githubHome); + const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); + if (!fs_1.existsSync(githubWorkflow)) + fs_1.mkdirSync(githubWorkflow); return `--env UNITY_SERIAL \ --env GITHUB_WORKSPACE=/github/workspace \ ${sshAgent ? '--env SSH_AUTH_SOCK=/ssh-agent' : ''} \ @@ -3454,22 +3454,22 @@ class Docker { --volume "${githubWorkflow}":"/github/workflow:z" \ --volume "${workspace}":"/github/workspace:z" \ ${sshAgent ? `--volume ${sshAgent}:/ssh-agent` : ''} \ - ${sshAgent ? '--volume /home/runner/.ssh/known_hosts:/root/.ssh/known_hosts:ro' : ''}`; - } - case 'win32': + ${sshAgent ? '--volume /home/runner/.ssh/known_hosts:/root/.ssh/known_hosts:ro' : ''}`; + } + case 'win32': return `--env UNITY_SERIAL="${unitySerial}" \ --env GITHUB_WORKSPACE=c:/github/workspace \ --volume "${workspace}":"c:/github/workspace" \ --volume "c:/regkeys":"c:/regkeys" \ --volume "C:/Program Files (x86)/Microsoft Visual Studio":"C:/Program Files (x86)/Microsoft Visual Studio" \ --volume "C:/Program Files (x86)/Windows Kits":"C:/Program Files (x86)/Windows Kits" \ - --volume "C:/ProgramData/Microsoft/VisualStudio":"C:/ProgramData/Microsoft/VisualStudio"`; - //Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit - } - return ''; - } -} -exports["default"] = Docker; + --volume "C:/ProgramData/Microsoft/VisualStudio":"C:/ProgramData/Microsoft/VisualStudio"`; + //Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit + } + return ''; + } +} +exports["default"] = Docker; /***/ }), @@ -3478,15 +3478,15 @@ exports["default"] = Docker; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class NotImplementedException extends Error { - constructor(message = '') { - super(message); - this.name = 'NotImplementedException'; - } -} -exports["default"] = NotImplementedException; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class NotImplementedException extends Error { + constructor(message = '') { + super(message); + this.name = 'NotImplementedException'; + } +} +exports["default"] = NotImplementedException; /***/ }), @@ -3495,15 +3495,15 @@ exports["default"] = NotImplementedException; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class ValidationError extends Error { - constructor(message = '') { - super(message); - this.name = 'ValidationError'; - } -} -exports["default"] = ValidationError; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class ValidationError extends Error { + constructor(message = '') { + super(message); + this.name = 'ValidationError'; + } +} +exports["default"] = ValidationError; /***/ }), @@ -3512,74 +3512,74 @@ exports["default"] = ValidationError; /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const test_license_reader_1 = __nccwpck_require__(13963); -class Parameter { -} -class ImageEnvironmentFactory { - static getEnvVarString(parameters) { - const environmentVariables = ImageEnvironmentFactory.getEnvironmentVariables(parameters); - let string = ''; - for (const p of environmentVariables) { - if (p.value === '' || p.value === undefined) { - continue; - } - if (p.name !== 'ANDROID_KEYSTORE_BASE64' && p.value.toString().includes(`\n`)) { - string += `--env ${p.name} `; - continue; - } - string += `--env ${p.name}="${p.value}" `; - } - return string; - } - static getEnvironmentVariables(parameters) { - const environmentVariables = [ - { name: 'UNITY_LICENSE', value: process.env.UNITY_LICENSE || test_license_reader_1.ReadLicense() }, - { name: 'UNITY_LICENSE_FILE', value: process.env.UNITY_LICENSE_FILE }, - { name: 'UNITY_EMAIL', value: process.env.UNITY_EMAIL }, - { name: 'UNITY_PASSWORD', value: process.env.UNITY_PASSWORD }, - { name: 'UNITY_SERIAL', value: parameters.unitySerial }, - { name: 'UNITY_VERSION', value: parameters.version }, - { name: 'USYM_UPLOAD_AUTH_TOKEN', value: process.env.USYM_UPLOAD_AUTH_TOKEN }, - { name: 'PROJECT_PATH', value: parameters.projectPath }, - { name: 'BUILD_TARGET', value: parameters.platform }, - { name: 'BUILD_NAME', value: parameters.buildName }, - { name: 'BUILD_PATH', value: parameters.buildPath }, - { name: 'BUILD_FILE', value: parameters.buildFile }, - { name: 'BUILD_METHOD', value: parameters.buildMethod }, - { name: 'VERSION', value: parameters.buildVersion }, - { name: 'ANDROID_VERSION_CODE', value: parameters.androidVersionCode }, - { name: 'ANDROID_KEYSTORE_NAME', value: parameters.androidKeystoreName }, - { name: 'ANDROID_KEYSTORE_BASE64', value: parameters.androidKeystoreBase64 }, - { name: 'ANDROID_KEYSTORE_PASS', value: parameters.androidKeystorePass }, - { name: 'ANDROID_KEYALIAS_NAME', value: parameters.androidKeyaliasName }, - { name: 'ANDROID_KEYALIAS_PASS', value: parameters.androidKeyaliasPass }, - { name: 'ANDROID_SDK_MANAGER_PARAMETERS', value: parameters.androidSdkManagerParameters }, - { name: 'CUSTOM_PARAMETERS', value: parameters.customParameters }, - { name: 'CHOWN_FILES_TO', value: parameters.chownFilesTo }, - { name: 'GITHUB_REF', value: process.env.GITHUB_REF }, - { name: 'GITHUB_SHA', value: process.env.GITHUB_SHA }, - { name: 'GITHUB_REPOSITORY', value: process.env.GITHUB_REPOSITORY }, - { name: 'GITHUB_ACTOR', value: process.env.GITHUB_ACTOR }, - { name: 'GITHUB_WORKFLOW', value: process.env.GITHUB_WORKFLOW }, - { name: 'GITHUB_HEAD_REF', value: process.env.GITHUB_HEAD_REF }, - { name: 'GITHUB_BASE_REF', value: process.env.GITHUB_BASE_REF }, - { name: 'GITHUB_EVENT_NAME', value: process.env.GITHUB_EVENT_NAME }, - { name: 'GITHUB_WORKSPACE', value: '/github/workspace' }, - { name: 'GITHUB_ACTION', value: process.env.GITHUB_ACTION }, - { name: 'GITHUB_EVENT_PATH', value: process.env.GITHUB_EVENT_PATH }, - { name: 'RUNNER_OS', value: process.env.RUNNER_OS }, - { name: 'RUNNER_TOOL_CACHE', value: process.env.RUNNER_TOOL_CACHE }, - { name: 'RUNNER_TEMP', value: process.env.RUNNER_TEMP }, - { name: 'RUNNER_WORKSPACE', value: process.env.RUNNER_WORKSPACE }, - ]; - if (parameters.sshAgent) - environmentVariables.push({ name: 'SSH_AUTH_SOCK', value: '/ssh-agent' }); - return environmentVariables; - } -} -exports["default"] = ImageEnvironmentFactory; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const test_license_reader_1 = __nccwpck_require__(13963); +class Parameter { +} +class ImageEnvironmentFactory { + static getEnvVarString(parameters) { + const environmentVariables = ImageEnvironmentFactory.getEnvironmentVariables(parameters); + let string = ''; + for (const p of environmentVariables) { + if (p.value === '' || p.value === undefined) { + continue; + } + if (p.name !== 'ANDROID_KEYSTORE_BASE64' && p.value.toString().includes(`\n`)) { + string += `--env ${p.name} `; + continue; + } + string += `--env ${p.name}="${p.value}" `; + } + return string; + } + static getEnvironmentVariables(parameters) { + const environmentVariables = [ + { name: 'UNITY_LICENSE', value: process.env.UNITY_LICENSE || test_license_reader_1.ReadLicense() }, + { name: 'UNITY_LICENSE_FILE', value: process.env.UNITY_LICENSE_FILE }, + { name: 'UNITY_EMAIL', value: process.env.UNITY_EMAIL }, + { name: 'UNITY_PASSWORD', value: process.env.UNITY_PASSWORD }, + { name: 'UNITY_SERIAL', value: parameters.unitySerial }, + { name: 'UNITY_VERSION', value: parameters.version }, + { name: 'USYM_UPLOAD_AUTH_TOKEN', value: process.env.USYM_UPLOAD_AUTH_TOKEN }, + { name: 'PROJECT_PATH', value: parameters.projectPath }, + { name: 'BUILD_TARGET', value: parameters.platform }, + { name: 'BUILD_NAME', value: parameters.buildName }, + { name: 'BUILD_PATH', value: parameters.buildPath }, + { name: 'BUILD_FILE', value: parameters.buildFile }, + { name: 'BUILD_METHOD', value: parameters.buildMethod }, + { name: 'VERSION', value: parameters.buildVersion }, + { name: 'ANDROID_VERSION_CODE', value: parameters.androidVersionCode }, + { name: 'ANDROID_KEYSTORE_NAME', value: parameters.androidKeystoreName }, + { name: 'ANDROID_KEYSTORE_BASE64', value: parameters.androidKeystoreBase64 }, + { name: 'ANDROID_KEYSTORE_PASS', value: parameters.androidKeystorePass }, + { name: 'ANDROID_KEYALIAS_NAME', value: parameters.androidKeyaliasName }, + { name: 'ANDROID_KEYALIAS_PASS', value: parameters.androidKeyaliasPass }, + { name: 'ANDROID_SDK_MANAGER_PARAMETERS', value: parameters.androidSdkManagerParameters }, + { name: 'CUSTOM_PARAMETERS', value: parameters.customParameters }, + { name: 'CHOWN_FILES_TO', value: parameters.chownFilesTo }, + { name: 'GITHUB_REF', value: process.env.GITHUB_REF }, + { name: 'GITHUB_SHA', value: process.env.GITHUB_SHA }, + { name: 'GITHUB_REPOSITORY', value: process.env.GITHUB_REPOSITORY }, + { name: 'GITHUB_ACTOR', value: process.env.GITHUB_ACTOR }, + { name: 'GITHUB_WORKFLOW', value: process.env.GITHUB_WORKFLOW }, + { name: 'GITHUB_HEAD_REF', value: process.env.GITHUB_HEAD_REF }, + { name: 'GITHUB_BASE_REF', value: process.env.GITHUB_BASE_REF }, + { name: 'GITHUB_EVENT_NAME', value: process.env.GITHUB_EVENT_NAME }, + { name: 'GITHUB_WORKSPACE', value: '/github/workspace' }, + { name: 'GITHUB_ACTION', value: process.env.GITHUB_ACTION }, + { name: 'GITHUB_EVENT_PATH', value: process.env.GITHUB_EVENT_PATH }, + { name: 'RUNNER_OS', value: process.env.RUNNER_OS }, + { name: 'RUNNER_TOOL_CACHE', value: process.env.RUNNER_TOOL_CACHE }, + { name: 'RUNNER_TEMP', value: process.env.RUNNER_TEMP }, + { name: 'RUNNER_WORKSPACE', value: process.env.RUNNER_WORKSPACE }, + ]; + if (parameters.sshAgent) + environmentVariables.push({ name: 'SSH_AUTH_SOCK', value: '/ssh-agent' }); + return environmentVariables; + } +} +exports["default"] = ImageEnvironmentFactory; /***/ }), @@ -3588,140 +3588,140 @@ exports["default"] = ImageEnvironmentFactory; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const platform_1 = __importDefault(__nccwpck_require__(9707)); -class ImageTag { - constructor(imageProperties) { - const { repository = 'unityci', name = 'editor', version = '2019.2.11f1', platform, cloudRunnerBuilderPlatform, customImage, } = imageProperties; - if (!ImageTag.versionPattern.test(version)) { - throw new Error(`Invalid version "${version}".`); - } - const builderPlatformSuffix = ImageTag.getTargetPlatformToImageSuffixMap(platform, version); - this.repository = repository; - this.name = name; - this.version = version; - this.platform = platform; - this.builderPlatformSuffix = builderPlatformSuffix; - this.cloudRunnerBuilderPlatform = cloudRunnerBuilderPlatform; - this.customImage = customImage; - } - static get versionPattern() { - return /^20\d{2}\.\d\.\w{3,4}|3$/; - } - static get imageSuffixes() { - return { - generic: '', - webgl: 'webgl', - mac: 'mac-mono', - windows: 'windows-mono', - windowsIl2cpp: 'windows-il2cpp', - wsaPlayer: 'universal-windows-platform', - linux: 'base', - linuxIl2cpp: 'linux-il2cpp', - android: 'android', - ios: 'ios', - tvos: 'appletv', - facebook: 'facebook', - }; - } - static getTargetPlatformToImageSuffixMap(platform, version) { - const { generic, webgl, mac, windows, windowsIl2cpp, wsaPlayer, linux, linuxIl2cpp, android, ios, tvos, facebook } = ImageTag.imageSuffixes; - const [major, minor] = version.split('.').map((digit) => Number(digit)); - // @see: https://docs.unity3d.com/ScriptReference/BuildTarget.html - switch (platform) { - case platform_1.default.types.StandaloneOSX: - return mac; - case platform_1.default.types.StandaloneWindows: - case platform_1.default.types.StandaloneWindows64: - // Can only build windows-il2cpp on a windows based system - if (process.platform === 'win32') { - // Unity versions before 2019.3 do not support il2cpp - if (major >= 2020 || (major === 2019 && minor >= 3)) { - return windowsIl2cpp; - } - else { + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const platform_1 = __importDefault(__nccwpck_require__(9707)); +class ImageTag { + constructor(imageProperties) { + const { repository = 'unityci', name = 'editor', version = '2019.2.11f1', platform, cloudRunnerBuilderPlatform, customImage, } = imageProperties; + if (!ImageTag.versionPattern.test(version)) { + throw new Error(`Invalid version "${version}".`); + } + const builderPlatformSuffix = ImageTag.getTargetPlatformToImageSuffixMap(platform, version); + this.repository = repository; + this.name = name; + this.version = version; + this.platform = platform; + this.builderPlatformSuffix = builderPlatformSuffix; + this.cloudRunnerBuilderPlatform = cloudRunnerBuilderPlatform; + this.customImage = customImage; + } + static get versionPattern() { + return /^20\d{2}\.\d\.\w{3,4}|3$/; + } + static get imageSuffixes() { + return { + generic: '', + webgl: 'webgl', + mac: 'mac-mono', + windows: 'windows-mono', + windowsIl2cpp: 'windows-il2cpp', + wsaPlayer: 'universal-windows-platform', + linux: 'base', + linuxIl2cpp: 'linux-il2cpp', + android: 'android', + ios: 'ios', + tvos: 'appletv', + facebook: 'facebook', + }; + } + static getTargetPlatformToImageSuffixMap(platform, version) { + const { generic, webgl, mac, windows, windowsIl2cpp, wsaPlayer, linux, linuxIl2cpp, android, ios, tvos, facebook } = ImageTag.imageSuffixes; + const [major, minor] = version.split('.').map((digit) => Number(digit)); + // @see: https://docs.unity3d.com/ScriptReference/BuildTarget.html + switch (platform) { + case platform_1.default.types.StandaloneOSX: + return mac; + case platform_1.default.types.StandaloneWindows: + case platform_1.default.types.StandaloneWindows64: + // Can only build windows-il2cpp on a windows based system + if (process.platform === 'win32') { + // Unity versions before 2019.3 do not support il2cpp + if (major >= 2020 || (major === 2019 && minor >= 3)) { + return windowsIl2cpp; + } + else { throw new Error(`Windows-based builds are only supported on 2019.3.X+ versions of Unity. - If you are trying to build for windows-mono, please use a Linux based OS.`); - } - } - return windows; - case platform_1.default.types.StandaloneLinux64: { - // Unity versions before 2019.3 do not support il2cpp - if (major >= 2020 || (major === 2019 && minor >= 3)) { - return linuxIl2cpp; - } - return linux; - } - case platform_1.default.types.iOS: - return ios; - case platform_1.default.types.Android: - return android; - case platform_1.default.types.WebGL: - return webgl; - case platform_1.default.types.WSAPlayer: - if (process.platform !== 'win32') { - throw new Error(`WSAPlayer can only be built on a windows base OS`); - } - return wsaPlayer; - case platform_1.default.types.PS4: - return windows; - case platform_1.default.types.XboxOne: - return windows; - case platform_1.default.types.tvOS: - if (process.platform !== 'win32') { - throw new Error(`tvOS can only be built on a windows base OS`); - } - return tvos; - case platform_1.default.types.Switch: - return windows; - // Unsupported - case platform_1.default.types.Lumin: - return windows; - case platform_1.default.types.BJM: - return windows; - case platform_1.default.types.Stadia: - return windows; - case platform_1.default.types.Facebook: - return facebook; - case platform_1.default.types.NoTarget: - return generic; - // Test specific - case platform_1.default.types.Test: - return generic; - default: + If you are trying to build for windows-mono, please use a Linux based OS.`); + } + } + return windows; + case platform_1.default.types.StandaloneLinux64: { + // Unity versions before 2019.3 do not support il2cpp + if (major >= 2020 || (major === 2019 && minor >= 3)) { + return linuxIl2cpp; + } + return linux; + } + case platform_1.default.types.iOS: + return ios; + case platform_1.default.types.Android: + return android; + case platform_1.default.types.WebGL: + return webgl; + case platform_1.default.types.WSAPlayer: + if (process.platform !== 'win32') { + throw new Error(`WSAPlayer can only be built on a windows base OS`); + } + return wsaPlayer; + case platform_1.default.types.PS4: + return windows; + case platform_1.default.types.XboxOne: + return windows; + case platform_1.default.types.tvOS: + if (process.platform !== 'win32') { + throw new Error(`tvOS can only be built on a windows base OS`); + } + return tvos; + case platform_1.default.types.Switch: + return windows; + // Unsupported + case platform_1.default.types.Lumin: + return windows; + case platform_1.default.types.BJM: + return windows; + case platform_1.default.types.Stadia: + return windows; + case platform_1.default.types.Facebook: + return facebook; + case platform_1.default.types.NoTarget: + return generic; + // Test specific + case platform_1.default.types.Test: + return generic; + default: throw new Error(` Platform must be one of the ones described in the documentation. - "${platform}" is currently not supported.`); - } - } - get tag() { - const tagPlatform = this.cloudRunnerBuilderPlatform ? this.cloudRunnerBuilderPlatform : process.platform; - //We check the host os so we know what type of the images we need to pull - switch (tagPlatform) { - case 'win32': - return `windows-${this.version}-${this.builderPlatformSuffix}`.replace(/-+$/, ''); - case 'linux': - return `${this.version}-${this.builderPlatformSuffix}`.replace(/-+$/, ''); - default: - break; - } - } - get image() { - return `${this.repository}/${this.name}`.replace(/^\/+/, ''); - } - toString() { - const { image, tag, customImage } = this; - if (customImage && customImage !== '') { - return customImage; - } - return `${image}:${tag}-0`; // '0' here represents the docker repo version - } -} -exports["default"] = ImageTag; + "${platform}" is currently not supported.`); + } + } + get tag() { + const tagPlatform = this.cloudRunnerBuilderPlatform ? this.cloudRunnerBuilderPlatform : process.platform; + //We check the host os so we know what type of the images we need to pull + switch (tagPlatform) { + case 'win32': + return `windows-${this.version}-${this.builderPlatformSuffix}`.replace(/-+$/, ''); + case 'linux': + return `${this.version}-${this.builderPlatformSuffix}`.replace(/-+$/, ''); + default: + break; + } + } + get image() { + return `${this.repository}/${this.name}`.replace(/^\/+/, ''); + } + toString() { + const { image, tag, customImage } = this; + if (customImage && customImage !== '') { + return customImage; + } + return `${image}:${tag}-0`; // '0' here represents the docker repo version + } +} +exports["default"] = ImageTag; /***/ }), @@ -3730,36 +3730,36 @@ exports["default"] = ImageTag; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloudRunner = exports.Versioning = exports.Unity = exports.Project = exports.Platform = exports.Output = exports.ImageTag = exports.Input = exports.Docker = exports.Cache = exports.BuildParameters = exports.Action = void 0; -const action_1 = __importDefault(__nccwpck_require__(89088)); -exports.Action = action_1.default; -const build_parameters_1 = __importDefault(__nccwpck_require__(80787)); -exports.BuildParameters = build_parameters_1.default; -const cache_1 = __importDefault(__nccwpck_require__(97134)); -exports.Cache = cache_1.default; -const docker_1 = __importDefault(__nccwpck_require__(16934)); -exports.Docker = docker_1.default; -const input_1 = __importDefault(__nccwpck_require__(91933)); -exports.Input = input_1.default; -const image_tag_1 = __importDefault(__nccwpck_require__(57648)); -exports.ImageTag = image_tag_1.default; -const output_1 = __importDefault(__nccwpck_require__(85487)); -exports.Output = output_1.default; -const platform_1 = __importDefault(__nccwpck_require__(9707)); -exports.Platform = platform_1.default; -const project_1 = __importDefault(__nccwpck_require__(88666)); -exports.Project = project_1.default; -const unity_1 = __importDefault(__nccwpck_require__(70498)); -exports.Unity = unity_1.default; -const versioning_1 = __importDefault(__nccwpck_require__(88729)); -exports.Versioning = versioning_1.default; -const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); -exports.CloudRunner = cloud_runner_1.default; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloudRunner = exports.Versioning = exports.Unity = exports.Project = exports.Platform = exports.Output = exports.ImageTag = exports.Input = exports.Docker = exports.Cache = exports.BuildParameters = exports.Action = void 0; +const action_1 = __importDefault(__nccwpck_require__(89088)); +exports.Action = action_1.default; +const build_parameters_1 = __importDefault(__nccwpck_require__(80787)); +exports.BuildParameters = build_parameters_1.default; +const cache_1 = __importDefault(__nccwpck_require__(97134)); +exports.Cache = cache_1.default; +const docker_1 = __importDefault(__nccwpck_require__(16934)); +exports.Docker = docker_1.default; +const input_1 = __importDefault(__nccwpck_require__(91933)); +exports.Input = input_1.default; +const image_tag_1 = __importDefault(__nccwpck_require__(57648)); +exports.ImageTag = image_tag_1.default; +const output_1 = __importDefault(__nccwpck_require__(85487)); +exports.Output = output_1.default; +const platform_1 = __importDefault(__nccwpck_require__(9707)); +exports.Platform = platform_1.default; +const project_1 = __importDefault(__nccwpck_require__(88666)); +exports.Project = project_1.default; +const unity_1 = __importDefault(__nccwpck_require__(70498)); +exports.Unity = unity_1.default; +const versioning_1 = __importDefault(__nccwpck_require__(88729)); +exports.Versioning = versioning_1.default; +const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); +exports.CloudRunner = cloud_runner_1.default; /***/ }), @@ -3768,29 +3768,29 @@ exports.CloudRunner = cloud_runner_1.default; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ActionYamlReader = void 0; -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const yaml_1 = __importDefault(__nccwpck_require__(44603)); -class ActionYamlReader { - constructor() { - let filename = `action.yml`; - if (!fs_1.default.existsSync(filename)) { - filename = path_1.default.join(__dirname, `..`, filename); - } - this.actionYamlParsed = yaml_1.default.parse(fs_1.default.readFileSync(filename).toString()); - } - GetActionYamlValue(key) { - var _a; - return ((_a = this.actionYamlParsed.inputs[key]) === null || _a === void 0 ? void 0 : _a.description) || 'No description found in action.yml'; - } -} -exports.ActionYamlReader = ActionYamlReader; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ActionYamlReader = void 0; +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const yaml_1 = __importDefault(__nccwpck_require__(44603)); +class ActionYamlReader { + constructor() { + let filename = `action.yml`; + if (!fs_1.default.existsSync(filename)) { + filename = path_1.default.join(__dirname, `..`, filename); + } + this.actionYamlParsed = yaml_1.default.parse(fs_1.default.readFileSync(filename).toString()); + } + GetActionYamlValue(key) { + var _a; + return ((_a = this.actionYamlParsed.inputs[key]) === null || _a === void 0 ? void 0 : _a.description) || 'No description found in action.yml'; + } +} +exports.ActionYamlReader = ActionYamlReader; /***/ }), @@ -3799,27 +3799,27 @@ exports.ActionYamlReader = ActionYamlReader; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GenericInputReader = void 0; -const cloud_runner_system_1 = __nccwpck_require__(66879); -class GenericInputReader { - static Run(command) { - return __awaiter(this, void 0, void 0, function* () { - return yield cloud_runner_system_1.CloudRunnerSystem.Run(command, false, true); - }); - } -} -exports.GenericInputReader = GenericInputReader; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GenericInputReader = void 0; +const cloud_runner_system_1 = __nccwpck_require__(66879); +class GenericInputReader { + static Run(command) { + return __awaiter(this, void 0, void 0, function* () { + return yield cloud_runner_system_1.CloudRunnerSystem.Run(command, false, true); + }); + } +} +exports.GenericInputReader = GenericInputReader; /***/ }), @@ -3828,42 +3828,42 @@ exports.GenericInputReader = GenericInputReader; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GitRepoReader = void 0; -const console_1 = __nccwpck_require__(96206); -const system_1 = __importDefault(__nccwpck_require__(62177)); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const cloud_runner_system_1 = __nccwpck_require__(66879); -class GitRepoReader { - static GetRemote() { - return __awaiter(this, void 0, void 0, function* () { - return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`git remote -v`, false, true)) - .split(' ')[1] - .split('https://github.com/')[1] - .split('.git')[0]; - }); - } - static GetBranch() { - return __awaiter(this, void 0, void 0, function* () { - console_1.assert(fs_1.default.existsSync(`.git`)); - return (yield system_1.default.run(`git branch`, [], {}, false)).split('*')[1].split(`\n`)[0].replace(/ /g, ``); - }); - } -} -exports.GitRepoReader = GitRepoReader; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GitRepoReader = void 0; +const console_1 = __nccwpck_require__(96206); +const system_1 = __importDefault(__nccwpck_require__(62177)); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const cloud_runner_system_1 = __nccwpck_require__(66879); +class GitRepoReader { + static GetRemote() { + return __awaiter(this, void 0, void 0, function* () { + return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`git remote -v`, false, true)) + .split(' ')[1] + .split('https://github.com/')[1] + .split('.git')[0]; + }); + } + static GetBranch() { + return __awaiter(this, void 0, void 0, function* () { + console_1.assert(fs_1.default.existsSync(`.git`)); + return (yield system_1.default.run(`git branch`, [], {}, false)).split('*')[1].split(`\n`)[0].replace(/ /g, ``); + }); + } +} +exports.GitRepoReader = GitRepoReader; /***/ }), @@ -3872,60 +3872,60 @@ exports.GitRepoReader = GitRepoReader; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GithubCliReader = void 0; -const cloud_runner_system_1 = __nccwpck_require__(66879); -const core = __importStar(__nccwpck_require__(42186)); -class GithubCliReader { - static GetGitHubAuthToken() { - return __awaiter(this, void 0, void 0, function* () { - try { - const authStatus = yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status`, false, true); - if (authStatus.includes('You are not logged') || authStatus === '') { - return ''; - } - return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status -t`, false, true)) - .split(`Token: `)[1] - .replace(/ /g, '') - .replace(/\n/g, ''); - } - catch (error) { - core.info(error || 'Failed to get github auth token from gh cli'); - return ''; - } - }); - } -} -exports.GithubCliReader = GithubCliReader; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GithubCliReader = void 0; +const cloud_runner_system_1 = __nccwpck_require__(66879); +const core = __importStar(__nccwpck_require__(42186)); +class GithubCliReader { + static GetGitHubAuthToken() { + return __awaiter(this, void 0, void 0, function* () { + try { + const authStatus = yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status`, false, true); + if (authStatus.includes('You are not logged') || authStatus === '') { + return ''; + } + return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status -t`, false, true)) + .split(`Token: `)[1] + .replace(/ /g, '') + .replace(/\n/g, ''); + } + catch (error) { + core.info(error || 'Failed to get github auth token from gh cli'); + return ''; + } + }); + } +} +exports.GithubCliReader = GithubCliReader; /***/ }), @@ -3934,20 +3934,20 @@ exports.GithubCliReader = GithubCliReader; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReadLicense = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const yaml_1 = __importDefault(__nccwpck_require__(44603)); -function ReadLicense() { - const pipelineFile = path_1.default.join(__dirname, `.github`, `workflows`, `cloud-runner-k8s-pipeline.yml`); - return fs_1.default.existsSync(pipelineFile) ? yaml_1.default.parse(fs_1.default.readFileSync(pipelineFile, 'utf8')).env.UNITY_LICENSE : ''; -} -exports.ReadLicense = ReadLicense; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReadLicense = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const yaml_1 = __importDefault(__nccwpck_require__(44603)); +function ReadLicense() { + const pipelineFile = path_1.default.join(__dirname, `.github`, `workflows`, `cloud-runner-k8s-pipeline.yml`); + return fs_1.default.existsSync(pipelineFile) ? yaml_1.default.parse(fs_1.default.readFileSync(pipelineFile, 'utf8')).env.UNITY_LICENSE : ''; +} +exports.ReadLicense = ReadLicense; /***/ }), @@ -3956,279 +3956,279 @@ exports.ReadLicense = ReadLicense; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const generic_input_reader_1 = __nccwpck_require__(2263); -const platform_1 = __importDefault(__nccwpck_require__(9707)); -const formatFunction = (value, arguments_) => { - let formatted = value; - for (const argument in arguments_) { - formatted = formatted.replace(`{${arguments_[argument].key}}`, arguments_[argument].value); - } - return formatted; -}; -const core = __nccwpck_require__(42186); -/** - * Input variables specified in workflows using "with" prop. - * - * Note that input is always passed as a string, even booleans. - */ -class Input { - // also enabled debug logging for cloud runner - static get cloudRunnerTests() { - return Input.getInput(`cloudRunnerTests`) || Input.getInput(`CloudRunnerTests`) || false; - } - static shouldUseOverride(query) { - if (Input.readInputOverrideCommand() !== '') { - if (Input.readInputFromOverrideList() !== '') { - const doesInclude = Input.readInputFromOverrideList().split(',').includes(query) || - Input.readInputFromOverrideList().split(',').includes(Input.ToEnvVarFormat(query)); - return doesInclude ? true : false; - } - else { - return true; - } - } - } - static get cliMode() { - return Input.cliOptions !== undefined && Input.cliOptions.mode !== undefined && Input.cliOptions.mode !== ''; - } - static queryOverride(query) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.shouldUseOverride(query)) { - throw new Error(`Should not be trying to run override query on ${query}`); - } - return yield generic_input_reader_1.GenericInputReader.Run(formatFunction(Input.readInputOverrideCommand(), [{ key: 0, value: query }])); - }); - } - static PopulateQueryOverrideInput() { - return __awaiter(this, void 0, void 0, function* () { - const queries = Input.readInputFromOverrideList().split(','); - Input.queryOverrides = new Array(); - for (const element of queries) { - if (Input.shouldUseOverride(element)) { - Input.queryOverrides[element] = yield Input.queryOverride(element); - } - } - }); - } - static getInput(query) { - const coreInput = core.getInput(query); - if (Input.githubInputEnabled && coreInput && coreInput !== '') { - return coreInput; - } - if (Input.cliMode && Input.cliOptions[query] !== undefined) { - return Input.cliOptions[query]; - } - if (Input.queryOverrides !== undefined) { - if (Input.queryOverrides[query] !== null) { - return Input.queryOverrides[query]; - } - if (Input.queryOverrides[Input.ToEnvVarFormat(query)] !== null) { - return Input.queryOverrides[Input.ToEnvVarFormat(query)]; - } - } - if (process.env[query] !== undefined) { - return process.env[query]; - } - if (process.env[Input.ToEnvVarFormat(query)] !== undefined) { - return process.env[Input.ToEnvVarFormat(query)]; - } - return ''; - } - static get region() { - return Input.getInput('region') || 'eu-west-2'; - } - static get githubRepo() { - return Input.getInput('GITHUB_REPOSITORY') || Input.getInput('GITHUB_REPO') || false; - } - static get branch() { - if (Input.getInput(`GITHUB_REF`)) { - return Input.getInput(`GITHUB_REF`).replace('refs/', '').replace(`head/`, ''); - } - else if (Input.getInput('branch')) { - return Input.getInput('branch'); - } - else { - return ''; - } - } - static get cloudRunnerBuilderPlatform() { - return Input.cloudRunnerCluster === 'local' ? Input.getInput('cloudRunnerBuilderPlatform') || false : 'linux'; - } - static get gitSha() { - if (Input.getInput(`GITHUB_SHA`)) { - return Input.getInput(`GITHUB_SHA`); - } - else if (Input.getInput(`GitSHA`)) { - return Input.getInput(`GitSHA`); - } - } - static get runNumber() { - return Input.getInput('GITHUB_RUN_NUMBER') || '0'; - } - static get targetPlatform() { - return Input.getInput('targetPlatform') || platform_1.default.default; - } - static get unityVersion() { - return Input.getInput('unityVersion') || 'auto'; - } - static get customImage() { - return Input.getInput('customImage'); - } - static get projectPath() { - const input = Input.getInput('projectPath'); - const rawProjectPath = input - ? input - : fs_1.default.existsSync(path_1.default.join('test-project', 'ProjectSettings', 'ProjectVersion.txt')) && - !fs_1.default.existsSync(path_1.default.join('ProjectSettings', 'ProjectVersion.txt')) - ? 'test-project' - : '.'; - return rawProjectPath.replace(/\/$/, ''); - } - static get buildName() { - return Input.getInput('buildName') || this.targetPlatform; - } - static get buildsPath() { - return Input.getInput('buildsPath') || 'build'; - } - static get buildMethod() { - return Input.getInput('buildMethod') || ''; // processed in docker file - } - static get customParameters() { - return Input.getInput('customParameters') || ''; - } - static get versioningStrategy() { - return Input.getInput('versioning') || 'Semantic'; - } - static get specifiedVersion() { - return Input.getInput('version') || ''; - } - static get androidVersionCode() { - return Input.getInput('androidVersionCode'); - } - static get androidAppBundle() { - const input = Input.getInput('androidAppBundle') || false; - return input === 'true'; - } - static get androidKeystoreName() { - return Input.getInput('androidKeystoreName') || ''; - } - static get androidKeystoreBase64() { - return Input.getInput('androidKeystoreBase64') || ''; - } - static get androidKeystorePass() { - return Input.getInput('androidKeystorePass') || ''; - } - static get androidKeyaliasName() { - return Input.getInput('androidKeyaliasName') || ''; - } - static get androidKeyaliasPass() { - return Input.getInput('androidKeyaliasPass') || ''; - } - static get androidTargetSdkVersion() { - return core.getInput('androidTargetSdkVersion') || ''; - } - static get sshAgent() { - return Input.getInput('sshAgent') || ''; - } - static get gitPrivateToken() { - return core.getInput('gitPrivateToken') || false; - } - static get customJob() { - return Input.getInput('customJob') || ''; - } - static customJobHooks() { - return Input.getInput('customJobHooks') || ''; - } - static cachePushOverrideCommand() { - return Input.getInput('cachePushOverrideCommand') || ''; - } - static cachePullOverrideCommand() { - return Input.getInput('cachePullOverrideCommand') || ''; - } - static readInputFromOverrideList() { - return Input.getInput('readInputFromOverrideList') || ''; - } - static readInputOverrideCommand() { - return Input.getInput('readInputOverrideCommand') || ''; - } - static get cloudRunnerBranch() { - return Input.getInput('cloudRunnerBranch') || 'cloud-runner-develop'; - } - static get chownFilesTo() { - return Input.getInput('chownFilesTo') || ''; - } - static get allowDirtyBuild() { - const input = Input.getInput('allowDirtyBuild') || false; - return input === 'true'; - } - static get postBuildSteps() { - return Input.getInput('postBuildSteps') || ''; - } - static get preBuildSteps() { - return Input.getInput('preBuildSteps') || ''; - } - static get awsBaseStackName() { - return Input.getInput('awsBaseStackName') || 'game-ci'; - } - static get cloudRunnerCluster() { - if (Input.cliMode) { - return Input.getInput('cloudRunnerCluster') || 'aws'; - } - return Input.getInput('cloudRunnerCluster') || 'local'; - } - static get cloudRunnerCpu() { - return Input.getInput('cloudRunnerCpu') || '1.0'; - } - static get cloudRunnerMemory() { - return Input.getInput('cloudRunnerMemory') || '750M'; - } - static get kubeConfig() { - return Input.getInput('kubeConfig') || ''; - } - static get kubeVolume() { - return Input.getInput('kubeVolume') || ''; - } - static get kubeVolumeSize() { - return Input.getInput('kubeVolumeSize') || '5Gi'; - } - static get kubeStorageClass() { - return Input.getInput('kubeStorageClass') || ''; - } - static get checkDependencyHealthOverride() { - return Input.getInput('checkDependencyHealthOverride') || ''; - } - static get startDependenciesOverride() { - return Input.getInput('startDependenciesOverride') || ''; - } - static get cacheKey() { - return Input.getInput('cacheKey') || ''; - } - static ToEnvVarFormat(input) { - return input - .replace(/([A-Z])/g, ' $1') - .trim() - .toUpperCase() - .replace(/ /g, '_'); - } -} -Input.githubInputEnabled = true; -exports["default"] = Input; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const generic_input_reader_1 = __nccwpck_require__(2263); +const platform_1 = __importDefault(__nccwpck_require__(9707)); +const formatFunction = (value, arguments_) => { + let formatted = value; + for (const argument in arguments_) { + formatted = formatted.replace(`{${arguments_[argument].key}}`, arguments_[argument].value); + } + return formatted; +}; +const core = __nccwpck_require__(42186); +/** + * Input variables specified in workflows using "with" prop. + * + * Note that input is always passed as a string, even booleans. + */ +class Input { + // also enabled debug logging for cloud runner + static get cloudRunnerTests() { + return Input.getInput(`cloudRunnerTests`) || Input.getInput(`CloudRunnerTests`) || false; + } + static shouldUseOverride(query) { + if (Input.readInputOverrideCommand() !== '') { + if (Input.readInputFromOverrideList() !== '') { + const doesInclude = Input.readInputFromOverrideList().split(',').includes(query) || + Input.readInputFromOverrideList().split(',').includes(Input.ToEnvVarFormat(query)); + return doesInclude ? true : false; + } + else { + return true; + } + } + } + static get cliMode() { + return Input.cliOptions !== undefined && Input.cliOptions.mode !== undefined && Input.cliOptions.mode !== ''; + } + static queryOverride(query) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.shouldUseOverride(query)) { + throw new Error(`Should not be trying to run override query on ${query}`); + } + return yield generic_input_reader_1.GenericInputReader.Run(formatFunction(Input.readInputOverrideCommand(), [{ key: 0, value: query }])); + }); + } + static PopulateQueryOverrideInput() { + return __awaiter(this, void 0, void 0, function* () { + const queries = Input.readInputFromOverrideList().split(','); + Input.queryOverrides = new Array(); + for (const element of queries) { + if (Input.shouldUseOverride(element)) { + Input.queryOverrides[element] = yield Input.queryOverride(element); + } + } + }); + } + static getInput(query) { + const coreInput = core.getInput(query); + if (Input.githubInputEnabled && coreInput && coreInput !== '') { + return coreInput; + } + if (Input.cliMode && Input.cliOptions[query] !== undefined) { + return Input.cliOptions[query]; + } + if (Input.queryOverrides !== undefined) { + if (Input.queryOverrides[query] !== null) { + return Input.queryOverrides[query]; + } + if (Input.queryOverrides[Input.ToEnvVarFormat(query)] !== null) { + return Input.queryOverrides[Input.ToEnvVarFormat(query)]; + } + } + if (process.env[query] !== undefined) { + return process.env[query]; + } + if (process.env[Input.ToEnvVarFormat(query)] !== undefined) { + return process.env[Input.ToEnvVarFormat(query)]; + } + return ''; + } + static get region() { + return Input.getInput('region') || 'eu-west-2'; + } + static get githubRepo() { + return Input.getInput('GITHUB_REPOSITORY') || Input.getInput('GITHUB_REPO') || false; + } + static get branch() { + if (Input.getInput(`GITHUB_REF`)) { + return Input.getInput(`GITHUB_REF`).replace('refs/', '').replace(`head/`, ''); + } + else if (Input.getInput('branch')) { + return Input.getInput('branch'); + } + else { + return ''; + } + } + static get cloudRunnerBuilderPlatform() { + return Input.cloudRunnerCluster === 'local' ? Input.getInput('cloudRunnerBuilderPlatform') || false : 'linux'; + } + static get gitSha() { + if (Input.getInput(`GITHUB_SHA`)) { + return Input.getInput(`GITHUB_SHA`); + } + else if (Input.getInput(`GitSHA`)) { + return Input.getInput(`GitSHA`); + } + } + static get runNumber() { + return Input.getInput('GITHUB_RUN_NUMBER') || '0'; + } + static get targetPlatform() { + return Input.getInput('targetPlatform') || platform_1.default.default; + } + static get unityVersion() { + return Input.getInput('unityVersion') || 'auto'; + } + static get customImage() { + return Input.getInput('customImage'); + } + static get projectPath() { + const input = Input.getInput('projectPath'); + const rawProjectPath = input + ? input + : fs_1.default.existsSync(path_1.default.join('test-project', 'ProjectSettings', 'ProjectVersion.txt')) && + !fs_1.default.existsSync(path_1.default.join('ProjectSettings', 'ProjectVersion.txt')) + ? 'test-project' + : '.'; + return rawProjectPath.replace(/\/$/, ''); + } + static get buildName() { + return Input.getInput('buildName') || this.targetPlatform; + } + static get buildsPath() { + return Input.getInput('buildsPath') || 'build'; + } + static get buildMethod() { + return Input.getInput('buildMethod') || ''; // processed in docker file + } + static get customParameters() { + return Input.getInput('customParameters') || ''; + } + static get versioningStrategy() { + return Input.getInput('versioning') || 'Semantic'; + } + static get specifiedVersion() { + return Input.getInput('version') || ''; + } + static get androidVersionCode() { + return Input.getInput('androidVersionCode'); + } + static get androidAppBundle() { + const input = Input.getInput('androidAppBundle') || false; + return input === 'true'; + } + static get androidKeystoreName() { + return Input.getInput('androidKeystoreName') || ''; + } + static get androidKeystoreBase64() { + return Input.getInput('androidKeystoreBase64') || ''; + } + static get androidKeystorePass() { + return Input.getInput('androidKeystorePass') || ''; + } + static get androidKeyaliasName() { + return Input.getInput('androidKeyaliasName') || ''; + } + static get androidKeyaliasPass() { + return Input.getInput('androidKeyaliasPass') || ''; + } + static get androidTargetSdkVersion() { + return core.getInput('androidTargetSdkVersion') || ''; + } + static get sshAgent() { + return Input.getInput('sshAgent') || ''; + } + static get gitPrivateToken() { + return core.getInput('gitPrivateToken') || false; + } + static get customJob() { + return Input.getInput('customJob') || ''; + } + static customJobHooks() { + return Input.getInput('customJobHooks') || ''; + } + static cachePushOverrideCommand() { + return Input.getInput('cachePushOverrideCommand') || ''; + } + static cachePullOverrideCommand() { + return Input.getInput('cachePullOverrideCommand') || ''; + } + static readInputFromOverrideList() { + return Input.getInput('readInputFromOverrideList') || ''; + } + static readInputOverrideCommand() { + return Input.getInput('readInputOverrideCommand') || ''; + } + static get cloudRunnerBranch() { + return Input.getInput('cloudRunnerBranch') || 'cloud-runner-develop'; + } + static get chownFilesTo() { + return Input.getInput('chownFilesTo') || ''; + } + static get allowDirtyBuild() { + const input = Input.getInput('allowDirtyBuild') || false; + return input === 'true'; + } + static get postBuildSteps() { + return Input.getInput('postBuildSteps') || ''; + } + static get preBuildSteps() { + return Input.getInput('preBuildSteps') || ''; + } + static get awsBaseStackName() { + return Input.getInput('awsBaseStackName') || 'game-ci'; + } + static get cloudRunnerCluster() { + if (Input.cliMode) { + return Input.getInput('cloudRunnerCluster') || 'aws'; + } + return Input.getInput('cloudRunnerCluster') || 'local'; + } + static get cloudRunnerCpu() { + return Input.getInput('cloudRunnerCpu') || '1.0'; + } + static get cloudRunnerMemory() { + return Input.getInput('cloudRunnerMemory') || '750M'; + } + static get kubeConfig() { + return Input.getInput('kubeConfig') || ''; + } + static get kubeVolume() { + return Input.getInput('kubeVolume') || ''; + } + static get kubeVolumeSize() { + return Input.getInput('kubeVolumeSize') || '5Gi'; + } + static get kubeStorageClass() { + return Input.getInput('kubeStorageClass') || ''; + } + static get checkDependencyHealthOverride() { + return Input.getInput('checkDependencyHealthOverride') || ''; + } + static get startDependenciesOverride() { + return Input.getInput('startDependenciesOverride') || ''; + } + static get cacheKey() { + return Input.getInput('cacheKey') || ''; + } + static ToEnvVarFormat(input) { + return input + .replace(/([A-Z])/g, ' $1') + .trim() + .toUpperCase() + .replace(/ /g, '_'); + } +} +Input.githubInputEnabled = true; +exports["default"] = Input; /***/ }), @@ -4237,29 +4237,29 @@ exports["default"] = Input; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const exec_1 = __nccwpck_require__(71514); -class MacBuilder { - static run(actionFolder, workspace, buildParameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - yield exec_1.exec('bash', [`${actionFolder}/platforms/mac/entrypoint.sh`], { - silent, - ignoreReturnCode: true, - }); - }); - } -} -exports["default"] = MacBuilder; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const exec_1 = __nccwpck_require__(71514); +class MacBuilder { + static run(actionFolder, workspace, buildParameters, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + yield exec_1.exec('bash', [`${actionFolder}/platforms/mac/entrypoint.sh`], { + silent, + ignoreReturnCode: true, + }); + }); + } +} +exports["default"] = MacBuilder; /***/ }), @@ -4268,26 +4268,26 @@ exports["default"] = MacBuilder; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __nccwpck_require__(42186); -class Output { - static setBuildVersion(buildVersion) { - return __awaiter(this, void 0, void 0, function* () { - yield core.setOutput('buildVersion', buildVersion); - }); - } -} -exports["default"] = Output; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(42186); +class Output { + static setBuildVersion(buildVersion) { + return __awaiter(this, void 0, void 0, function* () { + yield core.setOutput('buildVersion', buildVersion); + }); + } +} +exports["default"] = Output; /***/ }), @@ -4296,39 +4296,39 @@ exports["default"] = Output; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const platform_setup_1 = __nccwpck_require__(2014); -const validate_windows_1 = __importDefault(__nccwpck_require__(41563)); -class PlatformSetup { - static setup(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - switch (process.platform) { - case 'win32': - validate_windows_1.default.validate(buildParameters); - platform_setup_1.SetupWindows.setup(buildParameters); - break; - case 'darwin': - yield platform_setup_1.SetupMac.setup(buildParameters, actionFolder); - break; - //Add other baseOS's here - } - }); - } -} -exports["default"] = PlatformSetup; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const platform_setup_1 = __nccwpck_require__(2014); +const validate_windows_1 = __importDefault(__nccwpck_require__(41563)); +class PlatformSetup { + static setup(buildParameters, actionFolder) { + return __awaiter(this, void 0, void 0, function* () { + switch (process.platform) { + case 'win32': + validate_windows_1.default.validate(buildParameters); + platform_setup_1.SetupWindows.setup(buildParameters); + break; + case 'darwin': + yield platform_setup_1.SetupMac.setup(buildParameters, actionFolder); + break; + //Add other baseOS's here + } + }); + } +} +exports["default"] = PlatformSetup; /***/ }), @@ -4337,16 +4337,16 @@ exports["default"] = PlatformSetup; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SetupMac = exports.SetupWindows = void 0; -const setup_windows_1 = __importDefault(__nccwpck_require__(37449)); -exports.SetupWindows = setup_windows_1.default; -const setup_mac_1 = __importDefault(__nccwpck_require__(22466)); -exports.SetupMac = setup_mac_1.default; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SetupMac = exports.SetupWindows = void 0; +const setup_windows_1 = __importDefault(__nccwpck_require__(37449)); +exports.SetupWindows = setup_windows_1.default; +const setup_mac_1 = __importDefault(__nccwpck_require__(22466)); +exports.SetupMac = setup_mac_1.default; /***/ }), @@ -4355,93 +4355,93 @@ exports.SetupMac = setup_mac_1.default; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const unity_changeset_1 = __nccwpck_require__(4635); -const exec_1 = __nccwpck_require__(71514); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -class SetupMac { - static setup(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.version}/Unity.app/Contents/MacOS/Unity`; - // Only install unity if the editor doesn't already exist - if (!fs_1.default.existsSync(unityEditorPath)) { - yield SetupMac.installUnityHub(); - yield SetupMac.installUnity(buildParameters); - } - yield SetupMac.setEnvironmentVariables(buildParameters, actionFolder); - }); - } - static installUnityHub(silent = false) { - return __awaiter(this, void 0, void 0, function* () { - const command = 'brew install unity-hub'; - if (!fs_1.default.existsSync(this.unityHubPath)) { - // Ignoring return code because the log seems to overflow the internal buffer which triggers - // a false error - const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); - if (errorCode) { - throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); - } - } - }); - } - static installUnity(buildParameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - const unityChangeset = yield unity_changeset_1.getUnityChangeset(buildParameters.version); + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const unity_changeset_1 = __nccwpck_require__(4635); +const exec_1 = __nccwpck_require__(71514); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +class SetupMac { + static setup(buildParameters, actionFolder) { + return __awaiter(this, void 0, void 0, function* () { + const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.version}/Unity.app/Contents/MacOS/Unity`; + // Only install unity if the editor doesn't already exist + if (!fs_1.default.existsSync(unityEditorPath)) { + yield SetupMac.installUnityHub(); + yield SetupMac.installUnity(buildParameters); + } + yield SetupMac.setEnvironmentVariables(buildParameters, actionFolder); + }); + } + static installUnityHub(silent = false) { + return __awaiter(this, void 0, void 0, function* () { + const command = 'brew install unity-hub'; + if (!fs_1.default.existsSync(this.unityHubPath)) { + // Ignoring return code because the log seems to overflow the internal buffer which triggers + // a false error + const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); + if (errorCode) { + throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); + } + } + }); + } + static installUnity(buildParameters, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + const unityChangeset = yield unity_changeset_1.getUnityChangeset(buildParameters.version); const command = `${this.unityHubPath} -- --headless install \ --version ${buildParameters.version} \ --changeset ${unityChangeset.changeset} \ --module mac-il2cpp \ - --childModules`; - // Ignoring return code because the log seems to overflow the internal buffer which triggers - // a false error - const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); - if (errorCode) { - throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); - } - }); - } - static setEnvironmentVariables(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - // Need to set environment variables from here because we execute - // the scripts on the host for mac - process.env.ACTION_FOLDER = actionFolder; - process.env.UNITY_VERSION = buildParameters.version; - process.env.UNITY_SERIAL = buildParameters.unitySerial; - process.env.PROJECT_PATH = buildParameters.projectPath; - process.env.BUILD_TARGET = buildParameters.platform; - process.env.BUILD_NAME = buildParameters.buildName; - process.env.BUILD_PATH = buildParameters.buildPath; - process.env.BUILD_FILE = buildParameters.buildFile; - process.env.BUILD_METHOD = buildParameters.buildMethod; - process.env.VERSION = buildParameters.buildVersion; - process.env.ANDROID_VERSION_CODE = buildParameters.androidVersionCode; - process.env.ANDROID_KEYSTORE_NAME = buildParameters.androidKeystoreName; - process.env.ANDROID_KEYSTORE_BASE64 = buildParameters.androidKeystoreBase64; - process.env.ANDROID_KEYSTORE_PASS = buildParameters.androidKeystorePass; - process.env.ANDROID_KEYALIAS_NAME = buildParameters.androidKeyaliasName; - process.env.ANDROID_KEYALIAS_PASS = buildParameters.androidKeyaliasPass; - process.env.ANDROID_TARGET_SDK_VERSION = buildParameters.androidTargetSdkVersion; - process.env.ANDROID_SDK_MANAGER_PARAMETERS = buildParameters.androidSdkManagerParameters; - process.env.CUSTOM_PARAMETERS = buildParameters.customParameters; - process.env.CHOWN_FILES_TO = buildParameters.chownFilesTo; - }); - } -} -SetupMac.unityHubPath = `"/Applications/Unity Hub.app/Contents/MacOS/Unity Hub"`; -exports["default"] = SetupMac; + --childModules`; + // Ignoring return code because the log seems to overflow the internal buffer which triggers + // a false error + const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); + if (errorCode) { + throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); + } + }); + } + static setEnvironmentVariables(buildParameters, actionFolder) { + return __awaiter(this, void 0, void 0, function* () { + // Need to set environment variables from here because we execute + // the scripts on the host for mac + process.env.ACTION_FOLDER = actionFolder; + process.env.UNITY_VERSION = buildParameters.version; + process.env.UNITY_SERIAL = buildParameters.unitySerial; + process.env.PROJECT_PATH = buildParameters.projectPath; + process.env.BUILD_TARGET = buildParameters.platform; + process.env.BUILD_NAME = buildParameters.buildName; + process.env.BUILD_PATH = buildParameters.buildPath; + process.env.BUILD_FILE = buildParameters.buildFile; + process.env.BUILD_METHOD = buildParameters.buildMethod; + process.env.VERSION = buildParameters.buildVersion; + process.env.ANDROID_VERSION_CODE = buildParameters.androidVersionCode; + process.env.ANDROID_KEYSTORE_NAME = buildParameters.androidKeystoreName; + process.env.ANDROID_KEYSTORE_BASE64 = buildParameters.androidKeystoreBase64; + process.env.ANDROID_KEYSTORE_PASS = buildParameters.androidKeystorePass; + process.env.ANDROID_KEYALIAS_NAME = buildParameters.androidKeyaliasName; + process.env.ANDROID_KEYALIAS_PASS = buildParameters.androidKeyaliasPass; + process.env.ANDROID_TARGET_SDK_VERSION = buildParameters.androidTargetSdkVersion; + process.env.ANDROID_SDK_MANAGER_PARAMETERS = buildParameters.androidSdkManagerParameters; + process.env.CUSTOM_PARAMETERS = buildParameters.customParameters; + process.env.CHOWN_FILES_TO = buildParameters.chownFilesTo; + }); + } +} +SetupMac.unityHubPath = `"/Applications/Unity Hub.app/Contents/MacOS/Unity Hub"`; +exports["default"] = SetupMac; /***/ }), @@ -4450,53 +4450,53 @@ exports["default"] = SetupMac; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const exec_1 = __nccwpck_require__(71514); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -class SetupWindows { - static setup(buildParameters) { - return __awaiter(this, void 0, void 0, function* () { - yield SetupWindows.setupWindowsRun(buildParameters.platform); - }); - } - //Setup prerequisite files/folders for a windows-based docker run - static setupWindowsRun(platform, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - if (!fs_1.default.existsSync('c:/regkeys')) { - fs_1.default.mkdirSync('c:/regkeys'); - } - switch (platform) { - //These all need the Windows 10 SDK - case 'StandaloneWindows': - case 'StandaloneWindows64': - case 'WSAPlayer': - this.generateWinSDKRegKeys(silent); - break; - } - }); - } - static generateWinSDKRegKeys(silent = false) { - return __awaiter(this, void 0, void 0, function* () { - // Export registry keys that point to the location of the windows 10 sdk - const exportWinSDKRegKeysCommand = 'reg export "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0" c:/regkeys/winsdk.reg /y'; - yield exec_1.exec(exportWinSDKRegKeysCommand, undefined, { silent }); - }); - } -} -exports["default"] = SetupWindows; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const exec_1 = __nccwpck_require__(71514); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +class SetupWindows { + static setup(buildParameters) { + return __awaiter(this, void 0, void 0, function* () { + yield SetupWindows.setupWindowsRun(buildParameters.platform); + }); + } + //Setup prerequisite files/folders for a windows-based docker run + static setupWindowsRun(platform, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + if (!fs_1.default.existsSync('c:/regkeys')) { + fs_1.default.mkdirSync('c:/regkeys'); + } + switch (platform) { + //These all need the Windows 10 SDK + case 'StandaloneWindows': + case 'StandaloneWindows64': + case 'WSAPlayer': + this.generateWinSDKRegKeys(silent); + break; + } + }); + } + static generateWinSDKRegKeys(silent = false) { + return __awaiter(this, void 0, void 0, function* () { + // Export registry keys that point to the location of the windows 10 sdk + const exportWinSDKRegKeysCommand = 'reg export "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0" c:/regkeys/winsdk.reg /y'; + yield exec_1.exec(exportWinSDKRegKeysCommand, undefined, { silent }); + }); + } +} +exports["default"] = SetupWindows; /***/ }), @@ -4505,61 +4505,61 @@ exports["default"] = SetupWindows; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -class ValidateWindows { - static validate(buildParameters) { - ValidateWindows.validateWindowsPlatformRequirements(buildParameters.platform); - if (!(process.env.UNITY_EMAIL && process.env.UNITY_PASSWORD)) { + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +class ValidateWindows { + static validate(buildParameters) { + ValidateWindows.validateWindowsPlatformRequirements(buildParameters.platform); + if (!(process.env.UNITY_EMAIL && process.env.UNITY_PASSWORD)) { throw new Error(`Unity email and password must be set for Windows based builds to authenticate the license. Make sure to set them inside UNITY_EMAIL - and UNITY_PASSWORD in Github Secrets and pass them into the environment.`); - } - } - static validateWindowsPlatformRequirements(platform) { - switch (platform) { - case 'StandaloneWindows': - this.checkForVisualStudio(); - this.checkForWin10SDK(); - break; - case 'StandaloneWindows64': - this.checkForVisualStudio(); - this.checkForWin10SDK(); - break; - case 'WSAPlayer': - this.checkForVisualStudio(); - this.checkForWin10SDK(); - break; - case 'tvOS': - this.checkForVisualStudio(); - break; - } - } - static checkForWin10SDK() { - //Check for Windows 10 SDK on runner - const windows10SDKPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Windows Kits'); - if (!windows10SDKPathExists) { + and UNITY_PASSWORD in Github Secrets and pass them into the environment.`); + } + } + static validateWindowsPlatformRequirements(platform) { + switch (platform) { + case 'StandaloneWindows': + this.checkForVisualStudio(); + this.checkForWin10SDK(); + break; + case 'StandaloneWindows64': + this.checkForVisualStudio(); + this.checkForWin10SDK(); + break; + case 'WSAPlayer': + this.checkForVisualStudio(); + this.checkForWin10SDK(); + break; + case 'tvOS': + this.checkForVisualStudio(); + break; + } + } + static checkForWin10SDK() { + //Check for Windows 10 SDK on runner + const windows10SDKPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Windows Kits'); + if (!windows10SDKPathExists) { throw new Error(`Windows 10 SDK not found in default location. Make sure the runner has a Windows 10 SDK installed in the default - location.`); - } - } - static checkForVisualStudio() { - //Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit - const visualStudioInstallPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Microsoft Visual Studio'); - const visualStudioDataPathExists = fs_1.default.existsSync('C:/ProgramData/Microsoft/VisualStudio'); - if (!visualStudioInstallPathExists || !visualStudioDataPathExists) { + location.`); + } + } + static checkForVisualStudio() { + //Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit + const visualStudioInstallPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Microsoft Visual Studio'); + const visualStudioDataPathExists = fs_1.default.existsSync('C:/ProgramData/Microsoft/VisualStudio'); + if (!visualStudioInstallPathExists || !visualStudioDataPathExists) { throw new Error(`Visual Studio not found at the default location. Make sure the runner has Visual Studio installed in the - default location`); - } - } -} -exports["default"] = ValidateWindows; + default location`); + } + } +} +exports["default"] = ValidateWindows; /***/ }), @@ -4568,55 +4568,55 @@ exports["default"] = ValidateWindows; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class Platform { - static get default() { - return Platform.types.StandaloneWindows64; - } - static get types() { - return { - StandaloneOSX: 'StandaloneOSX', - StandaloneWindows: 'StandaloneWindows', - StandaloneWindows64: 'StandaloneWindows64', - StandaloneLinux64: 'StandaloneLinux64', - iOS: 'iOS', - Android: 'Android', - WebGL: 'WebGL', - WSAPlayer: 'WSAPlayer', - PS4: 'PS4', - XboxOne: 'XboxOne', - tvOS: 'tvOS', - Switch: 'Switch', - // Unsupported - Lumin: 'Lumin', - BJM: 'BJM', - Stadia: 'Stadia', - Facebook: 'Facebook', - NoTarget: 'NoTarget', - // Test specific - Test: 'Test', - }; - } - static isWindows(platform) { - switch (platform) { - case Platform.types.StandaloneWindows: - case Platform.types.StandaloneWindows64: - return true; - default: - return false; - } - } - static isAndroid(platform) { - switch (platform) { - case Platform.types.Android: - return true; - default: - return false; - } - } -} -exports["default"] = Platform; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class Platform { + static get default() { + return Platform.types.StandaloneWindows64; + } + static get types() { + return { + StandaloneOSX: 'StandaloneOSX', + StandaloneWindows: 'StandaloneWindows', + StandaloneWindows64: 'StandaloneWindows64', + StandaloneLinux64: 'StandaloneLinux64', + iOS: 'iOS', + Android: 'Android', + WebGL: 'WebGL', + WSAPlayer: 'WSAPlayer', + PS4: 'PS4', + XboxOne: 'XboxOne', + tvOS: 'tvOS', + Switch: 'Switch', + // Unsupported + Lumin: 'Lumin', + BJM: 'BJM', + Stadia: 'Stadia', + Facebook: 'Facebook', + NoTarget: 'NoTarget', + // Test specific + Test: 'Test', + }; + } + static isWindows(platform) { + switch (platform) { + case Platform.types.StandaloneWindows: + case Platform.types.StandaloneWindows64: + return true; + default: + return false; + } + } + static isAndroid(platform) { + switch (platform) { + case Platform.types.Android: + return true; + default: + return false; + } + } +} +exports["default"] = Platform; /***/ }), @@ -4625,28 +4625,28 @@ exports["default"] = Platform; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const input_1 = __importDefault(__nccwpck_require__(91933)); -const unity_1 = __importDefault(__nccwpck_require__(70498)); -const action_1 = __importDefault(__nccwpck_require__(89088)); -class Project { - static get relativePath() { - const { projectPath } = input_1.default; - return `${projectPath}`; - } - static get absolutePath() { - const { workspace } = action_1.default; - return `${workspace}/${this.relativePath}`; - } - static get libraryFolder() { - return `${this.relativePath}/${unity_1.default.libraryFolder}`; - } -} -exports["default"] = Project; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const input_1 = __importDefault(__nccwpck_require__(91933)); +const unity_1 = __importDefault(__nccwpck_require__(70498)); +const action_1 = __importDefault(__nccwpck_require__(89088)); +class Project { + static get relativePath() { + const { projectPath } = input_1.default; + return `${projectPath}`; + } + static get absolutePath() { + const { workspace } = action_1.default; + return `${workspace}/${this.relativePath}`; + } + static get libraryFolder() { + return `${this.relativePath}/${unity_1.default.libraryFolder}`; + } +} +exports["default"] = Project; /***/ }), @@ -4655,92 +4655,92 @@ exports["default"] = Project; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const exec_1 = __nccwpck_require__(71514); -class System { - static run(command, arguments_ = [], options = {}, shouldLog = true) { - return __awaiter(this, void 0, void 0, function* () { - let result = ''; - let error = ''; - let debug = ''; - const listeners = { - stdout: (dataBuffer) => { - result += dataBuffer.toString(); - }, - stderr: (dataBuffer) => { - error += dataBuffer.toString(); - }, - debug: (dataString) => { - debug += dataString.toString(); - }, - }; - const showOutput = () => { - if (debug !== '' && shouldLog) { - core.debug(debug); - } - if (result !== '' && shouldLog) { - core.info(result); - } - if (error !== '' && shouldLog) { - core.warning(error); - } - }; - const throwContextualError = (message) => { - let commandAsString = command; - if (Array.isArray(arguments_)) { - commandAsString += ` ${arguments_.join(' ')}`; - } - else if (typeof arguments_ === 'string') { - commandAsString += ` ${arguments_}`; - } - throw new Error(`Failed to run "${commandAsString}".\n ${message}`); - }; - try { - const exitCode = yield exec_1.exec(command, arguments_, Object.assign({ silent: true, listeners }, options)); - showOutput(); - if (exitCode !== 0) { - throwContextualError(`Command returned non-zero exit code.\nError: ${error}`); - } - } - catch (inCommandError) { - showOutput(); - throwContextualError(`In-command error caught: ${inCommandError}`); - } - return result; - }); - } -} -exports["default"] = System; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +const exec_1 = __nccwpck_require__(71514); +class System { + static run(command, arguments_ = [], options = {}, shouldLog = true) { + return __awaiter(this, void 0, void 0, function* () { + let result = ''; + let error = ''; + let debug = ''; + const listeners = { + stdout: (dataBuffer) => { + result += dataBuffer.toString(); + }, + stderr: (dataBuffer) => { + error += dataBuffer.toString(); + }, + debug: (dataString) => { + debug += dataString.toString(); + }, + }; + const showOutput = () => { + if (debug !== '' && shouldLog) { + core.debug(debug); + } + if (result !== '' && shouldLog) { + core.info(result); + } + if (error !== '' && shouldLog) { + core.warning(error); + } + }; + const throwContextualError = (message) => { + let commandAsString = command; + if (Array.isArray(arguments_)) { + commandAsString += ` ${arguments_.join(' ')}`; + } + else if (typeof arguments_ === 'string') { + commandAsString += ` ${arguments_}`; + } + throw new Error(`Failed to run "${commandAsString}".\n ${message}`); + }; + try { + const exitCode = yield exec_1.exec(command, arguments_, Object.assign({ silent: true, listeners }, options)); + showOutput(); + if (exitCode !== 0) { + throwContextualError(`Command returned non-zero exit code.\nError: ${error}`); + } + } + catch (inCommandError) { + showOutput(); + throwContextualError(`In-command error caught: ${inCommandError}`); + } + return result; + }); + } +} +exports["default"] = System; /***/ }), @@ -4749,58 +4749,58 @@ exports["default"] = System; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs = __importStar(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -class UnityVersioning { - static get versionPattern() { - return /20\d{2}\.\d\.\w{3,4}|3/; - } - static determineUnityVersion(projectPath, unityVersion) { - if (unityVersion === 'auto') { - return UnityVersioning.read(projectPath); - } - return unityVersion; - } - static read(projectPath) { - const filePath = path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); - if (!fs.existsSync(filePath)) { - throw new Error(`Project settings file not found at "${filePath}". Have you correctly set the projectPath?`); - } - return UnityVersioning.parse(fs.readFileSync(filePath, 'utf8')); - } - static parse(projectVersionTxt) { - const matches = projectVersionTxt.match(UnityVersioning.versionPattern); - if (!matches || matches.length === 0) { - throw new Error(`Failed to parse version from "${projectVersionTxt}".`); - } - return matches[0]; - } -} -exports["default"] = UnityVersioning; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs = __importStar(__nccwpck_require__(57147)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +class UnityVersioning { + static get versionPattern() { + return /20\d{2}\.\d\.\w{3,4}|3/; + } + static determineUnityVersion(projectPath, unityVersion) { + if (unityVersion === 'auto') { + return UnityVersioning.read(projectPath); + } + return unityVersion; + } + static read(projectPath) { + const filePath = path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); + if (!fs.existsSync(filePath)) { + throw new Error(`Project settings file not found at "${filePath}". Have you correctly set the projectPath?`); + } + return UnityVersioning.parse(fs.readFileSync(filePath, 'utf8')); + } + static parse(projectVersionTxt) { + const matches = projectVersionTxt.match(UnityVersioning.versionPattern); + if (!matches || matches.length === 0) { + throw new Error(`Failed to parse version from "${projectVersionTxt}".`); + } + return matches[0]; + } +} +exports["default"] = UnityVersioning; /***/ }), @@ -4809,14 +4809,14 @@ exports["default"] = UnityVersioning; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class Unity { - static get libraryFolder() { - return 'Library'; - } -} -exports["default"] = Unity; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +class Unity { + static get libraryFolder() { + return 'Library'; + } +} +exports["default"] = Unity; /***/ }), @@ -4825,325 +4825,325 @@ exports["default"] = Unity; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(42186)); -const not_implemented_exception_1 = __importDefault(__nccwpck_require__(26574)); -const validation_error_1 = __importDefault(__nccwpck_require__(97266)); -const input_1 = __importDefault(__nccwpck_require__(91933)); -const system_1 = __importDefault(__nccwpck_require__(62177)); -class Versioning { - static get projectPath() { - return input_1.default.projectPath; - } - static get isDirtyAllowed() { - return input_1.default.allowDirtyBuild; - } - static get strategies() { - return { None: 'None', Semantic: 'Semantic', Tag: 'Tag', Custom: 'Custom' }; - } - /** - * Get the branch name of the (related) branch - */ - static get branch() { - // Todo - use optional chaining (https://github.com/zeit/ncc/issues/534) - return this.headRef || (this.ref && this.ref.slice(11)); - } - /** - * For pull requests we can reliably use GITHUB_HEAD_REF - */ - static get headRef() { - return process.env.GITHUB_HEAD_REF; - } - /** - * For branches GITHUB_REF will have format `refs/heads/feature-branch-1` - */ - static get ref() { - return process.env.GITHUB_REF; - } - /** - * The commit SHA that triggered the workflow run. - */ - static get sha() { - return process.env.GITHUB_SHA; - } - /** - * Maximum number of lines to print when logging the git diff - */ - static get maxDiffLines() { - return 60; - } - /** - * Log up to maxDiffLines of the git diff. - */ - static logDiff() { - return __awaiter(this, void 0, void 0, function* () { - const diffCommand = `git --no-pager diff | head -n ${this.maxDiffLines.toString()}`; - yield system_1.default.run('sh', undefined, { - input: Buffer.from(diffCommand), - silent: true, - }); - }); - } - /** - * Regex to parse version description into separate fields - */ - static get descriptionRegex1() { - return /^v?([\d.]+)-(\d+)-g(\w+)-?(\w+)*/g; - } - static get descriptionRegex2() { - return /^v?([\d.]+-\w+)-(\d+)-g(\w+)-?(\w+)*/g; - } - static get descriptionRegex3() { - return /^v?([\d.]+-\w+\.\d+)-(\d+)-g(\w+)-?(\w+)*/g; - } - static determineVersion(strategy, inputVersion) { - return __awaiter(this, void 0, void 0, function* () { - // Validate input - if (!Object.hasOwnProperty.call(this.strategies, strategy)) { - throw new validation_error_1.default(`Versioning strategy should be one of ${Object.values(this.strategies).join(', ')}.`); - } - let version; - switch (strategy) { - case this.strategies.None: - version = 'none'; - break; - case this.strategies.Custom: - version = inputVersion; - break; - case this.strategies.Semantic: - version = yield this.generateSemanticVersion(); - break; - case this.strategies.Tag: - version = yield this.generateTagVersion(); - break; - default: - throw new not_implemented_exception_1.default(`Strategy ${strategy} is not implemented.`); - } - return version; - }); - } - /** - * Automatically generates a version based on SemVer out of the box. - * - * The version works as follows: `..` for example `0.1.2`. - * - * The latest tag dictates `.` - * The number of commits since that tag dictates``. - * - * @See: https://semver.org/ - */ - static generateSemanticVersion() { - return __awaiter(this, void 0, void 0, function* () { - if (yield this.isShallow()) { - yield this.fetch(); - } - yield this.logDiff(); - if ((yield this.isDirty()) && !this.isDirtyAllowed) { - throw new Error('Branch is dirty. Refusing to base semantic version on uncommitted changes'); - } - if (!(yield this.hasAnyVersionTags())) { - const version = `0.0.${yield this.getTotalNumberOfCommits()}`; - core.info(`Generated version ${version} (no version tags found).`); - return version; - } - const versionDescriptor = yield this.parseSemanticVersion(); - if (versionDescriptor) { - const { tag, commits, hash } = versionDescriptor; - // Ensure 3 digits (commits should always be patch level) - const [major, minor, patch] = `${tag}.${commits}`.split('.'); - const threeDigitVersion = /^\d+$/.test(patch) ? `${major}.${minor}.${patch}` : `${major}.0.${minor}`; - core.info(`Found semantic version ${threeDigitVersion} for ${this.branch}@${hash}`); - return `${threeDigitVersion}`; - } - const version = `0.0.${yield this.getTotalNumberOfCommits()}`; - core.info(`Generated version ${version} (semantic version couldn't be determined).`); - return version; - }); - } - /** - * Generate the proper version for unity based on an existing tag. - */ - static generateTagVersion() { - return __awaiter(this, void 0, void 0, function* () { - let tag = yield this.getTag(); - if (tag.charAt(0) === 'v') { - tag = tag.slice(1); - } - return tag; - }); - } - /** - * Parses the versionDescription into their named parts. - */ - static parseSemanticVersion() { - return __awaiter(this, void 0, void 0, function* () { - const description = yield this.getVersionDescription(); - try { - const [match, tag, commits, hash] = this.descriptionRegex1.exec(description); - return { - match, - tag, - commits, - hash, - }; - } - catch (_a) { - try { - const [match, tag, commits, hash] = this.descriptionRegex2.exec(description); - return { - match, - tag, - commits, - hash, - }; - } - catch (_b) { - try { - const [match, tag, commits, hash] = this.descriptionRegex3.exec(description); - return { - match, - tag, - commits, - hash, - }; - } - catch (_c) { - core.warning(`Failed to parse git describe output or version can not be determined through: "${description}".`); - return false; - } - } - } - }); - } - /** - * Returns whether the repository is shallow. - */ - static isShallow() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.git(['rev-parse', '--is-shallow-repository']); - return output !== 'false\n'; - }); - } - /** - * Retrieves refs from the configured remote. - * - * Fetch unshallow for incomplete repository, but fall back to normal fetch. - * - * Note: `--all` should not be used, and would break fetching for push event. - */ - static fetch() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield this.git(['fetch', '--unshallow']); - } - catch (error) { - core.warning(`Fetch --unshallow caught: ${error}`); - yield this.git(['fetch']); - } - }); - } - /** - * Retrieves information about the branch. - * - * Format: `v0.12-24-gd2198ab` - * - * In this format v0.12 is the latest tag, 24 are the number of commits since, and gd2198ab - * identifies the current commit. - */ - static getVersionDescription() { - return __awaiter(this, void 0, void 0, function* () { - return this.git(['describe', '--long', '--tags', '--always', this.sha]); - }); - } - /** - * Returns whether there are uncommitted changes that are not ignored. - */ - static isDirty() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.git(['status', '--porcelain']); - const isDirty = output !== ''; - if (isDirty) { - core.warning('Changes were made to the following files and folders:\n'); - core.warning(output); - } - return isDirty; - }); - } - /** - * Get the tag if there is one pointing at HEAD - */ - static getTag() { - return __awaiter(this, void 0, void 0, function* () { - return (yield this.git(['tag', '--points-at', 'HEAD'])).trim(); - }); - } - /** - * Whether or not the repository has any version tags yet. - */ - static hasAnyVersionTags() { - return __awaiter(this, void 0, void 0, function* () { - const numberOfCommitsAsString = yield system_1.default.run('sh', undefined, { - input: Buffer.from('git tag --list --merged HEAD | grep v[0-9]* | wc -l'), - cwd: this.projectPath, - silent: false, - }); - const numberOfCommits = Number.parseInt(numberOfCommitsAsString, 10); - return numberOfCommits !== 0; - }); - } - /** - * Get the total number of commits on head. - * - * Note: HEAD should not be used, as it may be detached, resulting in an additional count. - */ - static getTotalNumberOfCommits() { - return __awaiter(this, void 0, void 0, function* () { - const numberOfCommitsAsString = yield this.git(['rev-list', '--count', this.sha]); - return Number.parseInt(numberOfCommitsAsString, 10); - }); - } - /** - * Run git in the specified project path - */ - static git(arguments_, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - return system_1.default.run('git', arguments_, Object.assign({ cwd: this.projectPath }, options)); - }); - } -} -exports["default"] = Versioning; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +const not_implemented_exception_1 = __importDefault(__nccwpck_require__(26574)); +const validation_error_1 = __importDefault(__nccwpck_require__(97266)); +const input_1 = __importDefault(__nccwpck_require__(91933)); +const system_1 = __importDefault(__nccwpck_require__(62177)); +class Versioning { + static get projectPath() { + return input_1.default.projectPath; + } + static get isDirtyAllowed() { + return input_1.default.allowDirtyBuild; + } + static get strategies() { + return { None: 'None', Semantic: 'Semantic', Tag: 'Tag', Custom: 'Custom' }; + } + /** + * Get the branch name of the (related) branch + */ + static get branch() { + // Todo - use optional chaining (https://github.com/zeit/ncc/issues/534) + return this.headRef || (this.ref && this.ref.slice(11)); + } + /** + * For pull requests we can reliably use GITHUB_HEAD_REF + */ + static get headRef() { + return process.env.GITHUB_HEAD_REF; + } + /** + * For branches GITHUB_REF will have format `refs/heads/feature-branch-1` + */ + static get ref() { + return process.env.GITHUB_REF; + } + /** + * The commit SHA that triggered the workflow run. + */ + static get sha() { + return process.env.GITHUB_SHA; + } + /** + * Maximum number of lines to print when logging the git diff + */ + static get maxDiffLines() { + return 60; + } + /** + * Log up to maxDiffLines of the git diff. + */ + static logDiff() { + return __awaiter(this, void 0, void 0, function* () { + const diffCommand = `git --no-pager diff | head -n ${this.maxDiffLines.toString()}`; + yield system_1.default.run('sh', undefined, { + input: Buffer.from(diffCommand), + silent: true, + }); + }); + } + /** + * Regex to parse version description into separate fields + */ + static get descriptionRegex1() { + return /^v?([\d.]+)-(\d+)-g(\w+)-?(\w+)*/g; + } + static get descriptionRegex2() { + return /^v?([\d.]+-\w+)-(\d+)-g(\w+)-?(\w+)*/g; + } + static get descriptionRegex3() { + return /^v?([\d.]+-\w+\.\d+)-(\d+)-g(\w+)-?(\w+)*/g; + } + static determineVersion(strategy, inputVersion) { + return __awaiter(this, void 0, void 0, function* () { + // Validate input + if (!Object.hasOwnProperty.call(this.strategies, strategy)) { + throw new validation_error_1.default(`Versioning strategy should be one of ${Object.values(this.strategies).join(', ')}.`); + } + let version; + switch (strategy) { + case this.strategies.None: + version = 'none'; + break; + case this.strategies.Custom: + version = inputVersion; + break; + case this.strategies.Semantic: + version = yield this.generateSemanticVersion(); + break; + case this.strategies.Tag: + version = yield this.generateTagVersion(); + break; + default: + throw new not_implemented_exception_1.default(`Strategy ${strategy} is not implemented.`); + } + return version; + }); + } + /** + * Automatically generates a version based on SemVer out of the box. + * + * The version works as follows: `..` for example `0.1.2`. + * + * The latest tag dictates `.` + * The number of commits since that tag dictates``. + * + * @See: https://semver.org/ + */ + static generateSemanticVersion() { + return __awaiter(this, void 0, void 0, function* () { + if (yield this.isShallow()) { + yield this.fetch(); + } + yield this.logDiff(); + if ((yield this.isDirty()) && !this.isDirtyAllowed) { + throw new Error('Branch is dirty. Refusing to base semantic version on uncommitted changes'); + } + if (!(yield this.hasAnyVersionTags())) { + const version = `0.0.${yield this.getTotalNumberOfCommits()}`; + core.info(`Generated version ${version} (no version tags found).`); + return version; + } + const versionDescriptor = yield this.parseSemanticVersion(); + if (versionDescriptor) { + const { tag, commits, hash } = versionDescriptor; + // Ensure 3 digits (commits should always be patch level) + const [major, minor, patch] = `${tag}.${commits}`.split('.'); + const threeDigitVersion = /^\d+$/.test(patch) ? `${major}.${minor}.${patch}` : `${major}.0.${minor}`; + core.info(`Found semantic version ${threeDigitVersion} for ${this.branch}@${hash}`); + return `${threeDigitVersion}`; + } + const version = `0.0.${yield this.getTotalNumberOfCommits()}`; + core.info(`Generated version ${version} (semantic version couldn't be determined).`); + return version; + }); + } + /** + * Generate the proper version for unity based on an existing tag. + */ + static generateTagVersion() { + return __awaiter(this, void 0, void 0, function* () { + let tag = yield this.getTag(); + if (tag.charAt(0) === 'v') { + tag = tag.slice(1); + } + return tag; + }); + } + /** + * Parses the versionDescription into their named parts. + */ + static parseSemanticVersion() { + return __awaiter(this, void 0, void 0, function* () { + const description = yield this.getVersionDescription(); + try { + const [match, tag, commits, hash] = this.descriptionRegex1.exec(description); + return { + match, + tag, + commits, + hash, + }; + } + catch (_a) { + try { + const [match, tag, commits, hash] = this.descriptionRegex2.exec(description); + return { + match, + tag, + commits, + hash, + }; + } + catch (_b) { + try { + const [match, tag, commits, hash] = this.descriptionRegex3.exec(description); + return { + match, + tag, + commits, + hash, + }; + } + catch (_c) { + core.warning(`Failed to parse git describe output or version can not be determined through: "${description}".`); + return false; + } + } + } + }); + } + /** + * Returns whether the repository is shallow. + */ + static isShallow() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.git(['rev-parse', '--is-shallow-repository']); + return output !== 'false\n'; + }); + } + /** + * Retrieves refs from the configured remote. + * + * Fetch unshallow for incomplete repository, but fall back to normal fetch. + * + * Note: `--all` should not be used, and would break fetching for push event. + */ + static fetch() { + return __awaiter(this, void 0, void 0, function* () { + try { + yield this.git(['fetch', '--unshallow']); + } + catch (error) { + core.warning(`Fetch --unshallow caught: ${error}`); + yield this.git(['fetch']); + } + }); + } + /** + * Retrieves information about the branch. + * + * Format: `v0.12-24-gd2198ab` + * + * In this format v0.12 is the latest tag, 24 are the number of commits since, and gd2198ab + * identifies the current commit. + */ + static getVersionDescription() { + return __awaiter(this, void 0, void 0, function* () { + return this.git(['describe', '--long', '--tags', '--always', this.sha]); + }); + } + /** + * Returns whether there are uncommitted changes that are not ignored. + */ + static isDirty() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.git(['status', '--porcelain']); + const isDirty = output !== ''; + if (isDirty) { + core.warning('Changes were made to the following files and folders:\n'); + core.warning(output); + } + return isDirty; + }); + } + /** + * Get the tag if there is one pointing at HEAD + */ + static getTag() { + return __awaiter(this, void 0, void 0, function* () { + return (yield this.git(['tag', '--points-at', 'HEAD'])).trim(); + }); + } + /** + * Whether or not the repository has any version tags yet. + */ + static hasAnyVersionTags() { + return __awaiter(this, void 0, void 0, function* () { + const numberOfCommitsAsString = yield system_1.default.run('sh', undefined, { + input: Buffer.from('git tag --list --merged HEAD | grep v[0-9]* | wc -l'), + cwd: this.projectPath, + silent: false, + }); + const numberOfCommits = Number.parseInt(numberOfCommitsAsString, 10); + return numberOfCommits !== 0; + }); + } + /** + * Get the total number of commits on head. + * + * Note: HEAD should not be used, as it may be detached, resulting in an additional count. + */ + static getTotalNumberOfCommits() { + return __awaiter(this, void 0, void 0, function* () { + const numberOfCommitsAsString = yield this.git(['rev-list', '--count', this.sha]); + return Number.parseInt(numberOfCommitsAsString, 10); + }); + } + /** + * Run git in the specified project path + */ + static git(arguments_, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + return system_1.default.run('git', arguments_, Object.assign({ cwd: this.projectPath }, options)); + }); + } +} +exports["default"] = Versioning; /***/ }), @@ -171495,4883 +171495,4883 @@ exports.forgivingBase64Decode = data => { /***/ 49458: /***/ (function(module) { -;(function (globalScope) { - 'use strict'; - - - /* - * decimal.js v10.2.1 - * An arbitrary-precision Decimal type for JavaScript. - * https://github.com/MikeMcl/decimal.js - * Copyright (c) 2020 Michael Mclaughlin - * MIT Licence - */ - - - // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // - - - // The maximum exponent magnitude. - // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. - var EXP_LIMIT = 9e15, // 0 to 9e15 - - // The limit on the value of `precision`, and on the value of the first argument to - // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. - MAX_DIGITS = 1e9, // 0 to 1e9 - - // Base conversion alphabet. - NUMERALS = '0123456789abcdef', - - // The natural logarithm of 10 (1025 digits). - LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', - - // Pi (1025 digits). - PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', - - - // The initial configuration properties of the Decimal constructor. - DEFAULTS = { - - // These values must be integers within the stated ranges (inclusive). - // Most of these values can be changed at run-time using the `Decimal.config` method. - - // The maximum number of significant digits of the result of a calculation or base conversion. - // E.g. `Decimal.config({ precision: 20 });` - precision: 20, // 1 to MAX_DIGITS - - // The rounding mode used when rounding to `precision`. - // - // ROUND_UP 0 Away from zero. - // ROUND_DOWN 1 Towards zero. - // ROUND_CEIL 2 Towards +Infinity. - // ROUND_FLOOR 3 Towards -Infinity. - // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - // - // E.g. - // `Decimal.rounding = 4;` - // `Decimal.rounding = Decimal.ROUND_HALF_UP;` - rounding: 4, // 0 to 8 - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 The IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. - // - // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian - // division (9) are commonly used for the modulus operation. The other rounding modes can also - // be used, but they may not give useful results. - modulo: 1, // 0 to 9 - - // The exponent value at and beneath which `toString` returns exponential notation. - // JavaScript numbers: -7 - toExpNeg: -7, // 0 to -EXP_LIMIT - - // The exponent value at and above which `toString` returns exponential notation. - // JavaScript numbers: 21 - toExpPos: 21, // 0 to EXP_LIMIT - - // The minimum exponent value, beneath which underflow to zero occurs. - // JavaScript numbers: -324 (5e-324) - minE: -EXP_LIMIT, // -1 to -EXP_LIMIT - - // The maximum exponent value, above which overflow to Infinity occurs. - // JavaScript numbers: 308 (1.7976931348623157e+308) - maxE: EXP_LIMIT, // 1 to EXP_LIMIT - - // Whether to use cryptographically-secure random number generation, if available. - crypto: false // true/false - }, - - - // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // - - - Decimal, inexact, noConflict, quadrant, - external = true, - - decimalError = '[DecimalError] ', - invalidArgument = decimalError + 'Invalid argument: ', - precisionLimitExceeded = decimalError + 'Precision limit exceeded', - cryptoUnavailable = decimalError + 'crypto unavailable', - - mathfloor = Math.floor, - mathpow = Math.pow, - - isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, - isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, - isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, - isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, - - BASE = 1e7, - LOG_BASE = 7, - MAX_SAFE_INTEGER = 9007199254740991, - - LN10_PRECISION = LN10.length - 1, - PI_PRECISION = PI.length - 1, - - // Decimal.prototype object - P = { name: '[object Decimal]' }; - - - // Decimal prototype methods - - - /* - * absoluteValue abs - * ceil - * comparedTo cmp - * cosine cos - * cubeRoot cbrt - * decimalPlaces dp - * dividedBy div - * dividedToIntegerBy divToInt - * equals eq - * floor - * greaterThan gt - * greaterThanOrEqualTo gte - * hyperbolicCosine cosh - * hyperbolicSine sinh - * hyperbolicTangent tanh - * inverseCosine acos - * inverseHyperbolicCosine acosh - * inverseHyperbolicSine asinh - * inverseHyperbolicTangent atanh - * inverseSine asin - * inverseTangent atan - * isFinite - * isInteger isInt - * isNaN - * isNegative isNeg - * isPositive isPos - * isZero - * lessThan lt - * lessThanOrEqualTo lte - * logarithm log - * [maximum] [max] - * [minimum] [min] - * minus sub - * modulo mod - * naturalExponential exp - * naturalLogarithm ln - * negated neg - * plus add - * precision sd - * round - * sine sin - * squareRoot sqrt - * tangent tan - * times mul - * toBinary - * toDecimalPlaces toDP - * toExponential - * toFixed - * toFraction - * toHexadecimal toHex - * toNearest - * toNumber - * toOctal - * toPower pow - * toPrecision - * toSignificantDigits toSD - * toString - * truncated trunc - * valueOf toJSON - */ - - - /* - * Return a new Decimal whose value is the absolute value of this Decimal. - * - */ - P.absoluteValue = P.abs = function () { - var x = new this.constructor(this); - if (x.s < 0) x.s = 1; - return finalise(x); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of positive Infinity. - * - */ - P.ceil = function () { - return finalise(new this.constructor(this), this.e + 1, 2); - }; - - - /* - * Return - * 1 if the value of this Decimal is greater than the value of `y`, - * -1 if the value of this Decimal is less than the value of `y`, - * 0 if they have the same value, - * NaN if the value of either Decimal is NaN. - * - */ - P.comparedTo = P.cmp = function (y) { - var i, j, xdL, ydL, - x = this, - xd = x.d, - yd = (y = new x.constructor(y)).d, - xs = x.s, - ys = y.s; - - // Either NaN or ±Infinity? - if (!xd || !yd) { - return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; - } - - // Either zero? - if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; - - // Signs differ? - if (xs !== ys) return xs; - - // Compare exponents. - if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; - - xdL = xd.length; - ydL = yd.length; - - // Compare digit by digit. - for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { - if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; - } - - // Compare lengths. - return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; - }; - - - /* - * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * cos(0) = 1 - * cos(-0) = 1 - * cos(Infinity) = NaN - * cos(-Infinity) = NaN - * cos(NaN) = NaN - * - */ - P.cosine = P.cos = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.d) return new Ctor(NaN); - - // cos(0) = cos(-0) = 1 - if (!x.d[0]) return new Ctor(1); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); - }; - - - /* - * - * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * cbrt(0) = 0 - * cbrt(-0) = -0 - * cbrt(1) = 1 - * cbrt(-1) = -1 - * cbrt(N) = N - * cbrt(-I) = -I - * cbrt(I) = I - * - * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) - * - */ - P.cubeRoot = P.cbrt = function () { - var e, m, n, r, rep, s, sd, t, t3, t3plusx, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - external = false; - - // Initial estimate. - s = x.s * mathpow(x.s * x, 1 / 3); - - // Math.cbrt underflow/overflow? - // Pass x to Math.pow as integer, then adjust the exponent of the result. - if (!s || Math.abs(s) == 1 / 0) { - n = digitsToString(x.d); - e = x.e; - - // Adjust n exponent so it is a multiple of 3 away from x exponent. - if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); - s = mathpow(n, 1 / 3); - - // Rarely, e may be one less than the result exponent value. - e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - r.s = x.s; - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Halley's method. - // TODO? Compare Newton's method. - for (;;) { - t = r; - t3 = t.times(t).times(t); - t3plusx = t3.plus(x); - r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 - // , i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return the number of decimal places of the value of this Decimal. - * - */ - P.decimalPlaces = P.dp = function () { - var w, - d = this.d, - n = NaN; - - if (d) { - w = d.length - 1; - n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last word. - w = d[w]; - if (w) for (; w % 10 == 0; w /= 10) n--; - if (n < 0) n = 0; - } - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedBy = P.div = function (y) { - return divide(this, new this.constructor(y)); - }; - - - /* - * Return a new Decimal whose value is the integer part of dividing the value of this Decimal - * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedToIntegerBy = P.divToInt = function (y) { - var x = this, - Ctor = x.constructor; - return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); - }; - - - /* - * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. - * - */ - P.equals = P.eq = function (y) { - return this.cmp(y) === 0; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of negative Infinity. - * - */ - P.floor = function () { - return finalise(new this.constructor(this), this.e + 1, 3); - }; - - - /* - * Return true if the value of this Decimal is greater than the value of `y`, otherwise return - * false. - * - */ - P.greaterThan = P.gt = function (y) { - return this.cmp(y) > 0; - }; - - - /* - * Return true if the value of this Decimal is greater than or equal to the value of `y`, - * otherwise return false. - * - */ - P.greaterThanOrEqualTo = P.gte = function (y) { - var k = this.cmp(y); - return k == 1 || k === 0; - }; - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [1, Infinity] - * - * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... - * - * cosh(0) = 1 - * cosh(-0) = 1 - * cosh(Infinity) = Infinity - * cosh(-Infinity) = Infinity - * cosh(NaN) = NaN - * - * x time taken (ms) result - * 1000 9 9.8503555700852349694e+433 - * 10000 25 4.4034091128314607936e+4342 - * 100000 171 1.4033316802130615897e+43429 - * 1000000 3817 1.5166076984010437725e+434294 - * 10000000 abandoned after 2 minute wait - * - * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) - * - */ - P.hyperbolicCosine = P.cosh = function () { - var k, n, pr, rm, len, - x = this, - Ctor = x.constructor, - one = new Ctor(1); - - if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); - if (x.isZero()) return one; - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 - // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) - - // Estimate the optimum number of times to use the argument reduction. - // TODO? Estimation reused from cosine() and may not be optimal here. - if (len < 32) { - k = Math.ceil(len / 3); - n = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - n = '2.3283064365386962890625e-10'; - } - - x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); - - // Reverse argument reduction - var cosh2_x, - i = k, - d8 = new Ctor(8); - for (; i--;) { - cosh2_x = x.times(x); - x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); - } - - return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... - * - * sinh(0) = 0 - * sinh(-0) = -0 - * sinh(Infinity) = Infinity - * sinh(-Infinity) = -Infinity - * sinh(NaN) = NaN - * - * x time taken (ms) - * 10 2 ms - * 100 5 ms - * 1000 14 ms - * 10000 82 ms - * 100000 886 ms 1.4033316802130615897e+43429 - * 200000 2613 ms - * 300000 5407 ms - * 400000 8824 ms - * 500000 13026 ms 8.7080643612718084129e+217146 - * 1000000 48543 ms - * - * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) - * - */ - P.hyperbolicSine = P.sinh = function () { - var k, pr, rm, len, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - if (len < 3) { - x = taylorSeries(Ctor, 2, x, x, true); - } else { - - // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) - // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) - // 3 multiplications and 1 addition - - // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) - // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) - // 4 multiplications and 2 additions - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x, true); - - // Reverse argument reduction - var sinh2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sinh2_x = x.times(x); - x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); - } - } - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * tanh(x) = sinh(x) / cosh(x) - * - * tanh(0) = 0 - * tanh(-0) = -0 - * tanh(Infinity) = 1 - * tanh(-Infinity) = -1 - * tanh(NaN) = NaN - * - */ - P.hyperbolicTangent = P.tanh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(x.s); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 7; - Ctor.rounding = 1; - - return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); - }; - - - /* - * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of - * this Decimal. - * - * Domain: [-1, 1] - * Range: [0, pi] - * - * acos(x) = pi/2 - asin(x) - * - * acos(0) = pi/2 - * acos(-0) = pi/2 - * acos(1) = 0 - * acos(-1) = pi - * acos(1/2) = pi/3 - * acos(-1/2) = 2*pi/3 - * acos(|x| > 1) = NaN - * acos(NaN) = NaN - * - */ - P.inverseCosine = P.acos = function () { - var halfPi, - x = this, - Ctor = x.constructor, - k = x.abs().cmp(1), - pr = Ctor.precision, - rm = Ctor.rounding; - - if (k !== -1) { - return k === 0 - // |x| is 1 - ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) - // |x| > 1 or x is NaN - : new Ctor(NaN); - } - - if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); - - // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.asin(); - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return halfPi.minus(x); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the - * value of this Decimal. - * - * Domain: [1, Infinity] - * Range: [0, Infinity] - * - * acosh(x) = ln(x + sqrt(x^2 - 1)) - * - * acosh(x < 1) = NaN - * acosh(NaN) = NaN - * acosh(Infinity) = Infinity - * acosh(-Infinity) = NaN - * acosh(0) = NaN - * acosh(-0) = NaN - * acosh(1) = 0 - * acosh(-1) = NaN - * - */ - P.inverseHyperbolicCosine = P.acosh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); - if (!x.isFinite()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; - Ctor.rounding = 1; - external = false; - - x = x.times(x).minus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * asinh(x) = ln(x + sqrt(x^2 + 1)) - * - * asinh(NaN) = NaN - * asinh(Infinity) = Infinity - * asinh(-Infinity) = -Infinity - * asinh(0) = 0 - * asinh(-0) = -0 - * - */ - P.inverseHyperbolicSine = P.asinh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; - Ctor.rounding = 1; - external = false; - - x = x.times(x).plus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the - * value of this Decimal. - * - * Domain: [-1, 1] - * Range: [-Infinity, Infinity] - * - * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) - * - * atanh(|x| > 1) = NaN - * atanh(NaN) = NaN - * atanh(Infinity) = NaN - * atanh(-Infinity) = NaN - * atanh(0) = 0 - * atanh(-0) = -0 - * atanh(1) = Infinity - * atanh(-1) = -Infinity - * - */ - P.inverseHyperbolicTangent = P.atanh = function () { - var pr, rm, wpr, xsd, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); - - pr = Ctor.precision; - rm = Ctor.rounding; - xsd = x.sd(); - - if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); - - Ctor.precision = wpr = xsd - x.e; - - x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); - - Ctor.precision = pr + 4; - Ctor.rounding = 1; - - x = x.ln(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(0.5); - }; - - - /* - * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) - * - * asin(0) = 0 - * asin(-0) = -0 - * asin(1/2) = pi/6 - * asin(-1/2) = -pi/6 - * asin(1) = pi/2 - * asin(-1) = -pi/2 - * asin(|x| > 1) = NaN - * asin(NaN) = NaN - * - * TODO? Compare performance of Taylor series. - * - */ - P.inverseSine = P.asin = function () { - var halfPi, k, - pr, rm, - x = this, - Ctor = x.constructor; - - if (x.isZero()) return new Ctor(x); - - k = x.abs().cmp(1); - pr = Ctor.precision; - rm = Ctor.rounding; - - if (k !== -1) { - - // |x| is 1 - if (k === 0) { - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - halfPi.s = x.s; - return halfPi; - } - - // |x| > 1 or x is NaN - return new Ctor(NaN); - } - - // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(2); - }; - - - /* - * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - * - * atan(0) = 0 - * atan(-0) = -0 - * atan(1) = pi/4 - * atan(-1) = -pi/4 - * atan(Infinity) = pi/2 - * atan(-Infinity) = -pi/2 - * atan(NaN) = NaN - * - */ - P.inverseTangent = P.atan = function () { - var i, j, k, n, px, t, r, wpr, x2, - x = this, - Ctor = x.constructor, - pr = Ctor.precision, - rm = Ctor.rounding; - - if (!x.isFinite()) { - if (!x.s) return new Ctor(NaN); - if (pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.5); - r.s = x.s; - return r; - } - } else if (x.isZero()) { - return new Ctor(x); - } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.25); - r.s = x.s; - return r; - } - - Ctor.precision = wpr = pr + 10; - Ctor.rounding = 1; - - // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); - - // Argument reduction - // Ensure |x| < 0.42 - // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) - - k = Math.min(28, wpr / LOG_BASE + 2 | 0); - - for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); - - external = false; - - j = Math.ceil(wpr / LOG_BASE); - n = 1; - x2 = x.times(x); - r = new Ctor(x); - px = x; - - // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - for (; i !== -1;) { - px = px.times(x2); - t = r.minus(px.div(n += 2)); - - px = px.times(x2); - r = t.plus(px.div(n += 2)); - - if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); - } - - if (k) r = r.times(2 << (k - 1)); - - external = true; - - return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return true if the value of this Decimal is a finite number, otherwise return false. - * - */ - P.isFinite = function () { - return !!this.d; - }; - - - /* - * Return true if the value of this Decimal is an integer, otherwise return false. - * - */ - P.isInteger = P.isInt = function () { - return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; - }; - - - /* - * Return true if the value of this Decimal is NaN, otherwise return false. - * - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this Decimal is negative, otherwise return false. - * - */ - P.isNegative = P.isNeg = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this Decimal is positive, otherwise return false. - * - */ - P.isPositive = P.isPos = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this Decimal is 0 or -0, otherwise return false. - * - */ - P.isZero = function () { - return !!this.d && this.d[0] === 0; - }; - - - /* - * Return true if the value of this Decimal is less than `y`, otherwise return false. - * - */ - P.lessThan = P.lt = function (y) { - return this.cmp(y) < 0; - }; - - - /* - * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. - * - */ - P.lessThanOrEqualTo = P.lte = function (y) { - return this.cmp(y) < 1; - }; - - - /* - * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * If no base is specified, return log[10](arg). - * - * log[base](arg) = ln(arg) / ln(base) - * - * The result will always be correctly rounded if the base of the log is 10, and 'almost always' - * otherwise: - * - * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen - * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error - * between the result and the correctly rounded result will be one ulp (unit in the last place). - * - * log[-b](a) = NaN - * log[0](a) = NaN - * log[1](a) = NaN - * log[NaN](a) = NaN - * log[Infinity](a) = NaN - * log[b](0) = -Infinity - * log[b](-0) = -Infinity - * log[b](-a) = NaN - * log[b](1) = 0 - * log[b](Infinity) = Infinity - * log[b](NaN) = NaN - * - * [base] {number|string|Decimal} The base of the logarithm. - * - */ - P.logarithm = P.log = function (base) { - var isBase10, d, denominator, k, inf, num, sd, r, - arg = this, - Ctor = arg.constructor, - pr = Ctor.precision, - rm = Ctor.rounding, - guard = 5; - - // Default base is 10. - if (base == null) { - base = new Ctor(10); - isBase10 = true; - } else { - base = new Ctor(base); - d = base.d; - - // Return NaN if base is negative, or non-finite, or is 0 or 1. - if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); - - isBase10 = base.eq(10); - } - - d = arg.d; - - // Is arg negative, non-finite, 0 or 1? - if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { - return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); - } - - // The result will have a non-terminating decimal expansion if base is 10 and arg is not an - // integer power of 10. - if (isBase10) { - if (d.length > 1) { - inf = true; - } else { - for (k = d[0]; k % 10 === 0;) k /= 10; - inf = k !== 1; - } - } - - external = false; - sd = pr + guard; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - - // The result will have 5 rounding digits. - r = divide(num, denominator, sd, 1); - - // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, - // calculate 10 further digits. - // - // If the result is known to have an infinite decimal expansion, repeat this until it is clear - // that the result is above or below the boundary. Otherwise, if after calculating the 10 - // further digits, the last 14 are nines, round up and assume the result is exact. - // Also assume the result is exact if the last 14 are zero. - // - // Example of a result that will be incorrectly rounded: - // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... - // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it - // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so - // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal - // place is still 2.6. - if (checkRoundingDigits(r.d, k = pr, rm)) { - - do { - sd += 10; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - r = divide(num, denominator, sd, 1); - - if (!inf) { - - // Check for 14 nines from the 2nd rounding digit, as the first may be 4. - if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - - break; - } - } while (checkRoundingDigits(r.d, k += 10, rm)); - } - - external = true; - - return finalise(r, pr, rm); - }; - - - /* - * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.max = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'lt'); - }; - */ - - - /* - * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.min = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'gt'); - }; - */ - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.minus = P.sub = function (y) { - var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return y negated if x is finite and y is ±Infinity. - else if (x.d) y.s = -y.s; - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with different signs. - // Return NaN if both are ±Infinity with the same sign. - else y = new Ctor(y.d || x.s !== y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.plus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return y negated if x is zero and y is non-zero. - if (yd[0]) y.s = -y.s; - - // Return x if y is zero and x is non-zero. - else if (xd[0]) y = new Ctor(x); - - // Return zero if both are zero. - // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. - else return new Ctor(rm === 3 ? -0 : 0); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - e = mathfloor(y.e / LOG_BASE); - xe = mathfloor(x.e / LOG_BASE); - - xd = xd.slice(); - k = xe - e; - - // If base 1e7 exponents differ... - if (k) { - xLTy = k < 0; - - if (xLTy) { - d = xd; - k = -k; - len = yd.length; - } else { - d = yd; - e = xe; - len = xd.length; - } - - // Numbers with massively different exponents would result in a very high number of - // zeros needing to be prepended, but this can be avoided while still ensuring correct - // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. - i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; - - if (k > i) { - k = i; - d.length = 1; - } - - // Prepend zeros to equalise exponents. - d.reverse(); - for (i = k; i--;) d.push(0); - d.reverse(); - - // Base 1e7 exponents equal. - } else { - - // Check digits to determine which is the bigger number. - - i = xd.length; - len = yd.length; - xLTy = i < len; - if (xLTy) len = i; - - for (i = 0; i < len; i++) { - if (xd[i] != yd[i]) { - xLTy = xd[i] < yd[i]; - break; - } - } - - k = 0; - } - - if (xLTy) { - d = xd; - xd = yd; - yd = d; - y.s = -y.s; - } - - len = xd.length; - - // Append zeros to `xd` if shorter. - // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. - for (i = yd.length - len; i > 0; --i) xd[len++] = 0; - - // Subtract yd from xd. - for (i = yd.length; i > k;) { - - if (xd[--i] < yd[i]) { - for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; - --xd[j]; - xd[i] += BASE; - } - - xd[i] -= yd[i]; - } - - // Remove trailing zeros. - for (; xd[--len] === 0;) xd.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xd[0] === 0; xd.shift()) --e; - - // Zero? - if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * The result depends on the modulo mode. - * - */ - P.modulo = P.mod = function (y) { - var q, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. - if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); - - // Return x if y is ±Infinity or x is ±0. - if (!y.d || x.d && !x.d[0]) { - return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); - } - - // Prevent rounding of intermediate calculations. - external = false; - - if (Ctor.modulo == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // result = x - q * y where 0 <= result < abs(y) - q = divide(x, y.abs(), 0, 3, 1); - q.s *= y.s; - } else { - q = divide(x, y, 0, Ctor.modulo, 1); - } - - q = q.times(y); - - external = true; - - return x.minus(q); - }; - - - /* - * Return a new Decimal whose value is the natural exponential of the value of this Decimal, - * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.naturalExponential = P.exp = function () { - return naturalExponential(this); - }; - - - /* - * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.naturalLogarithm = P.ln = function () { - return naturalLogarithm(this); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by - * -1. - * - */ - P.negated = P.neg = function () { - var x = new this.constructor(this); - x.s = -x.s; - return finalise(x); - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.plus = P.add = function (y) { - var carry, d, e, i, k, len, pr, rm, xd, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with the same sign. - // Return NaN if both are ±Infinity with different signs. - // Return y if x is finite and y is ±Infinity. - else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.minus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return x if y is zero. - // Return y if y is non-zero. - if (!yd[0]) y = new Ctor(x); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - k = mathfloor(x.e / LOG_BASE); - e = mathfloor(y.e / LOG_BASE); - - xd = xd.slice(); - i = k - e; - - // If base 1e7 exponents differ... - if (i) { - - if (i < 0) { - d = xd; - i = -i; - len = yd.length; - } else { - d = yd; - e = k; - len = xd.length; - } - - // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. - k = Math.ceil(pr / LOG_BASE); - len = k > len ? k + 1 : len + 1; - - if (i > len) { - i = len; - d.length = 1; - } - - // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. - d.reverse(); - for (; i--;) d.push(0); - d.reverse(); - } - - len = xd.length; - i = yd.length; - - // If yd is longer than xd, swap xd and yd so xd points to the longer array. - if (len - i < 0) { - i = len; - d = yd; - yd = xd; - xd = d; - } - - // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. - for (carry = 0; i;) { - carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; - xd[i] %= BASE; - } - - if (carry) { - xd.unshift(carry); - ++e; - } - - // Remove trailing zeros. - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - for (len = xd.length; xd[--len] == 0;) xd.pop(); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * Return the number of significant digits of the value of this Decimal. - * - * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. - * - */ - P.precision = P.sd = function (z) { - var k, - x = this; - - if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); - - if (x.d) { - k = getPrecision(x.d); - if (z && x.e + 1 > k) k = x.e + 1; - } else { - k = NaN; - } - - return k; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using - * rounding mode `rounding`. - * - */ - P.round = function () { - var x = this, - Ctor = x.constructor; - - return finalise(new Ctor(x), x.e + 1, Ctor.rounding); - }; - - - /* - * Return a new Decimal whose value is the sine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * sin(x) = x - x^3/3! + x^5/5! - ... - * - * sin(0) = 0 - * sin(-0) = -0 - * sin(Infinity) = NaN - * sin(-Infinity) = NaN - * sin(NaN) = NaN - * - */ - P.sine = P.sin = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = sine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - */ - P.squareRoot = P.sqrt = function () { - var m, n, sd, r, rep, t, - x = this, - d = x.d, - e = x.e, - s = x.s, - Ctor = x.constructor; - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !d || !d[0]) { - return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); - } - - external = false; - - // Initial estimate. - s = Math.sqrt(+x); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = digitsToString(d); - - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(n); - e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Newton-Raphson iteration. - for (;;) { - t = r; - r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or - // 4999, i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * tan(0) = 0 - * tan(-0) = -0 - * tan(Infinity) = NaN - * tan(-Infinity) = NaN - * tan(NaN) = NaN - * - */ - P.tangent = P.tan = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 10; - Ctor.rounding = 1; - - x = x.sin(); - x.s = 1; - x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - */ - P.times = P.mul = function (y) { - var carry, e, i, k, r, rL, t, xdL, ydL, - x = this, - Ctor = x.constructor, - xd = x.d, - yd = (y = new Ctor(y)).d; - - y.s *= x.s; - - // If either is NaN, ±Infinity or ±0... - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd - - // Return NaN if either is NaN. - // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. - ? NaN - - // Return ±Infinity if either is ±Infinity. - // Return ±0 if either is ±0. - : !xd || !yd ? y.s / 0 : y.s * 0); - } - - e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); - xdL = xd.length; - ydL = yd.length; - - // Ensure xd points to the longer array. - if (xdL < ydL) { - r = xd; - xd = yd; - yd = r; - rL = xdL; - xdL = ydL; - ydL = rL; - } - - // Initialise the result array with zeros. - r = []; - rL = xdL + ydL; - for (i = rL; i--;) r.push(0); - - // Multiply! - for (i = ydL; --i >= 0;) { - carry = 0; - for (k = xdL + i; k > i;) { - t = r[k] + yd[i] * xd[k - i - 1] + carry; - r[k--] = t % BASE | 0; - carry = t / BASE | 0; - } - - r[k] = (r[k] + carry) % BASE | 0; - } - - // Remove trailing zeros. - for (; !r[--rL];) r.pop(); - - if (carry) ++e; - else r.shift(); - - y.d = r; - y.e = getBase10Exponent(r, e); - - return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; - }; - - - /* - * Return a string representing the value of this Decimal in base 2, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toBinary = function (sd, rm) { - return toStringBinary(this, 2, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` - * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. - * - * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toDecimalPlaces = P.toDP = function (dp, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - if (dp === void 0) return x; - - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - return finalise(x, dp + x.e + 1, rm); - }; - - - /* - * Return a string representing the value of this Decimal in exponential notation rounded to - * `dp` fixed decimal places using rounding mode `rounding`. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toExponential = function (dp, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x, true); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), dp + 1, rm); - str = finiteToString(x, true, dp + 1); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a string representing the value of this Decimal in normal (fixed-point) notation to - * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is - * omitted. - * - * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - * (-0).toFixed(3) is '0.000'. - * (-0.5).toFixed(0) is '-0'. - * - */ - P.toFixed = function (dp, rm) { - var str, y, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - y = finalise(new Ctor(x), dp + x.e + 1, rm); - str = finiteToString(y, false, dp + y.e + 1); - } - - // To determine whether to add the minus sign look at the value before it was rounded, - // i.e. look at `x` rather than `y`. - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return an array representing the value of this Decimal as a simple fraction with an integer - * numerator and an integer denominator. - * - * The denominator will be a positive non-zero value less than or equal to the specified maximum - * denominator. If a maximum denominator is not specified, the denominator will be the lowest - * value necessary to represent the number exactly. - * - * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. - * - */ - P.toFraction = function (maxD) { - var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, - x = this, - xd = x.d, - Ctor = x.constructor; - - if (!xd) return new Ctor(x); - - n1 = d0 = new Ctor(1); - d1 = n0 = new Ctor(0); - - d = new Ctor(d1); - e = d.e = getPrecision(xd) - x.e - 1; - k = e % LOG_BASE; - d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); - - if (maxD == null) { - - // d is 10**e, the minimum max-denominator needed. - maxD = e > 0 ? d : n1; - } else { - n = new Ctor(maxD); - if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); - maxD = n.gt(d) ? (e > 0 ? d : n1) : n; - } - - external = false; - n = new Ctor(digitsToString(xd)); - pr = Ctor.precision; - Ctor.precision = e = xd.length * LOG_BASE * 2; - - for (;;) { - q = divide(n, d, 0, 1, 1); - d2 = d0.plus(q.times(d1)); - if (d2.cmp(maxD) == 1) break; - d0 = d1; - d1 = d2; - d2 = n1; - n1 = n0.plus(q.times(d2)); - n0 = d2; - d2 = d; - d = n.minus(q.times(d2)); - n = d2; - } - - d2 = divide(maxD.minus(d0), d1, 0, 1, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - - // Determine which fraction is closer to x, n0/d0 or n1/d1? - r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 - ? [n1, d1] : [n0, d0]; - - Ctor.precision = pr; - external = true; - - return r; - }; - - - /* - * Return a string representing the value of this Decimal in base 16, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toHexadecimal = P.toHex = function (sd, rm) { - return toStringBinary(this, 16, sd, rm); - }; - - - /* - * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding - * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. - * - * The return value will always have the same sign as this Decimal, unless either this Decimal - * or `y` is NaN, in which case the return value will be also be NaN. - * - * The return value is not affected by the value of `precision`. - * - * y {number|string|Decimal} The magnitude to round to a multiple of. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toNearest() rounding mode not an integer: {rm}' - * 'toNearest() rounding mode out of range: {rm}' - * - */ - P.toNearest = function (y, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - - if (y == null) { - - // If x is not finite, return x. - if (!x.d) return x; - - y = new Ctor(1); - rm = Ctor.rounding; - } else { - y = new Ctor(y); - if (rm === void 0) { - rm = Ctor.rounding; - } else { - checkInt32(rm, 0, 8); - } - - // If x is not finite, return x if y is not NaN, else NaN. - if (!x.d) return y.s ? x : y; - - // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. - if (!y.d) { - if (y.s) y.s = x.s; - return y; - } - } - - // If y is not zero, calculate the nearest multiple of y to x. - if (y.d[0]) { - external = false; - x = divide(x, y, 0, rm, 1).times(y); - external = true; - finalise(x); - - // If y is zero, return zero with the sign of x. - } else { - y.s = x.s; - x = y; - } - - return x; - }; - - - /* - * Return the value of this Decimal converted to a number primitive. - * Zero keeps its sign. - * - */ - P.toNumber = function () { - return +this; - }; - - - /* - * Return a string representing the value of this Decimal in base 8, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toOctal = function (sd, rm) { - return toStringBinary(this, 8, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded - * to `precision` significant digits using rounding mode `rounding`. - * - * ECMAScript compliant. - * - * pow(x, NaN) = NaN - * pow(x, ±0) = 1 - - * pow(NaN, non-zero) = NaN - * pow(abs(x) > 1, +Infinity) = +Infinity - * pow(abs(x) > 1, -Infinity) = +0 - * pow(abs(x) == 1, ±Infinity) = NaN - * pow(abs(x) < 1, +Infinity) = +0 - * pow(abs(x) < 1, -Infinity) = +Infinity - * pow(+Infinity, y > 0) = +Infinity - * pow(+Infinity, y < 0) = +0 - * pow(-Infinity, odd integer > 0) = -Infinity - * pow(-Infinity, even integer > 0) = +Infinity - * pow(-Infinity, odd integer < 0) = -0 - * pow(-Infinity, even integer < 0) = +0 - * pow(+0, y > 0) = +0 - * pow(+0, y < 0) = +Infinity - * pow(-0, odd integer > 0) = -0 - * pow(-0, even integer > 0) = +0 - * pow(-0, odd integer < 0) = -Infinity - * pow(-0, even integer < 0) = +Infinity - * pow(finite x < 0, finite non-integer) = NaN - * - * For non-integer or very large exponents pow(x, y) is calculated using - * - * x^y = exp(y*ln(x)) - * - * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the - * probability of an incorrectly rounded result - * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 - * i.e. 1 in 250,000,000,000,000 - * - * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). - * - * y {number|string|Decimal} The power to which to raise this Decimal. - * - */ - P.toPower = P.pow = function (y) { - var e, k, pr, r, rm, s, - x = this, - Ctor = x.constructor, - yn = +(y = new Ctor(y)); - - // Either ±Infinity, NaN or ±0? - if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); - - x = new Ctor(x); - - if (x.eq(1)) return x; - - pr = Ctor.precision; - rm = Ctor.rounding; - - if (y.eq(1)) return finalise(x, pr, rm); - - // y exponent - e = mathfloor(y.e / LOG_BASE); - - // If y is a small integer use the 'exponentiation by squaring' algorithm. - if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { - r = intPow(Ctor, x, k, pr); - return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); - } - - s = x.s; - - // if x is negative - if (s < 0) { - - // if y is not an integer - if (e < y.d.length - 1) return new Ctor(NaN); - - // Result is positive if x is negative and the last digit of integer y is even. - if ((y.d[e] & 1) == 0) s = 1; - - // if x.eq(-1) - if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { - x.s = s; - return x; - } - } - - // Estimate result exponent. - // x^y = 10^e, where e = y * log10(x) - // log10(x) = log10(x_significand) + x_exponent - // log10(x_significand) = ln(x_significand) / ln(10) - k = mathpow(+x, yn); - e = k == 0 || !isFinite(k) - ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) - : new Ctor(k + '').e; - - // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. - - // Overflow/underflow? - if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); - - external = false; - Ctor.rounding = x.s = 1; - - // Estimate the extra guard digits needed to ensure five correct rounding digits from - // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): - // new Decimal(2.32456).pow('2087987436534566.46411') - // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 - k = Math.min(12, (e + '').length); - - // r = x^y = exp(y*ln(x)) - r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); - - // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) - if (r.d) { - - // Truncate to the required precision plus five rounding digits. - r = finalise(r, pr + 5, 1); - - // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate - // the result. - if (checkRoundingDigits(r.d, pr, rm)) { - e = pr + 10; - - // Truncate to the increased precision plus five rounding digits. - r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); - - // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). - if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - } - } - - r.s = s; - external = true; - Ctor.rounding = rm; - - return finalise(r, pr, rm); - }; - - - /* - * Return a string representing the value of this Decimal rounded to `sd` significant digits - * using rounding mode `rounding`. - * - * Return exponential notation if `sd` is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toPrecision = function (sd, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (sd === void 0) { - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), sd, rm); - str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` - * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if - * omitted. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toSD() digits out of range: {sd}' - * 'toSD() digits not an integer: {sd}' - * 'toSD() rounding mode not an integer: {rm}' - * 'toSD() rounding mode out of range: {rm}' - * - */ - P.toSignificantDigits = P.toSD = function (sd, rm) { - var x = this, - Ctor = x.constructor; - - if (sd === void 0) { - sd = Ctor.precision; - rm = Ctor.rounding; - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } - - return finalise(new Ctor(x), sd, rm); - }; - - - /* - * Return a string representing the value of this Decimal. - * - * Return exponential notation if this Decimal has a positive exponent equal to or greater than - * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. - * - */ - P.toString = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. - * - */ - P.truncated = P.trunc = function () { - return finalise(new this.constructor(this), this.e + 1, 1); - }; - - - /* - * Return a string representing the value of this Decimal. - * Unlike `toString`, negative zero will include the minus sign. - * - */ - P.valueOf = P.toJSON = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() ? '-' + str : str; - }; - - - /* - // Add aliases to match BigDecimal method names. - // P.add = P.plus; - P.subtract = P.minus; - P.multiply = P.times; - P.divide = P.div; - P.remainder = P.mod; - P.compareTo = P.cmp; - P.negate = P.neg; - */ - - - // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. - - - /* - * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, - * finiteToString, naturalExponential, naturalLogarithm - * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, - * P.toPrecision, P.toSignificantDigits, toStringBinary, random - * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm - * convertBase toStringBinary, parseOther - * cos P.cos - * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, - * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, - * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, - * taylorSeries, atan2, parseOther - * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, - * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, - * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, - * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, - * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, - * P.truncated, divide, getLn10, getPi, naturalExponential, - * naturalLogarithm, ceil, floor, round, trunc - * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, - * toStringBinary - * getBase10Exponent P.minus, P.plus, P.times, parseOther - * getLn10 P.logarithm, naturalLogarithm - * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 - * getPrecision P.precision, P.toFraction - * getZeroString digitsToString, finiteToString - * intPow P.toPower, parseOther - * isOdd toLessThanHalfPi - * maxOrMin max, min - * naturalExponential P.naturalExponential, P.toPower - * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, - * P.toPower, naturalExponential - * nonFiniteToString finiteToString, toStringBinary - * parseDecimal Decimal - * parseOther Decimal - * sin P.sin - * taylorSeries P.cosh, P.sinh, cos, sin - * toLessThanHalfPi P.cos, P.sin - * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal - * truncate intPow - * - * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, - * naturalLogarithm, config, parseOther, random, Decimal - */ - - - function digitsToString(d) { - var i, k, ws, - indexOfLastWord = d.length - 1, - str = '', - w = d[0]; - - if (indexOfLastWord > 0) { - str += w; - for (i = 1; i < indexOfLastWord; i++) { - ws = d[i] + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - str += ws; - } - - w = d[i]; - ws = w + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - } else if (w === 0) { - return '0'; - } - - // Remove trailing zeros of last w. - for (; w % 10 === 0;) w /= 10; - - return str + w; - } - - - function checkInt32(i, min, max) { - if (i !== ~~i || i < min || i > max) { - throw Error(invalidArgument + i); - } - } - - - /* - * Check 5 rounding digits if `repeating` is null, 4 otherwise. - * `repeating == null` if caller is `log` or `pow`, - * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. - */ - function checkRoundingDigits(d, i, rm, repeating) { - var di, k, r, rd; - - // Get the length of the first word of the array d. - for (k = d[0]; k >= 10; k /= 10) --i; - - // Is the rounding digit in the first word of d? - if (--i < 0) { - i += LOG_BASE; - di = 0; - } else { - di = Math.ceil((i + 1) / LOG_BASE); - i %= LOG_BASE; - } - - // i is the index (0 - 6) of the rounding digit. - // E.g. if within the word 3487563 the first rounding digit is 5, - // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 - k = mathpow(10, LOG_BASE - i); - rd = d[di] % k | 0; - - if (repeating == null) { - if (i < 3) { - if (i == 0) rd = rd / 100 | 0; - else if (i == 1) rd = rd / 10 | 0; - r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; - } else { - r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && - (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || - (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; - } - } else { - if (i < 4) { - if (i == 0) rd = rd / 1000 | 0; - else if (i == 1) rd = rd / 100 | 0; - else if (i == 2) rd = rd / 10 | 0; - r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; - } else { - r = ((repeating || rm < 4) && rd + 1 == k || - (!repeating && rm > 3) && rd + 1 == k / 2) && - (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; - } - } - - return r; - } - - - // Convert string of `baseIn` to an array of numbers of `baseOut`. - // Eg. convertBase('255', 10, 16) returns [15, 15]. - // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. - function convertBase(str, baseIn, baseOut) { - var j, - arr = [0], - arrL, - i = 0, - strL = str.length; - - for (; i < strL;) { - for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; - arr[0] += NUMERALS.indexOf(str.charAt(i++)); - for (j = 0; j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] === void 0) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - - /* - * cos(x) = 1 - x^2/2! + x^4/4! - ... - * |x| < pi/2 - * - */ - function cosine(Ctor, x) { - var k, y, - len = x.d.length; - - // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 - // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 - - // Estimate the optimum number of times to use the argument reduction. - if (len < 32) { - k = Math.ceil(len / 3); - y = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - y = '2.3283064365386962890625e-10'; - } - - Ctor.precision += k; - - x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); - - // Reverse argument reduction - for (var i = k; i--;) { - var cos2x = x.times(x); - x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); - } - - Ctor.precision -= k; - - return x; - } - - - /* - * Perform division in the specified base. - */ - var divide = (function () { - - // Assumes non-zero x and k, and hence non-zero result. - function multiplyInteger(x, k, base) { - var temp, - carry = 0, - i = x.length; - - for (x = x.slice(); i--;) { - temp = x[i] * k + carry; - x[i] = temp % base | 0; - carry = temp / base | 0; - } - - if (carry) x.unshift(carry); - - return x; - } - - function compare(a, b, aL, bL) { - var i, r; - - if (aL != bL) { - r = aL > bL ? 1 : -1; - } else { - for (i = r = 0; i < aL; i++) { - if (a[i] != b[i]) { - r = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return r; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1;) a.shift(); - } - - return function (x, y, pr, rm, dp, base) { - var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, - yL, yz, - Ctor = x.constructor, - sign = x.s == y.s ? 1 : -1, - xd = x.d, - yd = y.d; - - // Either NaN, Infinity or 0? - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(// Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : - - // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. - xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); - } - - if (base) { - logBase = 1; - e = x.e - y.e; - } else { - base = BASE; - logBase = LOG_BASE; - e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); - } - - yL = yd.length; - xL = xd.length; - q = new Ctor(sign); - qd = q.d = []; - - // Result exponent may be one less than e. - // The digit array of a Decimal from toStringBinary may have trailing zeros. - for (i = 0; yd[i] == (xd[i] || 0); i++); - - if (yd[i] > (xd[i] || 0)) e--; - - if (pr == null) { - sd = pr = Ctor.precision; - rm = Ctor.rounding; - } else if (dp) { - sd = pr + (x.e - y.e) + 1; - } else { - sd = pr; - } - - if (sd < 0) { - qd.push(1); - more = true; - } else { - - // Convert precision in number of base 10 digits to base 1e7 digits. - sd = sd / logBase + 2 | 0; - i = 0; - - // divisor < 1e7 - if (yL == 1) { - k = 0; - yd = yd[0]; - sd++; - - // k is the carry. - for (; (i < xL || k) && sd--; i++) { - t = k * base + (xd[i] || 0); - qd[i] = t / yd | 0; - k = t % yd | 0; - } - - more = k || i < xL; - - // divisor >= 1e7 - } else { - - // Normalise xd and yd so highest order digit of yd is >= base/2 - k = base / (yd[0] + 1) | 0; - - if (k > 1) { - yd = multiplyInteger(yd, k, base); - xd = multiplyInteger(xd, k, base); - yL = yd.length; - xL = xd.length; - } - - xi = yL; - rem = xd.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL;) rem[remL++] = 0; - - yz = yd.slice(); - yz.unshift(0); - yd0 = yd[0]; - - if (yd[1] >= base / 2) ++yd0; - - do { - k = 0; - - // Compare divisor and remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, k. - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // k will be how many times the divisor goes into the current remainder. - k = rem0 / yd0 | 0; - - // Algorithm: - // 1. product = divisor * trial digit (k) - // 2. if product > remainder: product -= divisor, k-- - // 3. remainder -= product - // 4. if product was < remainder at 2: - // 5. compare new remainder and divisor - // 6. If remainder > divisor: remainder -= divisor, k++ - - if (k > 1) { - if (k >= base) k = base - 1; - - // product = divisor * trial digit. - prod = multiplyInteger(yd, k, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - cmp = compare(prod, rem, prodL, remL); - - // product > remainder. - if (cmp == 1) { - k--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yd, prodL, base); - } - } else { - - // cmp is -1. - // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 - // to avoid it. If k is 1 there is a need to compare yd and rem again below. - if (k == 0) cmp = k = 1; - prod = yd.slice(); - } - - prodL = prod.length; - if (prodL < remL) prod.unshift(0); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - - // If product was < previous remainder. - if (cmp == -1) { - remL = rem.length; - - // Compare divisor and new remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < new remainder, subtract divisor from remainder. - if (cmp < 1) { - k++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yd, remL, base); - } - } - - remL = rem.length; - } else if (cmp === 0) { - k++; - rem = [0]; - } // if cmp === 1, k will be 0 - - // Add the next digit, k, to the result array. - qd[i++] = k; - - // Update the remainder. - if (cmp && rem[0]) { - rem[remL++] = xd[xi] || 0; - } else { - rem = [xd[xi]]; - remL = 1; - } - - } while ((xi++ < xL || rem[0] !== void 0) && sd--); - - more = rem[0] !== void 0; - } - - // Leading zero? - if (!qd[0]) qd.shift(); - } - - // logBase is 1 when divide is being used for base conversion. - if (logBase == 1) { - q.e = e; - inexact = more; - } else { - - // To calculate q.e, first get the number of digits of qd[0]. - for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; - q.e = i + e * logBase - 1; - - finalise(q, dp ? pr + q.e + 1 : pr, rm, more); - } - - return q; - }; - })(); - - - /* - * Round `x` to `sd` significant digits using rounding mode `rm`. - * Check for over/under-flow. - */ - function finalise(x, sd, rm, isTruncated) { - var digits, i, j, k, rd, roundUp, w, xd, xdi, - Ctor = x.constructor; - - // Don't round if sd is null or undefined. - out: if (sd != null) { - xd = x.d; - - // Infinity/NaN. - if (!xd) return x; - - // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. - // w: the word of xd containing rd, a base 1e7 number. - // xdi: the index of w within xd. - // digits: the number of digits of w. - // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if - // they had leading zeros) - // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). - - // Get the length of the first word of the digits array xd. - for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; - i = sd - digits; - - // Is the rounding digit in the first word of xd? - if (i < 0) { - i += LOG_BASE; - j = sd; - w = xd[xdi = 0]; - - // Get the rounding digit at index j of w. - rd = w / mathpow(10, digits - j - 1) % 10 | 0; - } else { - xdi = Math.ceil((i + 1) / LOG_BASE); - k = xd.length; - if (xdi >= k) { - if (isTruncated) { - - // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. - for (; k++ <= xdi;) xd.push(0); - w = rd = 0; - digits = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - w = k = xd[xdi]; - - // Get the number of digits of w. - for (digits = 1; k >= 10; k /= 10) digits++; - - // Get the index of rd within w. - i %= LOG_BASE; - - // Get the index of rd within w, adjusted for leading zeros. - // The number of leading zeros of w is given by LOG_BASE - digits. - j = i - LOG_BASE + digits; - - // Get the rounding digit at index j of w. - rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; - } - } - - // Are there any non-zero digits after the rounding digit? - isTruncated = isTruncated || sd < 0 || - xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); - - // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right - // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression - // will give 714. - - roundUp = rm < 4 - ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xd[0]) { - xd.length = 0; - if (roundUp) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); - x.e = -sd || 0; - } else { - - // Zero. - xd[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xd.length = xdi; - k = 1; - xdi--; - } else { - xd.length = xdi + 1; - k = mathpow(10, LOG_BASE - i); - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of w. - xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; - } - - if (roundUp) { - for (;;) { - - // Is the digit to be rounded up in the first word of xd? - if (xdi == 0) { - - // i will be the length of xd[0] before k is added. - for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; - j = xd[0] += k; - for (k = 1; j >= 10; j /= 10) k++; - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xd[0] == BASE) xd[0] = 1; - } - - break; - } else { - xd[xdi] += k; - if (xd[xdi] != BASE) break; - xd[xdi--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xd.length; xd[--i] === 0;) xd.pop(); - } - - if (external) { - - // Overflow? - if (x.e > Ctor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < Ctor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // Ctor.underflow = true; - } // else Ctor.underflow = false; - } - - return x; - } - - - function finiteToString(x, isExp, sd) { - if (!x.isFinite()) return nonFiniteToString(x); - var k, - e = x.e, - str = digitsToString(x.d), - len = str.length; - - if (isExp) { - if (sd && (k = sd - len) > 0) { - str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); - } else if (len > 1) { - str = str.charAt(0) + '.' + str.slice(1); - } - - str = str + (x.e < 0 ? 'e' : 'e+') + x.e; - } else if (e < 0) { - str = '0.' + getZeroString(-e - 1) + str; - if (sd && (k = sd - len) > 0) str += getZeroString(k); - } else if (e >= len) { - str += getZeroString(e + 1 - len); - if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); - } else { - if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); - if (sd && (k = sd - len) > 0) { - if (e + 1 === len) str += '.'; - str += getZeroString(k); - } - } - - return str; - } - - - // Calculate the base 10 exponent from the base 1e7 exponent. - function getBase10Exponent(digits, e) { - var w = digits[0]; - - // Add the number of digits of the first word of the digits array. - for ( e *= LOG_BASE; w >= 10; w /= 10) e++; - return e; - } - - - function getLn10(Ctor, sd, pr) { - if (sd > LN10_PRECISION) { - - // Reset global state in case the exception is caught. - external = true; - if (pr) Ctor.precision = pr; - throw Error(precisionLimitExceeded); - } - return finalise(new Ctor(LN10), sd, 1, true); - } - - - function getPi(Ctor, sd, rm) { - if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); - return finalise(new Ctor(PI), sd, rm, true); - } - - - function getPrecision(digits) { - var w = digits.length - 1, - len = w * LOG_BASE + 1; - - w = digits[w]; - - // If non-zero... - if (w) { - - // Subtract the number of trailing zeros of the last word. - for (; w % 10 == 0; w /= 10) len--; - - // Add the number of digits of the first word. - for (w = digits[0]; w >= 10; w /= 10) len++; - } - - return len; - } - - - function getZeroString(k) { - var zs = ''; - for (; k--;) zs += '0'; - return zs; - } - - - /* - * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an - * integer of type number. - * - * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. - * - */ - function intPow(Ctor, x, n, pr) { - var isTruncated, - r = new Ctor(1), - - // Max n of 9007199254740991 takes 53 loop iterations. - // Maximum digits array length; leaves [28, 34] guard digits. - k = Math.ceil(pr / LOG_BASE + 4); - - external = false; - - for (;;) { - if (n % 2) { - r = r.times(x); - if (truncate(r.d, k)) isTruncated = true; - } - - n = mathfloor(n / 2); - if (n === 0) { - - // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. - n = r.d.length - 1; - if (isTruncated && r.d[n] === 0) ++r.d[n]; - break; - } - - x = x.times(x); - truncate(x.d, k); - } - - external = true; - - return r; - } - - - function isOdd(n) { - return n.d[n.d.length - 1] & 1; - } - - - /* - * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. - */ - function maxOrMin(Ctor, args, ltgt) { - var y, - x = new Ctor(args[0]), - i = 0; - - for (; ++i < args.length;) { - y = new Ctor(args[i]); - if (!y.s) { - x = y; - break; - } else if (x[ltgt](y)) { - x = y; - } - } - - return x; - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant - * digits. - * - * Taylor/Maclaurin series. - * - * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... - * - * Argument reduction: - * Repeat x = x / 32, k += 5, until |x| < 0.1 - * exp(x) = exp(x / 2^k)^(2^k) - * - * Previously, the argument was initially reduced by - * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) - * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was - * found to be slower than just dividing repeatedly by 32 as above. - * - * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 - * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 - * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) - * - * exp(Infinity) = Infinity - * exp(-Infinity) = 0 - * exp(NaN) = NaN - * exp(±0) = 1 - * - * exp(x) is non-terminating for any finite, non-zero x. - * - * The result will always be correctly rounded. - * - */ - function naturalExponential(x, sd) { - var denominator, guard, j, pow, sum, t, wpr, - rep = 0, - i = 0, - k = 0, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // 0/NaN/Infinity? - if (!x.d || !x.d[0] || x.e > 17) { - - return new Ctor(x.d - ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 - : x.s ? x.s < 0 ? 0 : x : 0 / 0); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - t = new Ctor(0.03125); - - // while abs(x) >= 0.1 - while (x.e > -2) { - - // x = x / 2^5 - x = x.times(t); - k += 5; - } - - // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision - // necessary to ensure the first 4 rounding digits are correct. - guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; - wpr += guard; - denominator = pow = sum = new Ctor(1); - Ctor.precision = wpr; - - for (;;) { - pow = finalise(pow.times(x), wpr, 1); - denominator = denominator.times(++i); - t = sum.plus(divide(pow, denominator, wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - j = k; - while (j--) sum = finalise(sum.times(sum), wpr, 1); - - // Check to see if the first 4 rounding digits are [49]999. - // If so, repeat the summation with a higher precision, otherwise - // e.g. with precision: 18, rounding: 1 - // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - - if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += 10; - denominator = pow = t = new Ctor(1); - i = 0; - rep++; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - } - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant - * digits. - * - * ln(-n) = NaN - * ln(0) = -Infinity - * ln(-0) = -Infinity - * ln(1) = 0 - * ln(Infinity) = Infinity - * ln(-Infinity) = NaN - * ln(NaN) = NaN - * - * ln(n) (n != 1) is non-terminating. - * - */ - function naturalLogarithm(y, sd) { - var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, - n = 1, - guard = 10, - x = y, - xd = x.d, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // Is x negative or Infinity, NaN, 0 or 1? - if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { - return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - Ctor.precision = wpr += guard; - c = digitsToString(xd); - c0 = c.charAt(0); - - if (Math.abs(e = x.e) < 1.5e15) { - - // Argument reduction. - // The series converges faster the closer the argument is to 1, so using - // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b - // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, - // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can - // later be divided by this number, then separate out the power of 10 using - // ln(a*10^b) = ln(a) + b*ln(10). - - // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). - //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { - // max n is 6 (gives 0.7 - 1.3) - while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { - x = x.times(y); - c = digitsToString(x.d); - c0 = c.charAt(0); - n++; - } - - e = x.e; - - if (c0 > 1) { - x = new Ctor('0.' + c); - e++; - } else { - x = new Ctor(c0 + '.' + c.slice(1)); - } - } else { - - // The argument reduction method above may result in overflow if the argument y is a massive - // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this - // function using ln(x*10^e) = ln(x) + e*ln(10). - t = getLn10(Ctor, wpr + 2, pr).times(e + ''); - x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); - Ctor.precision = pr; - - return sd == null ? finalise(x, pr, rm, external = true) : x; - } - - // x1 is x reduced to a value near 1. - x1 = x; - - // Taylor series. - // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) - // where x = (y - 1)/(y + 1) (|x| < 1) - sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = 3; - - for (;;) { - numerator = finalise(numerator.times(x2), wpr, 1); - t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - sum = sum.times(2); - - // Reverse the argument reduction. Check that e is not 0 because, besides preventing an - // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. - if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); - sum = divide(sum, new Ctor(n), wpr, 1); - - // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has - // been repeated previously) and the first 4 rounding digits 9999? - // If so, restart the summation with a higher precision, otherwise - // e.g. with precision: 12, rounding: 1 - // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += guard; - t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = rep = 1; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - denominator += 2; - } - } - - - // ±Infinity, NaN. - function nonFiniteToString(x) { - // Unsigned. - return String(x.s * x.s / 0); - } - - - /* - * Parse the value of a new Decimal `x` from string `str`. - */ - function parseDecimal(x, str) { - var e, i, len; - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(len - 1) === 48; --len); - str = str.slice(i, len); - - if (str) { - len -= i; - x.e = e = e - i - 1; - x.d = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first word of the digits array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; - - if (i < len) { - if (i) x.d.push(+str.slice(0, i)); - for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); - str = str.slice(i); - i = LOG_BASE - str.length; - } else { - i -= len; - } - - for (; i--;) str += '0'; - x.d.push(+str); - - if (external) { - - // Overflow? - if (x.e > x.constructor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < x.constructor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // x.constructor.underflow = true; - } // else x.constructor.underflow = false; - } - } else { - - // Zero. - x.e = 0; - x.d = [0]; - } - - return x; - } - - - /* - * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. - */ - function parseOther(x, str) { - var base, Ctor, divisor, i, isFloat, len, p, xd, xe; - - if (str === 'Infinity' || str === 'NaN') { - if (!+str) x.s = NaN; - x.e = NaN; - x.d = null; - return x; - } - - if (isHex.test(str)) { - base = 16; - str = str.toLowerCase(); - } else if (isBinary.test(str)) { - base = 2; - } else if (isOctal.test(str)) { - base = 8; - } else { - throw Error(invalidArgument + str); - } - - // Is there a binary exponent part? - i = str.search(/p/i); - - if (i > 0) { - p = +str.slice(i + 1); - str = str.substring(2, i); - } else { - str = str.slice(2); - } - - // Convert `str` as an integer then divide the result by `base` raised to a power such that the - // fraction part will be restored. - i = str.indexOf('.'); - isFloat = i >= 0; - Ctor = x.constructor; - - if (isFloat) { - str = str.replace('.', ''); - len = str.length; - i = len - i; - - // log[10](16) = 1.2041... , log[10](88) = 1.9444.... - divisor = intPow(Ctor, new Ctor(base), i, i * 2); - } - - xd = convertBase(str, base, BASE); - xe = xd.length - 1; - - // Remove trailing zeros. - for (i = xe; xd[i] === 0; --i) xd.pop(); - if (i < 0) return new Ctor(x.s * 0); - x.e = getBase10Exponent(xd, xe); - x.d = xd; - external = false; - - // At what precision to perform the division to ensure exact conversion? - // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) - // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 - // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. - // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount - // Therefore using 4 * the number of digits of str will always be enough. - if (isFloat) x = divide(x, divisor, len * 4); - - // Multiply by the binary exponent part if present. - if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); - external = true; - - return x; - } - - - /* - * sin(x) = x - x^3/3! + x^5/5! - ... - * |x| < pi/2 - * - */ - function sine(Ctor, x) { - var k, - len = x.d.length; - - if (len < 3) return taylorSeries(Ctor, 2, x, x); - - // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) - // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) - // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x); - - // Reverse argument reduction - var sin2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sin2_x = x.times(x); - x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); - } - - return x; - } - - - // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. - function taylorSeries(Ctor, n, x, y, isHyperbolic) { - var j, t, u, x2, - i = 1, - pr = Ctor.precision, - k = Math.ceil(pr / LOG_BASE); - - external = false; - x2 = x.times(x); - u = new Ctor(y); - - for (;;) { - t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); - u = isHyperbolic ? y.plus(t) : y.minus(t); - y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); - t = u.plus(y); - - if (t.d[k] !== void 0) { - for (j = k; t.d[j] === u.d[j] && j--;); - if (j == -1) break; - } - - j = u; - u = y; - y = t; - t = j; - i++; - } - - external = true; - t.d.length = k + 1; - - return t; - } - - - // Exponent e must be positive and non-zero. - function tinyPow(b, e) { - var n = b; - while (--e) n *= b; - return n; - } - - - // Return the absolute value of `x` reduced to less than or equal to half pi. - function toLessThanHalfPi(Ctor, x) { - var t, - isNeg = x.s < 0, - pi = getPi(Ctor, Ctor.precision, 1), - halfPi = pi.times(0.5); - - x = x.abs(); - - if (x.lte(halfPi)) { - quadrant = isNeg ? 4 : 1; - return x; - } - - t = x.divToInt(pi); - - if (t.isZero()) { - quadrant = isNeg ? 3 : 2; - } else { - x = x.minus(t.times(pi)); - - // 0 <= x < pi - if (x.lte(halfPi)) { - quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); - return x; - } - - quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); - } - - return x.minus(pi).abs(); - } - - - /* - * Return the value of Decimal `x` as a string in base `baseOut`. - * - * If the optional `sd` argument is present include a binary exponent suffix. - */ - function toStringBinary(x, baseOut, sd, rm) { - var base, e, i, k, len, roundUp, str, xd, y, - Ctor = x.constructor, - isExp = sd !== void 0; - - if (isExp) { - checkInt32(sd, 1, MAX_DIGITS); - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } else { - sd = Ctor.precision; - rm = Ctor.rounding; - } - - if (!x.isFinite()) { - str = nonFiniteToString(x); - } else { - str = finiteToString(x); - i = str.indexOf('.'); - - // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: - // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) - // minBinaryExponent = floor(decimalExponent * log[2](10)) - // log[2](10) = 3.321928094887362347870319429489390175864 - - if (isExp) { - base = 2; - if (baseOut == 16) { - sd = sd * 4 - 3; - } else if (baseOut == 8) { - sd = sd * 3 - 2; - } - } else { - base = baseOut; - } - - // Convert the number as an integer then divide the result by its base raised to a power such - // that the fraction part will be restored. - - // Non-integer. - if (i >= 0) { - str = str.replace('.', ''); - y = new Ctor(1); - y.e = str.length - i; - y.d = convertBase(finiteToString(y), 10, base); - y.e = y.d.length; - } - - xd = convertBase(str, 10, base); - e = len = xd.length; - - // Remove trailing zeros. - for (; xd[--len] == 0;) xd.pop(); - - if (!xd[0]) { - str = isExp ? '0p+0' : '0'; - } else { - if (i < 0) { - e--; - } else { - x = new Ctor(x); - x.d = xd; - x.e = e; - x = divide(x, y, sd, rm, 0, base); - xd = x.d; - e = x.e; - roundUp = inexact; - } - - // The rounding digit, i.e. the digit after the digit that may be rounded up. - i = xd[sd]; - k = base / 2; - roundUp = roundUp || xd[sd + 1] !== void 0; - - roundUp = rm < 4 - ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) - : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || - rm === (x.s < 0 ? 8 : 7)); - - xd.length = sd; - - if (roundUp) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (; ++xd[--sd] > base - 1;) { - xd[sd] = 0; - if (!sd) { - ++e; - xd.unshift(1); - } - } - } - - // Determine trailing zeros. - for (len = xd.length; !xd[len - 1]; --len); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); - - // Add binary exponent suffix? - if (isExp) { - if (len > 1) { - if (baseOut == 16 || baseOut == 8) { - i = baseOut == 16 ? 4 : 3; - for (--len; len % i; len++) str += '0'; - xd = convertBase(str, base, baseOut); - for (len = xd.length; !xd[len - 1]; --len); - - // xd[0] will always be be 1 - for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); - } else { - str = str.charAt(0) + '.' + str.slice(1); - } - } - - str = str + (e < 0 ? 'p' : 'p+') + e; - } else if (e < 0) { - for (; ++e;) str = '0' + str; - str = '0.' + str; - } else { - if (++e > len) for (e -= len; e-- ;) str += '0'; - else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); - } - } - - str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; - } - - return x.s < 0 ? '-' + str : str; - } - - - // Does not strip trailing zeros. - function truncate(arr, len) { - if (arr.length > len) { - arr.length = len; - return true; - } - } - - - // Decimal methods - - - /* - * abs - * acos - * acosh - * add - * asin - * asinh - * atan - * atanh - * atan2 - * cbrt - * ceil - * clone - * config - * cos - * cosh - * div - * exp - * floor - * hypot - * ln - * log - * log2 - * log10 - * max - * min - * mod - * mul - * pow - * random - * round - * set - * sign - * sin - * sinh - * sqrt - * sub - * tan - * tanh - * trunc - */ - - - /* - * Return a new Decimal whose value is the absolute value of `x`. - * - * x {number|string|Decimal} - * - */ - function abs(x) { - return new this(x).abs(); - } - - - /* - * Return a new Decimal whose value is the arccosine in radians of `x`. - * - * x {number|string|Decimal} - * - */ - function acos(x) { - return new this(x).acos(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function acosh(x) { - return new this(x).acosh(); - } - - - /* - * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function add(x, y) { - return new this(x).plus(y); - } - - - /* - * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function asin(x) { - return new this(x).asin(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function asinh(x) { - return new this(x).asinh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function atan(x) { - return new this(x).atan(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function atanh(x) { - return new this(x).atanh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi - * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi, pi] - * - * y {number|string|Decimal} The y-coordinate. - * x {number|string|Decimal} The x-coordinate. - * - * atan2(±0, -0) = ±pi - * atan2(±0, +0) = ±0 - * atan2(±0, -x) = ±pi for x > 0 - * atan2(±0, x) = ±0 for x > 0 - * atan2(-y, ±0) = -pi/2 for y > 0 - * atan2(y, ±0) = pi/2 for y > 0 - * atan2(±y, -Infinity) = ±pi for finite y > 0 - * atan2(±y, +Infinity) = ±0 for finite y > 0 - * atan2(±Infinity, x) = ±pi/2 for finite x - * atan2(±Infinity, -Infinity) = ±3*pi/4 - * atan2(±Infinity, +Infinity) = ±pi/4 - * atan2(NaN, x) = NaN - * atan2(y, NaN) = NaN - * - */ - function atan2(y, x) { - y = new this(y); - x = new this(x); - var r, - pr = this.precision, - rm = this.rounding, - wpr = pr + 4; - - // Either NaN - if (!y.s || !x.s) { - r = new this(NaN); - - // Both ±Infinity - } else if (!y.d && !x.d) { - r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); - r.s = y.s; - - // x is ±Infinity or y is ±0 - } else if (!x.d || y.isZero()) { - r = x.s < 0 ? getPi(this, pr, rm) : new this(0); - r.s = y.s; - - // y is ±Infinity or x is ±0 - } else if (!y.d || x.isZero()) { - r = getPi(this, wpr, 1).times(0.5); - r.s = y.s; - - // Both non-zero and finite - } else if (x.s < 0) { - this.precision = wpr; - this.rounding = 1; - r = this.atan(divide(y, x, wpr, 1)); - x = getPi(this, wpr, 1); - this.precision = pr; - this.rounding = rm; - r = y.s < 0 ? r.minus(x) : r.plus(x); - } else { - r = this.atan(divide(y, x, wpr, 1)); - } - - return r; - } - - - /* - * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function cbrt(x) { - return new this(x).cbrt(); - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. - * - * x {number|string|Decimal} - * - */ - function ceil(x) { - return finalise(x = new this(x), x.e + 1, 2); - } - - - /* - * Configure global settings for a Decimal constructor. - * - * `obj` is an object with one or more of the following properties, - * - * precision {number} - * rounding {number} - * toExpNeg {number} - * toExpPos {number} - * maxE {number} - * minE {number} - * modulo {number} - * crypto {boolean|number} - * defaults {true} - * - * E.g. Decimal.config({ precision: 20, rounding: 4 }) - * - */ - function config(obj) { - if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); - var i, p, v, - useDefaults = obj.defaults === true, - ps = [ - 'precision', 1, MAX_DIGITS, - 'rounding', 0, 8, - 'toExpNeg', -EXP_LIMIT, 0, - 'toExpPos', 0, EXP_LIMIT, - 'maxE', 0, EXP_LIMIT, - 'minE', -EXP_LIMIT, 0, - 'modulo', 0, 9 - ]; - - for (i = 0; i < ps.length; i += 3) { - if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; - else throw Error(invalidArgument + p + ': ' + v); - } - } - - if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (v === true || v === false || v === 0 || v === 1) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - this[p] = true; - } else { - throw Error(cryptoUnavailable); - } - } else { - this[p] = false; - } - } else { - throw Error(invalidArgument + p + ': ' + v); - } - } - - return this; - } - - - /* - * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cos(x) { - return new this(x).cos(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cosh(x) { - return new this(x).cosh(); - } - - - /* - * Create and return a Decimal constructor with the same configuration properties as this Decimal - * constructor. - * - */ - function clone(obj) { - var i, p, ps; - - /* - * The Decimal constructor and exported function. - * Return a new Decimal instance. - * - * v {number|string|Decimal} A numeric value. - * - */ - function Decimal(v) { - var e, i, t, - x = this; - - // Decimal called without new. - if (!(x instanceof Decimal)) return new Decimal(v); - - // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor - // which points to Object. - x.constructor = Decimal; - - // Duplicate. - if (v instanceof Decimal) { - x.s = v.s; - - if (external) { - if (!v.d || v.e > Decimal.maxE) { - - // Infinity. - x.e = NaN; - x.d = null; - } else if (v.e < Decimal.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - } else { - x.e = v.e; - x.d = v.d.slice(); - } - } else { - x.e = v.e; - x.d = v.d ? v.d.slice() : v.d; - } - - return; - } - - t = typeof v; - - if (t === 'number') { - if (v === 0) { - x.s = 1 / v < 0 ? -1 : 1; - x.e = 0; - x.d = [0]; - return; - } - - if (v < 0) { - v = -v; - x.s = -1; - } else { - x.s = 1; - } - - // Fast path for small integers. - if (v === ~~v && v < 1e7) { - for (e = 0, i = v; i >= 10; i /= 10) e++; - - if (external) { - if (e > Decimal.maxE) { - x.e = NaN; - x.d = null; - } else if (e < Decimal.minE) { - x.e = 0; - x.d = [0]; - } else { - x.e = e; - x.d = [v]; - } - } else { - x.e = e; - x.d = [v]; - } - - return; - - // Infinity, NaN. - } else if (v * 0 !== 0) { - if (!v) x.s = NaN; - x.e = NaN; - x.d = null; - return; - } - - return parseDecimal(x, v.toString()); - - } else if (t !== 'string') { - throw Error(invalidArgument + v); - } - - // Minus sign? - if ((i = v.charCodeAt(0)) === 45) { - v = v.slice(1); - x.s = -1; - } else { - // Plus sign? - if (i === 43) v = v.slice(1); - x.s = 1; - } - - return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); - } - - Decimal.prototype = P; - - Decimal.ROUND_UP = 0; - Decimal.ROUND_DOWN = 1; - Decimal.ROUND_CEIL = 2; - Decimal.ROUND_FLOOR = 3; - Decimal.ROUND_HALF_UP = 4; - Decimal.ROUND_HALF_DOWN = 5; - Decimal.ROUND_HALF_EVEN = 6; - Decimal.ROUND_HALF_CEIL = 7; - Decimal.ROUND_HALF_FLOOR = 8; - Decimal.EUCLID = 9; - - Decimal.config = Decimal.set = config; - Decimal.clone = clone; - Decimal.isDecimal = isDecimalInstance; - - Decimal.abs = abs; - Decimal.acos = acos; - Decimal.acosh = acosh; // ES6 - Decimal.add = add; - Decimal.asin = asin; - Decimal.asinh = asinh; // ES6 - Decimal.atan = atan; - Decimal.atanh = atanh; // ES6 - Decimal.atan2 = atan2; - Decimal.cbrt = cbrt; // ES6 - Decimal.ceil = ceil; - Decimal.cos = cos; - Decimal.cosh = cosh; // ES6 - Decimal.div = div; - Decimal.exp = exp; - Decimal.floor = floor; - Decimal.hypot = hypot; // ES6 - Decimal.ln = ln; - Decimal.log = log; - Decimal.log10 = log10; // ES6 - Decimal.log2 = log2; // ES6 - Decimal.max = max; - Decimal.min = min; - Decimal.mod = mod; - Decimal.mul = mul; - Decimal.pow = pow; - Decimal.random = random; - Decimal.round = round; - Decimal.sign = sign; // ES6 - Decimal.sin = sin; - Decimal.sinh = sinh; // ES6 - Decimal.sqrt = sqrt; - Decimal.sub = sub; - Decimal.tan = tan; - Decimal.tanh = tanh; // ES6 - Decimal.trunc = trunc; // ES6 - - if (obj === void 0) obj = {}; - if (obj) { - if (obj.defaults !== true) { - ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; - for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; - } - } - - Decimal.config(obj); - - return Decimal; - } - - - /* - * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function div(x, y) { - return new this(x).div(y); - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The power to which to raise the base of the natural log. - * - */ - function exp(x) { - return new this(x).exp(); - } - - - /* - * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. - * - * x {number|string|Decimal} - * - */ - function floor(x) { - return finalise(x = new this(x), x.e + 1, 3); - } - - - /* - * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) - * - * arguments {number|string|Decimal} - * - */ - function hypot() { - var i, n, - t = new this(0); - - external = false; - - for (i = 0; i < arguments.length;) { - n = new this(arguments[i++]); - if (!n.d) { - if (n.s) { - external = true; - return new this(1 / 0); - } - t = n; - } else if (t.d) { - t = t.plus(n.times(n)); - } - } - - external = true; - - return t.sqrt(); - } - - - /* - * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), - * otherwise return false. - * - */ - function isDecimalInstance(obj) { - return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function ln(x) { - return new this(x).ln(); - } - - - /* - * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base - * is specified, rounded to `precision` significant digits using rounding mode `rounding`. - * - * log[y](x) - * - * x {number|string|Decimal} The argument of the logarithm. - * y {number|string|Decimal} The base of the logarithm. - * - */ - function log(x, y) { - return new this(x).log(y); - } - - - /* - * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log2(x) { - return new this(x).log(2); - } - - - /* - * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log10(x) { - return new this(x).log(10); - } - - - /* - * Return a new Decimal whose value is the maximum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function max() { - return maxOrMin(this, arguments, 'lt'); - } - - - /* - * Return a new Decimal whose value is the minimum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function min() { - return maxOrMin(this, arguments, 'gt'); - } - - - /* - * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mod(x, y) { - return new this(x).mod(y); - } - - - /* - * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mul(x, y) { - return new this(x).mul(y); - } - - - /* - * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The base. - * y {number|string|Decimal} The exponent. - * - */ - function pow(x, y) { - return new this(x).pow(y); - } - - - /* - * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with - * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros - * are produced). - * - * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. - * - */ - function random(sd) { - var d, e, k, n, - i = 0, - r = new this(1), - rd = []; - - if (sd === void 0) sd = this.precision; - else checkInt32(sd, 1, MAX_DIGITS); - - k = Math.ceil(sd / LOG_BASE); - - if (!this.crypto) { - for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; - - // Browsers supporting crypto.getRandomValues. - } else if (crypto.getRandomValues) { - d = crypto.getRandomValues(new Uint32Array(k)); - - for (; i < k;) { - n = d[i]; - - // 0 <= n < 4294967296 - // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). - if (n >= 4.29e9) { - d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; - } else { - - // 0 <= n <= 4289999999 - // 0 <= (n % 1e7) <= 9999999 - rd[i++] = n % 1e7; - } - } - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - d = crypto.randomBytes(k *= 4); - - for (; i < k;) { - - // 0 <= n < 2147483648 - n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); - - // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). - if (n >= 2.14e9) { - crypto.randomBytes(4).copy(d, i); - } else { - - // 0 <= n <= 2139999999 - // 0 <= (n % 1e7) <= 9999999 - rd.push(n % 1e7); - i += 4; - } - } - - i = k / 4; - } else { - throw Error(cryptoUnavailable); - } - - k = rd[--i]; - sd %= LOG_BASE; - - // Convert trailing digits to zeros according to sd. - if (k && sd) { - n = mathpow(10, LOG_BASE - sd); - rd[i] = (k / n | 0) * n; - } - - // Remove trailing words which are zero. - for (; rd[i] === 0; i--) rd.pop(); - - // Zero? - if (i < 0) { - e = 0; - rd = [0]; - } else { - e = -1; - - // Remove leading words which are zero and adjust exponent accordingly. - for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); - - // Count the digits of the first word of rd to determine leading zeros. - for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; - - // Adjust the exponent for leading zeros of the first word of rd. - if (k < LOG_BASE) e -= LOG_BASE - k; - } - - r.e = e; - r.d = rd; - - return r; - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. - * - * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). - * - * x {number|string|Decimal} - * - */ - function round(x) { - return finalise(x = new this(x), x.e + 1, this.rounding); - } - - - /* - * Return - * 1 if x > 0, - * -1 if x < 0, - * 0 if x is 0, - * -0 if x is -0, - * NaN otherwise - * - * x {number|string|Decimal} - * - */ - function sign(x) { - x = new this(x); - return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; - } - - - /* - * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sin(x) { - return new this(x).sin(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sinh(x) { - return new this(x).sinh(); - } - - - /* - * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function sqrt(x) { - return new this(x).sqrt(); - } - - - /* - * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function sub(x, y) { - return new this(x).sub(y); - } - - - /* - * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tan(x) { - return new this(x).tan(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tanh(x) { - return new this(x).tanh(); - } - - - /* - * Return a new Decimal whose value is `x` truncated to an integer. - * - * x {number|string|Decimal} - * - */ - function trunc(x) { - return finalise(x = new this(x), x.e + 1, 1); - } - - - // Create and configure initial Decimal constructor. - Decimal = clone(DEFAULTS); - - Decimal['default'] = Decimal.Decimal = Decimal; - - // Create the internal constants from their string values. - LN10 = new Decimal(LN10); - PI = new Decimal(PI); - - - // Export. - - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { - return Decimal; - }); - - // Node and other environments that support module.exports. - } else if ( true && module.exports) { - if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { - P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; - P[Symbol.toStringTag] = 'Decimal'; - } - - module.exports = Decimal; - - // Browser. - } else { - if (!globalScope) { - globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; - } - - noConflict = globalScope.Decimal; - Decimal.noConflict = function () { - globalScope.Decimal = noConflict; - return Decimal; - }; - - globalScope.Decimal = Decimal; - } -})(this); +;(function (globalScope) { + 'use strict'; + + + /* + * decimal.js v10.2.1 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2020 Michael Mclaughlin + * MIT Licence + */ + + + // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // + + + // The maximum exponent magnitude. + // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. + var EXP_LIMIT = 9e15, // 0 to 9e15 + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + MAX_DIGITS = 1e9, // 0 to 1e9 + + // Base conversion alphabet. + NUMERALS = '0123456789abcdef', + + // The natural logarithm of 10 (1025 digits). + LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', + + // Pi (1025 digits). + PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', + + + // The initial configuration properties of the Decimal constructor. + DEFAULTS = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed at run-time using the `Decimal.config` method. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used when rounding to `precision`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 The IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. + // + // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian + // division (9) are commonly used for the modulus operation. The other rounding modes can also + // be used, but they may not give useful results. + modulo: 1, // 0 to 9 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -EXP_LIMIT + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to EXP_LIMIT + + // The minimum exponent value, beneath which underflow to zero occurs. + // JavaScript numbers: -324 (5e-324) + minE: -EXP_LIMIT, // -1 to -EXP_LIMIT + + // The maximum exponent value, above which overflow to Infinity occurs. + // JavaScript numbers: 308 (1.7976931348623157e+308) + maxE: EXP_LIMIT, // 1 to EXP_LIMIT + + // Whether to use cryptographically-secure random number generation, if available. + crypto: false // true/false + }, + + + // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // + + + Decimal, inexact, noConflict, quadrant, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + precisionLimitExceeded = decimalError + 'Precision limit exceeded', + cryptoUnavailable = decimalError + 'crypto unavailable', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, + isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, + isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + + LN10_PRECISION = LN10.length - 1, + PI_PRECISION = PI.length - 1, + + // Decimal.prototype object + P = { name: '[object Decimal]' }; + + + // Decimal prototype methods + + + /* + * absoluteValue abs + * ceil + * comparedTo cmp + * cosine cos + * cubeRoot cbrt + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy divToInt + * equals eq + * floor + * greaterThan gt + * greaterThanOrEqualTo gte + * hyperbolicCosine cosh + * hyperbolicSine sinh + * hyperbolicTangent tanh + * inverseCosine acos + * inverseHyperbolicCosine acosh + * inverseHyperbolicSine asinh + * inverseHyperbolicTangent atanh + * inverseSine asin + * inverseTangent atan + * isFinite + * isInteger isInt + * isNaN + * isNegative isNeg + * isPositive isPos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * [maximum] [max] + * [minimum] [min] + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * round + * sine sin + * squareRoot sqrt + * tangent tan + * times mul + * toBinary + * toDecimalPlaces toDP + * toExponential + * toFixed + * toFraction + * toHexadecimal toHex + * toNearest + * toNumber + * toOctal + * toPower pow + * toPrecision + * toSignificantDigits toSD + * toString + * truncated trunc + * valueOf toJSON + */ + + + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s < 0) x.s = 1; + return finalise(x); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of positive Infinity. + * + */ + P.ceil = function () { + return finalise(new this.constructor(this), this.e + 1, 2); + }; + + + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value, + * NaN if the value of either Decimal is NaN. + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this, + xd = x.d, + yd = (y = new x.constructor(y)).d, + xs = x.s, + ys = y.s; + + // Either NaN or ±Infinity? + if (!xd || !yd) { + return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; + } + + // Either zero? + if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; + + // Signs differ? + if (xs !== ys) return xs; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; + + xdL = xd.length; + ydL = yd.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; + }; + + + /* + * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * cos(0) = 1 + * cos(-0) = 1 + * cos(Infinity) = NaN + * cos(-Infinity) = NaN + * cos(NaN) = NaN + * + */ + P.cosine = P.cos = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.d) return new Ctor(NaN); + + // cos(0) = cos(-0) = 1 + if (!x.d[0]) return new Ctor(1); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); + }; + + + /* + * + * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * cbrt(0) = 0 + * cbrt(-0) = -0 + * cbrt(1) = 1 + * cbrt(-1) = -1 + * cbrt(N) = N + * cbrt(-I) = -I + * cbrt(I) = I + * + * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) + * + */ + P.cubeRoot = P.cbrt = function () { + var e, m, n, r, rep, s, sd, t, t3, t3plusx, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + external = false; + + // Initial estimate. + s = x.s * mathpow(x.s * x, 1 / 3); + + // Math.cbrt underflow/overflow? + // Pass x to Math.pow as integer, then adjust the exponent of the result. + if (!s || Math.abs(s) == 1 / 0) { + n = digitsToString(x.d); + e = x.e; + + // Adjust n exponent so it is a multiple of 3 away from x exponent. + if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); + s = mathpow(n, 1 / 3); + + // Rarely, e may be one less than the result exponent value. + e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + r.s = x.s; + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Halley's method. + // TODO? Compare Newton's method. + for (;;) { + t = r; + t3 = t.times(t).times(t); + t3plusx = t3.plus(x); + r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 + // , i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var w, + d = this.d, + n = NaN; + + if (d) { + w = d.length - 1; + n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = d[w]; + if (w) for (; w % 10 == 0; w /= 10) n--; + if (n < 0) n = 0; + } + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; + + + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.dividedToIntegerBy = P.divToInt = function (y) { + var x = this, + Ctor = x.constructor; + return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); + }; + + + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return this.cmp(y) === 0; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the + * direction of negative Infinity. + * + */ + P.floor = function () { + return finalise(new this.constructor(this), this.e + 1, 3); + }; + + + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; + + + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + var k = this.cmp(y); + return k == 1 || k === 0; + }; + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [1, Infinity] + * + * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... + * + * cosh(0) = 1 + * cosh(-0) = 1 + * cosh(Infinity) = Infinity + * cosh(-Infinity) = Infinity + * cosh(NaN) = NaN + * + * x time taken (ms) result + * 1000 9 9.8503555700852349694e+433 + * 10000 25 4.4034091128314607936e+4342 + * 100000 171 1.4033316802130615897e+43429 + * 1000000 3817 1.5166076984010437725e+434294 + * 10000000 abandoned after 2 minute wait + * + * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) + * + */ + P.hyperbolicCosine = P.cosh = function () { + var k, n, pr, rm, len, + x = this, + Ctor = x.constructor, + one = new Ctor(1); + + if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); + if (x.isZero()) return one; + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 + // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) + + // Estimate the optimum number of times to use the argument reduction. + // TODO? Estimation reused from cosine() and may not be optimal here. + if (len < 32) { + k = Math.ceil(len / 3); + n = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + n = '2.3283064365386962890625e-10'; + } + + x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); + + // Reverse argument reduction + var cosh2_x, + i = k, + d8 = new Ctor(8); + for (; i--;) { + cosh2_x = x.times(x); + x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); + } + + return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... + * + * sinh(0) = 0 + * sinh(-0) = -0 + * sinh(Infinity) = Infinity + * sinh(-Infinity) = -Infinity + * sinh(NaN) = NaN + * + * x time taken (ms) + * 10 2 ms + * 100 5 ms + * 1000 14 ms + * 10000 82 ms + * 100000 886 ms 1.4033316802130615897e+43429 + * 200000 2613 ms + * 300000 5407 ms + * 400000 8824 ms + * 500000 13026 ms 8.7080643612718084129e+217146 + * 1000000 48543 ms + * + * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) + * + */ + P.hyperbolicSine = P.sinh = function () { + var k, pr, rm, len, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; + Ctor.rounding = 1; + len = x.d.length; + + if (len < 3) { + x = taylorSeries(Ctor, 2, x, x, true); + } else { + + // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) + // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) + // 3 multiplications and 1 addition + + // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) + // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) + // 4 multiplications and 2 additions + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x, true); + + // Reverse argument reduction + var sinh2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sinh2_x = x.times(x); + x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); + } + } + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * tanh(x) = sinh(x) / cosh(x) + * + * tanh(0) = 0 + * tanh(-0) = -0 + * tanh(Infinity) = 1 + * tanh(-Infinity) = -1 + * tanh(NaN) = NaN + * + */ + P.hyperbolicTangent = P.tanh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(x.s); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 7; + Ctor.rounding = 1; + + return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); + }; + + + /* + * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of + * this Decimal. + * + * Domain: [-1, 1] + * Range: [0, pi] + * + * acos(x) = pi/2 - asin(x) + * + * acos(0) = pi/2 + * acos(-0) = pi/2 + * acos(1) = 0 + * acos(-1) = pi + * acos(1/2) = pi/3 + * acos(-1/2) = 2*pi/3 + * acos(|x| > 1) = NaN + * acos(NaN) = NaN + * + */ + P.inverseCosine = P.acos = function () { + var halfPi, + x = this, + Ctor = x.constructor, + k = x.abs().cmp(1), + pr = Ctor.precision, + rm = Ctor.rounding; + + if (k !== -1) { + return k === 0 + // |x| is 1 + ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) + // |x| > 1 or x is NaN + : new Ctor(NaN); + } + + if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); + + // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.asin(); + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return halfPi.minus(x); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the + * value of this Decimal. + * + * Domain: [1, Infinity] + * Range: [0, Infinity] + * + * acosh(x) = ln(x + sqrt(x^2 - 1)) + * + * acosh(x < 1) = NaN + * acosh(NaN) = NaN + * acosh(Infinity) = Infinity + * acosh(-Infinity) = NaN + * acosh(0) = NaN + * acosh(-0) = NaN + * acosh(1) = 0 + * acosh(-1) = NaN + * + */ + P.inverseHyperbolicCosine = P.acosh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); + if (!x.isFinite()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; + Ctor.rounding = 1; + external = false; + + x = x.times(x).minus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * asinh(x) = ln(x + sqrt(x^2 + 1)) + * + * asinh(NaN) = NaN + * asinh(Infinity) = Infinity + * asinh(-Infinity) = -Infinity + * asinh(0) = 0 + * asinh(-0) = -0 + * + */ + P.inverseHyperbolicSine = P.asinh = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite() || x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; + Ctor.rounding = 1; + external = false; + + x = x.times(x).plus(1).sqrt().plus(x); + + external = true; + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.ln(); + }; + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the + * value of this Decimal. + * + * Domain: [-1, 1] + * Range: [-Infinity, Infinity] + * + * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) + * + * atanh(|x| > 1) = NaN + * atanh(NaN) = NaN + * atanh(Infinity) = NaN + * atanh(-Infinity) = NaN + * atanh(0) = 0 + * atanh(-0) = -0 + * atanh(1) = Infinity + * atanh(-1) = -Infinity + * + */ + P.inverseHyperbolicTangent = P.atanh = function () { + var pr, rm, wpr, xsd, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); + + pr = Ctor.precision; + rm = Ctor.rounding; + xsd = x.sd(); + + if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); + + Ctor.precision = wpr = xsd - x.e; + + x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); + + Ctor.precision = pr + 4; + Ctor.rounding = 1; + + x = x.ln(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(0.5); + }; + + + /* + * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this + * Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) + * + * asin(0) = 0 + * asin(-0) = -0 + * asin(1/2) = pi/6 + * asin(-1/2) = -pi/6 + * asin(1) = pi/2 + * asin(-1) = -pi/2 + * asin(|x| > 1) = NaN + * asin(NaN) = NaN + * + * TODO? Compare performance of Taylor series. + * + */ + P.inverseSine = P.asin = function () { + var halfPi, k, + pr, rm, + x = this, + Ctor = x.constructor; + + if (x.isZero()) return new Ctor(x); + + k = x.abs().cmp(1); + pr = Ctor.precision; + rm = Ctor.rounding; + + if (k !== -1) { + + // |x| is 1 + if (k === 0) { + halfPi = getPi(Ctor, pr + 4, rm).times(0.5); + halfPi.s = x.s; + return halfPi; + } + + // |x| > 1 or x is NaN + return new Ctor(NaN); + } + + // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 + + Ctor.precision = pr + 6; + Ctor.rounding = 1; + + x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return x.times(2); + }; + + + /* + * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value + * of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi/2, pi/2] + * + * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + * + * atan(0) = 0 + * atan(-0) = -0 + * atan(1) = pi/4 + * atan(-1) = -pi/4 + * atan(Infinity) = pi/2 + * atan(-Infinity) = -pi/2 + * atan(NaN) = NaN + * + */ + P.inverseTangent = P.atan = function () { + var i, j, k, n, px, t, r, wpr, x2, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + rm = Ctor.rounding; + + if (!x.isFinite()) { + if (!x.s) return new Ctor(NaN); + if (pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.5); + r.s = x.s; + return r; + } + } else if (x.isZero()) { + return new Ctor(x); + } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { + r = getPi(Ctor, pr + 4, rm).times(0.25); + r.s = x.s; + return r; + } + + Ctor.precision = wpr = pr + 10; + Ctor.rounding = 1; + + // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); + + // Argument reduction + // Ensure |x| < 0.42 + // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) + + k = Math.min(28, wpr / LOG_BASE + 2 | 0); + + for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); + + external = false; + + j = Math.ceil(wpr / LOG_BASE); + n = 1; + x2 = x.times(x); + r = new Ctor(x); + px = x; + + // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... + for (; i !== -1;) { + px = px.times(x2); + t = r.minus(px.div(n += 2)); + + px = px.times(x2); + r = t.plus(px.div(n += 2)); + + if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); + } + + if (k) r = r.times(2 << (k - 1)); + + external = true; + + return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); + }; + + + /* + * Return true if the value of this Decimal is a finite number, otherwise return false. + * + */ + P.isFinite = function () { + return !!this.d; + }; + + + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isInt = function () { + return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; + }; + + + /* + * Return true if the value of this Decimal is NaN, otherwise return false. + * + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.isPos = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this Decimal is 0 or -0, otherwise return false. + * + */ + P.isZero = function () { + return !!this.d && this.d[0] === 0; + }; + + + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; + + + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + + + /* + * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * If no base is specified, return log[10](arg). + * + * log[base](arg) = ln(arg) / ln(base) + * + * The result will always be correctly rounded if the base of the log is 10, and 'almost always' + * otherwise: + * + * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen + * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error + * between the result and the correctly rounded result will be one ulp (unit in the last place). + * + * log[-b](a) = NaN + * log[0](a) = NaN + * log[1](a) = NaN + * log[NaN](a) = NaN + * log[Infinity](a) = NaN + * log[b](0) = -Infinity + * log[b](-0) = -Infinity + * log[b](-a) = NaN + * log[b](1) = 0 + * log[b](Infinity) = Infinity + * log[b](NaN) = NaN + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var isBase10, d, denominator, k, inf, num, sd, r, + arg = this, + Ctor = arg.constructor, + pr = Ctor.precision, + rm = Ctor.rounding, + guard = 5; + + // Default base is 10. + if (base == null) { + base = new Ctor(10); + isBase10 = true; + } else { + base = new Ctor(base); + d = base.d; + + // Return NaN if base is negative, or non-finite, or is 0 or 1. + if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); + + isBase10 = base.eq(10); + } + + d = arg.d; + + // Is arg negative, non-finite, 0 or 1? + if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { + return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); + } + + // The result will have a non-terminating decimal expansion if base is 10 and arg is not an + // integer power of 10. + if (isBase10) { + if (d.length > 1) { + inf = true; + } else { + for (k = d[0]; k % 10 === 0;) k /= 10; + inf = k !== 1; + } + } + + external = false; + sd = pr + guard; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + + // The result will have 5 rounding digits. + r = divide(num, denominator, sd, 1); + + // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, + // calculate 10 further digits. + // + // If the result is known to have an infinite decimal expansion, repeat this until it is clear + // that the result is above or below the boundary. Otherwise, if after calculating the 10 + // further digits, the last 14 are nines, round up and assume the result is exact. + // Also assume the result is exact if the last 14 are zero. + // + // Example of a result that will be incorrectly rounded: + // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... + // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it + // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so + // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal + // place is still 2.6. + if (checkRoundingDigits(r.d, k = pr, rm)) { + + do { + sd += 10; + num = naturalLogarithm(arg, sd); + denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); + r = divide(num, denominator, sd, 1); + + if (!inf) { + + // Check for 14 nines from the 2nd rounding digit, as the first may be 4. + if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + + break; + } + } while (checkRoundingDigits(r.d, k += 10, rm)); + } + + external = true; + + return finalise(r, pr, rm); + }; + + + /* + * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.max = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'lt'); + }; + */ + + + /* + * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. + * + * arguments {number|string|Decimal} + * + P.min = function () { + Array.prototype.push.call(arguments, this); + return maxOrMin(this.constructor, arguments, 'gt'); + }; + */ + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.minus = P.sub = function (y) { + var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return y negated if x is finite and y is ±Infinity. + else if (x.d) y.s = -y.s; + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with different signs. + // Return NaN if both are ±Infinity with the same sign. + else y = new Ctor(y.d || x.s !== y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.plus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return y negated if x is zero and y is non-zero. + if (yd[0]) y.s = -y.s; + + // Return x if y is zero and x is non-zero. + else if (xd[0]) y = new Ctor(x); + + // Return zero if both are zero. + // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. + else return new Ctor(rm === 3 ? -0 : 0); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + e = mathfloor(y.e / LOG_BASE); + xe = mathfloor(x.e / LOG_BASE); + + xd = xd.slice(); + k = xe - e; + + // If base 1e7 exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of + // zeros needing to be prepended, but this can be avoided while still ensuring correct + // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to `xd` if shorter. + // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * The result depends on the modulo mode. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. + if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); + + // Return x if y is ±Infinity or x is ±0. + if (!y.d || x.d && !x.d[0]) { + return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); + } + + // Prevent rounding of intermediate calculations. + external = false; + + if (Ctor.modulo == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // result = x - q * y where 0 <= result < abs(y) + q = divide(x, y.abs(), 0, 3, 1); + q.s *= y.s; + } else { + q = divide(x, y, 0, Ctor.modulo, 1); + } + + q = q.times(y); + + external = true; + + return x.minus(q); + }; + + + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.naturalExponential = P.exp = function () { + return naturalExponential(this); + }; + + + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + */ + P.naturalLogarithm = P.ln = function () { + return naturalLogarithm(this); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s; + return finalise(x); + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + */ + P.plus = P.add = function (y) { + var carry, d, e, i, k, len, pr, rm, xd, yd, + x = this, + Ctor = x.constructor; + + y = new Ctor(y); + + // If either is not finite... + if (!x.d || !y.d) { + + // Return NaN if either is NaN. + if (!x.s || !y.s) y = new Ctor(NaN); + + // Return x if y is finite and x is ±Infinity. + // Return x if both are ±Infinity with the same sign. + // Return NaN if both are ±Infinity with different signs. + // Return y if x is finite and y is ±Infinity. + else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); + + return y; + } + + // If signs differ... + if (x.s != y.s) { + y.s = -y.s; + return x.minus(y); + } + + xd = x.d; + yd = y.d; + pr = Ctor.precision; + rm = Ctor.rounding; + + // If either is zero... + if (!xd[0] || !yd[0]) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!yd[0]) y = new Ctor(x); + + return external ? finalise(y, pr, rm) : y; + } + + // x and y are finite, non-zero numbers with the same sign. + + // Calculate base 1e7 exponents. + k = mathfloor(x.e / LOG_BASE); + e = mathfloor(y.e / LOG_BASE); + + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = getBase10Exponent(xd, e); + + return external ? finalise(y, pr, rm) : y; + }; + + + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var k, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + if (x.d) { + k = getPrecision(x.d); + if (z && x.e + 1 > k) k = x.e + 1; + } else { + k = NaN; + } + + return k; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.round = function () { + var x = this, + Ctor = x.constructor; + + return finalise(new Ctor(x), x.e + 1, Ctor.rounding); + }; + + + /* + * Return a new Decimal whose value is the sine of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-1, 1] + * + * sin(x) = x - x^3/3! + x^5/5! - ... + * + * sin(0) = 0 + * sin(-0) = -0 + * sin(Infinity) = NaN + * sin(-Infinity) = NaN + * sin(NaN) = NaN + * + */ + P.sine = P.sin = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; + Ctor.rounding = 1; + + x = sine(Ctor, toLessThanHalfPi(Ctor, x)); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); + }; + + + /* + * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + */ + P.squareRoot = P.sqrt = function () { + var m, n, sd, r, rep, t, + x = this, + d = x.d, + e = x.e, + s = x.s, + Ctor = x.constructor; + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !d || !d[0]) { + return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); + } + + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(d); + + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + sd = (e = Ctor.precision) + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); + + // TODO? Replace with for-loop and checkRoundingDigits. + if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { + n = n.slice(sd - 3, sd + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + if (!rep) { + finalise(t, e + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + sd += 4; + rep = 1; + } else { + + // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. + // If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + finalise(r, e + 1, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + + external = true; + + return finalise(r, e, Ctor.rounding, m); + }; + + + /* + * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. + * + * Domain: [-Infinity, Infinity] + * Range: [-Infinity, Infinity] + * + * tan(0) = 0 + * tan(-0) = -0 + * tan(Infinity) = NaN + * tan(-Infinity) = NaN + * tan(NaN) = NaN + * + */ + P.tangent = P.tan = function () { + var pr, rm, + x = this, + Ctor = x.constructor; + + if (!x.isFinite()) return new Ctor(NaN); + if (x.isZero()) return new Ctor(x); + + pr = Ctor.precision; + rm = Ctor.rounding; + Ctor.precision = pr + 10; + Ctor.rounding = 1; + + x = x.sin(); + x.s = 1; + x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); + + Ctor.precision = pr; + Ctor.rounding = rm; + + return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + y.s *= x.s; + + // If either is NaN, ±Infinity or ±0... + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd + + // Return NaN if either is NaN. + // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. + ? NaN + + // Return ±Infinity if either is ±Infinity. + // Return ±0 if either is ±0. + : !xd || !yd ? y.s / 0 : y.s * 0); + } + + e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = getBase10Exponent(r, e); + + return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; + }; + + + /* + * Return a string representing the value of this Decimal in base 2, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toBinary = function (sd, rm) { + return toStringBinary(this, 2, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.toDP = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return finalise(x, dp + x.e + 1, rm); + }; + + + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), dp + 1, rm); + str = finiteToString(x, true, dp + 1); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = finiteToString(x); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = finalise(new Ctor(x), dp + x.e + 1, rm); + str = finiteToString(y, false, dp + y.e + 1); + } + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return an array representing the value of this Decimal as a simple fraction with an integer + * numerator and an integer denominator. + * + * The denominator will be a positive non-zero value less than or equal to the specified maximum + * denominator. If a maximum denominator is not specified, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. + * + */ + P.toFraction = function (maxD) { + var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, + x = this, + xd = x.d, + Ctor = x.constructor; + + if (!xd) return new Ctor(x); + + n1 = d0 = new Ctor(1); + d1 = n0 = new Ctor(0); + + d = new Ctor(d1); + e = d.e = getPrecision(xd) - x.e - 1; + k = e % LOG_BASE; + d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); + + if (maxD == null) { + + // d is 10**e, the minimum max-denominator needed. + maxD = e > 0 ? d : n1; + } else { + n = new Ctor(maxD); + if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); + maxD = n.gt(d) ? (e > 0 ? d : n1) : n; + } + + external = false; + n = new Ctor(digitsToString(xd)); + pr = Ctor.precision; + Ctor.precision = e = xd.length * LOG_BASE * 2; + + for (;;) { + q = divide(n, d, 0, 1, 1); + d2 = d0.plus(q.times(d1)); + if (d2.cmp(maxD) == 1) break; + d0 = d1; + d1 = d2; + d2 = n1; + n1 = n0.plus(q.times(d2)); + n0 = d2; + d2 = d; + d = n.minus(q.times(d2)); + n = d2; + } + + d2 = divide(maxD.minus(d0), d1, 0, 1, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + + // Determine which fraction is closer to x, n0/d0 or n1/d1? + r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 + ? [n1, d1] : [n0, d0]; + + Ctor.precision = pr; + external = true; + + return r; + }; + + + /* + * Return a string representing the value of this Decimal in base 16, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toHexadecimal = P.toHex = function (sd, rm) { + return toStringBinary(this, 16, sd, rm); + }; + + + /* + * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding + * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. + * + * The return value will always have the same sign as this Decimal, unless either this Decimal + * or `y` is NaN, in which case the return value will be also be NaN. + * + * The return value is not affected by the value of `precision`. + * + * y {number|string|Decimal} The magnitude to round to a multiple of. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toNearest() rounding mode not an integer: {rm}' + * 'toNearest() rounding mode out of range: {rm}' + * + */ + P.toNearest = function (y, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + + if (y == null) { + + // If x is not finite, return x. + if (!x.d) return x; + + y = new Ctor(1); + rm = Ctor.rounding; + } else { + y = new Ctor(y); + if (rm === void 0) { + rm = Ctor.rounding; + } else { + checkInt32(rm, 0, 8); + } + + // If x is not finite, return x if y is not NaN, else NaN. + if (!x.d) return y.s ? x : y; + + // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. + if (!y.d) { + if (y.s) y.s = x.s; + return y; + } + } + + // If y is not zero, calculate the nearest multiple of y to x. + if (y.d[0]) { + external = false; + x = divide(x, y, 0, rm, 1).times(y); + external = true; + finalise(x); + + // If y is zero, return zero with the sign of x. + } else { + y.s = x.s; + x = y; + } + + return x; + }; + + + /* + * Return the value of this Decimal converted to a number primitive. + * Zero keeps its sign. + * + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this Decimal in base 8, round to `sd` significant + * digits using rounding mode `rm`. + * + * If the optional `sd` argument is present then return binary exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toOctal = function (sd, rm) { + return toStringBinary(this, 8, sd, rm); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded + * to `precision` significant digits using rounding mode `rounding`. + * + * ECMAScript compliant. + * + * pow(x, NaN) = NaN + * pow(x, ±0) = 1 + + * pow(NaN, non-zero) = NaN + * pow(abs(x) > 1, +Infinity) = +Infinity + * pow(abs(x) > 1, -Infinity) = +0 + * pow(abs(x) == 1, ±Infinity) = NaN + * pow(abs(x) < 1, +Infinity) = +0 + * pow(abs(x) < 1, -Infinity) = +Infinity + * pow(+Infinity, y > 0) = +Infinity + * pow(+Infinity, y < 0) = +0 + * pow(-Infinity, odd integer > 0) = -Infinity + * pow(-Infinity, even integer > 0) = +Infinity + * pow(-Infinity, odd integer < 0) = -0 + * pow(-Infinity, even integer < 0) = +0 + * pow(+0, y > 0) = +0 + * pow(+0, y < 0) = +Infinity + * pow(-0, odd integer > 0) = -0 + * pow(-0, even integer > 0) = +0 + * pow(-0, odd integer < 0) = -Infinity + * pow(-0, even integer < 0) = +Infinity + * pow(finite x < 0, finite non-integer) = NaN + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the + * probability of an incorrectly rounded result + * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 + * i.e. 1 in 250,000,000,000,000 + * + * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, rm, s, + x = this, + Ctor = x.constructor, + yn = +(y = new Ctor(y)); + + // Either ±Infinity, NaN or ±0? + if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); + + x = new Ctor(x); + + if (x.eq(1)) return x; + + pr = Ctor.precision; + rm = Ctor.rounding; + + if (y.eq(1)) return finalise(x, pr, rm); + + // y exponent + e = mathfloor(y.e / LOG_BASE); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = intPow(Ctor, x, k, pr); + return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); + } + + s = x.s; + + // if x is negative + if (s < 0) { + + // if y is not an integer + if (e < y.d.length - 1) return new Ctor(NaN); + + // Result is positive if x is negative and the last digit of integer y is even. + if ((y.d[e] & 1) == 0) s = 1; + + // if x.eq(-1) + if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { + x.s = s; + return x; + } + } + + // Estimate result exponent. + // x^y = 10^e, where e = y * log10(x) + // log10(x) = log10(x_significand) + x_exponent + // log10(x_significand) = ln(x_significand) / ln(10) + k = mathpow(+x, yn); + e = k == 0 || !isFinite(k) + ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) + : new Ctor(k + '').e; + + // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. + + // Overflow/underflow? + if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); + + external = false; + Ctor.rounding = x.s = 1; + + // Estimate the extra guard digits needed to ensure five correct rounding digits from + // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): + // new Decimal(2.32456).pow('2087987436534566.46411') + // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 + k = Math.min(12, (e + '').length); + + // r = x^y = exp(y*ln(x)) + r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); + + // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) + if (r.d) { + + // Truncate to the required precision plus five rounding digits. + r = finalise(r, pr + 5, 1); + + // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate + // the result. + if (checkRoundingDigits(r.d, pr, rm)) { + e = pr + 10; + + // Truncate to the increased precision plus five rounding digits. + r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); + + // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). + if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { + r = finalise(r, pr + 1, 0); + } + } + } + + r.s = s; + external = true; + Ctor.rounding = rm; + + return finalise(r, pr, rm); + }; + + + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = finalise(new Ctor(x), sd, rm); + str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); + } + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toSD() digits out of range: {sd}' + * 'toSD() digits not an integer: {sd}' + * 'toSD() rounding mode not an integer: {rm}' + * 'toSD() rounding mode out of range: {rm}' + * + */ + P.toSignificantDigits = P.toSD = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return finalise(new Ctor(x), sd, rm); + }; + + + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. + * + */ + P.truncated = P.trunc = function () { + return finalise(new this.constructor(this), this.e + 1, 1); + }; + + + /* + * Return a string representing the value of this Decimal. + * Unlike `toString`, negative zero will include the minus sign. + * + */ + P.valueOf = P.toJSON = function () { + var x = this, + Ctor = x.constructor, + str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); + + return x.isNeg() ? '-' + str : str; + }; + + + /* + // Add aliases to match BigDecimal method names. + // P.add = P.plus; + P.subtract = P.minus; + P.multiply = P.times; + P.divide = P.div; + P.remainder = P.mod; + P.compareTo = P.cmp; + P.negate = P.neg; + */ + + + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + + /* + * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, + * finiteToString, naturalExponential, naturalLogarithm + * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, + * P.toPrecision, P.toSignificantDigits, toStringBinary, random + * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm + * convertBase toStringBinary, parseOther + * cos P.cos + * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, + * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, + * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, + * taylorSeries, atan2, parseOther + * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, + * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, + * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, + * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, + * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, + * P.truncated, divide, getLn10, getPi, naturalExponential, + * naturalLogarithm, ceil, floor, round, trunc + * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, + * toStringBinary + * getBase10Exponent P.minus, P.plus, P.times, parseOther + * getLn10 P.logarithm, naturalLogarithm + * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 + * getPrecision P.precision, P.toFraction + * getZeroString digitsToString, finiteToString + * intPow P.toPower, parseOther + * isOdd toLessThanHalfPi + * maxOrMin max, min + * naturalExponential P.naturalExponential, P.toPower + * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, + * P.toPower, naturalExponential + * nonFiniteToString finiteToString, toStringBinary + * parseDecimal Decimal + * parseOther Decimal + * sin P.sin + * taylorSeries P.cosh, P.sinh, cos, sin + * toLessThanHalfPi P.cos, P.sin + * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal + * truncate intPow + * + * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, + * naturalLogarithm, config, parseOther, random, Decimal + */ + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; + } + + + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } + } + + + /* + * Check 5 rounding digits if `repeating` is null, 4 otherwise. + * `repeating == null` if caller is `log` or `pow`, + * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. + */ + function checkRoundingDigits(d, i, rm, repeating) { + var di, k, r, rd; + + // Get the length of the first word of the array d. + for (k = d[0]; k >= 10; k /= 10) --i; + + // Is the rounding digit in the first word of d? + if (--i < 0) { + i += LOG_BASE; + di = 0; + } else { + di = Math.ceil((i + 1) / LOG_BASE); + i %= LOG_BASE; + } + + // i is the index (0 - 6) of the rounding digit. + // E.g. if within the word 3487563 the first rounding digit is 5, + // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 + k = mathpow(10, LOG_BASE - i); + rd = d[di] % k | 0; + + if (repeating == null) { + if (i < 3) { + if (i == 0) rd = rd / 100 | 0; + else if (i == 1) rd = rd / 10 | 0; + r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; + } else { + r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && + (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || + (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; + } + } else { + if (i < 4) { + if (i == 0) rd = rd / 1000 | 0; + else if (i == 1) rd = rd / 100 | 0; + else if (i == 2) rd = rd / 10 | 0; + r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; + } else { + r = ((repeating || rm < 4) && rd + 1 == k || + (!repeating && rm > 3) && rd + 1 == k / 2) && + (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; + } + } + + return r; + } + + + // Convert string of `baseIn` to an array of numbers of `baseOut`. + // Eg. convertBase('255', 10, 16) returns [15, 15]. + // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + function convertBase(str, baseIn, baseOut) { + var j, + arr = [0], + arrL, + i = 0, + strL = str.length; + + for (; i < strL;) { + for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; + arr[0] += NUMERALS.indexOf(str.charAt(i++)); + for (j = 0; j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] === void 0) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + + /* + * cos(x) = 1 - x^2/2! + x^4/4! - ... + * |x| < pi/2 + * + */ + function cosine(Ctor, x) { + var k, y, + len = x.d.length; + + // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 + // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 + + // Estimate the optimum number of times to use the argument reduction. + if (len < 32) { + k = Math.ceil(len / 3); + y = (1 / tinyPow(4, k)).toString(); + } else { + k = 16; + y = '2.3283064365386962890625e-10'; + } + + Ctor.precision += k; + + x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); + + // Reverse argument reduction + for (var i = k; i--;) { + var cos2x = x.times(x); + x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); + } + + Ctor.precision -= k; + + return x; + } + + + /* + * Perform division in the specified base. + */ + var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k, base) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % base | 0; + carry = temp / base | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, rm, dp, base) { + var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, + yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either NaN, Infinity or 0? + if (!xd || !xd[0] || !yd || !yd[0]) { + + return new Ctor(// Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : + + // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. + xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); + } + + if (base) { + logBase = 1; + e = x.e - y.e; + } else { + base = BASE; + logBase = LOG_BASE; + e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); + } + + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + // The digit array of a Decimal from toStringBinary may have trailing zeros. + for (i = 0; yd[i] == (xd[i] || 0); i++); + + if (yd[i] > (xd[i] || 0)) e--; + + if (pr == null) { + sd = pr = Ctor.precision; + rm = Ctor.rounding; + } else if (dp) { + sd = pr + (x.e - y.e) + 1; + } else { + sd = pr; + } + + if (sd < 0) { + qd.push(1); + more = true; + } else { + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / logBase + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * base + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + more = k || i < xL; + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= base/2 + k = base / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k, base); + xd = multiplyInteger(xd, k, base); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= base / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= base) k = base - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL, base); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL, base); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + + more = rem[0] !== void 0; + } + + // Leading zero? + if (!qd[0]) qd.shift(); + } + + // logBase is 1 when divide is being used for base conversion. + if (logBase == 1) { + q.e = e; + inexact = more; + } else { + + // To calculate q.e, first get the number of digits of qd[0]. + for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; + q.e = i + e * logBase - 1; + + finalise(q, dp ? pr + q.e + 1 : pr, rm, more); + } + + return q; + }; + })(); + + + /* + * Round `x` to `sd` significant digits using rounding mode `rm`. + * Check for over/under-flow. + */ + function finalise(x, sd, rm, isTruncated) { + var digits, i, j, k, rd, roundUp, w, xd, xdi, + Ctor = x.constructor; + + // Don't round if sd is null or undefined. + out: if (sd != null) { + xd = x.d; + + // Infinity/NaN. + if (!xd) return x; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd containing rd, a base 1e7 number. + // xdi: the index of w within xd. + // digits: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; + i = sd - digits; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + + // Get the rounding digit at index j of w. + rd = w / mathpow(10, digits - j - 1) % 10 | 0; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) { + if (isTruncated) { + + // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. + for (; k++ <= xdi;) xd.push(0); + w = rd = 0; + digits = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + w = k = xd[xdi]; + + // Get the number of digits of w. + for (digits = 1; k >= 10; k /= 10) digits++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - digits. + j = i - LOG_BASE + digits; + + // Get the rounding digit at index j of w. + rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; + } + } + + // Are there any non-zero digits after the rounding digit? + isTruncated = isTruncated || sd < 0 || + xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); + + // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right + // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression + // will give 714. + + roundUp = rm < 4 + ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xd[0]) { + xd.length = 0; + if (roundUp) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = -sd || 0; + } else { + + // Zero. + xd[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; + } + + if (roundUp) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + + // i will be the length of xd[0] before k is added. + for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; + j = xd[0] += k; + for (k = 1; j >= 10; j /= 10) k++; + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xd[0] == BASE) xd[0] = 1; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + } + + if (external) { + + // Overflow? + if (x.e > Ctor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < Ctor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // Ctor.underflow = true; + } // else Ctor.underflow = false; + } + + return x; + } + + + function finiteToString(x, isExp, sd) { + if (!x.isFinite()) return nonFiniteToString(x); + var k, + e = x.e, + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (x.e < 0 ? 'e' : 'e+') + x.e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return str; + } + + + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(digits, e) { + var w = digits[0]; + + // Add the number of digits of the first word of the digits array. + for ( e *= LOG_BASE; w >= 10; w /= 10) e++; + return e; + } + + + function getLn10(Ctor, sd, pr) { + if (sd > LN10_PRECISION) { + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(precisionLimitExceeded); + } + return finalise(new Ctor(LN10), sd, 1, true); + } + + + function getPi(Ctor, sd, rm) { + if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); + return finalise(new Ctor(PI), sd, rm, true); + } + + + function getPrecision(digits) { + var w = digits.length - 1, + len = w * LOG_BASE + 1; + + w = digits[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) len--; + + // Add the number of digits of the first word. + for (w = digits[0]; w >= 10; w /= 10) len++; + } + + return len; + } + + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; + } + + + /* + * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an + * integer of type number. + * + * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. + * + */ + function intPow(Ctor, x, n, pr) { + var isTruncated, + r = new Ctor(1), + + // Max n of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + k = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (n % 2) { + r = r.times(x); + if (truncate(r.d, k)) isTruncated = true; + } + + n = mathfloor(n / 2); + if (n === 0) { + + // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. + n = r.d.length - 1; + if (isTruncated && r.d[n] === 0) ++r.d[n]; + break; + } + + x = x.times(x); + truncate(x.d, k); + } + + external = true; + + return r; + } + + + function isOdd(n) { + return n.d[n.d.length - 1] & 1; + } + + + /* + * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. + */ + function maxOrMin(Ctor, args, ltgt) { + var y, + x = new Ctor(args[0]), + i = 0; + + for (; ++i < args.length;) { + y = new Ctor(args[i]); + if (!y.s) { + x = y; + break; + } else if (x[ltgt](y)) { + x = y; + } + } + + return x; + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant + * digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 + * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(Infinity) = Infinity + * exp(-Infinity) = 0 + * exp(NaN) = NaN + * exp(±0) = 1 + * + * exp(x) is non-terminating for any finite, non-zero x. + * + * The result will always be correctly rounded. + * + */ + function naturalExponential(x, sd) { + var denominator, guard, j, pow, sum, t, wpr, + rep = 0, + i = 0, + k = 0, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // 0/NaN/Infinity? + if (!x.d || !x.d[0] || x.e > 17) { + + return new Ctor(x.d + ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 + : x.s ? x.s < 0 ? 0 : x : 0 / 0); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + // while abs(x) >= 0.1 + while (x.e > -2) { + + // x = x / 2^5 + x = x.times(t); + k += 5; + } + + // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision + // necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(1); + Ctor.precision = wpr; + + for (;;) { + pow = finalise(pow.times(x), wpr, 1); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + j = k; + while (j--) sum = finalise(sum.times(sum), wpr, 1); + + // Check to see if the first 4 rounding digits are [49]999. + // If so, repeat the summation with a higher precision, otherwise + // e.g. with precision: 18, rounding: 1 + // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + + if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += 10; + denominator = pow = t = new Ctor(1); + i = 0; + rep++; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + } + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant + * digits. + * + * ln(-n) = NaN + * ln(0) = -Infinity + * ln(-0) = -Infinity + * ln(1) = 0 + * ln(Infinity) = Infinity + * ln(-Infinity) = NaN + * ln(NaN) = NaN + * + * ln(n) (n != 1) is non-terminating. + * + */ + function naturalLogarithm(y, sd) { + var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + rm = Ctor.rounding, + pr = Ctor.precision; + + // Is x negative or Infinity, NaN, 0 or 1? + if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { + return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); + } + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + Ctor.precision = wpr += guard; + c = digitsToString(xd); + c0 = c.charAt(0); + + if (Math.abs(e = x.e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = x.e; + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + Ctor.precision = pr; + + return sd == null ? finalise(x, pr, rm, external = true) : x; + } + + // x1 is x reduced to a value near 1. + x1 = x; + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = 3; + + for (;;) { + numerator = finalise(numerator.times(x2), wpr, 1); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. Check that e is not 0 because, besides preventing an + // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr, 1); + + // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has + // been repeated previously) and the first 4 rounding digits 9999? + // If so, restart the summation with a higher precision, otherwise + // e.g. with precision: 12, rounding: 1 + // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. + // `wpr - guard` is the index of first rounding digit. + if (sd == null) { + if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { + Ctor.precision = wpr += guard; + t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); + x2 = finalise(x.times(x), wpr, 1); + denominator = rep = 1; + } else { + return finalise(sum, Ctor.precision = pr, rm, external = true); + } + } else { + Ctor.precision = pr; + return sum; + } + } + + sum = t; + denominator += 2; + } + } + + + // ±Infinity, NaN. + function nonFiniteToString(x) { + // Unsigned. + return String(x.s * x.s / 0); + } + + + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48; --len); + str = str.slice(i, len); + + if (str) { + len -= i; + x.e = e = e - i - 1; + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external) { + + // Overflow? + if (x.e > x.constructor.maxE) { + + // Infinity. + x.d = null; + x.e = NaN; + + // Underflow? + } else if (x.e < x.constructor.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + // x.constructor.underflow = true; + } // else x.constructor.underflow = false; + } + } else { + + // Zero. + x.e = 0; + x.d = [0]; + } + + return x; + } + + + /* + * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. + */ + function parseOther(x, str) { + var base, Ctor, divisor, i, isFloat, len, p, xd, xe; + + if (str === 'Infinity' || str === 'NaN') { + if (!+str) x.s = NaN; + x.e = NaN; + x.d = null; + return x; + } + + if (isHex.test(str)) { + base = 16; + str = str.toLowerCase(); + } else if (isBinary.test(str)) { + base = 2; + } else if (isOctal.test(str)) { + base = 8; + } else { + throw Error(invalidArgument + str); + } + + // Is there a binary exponent part? + i = str.search(/p/i); + + if (i > 0) { + p = +str.slice(i + 1); + str = str.substring(2, i); + } else { + str = str.slice(2); + } + + // Convert `str` as an integer then divide the result by `base` raised to a power such that the + // fraction part will be restored. + i = str.indexOf('.'); + isFloat = i >= 0; + Ctor = x.constructor; + + if (isFloat) { + str = str.replace('.', ''); + len = str.length; + i = len - i; + + // log[10](16) = 1.2041... , log[10](88) = 1.9444.... + divisor = intPow(Ctor, new Ctor(base), i, i * 2); + } + + xd = convertBase(str, base, BASE); + xe = xd.length - 1; + + // Remove trailing zeros. + for (i = xe; xd[i] === 0; --i) xd.pop(); + if (i < 0) return new Ctor(x.s * 0); + x.e = getBase10Exponent(xd, xe); + x.d = xd; + external = false; + + // At what precision to perform the division to ensure exact conversion? + // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) + // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 + // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. + // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount + // Therefore using 4 * the number of digits of str will always be enough. + if (isFloat) x = divide(x, divisor, len * 4); + + // Multiply by the binary exponent part if present. + if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); + external = true; + + return x; + } + + + /* + * sin(x) = x - x^3/3! + x^5/5! - ... + * |x| < pi/2 + * + */ + function sine(Ctor, x) { + var k, + len = x.d.length; + + if (len < 3) return taylorSeries(Ctor, 2, x, x); + + // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) + // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) + // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) + + // Estimate the optimum number of times to use the argument reduction. + k = 1.4 * Math.sqrt(len); + k = k > 16 ? 16 : k | 0; + + x = x.times(1 / tinyPow(5, k)); + x = taylorSeries(Ctor, 2, x, x); + + // Reverse argument reduction + var sin2_x, + d5 = new Ctor(5), + d16 = new Ctor(16), + d20 = new Ctor(20); + for (; k--;) { + sin2_x = x.times(x); + x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); + } + + return x; + } + + + // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. + function taylorSeries(Ctor, n, x, y, isHyperbolic) { + var j, t, u, x2, + i = 1, + pr = Ctor.precision, + k = Math.ceil(pr / LOG_BASE); + + external = false; + x2 = x.times(x); + u = new Ctor(y); + + for (;;) { + t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); + u = isHyperbolic ? y.plus(t) : y.minus(t); + y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); + t = u.plus(y); + + if (t.d[k] !== void 0) { + for (j = k; t.d[j] === u.d[j] && j--;); + if (j == -1) break; + } + + j = u; + u = y; + y = t; + t = j; + i++; + } + + external = true; + t.d.length = k + 1; + + return t; + } + + + // Exponent e must be positive and non-zero. + function tinyPow(b, e) { + var n = b; + while (--e) n *= b; + return n; + } + + + // Return the absolute value of `x` reduced to less than or equal to half pi. + function toLessThanHalfPi(Ctor, x) { + var t, + isNeg = x.s < 0, + pi = getPi(Ctor, Ctor.precision, 1), + halfPi = pi.times(0.5); + + x = x.abs(); + + if (x.lte(halfPi)) { + quadrant = isNeg ? 4 : 1; + return x; + } + + t = x.divToInt(pi); + + if (t.isZero()) { + quadrant = isNeg ? 3 : 2; + } else { + x = x.minus(t.times(pi)); + + // 0 <= x < pi + if (x.lte(halfPi)) { + quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); + return x; + } + + quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); + } + + return x.minus(pi).abs(); + } + + + /* + * Return the value of Decimal `x` as a string in base `baseOut`. + * + * If the optional `sd` argument is present include a binary exponent suffix. + */ + function toStringBinary(x, baseOut, sd, rm) { + var base, e, i, k, len, roundUp, str, xd, y, + Ctor = x.constructor, + isExp = sd !== void 0; + + if (isExp) { + checkInt32(sd, 1, MAX_DIGITS); + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } else { + sd = Ctor.precision; + rm = Ctor.rounding; + } + + if (!x.isFinite()) { + str = nonFiniteToString(x); + } else { + str = finiteToString(x); + i = str.indexOf('.'); + + // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: + // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) + // minBinaryExponent = floor(decimalExponent * log[2](10)) + // log[2](10) = 3.321928094887362347870319429489390175864 + + if (isExp) { + base = 2; + if (baseOut == 16) { + sd = sd * 4 - 3; + } else if (baseOut == 8) { + sd = sd * 3 - 2; + } + } else { + base = baseOut; + } + + // Convert the number as an integer then divide the result by its base raised to a power such + // that the fraction part will be restored. + + // Non-integer. + if (i >= 0) { + str = str.replace('.', ''); + y = new Ctor(1); + y.e = str.length - i; + y.d = convertBase(finiteToString(y), 10, base); + y.e = y.d.length; + } + + xd = convertBase(str, 10, base); + e = len = xd.length; + + // Remove trailing zeros. + for (; xd[--len] == 0;) xd.pop(); + + if (!xd[0]) { + str = isExp ? '0p+0' : '0'; + } else { + if (i < 0) { + e--; + } else { + x = new Ctor(x); + x.d = xd; + x.e = e; + x = divide(x, y, sd, rm, 0, base); + xd = x.d; + e = x.e; + roundUp = inexact; + } + + // The rounding digit, i.e. the digit after the digit that may be rounded up. + i = xd[sd]; + k = base / 2; + roundUp = roundUp || xd[sd + 1] !== void 0; + + roundUp = rm < 4 + ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) + : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || + rm === (x.s < 0 ? 8 : 7)); + + xd.length = sd; + + if (roundUp) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (; ++xd[--sd] > base - 1;) { + xd[sd] = 0; + if (!sd) { + ++e; + xd.unshift(1); + } + } + } + + // Determine trailing zeros. + for (len = xd.length; !xd[len - 1]; --len); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); + + // Add binary exponent suffix? + if (isExp) { + if (len > 1) { + if (baseOut == 16 || baseOut == 8) { + i = baseOut == 16 ? 4 : 3; + for (--len; len % i; len++) str += '0'; + xd = convertBase(str, base, baseOut); + for (len = xd.length; !xd[len - 1]; --len); + + // xd[0] will always be be 1 + for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); + } else { + str = str.charAt(0) + '.' + str.slice(1); + } + } + + str = str + (e < 0 ? 'p' : 'p+') + e; + } else if (e < 0) { + for (; ++e;) str = '0' + str; + str = '0.' + str; + } else { + if (++e > len) for (e -= len; e-- ;) str += '0'; + else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); + } + } + + str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; + } + + return x.s < 0 ? '-' + str : str; + } + + + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } + + + // Decimal methods + + + /* + * abs + * acos + * acosh + * add + * asin + * asinh + * atan + * atanh + * atan2 + * cbrt + * ceil + * clone + * config + * cos + * cosh + * div + * exp + * floor + * hypot + * ln + * log + * log2 + * log10 + * max + * min + * mod + * mul + * pow + * random + * round + * set + * sign + * sin + * sinh + * sqrt + * sub + * tan + * tanh + * trunc + */ + + + /* + * Return a new Decimal whose value is the absolute value of `x`. + * + * x {number|string|Decimal} + * + */ + function abs(x) { + return new this(x).abs(); + } + + + /* + * Return a new Decimal whose value is the arccosine in radians of `x`. + * + * x {number|string|Decimal} + * + */ + function acos(x) { + return new this(x).acos(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function acosh(x) { + return new this(x).acosh(); + } + + + /* + * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function add(x, y) { + return new this(x).plus(y); + } + + + /* + * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function asin(x) { + return new this(x).asin(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function asinh(x) { + return new this(x).asinh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function atan(x) { + return new this(x).atan(); + } + + + /* + * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to + * `precision` significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function atanh(x) { + return new this(x).atanh(); + } + + + /* + * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi + * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. + * + * Domain: [-Infinity, Infinity] + * Range: [-pi, pi] + * + * y {number|string|Decimal} The y-coordinate. + * x {number|string|Decimal} The x-coordinate. + * + * atan2(±0, -0) = ±pi + * atan2(±0, +0) = ±0 + * atan2(±0, -x) = ±pi for x > 0 + * atan2(±0, x) = ±0 for x > 0 + * atan2(-y, ±0) = -pi/2 for y > 0 + * atan2(y, ±0) = pi/2 for y > 0 + * atan2(±y, -Infinity) = ±pi for finite y > 0 + * atan2(±y, +Infinity) = ±0 for finite y > 0 + * atan2(±Infinity, x) = ±pi/2 for finite x + * atan2(±Infinity, -Infinity) = ±3*pi/4 + * atan2(±Infinity, +Infinity) = ±pi/4 + * atan2(NaN, x) = NaN + * atan2(y, NaN) = NaN + * + */ + function atan2(y, x) { + y = new this(y); + x = new this(x); + var r, + pr = this.precision, + rm = this.rounding, + wpr = pr + 4; + + // Either NaN + if (!y.s || !x.s) { + r = new this(NaN); + + // Both ±Infinity + } else if (!y.d && !x.d) { + r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); + r.s = y.s; + + // x is ±Infinity or y is ±0 + } else if (!x.d || y.isZero()) { + r = x.s < 0 ? getPi(this, pr, rm) : new this(0); + r.s = y.s; + + // y is ±Infinity or x is ±0 + } else if (!y.d || x.isZero()) { + r = getPi(this, wpr, 1).times(0.5); + r.s = y.s; + + // Both non-zero and finite + } else if (x.s < 0) { + this.precision = wpr; + this.rounding = 1; + r = this.atan(divide(y, x, wpr, 1)); + x = getPi(this, wpr, 1); + this.precision = pr; + this.rounding = rm; + r = y.s < 0 ? r.minus(x) : r.plus(x); + } else { + r = this.atan(divide(y, x, wpr, 1)); + } + + return r; + } + + + /* + * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function cbrt(x) { + return new this(x).cbrt(); + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. + * + * x {number|string|Decimal} + * + */ + function ceil(x) { + return finalise(x = new this(x), x.e + 1, 2); + } + + + /* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * maxE {number} + * minE {number} + * modulo {number} + * crypto {boolean|number} + * defaults {true} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ + function config(obj) { + if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); + var i, p, v, + useDefaults = obj.defaults === true, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -EXP_LIMIT, 0, + 'toExpPos', 0, EXP_LIMIT, + 'maxE', 0, EXP_LIMIT, + 'minE', -EXP_LIMIT, 0, + 'modulo', 0, 9 + ]; + + for (i = 0; i < ps.length; i += 3) { + if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; + if ((v = obj[p]) !== void 0) { + if (v === true || v === false || v === 0 || v === 1) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + this[p] = true; + } else { + throw Error(cryptoUnavailable); + } + } else { + this[p] = false; + } + } else { + throw Error(invalidArgument + p + ': ' + v); + } + } + + return this; + } + + + /* + * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cos(x) { + return new this(x).cos(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function cosh(x) { + return new this(x).cosh(); + } + + + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * v {number|string|Decimal} A numeric value. + * + */ + function Decimal(v) { + var e, i, t, + x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(v); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (v instanceof Decimal) { + x.s = v.s; + + if (external) { + if (!v.d || v.e > Decimal.maxE) { + + // Infinity. + x.e = NaN; + x.d = null; + } else if (v.e < Decimal.minE) { + + // Zero. + x.e = 0; + x.d = [0]; + } else { + x.e = v.e; + x.d = v.d.slice(); + } + } else { + x.e = v.e; + x.d = v.d ? v.d.slice() : v.d; + } + + return; + } + + t = typeof v; + + if (t === 'number') { + if (v === 0) { + x.s = 1 / v < 0 ? -1 : 1; + x.e = 0; + x.d = [0]; + return; + } + + if (v < 0) { + v = -v; + x.s = -1; + } else { + x.s = 1; + } + + // Fast path for small integers. + if (v === ~~v && v < 1e7) { + for (e = 0, i = v; i >= 10; i /= 10) e++; + + if (external) { + if (e > Decimal.maxE) { + x.e = NaN; + x.d = null; + } else if (e < Decimal.minE) { + x.e = 0; + x.d = [0]; + } else { + x.e = e; + x.d = [v]; + } + } else { + x.e = e; + x.d = [v]; + } + + return; + + // Infinity, NaN. + } else if (v * 0 !== 0) { + if (!v) x.s = NaN; + x.e = NaN; + x.d = null; + return; + } + + return parseDecimal(x, v.toString()); + + } else if (t !== 'string') { + throw Error(invalidArgument + v); + } + + // Minus sign? + if ((i = v.charCodeAt(0)) === 45) { + v = v.slice(1); + x.s = -1; + } else { + // Plus sign? + if (i === 43) v = v.slice(1); + x.s = 1; + } + + return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + Decimal.EUCLID = 9; + + Decimal.config = Decimal.set = config; + Decimal.clone = clone; + Decimal.isDecimal = isDecimalInstance; + + Decimal.abs = abs; + Decimal.acos = acos; + Decimal.acosh = acosh; // ES6 + Decimal.add = add; + Decimal.asin = asin; + Decimal.asinh = asinh; // ES6 + Decimal.atan = atan; + Decimal.atanh = atanh; // ES6 + Decimal.atan2 = atan2; + Decimal.cbrt = cbrt; // ES6 + Decimal.ceil = ceil; + Decimal.cos = cos; + Decimal.cosh = cosh; // ES6 + Decimal.div = div; + Decimal.exp = exp; + Decimal.floor = floor; + Decimal.hypot = hypot; // ES6 + Decimal.ln = ln; + Decimal.log = log; + Decimal.log10 = log10; // ES6 + Decimal.log2 = log2; // ES6 + Decimal.max = max; + Decimal.min = min; + Decimal.mod = mod; + Decimal.mul = mul; + Decimal.pow = pow; + Decimal.random = random; + Decimal.round = round; + Decimal.sign = sign; // ES6 + Decimal.sin = sin; + Decimal.sinh = sinh; // ES6 + Decimal.sqrt = sqrt; + Decimal.sub = sub; + Decimal.tan = tan; + Decimal.tanh = tanh; // ES6 + Decimal.trunc = trunc; // ES6 + + if (obj === void 0) obj = {}; + if (obj) { + if (obj.defaults !== true) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + } + + Decimal.config(obj); + + return Decimal; + } + + + /* + * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function div(x, y) { + return new this(x).div(y); + } + + + /* + * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The power to which to raise the base of the natural log. + * + */ + function exp(x) { + return new this(x).exp(); + } + + + /* + * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. + * + * x {number|string|Decimal} + * + */ + function floor(x) { + return finalise(x = new this(x), x.e + 1, 3); + } + + + /* + * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, + * rounded to `precision` significant digits using rounding mode `rounding`. + * + * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) + * + * arguments {number|string|Decimal} + * + */ + function hypot() { + var i, n, + t = new this(0); + + external = false; + + for (i = 0; i < arguments.length;) { + n = new this(arguments[i++]); + if (!n.d) { + if (n.s) { + external = true; + return new this(1 / 0); + } + t = n; + } else if (t.d) { + t = t.plus(n.times(n)); + } + } + + external = true; + + return t.sqrt(); + } + + + /* + * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), + * otherwise return false. + * + */ + function isDecimalInstance(obj) { + return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function ln(x) { + return new this(x).ln(); + } + + + /* + * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base + * is specified, rounded to `precision` significant digits using rounding mode `rounding`. + * + * log[y](x) + * + * x {number|string|Decimal} The argument of the logarithm. + * y {number|string|Decimal} The base of the logarithm. + * + */ + function log(x, y) { + return new this(x).log(y); + } + + + /* + * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log2(x) { + return new this(x).log(2); + } + + + /* + * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function log10(x) { + return new this(x).log(10); + } + + + /* + * Return a new Decimal whose value is the maximum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function max() { + return maxOrMin(this, arguments, 'lt'); + } + + + /* + * Return a new Decimal whose value is the minimum of the arguments. + * + * arguments {number|string|Decimal} + * + */ + function min() { + return maxOrMin(this, arguments, 'gt'); + } + + + /* + * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mod(x, y) { + return new this(x).mod(y); + } + + + /* + * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function mul(x, y) { + return new this(x).mul(y); + } + + + /* + * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} The base. + * y {number|string|Decimal} The exponent. + * + */ + function pow(x, y) { + return new this(x).pow(y); + } + + + /* + * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with + * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros + * are produced). + * + * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. + * + */ + function random(sd) { + var d, e, k, n, + i = 0, + r = new this(1), + rd = []; + + if (sd === void 0) sd = this.precision; + else checkInt32(sd, 1, MAX_DIGITS); + + k = Math.ceil(sd / LOG_BASE); + + if (!this.crypto) { + for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; + + // Browsers supporting crypto.getRandomValues. + } else if (crypto.getRandomValues) { + d = crypto.getRandomValues(new Uint32Array(k)); + + for (; i < k;) { + n = d[i]; + + // 0 <= n < 4294967296 + // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). + if (n >= 4.29e9) { + d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; + } else { + + // 0 <= n <= 4289999999 + // 0 <= (n % 1e7) <= 9999999 + rd[i++] = n % 1e7; + } + } + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + d = crypto.randomBytes(k *= 4); + + for (; i < k;) { + + // 0 <= n < 2147483648 + n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); + + // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). + if (n >= 2.14e9) { + crypto.randomBytes(4).copy(d, i); + } else { + + // 0 <= n <= 2139999999 + // 0 <= (n % 1e7) <= 9999999 + rd.push(n % 1e7); + i += 4; + } + } + + i = k / 4; + } else { + throw Error(cryptoUnavailable); + } + + k = rd[--i]; + sd %= LOG_BASE; + + // Convert trailing digits to zeros according to sd. + if (k && sd) { + n = mathpow(10, LOG_BASE - sd); + rd[i] = (k / n | 0) * n; + } + + // Remove trailing words which are zero. + for (; rd[i] === 0; i--) rd.pop(); + + // Zero? + if (i < 0) { + e = 0; + rd = [0]; + } else { + e = -1; + + // Remove leading words which are zero and adjust exponent accordingly. + for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); + + // Count the digits of the first word of rd to determine leading zeros. + for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; + + // Adjust the exponent for leading zeros of the first word of rd. + if (k < LOG_BASE) e -= LOG_BASE - k; + } + + r.e = e; + r.d = rd; + + return r; + } + + + /* + * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. + * + * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). + * + * x {number|string|Decimal} + * + */ + function round(x) { + return finalise(x = new this(x), x.e + 1, this.rounding); + } + + + /* + * Return + * 1 if x > 0, + * -1 if x < 0, + * 0 if x is 0, + * -0 if x is -0, + * NaN otherwise + * + * x {number|string|Decimal} + * + */ + function sign(x) { + x = new this(x); + return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; + } + + + /* + * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sin(x) { + return new this(x).sin(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function sinh(x) { + return new this(x).sinh(); + } + + + /* + * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} + * + */ + function sqrt(x) { + return new this(x).sqrt(); + } + + + /* + * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits + * using rounding mode `rounding`. + * + * x {number|string|Decimal} + * y {number|string|Decimal} + * + */ + function sub(x, y) { + return new this(x).sub(y); + } + + + /* + * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant + * digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tan(x) { + return new this(x).tan(); + } + + + /* + * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` + * significant digits using rounding mode `rounding`. + * + * x {number|string|Decimal} A value in radians. + * + */ + function tanh(x) { + return new this(x).tanh(); + } + + + /* + * Return a new Decimal whose value is `x` truncated to an integer. + * + * x {number|string|Decimal} + * + */ + function trunc(x) { + return finalise(x = new this(x), x.e + 1, 1); + } + + + // Create and configure initial Decimal constructor. + Decimal = clone(DEFAULTS); + + Decimal['default'] = Decimal.Decimal = Decimal; + + // Create the internal constants from their string values. + LN10 = new Decimal(LN10); + PI = new Decimal(PI); + + + // Export. + + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { + return Decimal; + }); + + // Node and other environments that support module.exports. + } else if ( true && module.exports) { + if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { + P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; + P[Symbol.toStringTag] = 'Decimal'; + } + + module.exports = Decimal; + + // Browser. + } else { + if (!globalScope) { + globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; + } + + noConflict = globalScope.Decimal; + Decimal.noConflict = function () { + globalScope.Decimal = noConflict; + return Decimal; + }; + + globalScope.Decimal = Decimal; + } +})(this); /***/ }), @@ -295053,277 +295053,277 @@ function escapeJsonPtr(str) { /***/ 21328: /***/ (function(module) { -/** - * JSONSchema Validator - Validates JavaScript objects using JSON Schemas - * (http://www.json.com/json-schema-proposal/) - * Licensed under AFL-2.1 OR BSD-3-Clause -To use the validator call the validate function with an instance object and an optional schema object. -If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), -that schema will be used to validate and the schema parameter is not necessary (if both exist, -both validations will occur). -The validate method will return an array of validation errors. If there are no errors, then an -empty list will be returned. A validation error will have two properties: -"property" which indicates which property had the error -"message" which indicates what the error was - */ -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], function () { - return factory(); - }); - } else if ( true && module.exports) { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals - root.jsonSchema = factory(); - } -}(this, function () {// setup primitive classes to be JSON Schema types -var exports = validate -exports.Integer = {type:"integer"}; -var primitiveConstructors = { - String: String, - Boolean: Boolean, - Number: Number, - Object: Object, - Array: Array, - Date: Date -} -exports.validate = validate; -function validate(/*Any*/instance,/*Object*/schema) { - // Summary: - // To use the validator call JSONSchema.validate with an instance object and an optional schema object. - // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), - // that schema will be used to validate and the schema parameter is not necessary (if both exist, - // both validations will occur). - // The validate method will return an object with two properties: - // valid: A boolean indicating if the instance is valid by the schema - // errors: An array of validation errors. If there are no errors, then an - // empty list will be returned. A validation error will have two properties: - // property: which indicates which property had the error - // message: which indicates what the error was - // - return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); - }; -exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { - // Summary: - // The checkPropertyChange method will check to see if an value can legally be in property with the given schema - // This is slightly different than the validate method in that it will fail if the schema is readonly and it will - // not check for self-validation, it is assumed that the passed in value is already internally valid. - // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for - // information. - // - return validate(value, schema, {changing: property || "property"}); - }; -var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { - - if (!options) options = {}; - var _changing = options.changing; - - function getType(schema){ - return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); - } - var errors = []; - // validate a value against a property definition - function checkProp(value, schema, path,i){ - - var l; - path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; - function addError(message){ - errors.push({property:path,message:message}); - } - - if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ - if(typeof schema == 'function'){ - if(!(value instanceof schema)){ - addError("is not an instance of the class/constructor " + schema.name); - } - }else if(schema){ - addError("Invalid schema/property definition " + schema); - } - return null; - } - if(_changing && schema.readonly){ - addError("is a readonly field, it can not be changed"); - } - if(schema['extends']){ // if it extends another schema, it must pass that schema as well - checkProp(value,schema['extends'],path,i); - } - // validate a value against a type definition - function checkType(type,value){ - if(type){ - if(typeof type == 'string' && type != 'any' && - (type == 'null' ? value !== null : typeof value != type) && - !(value instanceof Array && type == 'array') && - !(value instanceof Date && type == 'date') && - !(type == 'integer' && value%1===0)){ - return [{property:path,message:value + " - " + (typeof value) + " value found, but a " + type + " is required"}]; - } - if(type instanceof Array){ - var unionErrors=[]; - for(var j = 0; j < type.length; j++){ // a union type - if(!(unionErrors=checkType(type[j],value)).length){ - break; - } - } - if(unionErrors.length){ - return unionErrors; - } - }else if(typeof type == 'object'){ - var priorErrors = errors; - errors = []; - checkProp(value,type,path); - var theseErrors = errors; - errors = priorErrors; - return theseErrors; - } - } - return []; - } - if(value === undefined){ - if(schema.required){ - addError("is missing and it is required"); - } - }else{ - errors = errors.concat(checkType(getType(schema),value)); - if(schema.disallow && !checkType(schema.disallow,value).length){ - addError(" disallowed value was matched"); - } - if(value !== null){ - if(value instanceof Array){ - if(schema.items){ - var itemsIsArray = schema.items instanceof Array; - var propDef = schema.items; - for (i = 0, l = value.length; i < l; i += 1) { - if (itemsIsArray) - propDef = schema.items[i]; - if (options.coerce) - value[i] = options.coerce(value[i], propDef); - errors.concat(checkProp(value[i],propDef,path,i)); - } - } - if(schema.minItems && value.length < schema.minItems){ - addError("There must be a minimum of " + schema.minItems + " in the array"); - } - if(schema.maxItems && value.length > schema.maxItems){ - addError("There must be a maximum of " + schema.maxItems + " in the array"); - } - }else if(schema.properties || schema.additionalProperties){ - errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); - } - if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ - addError("does not match the regex pattern " + schema.pattern); - } - if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ - addError("may only be " + schema.maxLength + " characters long"); - } - if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ - addError("must be at least " + schema.minLength + " characters long"); - } - if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && - schema.minimum > value){ - addError("must have a minimum value of " + schema.minimum); - } - if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && - schema.maximum < value){ - addError("must have a maximum value of " + schema.maximum); - } - if(schema['enum']){ - var enumer = schema['enum']; - l = enumer.length; - var found; - for(var j = 0; j < l; j++){ - if(enumer[j]===value){ - found=1; - break; - } - } - if(!found){ - addError("does not have a value in the enumeration " + enumer.join(", ")); - } - } - if(typeof schema.maxDecimal == 'number' && - (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ - addError("may only have " + schema.maxDecimal + " digits of decimal places"); - } - } - } - return null; - } - // validate an object against a schema - function checkObj(instance,objTypeDef,path,additionalProp){ - - if(typeof objTypeDef =='object'){ - if(typeof instance != 'object' || instance instanceof Array){ - errors.push({property:path,message:"an object is required"}); - } - - for(var i in objTypeDef){ - if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ - var value = instance.hasOwnProperty(i) ? instance[i] : undefined; - // skip _not_ specified properties - if (value === undefined && options.existingOnly) continue; - var propDef = objTypeDef[i]; - // set default - if(value === undefined && propDef["default"]){ - value = instance[i] = propDef["default"]; - } - if(options.coerce && i in instance){ - value = instance[i] = options.coerce(value, propDef); - } - checkProp(value,propDef,path,i); - } - } - } - for(i in instance){ - if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ - if (options.filter) { - delete instance[i]; - continue; - } else { - errors.push({property:path,message:"The property " + i + - " is not defined in the schema and the schema does not allow additional properties"}); - } - } - var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; - if(requires && !(requires in instance)){ - errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); - } - value = instance[i]; - if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ - if(options.coerce){ - value = instance[i] = options.coerce(value, additionalProp); - } - checkProp(value,additionalProp,path,i); - } - if(!_changing && value && value.$schema){ - errors = errors.concat(checkProp(value,value.$schema,path,i)); - } - } - return errors; - } - if(schema){ - checkProp(instance,schema,'',_changing || ''); - } - if(!_changing && instance && instance.$schema){ - checkProp(instance,instance.$schema,'',''); - } - return {valid:!errors.length,errors:errors}; -}; -exports.mustBeValid = function(result){ - // summary: - // This checks to ensure that the result is valid and will throw an appropriate error message if it is not - // result: the result returned from checkPropertyChange or validate - if(!result.valid){ - throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); - } -} - -return exports; -})); +/** + * JSONSchema Validator - Validates JavaScript objects using JSON Schemas + * (http://www.json.com/json-schema-proposal/) + * Licensed under AFL-2.1 OR BSD-3-Clause +To use the validator call the validate function with an instance object and an optional schema object. +If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), +that schema will be used to validate and the schema parameter is not necessary (if both exist, +both validations will occur). +The validate method will return an array of validation errors. If there are no errors, then an +empty list will be returned. A validation error will have two properties: +"property" which indicates which property had the error +"message" which indicates what the error was + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], function () { + return factory(); + }); + } else if ( true && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + // Browser globals + root.jsonSchema = factory(); + } +}(this, function () {// setup primitive classes to be JSON Schema types +var exports = validate +exports.Integer = {type:"integer"}; +var primitiveConstructors = { + String: String, + Boolean: Boolean, + Number: Number, + Object: Object, + Array: Array, + Date: Date +} +exports.validate = validate; +function validate(/*Any*/instance,/*Object*/schema) { + // Summary: + // To use the validator call JSONSchema.validate with an instance object and an optional schema object. + // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), + // that schema will be used to validate and the schema parameter is not necessary (if both exist, + // both validations will occur). + // The validate method will return an object with two properties: + // valid: A boolean indicating if the instance is valid by the schema + // errors: An array of validation errors. If there are no errors, then an + // empty list will be returned. A validation error will have two properties: + // property: which indicates which property had the error + // message: which indicates what the error was + // + return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); + }; +exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { + // Summary: + // The checkPropertyChange method will check to see if an value can legally be in property with the given schema + // This is slightly different than the validate method in that it will fail if the schema is readonly and it will + // not check for self-validation, it is assumed that the passed in value is already internally valid. + // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for + // information. + // + return validate(value, schema, {changing: property || "property"}); + }; +var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { + + if (!options) options = {}; + var _changing = options.changing; + + function getType(schema){ + return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); + } + var errors = []; + // validate a value against a property definition + function checkProp(value, schema, path,i){ + + var l; + path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; + function addError(message){ + errors.push({property:path,message:message}); + } + + if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ + if(typeof schema == 'function'){ + if(!(value instanceof schema)){ + addError("is not an instance of the class/constructor " + schema.name); + } + }else if(schema){ + addError("Invalid schema/property definition " + schema); + } + return null; + } + if(_changing && schema.readonly){ + addError("is a readonly field, it can not be changed"); + } + if(schema['extends']){ // if it extends another schema, it must pass that schema as well + checkProp(value,schema['extends'],path,i); + } + // validate a value against a type definition + function checkType(type,value){ + if(type){ + if(typeof type == 'string' && type != 'any' && + (type == 'null' ? value !== null : typeof value != type) && + !(value instanceof Array && type == 'array') && + !(value instanceof Date && type == 'date') && + !(type == 'integer' && value%1===0)){ + return [{property:path,message:value + " - " + (typeof value) + " value found, but a " + type + " is required"}]; + } + if(type instanceof Array){ + var unionErrors=[]; + for(var j = 0; j < type.length; j++){ // a union type + if(!(unionErrors=checkType(type[j],value)).length){ + break; + } + } + if(unionErrors.length){ + return unionErrors; + } + }else if(typeof type == 'object'){ + var priorErrors = errors; + errors = []; + checkProp(value,type,path); + var theseErrors = errors; + errors = priorErrors; + return theseErrors; + } + } + return []; + } + if(value === undefined){ + if(schema.required){ + addError("is missing and it is required"); + } + }else{ + errors = errors.concat(checkType(getType(schema),value)); + if(schema.disallow && !checkType(schema.disallow,value).length){ + addError(" disallowed value was matched"); + } + if(value !== null){ + if(value instanceof Array){ + if(schema.items){ + var itemsIsArray = schema.items instanceof Array; + var propDef = schema.items; + for (i = 0, l = value.length; i < l; i += 1) { + if (itemsIsArray) + propDef = schema.items[i]; + if (options.coerce) + value[i] = options.coerce(value[i], propDef); + errors.concat(checkProp(value[i],propDef,path,i)); + } + } + if(schema.minItems && value.length < schema.minItems){ + addError("There must be a minimum of " + schema.minItems + " in the array"); + } + if(schema.maxItems && value.length > schema.maxItems){ + addError("There must be a maximum of " + schema.maxItems + " in the array"); + } + }else if(schema.properties || schema.additionalProperties){ + errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); + } + if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ + addError("does not match the regex pattern " + schema.pattern); + } + if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ + addError("may only be " + schema.maxLength + " characters long"); + } + if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ + addError("must be at least " + schema.minLength + " characters long"); + } + if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && + schema.minimum > value){ + addError("must have a minimum value of " + schema.minimum); + } + if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && + schema.maximum < value){ + addError("must have a maximum value of " + schema.maximum); + } + if(schema['enum']){ + var enumer = schema['enum']; + l = enumer.length; + var found; + for(var j = 0; j < l; j++){ + if(enumer[j]===value){ + found=1; + break; + } + } + if(!found){ + addError("does not have a value in the enumeration " + enumer.join(", ")); + } + } + if(typeof schema.maxDecimal == 'number' && + (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ + addError("may only have " + schema.maxDecimal + " digits of decimal places"); + } + } + } + return null; + } + // validate an object against a schema + function checkObj(instance,objTypeDef,path,additionalProp){ + + if(typeof objTypeDef =='object'){ + if(typeof instance != 'object' || instance instanceof Array){ + errors.push({property:path,message:"an object is required"}); + } + + for(var i in objTypeDef){ + if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ + var value = instance.hasOwnProperty(i) ? instance[i] : undefined; + // skip _not_ specified properties + if (value === undefined && options.existingOnly) continue; + var propDef = objTypeDef[i]; + // set default + if(value === undefined && propDef["default"]){ + value = instance[i] = propDef["default"]; + } + if(options.coerce && i in instance){ + value = instance[i] = options.coerce(value, propDef); + } + checkProp(value,propDef,path,i); + } + } + } + for(i in instance){ + if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ + if (options.filter) { + delete instance[i]; + continue; + } else { + errors.push({property:path,message:"The property " + i + + " is not defined in the schema and the schema does not allow additional properties"}); + } + } + var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; + if(requires && !(requires in instance)){ + errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); + } + value = instance[i]; + if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ + if(options.coerce){ + value = instance[i] = options.coerce(value, additionalProp); + } + checkProp(value,additionalProp,path,i); + } + if(!_changing && value && value.$schema){ + errors = errors.concat(checkProp(value,value.$schema,path,i)); + } + } + return errors; + } + if(schema){ + checkProp(instance,schema,'',_changing || ''); + } + if(!_changing && instance && instance.$schema){ + checkProp(instance,instance.$schema,'',''); + } + return {valid:!errors.length,errors:errors}; +}; +exports.mustBeValid = function(result){ + // summary: + // This checks to ensure that the result is valid and will throw an appropriate error message if it is not + // result: the result returned from checkPropertyChange or validate + if(!result.valid){ + throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); + } +} + +return exports; +})); /***/ }), @@ -307251,1303 +307251,1303 @@ exports.parseURL = __nccwpck_require__(40033).parseURL; /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -const punycode = __nccwpck_require__(85477); -const tr46 = __nccwpck_require__(42299); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} - -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} - -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} - -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} - -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} - -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} - -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} - -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} - -function defaultPort(scheme) { - return specialSchemes[scheme]; -} - -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } - - return "%" + hex; -} - -function utf8PercentEncode(c) { - const buf = new Buffer(c); - - let str = ""; - - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } - - return str; -} - -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); - } - } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); -} - -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} - -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); - - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } - - return cStr; -} - -function parseIPv4Number(input) { - let R = 10; - - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } - - if (input === "") { - return 0; - } - - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } - - return parseInt(input, R); -} - -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } - } - - if (parts.length > 4) { - return input; - } - - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } - - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; - } - - let ipv4 = numbers.pop(); - let counter = 0; - - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } - - return ipv4; -} - -function serializeIPv4(address) { - let output = ""; - let n = address; - - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; - } - n = Math.floor(n / 256); - } - - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; - } - - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } - - address[pieceIndex] = value; - ++pieceIndex; - } - - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; - } - - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); - - if (pieceIndex !== 7) { - output += ":"; - } - } - - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); - } - - if (!isSpecialArg) { - return parseOpaqueHost(input); - } - - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } - - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; - } - - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; - } - - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; - } - - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); - } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; - } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; - } - - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - } - - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - - this.state = stateOverride || "scheme start"; - - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; - - this.input = punycode.ucs2.decode(this.input); - - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} - -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } - - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } - - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); - - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; + +const punycode = __nccwpck_require__(85477); +const tr46 = __nccwpck_require__(42299); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; /***/ }), @@ -350838,290 +350838,290 @@ module.exports.STATUS_MAPPING = { /***/ 4351: /***/ ((module) => { -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - 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; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __createBinding = function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }; - - __exportStar = function (m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + 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; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __createBinding = function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + + __exportStar = function (m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); /***/ }), diff --git a/dist/platforms/ubuntu/Dockerfile b/dist/platforms/ubuntu/Dockerfile deleted file mode 100644 index 2cb677c3..00000000 --- a/dist/platforms/ubuntu/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -ARG IMAGE -FROM $IMAGE - -LABEL "com.github.actions.name"="Unity - Builder" -LABEL "com.github.actions.description"="Build Unity projects for different platforms." -LABEL "com.github.actions.icon"="box" -LABEL "com.github.actions.color"="gray-dark" - -LABEL "repository"="http://github.com/game-ci/unity-actions" -LABEL "homepage"="http://github.com/game-ci/unity-actions" -LABEL "maintainer"="Webber Takken " - -COPY default-build-script /UnityBuilderAction -COPY platforms/ubuntu/steps /steps -RUN chmod -R +x /steps -COPY platforms/ubuntu/entrypoint.sh /entrypoint.sh -RUN chmod +x /entrypoint.sh -RUN ls - -ENTRYPOINT ["/entrypoint.sh"] diff --git a/dist/platforms/windows/Dockerfile b/dist/platforms/windows/Dockerfile deleted file mode 100644 index 2e3c1d6d..00000000 --- a/dist/platforms/windows/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -ARG IMAGE -FROM $IMAGE - -LABEL "com.github.actions.name"="Unity - Builder" -LABEL "com.github.actions.description"="Build Unity projects for different platforms." -LABEL "com.github.actions.icon"="box" -LABEL "com.github.actions.color"="gray-dark" - -LABEL "repository"="http://github.com/game-ci/unity-actions" -LABEL "homepage"="http://github.com/game-ci/unity-actions" -LABEL "maintainer"="Webber Takken " - -COPY default-build-script c:/UnityBuilderAction -COPY platforms/windows/steps c:/steps -COPY platforms/windows/entrypoint.ps1 c:/entrypoint.ps1 -COPY BlankProject c:/BlankProject -RUN dir - -ENTRYPOINT ["powershell", "c:/entrypoint.ps1"] diff --git a/dist/platforms/windows/steps/activate.ps1 b/dist/platforms/windows/activate.ps1 similarity index 100% rename from dist/platforms/windows/steps/activate.ps1 rename to dist/platforms/windows/activate.ps1 diff --git a/dist/platforms/windows/steps/build.ps1 b/dist/platforms/windows/build.ps1 similarity index 100% rename from dist/platforms/windows/steps/build.ps1 rename to dist/platforms/windows/build.ps1 diff --git a/dist/platforms/windows/steps/return_license.ps1 b/dist/platforms/windows/return_license.ps1 similarity index 100% rename from dist/platforms/windows/steps/return_license.ps1 rename to dist/platforms/windows/return_license.ps1 diff --git a/jest.config.js b/jest.config.js index f3a27fa9..be54f49e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,11 +1,30 @@ module.exports = { + // Automatically clear mock calls and instances between every test clearMocks: true, + + // An array of file extensions your modules use moduleFileExtensions: ['js', 'ts'], + + // The test environment that will be used for testing testEnvironment: 'node', + + // The glob patterns Jest uses to detect test files testMatch: ['**/*.test.ts'], + + // This option allows use of a custom test runner testRunner: 'jest-circus/runner', + + // A map with regular expressions for transformers to paths transform: { '^.+\\.ts$': 'ts-jest', }, + + // Indicates whether each individual test should be reported during the run verbose: true, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + modulePathIgnorePatterns: ['/lib/', '/dist/'], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + setupFilesAfterEnv: ['/src/jest.setup.ts'], }; diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 00000000..6789e0af --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,38 @@ +# EXAMPLE USAGE +# Refer for explanation to following link: +# https://github.com/evilmartians/lefthook/blob/master/docs/full_guide.md +# + +color: true +extends: {} + +pre-push: + parallel: true + commands: + packages-audit: + tags: security + run: yarn audit + +pre-commit: + parallel: true + commands: + format documents: + glob: '*.{md,mdx}' + run: yarn prettier --write {staged_files} + format configs: + glob: '*.{json,yml,yaml}' + run: yarn prettier --write {staged_files} + format code: + glob: '*.{js,jsx,ts,tsx}' + exclude: 'dist/' + run: yarn prettier --write {staged_files} && yarn eslint {staged_files} && git add {staged_files} + run tests: + glob: '*.{js,jsx,ts,tsx}' + exclude: 'dist/' + run: yarn jest --passWithNoTests --findRelatedTests {staged_files} + build distributables: + skip: ['merge', 'rebase'] + run: yarn build && git add dist + make shell script executable: + glob: '*.sh' + run: git update-index --chmod=+x diff --git a/package.json b/package.json index f74de3d1..707dab2e 100644 --- a/package.json +++ b/package.json @@ -7,11 +7,10 @@ "author": "Webber ", "license": "MIT", "scripts": { - "prebuild": "yarn", - "build": "tsc && ncc build lib --source-map --license licenses.txt", + "prepare": "lefthook install", + "build": "yarn && tsc && ncc build lib --source-map --license licenses.txt", "lint": "prettier --check \"src/**/*.{js,ts}\" && eslint src/**/*.ts", "format": "prettier --write \"src/**/*.{js,ts}\"", - "prepare": "husky install", "cli": "yarn ts-node src/index.ts -m cli", "gcp-secrets-cli": "cross-env readInputOverrideCommand=\"gcloud secrets versions access 1 --secret=\"{0}\"\" yarn ts-node src/index.ts -m cli --readInputFromOverrideList UNITY_EMAIL,UNITY_SERIAL,UNITY_PASSWORD", "cli-aws": "cross-env cloudRunnerCluster=aws yarn run test-cli", @@ -42,6 +41,7 @@ "yaml": "^1.10.2" }, "devDependencies": { + "@arkweid/lefthook": "^0.7.7", "@types/jest": "^27.4.1", "@types/node": "^17.0.23", "@types/semver": "^7.3.9", @@ -54,27 +54,13 @@ "eslint-plugin-jest": "24.1.3", "eslint-plugin-prettier": "^3.3.1", "eslint-plugin-unicorn": "28.0.2", - "husky": "^7.0.4", "jest": "^27.5.1", "jest-circus": "^27.5.1", + "jest-fail-on-console": "^2.3.0", "js-yaml": "^4.1.0", - "lint-staged": "^12.3.4", "prettier": "^2.5.1", "ts-jest": "^27.1.3", "ts-node": "10.4.0", "typescript": "4.1.3" - }, - "lint-staged": { - "*.{js,jsx,ts,tsx}": [ - "prettier --write", - "eslint", - "jest --findRelatedTests" - ], - "*.{json,md,yaml,yml}": [ - "prettier --write" - ], - "*.sh": [ - "git update-index --chmod=+x" - ] } } diff --git a/src/index.ts b/src/index.ts index 2fe0b4d6..9178a87b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,13 +12,11 @@ async function runMain() { Action.checkCompatibility(); Cache.verify(); - const { dockerfile, workspace, actionFolder } = Action; + const { workspace, actionFolder } = Action; const buildParameters = await BuildParameters.create(); const baseImage = new ImageTag(buildParameters); - let builtImage; - if ( buildParameters.cloudRunnerCluster && buildParameters.cloudRunnerCluster !== '' && @@ -31,8 +29,7 @@ async function runMain() { if (process.platform === 'darwin') { MacBuilder.run(actionFolder, workspace, buildParameters); } else { - builtImage = await Docker.build({ path: actionFolder, dockerfile, baseImage }); - await Docker.run(builtImage, { workspace, ...buildParameters }); + await Docker.run(baseImage, { workspace, actionFolder, ...buildParameters }); } } diff --git a/src/jest.setup.ts b/src/jest.setup.ts new file mode 100644 index 00000000..40325e3b --- /dev/null +++ b/src/jest.setup.ts @@ -0,0 +1,9 @@ +import failOnConsole from 'jest-fail-on-console'; + +// Fail when console logs something inside a test - use spyOn instead +failOnConsole({ + shouldFailOnWarn: true, + shouldFailOnError: true, + shouldFailOnLog: true, + shouldFailOnAssert: true, +}); diff --git a/src/model/action.test.ts b/src/model/action.test.ts index f537f298..76fef312 100644 --- a/src/model/action.test.ts +++ b/src/model/action.test.ts @@ -30,11 +30,4 @@ describe('Action', () => { expect(path.basename(actionFolder)).toStrictEqual('dist'); expect(fs.existsSync(actionFolder)).toStrictEqual(true); }); - - it('returns the docker file', () => { - const { dockerfile } = Action; - - expect(path.basename(dockerfile)).toStrictEqual('Dockerfile'); - expect(fs.existsSync(dockerfile)).toStrictEqual(true); - }); }); diff --git a/src/model/action.ts b/src/model/action.ts index 06ee1ccd..28d07963 100644 --- a/src/model/action.ts +++ b/src/model/action.ts @@ -29,20 +29,6 @@ class Action { return `${Action.rootFolder}/dist`; } - static get dockerfile() { - const currentPlatform = process.platform; - switch (currentPlatform) { - case 'linux': - return `${Action.actionFolder}/platforms/ubuntu/Dockerfile`; - case 'win32': - return `${Action.actionFolder}/platforms/windows/Dockerfile`; - case 'darwin': - return 'unused'; //Mac doesn't use a container - default: - throw new Error(`No Dockerfile for currently unsupported platform: ${currentPlatform}`); - } - } - static get workspace() { return process.env.GITHUB_WORKSPACE; } diff --git a/src/model/build-parameters.test.ts b/src/model/build-parameters.test.ts index c4ab5659..5b3075c0 100644 --- a/src/model/build-parameters.test.ts +++ b/src/model/build-parameters.test.ts @@ -5,16 +5,15 @@ import BuildParameters from './build-parameters'; import Input from './input'; import Platform from './platform'; +// Todo - Don't use process.env directly, that's what the input model class is for. const testLicense = '\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nm0Db8UK+ktnOLJBtHybkfetpcKo=o/pUbSQAukz7+ZYAWhnA0AJbIlyyCPL7bKVEM2lVqbrXt7cyey+umkCXamuOgsWPVUKBMkXtMH8L\n5etLmD0getWIhTGhzOnDCk+gtIPfL4jMo9tkEuOCROQAXCci23VFscKcrkB+3X6h4wEOtA2APhOY\nB+wvC794o8/82ffjP79aVAi57rp3Wmzx+9pe9yMwoJuljAy2sc2tIMgdQGWVmOGBpQm3JqsidyzI\nJWG2kjnc7pDXK9pwYzXoKiqUqqrut90d+kQqRyv7MSZXR50HFqD/LI69h68b7P8Bjo3bPXOhNXGR\n9YCoemH6EkfCJxp2gIjzjWW+l2Hj2EsFQi8YXw=='; process.env.UNITY_LICENSE = testLicense; const determineVersion = jest.spyOn(Versioning, 'determineVersion').mockImplementation(async () => '1.3.37'); - const determineUnityVersion = jest .spyOn(UnityVersioning, 'determineUnityVersion') .mockImplementation(() => '2019.2.11f1'); - const determineSdkManagerParameters = jest .spyOn(AndroidVersioning, 'determineSdkManagerParameters') .mockImplementation(() => 'platforms;android-30'); diff --git a/src/model/build-parameters.ts b/src/model/build-parameters.ts index 9a2b7fea..b58a6e29 100644 --- a/src/model/build-parameters.ts +++ b/src/model/build-parameters.ts @@ -69,15 +69,13 @@ class BuildParameters { static async create(): Promise { const buildFile = this.parseBuildFile(Input.buildName, Input.targetPlatform, Input.androidAppBundle); - const unityVersion = UnityVersioning.determineUnityVersion(Input.projectPath, Input.unityVersion); - const buildVersion = await Versioning.determineVersion(Input.versioningStrategy, Input.specifiedVersion); - const androidVersionCode = AndroidVersioning.determineVersionCode(buildVersion, Input.androidVersionCode); - const androidSdkManagerParameters = AndroidVersioning.determineSdkManagerParameters(Input.androidTargetSdkVersion); + // Todo - Don't use process.env directly, that's what the input model class is for. + // --- let unitySerial = ''; if (!process.env.UNITY_SERIAL && Input.githubInputEnabled && Input.cliOptions === undefined) { //No serial was present so it is a personal license that we need to convert diff --git a/src/model/docker.test.ts b/src/model/docker.test.ts index 0c81f643..290d19bf 100644 --- a/src/model/docker.test.ts +++ b/src/model/docker.test.ts @@ -1,21 +1,7 @@ import Action from './action'; import Docker from './docker'; -import ImageTag from './image-tag'; describe('Docker', () => { - it.skip('builds', async () => { - const path = Action.actionFolder; - const dockerfile = `${path}/Dockerfile`; - const baseImage = new ImageTag({ - repository: '', - name: 'alpine', - version: '3', - platform: 'Test', - }); - const tag = await Docker.build({ path, dockerfile, baseImage }, true); - expect(tag).toBeInstanceOf(ImageTag); - expect(tag.toString()).toStrictEqual('unity-builder:3'); - }, 240000); it.skip('runs', async () => { const image = 'unity-builder:2019.2.11f1-webgl'; const parameters = { diff --git a/src/model/docker.ts b/src/model/docker.ts index 4b77a9a6..78d22071 100644 --- a/src/model/docker.ts +++ b/src/model/docker.ts @@ -1,75 +1,66 @@ import { exec } from '@actions/exec'; -import ImageTag from './image-tag'; import ImageEnvironmentFactory from './image-environment-factory'; import { existsSync, mkdirSync } from 'fs'; import path from 'path'; class Docker { - static async build(buildParameters, silent = false) { - const { path: buildPath, dockerfile, baseImage } = buildParameters; - const { version, platform } = baseImage; - - const tag = new ImageTag({ repository: '', name: 'unity-builder', version, platform }); - const command = `docker build ${buildPath} \ - --file ${dockerfile} \ - --build-arg IMAGE=${baseImage} \ - --tag ${tag}`; - - await exec(command, undefined, { silent }); - - return tag; - } - static async run(image, parameters, silent = false) { - const { workspace, unitySerial, runnerTempPath, sshAgent } = parameters; - - const baseOsSpecificArguments = this.getBaseOsSpecificArguments( - process.platform, - workspace, - unitySerial, - runnerTempPath, - sshAgent, - ); - - const runCommand = `docker run \ - --workdir /github/workspace \ - --rm \ - ${ImageEnvironmentFactory.getEnvVarString(parameters)} \ - ${baseOsSpecificArguments} \ - ${image}`; - + let runCommand = ''; + switch (process.platform) { + case 'linux': + runCommand = this.getLinuxCommand(image, parameters); + break; + case 'win32': + runCommand = this.getWindowsCommand(image, parameters); + } await exec(runCommand, undefined, { silent }); } - static getBaseOsSpecificArguments(baseOs, workspace, unitySerial, runnerTemporaryPath, sshAgent): string { - switch (baseOs) { - case 'linux': { - const githubHome = path.join(runnerTemporaryPath, '_github_home'); - if (!existsSync(githubHome)) mkdirSync(githubHome); - const githubWorkflow = path.join(runnerTemporaryPath, '_github_workflow'); - if (!existsSync(githubWorkflow)) mkdirSync(githubWorkflow); + static getLinuxCommand(image, parameters): string { + const { workspace, actionFolder, runnerTempPath, sshAgent } = parameters; - return `--env UNITY_SERIAL \ - --env GITHUB_WORKSPACE=/github/workspace \ - ${sshAgent ? '--env SSH_AUTH_SOCK=/ssh-agent' : ''} \ - --volume "/var/run/docker.sock":"/var/run/docker.sock:z" \ - --volume "${githubHome}":"/root:z" \ - --volume "${githubWorkflow}":"/github/workflow:z" \ - --volume "${workspace}":"/github/workspace:z" \ - ${sshAgent ? `--volume ${sshAgent}:/ssh-agent` : ''} \ - ${sshAgent ? '--volume /home/runner/.ssh/known_hosts:/root/.ssh/known_hosts:ro' : ''}`; - } - case 'win32': - return `--env UNITY_SERIAL="${unitySerial}" \ - --env GITHUB_WORKSPACE=c:/github/workspace \ - --volume "${workspace}":"c:/github/workspace" \ - --volume "c:/regkeys":"c:/regkeys" \ - --volume "C:/Program Files (x86)/Microsoft Visual Studio":"C:/Program Files (x86)/Microsoft Visual Studio" \ - --volume "C:/Program Files (x86)/Windows Kits":"C:/Program Files (x86)/Windows Kits" \ - --volume "C:/ProgramData/Microsoft/VisualStudio":"C:/ProgramData/Microsoft/VisualStudio"`; - //Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit - } - return ''; + const githubHome = path.join(runnerTempPath, '_github_home'); + if (!existsSync(githubHome)) mkdirSync(githubHome); + const githubWorkflow = path.join(runnerTempPath, '_github_workflow'); + if (!existsSync(githubWorkflow)) mkdirSync(githubWorkflow); + + return `docker run \ + --workdir /github/workspace \ + --rm \ + ${ImageEnvironmentFactory.getEnvVarString(parameters)} \ + --env UNITY_SERIAL \ + --env GITHUB_WORKSPACE=/github/workspace \ + ${sshAgent ? '--env SSH_AUTH_SOCK=/ssh-agent' : ''} \ + --volume "${githubHome}":"/root:z" \ + --volume "${githubWorkflow}":"/github/workflow:z" \ + --volume "${workspace}":"/github/workspace:z" \ + --volume "${actionFolder}/default-build-script:/UnityBuilderAction:z" \ + --volume "${actionFolder}/platforms/ubuntu/steps:/steps:z" \ + --volume "${actionFolder}/platforms/ubuntu/entrypoint.sh:/entrypoint.sh:z" \ + ${sshAgent ? `--volume ${sshAgent}:/ssh-agent` : ''} \ + ${sshAgent ? '--volume /home/runner/.ssh/known_hosts:/root/.ssh/known_hosts:ro' : ''} \ + ${image} \ + /bin/bash -c /entrypoint.sh`; + } + + static getWindowsCommand(image: any, parameters: any): string { + const { workspace, actionFolder, unitySerial } = parameters; + return `docker run \ + --workdir /github/workspace \ + --rm \ + ${ImageEnvironmentFactory.getEnvVarString(parameters)} \ + --env UNITY_SERIAL="${unitySerial}" \ + --env GITHUB_WORKSPACE=c:/github/workspace \ + --volume "${workspace}":"c:/github/workspace" \ + --volume "c:/regkeys":"c:/regkeys" \ + --volume "C:/Program Files (x86)/Microsoft Visual Studio":"C:/Program Files (x86)/Microsoft Visual Studio" \ + --volume "C:/Program Files (x86)/Windows Kits":"C:/Program Files (x86)/Windows Kits" \ + --volume "C:/ProgramData/Microsoft/VisualStudio":"C:/ProgramData/Microsoft/VisualStudio" \ + --volume "${actionFolder}/default-build-script":"c:/UnityBuilderAction" \ + --volume "${actionFolder}/platforms/windows":"c:/steps" \ + --volume "${actionFolder}/BlankProject":"c:/BlankProject" \ + ${image} \ + powershell c:/steps/entrypoint.ps1`; } } diff --git a/src/model/input-readers/git-repo.ts b/src/model/input-readers/git-repo.ts index c661cb7c..c952c089 100644 --- a/src/model/input-readers/git-repo.ts +++ b/src/model/input-readers/git-repo.ts @@ -10,6 +10,7 @@ export class GitRepoReader { .split('https://github.com/')[1] .split('.git')[0]; } + public static async GetBranch() { assert(fs.existsSync(`.git`)); return (await System.run(`git branch`, [], {}, false)).split('*')[1].split(`\n`)[0].replace(/ /g, ``); diff --git a/src/model/input-readers/github-cli.test.ts b/src/model/input-readers/github-cli.test.ts index ca4b6b72..424af059 100644 --- a/src/model/input-readers/github-cli.test.ts +++ b/src/model/input-readers/github-cli.test.ts @@ -2,8 +2,11 @@ import { GithubCliReader } from './github-cli'; import * as core from '@actions/core'; describe(`github cli`, () => { - it(`returns`, async () => { + // Todo - We can not assume that everyone has the GitHub cli installed locally. + it.skip(`returns`, async () => { const token = await GithubCliReader.GetGitHubAuthToken(); + + // Todo - use expect(result).toStrictEqual(something) core.info(token); }); }); diff --git a/src/model/input.ts b/src/model/input.ts index f8963cbf..d2120147 100644 --- a/src/model/input.ts +++ b/src/model/input.ts @@ -200,7 +200,7 @@ class Input { } static get androidTargetSdkVersion() { - return core.getInput('androidTargetSdkVersion') || ''; + return Input.getInput('androidTargetSdkVersion') || ''; } static get sshAgent() { diff --git a/src/model/system.integration.test.ts b/src/model/system.integration.test.ts new file mode 100644 index 00000000..4d452fd1 --- /dev/null +++ b/src/model/system.integration.test.ts @@ -0,0 +1,46 @@ +import * as core from '@actions/core'; +import System from './system'; + +jest.spyOn(core, 'debug').mockImplementation(() => {}); +jest.spyOn(core, 'info').mockImplementation(() => {}); +jest.spyOn(core, 'warning').mockImplementation(() => {}); +jest.spyOn(core, 'error').mockImplementation(() => {}); + +afterEach(() => jest.clearAllMocks()); + +describe('System', () => { + describe('run', () => { + /** + * Not all shells (e.g. Powershell, sh) have a reference to `echo` binary (absent or alias). + * To ensure our integration with '@actions/exec' works as expected we run some specific tests in CI only + */ + describe('integration', () => { + if (!process.env.CI) { + it("doesn't run locally", () => { + expect(true).toBe(true); + }); + } else { + it('runs a command successfully', async () => { + await expect(System.run('true')).resolves.not.toBeNull(); + }); + + it('outputs results', async () => { + await expect(System.run('echo test')).resolves.toStrictEqual('test\n'); + }); + + it('throws on when error code is not 0', async () => { + await expect(System.run('false')).rejects.toThrowError(); + }); + + it('allows pipes using buffer', async () => { + await expect( + System.run('sh', undefined, { + input: Buffer.from('git tag --list --merged HEAD | grep v[0-9]* | wc -l'), + // eslint-disable-next-line github/no-then + }).then((result) => Number(result)), + ).resolves.not.toBeNaN(); + }); + } + }); + }); +}); diff --git a/src/model/system.test.ts b/src/model/system.test.ts index 85349f54..b65ca6df 100644 --- a/src/model/system.test.ts +++ b/src/model/system.test.ts @@ -1,57 +1,46 @@ import * as core from '@actions/core'; +import * as exec from '@actions/exec'; import System from './system'; jest.spyOn(core, 'debug').mockImplementation(() => {}); const info = jest.spyOn(core, 'info').mockImplementation(() => {}); jest.spyOn(core, 'warning').mockImplementation(() => {}); jest.spyOn(core, 'error').mockImplementation(() => {}); +const execSpy = jest.spyOn(exec, 'exec').mockImplementation(async () => 0); -afterEach(() => { - jest.clearAllMocks(); -}); +afterEach(() => jest.clearAllMocks()); describe('System', () => { describe('run', () => { - it('runs a command successfully', async () => { - await expect(System.run('true')).resolves.not.toBeNull(); - }); + describe('units', () => { + it('passes the command to command line', async () => { + await expect(System.run('echo test')).resolves.not.toBeNull(); + await expect(execSpy).toHaveBeenLastCalledWith('echo test', expect.anything(), expect.anything()); + }); - it('outputs results', async () => { - await expect(System.run('echo test')).resolves.toStrictEqual('test\n'); - }); + it('throws on when error code is not 0', async () => { + execSpy.mockImplementationOnce(async () => 1); + await expect(System.run('false')).rejects.toThrowError(); + }); - it('throws on when error code is not 0', async () => { - await expect(System.run('false')).rejects.toThrowError(); - }); + it('throws when no command is given', async () => { + await expect(System.run('')).rejects.toThrowError(); + }); - it('throws when no arguments are given', async () => { - await expect(System.run('')).rejects.toThrowError(); - }); + it('throws when command consists only of spaces', async () => { + await expect(System.run(' \t\n')).rejects.toThrowError(); + }); - it('outputs info', async () => { - await expect(System.run('echo test')).resolves.not.toBeNull(); - expect(info).toHaveBeenLastCalledWith('test\n'); - }); + it('outputs info', async () => { + execSpy.mockImplementationOnce(async (input, _, options) => { + options?.listeners?.stdout?.(Buffer.from(input, 'utf8')); + return 0; + }); - it('outputs info only once', async () => { - await expect(System.run('echo 1')).resolves.not.toBeNull(); - expect(info).toHaveBeenCalledTimes(1); - expect(info).toHaveBeenLastCalledWith('1\n'); - - info.mockClear(); - await expect(System.run('echo 2')).resolves.not.toBeNull(); - await expect(System.run('echo 3')).resolves.not.toBeNull(); - expect(info).toHaveBeenCalledTimes(2); - expect(info).toHaveBeenLastCalledWith('3\n'); - }); - - it('allows pipes using buffer', async () => { - await expect( - System.run('sh', undefined, { - input: Buffer.from('git tag --list --merged HEAD | grep v[0-9]* | wc -l'), - // eslint-disable-next-line github/no-then - }).then((result) => Number(result)), - ).resolves.not.toBeNaN(); + await expect(System.run('foo-bar')).resolves.not.toBeNull(); + expect(info).toHaveBeenCalledTimes(1); + expect(info).toHaveBeenLastCalledWith('foo-bar'); + }); }); }); }); diff --git a/src/model/system.ts b/src/model/system.ts index c9f0c8bf..9f1cb676 100644 --- a/src/model/system.ts +++ b/src/model/system.ts @@ -45,6 +45,10 @@ class System { }; try { + if (command.trim() === '') { + throw new Error(`Failed to execute empty command`); + } + const exitCode = await exec(command, arguments_, { silent: true, listeners, ...options }); showOutput(); if (exitCode !== 0) { diff --git a/yarn.lock b/yarn.lock index 4a3a49b9..25a4eb0b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -45,6 +45,11 @@ dependencies: "@jridgewell/trace-mapping" "^0.3.0" +"@arkweid/lefthook@^0.7.7": + version "0.7.7" + resolved "https://registry.yarnpkg.com/@arkweid/lefthook/-/lefthook-0.7.7.tgz#12951b09b955d8054885ffe929aa07a49f39027c" + integrity sha512-Eq30OXKmjxIAIsTtbX2fcF3SNZIXS8yry1u8yty7PQFYRctx04rVlhOJCEB2UmfTh8T2vrOMC9IHHUvvo5zbaQ== + "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13": version "7.12.13" resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz" @@ -1451,7 +1456,7 @@ ansi-colors@^4.1.1: resolved "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz" integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== -ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: +ansi-escapes@^4.2.1: version "4.3.2" resolved "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz" integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== @@ -1463,11 +1468,6 @@ ansi-regex@^5.0.0, ansi-regex@^5.0.1: resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== -ansi-regex@^6.0.1: - version "6.0.1" - resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz" - integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== - ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz" @@ -1487,11 +1487,6 @@ ansi-styles@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== -ansi-styles@^6.0.0: - version "6.1.0" - resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.1.0.tgz" - integrity sha512-VbqNsoz55SYGczauuup0MFUyXNQviSpFTj1RQtFzmQLk18qbVSpTFFGMT293rmDaQuKCT6InmbuEyUne4mTuxQ== - anymatch@^3.0.3: version "3.1.2" resolved "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz" @@ -1863,6 +1858,14 @@ chalk@^4.0.0: ansi-styles "^4.1.0" supports-color "^7.1.0" +chalk@^4.1.0: + version "4.1.2" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" + integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + char-regex@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz" @@ -1900,29 +1903,6 @@ clean-stack@^2.0.0: resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== -cli-cursor@^3.1.0: - version "3.1.0" - resolved "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz" - integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== - dependencies: - restore-cursor "^3.1.0" - -cli-truncate@^2.1.0: - version "2.1.0" - resolved "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz" - integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== - dependencies: - slice-ansi "^3.0.0" - string-width "^4.2.0" - -cli-truncate@^3.1.0: - version "3.1.0" - resolved "https://registry.npmjs.org/cli-truncate/-/cli-truncate-3.1.0.tgz" - integrity sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA== - dependencies: - slice-ansi "^5.0.0" - string-width "^5.0.0" - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1978,11 +1958,6 @@ colorette@^1.2.2: resolved "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz" integrity sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w== -colorette@^2.0.16: - version "2.0.16" - resolved "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz" - integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g== - combined-stream@^1.0.6, combined-stream@^1.0.8, combined-stream@~1.0.6: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" @@ -2002,11 +1977,6 @@ commander@^7.2.0: resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== -commander@^8.3.0: - version "8.3.0" - resolved "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz" - integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== - commander@^9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/commander/-/commander-9.0.0.tgz#86d58f24ee98126568936bd1d3574e0308a99a40" @@ -2088,7 +2058,7 @@ data-urls@^2.0.0: whatwg-mimetype "^2.3.0" whatwg-url "^8.0.0" -debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.3: +debug@4, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1: version "4.3.3" resolved "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz" integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q== @@ -2245,11 +2215,6 @@ emoji-regex@^8.0.0: resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== -emoji-regex@^9.2.2: - version "9.2.2" - resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz" - integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== - end-of-stream@^1.1.0: version "1.4.4" resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" @@ -2577,7 +2542,7 @@ execa@5.0.0: signal-exit "^3.0.3" strip-final-newline "^2.0.0" -execa@^5.0.0, execa@^5.1.1: +execa@^5.0.0: version "5.1.1" resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd" integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg== @@ -3007,11 +2972,6 @@ human-signals@^2.1.0: resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== -husky@^7.0.4: - version "7.0.4" - resolved "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz" - integrity sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ== - iconv-lite@0.4.24: version "0.4.24" resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz" @@ -3139,11 +3099,6 @@ is-fullwidth-code-point@^3.0.0: resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== -is-fullwidth-code-point@^4.0.0: - version "4.0.0" - resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz" - integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== - is-generator-fn@^2.0.0: version "2.1.0" resolved "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz" @@ -3418,6 +3373,13 @@ jest-environment-node@^27.5.1: jest-mock "^27.5.1" jest-util "^27.5.1" +jest-fail-on-console@^2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/jest-fail-on-console/-/jest-fail-on-console-2.3.0.tgz#bf22af0e535512ec7e220223279e3fb7ae621b8b" + integrity sha512-RwTq79+v5OccU59VmhoTvsCyTQ11YeOtLL6xLtkks/H7afLay6gASk6a4qMlyLlpM36t0rPW+DQsJ4ZNcCS2ug== + dependencies: + chalk "^4.1.0" + jest-get-type@^27.5.1: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-27.5.1.tgz#3cd613c507b0f7ace013df407a1c1cd578bcb4f1" @@ -3935,49 +3897,11 @@ levn@~0.3.0: prelude-ls "~1.1.2" type-check "~0.3.2" -lilconfig@2.0.4: - version "2.0.4" - resolved "https://registry.npmjs.org/lilconfig/-/lilconfig-2.0.4.tgz" - integrity sha512-bfTIN7lEsiooCocSISTWXkiWJkRqtL9wYtYy+8EK3Y41qh3mpwPU0ycTOgjdY9ErwXCc8QyrQp82bdL0Xkm9yA== - lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= -lint-staged@^12.3.4: - version "12.3.4" - resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-12.3.4.tgz#4b1ff8c394c3e6da436aaec5afd4db18b5dac360" - integrity sha512-yv/iK4WwZ7/v0GtVkNb3R82pdL9M+ScpIbJLJNyCXkJ1FGaXvRCOg/SeL59SZtPpqZhE7BD6kPKFLIDUhDx2/w== - dependencies: - cli-truncate "^3.1.0" - colorette "^2.0.16" - commander "^8.3.0" - debug "^4.3.3" - execa "^5.1.1" - lilconfig "2.0.4" - listr2 "^4.0.1" - micromatch "^4.0.4" - normalize-path "^3.0.0" - object-inspect "^1.12.0" - string-argv "^0.3.1" - supports-color "^9.2.1" - yaml "^1.10.2" - -listr2@^4.0.1: - version "4.0.4" - resolved "https://registry.yarnpkg.com/listr2/-/listr2-4.0.4.tgz#d098a1c419284fb26e184b5d5889b235e8912245" - integrity sha512-vJOm5KD6uZXjSsrwajr+mNacIjf87gWvlBEltPWLbTkslUscWAzquyK4xfe9Zd4RDgO5nnwFyV06FC+uVR+5mg== - dependencies: - cli-truncate "^2.1.0" - colorette "^2.0.16" - log-update "^4.0.0" - p-map "^4.0.0" - rfdc "^1.3.0" - rxjs "^7.5.4" - through "^2.3.8" - wrap-ansi "^7.0.0" - load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz" @@ -4028,16 +3952,6 @@ lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.7.0: resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== -log-update@^4.0.0: - version "4.0.0" - resolved "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz" - integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== - dependencies: - ansi-escapes "^4.3.0" - cli-cursor "^3.1.0" - slice-ansi "^4.0.0" - wrap-ansi "^6.2.0" - lowercase-keys@^1.0.0, lowercase-keys@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz" @@ -4127,9 +4041,9 @@ minimatch@^3.0.4: brace-expansion "^1.1.7" minimist@^1.2.0, minimist@^1.2.5: - version "1.2.5" - resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz" - integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== + version "1.2.6" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" + integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minipass@^3.0.0: version "3.1.6" @@ -4245,11 +4159,6 @@ object-hash@^2.0.1: resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-2.2.0.tgz#5ad518581eefc443bd763472b8ff2e9c2c0d54a5" integrity sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw== -object-inspect@^1.12.0: - version "1.12.0" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.0.tgz#6e2c120e868fd1fd18cb4f18c31741d0d6e776f0" - integrity sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g== - object-inspect@^1.9.0: version "1.11.1" resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.1.tgz" @@ -4292,7 +4201,7 @@ once@^1.3.0, once@^1.3.1, once@^1.4.0: dependencies: wrappy "1" -onetime@^5.1.0, onetime@^5.1.2: +onetime@^5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== @@ -4397,13 +4306,6 @@ p-locate@^4.1.0: dependencies: p-limit "^2.2.0" -p-map@^4.0.0: - version "4.0.0" - resolved "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz" - integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== - dependencies: - aggregate-error "^3.0.0" - p-some@^5.0.0: version "5.0.0" resolved "https://registry.npmjs.org/p-some/-/p-some-5.0.0.tgz" @@ -4824,14 +4726,6 @@ responselike@^2.0.0: dependencies: lowercase-keys "^2.0.0" -restore-cursor@^3.1.0: - version "3.1.0" - resolved "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz" - integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== - dependencies: - onetime "^5.1.0" - signal-exit "^3.0.2" - reusify@^1.0.4: version "1.0.4" resolved "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz" @@ -4842,11 +4736,6 @@ rfc4648@^1.3.0: resolved "https://registry.yarnpkg.com/rfc4648/-/rfc4648-1.5.1.tgz#b0b16756e33d9de8c0c7833e94b28e627ec372a4" integrity sha512-60e/YWs2/D3MV1ErdjhJHcmlgnyLUiG4X/14dgsfm9/zmCWLN16xI6YqJYSCd/OANM7bUNzJqPY5B8/02S9Ibw== -rfdc@^1.3.0: - version "1.3.0" - resolved "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz" - integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA== - rimraf@^3.0.0, rimraf@^3.0.2: version "3.0.2" resolved "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz" @@ -4861,13 +4750,6 @@ run-parallel@^1.1.9: dependencies: queue-microtask "^1.2.2" -rxjs@^7.5.4: - version "7.5.4" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.5.4.tgz#3d6bd407e6b7ce9a123e76b1e770dc5761aa368d" - integrity sha512-h5M3Hk78r6wAheJF0a5YahB1yRQKCsZ4MsGdZ5O9ETbVtjPcScGfrMmoOq7EBsCRzd4BDkvDJ7ogP8Sz5tTFiQ== - dependencies: - tslib "^2.1.0" - safe-buffer@^5.0.1, safe-buffer@^5.1.2: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" @@ -4974,15 +4856,6 @@ slash@^3.0.0: resolved "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== -slice-ansi@^3.0.0: - version "3.0.0" - resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz" - integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== - dependencies: - ansi-styles "^4.0.0" - astral-regex "^2.0.0" - is-fullwidth-code-point "^3.0.0" - slice-ansi@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz" @@ -4992,14 +4865,6 @@ slice-ansi@^4.0.0: astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" -slice-ansi@^5.0.0: - version "5.0.0" - resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz" - integrity sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ== - dependencies: - ansi-styles "^6.0.0" - is-fullwidth-code-point "^4.0.0" - source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz" @@ -5086,11 +4951,6 @@ stream-buffers@^3.0.2: resolved "https://registry.yarnpkg.com/stream-buffers/-/stream-buffers-3.0.2.tgz#5249005a8d5c2d00b3a32e6e0a6ea209dc4f3521" integrity sha512-DQi1h8VEBA/lURbSwFtEHnSTb9s2/pwLEaFuNhXwy1Dx3Sa0lOuYT2yNUr4/j2fs8oCAMANtrZ5OrPZtyVs3MQ== -string-argv@^0.3.1: - version "0.3.1" - resolved "https://registry.npmjs.org/string-argv/-/string-argv-0.3.1.tgz" - integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== - string-length@^4.0.1: version "4.0.2" resolved "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz" @@ -5108,15 +4968,6 @@ string-width@^4.1.0, string-width@^4.2.0: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" -string-width@^5.0.0: - version "5.0.1" - resolved "https://registry.npmjs.org/string-width/-/string-width-5.0.1.tgz" - integrity sha512-5ohWO/M4//8lErlUUtrFy3b11GtNOuMOU0ysKCDXFcfXuuvUXu95akgj/i8ofmaGdN0hCqyl6uu9i8dS/mQp5g== - dependencies: - emoji-regex "^9.2.2" - is-fullwidth-code-point "^4.0.0" - strip-ansi "^7.0.1" - string.prototype.trimend@^1.0.4: version "1.0.4" resolved "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz" @@ -5140,13 +4991,6 @@ strip-ansi@^6.0.0: dependencies: ansi-regex "^5.0.0" -strip-ansi@^7.0.1: - version "7.0.1" - resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz" - integrity sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw== - dependencies: - ansi-regex "^6.0.1" - strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz" @@ -5188,11 +5032,6 @@ supports-color@^8.0.0: dependencies: has-flag "^4.0.0" -supports-color@^9.2.1: - version "9.2.1" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.2.1.tgz#599dc9d45acf74c6176e0d880bab1d7d718fe891" - integrity sha512-Obv7ycoCTG51N7y175StI9BlAXrmgZrFhZOb0/PyjHBher/NmsdBgbbQ1Inhq+gIhz6+7Gb+jWF2Vqi7Mf1xnQ== - supports-hyperlinks@^2.0.0: version "2.2.0" resolved "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz" @@ -5279,11 +5118,6 @@ throat@^6.0.1: resolved "https://registry.yarnpkg.com/throat/-/throat-6.0.1.tgz#d514fedad95740c12c2d7fc70ea863eb51ade375" integrity sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w== -through@^2.3.8: - version "2.3.8" - resolved "https://registry.npmjs.org/through/-/through-2.3.8.tgz" - integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= - tmp-promise@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/tmp-promise/-/tmp-promise-3.0.3.tgz#60a1a1cc98c988674fcbfd23b6e3367bdeac4ce7" @@ -5396,11 +5230,6 @@ tslib@^1.8.1, tslib@^1.9.3: resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== -tslib@^2.1.0: - version "2.3.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" - integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== - tsutils@^3.17.1: version "3.21.0" resolved "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz" @@ -5661,15 +5490,6 @@ word-wrap@^1.2.3, word-wrap@~1.2.3: resolved "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== -wrap-ansi@^6.2.0: - version "6.2.0" - resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz" - integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz"