diff --git a/dist/index.js b/dist/index.js index a367d62..f817678 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,49 +5,49 @@ require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap /***/ (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 main_1 = __nccwpck_require__(3109); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const post_1 = __nccwpck_require__(95); -/* - * GitHub Action can provide multiple executable entrypoints (pre, main, post), - * but it is complicated process to generate multiple `.js` files with `ncc`. - * So we rather generate just one entrypoint, that is symlinked to multiple locations (main.js and post.js). - * Then when GitHub Action Runner executes it as `node path/to/main.js` and `node path/to/post.js`, - * it can read arguments it was executed with and decide which file to execute. - * The argv[0] is going to be a full path to `node` executable and - * the argv[1] is going to be the full path to the script. - * In case index.js would be marked executable and executed directly without the argv[1] it defaults to "main.js". - */ -function run([, name = 'main.js']) { - return __awaiter(this, void 0, void 0, function* () { - const script = path_1.default.basename(name); - switch (script) { - case 'main.js': - yield (0, main_1.run)(); - break; - case 'post.js': - yield (0, post_1.run)(); - break; - default: - throw new Error(`Unknown script argument: '${script}'`); - } - }); -} -run(process.argv); + +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 main_1 = __nccwpck_require__(3109); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const post_1 = __nccwpck_require__(95); +/* + * GitHub Action can provide multiple executable entrypoints (pre, main, post), + * but it is complicated process to generate multiple `.js` files with `ncc`. + * So we rather generate just one entrypoint, that is symlinked to multiple locations (main.js and post.js). + * Then when GitHub Action Runner executes it as `node path/to/main.js` and `node path/to/post.js`, + * it can read arguments it was executed with and decide which file to execute. + * The argv[0] is going to be a full path to `node` executable and + * the argv[1] is going to be the full path to the script. + * In case index.js would be marked executable and executed directly without the argv[1] it defaults to "main.js". + */ +function run([, name = 'main.js']) { + return __awaiter(this, void 0, void 0, function* () { + const script = path_1.default.basename(name); + switch (script) { + case 'main.js':--workdir + yield (0, main_1.run)(); + break; + case 'post.js': + yield (0, post_1.run)(); + break; + default: + throw new Error(`Unknown script argument: '${script}'`); + } + }); +} +run(process.argv); /***/ }), @@ -56,86 +56,86 @@ run(process.argv); /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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.run = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const model_1 = __nccwpck_require__(1359); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - model_1.Action.checkCompatibility(); - const { workspace, actionFolder } = model_1.Action; - const { editorVersion, customImage, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, gitPrivateToken, githubToken, checkName, packageMode, packageName, chownFilesTo, unityLicensingServer, } = model_1.Input.getFromUser(); - const baseImage = new model_1.ImageTag({ editorVersion, customImage }); - const runnerContext = model_1.Action.runnerContext(); - try { - yield model_1.Docker.run(baseImage, Object.assign({ actionFolder, - editorVersion, - workspace, - projectPath, - customParameters, - testMode, - coverageOptions, - artifactsPath, - useHostNetwork, - sshAgent, - packageMode, - packageName, - gitPrivateToken, - githubToken, - chownFilesTo, - unityLicensingServer }, runnerContext)); - } - finally { - yield model_1.Output.setArtifactsPath(artifactsPath); - yield model_1.Output.setCoveragePath('CodeCoverage'); - } - if (githubToken) { - const failedTestCount = yield model_1.ResultsCheck.createCheck(artifactsPath, githubToken, checkName); - if (failedTestCount >= 1) { - core.setFailed(`Test(s) Failed! Check '${checkName}' for details.`); - } - } - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.run = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const model_1 = __nccwpck_require__(1359); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + model_1.Action.checkCompatibility(); + const { workspace, actionFolder } = model_1.Action; + const { editorVersion, customImage, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, gitPrivateToken, githubToken, checkName, packageMode, packageName, chownFilesTo, unityLicensingServer, } = model_1.Input.getFromUser(); + const baseImage = new model_1.ImageTag({ editorVersion, customImage }); + const runnerContext = model_1.Action.runnerContext(); + try { + yield model_1.Docker.run(baseImage, Object.assign({ actionFolder, + editorVersion, + workspace, + projectPath, + customParameters, + testMode, + coverageOptions, + artifactsPath, + useHostNetwork, + sshAgent, + packageMode, + packageName, + gitPrivateToken, + githubToken, + chownFilesTo, + unityLicensingServer }, runnerContext)); + } + finally { + yield model_1.Output.setArtifactsPath(artifactsPath); + yield model_1.Output.setCoveragePath('CodeCoverage'); + } + if (githubToken) { + const failedTestCount = yield model_1.ResultsCheck.createCheck(artifactsPath, githubToken, checkName); + if (failedTestCount >= 1) { + core.setFailed(`Test(s) Failed! Check '${checkName}' for details.`); + } + } + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; /***/ }), @@ -144,54 +144,54 @@ exports.run = run; /***/ (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__(1017)); -const Action = { - get supportedPlatforms() { - return ['linux', 'win32']; - }, - get isRunningLocally() { - return process.env.RUNNER_WORKSPACE === undefined; - }, - get isRunningFromSource() { - return path_1.default.basename(__dirname) === 'model'; - }, - get canonicalName() { - return 'unity-test-runner'; - }, - 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)); - }, - get actionFolder() { - return `${Action.rootFolder}/dist`; - }, - get workspace() { - return process.env.GITHUB_WORKSPACE; - }, - runnerContext() { - var _a, _b; - const runnerTemporaryPath = (_a = process.env.RUNNER_TEMP) !== null && _a !== void 0 ? _a : process.cwd(); - const githubAction = (_b = process.env.GITHUB_ACTION) !== null && _b !== void 0 ? _b : process.pid.toString(); - return { - runnerTemporaryPath, - githubAction, - }; - }, - 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__(1017)); +const Action = { + get supportedPlatforms() { + return ['linux', 'win32']; + }, + get isRunningLocally() { + return process.env.RUNNER_WORKSPACE === undefined; + }, + get isRunningFromSource() { + return path_1.default.basename(__dirname) === 'model'; + }, + get canonicalName() { + return 'unity-test-runner'; + }, + 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)); + }, + get actionFolder() { + return `${Action.rootFolder}/dist`; + }, + get workspace() { + return process.env.GITHUB_WORKSPACE; + }, + runnerContext() { + var _a, _b; + const runnerTemporaryPath = (_a = process.env.RUNNER_TEMP) !== null && _a !== void 0 ? _a : process.cwd(); + const githubAction = (_b = process.env.GITHUB_ACTION) !== null && _b !== void 0 ? _b : process.pid.toString(); + return { + runnerTemporaryPath, + githubAction, + }; + }, + checkCompatibility() { + const currentPlatform = process.platform; + if (!Action.supportedPlatforms.includes(currentPlatform)) { + throw new Error(`Currently ${currentPlatform}-platform is not supported`); + } + }, +}; +exports["default"] = Action; /***/ }), @@ -200,77 +200,77 @@ exports["default"] = Action; /***/ (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 = __nccwpck_require__(7147); -const licensing_server_setup_1 = __importDefault(__nccwpck_require__(6089)); -const exec_1 = __nccwpck_require__(1514); -const path_1 = __importDefault(__nccwpck_require__(1017)); -/** - * Build a path for a docker --cidfile parameter. Docker will store the the created container. - * This path is stable for the whole execution of the action, so it can be executed with the same parameters - * multiple times and get the same result. - */ -const containerIdFilePath = parameters => { - const { runnerTemporaryPath, githubAction } = parameters; - return path_1.default.join(runnerTemporaryPath, `container_${githubAction}`); -}; -const Docker = { - /** - * Remove a possible leftover container created by `Docker.run`. - */ - ensureContainerRemoval(parameters) { - return __awaiter(this, void 0, void 0, function* () { - const cidfile = containerIdFilePath(parameters); - if (!(0, fs_1.existsSync)(cidfile)) { - return; - } - const container = (0, fs_1.readFileSync)(cidfile, 'ascii').trim(); - yield (0, exec_1.exec)(`docker`, ['rm', '--force', '--volumes', container], { silent: true }); - (0, fs_1.rmSync)(cidfile); - }); - }, - run(image, parameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - let runCommand = ''; - if (parameters.unityLicensingServer !== '') { - licensing_server_setup_1.default.Setup(parameters.unityLicensingServer, parameters.actionFolder); - } - switch (process.platform) { - case 'linux': - runCommand = this.getLinuxCommand(image, parameters); - break; - case 'win32': - runCommand = this.getWindowsCommand(image, parameters); - break; - default: - throw new Error(`Operation system, ${process.platform}, is not supported yet.`); - } - yield (0, exec_1.exec)(runCommand, undefined, { silent }); - }); - }, - getLinuxCommand(image, parameters) { - const { actionFolder, editorVersion, workspace, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, packageMode, packageName, gitPrivateToken, githubToken, runnerTemporaryPath, chownFilesTo, unityLicensingServer, } = parameters; - const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); - if (!(0, fs_1.existsSync)(githubHome)) - (0, fs_1.mkdirSync)(githubHome); - const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); - if (!(0, fs_1.existsSync)(githubWorkflow)) - (0, fs_1.mkdirSync)(githubWorkflow); - const cidfile = containerIdFilePath(parameters); - const testPlatforms = (testMode === 'all' ? ['playmode', 'editmode', 'COMBINE_RESULTS'] : [testMode]).join(';'); + +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 = __nccwpck_require__(7147); +const licensing_server_setup_1 = __importDefault(__nccwpck_require__(6089)); +const exec_1 = __nccwpck_require__(1514); +const path_1 = __importDefault(__nccwpck_require__(1017)); +/** + * Build a path for a docker --cidfile parameter. Docker will store the the created container. + * This path is stable for the whole execution of the action, so it can be executed with the same parameters + * multiple times and get the same result. + */ +const containerIdFilePath = parameters => { + const { runnerTemporaryPath, githubAction } = parameters; + return path_1.default.join(runnerTemporaryPath, `container_${githubAction}`); +}; +const Docker = { + /** + * Remove a possible leftover container created by `Docker.run`. + */ + ensureContainerRemoval(parameters) { + return __awaiter(this, void 0, void 0, function* () { + const cidfile = containerIdFilePath(parameters); + if (!(0, fs_1.existsSync)(cidfile)) { + return; + } + const container = (0, fs_1.readFileSync)(cidfile, 'ascii').trim(); + yield (0, exec_1.exec)(`docker`, ['rm', '--force', '--volumes', container], { silent: true }); + (0, fs_1.rmSync)(cidfile); + }); + }, + run(image, parameters, silent = false) { + return __awaiter(this, void 0, void 0, function* () { + let runCommand = ''; + if (parameters.unityLicensingServer !== '') { + licensing_server_setup_1.default.Setup(parameters.unityLicensingServer, parameters.actionFolder); + } + switch (process.platform) { + case 'linux': + runCommand = this.getLinuxCommand(image, parameters); + break; + case 'win32': + runCommand = this.getWindowsCommand(image, parameters); + break; + default: + throw new Error(`Operation system, ${process.platform}, is not supported yet.`); + } + yield (0, exec_1.exec)(runCommand, undefined, { silent }); + }); + }, + getLinuxCommand(image, parameters) { + const { actionFolder, editorVersion, workspace, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, packageMode, packageName, gitPrivateToken, githubToken, runnerTemporaryPath, chownFilesTo, unityLicensingServer, } = parameters; + const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); + if (!(0, fs_1.existsSync)(githubHome)) + (0, fs_1.mkdirSync)(githubHome); + const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); + if (!(0, fs_1.existsSync)(githubWorkflow)) + (0, fs_1.mkdirSync)(githubWorkflow); + const cidfile = containerIdFilePath(parameters); + const testPlatforms = (testMode === 'all' ? ['playmode', 'editmode', 'COMBINE_RESULTS'] : [testMode]).join(';'); return `docker run \ --workdir /github/workspace \ --cidfile "${cidfile}" \ @@ -320,20 +320,20 @@ const Docker = { ${useHostNetwork ? '--net=host' : ''} \ ${githubToken ? '--env USE_EXIT_CODE=false' : '--env USE_EXIT_CODE=true'} \ ${image} \ - /bin/bash -c /entrypoint.sh`; - }, - getWindowsCommand(image, parameters) { - const { actionFolder, editorVersion, workspace, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, packageMode, packageName, gitPrivateToken, githubToken, runnerTemporaryPath, chownFilesTo, unityLicensingServer, } = parameters; - const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); - if (!(0, fs_1.existsSync)(githubHome)) - (0, fs_1.mkdirSync)(githubHome); - const cidfile = containerIdFilePath(parameters); - const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); - if (!(0, fs_1.existsSync)(githubWorkflow)) - (0, fs_1.mkdirSync)(githubWorkflow); - const testPlatforms = (testMode === 'all' ? ['playmode', 'editmode', 'COMBINE_RESULTS'] : [testMode]).join(';'); + /bin/bash -c /entrypoint.sh`; + }, + getWindowsCommand(image, parameters) { + const { actionFolder, editorVersion, workspace, projectPath, customParameters, testMode, coverageOptions, artifactsPath, useHostNetwork, sshAgent, packageMode, packageName, gitPrivateToken, githubToken, runnerTemporaryPath, chownFilesTo, unityLicensingServer, } = parameters; + const githubHome = path_1.default.join(runnerTemporaryPath, '_github_home'); + if (!(0, fs_1.existsSync)(githubHome)) + (0, fs_1.mkdirSync)(githubHome); + const cidfile = containerIdFilePath(parameters); + const githubWorkflow = path_1.default.join(runnerTemporaryPath, '_github_workflow'); + if (!(0, fs_1.existsSync)(githubWorkflow)) + (0, fs_1.mkdirSync)(githubWorkflow); + const testPlatforms = (testMode === 'all' ? ['playmode', 'editmode', 'COMBINE_RESULTS'] : [testMode]).join(';'); return `docker run \ - --workdir /github/workspace \ + --workdir "c:/github/workspace" \ --cidfile "${cidfile}" \ --rm \ --env UNITY_LICENSE \ @@ -359,7 +359,7 @@ const Docker = { --env GITHUB_HEAD_REF \ --env GITHUB_BASE_REF \ --env GITHUB_EVENT_NAME \ - --env GITHUB_WORKSPACE="/github/workspace" \ + --env GITHUB_WORKSPACE="c:/github/workspace" \ --env GITHUB_ACTION \ --env GITHUB_EVENT_PATH \ --env RUNNER_OS \ @@ -376,16 +376,16 @@ const Docker = { --volume "${actionFolder}/steps":"c:/steps" \ --volume "${actionFolder}":"c:/dist" \ ${sshAgent ? `--volume ${sshAgent}:c:/ssh-agent` : ''} \ - ${sshAgent - ? `--volume c:/Users/Administrator/.ssh/known_hosts:c:/root/.ssh/known_hosts` + ${sshAgent + ? `--volume c:/Users/Administrator/.ssh/known_hosts:c:/root/.ssh/known_hosts` : ''} \ ${useHostNetwork ? '--net=host' : ''} \ ${githubToken ? '--env USE_EXIT_CODE=false' : '--env USE_EXIT_CODE=true'} \ ${image} \ - powershell c:/dist/entrypoint.ps1`; - }, -}; -exports["default"] = Docker; + powershell c:/dist/entrypoint.ps1`; + }, +}; +exports["default"] = Docker; /***/ }), @@ -394,134 +394,134 @@ exports["default"] = Docker; /***/ (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 { editorVersion = '2019.2.11f1', targetPlatform = ImageTag.getImagePlatformType(process.platform), customImage, } = imageProperties; - if (!ImageTag.versionPattern.test(editorVersion)) { - throw new Error(`Invalid version "${editorVersion}".`); - } - // Either - this.customImage = customImage; - // Or - this.repository = 'unityci'; - this.name = 'editor'; - this.editorVersion = editorVersion; - this.targetPlatform = targetPlatform; - this.targetPlatformSuffix = ImageTag.getTargetPlatformSuffix(targetPlatform, editorVersion); - this.imagePlatformPrefix = ImageTag.getImagePlatformPrefix(process.platform); - this.imageRollingVersion = 1; - } - static get versionPattern() { - return /^20\d{2}\.\d\.\w{3,4}|3$/; - } - static get targetPlatformSuffixes() { - return { - generic: '', - webgl: 'webgl', - mac: 'mac-mono', - windows: 'windows-il2cpp', - linux: 'base', - linuxIl2cpp: 'linux-il2cpp', - android: 'android', - ios: 'ios', - facebook: 'facebook', - }; - } - static getImagePlatformPrefix(platform) { - switch (platform) { - case 'linux': - return 'ubuntu'; - case 'win32': - return 'windows'; - default: - throw new Error(`The Operating System of this runner, "${platform}", is not yet supported.`); - } - } - static getImagePlatformType(platform) { - switch (platform) { - case 'linux': - return platform_1.default.types.StandaloneLinux64; - case 'win32': - return platform_1.default.types.StandaloneWindows; - default: - throw new Error(`The Operating System of this runner, "${platform}", is not yet supported.`); - } - } - static getTargetPlatformSuffix(targetPlatform, editorVersion) { - const { generic, webgl, mac, windows, linux, linuxIl2cpp, android, ios, facebook } = ImageTag.targetPlatformSuffixes; - const [major, minor] = editorVersion.split('.').map(digit => Number(digit)); - // @see: https://docs.unity3d.com/ScriptReference/BuildTarget.html - switch (targetPlatform) { - case platform_1.default.types.StandaloneOSX: - return mac; - case platform_1.default.types.StandaloneWindows: - return windows; - case platform_1.default.types.StandaloneWindows64: - 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: - return windows; - case platform_1.default.types.PS4: - return windows; - case platform_1.default.types.XboxOne: - return windows; - case platform_1.default.types.tvOS: - return windows; - 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: + +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 { editorVersion = '2019.2.11f1', targetPlatform = ImageTag.getImagePlatformType(process.platform), customImage, } = imageProperties; + if (!ImageTag.versionPattern.test(editorVersion)) { + throw new Error(`Invalid version "${editorVersion}".`); + } + // Either + this.customImage = customImage; + // Or + this.repository = 'unityci'; + this.name = 'editor'; + this.editorVersion = editorVersion; + this.targetPlatform = targetPlatform; + this.targetPlatformSuffix = ImageTag.getTargetPlatformSuffix(targetPlatform, editorVersion); + this.imagePlatformPrefix = ImageTag.getImagePlatformPrefix(process.platform); + this.imageRollingVersion = 1; + } + static get versionPattern() { + return /^20\d{2}\.\d\.\w{3,4}|3$/; + } + static get targetPlatformSuffixes() { + return { + generic: '', + webgl: 'webgl', + mac: 'mac-mono', + windows: 'windows-il2cpp', + linux: 'base', + linuxIl2cpp: 'linux-il2cpp', + android: 'android', + ios: 'ios', + facebook: 'facebook', + }; + } + static getImagePlatformPrefix(platform) { + switch (platform) { + case 'linux': + return 'ubuntu'; + case 'win32': + return 'windows'; + default: + throw new Error(`The Operating System of this runner, "${platform}", is not yet supported.`); + } + } + static getImagePlatformType(platform) { + switch (platform) { + case 'linux': + return platform_1.default.types.StandaloneLinux64; + case 'win32': + return platform_1.default.types.StandaloneWindows; + default: + throw new Error(`The Operating System of this runner, "${platform}", is not yet supported.`); + } + } + static getTargetPlatformSuffix(targetPlatform, editorVersion) { + const { generic, webgl, mac, windows, linux, linuxIl2cpp, android, ios, facebook } = ImageTag.targetPlatformSuffixes; + const [major, minor] = editorVersion.split('.').map(digit => Number(digit)); + // @see: https://docs.unity3d.com/ScriptReference/BuildTarget.html + switch (targetPlatform) { + case platform_1.default.types.StandaloneOSX: + return mac; + case platform_1.default.types.StandaloneWindows: + return windows; + case platform_1.default.types.StandaloneWindows64: + 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: + return windows; + case platform_1.default.types.PS4: + return windows; + case platform_1.default.types.XboxOne: + return windows; + case platform_1.default.types.tvOS: + return windows; + 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. - "${targetPlatform}" is currently not supported.`); - } - } - get tag() { - const versionAndTarget = `${this.editorVersion}-${this.targetPlatformSuffix}`.replace(/-+$/, ''); - return `${this.imagePlatformPrefix}-${versionAndTarget}-${this.imageRollingVersion}`; - } - get image() { - return `${this.repository}/${this.name}`.replace(/^\/+/, ''); - } - toString() { - const { image, tag, customImage } = this; - if (customImage) - return customImage; - return `${image}:${tag}`; - } -} -exports["default"] = ImageTag; + "${targetPlatform}" is currently not supported.`); + } + } + get tag() { + const versionAndTarget = `${this.editorVersion}-${this.targetPlatformSuffix}`.replace(/-+$/, ''); + return `${this.imagePlatformPrefix}-${versionAndTarget}-${this.imageRollingVersion}`; + } + get image() { + return `${this.repository}/${this.name}`.replace(/^\/+/, ''); + } + toString() { + const { image, tag, customImage } = this; + if (customImage) + return customImage; + return `${image}:${tag}`; + } +} +exports["default"] = ImageTag; /***/ }), @@ -530,24 +530,24 @@ 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.ResultsCheck = exports.Output = exports.Input = exports.ImageTag = exports.Docker = exports.Action = void 0; -var action_1 = __nccwpck_require__(9088); -Object.defineProperty(exports, "Action", ({ enumerable: true, get: function () { return __importDefault(action_1).default; } })); -var docker_1 = __nccwpck_require__(6934); -Object.defineProperty(exports, "Docker", ({ enumerable: true, get: function () { return __importDefault(docker_1).default; } })); -var image_tag_1 = __nccwpck_require__(7648); -Object.defineProperty(exports, "ImageTag", ({ enumerable: true, get: function () { return __importDefault(image_tag_1).default; } })); -var input_1 = __nccwpck_require__(1933); -Object.defineProperty(exports, "Input", ({ enumerable: true, get: function () { return __importDefault(input_1).default; } })); -var output_1 = __nccwpck_require__(5487); -Object.defineProperty(exports, "Output", ({ enumerable: true, get: function () { return __importDefault(output_1).default; } })); -var results_check_1 = __nccwpck_require__(9183); -Object.defineProperty(exports, "ResultsCheck", ({ enumerable: true, get: function () { return __importDefault(results_check_1).default; } })); + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ResultsCheck = exports.Output = exports.Input = exports.ImageTag = exports.Docker = exports.Action = void 0; +var action_1 = __nccwpck_require__(9088); +Object.defineProperty(exports, "Action", ({ enumerable: true, get: function () { return __importDefault(action_1).default; } })); +var docker_1 = __nccwpck_require__(6934); +Object.defineProperty(exports, "Docker", ({ enumerable: true, get: function () { return __importDefault(docker_1).default; } })); +var image_tag_1 = __nccwpck_require__(7648); +Object.defineProperty(exports, "ImageTag", ({ enumerable: true, get: function () { return __importDefault(image_tag_1).default; } })); +var input_1 = __nccwpck_require__(1933); +Object.defineProperty(exports, "Input", ({ enumerable: true, get: function () { return __importDefault(input_1).default; } })); +var output_1 = __nccwpck_require__(5487); +Object.defineProperty(exports, "Output", ({ enumerable: true, get: function () { return __importDefault(output_1).default; } })); +var results_check_1 = __nccwpck_require__(9183); +Object.defineProperty(exports, "ResultsCheck", ({ enumerable: true, get: function () { return __importDefault(results_check_1).default; } })); /***/ }), @@ -556,129 +556,129 @@ Object.defineProperty(exports, "ResultsCheck", ({ enumerable: true, get: functio /***/ (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 unity_version_parser_1 = __importDefault(__nccwpck_require__(7049)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const core_1 = __nccwpck_require__(2186); -const Input = { - get testModes() { - return ['all', 'playmode', 'editmode', 'standalone']; - }, - isValidFolderName(folderName) { - const validFolderName = new RegExp(/^(\.|\.\/)?(\.?[\w~]+([ _-]?[\w~]+)*\/?)*$/); - return validFolderName.test(folderName); - }, - /** - * When in package mode, we need to scrape the package's name from its package.json file - */ - getPackageNameFromPackageJson(packagePath) { - const packageJsonPath = `${packagePath}/package.json`; - if (!fs_1.default.existsSync(packageJsonPath)) { - throw new Error(`Invalid projectPath - Cannot find package.json at ${packageJsonPath}`); - } - let packageJson; - try { - packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath).toString()); - } - catch (error) { - if (error instanceof SyntaxError) { - throw new SyntaxError(`Unable to parse package.json contents as JSON - ${error.message}`); - } - throw new Error(`Unable to parse package.json contents as JSON - unknown error ocurred`); - } - const rawPackageName = packageJson.name; - if (typeof rawPackageName !== 'string') { - throw new TypeError(`Unable to parse package name from package.json - package name should be string, but was ${typeof rawPackageName}`); - } - if (rawPackageName.length === 0) { - throw new Error(`Package name from package.json is a string, but is empty`); - } - return rawPackageName; - }, - /** - * When in package mode, we need to ensure that the Tests folder is present - */ - verifyTestsFolderIsPresent(packagePath) { - if (!fs_1.default.existsSync(`${packagePath}/Tests`)) { - throw new Error(`Invalid projectPath - Cannot find package tests folder at ${packagePath}/Tests`); - } - }, - getFromUser() { - // Input variables specified in workflow using "with" prop. - const unityVersion = (0, core_1.getInput)('unityVersion') || 'auto'; - const customImage = (0, core_1.getInput)('customImage') || ''; - const rawProjectPath = (0, core_1.getInput)('projectPath') || '.'; - const unityLicensingServer = (0, core_1.getInput)('unityLicensingServer') || ''; - const customParameters = (0, core_1.getInput)('customParameters') || ''; - const testMode = ((0, core_1.getInput)('testMode') || 'all').toLowerCase(); - const coverageOptions = (0, core_1.getInput)('coverageOptions') || ''; - const rawArtifactsPath = (0, core_1.getInput)('artifactsPath') || 'artifacts'; - const rawUseHostNetwork = (0, core_1.getInput)('useHostNetwork') || 'false'; - const sshAgent = (0, core_1.getInput)('sshAgent') || ''; - const gitPrivateToken = (0, core_1.getInput)('gitPrivateToken') || ''; - const githubToken = (0, core_1.getInput)('githubToken') || ''; - const checkName = (0, core_1.getInput)('checkName') || 'Test Results'; - const rawPackageMode = (0, core_1.getInput)('packageMode') || 'false'; - let packageName = ''; - const chownFilesTo = (0, core_1.getInput)('chownFilesTo') || ''; - // Validate input - if (!this.testModes.includes(testMode)) { - throw new Error(`Invalid testMode ${testMode}`); - } - if (!this.isValidFolderName(rawProjectPath)) { - throw new Error(`Invalid projectPath "${rawProjectPath}"`); - } - if (!this.isValidFolderName(rawArtifactsPath)) { - throw new Error(`Invalid artifactsPath "${rawArtifactsPath}"`); - } - if (rawUseHostNetwork !== 'true' && rawUseHostNetwork !== 'false') { - throw new Error(`Invalid useHostNetwork "${rawUseHostNetwork}"`); - } - if (rawPackageMode !== 'true' && rawPackageMode !== 'false') { - throw new Error(`Invalid packageMode "${rawPackageMode}"`); - } - // sanitize packageMode input and projectPath input since they are needed - // for input validation - const packageMode = rawPackageMode === 'true'; - const projectPath = rawProjectPath.replace(/\/$/, ''); - // if in package mode, attempt to get the package's name, and ensure tests are present - if (packageMode) { - if (unityVersion === 'auto') { - throw new Error('Package Mode is enabled, but unityVersion is set to "auto". unityVersion must manually be set in Package Mode.'); - } - packageName = this.getPackageNameFromPackageJson(projectPath); - this.verifyTestsFolderIsPresent(projectPath); - } - // Sanitise other input - const artifactsPath = rawArtifactsPath.replace(/\/$/, ''); - const useHostNetwork = rawUseHostNetwork === 'true'; - const editorVersion = unityVersion === 'auto' ? unity_version_parser_1.default.read(projectPath) : unityVersion; - // Return sanitised input - return { - editorVersion, - customImage, - projectPath, - customParameters, - testMode, - coverageOptions, - artifactsPath, - useHostNetwork, - sshAgent, - gitPrivateToken, - githubToken, - checkName, - packageMode, - packageName, - chownFilesTo, - unityLicensingServer, - }; - }, -}; -exports["default"] = Input; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const unity_version_parser_1 = __importDefault(__nccwpck_require__(7049)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const core_1 = __nccwpck_require__(2186); +const Input = { + get testModes() { + return ['all', 'playmode', 'editmode', 'standalone']; + }, + isValidFolderName(folderName) { + const validFolderName = new RegExp(/^(\.|\.\/)?(\.?[\w~]+([ _-]?[\w~]+)*\/?)*$/); + return validFolderName.test(folderName); + }, + /** + * When in package mode, we need to scrape the package's name from its package.json file + */ + getPackageNameFromPackageJson(packagePath) { + const packageJsonPath = `${packagePath}/package.json`; + if (!fs_1.default.existsSync(packageJsonPath)) { + throw new Error(`Invalid projectPath - Cannot find package.json at ${packageJsonPath}`); + } + let packageJson; + try { + packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath).toString()); + } + catch (error) { + if (error instanceof SyntaxError) { + throw new SyntaxError(`Unable to parse package.json contents as JSON - ${error.message}`); + } + throw new Error(`Unable to parse package.json contents as JSON - unknown error ocurred`); + } + const rawPackageName = packageJson.name; + if (typeof rawPackageName !== 'string') { + throw new TypeError(`Unable to parse package name from package.json - package name should be string, but was ${typeof rawPackageName}`); + } + if (rawPackageName.length === 0) { + throw new Error(`Package name from package.json is a string, but is empty`); + } + return rawPackageName; + }, + /** + * When in package mode, we need to ensure that the Tests folder is present + */ + verifyTestsFolderIsPresent(packagePath) { + if (!fs_1.default.existsSync(`${packagePath}/Tests`)) { + throw new Error(`Invalid projectPath - Cannot find package tests folder at ${packagePath}/Tests`); + } + }, + getFromUser() { + // Input variables specified in workflow using "with" prop. + const unityVersion = (0, core_1.getInput)('unityVersion') || 'auto'; + const customImage = (0, core_1.getInput)('customImage') || ''; + const rawProjectPath = (0, core_1.getInput)('projectPath') || '.'; + const unityLicensingServer = (0, core_1.getInput)('unityLicensingServer') || ''; + const customParameters = (0, core_1.getInput)('customParameters') || ''; + const testMode = ((0, core_1.getInput)('testMode') || 'all').toLowerCase(); + const coverageOptions = (0, core_1.getInput)('coverageOptions') || ''; + const rawArtifactsPath = (0, core_1.getInput)('artifactsPath') || 'artifacts'; + const rawUseHostNetwork = (0, core_1.getInput)('useHostNetwork') || 'false'; + const sshAgent = (0, core_1.getInput)('sshAgent') || ''; + const gitPrivateToken = (0, core_1.getInput)('gitPrivateToken') || ''; + const githubToken = (0, core_1.getInput)('githubToken') || ''; + const checkName = (0, core_1.getInput)('checkName') || 'Test Results'; + const rawPackageMode = (0, core_1.getInput)('packageMode') || 'false'; + let packageName = ''; + const chownFilesTo = (0, core_1.getInput)('chownFilesTo') || ''; + // Validate input + if (!this.testModes.includes(testMode)) { + throw new Error(`Invalid testMode ${testMode}`); + } + if (!this.isValidFolderName(rawProjectPath)) { + throw new Error(`Invalid projectPath "${rawProjectPath}"`); + } + if (!this.isValidFolderName(rawArtifactsPath)) { + throw new Error(`Invalid artifactsPath "${rawArtifactsPath}"`); + } + if (rawUseHostNetwork !== 'true' && rawUseHostNetwork !== 'false') { + throw new Error(`Invalid useHostNetwork "${rawUseHostNetwork}"`); + } + if (rawPackageMode !== 'true' && rawPackageMode !== 'false') { + throw new Error(`Invalid packageMode "${rawPackageMode}"`); + } + // sanitize packageMode input and projectPath input since they are needed + // for input validation + const packageMode = rawPackageMode === 'true'; + const projectPath = rawProjectPath.replace(/\/$/, ''); + // if in package mode, attempt to get the package's name, and ensure tests are present + if (packageMode) { + if (unityVersion === 'auto') { + throw new Error('Package Mode is enabled, but unityVersion is set to "auto". unityVersion must manually be set in Package Mode.'); + } + packageName = this.getPackageNameFromPackageJson(projectPath); + this.verifyTestsFolderIsPresent(projectPath); + } + // Sanitise other input + const artifactsPath = rawArtifactsPath.replace(/\/$/, ''); + const useHostNetwork = rawUseHostNetwork === 'true'; + const editorVersion = unityVersion === 'auto' ? unity_version_parser_1.default.read(projectPath) : unityVersion; + // Return sanitised input + return { + editorVersion, + customImage, + projectPath, + customParameters, + testMode, + coverageOptions, + artifactsPath, + useHostNetwork, + sshAgent, + gitPrivateToken, + githubToken, + checkName, + packageMode, + packageName, + chownFilesTo, + unityLicensingServer, + }; + }, +}; +exports["default"] = Input; /***/ }), @@ -687,50 +687,50 @@ exports["default"] = Input; /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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__(2186)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -class LicensingServerSetup { - static Setup(unityLicensingServer, actionFolder) { - const servicesConfigPath = `${actionFolder}/unity-config/services-config.json`; - const servicesConfigPathTemplate = `${servicesConfigPath}.template`; - if (!fs_1.default.existsSync(servicesConfigPathTemplate)) { - core.error(`Missing services config ${servicesConfigPathTemplate}`); - return; - } - let servicesConfig = fs_1.default.readFileSync(servicesConfigPathTemplate).toString(); - servicesConfig = servicesConfig.replace('%URL%', unityLicensingServer); - fs_1.default.writeFileSync(servicesConfigPath, servicesConfig); - } -} -exports["default"] = LicensingServerSetup; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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__(2186)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +class LicensingServerSetup { + static Setup(unityLicensingServer, actionFolder) { + const servicesConfigPath = `${actionFolder}/unity-config/services-config.json`; + const servicesConfigPathTemplate = `${servicesConfigPath}.template`; + if (!fs_1.default.existsSync(servicesConfigPathTemplate)) { + core.error(`Missing services config ${servicesConfigPathTemplate}`); + return; + } + let servicesConfig = fs_1.default.readFileSync(servicesConfigPathTemplate).toString(); + servicesConfig = servicesConfig.replace('%URL%', unityLicensingServer); + fs_1.default.writeFileSync(servicesConfigPath, servicesConfig); + } +} +exports["default"] = LicensingServerSetup; /***/ }), @@ -739,54 +739,54 @@ exports["default"] = LicensingServerSetup; /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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__(2186)); -const Output = { - setArtifactsPath(artifactsPath) { - return __awaiter(this, void 0, void 0, function* () { - yield core.setOutput('artifactsPath', artifactsPath); - }); - }, - setCoveragePath(coveragePath) { - return __awaiter(this, void 0, void 0, function* () { - yield core.setOutput('coveragePath', coveragePath); - }); - }, -}; -exports["default"] = Output; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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__(2186)); +const Output = { + setArtifactsPath(artifactsPath) { + return __awaiter(this, void 0, void 0, function* () { + yield core.setOutput('artifactsPath', artifactsPath); + }); + }, + setCoveragePath(coveragePath) { + return __awaiter(this, void 0, void 0, function* () { + yield core.setOutput('coveragePath', coveragePath); + }); + }, +}; +exports["default"] = Output; /***/ }), @@ -795,55 +795,55 @@ exports["default"] = Output; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const Platform = { - get default() { - return Platform.types.StandaloneWindows64; - }, - 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', - }; - }, - isWindows(platform) { - switch (platform) { - case Platform.types.StandaloneWindows: - case Platform.types.StandaloneWindows64: - return true; - default: - return false; - } - }, - isAndroid(platform) { - switch (platform) { - case Platform.types.Android: - return true; - default: - return false; - } - }, -}; -exports["default"] = Platform; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const Platform = { + get default() { + return Platform.types.StandaloneWindows64; + }, + 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', + }; + }, + isWindows(platform) { + switch (platform) { + case Platform.types.StandaloneWindows: + case Platform.types.StandaloneWindows64: + return true; + default: + return false; + } + }, + isAndroid(platform) { + switch (platform) { + case Platform.types.Android: + return true; + default: + return false; + } + }, +}; +exports["default"] = Platform; /***/ }), @@ -852,150 +852,150 @@ exports["default"] = Platform; /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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__(2186)); -const fs = __importStar(__nccwpck_require__(7147)); -const github = __importStar(__nccwpck_require__(5438)); -const handlebars_1 = __importDefault(__nccwpck_require__(7492)); -const results_parser_1 = __importDefault(__nccwpck_require__(4552)); -const results_meta_1 = __nccwpck_require__(5552); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const ResultsCheck = { - createCheck(artifactsPath, githubToken, checkName) { - return __awaiter(this, void 0, void 0, function* () { - // Validate input - if (!fs.existsSync(artifactsPath) || !githubToken || !checkName) { - throw new Error(`Missing input! {"artifactsPath": "${artifactsPath}", "githubToken": "${githubToken}, "checkName": "${checkName}"`); - } - // Parse all results files - const runs = []; - const files = fs.readdirSync(artifactsPath); - yield Promise.all(files.map((filepath) => __awaiter(this, void 0, void 0, function* () { - if (!filepath.endsWith('.xml')) - return; - core.info(`Processing file ${filepath}...`); - const fileData = yield results_parser_1.default.parseResults(path_1.default.join(artifactsPath, filepath)); - core.info(fileData.summary); - runs.push(fileData); - }))); - // Combine all results into a single run summary - const runSummary = new results_meta_1.RunMeta(checkName); - for (const run of runs) { - runSummary.total += run.total; - runSummary.passed += run.passed; - runSummary.skipped += run.skipped; - runSummary.failed += run.failed; - runSummary.duration += run.duration; - for (const suite of run.suites) { - runSummary.addTests(suite.tests); - } - } - // Log - core.info('================='); - core.info('Analyze result:'); - core.info(runSummary.summary); - // Format output - const title = runSummary.summary; - const summary = yield ResultsCheck.renderSummary(runs); - core.debug(`Summary view: ${summary}`); - const details = yield ResultsCheck.renderDetails(runs); - core.debug(`Details view: ${details}`); - const rawAnnotations = runSummary.extractAnnotations(); - core.debug(`Raw annotations: ${rawAnnotations}`); - const annotations = rawAnnotations.map(rawAnnotation => { - const annotation = rawAnnotation; - annotation.path = rawAnnotation.path.replace('/github/workspace/', ''); - return annotation; - }); - core.debug(`Annotations: ${annotations}`); - const output = { - title, - summary, - text: details, - annotations: annotations.slice(0, 50), - }; - // Call GitHub API - yield ResultsCheck.requestGitHubCheck(githubToken, checkName, output); - return runSummary.failed; - }); - }, - requestGitHubCheck(githubToken, checkName, output) { - return __awaiter(this, void 0, void 0, function* () { - const pullRequest = github.context.payload.pull_request; - const headSha = (pullRequest && pullRequest.head.sha) || github.context.sha; - const maxLength = 65534; - if (output.length > maxLength) { - core.warning(`Output too long (${output.length}) truncating to ${maxLength}`); - output = output.slice(0, maxLength); - } - core.info(`Posting results for ${headSha}`); - const createCheckRequest = Object.assign(Object.assign({}, github.context.repo), { name: checkName, head_sha: headSha, status: 'completed', conclusion: 'neutral', output }); - const octokit = github.getOctokit(githubToken); - yield octokit.rest.checks.create(createCheckRequest); - }); - }, - renderSummary(runMetas) { - return __awaiter(this, void 0, void 0, function* () { - return ResultsCheck.render(`${__dirname}/results-check-summary.hbs`, runMetas); - }); - }, - renderDetails(runMetas) { - return __awaiter(this, void 0, void 0, function* () { - return ResultsCheck.render(`${__dirname}/results-check-details.hbs`, runMetas); - }); - }, - render(viewPath, runMetas) { - return __awaiter(this, void 0, void 0, function* () { - handlebars_1.default.registerHelper('indent', toIndent => toIndent - .split('\n') - .map(s => ` ${s.replace('/github/workspace/', '')}`) - .join('\n')); - const source = yield fs.promises.readFile(viewPath, 'utf8'); - const template = handlebars_1.default.compile(source); - return template({ runs: runMetas }, { - allowProtoMethodsByDefault: true, - allowProtoPropertiesByDefault: true, - }); - }); - }, -}; -exports["default"] = ResultsCheck; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const github = __importStar(__nccwpck_require__(5438)); +const handlebars_1 = __importDefault(__nccwpck_require__(7492)); +const results_parser_1 = __importDefault(__nccwpck_require__(4552)); +const results_meta_1 = __nccwpck_require__(5552); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const ResultsCheck = { + createCheck(artifactsPath, githubToken, checkName) { + return __awaiter(this, void 0, void 0, function* () { + // Validate input + if (!fs.existsSync(artifactsPath) || !githubToken || !checkName) { + throw new Error(`Missing input! {"artifactsPath": "${artifactsPath}", "githubToken": "${githubToken}, "checkName": "${checkName}"`); + } + // Parse all results files + const runs = []; + const files = fs.readdirSync(artifactsPath); + yield Promise.all(files.map((filepath) => __awaiter(this, void 0, void 0, function* () { + if (!filepath.endsWith('.xml')) + return; + core.info(`Processing file ${filepath}...`); + const fileData = yield results_parser_1.default.parseResults(path_1.default.join(artifactsPath, filepath)); + core.info(fileData.summary); + runs.push(fileData); + }))); + // Combine all results into a single run summary + const runSummary = new results_meta_1.RunMeta(checkName); + for (const run of runs) { + runSummary.total += run.total; + runSummary.passed += run.passed; + runSummary.skipped += run.skipped; + runSummary.failed += run.failed; + runSummary.duration += run.duration; + for (const suite of run.suites) { + runSummary.addTests(suite.tests); + } + } + // Log + core.info('================='); + core.info('Analyze result:'); + core.info(runSummary.summary); + // Format output + const title = runSummary.summary; + const summary = yield ResultsCheck.renderSummary(runs); + core.debug(`Summary view: ${summary}`); + const details = yield ResultsCheck.renderDetails(runs); + core.debug(`Details view: ${details}`); + const rawAnnotations = runSummary.extractAnnotations(); + core.debug(`Raw annotations: ${rawAnnotations}`); + const annotations = rawAnnotations.map(rawAnnotation => { + const annotation = rawAnnotation; + annotation.path = rawAnnotation.path.replace('/github/workspace/', ''); + return annotation; + }); + core.debug(`Annotations: ${annotations}`); + const output = { + title, + summary, + text: details, + annotations: annotations.slice(0, 50), + }; + // Call GitHub API + yield ResultsCheck.requestGitHubCheck(githubToken, checkName, output); + return runSummary.failed; + }); + }, + requestGitHubCheck(githubToken, checkName, output) { + return __awaiter(this, void 0, void 0, function* () { + const pullRequest = github.context.payload.pull_request; + const headSha = (pullRequest && pullRequest.head.sha) || github.context.sha; + const maxLength = 65534; + if (output.length > maxLength) { + core.warning(`Output too long (${output.length}) truncating to ${maxLength}`); + output = output.slice(0, maxLength); + } + core.info(`Posting results for ${headSha}`); + const createCheckRequest = Object.assign(Object.assign({}, github.context.repo), { name: checkName, head_sha: headSha, status: 'completed', conclusion: 'neutral', output }); + const octokit = github.getOctokit(githubToken); + yield octokit.rest.checks.create(createCheckRequest); + }); + }, + renderSummary(runMetas) { + return __awaiter(this, void 0, void 0, function* () { + return ResultsCheck.render(`${__dirname}/results-check-summary.hbs`, runMetas); + }); + }, + renderDetails(runMetas) { + return __awaiter(this, void 0, void 0, function* () { + return ResultsCheck.render(`${__dirname}/results-check-details.hbs`, runMetas); + }); + }, + render(viewPath, runMetas) { + return __awaiter(this, void 0, void 0, function* () { + handlebars_1.default.registerHelper('indent', toIndent => toIndent + .split('\n') + .map(s => ` ${s.replace('/github/workspace/', '')}`) + .join('\n')); + const source = yield fs.promises.readFile(viewPath, 'utf8'); + const template = handlebars_1.default.compile(source); + return template({ runs: runMetas }, { + allowProtoMethodsByDefault: true, + allowProtoPropertiesByDefault: true, + }); + }); + }, +}; +exports["default"] = ResultsCheck; /***/ }), @@ -1004,112 +1004,112 @@ exports["default"] = ResultsCheck; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TestMeta = exports.RunMeta = exports.Meta = exports.timeHelper = void 0; -function timeHelper(seconds) { - return `${seconds.toFixed(3)}s`; -} -exports.timeHelper = timeHelper; -class Meta { - constructor(title) { - this.duration = 0; - this.title = title; - } -} -exports.Meta = Meta; -class RunMeta extends Meta { - constructor() { - super(...arguments); - this.total = 0; - this.passed = 0; - this.skipped = 0; - this.failed = 0; - this.tests = []; - this.suites = []; - } - extractAnnotations() { - const result = []; - for (const suite of this.suites) { - result.push(...suite.extractAnnotations()); - } - for (const test of this.tests) { - if (test.annotation !== undefined) { - result.push(test.annotation); - } - } - return result; - } - addTests(testSuite) { - for (const test of testSuite) { - this.addTest(test); - } - } - addTest(test) { - if (test.suite === undefined) { - return; - } - if (test.suite === this.title) { - this.total++; - this.duration += test.duration; - this.tests.push(test); - if (test.result === 'Passed') - this.passed++; - else if (test.result === 'Failed') - this.failed++; - else - this.skipped++; - return; - } - let target = this.suites.find(s => s.title === test.suite); - if (target === undefined) { - target = new RunMeta(test.suite); - this.suites.push(target); - } - target.addTest(test); - } - get summary() { - const result = this.failed > 0 ? 'Failed' : 'Passed'; - const sPart = this.skipped > 0 ? `, skipped: ${this.skipped}` : ''; - const fPart = this.failed > 0 ? `, failed: ${this.failed}` : ''; - const dPart = ` in ${timeHelper(this.duration)}`; - return `${this.mark} ${this.title} - ${this.passed}/${this.total}${sPart}${fPart} - ${result}${dPart}`; - } - get mark() { - if (this.failed > 0) - return '❌️'; - else if (this.skipped === 0) - return '✅'; - return '⚠️'; - } -} -exports.RunMeta = RunMeta; -class TestMeta extends Meta { - constructor(suite, title) { - super(title); - this.suite = suite; - this.result = undefined; - this.duration = Number.NaN; - } - isSkipped() { - return this.result === 'Skipped'; - } - isFailed() { - return this.result === 'Failed'; - } - get summary() { - const dPart = this.isSkipped() ? '' : ` in ${timeHelper(this.duration)}`; - return `${this.mark} **${this.title}** - ${this.result}${dPart}`; - } - get mark() { - if (this.isFailed()) - return '❌️'; - else if (this.isSkipped()) - return '⚠️'; - return '✅'; - } -} -exports.TestMeta = TestMeta; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TestMeta = exports.RunMeta = exports.Meta = exports.timeHelper = void 0; +function timeHelper(seconds) { + return `${seconds.toFixed(3)}s`; +} +exports.timeHelper = timeHelper; +class Meta { + constructor(title) { + this.duration = 0; + this.title = title; + } +} +exports.Meta = Meta; +class RunMeta extends Meta { + constructor() { + super(...arguments); + this.total = 0; + this.passed = 0; + this.skipped = 0; + this.failed = 0; + this.tests = []; + this.suites = []; + } + extractAnnotations() { + const result = []; + for (const suite of this.suites) { + result.push(...suite.extractAnnotations()); + } + for (const test of this.tests) { + if (test.annotation !== undefined) { + result.push(test.annotation); + } + } + return result; + } + addTests(testSuite) { + for (const test of testSuite) { + this.addTest(test); + } + } + addTest(test) { + if (test.suite === undefined) { + return; + } + if (test.suite === this.title) { + this.total++; + this.duration += test.duration; + this.tests.push(test); + if (test.result === 'Passed') + this.passed++; + else if (test.result === 'Failed') + this.failed++; + else + this.skipped++; + return; + } + let target = this.suites.find(s => s.title === test.suite); + if (target === undefined) { + target = new RunMeta(test.suite); + this.suites.push(target); + } + target.addTest(test); + } + get summary() { + const result = this.failed > 0 ? 'Failed' : 'Passed'; + const sPart = this.skipped > 0 ? `, skipped: ${this.skipped}` : ''; + const fPart = this.failed > 0 ? `, failed: ${this.failed}` : ''; + const dPart = ` in ${timeHelper(this.duration)}`; + return `${this.mark} ${this.title} - ${this.passed}/${this.total}${sPart}${fPart} - ${result}${dPart}`; + } + get mark() { + if (this.failed > 0) + return '❌️'; + else if (this.skipped === 0) + return '✅'; + return '⚠️'; + } +} +exports.RunMeta = RunMeta; +class TestMeta extends Meta { + constructor(suite, title) { + super(title); + this.suite = suite; + this.result = undefined; + this.duration = Number.NaN; + } + isSkipped() { + return this.result === 'Skipped'; + } + isFailed() { + return this.result === 'Failed'; + } + get summary() { + const dPart = this.isSkipped() ? '' : ` in ${timeHelper(this.duration)}`; + return `${this.mark} **${this.title}** - ${this.result}${dPart}`; + } + get mark() { + if (this.isFailed()) + return '❌️'; + else if (this.isSkipped()) + return '⚠️'; + return '✅'; + } +} +exports.TestMeta = TestMeta; /***/ }), @@ -1118,179 +1118,179 @@ exports.TestMeta = TestMeta; /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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__(2186)); -const fs = __importStar(__nccwpck_require__(7147)); -const xmljs = __importStar(__nccwpck_require__(8821)); -const results_meta_1 = __nccwpck_require__(5552); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const ResultsParser = { - parseResults(filepath) { - return __awaiter(this, void 0, void 0, function* () { - if (!fs.existsSync(filepath)) { - throw new Error(`Missing file! {"filepath": "${filepath}"}`); - } - core.info(`Trying to open ${filepath}`); - const file = yield fs.promises.readFile(filepath, 'utf8'); - const results = xmljs.xml2js(file, { compact: true }); - core.info(`File ${filepath} parsed...`); - return ResultsParser.convertResults(path_1.default.basename(filepath), results); - }); - }, - convertResults(filename, filedata) { - core.info(`Start analyzing results: ${filename}`); - const run = filedata['test-run']; - const runMeta = new results_meta_1.RunMeta(filename); - const tests = ResultsParser.convertSuite(run['test-suite']); - core.debug(tests.toString()); - runMeta.total = Number(run._attributes.total); - runMeta.failed = Number(run._attributes.failed); - runMeta.skipped = Number(run._attributes.skipped); - runMeta.passed = Number(run._attributes.passed); - runMeta.duration = Number(run._attributes.duration); - runMeta.addTests(tests); - return runMeta; - }, - convertSuite(suites) { - if (Array.isArray(suites)) { - const innerResult = []; - for (const suite of suites) { - innerResult.push(...ResultsParser.convertSuite(suite)); - } - return innerResult; - } - const result = []; - const innerSuite = suites['test-suite']; - if (innerSuite) { - result.push(...ResultsParser.convertSuite(innerSuite)); - } - const tests = suites['test-case']; - if (tests) { - result.push(...ResultsParser.convertTests(suites._attributes.fullname, tests)); - } - return result; - }, - convertTests(suite, tests) { - if (Array.isArray(tests)) { - const result = []; - for (const testCase of tests) { - result.push(ResultsParser.convertTestCase(suite, testCase)); - } - return result; - } - return [ResultsParser.convertTestCase(suite, tests)]; - }, - convertTestCase(suite, testCase) { - const { _attributes, failure, output } = testCase; - const { name, fullname, result, duration } = _attributes; - const testMeta = new results_meta_1.TestMeta(suite, name); - testMeta.result = result; - testMeta.duration = Number(duration); - if (!failure) { - core.debug(`Skip test ${fullname} without failure data`); - return testMeta; - } - core.debug(`Convert data for test ${fullname}`); - if (failure['stack-trace'] === undefined) { - core.warning(`No stack trace for test case: ${fullname}`); - return testMeta; - } - const trace = failure['stack-trace']._cdata; - if (trace === undefined) { - core.warning(`No cdata in stack trace for test case: ${fullname}`); - return testMeta; - } - const point = ResultsParser.findAnnotationPoint(trace); - if (!point.path || !point.line) { - core.warning(`Not able to find annotation point for failed test! Test trace: ${trace}`); - return testMeta; - } - const rawDetails = [trace]; - if (output && output._cdata) { - rawDetails.unshift(output._cdata); - } - else { - core.debug(`No console output for test case: ${fullname}`); - } - testMeta.annotation = { - path: point.path, - start_line: point.line, - end_line: point.line, - annotation_level: 'failure', - title: fullname, - message: failure.message._cdata ? failure.message._cdata : 'Test Failed!', - raw_details: rawDetails.join('\n'), - start_column: 0, - end_column: 0, - blob_href: '', - }; - core.info(`- ${testMeta.annotation.path}:${testMeta.annotation.start_line} - ${testMeta.annotation.title}`); - return testMeta; - }, - findAnnotationPoint(trace) { - // Find first entry with non-zero line number in stack trace - const items = trace.match(/at .* in ((?[^:]+):(?\d+))/g); - if (Array.isArray(items)) { - const result = []; - for (const item of items) { - const match = item.match(/at .* in ((?[^:]+):(?\d+))/); - const point = { - path: match ? match.groups.path : '', - line: match ? Number(match.groups.line) : 0, - }; - if (point.line > 0) { - result.push(point); - } - } - if (result.length > 0) { - return result[0]; - } - } - // If all entries have zero line number match fallback pattern - const match = trace.match(/at .* in ((?[^:]+):(?\d+))/); - return { - path: match ? match.groups.path : '', - line: match ? Number(match.groups.line) : 0, - }; - }, -}; -exports["default"] = ResultsParser; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const xmljs = __importStar(__nccwpck_require__(8821)); +const results_meta_1 = __nccwpck_require__(5552); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const ResultsParser = { + parseResults(filepath) { + return __awaiter(this, void 0, void 0, function* () { + if (!fs.existsSync(filepath)) { + throw new Error(`Missing file! {"filepath": "${filepath}"}`); + } + core.info(`Trying to open ${filepath}`); + const file = yield fs.promises.readFile(filepath, 'utf8'); + const results = xmljs.xml2js(file, { compact: true }); + core.info(`File ${filepath} parsed...`); + return ResultsParser.convertResults(path_1.default.basename(filepath), results); + }); + }, + convertResults(filename, filedata) { + core.info(`Start analyzing results: ${filename}`); + const run = filedata['test-run']; + const runMeta = new results_meta_1.RunMeta(filename); + const tests = ResultsParser.convertSuite(run['test-suite']); + core.debug(tests.toString()); + runMeta.total = Number(run._attributes.total); + runMeta.failed = Number(run._attributes.failed); + runMeta.skipped = Number(run._attributes.skipped); + runMeta.passed = Number(run._attributes.passed); + runMeta.duration = Number(run._attributes.duration); + runMeta.addTests(tests); + return runMeta; + }, + convertSuite(suites) { + if (Array.isArray(suites)) { + const innerResult = []; + for (const suite of suites) { + innerResult.push(...ResultsParser.convertSuite(suite)); + } + return innerResult; + } + const result = []; + const innerSuite = suites['test-suite']; + if (innerSuite) { + result.push(...ResultsParser.convertSuite(innerSuite)); + } + const tests = suites['test-case']; + if (tests) { + result.push(...ResultsParser.convertTests(suites._attributes.fullname, tests)); + } + return result; + }, + convertTests(suite, tests) { + if (Array.isArray(tests)) { + const result = []; + for (const testCase of tests) { + result.push(ResultsParser.convertTestCase(suite, testCase)); + } + return result; + } + return [ResultsParser.convertTestCase(suite, tests)]; + }, + convertTestCase(suite, testCase) { + const { _attributes, failure, output } = testCase; + const { name, fullname, result, duration } = _attributes; + const testMeta = new results_meta_1.TestMeta(suite, name); + testMeta.result = result; + testMeta.duration = Number(duration); + if (!failure) { + core.debug(`Skip test ${fullname} without failure data`); + return testMeta; + } + core.debug(`Convert data for test ${fullname}`); + if (failure['stack-trace'] === undefined) { + core.warning(`No stack trace for test case: ${fullname}`); + return testMeta; + } + const trace = failure['stack-trace']._cdata; + if (trace === undefined) { + core.warning(`No cdata in stack trace for test case: ${fullname}`); + return testMeta; + } + const point = ResultsParser.findAnnotationPoint(trace); + if (!point.path || !point.line) { + core.warning(`Not able to find annotation point for failed test! Test trace: ${trace}`); + return testMeta; + } + const rawDetails = [trace]; + if (output && output._cdata) { + rawDetails.unshift(output._cdata); + } + else { + core.debug(`No console output for test case: ${fullname}`); + } + testMeta.annotation = { + path: point.path, + start_line: point.line, + end_line: point.line, + annotation_level: 'failure', + title: fullname, + message: failure.message._cdata ? failure.message._cdata : 'Test Failed!', + raw_details: rawDetails.join('\n'), + start_column: 0, + end_column: 0, + blob_href: '', + }; + core.info(`- ${testMeta.annotation.path}:${testMeta.annotation.start_line} - ${testMeta.annotation.title}`); + return testMeta; + }, + findAnnotationPoint(trace) { + // Find first entry with non-zero line number in stack trace + const items = trace.match(/at .* in ((?[^:]+):(?\d+))/g); + if (Array.isArray(items)) { + const result = []; + for (const item of items) { + const match = item.match(/at .* in ((?[^:]+):(?\d+))/); + const point = { + path: match ? match.groups.path : '', + line: match ? Number(match.groups.line) : 0, + }; + if (point.line > 0) { + result.push(point); + } + } + if (result.length > 0) { + return result[0]; + } + } + // If all entries have zero line number match fallback pattern + const match = trace.match(/at .* in ((?[^:]+):(?\d+))/); + return { + path: match ? match.groups.path : '', + line: match ? Number(match.groups.line) : 0, + }; + }, +}; +exports["default"] = ResultsParser; /***/ }), @@ -1299,33 +1299,33 @@ exports["default"] = ResultsParser; /***/ (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__(7147)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const UnityVersionParser = { - get versionPattern() { - return /20\d{2}\.\d\.\w{3,4}|3/; - }, - parse(projectVersionTxt) { - const matches = projectVersionTxt.match(UnityVersionParser.versionPattern); - if (!matches || matches.length === 0) { - throw new Error(`Failed to parse version from "${projectVersionTxt}".`); - } - return matches[0]; - }, - read(projectPath) { - const filePath = path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); - if (!fs_1.default.existsSync(filePath)) { - throw new Error(`Project settings file not found at "${filePath}". Have you correctly set the projectPath?`); - } - return UnityVersionParser.parse(fs_1.default.readFileSync(filePath, 'utf8')); - }, -}; -exports["default"] = UnityVersionParser; + +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__(7147)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const UnityVersionParser = { + get versionPattern() { + return /20\d{2}\.\d\.\w{3,4}|3/; + }, + parse(projectVersionTxt) { + const matches = projectVersionTxt.match(UnityVersionParser.versionPattern); + if (!matches || matches.length === 0) { + throw new Error(`Failed to parse version from "${projectVersionTxt}".`); + } + return matches[0]; + }, + read(projectPath) { + const filePath = path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); + if (!fs_1.default.existsSync(filePath)) { + throw new Error(`Project settings file not found at "${filePath}". Have you correctly set the projectPath?`); + } + return UnityVersionParser.parse(fs_1.default.readFileSync(filePath, 'utf8')); + }, +}; +exports["default"] = UnityVersionParser; /***/ }), @@ -1334,59 +1334,59 @@ exports["default"] = UnityVersionParser; /***/ (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; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (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.run = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const action_1 = __importDefault(__nccwpck_require__(9088)); -const model_1 = __nccwpck_require__(1359); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - const parameters = action_1.default.runnerContext(); - yield model_1.Docker.ensureContainerRemoval(parameters); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.run = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const action_1 = __importDefault(__nccwpck_require__(9088)); +const model_1 = __nccwpck_require__(1359); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + const parameters = action_1.default.runnerContext(); + yield model_1.Docker.ensureContainerRemoval(parameters); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; /***/ }), @@ -1946,8 +1946,8 @@ class OidcClient { const res = yield httpclient .getJson(id_token_url) .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n Error Message: ${error.result.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; @@ -15093,1303 +15093,1303 @@ exports.parseURL = __nccwpck_require__(33).parseURL; /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -const punycode = __nccwpck_require__(5477); -const tr46 = __nccwpck_require__(2299); - -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__(5477); +const tr46 = __nccwpck_require__(2299); + +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 }); +}; /***/ }), @@ -19776,7 +19776,7 @@ IndexedSourceMapConsumer.prototype.sourceContentFor = * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. The - * line number is 1-based. + * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ @@ -22227,17 +22227,17 @@ function wrappy (fn, cb) { /***/ 1709: /***/ ((module) => { -module.exports = { - - isArray: function(value) { - if (Array.isArray) { - return Array.isArray(value); - } - // fallback for older browsers like IE 8 - return Object.prototype.toString.call( value ) === '[object Array]'; - } - -}; +module.exports = { + + isArray: function(value) { + if (Array.isArray) { + return Array.isArray(value); + } + // fallback for older browsers like IE 8 + return Object.prototype.toString.call( value ) === '[object Array]'; + } + +}; /***/ }), @@ -22245,19 +22245,19 @@ module.exports = { /***/ 8821: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*jslint node:true */ - -var xml2js = __nccwpck_require__(2903); -var xml2json = __nccwpck_require__(8919); -var js2xml = __nccwpck_require__(4453); -var json2xml = __nccwpck_require__(1900); - -module.exports = { - xml2js: xml2js, - xml2json: xml2json, - js2xml: js2xml, - json2xml: json2xml -}; +/*jslint node:true */ + +var xml2js = __nccwpck_require__(2903); +var xml2json = __nccwpck_require__(8919); +var js2xml = __nccwpck_require__(4453); +var json2xml = __nccwpck_require__(1900); + +module.exports = { + xml2js: xml2js, + xml2json: xml2json, + js2xml: js2xml, + json2xml: json2xml +}; /***/ }), @@ -22592,24 +22592,24 @@ module.exports = function (js, options) { /***/ 1900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var js2xml = __nccwpck_require__(4453); - -module.exports = function (json, options) { - if (json instanceof Buffer) { - json = json.toString(); - } - var js = null; - if (typeof (json) === 'string') { - try { - js = JSON.parse(json); - } catch (e) { - throw new Error('The JSON structure is invalid'); - } - } else { - js = json; - } - return js2xml(js, options); -}; +var js2xml = __nccwpck_require__(4453); + +module.exports = function (json, options) { + if (json instanceof Buffer) { + json = json.toString(); + } + var js = null; + if (typeof (json) === 'string') { + try { + js = JSON.parse(json); + } catch (e) { + throw new Error('The JSON structure is invalid'); + } + } else { + js = json; + } + return js2xml(js, options); +}; /***/ }), @@ -22617,49 +22617,49 @@ module.exports = function (json, options) { /***/ 6717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var isArray = (__nccwpck_require__(1709).isArray); - -module.exports = { - - copyOptions: function (options) { - var key, copy = {}; - for (key in options) { - if (options.hasOwnProperty(key)) { - copy[key] = options[key]; - } - } - return copy; - }, - - ensureFlagExists: function (item, options) { - if (!(item in options) || typeof options[item] !== 'boolean') { - options[item] = false; - } - }, - - ensureSpacesExists: function (options) { - if (!('spaces' in options) || (typeof options.spaces !== 'number' && typeof options.spaces !== 'string')) { - options.spaces = 0; - } - }, - - ensureAlwaysArrayExists: function (options) { - if (!('alwaysArray' in options) || (typeof options.alwaysArray !== 'boolean' && !isArray(options.alwaysArray))) { - options.alwaysArray = false; - } - }, - - ensureKeyExists: function (key, options) { - if (!(key + 'Key' in options) || typeof options[key + 'Key'] !== 'string') { - options[key + 'Key'] = options.compact ? '_' + key : key; - } - }, - - checkFnExists: function (key, options) { - return key + 'Fn' in options; - } - -}; +var isArray = (__nccwpck_require__(1709).isArray); + +module.exports = { + + copyOptions: function (options) { + var key, copy = {}; + for (key in options) { + if (options.hasOwnProperty(key)) { + copy[key] = options[key]; + } + } + return copy; + }, + + ensureFlagExists: function (item, options) { + if (!(item in options) || typeof options[item] !== 'boolean') { + options[item] = false; + } + }, + + ensureSpacesExists: function (options) { + if (!('spaces' in options) || (typeof options.spaces !== 'number' && typeof options.spaces !== 'string')) { + options.spaces = 0; + } + }, + + ensureAlwaysArrayExists: function (options) { + if (!('alwaysArray' in options) || (typeof options.alwaysArray !== 'boolean' && !isArray(options.alwaysArray))) { + options.alwaysArray = false; + } + }, + + ensureKeyExists: function (key, options) { + if (!(key + 'Key' in options) || typeof options[key + 'Key'] !== 'string') { + options[key + 'Key'] = options.compact ? '_' + key : key; + } + }, + + checkFnExists: function (key, options) { + return key + 'Fn' in options; + } + +}; /***/ }), @@ -22667,368 +22667,368 @@ module.exports = { /***/ 2903: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var sax = __nccwpck_require__(2043); -var expat /*= require('node-expat');*/ = { on: function () { }, parse: function () { } }; -var helper = __nccwpck_require__(6717); -var isArray = (__nccwpck_require__(1709).isArray); - -var options; -var pureJsParser = true; -var currentElement; - -function validateOptions(userOptions) { - options = helper.copyOptions(userOptions); - helper.ensureFlagExists('ignoreDeclaration', options); - helper.ensureFlagExists('ignoreInstruction', options); - helper.ensureFlagExists('ignoreAttributes', options); - helper.ensureFlagExists('ignoreText', options); - helper.ensureFlagExists('ignoreComment', options); - helper.ensureFlagExists('ignoreCdata', options); - helper.ensureFlagExists('ignoreDoctype', options); - helper.ensureFlagExists('compact', options); - helper.ensureFlagExists('alwaysChildren', options); - helper.ensureFlagExists('addParent', options); - helper.ensureFlagExists('trim', options); - helper.ensureFlagExists('nativeType', options); - helper.ensureFlagExists('nativeTypeAttributes', options); - helper.ensureFlagExists('sanitize', options); - helper.ensureFlagExists('instructionHasAttributes', options); - helper.ensureFlagExists('captureSpacesBetweenElements', options); - helper.ensureAlwaysArrayExists(options); - helper.ensureKeyExists('declaration', options); - helper.ensureKeyExists('instruction', options); - helper.ensureKeyExists('attributes', options); - helper.ensureKeyExists('text', options); - helper.ensureKeyExists('comment', options); - helper.ensureKeyExists('cdata', options); - helper.ensureKeyExists('doctype', options); - helper.ensureKeyExists('type', options); - helper.ensureKeyExists('name', options); - helper.ensureKeyExists('elements', options); - helper.ensureKeyExists('parent', options); - helper.checkFnExists('doctype', options); - helper.checkFnExists('instruction', options); - helper.checkFnExists('cdata', options); - helper.checkFnExists('comment', options); - helper.checkFnExists('text', options); - helper.checkFnExists('instructionName', options); - helper.checkFnExists('elementName', options); - helper.checkFnExists('attributeName', options); - helper.checkFnExists('attributeValue', options); - helper.checkFnExists('attributes', options); - return options; -} - -function nativeType(value) { - var nValue = Number(value); - if (!isNaN(nValue)) { - return nValue; - } - var bValue = value.toLowerCase(); - if (bValue === 'true') { - return true; - } else if (bValue === 'false') { - return false; - } - return value; -} - -function addField(type, value) { - var key; - if (options.compact) { - if ( - !currentElement[options[type + 'Key']] && - (isArray(options.alwaysArray) ? options.alwaysArray.indexOf(options[type + 'Key']) !== -1 : options.alwaysArray) - ) { - currentElement[options[type + 'Key']] = []; - } - if (currentElement[options[type + 'Key']] && !isArray(currentElement[options[type + 'Key']])) { - currentElement[options[type + 'Key']] = [currentElement[options[type + 'Key']]]; - } - if (type + 'Fn' in options && typeof value === 'string') { - value = options[type + 'Fn'](value, currentElement); - } - if (type === 'instruction' && ('instructionFn' in options || 'instructionNameFn' in options)) { - for (key in value) { - if (value.hasOwnProperty(key)) { - if ('instructionFn' in options) { - value[key] = options.instructionFn(value[key], key, currentElement); - } else { - var temp = value[key]; - delete value[key]; - value[options.instructionNameFn(key, temp, currentElement)] = temp; - } - } - } - } - if (isArray(currentElement[options[type + 'Key']])) { - currentElement[options[type + 'Key']].push(value); - } else { - currentElement[options[type + 'Key']] = value; - } - } else { - if (!currentElement[options.elementsKey]) { - currentElement[options.elementsKey] = []; - } - var element = {}; - element[options.typeKey] = type; - if (type === 'instruction') { - for (key in value) { - if (value.hasOwnProperty(key)) { - break; - } - } - element[options.nameKey] = 'instructionNameFn' in options ? options.instructionNameFn(key, value, currentElement) : key; - if (options.instructionHasAttributes) { - element[options.attributesKey] = value[key][options.attributesKey]; - if ('instructionFn' in options) { - element[options.attributesKey] = options.instructionFn(element[options.attributesKey], key, currentElement); - } - } else { - if ('instructionFn' in options) { - value[key] = options.instructionFn(value[key], key, currentElement); - } - element[options.instructionKey] = value[key]; - } - } else { - if (type + 'Fn' in options) { - value = options[type + 'Fn'](value, currentElement); - } - element[options[type + 'Key']] = value; - } - if (options.addParent) { - element[options.parentKey] = currentElement; - } - currentElement[options.elementsKey].push(element); - } -} - -function manipulateAttributes(attributes) { - if ('attributesFn' in options && attributes) { - attributes = options.attributesFn(attributes, currentElement); - } - if ((options.trim || 'attributeValueFn' in options || 'attributeNameFn' in options || options.nativeTypeAttributes) && attributes) { - var key; - for (key in attributes) { - if (attributes.hasOwnProperty(key)) { - if (options.trim) attributes[key] = attributes[key].trim(); - if (options.nativeTypeAttributes) { - attributes[key] = nativeType(attributes[key]); - } - if ('attributeValueFn' in options) attributes[key] = options.attributeValueFn(attributes[key], key, currentElement); - if ('attributeNameFn' in options) { - var temp = attributes[key]; - delete attributes[key]; - attributes[options.attributeNameFn(key, attributes[key], currentElement)] = temp; - } - } - } - } - return attributes; -} - -function onInstruction(instruction) { - var attributes = {}; - if (instruction.body && (instruction.name.toLowerCase() === 'xml' || options.instructionHasAttributes)) { - var attrsRegExp = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g; - var match; - while ((match = attrsRegExp.exec(instruction.body)) !== null) { - attributes[match[1]] = match[2] || match[3] || match[4]; - } - attributes = manipulateAttributes(attributes); - } - if (instruction.name.toLowerCase() === 'xml') { - if (options.ignoreDeclaration) { - return; - } - currentElement[options.declarationKey] = {}; - if (Object.keys(attributes).length) { - currentElement[options.declarationKey][options.attributesKey] = attributes; - } - if (options.addParent) { - currentElement[options.declarationKey][options.parentKey] = currentElement; - } - } else { - if (options.ignoreInstruction) { - return; - } - if (options.trim) { - instruction.body = instruction.body.trim(); - } - var value = {}; - if (options.instructionHasAttributes && Object.keys(attributes).length) { - value[instruction.name] = {}; - value[instruction.name][options.attributesKey] = attributes; - } else { - value[instruction.name] = instruction.body; - } - addField('instruction', value); - } -} - -function onStartElement(name, attributes) { - var element; - if (typeof name === 'object') { - attributes = name.attributes; - name = name.name; - } - attributes = manipulateAttributes(attributes); - if ('elementNameFn' in options) { - name = options.elementNameFn(name, currentElement); - } - if (options.compact) { - element = {}; - if (!options.ignoreAttributes && attributes && Object.keys(attributes).length) { - element[options.attributesKey] = {}; - var key; - for (key in attributes) { - if (attributes.hasOwnProperty(key)) { - element[options.attributesKey][key] = attributes[key]; - } - } - } - if ( - !(name in currentElement) && - (isArray(options.alwaysArray) ? options.alwaysArray.indexOf(name) !== -1 : options.alwaysArray) - ) { - currentElement[name] = []; - } - if (currentElement[name] && !isArray(currentElement[name])) { - currentElement[name] = [currentElement[name]]; - } - if (isArray(currentElement[name])) { - currentElement[name].push(element); - } else { - currentElement[name] = element; - } - } else { - if (!currentElement[options.elementsKey]) { - currentElement[options.elementsKey] = []; - } - element = {}; - element[options.typeKey] = 'element'; - element[options.nameKey] = name; - if (!options.ignoreAttributes && attributes && Object.keys(attributes).length) { - element[options.attributesKey] = attributes; - } - if (options.alwaysChildren) { - element[options.elementsKey] = []; - } - currentElement[options.elementsKey].push(element); - } - element[options.parentKey] = currentElement; // will be deleted in onEndElement() if !options.addParent - currentElement = element; -} - -function onText(text) { - if (options.ignoreText) { - return; - } - if (!text.trim() && !options.captureSpacesBetweenElements) { - return; - } - if (options.trim) { - text = text.trim(); - } - if (options.nativeType) { - text = nativeType(text); - } - if (options.sanitize) { - text = text.replace(/&/g, '&').replace(//g, '>'); - } - addField('text', text); -} - -function onComment(comment) { - if (options.ignoreComment) { - return; - } - if (options.trim) { - comment = comment.trim(); - } - addField('comment', comment); -} - -function onEndElement(name) { - var parentElement = currentElement[options.parentKey]; - if (!options.addParent) { - delete currentElement[options.parentKey]; - } - currentElement = parentElement; -} - -function onCdata(cdata) { - if (options.ignoreCdata) { - return; - } - if (options.trim) { - cdata = cdata.trim(); - } - addField('cdata', cdata); -} - -function onDoctype(doctype) { - if (options.ignoreDoctype) { - return; - } - doctype = doctype.replace(/^ /, ''); - if (options.trim) { - doctype = doctype.trim(); - } - addField('doctype', doctype); -} - -function onError(error) { - error.note = error; //console.error(error); -} - -module.exports = function (xml, userOptions) { - - var parser = pureJsParser ? sax.parser(true, {}) : parser = new expat.Parser('UTF-8'); - var result = {}; - currentElement = result; - - options = validateOptions(userOptions); - - if (pureJsParser) { - parser.opt = {strictEntities: true}; - parser.onopentag = onStartElement; - parser.ontext = onText; - parser.oncomment = onComment; - parser.onclosetag = onEndElement; - parser.onerror = onError; - parser.oncdata = onCdata; - parser.ondoctype = onDoctype; - parser.onprocessinginstruction = onInstruction; - } else { - parser.on('startElement', onStartElement); - parser.on('text', onText); - parser.on('comment', onComment); - parser.on('endElement', onEndElement); - parser.on('error', onError); - //parser.on('startCdata', onStartCdata); - //parser.on('endCdata', onEndCdata); - //parser.on('entityDecl', onEntityDecl); - } - - if (pureJsParser) { - parser.write(xml).close(); - } else { - if (!parser.parse(xml)) { - throw new Error('XML parsing error: ' + parser.getError()); - } - } - - if (result[options.elementsKey]) { - var temp = result[options.elementsKey]; - delete result[options.elementsKey]; - result[options.elementsKey] = temp; - delete result.text; - } - - return result; - -}; +var sax = __nccwpck_require__(2043); +var expat /*= require('node-expat');*/ = { on: function () { }, parse: function () { } }; +var helper = __nccwpck_require__(6717); +var isArray = (__nccwpck_require__(1709).isArray); + +var options; +var pureJsParser = true; +var currentElement; + +function validateOptions(userOptions) { + options = helper.copyOptions(userOptions); + helper.ensureFlagExists('ignoreDeclaration', options); + helper.ensureFlagExists('ignoreInstruction', options); + helper.ensureFlagExists('ignoreAttributes', options); + helper.ensureFlagExists('ignoreText', options); + helper.ensureFlagExists('ignoreComment', options); + helper.ensureFlagExists('ignoreCdata', options); + helper.ensureFlagExists('ignoreDoctype', options); + helper.ensureFlagExists('compact', options); + helper.ensureFlagExists('alwaysChildren', options); + helper.ensureFlagExists('addParent', options); + helper.ensureFlagExists('trim', options); + helper.ensureFlagExists('nativeType', options); + helper.ensureFlagExists('nativeTypeAttributes', options); + helper.ensureFlagExists('sanitize', options); + helper.ensureFlagExists('instructionHasAttributes', options); + helper.ensureFlagExists('captureSpacesBetweenElements', options); + helper.ensureAlwaysArrayExists(options); + helper.ensureKeyExists('declaration', options); + helper.ensureKeyExists('instruction', options); + helper.ensureKeyExists('attributes', options); + helper.ensureKeyExists('text', options); + helper.ensureKeyExists('comment', options); + helper.ensureKeyExists('cdata', options); + helper.ensureKeyExists('doctype', options); + helper.ensureKeyExists('type', options); + helper.ensureKeyExists('name', options); + helper.ensureKeyExists('elements', options); + helper.ensureKeyExists('parent', options); + helper.checkFnExists('doctype', options); + helper.checkFnExists('instruction', options); + helper.checkFnExists('cdata', options); + helper.checkFnExists('comment', options); + helper.checkFnExists('text', options); + helper.checkFnExists('instructionName', options); + helper.checkFnExists('elementName', options); + helper.checkFnExists('attributeName', options); + helper.checkFnExists('attributeValue', options); + helper.checkFnExists('attributes', options); + return options; +} + +function nativeType(value) { + var nValue = Number(value); + if (!isNaN(nValue)) { + return nValue; + } + var bValue = value.toLowerCase(); + if (bValue === 'true') { + return true; + } else if (bValue === 'false') { + return false; + } + return value; +} + +function addField(type, value) { + var key; + if (options.compact) { + if ( + !currentElement[options[type + 'Key']] && + (isArray(options.alwaysArray) ? options.alwaysArray.indexOf(options[type + 'Key']) !== -1 : options.alwaysArray) + ) { + currentElement[options[type + 'Key']] = []; + } + if (currentElement[options[type + 'Key']] && !isArray(currentElement[options[type + 'Key']])) { + currentElement[options[type + 'Key']] = [currentElement[options[type + 'Key']]]; + } + if (type + 'Fn' in options && typeof value === 'string') { + value = options[type + 'Fn'](value, currentElement); + } + if (type === 'instruction' && ('instructionFn' in options || 'instructionNameFn' in options)) { + for (key in value) { + if (value.hasOwnProperty(key)) { + if ('instructionFn' in options) { + value[key] = options.instructionFn(value[key], key, currentElement); + } else { + var temp = value[key]; + delete value[key]; + value[options.instructionNameFn(key, temp, currentElement)] = temp; + } + } + } + } + if (isArray(currentElement[options[type + 'Key']])) { + currentElement[options[type + 'Key']].push(value); + } else { + currentElement[options[type + 'Key']] = value; + } + } else { + if (!currentElement[options.elementsKey]) { + currentElement[options.elementsKey] = []; + } + var element = {}; + element[options.typeKey] = type; + if (type === 'instruction') { + for (key in value) { + if (value.hasOwnProperty(key)) { + break; + } + } + element[options.nameKey] = 'instructionNameFn' in options ? options.instructionNameFn(key, value, currentElement) : key; + if (options.instructionHasAttributes) { + element[options.attributesKey] = value[key][options.attributesKey]; + if ('instructionFn' in options) { + element[options.attributesKey] = options.instructionFn(element[options.attributesKey], key, currentElement); + } + } else { + if ('instructionFn' in options) { + value[key] = options.instructionFn(value[key], key, currentElement); + } + element[options.instructionKey] = value[key]; + } + } else { + if (type + 'Fn' in options) { + value = options[type + 'Fn'](value, currentElement); + } + element[options[type + 'Key']] = value; + } + if (options.addParent) { + element[options.parentKey] = currentElement; + } + currentElement[options.elementsKey].push(element); + } +} + +function manipulateAttributes(attributes) { + if ('attributesFn' in options && attributes) { + attributes = options.attributesFn(attributes, currentElement); + } + if ((options.trim || 'attributeValueFn' in options || 'attributeNameFn' in options || options.nativeTypeAttributes) && attributes) { + var key; + for (key in attributes) { + if (attributes.hasOwnProperty(key)) { + if (options.trim) attributes[key] = attributes[key].trim(); + if (options.nativeTypeAttributes) { + attributes[key] = nativeType(attributes[key]); + } + if ('attributeValueFn' in options) attributes[key] = options.attributeValueFn(attributes[key], key, currentElement); + if ('attributeNameFn' in options) { + var temp = attributes[key]; + delete attributes[key]; + attributes[options.attributeNameFn(key, attributes[key], currentElement)] = temp; + } + } + } + } + return attributes; +} + +function onInstruction(instruction) { + var attributes = {}; + if (instruction.body && (instruction.name.toLowerCase() === 'xml' || options.instructionHasAttributes)) { + var attrsRegExp = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g; + var match; + while ((match = attrsRegExp.exec(instruction.body)) !== null) { + attributes[match[1]] = match[2] || match[3] || match[4]; + } + attributes = manipulateAttributes(attributes); + } + if (instruction.name.toLowerCase() === 'xml') { + if (options.ignoreDeclaration) { + return; + } + currentElement[options.declarationKey] = {}; + if (Object.keys(attributes).length) { + currentElement[options.declarationKey][options.attributesKey] = attributes; + } + if (options.addParent) { + currentElement[options.declarationKey][options.parentKey] = currentElement; + } + } else { + if (options.ignoreInstruction) { + return; + } + if (options.trim) { + instruction.body = instruction.body.trim(); + } + var value = {}; + if (options.instructionHasAttributes && Object.keys(attributes).length) { + value[instruction.name] = {}; + value[instruction.name][options.attributesKey] = attributes; + } else { + value[instruction.name] = instruction.body; + } + addField('instruction', value); + } +} + +function onStartElement(name, attributes) { + var element; + if (typeof name === 'object') { + attributes = name.attributes; + name = name.name; + } + attributes = manipulateAttributes(attributes); + if ('elementNameFn' in options) { + name = options.elementNameFn(name, currentElement); + } + if (options.compact) { + element = {}; + if (!options.ignoreAttributes && attributes && Object.keys(attributes).length) { + element[options.attributesKey] = {}; + var key; + for (key in attributes) { + if (attributes.hasOwnProperty(key)) { + element[options.attributesKey][key] = attributes[key]; + } + } + } + if ( + !(name in currentElement) && + (isArray(options.alwaysArray) ? options.alwaysArray.indexOf(name) !== -1 : options.alwaysArray) + ) { + currentElement[name] = []; + } + if (currentElement[name] && !isArray(currentElement[name])) { + currentElement[name] = [currentElement[name]]; + } + if (isArray(currentElement[name])) { + currentElement[name].push(element); + } else { + currentElement[name] = element; + } + } else { + if (!currentElement[options.elementsKey]) { + currentElement[options.elementsKey] = []; + } + element = {}; + element[options.typeKey] = 'element'; + element[options.nameKey] = name; + if (!options.ignoreAttributes && attributes && Object.keys(attributes).length) { + element[options.attributesKey] = attributes; + } + if (options.alwaysChildren) { + element[options.elementsKey] = []; + } + currentElement[options.elementsKey].push(element); + } + element[options.parentKey] = currentElement; // will be deleted in onEndElement() if !options.addParent + currentElement = element; +} + +function onText(text) { + if (options.ignoreText) { + return; + } + if (!text.trim() && !options.captureSpacesBetweenElements) { + return; + } + if (options.trim) { + text = text.trim(); + } + if (options.nativeType) { + text = nativeType(text); + } + if (options.sanitize) { + text = text.replace(/&/g, '&').replace(//g, '>'); + } + addField('text', text); +} + +function onComment(comment) { + if (options.ignoreComment) { + return; + } + if (options.trim) { + comment = comment.trim(); + } + addField('comment', comment); +} + +function onEndElement(name) { + var parentElement = currentElement[options.parentKey]; + if (!options.addParent) { + delete currentElement[options.parentKey]; + } + currentElement = parentElement; +} + +function onCdata(cdata) { + if (options.ignoreCdata) { + return; + } + if (options.trim) { + cdata = cdata.trim(); + } + addField('cdata', cdata); +} + +function onDoctype(doctype) { + if (options.ignoreDoctype) { + return; + } + doctype = doctype.replace(/^ /, ''); + if (options.trim) { + doctype = doctype.trim(); + } + addField('doctype', doctype); +} + +function onError(error) { + error.note = error; //console.error(error); +} + +module.exports = function (xml, userOptions) { + + var parser = pureJsParser ? sax.parser(true, {}) : parser = new expat.Parser('UTF-8'); + var result = {}; + currentElement = result; + + options = validateOptions(userOptions); + + if (pureJsParser) { + parser.opt = {strictEntities: true}; + parser.onopentag = onStartElement; + parser.ontext = onText; + parser.oncomment = onComment; + parser.onclosetag = onEndElement; + parser.onerror = onError; + parser.oncdata = onCdata; + parser.ondoctype = onDoctype; + parser.onprocessinginstruction = onInstruction; + } else { + parser.on('startElement', onStartElement); + parser.on('text', onText); + parser.on('comment', onComment); + parser.on('endElement', onEndElement); + parser.on('error', onError); + //parser.on('startCdata', onStartCdata); + //parser.on('endCdata', onEndCdata); + //parser.on('entityDecl', onEntityDecl); + } + + if (pureJsParser) { + parser.write(xml).close(); + } else { + if (!parser.parse(xml)) { + throw new Error('XML parsing error: ' + parser.getError()); + } + } + + if (result[options.elementsKey]) { + var temp = result[options.elementsKey]; + delete result[options.elementsKey]; + result[options.elementsKey] = temp; + delete result.text; + } + + return result; + +}; /***/ }), @@ -23036,28 +23036,28 @@ module.exports = function (xml, userOptions) { /***/ 8919: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var helper = __nccwpck_require__(6717); -var xml2js = __nccwpck_require__(2903); - -function validateOptions (userOptions) { - var options = helper.copyOptions(userOptions); - helper.ensureSpacesExists(options); - return options; -} - -module.exports = function(xml, userOptions) { - var options, js, json, parentKey; - options = validateOptions(userOptions); - js = xml2js(xml, options); - parentKey = 'compact' in options && options.compact ? '_parent' : 'parent'; - // parentKey = ptions.compact ? '_parent' : 'parent'; // consider this - if ('addParent' in options && options.addParent) { - json = JSON.stringify(js, function (k, v) { return k === parentKey? '_' : v; }, options.spaces); - } else { - json = JSON.stringify(js, null, options.spaces); - } - return json.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); -}; +var helper = __nccwpck_require__(6717); +var xml2js = __nccwpck_require__(2903); + +function validateOptions (userOptions) { + var options = helper.copyOptions(userOptions); + helper.ensureSpacesExists(options); + return options; +} + +module.exports = function(xml, userOptions) { + var options, js, json, parentKey; + options = validateOptions(userOptions); + js = xml2js(xml, options); + parentKey = 'compact' in options && options.compact ? '_parent' : 'parent'; + // parentKey = ptions.compact ? '_parent' : 'parent'; // consider this + if ('addParent' in options && options.addParent) { + json = JSON.stringify(js, function (k, v) { return k === parentKey? '_' : v; }, options.spaces); + } else { + json = JSON.stringify(js, null, options.spaces); + } + return json.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); +}; /***/ }), @@ -23226,7 +23226,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; -/******/ +/******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache @@ -23240,7 +23240,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ // no module.loaded needed /******/ exports: {} /******/ }; -/******/ +/******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { @@ -23249,24 +23249,24 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } -/******/ +/******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } -/******/ +/******/ /************************************************************************/ /******/ /* webpack/runtime/compat */ -/******/ +/******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; -/******/ +/******/ /************************************************************************/ -/******/ +/******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __nccwpck_require__(4822); /******/ module.exports = __webpack_exports__; -/******/ +/******/ /******/ })() ; -//# sourceMappingURL=index.js.map \ No newline at end of file +//# sourceMappingURL=index.js.map