diff --git a/package-lock.json b/package-lock.json index a35cde52..5320c234 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@sweetalert2/theme-borderless": "^5.0.18", "@titaniumnetwork-dev/ultraviolet": "^3.2.7", "@tomphttp/bare-server-node": "2.0.2", + "archiver": "^7.0.1", "express": "^4.19.2", "sweetalert2": "^11.14.4", "wisp-server-node": "^1.1.7" @@ -467,6 +468,23 @@ "p-limit": "^3.1.0" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/@lukeed/ms": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", @@ -515,6 +533,16 @@ "node": ">= 0.6" } }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@sweetalert2/theme-borderless": { "version": "5.0.18", "resolved": "https://registry.npmjs.org/@sweetalert2/theme-borderless/-/theme-borderless-5.0.18.tgz", @@ -551,6 +579,18 @@ "node": ">=18.0.0" } }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/abstract-logging": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", @@ -615,6 +655,151 @@ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.3.tgz", "integrity": "sha512-aLrHthzCjH5He4Z2H9YZ+v6Ujb9ocRuW6ZzkJQOrTxleEijANq4v1TsaPaVG1PZcuurEzrLcWRyYBYXD5cEiaw==" }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/archiver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/archiver/-/archiver-7.0.1.tgz", + "integrity": "sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^5.0.2", + "async": "^3.2.4", + "buffer-crc32": "^1.0.0", + "readable-stream": "^4.0.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^3.0.0", + "zip-stream": "^6.0.1" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/archiver-utils": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-5.0.2.tgz", + "integrity": "sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA==", + "license": "MIT", + "dependencies": { + "glob": "^10.0.0", + "graceful-fs": "^4.2.0", + "is-stream": "^2.0.1", + "lazystream": "^1.0.0", + "lodash": "^4.17.15", + "normalize-path": "^3.0.0", + "readable-stream": "^4.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/archiver-utils/node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/archiver-utils/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/archiver-utils/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/archiver/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/archiver/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -628,6 +813,12 @@ "astring": "bin/astring" } }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, "node_modules/async-exit-hook": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz", @@ -653,11 +844,44 @@ "fastq": "^1.17.1" } }, + "node_modules/b4a": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.7.tgz", + "integrity": "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==", + "license": "Apache-2.0" + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "node_modules/bare-events": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.0.tgz", + "integrity": "sha512-/E8dDe9dsbLyh2qrZ64PEPadOQ0F4gbl1sUJOrmph7xOiIxfY8vwab/4bFLh4Y88/Hk/ujKcrQKc+ps0mv873A==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/big-integer": { "version": "1.6.52", "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", @@ -708,6 +932,39 @@ "balanced-match": "^1.0.0" } }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-crc32": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-1.0.0.tgz", + "integrity": "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -777,6 +1034,24 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/commander": { "version": "10.0.1", "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", @@ -785,6 +1060,47 @@ "node": ">=14" } }, + "node_modules/compress-commons": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-6.0.2.tgz", + "integrity": "sha512-6FqVXeETqWPoGcfzrXb37E50NP0LXT8kAMu5ooZayhWWdgEY4lBEEcbQNXtkuKQsGduxiIcI4gOTsxTmuq/bSg==", + "license": "MIT", + "dependencies": { + "crc-32": "^1.2.0", + "crc32-stream": "^6.0.0", + "is-stream": "^2.0.1", + "normalize-path": "^3.0.0", + "readable-stream": "^4.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/compress-commons/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/compress-commons/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -822,6 +1138,56 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/crc32-stream": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-6.0.0.tgz", + "integrity": "sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==", + "license": "MIT", + "dependencies": { + "crc-32": "^1.2.0", + "readable-stream": "^4.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/crc32-stream/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/crc32-stream/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -1084,11 +1450,23 @@ "stream-shift": "^1.0.0" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -1185,6 +1563,24 @@ "node": ">= 0.6" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, "node_modules/execa": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/execa/-/execa-4.1.0.tgz", @@ -1263,6 +1659,12 @@ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", + "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", + "license": "MIT" + }, "node_modules/fast-json-stringify": { "version": "5.16.1", "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-5.16.1.tgz", @@ -1390,6 +1792,34 @@ "node": ">=14" } }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -1500,6 +1930,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, "node_modules/has-property-descriptors": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", @@ -1583,6 +2019,26 @@ "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz", "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==" }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -1635,6 +2091,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-git-repository": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-git-repository/-/is-git-repository-1.1.1.tgz", @@ -1799,6 +2264,21 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/json-schema-ref-resolver": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz", @@ -1812,6 +2292,18 @@ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" }, + "node_modules/lazystream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", + "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.0.5" + }, + "engines": { + "node": ">= 0.6.3" + } + }, "node_modules/light-my-request": { "version": "5.14.0", "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-5.14.0.tgz", @@ -1822,6 +2314,12 @@ "set-cookie-parser": "^2.4.1" } }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, "node_modules/lru-cache": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", @@ -1941,6 +2439,15 @@ "node-gyp-build-test": "build-test.js" } }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", @@ -2051,6 +2558,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, "node_modules/parse5": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.0.tgz", @@ -2091,6 +2604,28 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, "node_modules/path-to-regexp": { "version": "0.1.10", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", @@ -2145,6 +2680,15 @@ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.0.tgz", "integrity": "sha512-/MyYDxttz7DfGMMHiysAsFE4qF+pQYAA8ziO/3NcRVrQ5fSk+Mns4QZA/oRPFzvcqNoVJXQNWNAsdwBXLUkQKw==" }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -2237,6 +2781,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/queue-tick": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz", + "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==", + "license": "MIT" + }, "node_modules/quick-format-unescaped": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", @@ -2283,6 +2833,15 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, + "node_modules/readdir-glob": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", + "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.1.0" + } + }, "node_modules/real-require": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", @@ -2595,6 +3154,20 @@ "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz", "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==" }, + "node_modules/streamx": { + "version": "2.21.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.21.0.tgz", + "integrity": "sha512-Qz6MsDZXJ6ur9u+b+4xCG18TluU7PGlRfXVAAjNiGsFrBUt/ioyLkxbFaKJygoPs+/kW4VyBj0bSj89Qu0IGyg==", + "license": "MIT", + "dependencies": { + "fast-fifo": "^1.3.2", + "queue-tick": "^1.0.1", + "text-decoder": "^1.1.0" + }, + "optionalDependencies": { + "bare-events": "^2.2.0" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -2608,6 +3181,102 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/strip-eof": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", @@ -2634,6 +3303,23 @@ "url": "https://github.com/sponsors/limonte" } }, + "node_modules/tar-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", + "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", + "license": "MIT", + "dependencies": { + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" + } + }, + "node_modules/text-decoder": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.1.tgz", + "integrity": "sha512-x9v3H/lTKIJKQQe7RPQkLfKAnc9lUTkWDypIQgTzPJAq+5/GCDHonmshfvlsNSj58yyshbIJJDLmU15qNERrXQ==", + "license": "Apache-2.0" + }, "node_modules/thread-stream": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", @@ -2765,6 +3451,97 @@ "ws": "^8.18.0" } }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -2813,6 +3590,45 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zip-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-6.0.1.tgz", + "integrity": "sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^5.0.0", + "compress-commons": "^6.0.2", + "readable-stream": "^4.0.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/zip-stream/node_modules/readable-stream": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/zip-stream/node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } } } } diff --git a/package.json b/package.json index 99c8ff29..e1acb153 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "@mercuryworkshop/bare-mux": "^2.0.9", "wisp-server-node": "^1.1.7", "express": "^4.19.2", + "archiver": "^7.0.1", "sweetalert2": "^11.14.4" } } diff --git a/public/.DS_Store b/public/.DS_Store index 03a79c9f..534a5b93 100644 Binary files a/public/.DS_Store and b/public/.DS_Store differ diff --git a/public/assets/.DS_Store b/public/assets/.DS_Store index fc7112c2..74b8c23b 100644 Binary files a/public/assets/.DS_Store and b/public/assets/.DS_Store differ diff --git a/public/assets/games/.DS_Store b/public/assets/games/.DS_Store index e1ddb440..43cead70 100644 Binary files a/public/assets/games/.DS_Store and b/public/assets/games/.DS_Store differ diff --git a/public/assets/games/bobble/favicon.png b/public/assets/games/bobble/favicon.png new file mode 100644 index 00000000..083d7304 Binary files /dev/null and b/public/assets/games/bobble/favicon.png differ diff --git a/public/assets/games/bobble/index-nothreads.js b/public/assets/games/bobble/index-nothreads.js new file mode 100644 index 00000000..605d26b7 --- /dev/null +++ b/public/assets/games/bobble/index-nothreads.js @@ -0,0 +1,796 @@ + +var Godot = (() => { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( +function(Godot) { + Godot = Godot || {}; + +var Module=typeof Godot!="undefined"?Godot:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var tempRet0=0;var setTempRet0=value=>{tempRet0=value};var getTempRet0=()=>tempRet0;var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||false;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||134217728;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;SOCKFS.root=FS.mount(SOCKFS,{},null);if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){___funcs_on_exit();callRuntimeCallbacks(__ATEXIT__);FS.quit();TTY.shutdown();IDBFS.quit();runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){{if(Module["onAbort"]){Module["onAbort"](what)}}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="godot.javascript.opt.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["Kj"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["Mj"];addOnInit(Module["asm"]["Lj"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function getValue(ptr,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":return HEAP8[ptr>>0];case"i8":return HEAP8[ptr>>0];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP32[ptr>>2];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];case"*":return HEAPU32[ptr>>2];default:abort("invalid type for getValue: "+type)}return null}function handleException(e){if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)}function setValue(ptr,value,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;case"*":HEAPU32[ptr>>2]=value;break;default:abort("invalid type for setValue: "+type)}}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function getWasmTableEntry(funcPtr){return wasmTable.get(funcPtr)}function ___call_sighandler(fp,sig){getWasmTableEntry(fp)(sig)}function getRandomDevice(){if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){var randomBuffer=new Uint8Array(1);return()=>{crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else return()=>abort("randomDevice")}var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:(l,r)=>{return PATH.normalize(l+"/"+r)}};var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.flush(stream.tty)},flush:function(stream){stream.tty.ops.flush(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function zeroMemory(address,size){HEAPU8.fill(0,address,address+size)}function mmapAlloc(size){abort()}var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{assert(arrayBuffer,'Loading data file "'+url+'" failed (no arrayBuffer).');onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},event=>{if(onerror){onerror()}else{throw'Loading data file "'+url+'" failed.'}});if(dep)addRunDependency(dep)}var IDBFS={dbs:{},indexedDB:()=>{if(typeof indexedDB!="undefined")return indexedDB;var ret=null;if(typeof window=="object")ret=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB;assert(ret,"IDBFS used, but indexedDB not supported");return ret},DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",mount:function(mount){return MEMFS.mount.apply(null,arguments)},syncfs:(mount,populate,callback)=>{IDBFS.getLocalSet(mount,(err,local)=>{if(err)return callback(err);IDBFS.getRemoteSet(mount,(err,remote)=>{if(err)return callback(err);var src=populate?remote:local;var dst=populate?local:remote;IDBFS.reconcile(src,dst,callback)})})},quit:()=>{Object.values(IDBFS.dbs).forEach(value=>value.close());IDBFS.dbs={}},getDB:(name,callback)=>{var db=IDBFS.dbs[name];if(db){return callback(null,db)}var req;try{req=IDBFS.indexedDB().open(name,IDBFS.DB_VERSION)}catch(e){return callback(e)}if(!req){return callback("Unable to connect to IndexedDB")}req.onupgradeneeded=e=>{var db=e.target.result;var transaction=e.target.transaction;var fileStore;if(db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)){fileStore=transaction.objectStore(IDBFS.DB_STORE_NAME)}else{fileStore=db.createObjectStore(IDBFS.DB_STORE_NAME)}if(!fileStore.indexNames.contains("timestamp")){fileStore.createIndex("timestamp","timestamp",{unique:false})}};req.onsuccess=()=>{db=req.result;IDBFS.dbs[name]=db;callback(null,db)};req.onerror=e=>{callback(this.error);e.preventDefault()}},getLocalSet:(mount,callback)=>{var entries={};function isRealDir(p){return p!=="."&&p!==".."}function toAbsolute(root){return p=>{return PATH.join2(root,p)}}var check=FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));while(check.length){var path=check.pop();var stat;try{stat=FS.stat(path)}catch(e){return callback(e)}if(FS.isDir(stat.mode)){check.push.apply(check,FS.readdir(path).filter(isRealDir).map(toAbsolute(path)))}entries[path]={"timestamp":stat.mtime}}return callback(null,{type:"local",entries:entries})},getRemoteSet:(mount,callback)=>{var entries={};IDBFS.getDB(mount.mountpoint,(err,db)=>{if(err)return callback(err);try{var transaction=db.transaction([IDBFS.DB_STORE_NAME],"readonly");transaction.onerror=e=>{callback(this.error);e.preventDefault()};var store=transaction.objectStore(IDBFS.DB_STORE_NAME);var index=store.index("timestamp");index.openKeyCursor().onsuccess=event=>{var cursor=event.target.result;if(!cursor){return callback(null,{type:"remote",db:db,entries:entries})}entries[cursor.primaryKey]={"timestamp":cursor.key};cursor.continue()}}catch(e){return callback(e)}})},loadLocalEntry:(path,callback)=>{var stat,node;try{var lookup=FS.lookupPath(path);node=lookup.node;stat=FS.stat(path)}catch(e){return callback(e)}if(FS.isDir(stat.mode)){return callback(null,{"timestamp":stat.mtime,"mode":stat.mode})}else if(FS.isFile(stat.mode)){node.contents=MEMFS.getFileDataAsTypedArray(node);return callback(null,{"timestamp":stat.mtime,"mode":stat.mode,"contents":node.contents})}else{return callback(new Error("node type not supported"))}},storeLocalEntry:(path,entry,callback)=>{try{if(FS.isDir(entry["mode"])){FS.mkdirTree(path,entry["mode"])}else if(FS.isFile(entry["mode"])){FS.writeFile(path,entry["contents"],{canOwn:true})}else{return callback(new Error("node type not supported"))}FS.chmod(path,entry["mode"]);FS.utime(path,entry["timestamp"],entry["timestamp"])}catch(e){return callback(e)}callback(null)},removeLocalEntry:(path,callback)=>{try{var stat=FS.stat(path);if(FS.isDir(stat.mode)){FS.rmdir(path)}else if(FS.isFile(stat.mode)){FS.unlink(path)}}catch(e){return callback(e)}callback(null)},loadRemoteEntry:(store,path,callback)=>{var req=store.get(path);req.onsuccess=event=>{callback(null,event.target.result)};req.onerror=e=>{callback(this.error);e.preventDefault()}},storeRemoteEntry:(store,path,entry,callback)=>{try{var req=store.put(entry,path)}catch(e){callback(e);return}req.onsuccess=()=>{callback(null)};req.onerror=e=>{callback(this.error);e.preventDefault()}},removeRemoteEntry:(store,path,callback)=>{var req=store.delete(path);req.onsuccess=()=>{callback(null)};req.onerror=e=>{callback(this.error);e.preventDefault()}},reconcile:(src,dst,callback)=>{var total=0;var create=[];Object.keys(src.entries).forEach(function(key){var e=src.entries[key];var e2=dst.entries[key];if(!e2||e["timestamp"].getTime()!=e2["timestamp"].getTime()){create.push(key);total++}});var remove=[];Object.keys(dst.entries).forEach(function(key){if(!src.entries[key]){remove.push(key);total++}});if(!total){return callback(null)}var errored=false;var db=src.type==="remote"?src.db:dst.db;var transaction=db.transaction([IDBFS.DB_STORE_NAME],"readwrite");var store=transaction.objectStore(IDBFS.DB_STORE_NAME);function done(err){if(err&&!errored){errored=true;return callback(err)}}transaction.onerror=e=>{done(this.error);e.preventDefault()};transaction.oncomplete=e=>{if(!errored){callback(null)}};create.sort().forEach(path=>{if(dst.type==="local"){IDBFS.loadRemoteEntry(store,path,(err,entry)=>{if(err)return done(err);IDBFS.storeLocalEntry(path,entry,done)})}else{IDBFS.loadLocalEntry(path,(err,entry)=>{if(err)return done(err);IDBFS.storeRemoteEntry(store,path,entry,done)})}});remove.sort().reverse().forEach(path=>{if(dst.type==="local"){IDBFS.removeLocalEntry(path,done)}else{IDBFS.removeRemoteEntry(store,path,done)}})}};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path,opts={})=>{path=PATH_FS.resolve(FS.cwd(),path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};opts=Object.assign(defaults,opts);if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(p=>!!p),false);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:node=>{var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:(parentid,name)=>{var hash=0;for(var i=0;i>>0)%FS.nameTable.length},hashAddNode:node=>{var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:node=>{var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:(parent,name)=>{var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode:(parent,name,mode,rdev)=>{var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode:node=>{FS.hashRemoveNode(node)},isRoot:node=>{return node===node.parent},isMountpoint:node=>{return!!node.mounted},isFile:mode=>{return(mode&61440)===32768},isDir:mode=>{return(mode&61440)===16384},isLink:mode=>{return(mode&61440)===40960},isChrdev:mode=>{return(mode&61440)===8192},isBlkdev:mode=>{return(mode&61440)===24576},isFIFO:mode=>{return(mode&61440)===4096},isSocket:mode=>{return(mode&49152)===49152},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:str=>{var flags=FS.flagModes[str];if(typeof flags=="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},flagsToPermissionString:flag=>{var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions:(node,perms)=>{if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:dir=>{var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:(dir,name)=>{try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete:(dir,name,isdir)=>{var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen:(node,flags)=>{if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:(fd_start=0,fd_end=FS.MAX_OPEN_FDS)=>{for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:fd=>FS.streams[fd],createStream:(stream,fd_start,fd_end)=>{if(!FS.FSStream){FS.FSStream=function(){this.shared={}};FS.FSStream.prototype={};Object.defineProperties(FS.FSStream.prototype,{object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}},flags:{get:function(){return this.shared.flags},set:function(val){this.shared.flags=val}},position:{get:function(){return this.shared.position},set:function(val){this.shared.position=val}}})}stream=Object.assign(new FS.FSStream,stream);var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:fd=>{FS.streams[fd]=null},chrdev_stream_ops:{open:stream=>{var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek:()=>{throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice:(dev,ops)=>{FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts:mount=>{var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs:(populate,callback)=>{if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err("warning: "+FS.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work")}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount:(type,opts,mountpoint)=>{var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount:mountpoint=>{var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup:(parent,name)=>{return parent.node_ops.lookup(parent,name)},mknod:(path,mode,dev)=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create:(path,mode)=>{mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:(path,mode)=>{mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:(path,mode)=>{var dirs=path.split("/");var d="";for(var i=0;i{if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink:(oldpath,newpath)=>{if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename:(old_path,new_path)=>{var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name)}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir:path=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir:path=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node.node_ops.readdir){throw new FS.ErrnoError(54)}return node.node_ops.readdir(node)},unlink:path=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink:path=>{var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return PATH_FS.resolve(FS.getPath(link.parent),link.node_ops.readlink(link))},stat:(path,dontFollow)=>{var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;if(!node){throw new FS.ErrnoError(44)}if(!node.node_ops.getattr){throw new FS.ErrnoError(63)}return node.node_ops.getattr(node)},lstat:path=>{return FS.stat(path,true)},chmod:(path,mode,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{mode:mode&4095|node.mode&~4095,timestamp:Date.now()})},lchmod:(path,mode)=>{FS.chmod(path,mode,true)},fchmod:(fd,mode)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chmod(stream.node,mode)},chown:(path,uid,gid,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{timestamp:Date.now()})},lchown:(path,uid,gid)=>{FS.chown(path,uid,gid,true)},fchown:(fd,uid,gid)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chown(stream.node,uid,gid)},truncate:(path,len)=>{if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}node.node_ops.setattr(node,{size:len,timestamp:Date.now()})},ftruncate:(fd,len)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.truncate(stream.node,len)},utime:(path,atime,mtime)=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;node.node_ops.setattr(node,{timestamp:Math.max(atime,mtime)})},open:(path,flags,mode)=>{if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS.modeStringToFlags(flags):flags;mode=typeof mode=="undefined"?438:mode;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;if(typeof path=="object"){node=path}else{path=PATH.normalize(path);try{var lookup=FS.lookupPath(path,{follow:!(flags&131072)});node=lookup.node}catch(e){}}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else{node=FS.mknod(path,mode,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node:node,path:FS.getPath(node),flags:flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){if(!FS.readFiles)FS.readFiles={};if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close:stream=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed:stream=>{return stream.fd===null},llseek:(stream,offset,whence)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read:(stream,buffer,offset,length,position)=>{if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write:(stream,buffer,offset,length,position,canOwn)=>{if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},allocate:(stream,offset,length)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(offset<0||length<=0){throw new FS.ErrnoError(28)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(!FS.isFile(stream.node.mode)&&!FS.isDir(stream.node.mode)){throw new FS.ErrnoError(43)}if(!stream.stream_ops.allocate){throw new FS.ErrnoError(138)}stream.stream_ops.allocate(stream,offset,length)},mmap:(stream,length,position,prot,flags)=>{if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync:(stream,buffer,offset,length,mmapFlags)=>{if(!stream||!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},munmap:stream=>0,ioctl:(stream,cmd,arg)=>{if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile:(path,opts={})=>{opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error('Invalid encoding type "'+opts.encoding+'"')}var ret;var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile:(path,data,opts={})=>{opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir:path=>{var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories:()=>{FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices:()=>{FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var random_device=getRandomDevice();FS.createDevice("/dev","random",random_device);FS.createDevice("/dev","urandom",random_device);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount:()=>{var node=FS.createNode(proc_self,"fd",16384|511,73);node.node_ops={lookup:(parent,name)=>{var fd=+name;var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams:()=>{if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},ensureErrnoError:()=>{if(FS.ErrnoError)return;FS.ErrnoError=function ErrnoError(errno,node){this.node=node;this.setErrno=function(errno){this.errno=errno};this.setErrno(errno);this.message="FS error"};FS.ErrnoError.prototype=new Error;FS.ErrnoError.prototype.constructor=FS.ErrnoError;[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack=""})},staticInit:()=>{FS.ensureErrnoError();FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={"MEMFS":MEMFS,"IDBFS":IDBFS}},init:(input,output,error)=>{FS.init.initialized=true;FS.ensureErrnoError();Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit:()=>{FS.init.initialized=false;_fflush(0);for(var i=0;i{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode},findObject:(path,dontResolveLastLink)=>{var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath:(path,dontResolveLastLink)=>{try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath:(parent,path,canRead,canWrite)=>{parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){}parent=current}return current},createFile:(parent,name,properties,canRead,canWrite)=>{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile:(parent,name,data,canRead,canWrite,canOwn)=>{var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS.getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(!!input,!!output);if(!FS.createDevice.major)FS.createDevice.major=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open:stream=>{stream.seekable=false},close:stream=>{if(output&&output.buffer&&output.buffer.length){output(10)}},read:(stream,buffer,offset,length,pos)=>{var bytesRead=0;for(var i=0;i{for(var i=0;i{if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else if(read_){try{obj.contents=intArrayFromString(read_(obj.url),true);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}else{throw new Error("Cannot load without read() or XMLHttpRequest.")}},createLazyFile:(parent,name,url,canRead,canWrite)=>{function LazyUint8Array(){this.lengthKnown=false;this.chunks=[]}LazyUint8Array.prototype.get=function LazyUint8Array_get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr:ptr,allocated:true}};node.stream_ops=stream_ops;return node},createPreloadedFile:(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency("cp "+fullname);function processData(byteArray){function finish(byteArray){if(preFinish)preFinish();if(!dontCreateFile){FS.createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}if(onload)onload();removeRunDependency(dep)}if(Browser.handledByPreloadPlugin(byteArray,fullname,finish,()=>{if(onerror)onerror();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,byteArray=>processData(byteArray),onerror)}else{processData(url)}},indexedDB:()=>{return window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB},DB_NAME:()=>{return"EM_FS_"+window.location.pathname},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=()=>{out("creating db");var db=openRequest.result;db.createObjectStore(FS.DB_STORE_NAME)};openRequest.onsuccess=()=>{var db=openRequest.result;var transaction=db.transaction([FS.DB_STORE_NAME],"readwrite");var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var putRequest=files.put(FS.analyzePath(path).object.contents,path);putRequest.onsuccess=()=>{ok++;if(ok+fail==total)finish()};putRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror},loadFilesFromDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=onerror;openRequest.onsuccess=()=>{var db=openRequest.result;try{var transaction=db.transaction([FS.DB_STORE_NAME],"readonly")}catch(e){onerror(e);return}var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var getRequest=files.get(path);getRequest.onsuccess=()=>{if(FS.analyzePath(path).exists){FS.unlink(path)}FS.createDataFile(PATH.dirname(path),PATH.basename(path),getRequest.result,true,true,true);ok++;if(ok+fail==total)finish()};getRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror}};var SOCKFS={mount:function(mount){Module["websocket"]=Module["websocket"]&&"object"===typeof Module["websocket"]?Module["websocket"]:{};Module["websocket"]._callbacks={};Module["websocket"]["on"]=function(event,callback){if("function"===typeof callback){this._callbacks[event]=callback}return this};Module["websocket"].emit=function(event,param){if("function"===typeof this._callbacks[event]){this._callbacks[event].call(this,param)}};return FS.createNode(null,"/",16384|511,0)},createSocket:function(family,type,protocol){type&=~526336;var streaming=type==1;if(streaming&&protocol&&protocol!=6){throw new FS.ErrnoError(66)}var sock={family:family,type:type,protocol:protocol,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops};var name=SOCKFS.nextname();var node=FS.createNode(SOCKFS.root,name,49152,0);node.sock=sock;var stream=FS.createStream({path:name,node:node,flags:2,seekable:false,stream_ops:SOCKFS.stream_ops});sock.stream=stream;return sock},getSocket:function(fd){var stream=FS.getStream(fd);if(!stream||!FS.isSocket(stream.node.mode)){return null}return stream.node.sock},stream_ops:{poll:function(stream){var sock=stream.node.sock;return sock.sock_ops.poll(sock)},ioctl:function(stream,request,varargs){var sock=stream.node.sock;return sock.sock_ops.ioctl(sock,request,varargs)},read:function(stream,buffer,offset,length,position){var sock=stream.node.sock;var msg=sock.sock_ops.recvmsg(sock,length);if(!msg){return 0}buffer.set(msg.buffer,offset);return msg.buffer.length},write:function(stream,buffer,offset,length,position){var sock=stream.node.sock;return sock.sock_ops.sendmsg(sock,buffer,offset,length)},close:function(stream){var sock=stream.node.sock;sock.sock_ops.close(sock)}},nextname:function(){if(!SOCKFS.nextname.current){SOCKFS.nextname.current=0}return"socket["+SOCKFS.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(sock,addr,port){var ws;if(typeof addr=="object"){ws=addr;addr=null;port=null}if(ws){if(ws._socket){addr=ws._socket.remoteAddress;port=ws._socket.remotePort}else{var result=/ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);if(!result){throw new Error("WebSocket URL must be in the format ws(s)://address:port")}addr=result[1];port=parseInt(result[2],10)}}else{try{var runtimeConfig=Module["websocket"]&&"object"===typeof Module["websocket"];var url="ws:#".replace("#","//");if(runtimeConfig){if("string"===typeof Module["websocket"]["url"]){url=Module["websocket"]["url"]}}if(url==="ws://"||url==="wss://"){var parts=addr.split("/");url=url+parts[0]+":"+port+"/"+parts.slice(1).join("/")}var subProtocols="binary";if(runtimeConfig){if("string"===typeof Module["websocket"]["subprotocol"]){subProtocols=Module["websocket"]["subprotocol"]}}var opts=undefined;if(subProtocols!=="null"){subProtocols=subProtocols.replace(/^ +| +$/g,"").split(/ *, */);opts=subProtocols}if(runtimeConfig&&null===Module["websocket"]["subprotocol"]){subProtocols="null";opts=undefined}var WebSocketConstructor;{WebSocketConstructor=WebSocket}ws=new WebSocketConstructor(url,opts);ws.binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}}var peer={addr:addr,port:port,socket:ws,dgram_send_queue:[]};SOCKFS.websocket_sock_ops.addPeer(sock,peer);SOCKFS.websocket_sock_ops.handlePeerEvents(sock,peer);if(sock.type===2&&typeof sock.sport!="undefined"){peer.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(sock.sport&65280)>>8,sock.sport&255]))}return peer},getPeer:function(sock,addr,port){return sock.peers[addr+":"+port]},addPeer:function(sock,peer){sock.peers[peer.addr+":"+peer.port]=peer},removePeer:function(sock,peer){delete sock.peers[peer.addr+":"+peer.port]},handlePeerEvents:function(sock,peer){var first=true;var handleOpen=function(){Module["websocket"].emit("open",sock.stream.fd);try{var queued=peer.dgram_send_queue.shift();while(queued){peer.socket.send(queued);queued=peer.dgram_send_queue.shift()}}catch(e){peer.socket.close()}};function handleMessage(data){if(typeof data=="string"){var encoder=new TextEncoder;data=encoder.encode(data)}else{assert(data.byteLength!==undefined);if(data.byteLength==0){return}data=new Uint8Array(data)}var wasfirst=first;first=false;if(wasfirst&&data.length===10&&data[0]===255&&data[1]===255&&data[2]===255&&data[3]===255&&data[4]==="p".charCodeAt(0)&&data[5]==="o".charCodeAt(0)&&data[6]==="r".charCodeAt(0)&&data[7]==="t".charCodeAt(0)){var newport=data[8]<<8|data[9];SOCKFS.websocket_sock_ops.removePeer(sock,peer);peer.port=newport;SOCKFS.websocket_sock_ops.addPeer(sock,peer);return}sock.recv_queue.push({addr:peer.addr,port:peer.port,data:data});Module["websocket"].emit("message",sock.stream.fd)}if(ENVIRONMENT_IS_NODE){peer.socket.on("open",handleOpen);peer.socket.on("message",function(data,isBinary){if(!isBinary){return}handleMessage(new Uint8Array(data).buffer)});peer.socket.on("close",function(){Module["websocket"].emit("close",sock.stream.fd)});peer.socket.on("error",function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])})}else{peer.socket.onopen=handleOpen;peer.socket.onclose=function(){Module["websocket"].emit("close",sock.stream.fd)};peer.socket.onmessage=function peer_socket_onmessage(event){handleMessage(event.data)};peer.socket.onerror=function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])}}},poll:function(sock){if(sock.type===1&&sock.server){return sock.pending.length?64|1:0}var mask=0;var dest=sock.type===1?SOCKFS.websocket_sock_ops.getPeer(sock,sock.daddr,sock.dport):null;if(sock.recv_queue.length||!dest||dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=64|1}if(!dest||dest&&dest.socket.readyState===dest.socket.OPEN){mask|=4}if(dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=16}return mask},ioctl:function(sock,request,arg){switch(request){case 21531:var bytes=0;if(sock.recv_queue.length){bytes=sock.recv_queue[0].data.length}HEAP32[arg>>2]=bytes;return 0;default:return 28}},close:function(sock){if(sock.server){try{sock.server.close()}catch(e){}sock.server=null}var peers=Object.keys(sock.peers);for(var i=0;i>2]=value;return value}function inetPton4(str){var b=str.split(".");for(var i=0;i<4;i++){var tmp=Number(b[i]);if(isNaN(tmp))return null;b[i]=tmp}return(b[0]|b[1]<<8|b[2]<<16|b[3]<<24)>>>0}function jstoi_q(str){return parseInt(str)}function inetPton6(str){var words;var w,offset,z;var valid6regx=/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i;var parts=[];if(!valid6regx.test(str)){return null}if(str==="::"){return[0,0,0,0,0,0,0,0]}if(str.startsWith("::")){str=str.replace("::","Z:")}else{str=str.replace("::",":Z:")}if(str.indexOf(".")>0){str=str.replace(new RegExp("[.]","g"),":");words=str.split(":");words[words.length-4]=jstoi_q(words[words.length-4])+jstoi_q(words[words.length-3])*256;words[words.length-3]=jstoi_q(words[words.length-2])+jstoi_q(words[words.length-1])*256;words=words.slice(0,words.length-2)}else{words=str.split(":")}offset=0;z=0;for(w=0;w>2]=16}HEAP16[sa>>1]=family;HEAP32[sa+4>>2]=addr;HEAP16[sa+2>>1]=_htons(port);break;case 10:addr=inetPton6(addr);zeroMemory(sa,28);if(addrlen){HEAP32[addrlen>>2]=28}HEAP32[sa>>2]=family;HEAP32[sa+8>>2]=addr[0];HEAP32[sa+12>>2]=addr[1];HEAP32[sa+16>>2]=addr[2];HEAP32[sa+20>>2]=addr[3];HEAP16[sa+2>>1]=_htons(port);break;default:return 5}return 0}var DNS={address_map:{id:1,addrs:{},names:{}},lookup_name:function(name){var res=inetPton4(name);if(res!==null){return name}res=inetPton6(name);if(res!==null){return name}var addr;if(DNS.address_map.addrs[name]){addr=DNS.address_map.addrs[name]}else{var id=DNS.address_map.id++;assert(id<65535,"exceeded max address mappings of 65535");addr="172.29."+(id&255)+"."+(id&65280);DNS.address_map.names[addr]=name;DNS.address_map.addrs[name]=addr}return addr},lookup_addr:function(addr){if(DNS.address_map.names[addr]){return DNS.address_map.names[addr]}return null}};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt:function(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=FS.getStream(dirfd);if(!dirstream)throw new FS.ErrnoError(8);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return PATH.join2(dir,path)},doStat:function(func,path,buf){try{var stat=func(path)}catch(e){if(e&&e.node&&PATH.normalize(path)!==PATH.normalize(FS.getPath(e.node))){return-54}throw e}HEAP32[buf>>2]=stat.dev;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAP32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;tempI64=[Math.floor(stat.atime.getTime()/1e3)>>>0,(tempDouble=Math.floor(stat.atime.getTime()/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAP32[buf+64>>2]=0;tempI64=[Math.floor(stat.mtime.getTime()/1e3)>>>0,(tempDouble=Math.floor(stat.mtime.getTime()/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAP32[buf+80>>2]=0;tempI64=[Math.floor(stat.ctime.getTime()/1e3)>>>0,(tempDouble=Math.floor(stat.ctime.getTime()/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];HEAP32[buf+96>>2]=0;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+104>>2]=tempI64[0],HEAP32[buf+108>>2]=tempI64[1];return 0},doMsync:function(addr,stream,len,flags,offset){var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream}};function ___syscall_accept4(fd,addr,addrlen,flags){try{var sock=getSocketFromFD(fd);var newsock=sock.sock_ops.accept(sock);if(addr){var errno=writeSockaddr(addr,newsock.family,DNS.lookup_name(newsock.daddr),newsock.dport,addrlen)}return newsock.stream.fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function inetNtop4(addr){return(addr&255)+"."+(addr>>8&255)+"."+(addr>>16&255)+"."+(addr>>24&255)}function inetNtop6(ints){var str="";var word=0;var longest=0;var lastzero=0;var zstart=0;var len=0;var i=0;var parts=[ints[0]&65535,ints[0]>>16,ints[1]&65535,ints[1]>>16,ints[2]&65535,ints[2]>>16,ints[3]&65535,ints[3]>>16];var hasipv4=true;var v4part="";for(i=0;i<5;i++){if(parts[i]!==0){hasipv4=false;break}}if(hasipv4){v4part=inetNtop4(parts[6]|parts[7]<<16);if(parts[5]===-1){str="::ffff:";str+=v4part;return str}if(parts[5]===0){str="::";if(v4part==="0.0.0.0")v4part="";if(v4part==="0.0.0.1")v4part="1";str+=v4part;return str}}for(word=0;word<8;word++){if(parts[word]===0){if(word-lastzero>1){len=0}lastzero=word;len++}if(len>longest){longest=len;zstart=word-longest+1}}for(word=0;word<8;word++){if(longest>1){if(parts[word]===0&&word>=zstart&&word>1];var port=_ntohs(HEAPU16[sa+2>>1]);var addr;switch(family){case 2:if(salen!==16){return{errno:28}}addr=HEAP32[sa+4>>2];addr=inetNtop4(addr);break;case 10:if(salen!==28){return{errno:28}}addr=[HEAP32[sa+8>>2],HEAP32[sa+12>>2],HEAP32[sa+16>>2],HEAP32[sa+20>>2]];addr=inetNtop6(addr);break;default:return{errno:5}}return{family:family,addr:addr,port:port}}function getSocketAddress(addrp,addrlen,allowNull){if(allowNull&&addrp===0)return null;var info=readSockaddr(addrp,addrlen);if(info.errno)throw new FS.ErrnoError(info.errno);info.addr=DNS.lookup_addr(info.addr)||info.addr;return info}function ___syscall_bind(fd,addr,addrlen){try{var sock=getSocketFromFD(fd);var info=getSocketAddress(addr,addrlen);sock.sock_ops.bind(sock,info.addr,info.port);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_chdir(path){try{path=SYSCALLS.getStr(path);FS.chdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_connect(fd,addr,addrlen){try{var sock=getSocketFromFD(fd);var info=getSocketAddress(addr,addrlen);sock.sock_ops.connect(sock,info.addr,info.port);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.createStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 5:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_getcwd(buf,size){try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size>>0,(tempDouble=id,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos>>2]=tempI64[0],HEAP32[dirp+pos+4>>2]=tempI64[1];tempI64=[(idx+1)*struct_size>>>0,(tempDouble=(idx+1)*struct_size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos+8>>2]=tempI64[0],HEAP32[dirp+pos+12>>2]=tempI64[1];HEAP16[dirp+pos+16>>1]=280;HEAP8[dirp+pos+18>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size;idx+=1}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_listen(fd,backlog){try{var sock=getSocketFromFD(fd);sock.sock_ops.listen(sock,backlog);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);path=PATH.normalize(path);if(path[path.length-1]==="/")path=path.substr(0,path.length-1);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~4352;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.doStat(nofollow?FS.lstat:FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?SYSCALLS.get():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_poll(fds,nfds,timeout){try{var nonzero=0;for(var i=0;i>2];var events=HEAP16[pollfd+4>>1];var mask=32;var stream=FS.getStream(fd);if(stream){mask=SYSCALLS.DEFAULT_POLLMASK;if(stream.stream_ops.poll){mask=stream.stream_ops.poll(stream)}}mask&=events|8|16;if(mask)nonzero++;HEAP16[pollfd+6>>1]=mask}return nonzero}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_readlinkat(dirfd,path,buf,bufsize){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_recvfrom(fd,buf,len,flags,addr,addrlen){try{var sock=getSocketFromFD(fd);var msg=sock.sock_ops.recvmsg(sock,len);if(!msg)return 0;if(addr){var errno=writeSockaddr(addr,sock.family,DNS.lookup_name(msg.addr),msg.port,addrlen)}HEAPU8.set(msg.buffer,buf);return msg.buffer.byteLength}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_renameat(olddirfd,oldpath,newdirfd,newpath){try{oldpath=SYSCALLS.getStr(oldpath);newpath=SYSCALLS.getStr(newpath);oldpath=SYSCALLS.calculateAt(olddirfd,oldpath);newpath=SYSCALLS.calculateAt(newdirfd,newpath);FS.rename(oldpath,newpath);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_sendmsg(fd,message,flags){try{var sock=getSocketFromFD(fd);var iov=HEAPU32[message+8>>2];var num=HEAP32[message+12>>2];var addr,port;var name=HEAPU32[message>>2];var namelen=HEAP32[message+4>>2];if(name){var info=readSockaddr(name,namelen);if(info.errno)return-info.errno;port=info.port;addr=DNS.lookup_addr(info.addr)||info.addr}var total=0;for(var i=0;i>2]}var view=new Uint8Array(total);var offset=0;for(var i=0;i>2];var iovlen=HEAP32[iov+(8*i+4)>>2];for(var j=0;j>0]}}return sock.sock_ops.sendmsg(sock,view,0,total,addr,port)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_sendto(fd,message,length,flags,addr,addr_len){try{var sock=getSocketFromFD(fd);var dest=getSocketAddress(addr,addr_len,true);if(!dest){return FS.write(sock.stream,HEAP8,message,length)}return sock.sock_ops.sendmsg(sock,HEAP8,message,length,dest.addr,dest.port)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_socket(domain,type,protocol){try{var sock=SOCKFS.createSocket(domain,type,protocol);return sock.stream.fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_statfs64(path,size,buf){try{path=SYSCALLS.getStr(path);HEAP32[buf+4>>2]=4096;HEAP32[buf+40>>2]=4096;HEAP32[buf+8>>2]=1e6;HEAP32[buf+12>>2]=5e5;HEAP32[buf+16>>2]=5e5;HEAP32[buf+20>>2]=FS.nextInode;HEAP32[buf+24>>2]=1e6;HEAP32[buf+28>>2]=42;HEAP32[buf+44>>2]=2;HEAP32[buf+36>>2]=255;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_symlink(target,linkpath){try{target=SYSCALLS.getStr(target);linkpath=SYSCALLS.getStr(linkpath);FS.symlink(target,linkpath);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(flags===0){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{abort("Invalid flags passed to unlinkat")}return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function __dlinit(main_dso_handle){}var dlopenMissingError="To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking";function __dlopen_js(filename,flag){abort(dlopenMissingError)}function __dlsym_js(handle,symbol){abort(dlopenMissingError)}function __emscripten_date_now(){return Date.now()}var nowIsMonotonic=true;function __emscripten_get_now_is_monotonic(){return nowIsMonotonic}function __emscripten_throw_longjmp(){throw Infinity}function readI53FromI64(ptr){return HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296}function __gmtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getUTCSeconds();HEAP32[tmPtr+4>>2]=date.getUTCMinutes();HEAP32[tmPtr+8>>2]=date.getUTCHours();HEAP32[tmPtr+12>>2]=date.getUTCDate();HEAP32[tmPtr+16>>2]=date.getUTCMonth();HEAP32[tmPtr+20>>2]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday}function __localtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var start=new Date(date.getFullYear(),0,1);var yday=(date.getTime()-start.getTime())/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function _tzset_impl(timezone,daylight,tzname){var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAP32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);function extractZone(date){var match=date.toTimeString().match(/\(([A-Za-z ]+)\)$/);return match?match[1]:"GMT"}var winterName=extractZone(winter);var summerName=extractZone(summer);var winterNamePtr=allocateUTF8(winterName);var summerNamePtr=allocateUTF8(summerName);if(summerOffset>2]=winterNamePtr;HEAPU32[tzname+4>>2]=summerNamePtr}else{HEAPU32[tzname>>2]=summerNamePtr;HEAPU32[tzname+4>>2]=winterNamePtr}}function __tzset_js(timezone,daylight,tzname){if(__tzset_js.called)return;__tzset_js.called=true;_tzset_impl(timezone,daylight,tzname)}function _abort(){abort("")}function runtimeKeepalivePush(){runtimeKeepaliveCounter+=1}function _emscripten_set_main_loop_timing(mode,value){Browser.mainLoop.timingMode=mode;Browser.mainLoop.timingValue=value;if(!Browser.mainLoop.func){return 1}if(!Browser.mainLoop.running){runtimeKeepalivePush();Browser.mainLoop.running=true}if(mode==0){Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_setTimeout(){var timeUntilNextTick=Math.max(0,Browser.mainLoop.tickStartTime+value-_emscripten_get_now())|0;setTimeout(Browser.mainLoop.runner,timeUntilNextTick)};Browser.mainLoop.method="timeout"}else if(mode==1){Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_rAF(){Browser.requestAnimationFrame(Browser.mainLoop.runner)};Browser.mainLoop.method="rAF"}else if(mode==2){if(typeof setImmediate=="undefined"){var setImmediates=[];var emscriptenMainLoopMessageId="setimmediate";var Browser_setImmediate_messageHandler=event=>{if(event.data===emscriptenMainLoopMessageId||event.data.target===emscriptenMainLoopMessageId){event.stopPropagation();setImmediates.shift()()}};addEventListener("message",Browser_setImmediate_messageHandler,true);setImmediate=function Browser_emulated_setImmediate(func){setImmediates.push(func);if(ENVIRONMENT_IS_WORKER){if(Module["setImmediates"]===undefined)Module["setImmediates"]=[];Module["setImmediates"].push(func);postMessage({target:emscriptenMainLoopMessageId})}else postMessage(emscriptenMainLoopMessageId,"*")}}Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_setImmediate(){setImmediate(Browser.mainLoop.runner)};Browser.mainLoop.method="immediate"}return 0}var _emscripten_get_now;_emscripten_get_now=()=>performance.now();function _emscripten_webgl_do_commit_frame(){if(!GL.currentContext||!GL.currentContext.GLctx){return-3}if(GL.currentContext.defaultFbo){GL.blitOffscreenFramebuffer(GL.currentContext);return 0}if(!GL.currentContext.attributes.explicitSwapControl){return-3}return 0}var _emscripten_webgl_commit_frame=_emscripten_webgl_do_commit_frame;function _proc_exit(code){EXITSTATUS=code;if(!keepRuntimeAlive()){if(Module["onExit"])Module["onExit"](code);ABORT=true}quit_(code,new ExitStatus(code))}function exitJS(status,implicit){EXITSTATUS=status;if(!keepRuntimeAlive()){exitRuntime()}_proc_exit(status)}var _exit=exitJS;function maybeExit(){if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}}function runtimeKeepalivePop(){runtimeKeepaliveCounter-=1}function setMainLoop(browserIterationFunc,fps,simulateInfiniteLoop,arg,noSetTiming){assert(!Browser.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters.");Browser.mainLoop.func=browserIterationFunc;Browser.mainLoop.arg=arg;var thisMainLoopId=Browser.mainLoop.currentlyRunningMainloop;function checkIsRunning(){if(thisMainLoopId0){var start=Date.now();var blocker=Browser.mainLoop.queue.shift();blocker.func(blocker.arg);if(Browser.mainLoop.remainingBlockers){var remaining=Browser.mainLoop.remainingBlockers;var next=remaining%1==0?remaining-1:Math.floor(remaining);if(blocker.counted){Browser.mainLoop.remainingBlockers=next}else{next=next+.5;Browser.mainLoop.remainingBlockers=(8*remaining+next)/9}}out('main loop blocker "'+blocker.name+'" took '+(Date.now()-start)+" ms");Browser.mainLoop.updateStatus();if(!checkIsRunning())return;setTimeout(Browser.mainLoop.runner,0);return}if(!checkIsRunning())return;Browser.mainLoop.currentFrameNumber=Browser.mainLoop.currentFrameNumber+1|0;if(Browser.mainLoop.timingMode==1&&Browser.mainLoop.timingValue>1&&Browser.mainLoop.currentFrameNumber%Browser.mainLoop.timingValue!=0){Browser.mainLoop.scheduler();return}else if(Browser.mainLoop.timingMode==0){Browser.mainLoop.tickStartTime=_emscripten_get_now()}Browser.mainLoop.runIter(browserIterationFunc);if(!checkIsRunning())return;if(typeof SDL=="object"&&SDL.audio&&SDL.audio.queueNewAudioData)SDL.audio.queueNewAudioData();Browser.mainLoop.scheduler()};if(!noSetTiming){if(fps&&fps>0)_emscripten_set_main_loop_timing(0,1e3/fps);else _emscripten_set_main_loop_timing(1,1);Browser.mainLoop.scheduler()}if(simulateInfiniteLoop){throw"unwind"}}function callUserCallback(func){if(runtimeExited||ABORT){return}try{func();maybeExit()}catch(e){handleException(e)}}function safeSetTimeout(func,timeout){runtimeKeepalivePush();return setTimeout(function(){runtimeKeepalivePop();callUserCallback(func)},timeout)}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}var Browser={mainLoop:{running:false,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Browser.mainLoop.scheduler=null;Browser.mainLoop.currentlyRunningMainloop++},resume:function(){Browser.mainLoop.currentlyRunningMainloop++;var timingMode=Browser.mainLoop.timingMode;var timingValue=Browser.mainLoop.timingValue;var func=Browser.mainLoop.func;Browser.mainLoop.func=null;setMainLoop(func,0,false,Browser.mainLoop.arg,true);_emscripten_set_main_loop_timing(timingMode,timingValue);Browser.mainLoop.scheduler()},updateStatus:function(){if(Module["setStatus"]){var message=Module["statusMessage"]||"Please wait...";var remaining=Browser.mainLoop.remainingBlockers;var expected=Browser.mainLoop.expectedBlockers;if(remaining){if(remaining{assert(img.complete,"Image "+name+" could not be decoded");var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);preloadedImages[name]=canvas;Browser.URLObject.revokeObjectURL(url);if(onload)onload(byteArray)};img.onerror=event=>{out("Image "+url+" could not be decoded");if(onerror)onerror()};img.src=url};Module["preloadPlugins"].push(imagePlugin);var audioPlugin={};audioPlugin["canHandle"]=function audioPlugin_canHandle(name){return!Module.noAudioDecoding&&name.substr(-4)in{".ogg":1,".wav":1,".mp3":1}};audioPlugin["handle"]=function audioPlugin_handle(byteArray,name,onload,onerror){var done=false;function finish(audio){if(done)return;done=true;preloadedAudios[name]=audio;if(onload)onload(byteArray)}function fail(){if(done)return;done=true;preloadedAudios[name]=new Audio;if(onerror)onerror()}if(Browser.hasBlobConstructor){try{var b=new Blob([byteArray],{type:Browser.getMimetype(name)})}catch(e){return fail()}var url=Browser.URLObject.createObjectURL(b);var audio=new Audio;audio.addEventListener("canplaythrough",()=>finish(audio),false);audio.onerror=function audio_onerror(event){if(done)return;err("warning: browser could not fully decode audio "+name+", trying slower base64 approach");function encode64(data){var BASE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var PAD="=";var ret="";var leftchar=0;var leftbits=0;for(var i=0;i=6){var curr=leftchar>>leftbits-6&63;leftbits-=6;ret+=BASE[curr]}}if(leftbits==2){ret+=BASE[(leftchar&3)<<4];ret+=PAD+PAD}else if(leftbits==4){ret+=BASE[(leftchar&15)<<2];ret+=PAD}return ret}audio.src="data:audio/x-"+name.substr(-3)+";base64,"+encode64(byteArray);finish(audio)};audio.src=url;safeSetTimeout(function(){finish(audio)},1e4)}else{return fail()}};Module["preloadPlugins"].push(audioPlugin);function pointerLockChange(){Browser.pointerLock=document["pointerLockElement"]===Module["canvas"]||document["mozPointerLockElement"]===Module["canvas"]||document["webkitPointerLockElement"]===Module["canvas"]||document["msPointerLockElement"]===Module["canvas"]}var canvas=Module["canvas"];if(canvas){canvas.requestPointerLock=canvas["requestPointerLock"]||canvas["mozRequestPointerLock"]||canvas["webkitRequestPointerLock"]||canvas["msRequestPointerLock"]||(()=>{});canvas.exitPointerLock=document["exitPointerLock"]||document["mozExitPointerLock"]||document["webkitExitPointerLock"]||document["msExitPointerLock"]||(()=>{});canvas.exitPointerLock=canvas.exitPointerLock.bind(document);document.addEventListener("pointerlockchange",pointerLockChange,false);document.addEventListener("mozpointerlockchange",pointerLockChange,false);document.addEventListener("webkitpointerlockchange",pointerLockChange,false);document.addEventListener("mspointerlockchange",pointerLockChange,false);if(Module["elementPointerLock"]){canvas.addEventListener("click",ev=>{if(!Browser.pointerLock&&Module["canvas"].requestPointerLock){Module["canvas"].requestPointerLock();ev.preventDefault()}},false)}}},handledByPreloadPlugin:function(byteArray,fullname,finish,onerror){Browser.init();var handled=false;Module["preloadPlugins"].forEach(function(plugin){if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled},createContext:function(canvas,useWebGL,setInModule,webGLContextAttributes){if(useWebGL&&Module.ctx&&canvas==Module.canvas)return Module.ctx;var ctx;var contextHandle;if(useWebGL){var contextAttributes={antialias:false,alpha:false,majorVersion:typeof WebGL2RenderingContext!="undefined"?2:1};if(webGLContextAttributes){for(var attribute in webGLContextAttributes){contextAttributes[attribute]=webGLContextAttributes[attribute]}}if(typeof GL!="undefined"){contextHandle=GL.createContext(canvas,contextAttributes);if(contextHandle){ctx=GL.getContext(contextHandle).GLctx}}}else{ctx=canvas.getContext("2d")}if(!ctx)return null;if(setInModule){if(!useWebGL)assert(typeof GLctx=="undefined","cannot set in module if GLctx is used, but we are a non-GL context that would replace it");Module.ctx=ctx;if(useWebGL)GL.makeContextCurrent(contextHandle);Module.useWebGL=useWebGL;Browser.moduleContextCreatedCallbacks.forEach(function(callback){callback()});Browser.init()}return ctx},destroyContext:function(canvas,useWebGL,setInModule){},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen:function(lockPointer,resizeCanvas){Browser.lockPointer=lockPointer;Browser.resizeCanvas=resizeCanvas;if(typeof Browser.lockPointer=="undefined")Browser.lockPointer=true;if(typeof Browser.resizeCanvas=="undefined")Browser.resizeCanvas=false;var canvas=Module["canvas"];function fullscreenChange(){Browser.isFullscreen=false;var canvasContainer=canvas.parentNode;if((document["fullscreenElement"]||document["mozFullScreenElement"]||document["msFullscreenElement"]||document["webkitFullscreenElement"]||document["webkitCurrentFullScreenElement"])===canvasContainer){canvas.exitFullscreen=Browser.exitFullscreen;if(Browser.lockPointer)canvas.requestPointerLock();Browser.isFullscreen=true;if(Browser.resizeCanvas){Browser.setFullscreenCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}else{canvasContainer.parentNode.insertBefore(canvas,canvasContainer);canvasContainer.parentNode.removeChild(canvasContainer);if(Browser.resizeCanvas){Browser.setWindowedCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}if(Module["onFullScreen"])Module["onFullScreen"](Browser.isFullscreen);if(Module["onFullscreen"])Module["onFullscreen"](Browser.isFullscreen)}if(!Browser.fullscreenHandlersInstalled){Browser.fullscreenHandlersInstalled=true;document.addEventListener("fullscreenchange",fullscreenChange,false);document.addEventListener("mozfullscreenchange",fullscreenChange,false);document.addEventListener("webkitfullscreenchange",fullscreenChange,false);document.addEventListener("MSFullscreenChange",fullscreenChange,false)}var canvasContainer=document.createElement("div");canvas.parentNode.insertBefore(canvasContainer,canvas);canvasContainer.appendChild(canvas);canvasContainer.requestFullscreen=canvasContainer["requestFullscreen"]||canvasContainer["mozRequestFullScreen"]||canvasContainer["msRequestFullscreen"]||(canvasContainer["webkitRequestFullscreen"]?()=>canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]):null)||(canvasContainer["webkitRequestFullScreen"]?()=>canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]):null);canvasContainer.requestFullscreen()},exitFullscreen:function(){if(!Browser.isFullscreen){return false}var CFS=document["exitFullscreen"]||document["cancelFullScreen"]||document["mozCancelFullScreen"]||document["msExitFullscreen"]||document["webkitCancelFullScreen"]||function(){};CFS.apply(document,[]);return true},nextRAF:0,fakeRequestAnimationFrame:function(func){var now=Date.now();if(Browser.nextRAF===0){Browser.nextRAF=now+1e3/60}else{while(now+2>=Browser.nextRAF){Browser.nextRAF+=1e3/60}}var delay=Math.max(Browser.nextRAF-now,0);setTimeout(func,delay)},requestAnimationFrame:function(func){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(func);return}var RAF=Browser.fakeRequestAnimationFrame;RAF(func)},safeSetTimeout:function(func){return safeSetTimeout(func)},safeRequestAnimationFrame:function(func){runtimeKeepalivePush();return Browser.requestAnimationFrame(function(){runtimeKeepalivePop();callUserCallback(func)})},getMimetype:function(name){return{"jpg":"image/jpeg","jpeg":"image/jpeg","png":"image/png","bmp":"image/bmp","ogg":"audio/ogg","wav":"audio/wav","mp3":"audio/mpeg"}[name.substr(name.lastIndexOf(".")+1)]},getUserMedia:function(func){if(!window.getUserMedia){window.getUserMedia=navigator["getUserMedia"]||navigator["mozGetUserMedia"]}window.getUserMedia(func)},getMovementX:function(event){return event["movementX"]||event["mozMovementX"]||event["webkitMovementX"]||0},getMovementY:function(event){return event["movementY"]||event["mozMovementY"]||event["webkitMovementY"]||0},getMouseWheelDelta:function(event){var delta=0;switch(event.type){case"DOMMouseScroll":delta=event.detail/3;break;case"mousewheel":delta=event.wheelDelta/120;break;case"wheel":delta=event.deltaY;switch(event.deltaMode){case 0:delta/=100;break;case 1:delta/=3;break;case 2:delta*=80;break;default:throw"unrecognized mouse wheel delta mode: "+event.deltaMode}break;default:throw"unrecognized mouse wheel event: "+event.type}return delta},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(event){if(Browser.pointerLock){if(event.type!="mousemove"&&"mozMovementX"in event){Browser.mouseMovementX=Browser.mouseMovementY=0}else{Browser.mouseMovementX=Browser.getMovementX(event);Browser.mouseMovementY=Browser.getMovementY(event)}if(typeof SDL!="undefined"){Browser.mouseX=SDL.mouseX+Browser.mouseMovementX;Browser.mouseY=SDL.mouseY+Browser.mouseMovementY}else{Browser.mouseX+=Browser.mouseMovementX;Browser.mouseY+=Browser.mouseMovementY}}else{var rect=Module["canvas"].getBoundingClientRect();var cw=Module["canvas"].width;var ch=Module["canvas"].height;var scrollX=typeof window.scrollX!="undefined"?window.scrollX:window.pageXOffset;var scrollY=typeof window.scrollY!="undefined"?window.scrollY:window.pageYOffset;if(event.type==="touchstart"||event.type==="touchend"||event.type==="touchmove"){var touch=event.touch;if(touch===undefined){return}var adjustedX=touch.pageX-(scrollX+rect.left);var adjustedY=touch.pageY-(scrollY+rect.top);adjustedX=adjustedX*(cw/rect.width);adjustedY=adjustedY*(ch/rect.height);var coords={x:adjustedX,y:adjustedY};if(event.type==="touchstart"){Browser.lastTouches[touch.identifier]=coords;Browser.touches[touch.identifier]=coords}else if(event.type==="touchend"||event.type==="touchmove"){var last=Browser.touches[touch.identifier];if(!last)last=coords;Browser.lastTouches[touch.identifier]=last;Browser.touches[touch.identifier]=coords}return}var x=event.pageX-(scrollX+rect.left);var y=event.pageY-(scrollY+rect.top);x=x*(cw/rect.width);y=y*(ch/rect.height);Browser.mouseMovementX=x-Browser.mouseX;Browser.mouseMovementY=y-Browser.mouseY;Browser.mouseX=x;Browser.mouseY=y}},resizeListeners:[],updateResizeListeners:function(){var canvas=Module["canvas"];Browser.resizeListeners.forEach(function(listener){listener(canvas.width,canvas.height)})},setCanvasSize:function(width,height,noUpdates){var canvas=Module["canvas"];Browser.updateCanvasDimensions(canvas,width,height);if(!noUpdates)Browser.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags|8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Module["canvas"]);Browser.updateResizeListeners()},setWindowedCanvasSize:function(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags&~8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Module["canvas"]);Browser.updateResizeListeners()},updateCanvasDimensions:function(canvas,wNative,hNative){if(wNative&&hNative){canvas.widthNative=wNative;canvas.heightNative=hNative}else{wNative=canvas.widthNative;hNative=canvas.heightNative}var w=wNative;var h=hNative;if(Module["forcedAspectRatio"]&&Module["forcedAspectRatio"]>0){if(w/h>2]:-1;source+=UTF8ToString(HEAP32[string+i*4>>2],len<0?undefined:len)}return source},createContext:function(canvas,webGLContextAttributes){if(webGLContextAttributes.renderViaOffscreenBackBuffer)webGLContextAttributes["preserveDrawingBuffer"]=true;if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},enableOffscreenFramebufferAttributes:function(webGLContextAttributes){webGLContextAttributes.renderViaOffscreenBackBuffer=true;webGLContextAttributes.preserveDrawingBuffer=true},createOffscreenFramebuffer:function(context){var gl=context.GLctx;var fbo=gl.createFramebuffer();gl.bindFramebuffer(36160,fbo);context.defaultFbo=fbo;context.defaultFboForbidBlitFramebuffer=false;if(gl.getContextAttributes().antialias){context.defaultFboForbidBlitFramebuffer=true}else{var firefoxMatch=navigator.userAgent.toLowerCase().match(/firefox\/(\d\d)/);if(firefoxMatch!=null){var firefoxVersion=firefoxMatch[1];context.defaultFboForbidBlitFramebuffer=firefoxVersion<67}}context.defaultColorTarget=gl.createTexture();context.defaultDepthTarget=gl.createRenderbuffer();GL.resizeOffscreenFramebuffer(context);gl.bindTexture(3553,context.defaultColorTarget);gl.texParameteri(3553,10241,9728);gl.texParameteri(3553,10240,9728);gl.texParameteri(3553,10242,33071);gl.texParameteri(3553,10243,33071);gl.texImage2D(3553,0,6408,gl.canvas.width,gl.canvas.height,0,6408,5121,null);gl.framebufferTexture2D(36160,36064,3553,context.defaultColorTarget,0);gl.bindTexture(3553,null);var depthTarget=gl.createRenderbuffer();gl.bindRenderbuffer(36161,context.defaultDepthTarget);gl.renderbufferStorage(36161,33189,gl.canvas.width,gl.canvas.height);gl.framebufferRenderbuffer(36160,36096,36161,context.defaultDepthTarget);gl.bindRenderbuffer(36161,null);var vertices=[-1,-1,-1,1,1,-1,1,1];var vb=gl.createBuffer();gl.bindBuffer(34962,vb);gl.bufferData(34962,new Float32Array(vertices),35044);gl.bindBuffer(34962,null);context.blitVB=vb;var vsCode="attribute vec2 pos;"+"varying lowp vec2 tex;"+"void main() { tex = pos * 0.5 + vec2(0.5,0.5); gl_Position = vec4(pos, 0.0, 1.0); }";var vs=gl.createShader(35633);gl.shaderSource(vs,vsCode);gl.compileShader(vs);var fsCode="varying lowp vec2 tex;"+"uniform sampler2D sampler;"+"void main() { gl_FragColor = texture2D(sampler, tex); }";var fs=gl.createShader(35632);gl.shaderSource(fs,fsCode);gl.compileShader(fs);var blitProgram=gl.createProgram();gl.attachShader(blitProgram,vs);gl.attachShader(blitProgram,fs);gl.linkProgram(blitProgram);context.blitProgram=blitProgram;context.blitPosLoc=gl.getAttribLocation(blitProgram,"pos");gl.useProgram(blitProgram);gl.uniform1i(gl.getUniformLocation(blitProgram,"sampler"),0);gl.useProgram(null);context.defaultVao=undefined;if(gl.createVertexArray){context.defaultVao=gl.createVertexArray();gl.bindVertexArray(context.defaultVao);gl.enableVertexAttribArray(context.blitPosLoc);gl.bindVertexArray(null)}},resizeOffscreenFramebuffer:function(context){var gl=context.GLctx;if(context.defaultColorTarget){var prevTextureBinding=gl.getParameter(32873);gl.bindTexture(3553,context.defaultColorTarget);gl.texImage2D(3553,0,6408,gl.drawingBufferWidth,gl.drawingBufferHeight,0,6408,5121,null);gl.bindTexture(3553,prevTextureBinding)}if(context.defaultDepthTarget){var prevRenderBufferBinding=gl.getParameter(36007);gl.bindRenderbuffer(36161,context.defaultDepthTarget);gl.renderbufferStorage(36161,33189,gl.drawingBufferWidth,gl.drawingBufferHeight);gl.bindRenderbuffer(36161,prevRenderBufferBinding)}},blitOffscreenFramebuffer:function(context){var gl=context.GLctx;var prevScissorTest=gl.getParameter(3089);if(prevScissorTest)gl.disable(3089);var prevFbo=gl.getParameter(36006);if(gl.blitFramebuffer&&!context.defaultFboForbidBlitFramebuffer){gl.bindFramebuffer(36008,context.defaultFbo);gl.bindFramebuffer(36009,null);gl.blitFramebuffer(0,0,gl.canvas.width,gl.canvas.height,0,0,gl.canvas.width,gl.canvas.height,16384,9728)}else{gl.bindFramebuffer(36160,null);var prevProgram=gl.getParameter(35725);gl.useProgram(context.blitProgram);var prevVB=gl.getParameter(34964);gl.bindBuffer(34962,context.blitVB);var prevActiveTexture=gl.getParameter(34016);gl.activeTexture(33984);var prevTextureBinding=gl.getParameter(32873);gl.bindTexture(3553,context.defaultColorTarget);var prevBlend=gl.getParameter(3042);if(prevBlend)gl.disable(3042);var prevCullFace=gl.getParameter(2884);if(prevCullFace)gl.disable(2884);var prevDepthTest=gl.getParameter(2929);if(prevDepthTest)gl.disable(2929);var prevStencilTest=gl.getParameter(2960);if(prevStencilTest)gl.disable(2960);function draw(){gl.vertexAttribPointer(context.blitPosLoc,2,5126,false,0,0);gl.drawArrays(5,0,4)}if(context.defaultVao){var prevVAO=gl.getParameter(34229);gl.bindVertexArray(context.defaultVao);draw();gl.bindVertexArray(prevVAO)}else{var prevVertexAttribPointer={buffer:gl.getVertexAttrib(context.blitPosLoc,34975),size:gl.getVertexAttrib(context.blitPosLoc,34339),stride:gl.getVertexAttrib(context.blitPosLoc,34340),type:gl.getVertexAttrib(context.blitPosLoc,34341),normalized:gl.getVertexAttrib(context.blitPosLoc,34922),pointer:gl.getVertexAttribOffset(context.blitPosLoc,34373)};var maxVertexAttribs=gl.getParameter(34921);var prevVertexAttribEnables=[];for(var i=0;i=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}__webgl_enable_WEBGL_multi_draw(GLctx);var exts=GLctx.getSupportedExtensions()||[];exts.forEach(function(ext){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}})}};function _emscripten_glActiveTexture(x0){GLctx["activeTexture"](x0)}function _emscripten_glAttachShader(program,shader){GLctx.attachShader(GL.programs[program],GL.shaders[shader])}function _emscripten_glBeginQuery(target,id){GLctx["beginQuery"](target,GL.queries[id])}function _emscripten_glBeginQueryEXT(target,id){GLctx.disjointTimerQueryExt["beginQueryEXT"](target,GL.queries[id])}function _emscripten_glBeginTransformFeedback(x0){GLctx["beginTransformFeedback"](x0)}function _emscripten_glBindAttribLocation(program,index,name){GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))}function _emscripten_glBindBuffer(target,buffer){if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])}function _emscripten_glBindBufferBase(target,index,buffer){GLctx["bindBufferBase"](target,index,GL.buffers[buffer])}function _emscripten_glBindBufferRange(target,index,buffer,offset,ptrsize){GLctx["bindBufferRange"](target,index,GL.buffers[buffer],offset,ptrsize)}function _emscripten_glBindFramebuffer(target,framebuffer){GLctx.bindFramebuffer(target,framebuffer?GL.framebuffers[framebuffer]:GL.currentContext.defaultFbo)}function _emscripten_glBindRenderbuffer(target,renderbuffer){GLctx.bindRenderbuffer(target,GL.renderbuffers[renderbuffer])}function _emscripten_glBindSampler(unit,sampler){GLctx["bindSampler"](unit,GL.samplers[sampler])}function _emscripten_glBindTexture(target,texture){GLctx.bindTexture(target,GL.textures[texture])}function _emscripten_glBindTransformFeedback(target,id){GLctx["bindTransformFeedback"](target,GL.transformFeedbacks[id])}function _emscripten_glBindVertexArray(vao){GLctx["bindVertexArray"](GL.vaos[vao])}function _emscripten_glBindVertexArrayOES(vao){GLctx["bindVertexArray"](GL.vaos[vao])}function _emscripten_glBlendColor(x0,x1,x2,x3){GLctx["blendColor"](x0,x1,x2,x3)}function _emscripten_glBlendEquation(x0){GLctx["blendEquation"](x0)}function _emscripten_glBlendEquationSeparate(x0,x1){GLctx["blendEquationSeparate"](x0,x1)}function _emscripten_glBlendFunc(x0,x1){GLctx["blendFunc"](x0,x1)}function _emscripten_glBlendFuncSeparate(x0,x1,x2,x3){GLctx["blendFuncSeparate"](x0,x1,x2,x3)}function _emscripten_glBlitFramebuffer(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9){GLctx["blitFramebuffer"](x0,x1,x2,x3,x4,x5,x6,x7,x8,x9)}function _emscripten_glBufferData(target,size,data,usage){if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}}else{GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)}}function _emscripten_glBufferSubData(target,offset,size,data){if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))}function _emscripten_glCheckFramebufferStatus(x0){return GLctx["checkFramebufferStatus"](x0)}function _emscripten_glClear(x0){GLctx["clear"](x0)}function _emscripten_glClearBufferfi(x0,x1,x2,x3){GLctx["clearBufferfi"](x0,x1,x2,x3)}function _emscripten_glClearBufferfv(buffer,drawbuffer,value){GLctx["clearBufferfv"](buffer,drawbuffer,HEAPF32,value>>2)}function _emscripten_glClearBufferiv(buffer,drawbuffer,value){GLctx["clearBufferiv"](buffer,drawbuffer,HEAP32,value>>2)}function _emscripten_glClearBufferuiv(buffer,drawbuffer,value){GLctx["clearBufferuiv"](buffer,drawbuffer,HEAPU32,value>>2)}function _emscripten_glClearColor(x0,x1,x2,x3){GLctx["clearColor"](x0,x1,x2,x3)}function _emscripten_glClearDepthf(x0){GLctx["clearDepth"](x0)}function _emscripten_glClearStencil(x0){GLctx["clearStencil"](x0)}function convertI32PairToI53(lo,hi){return(lo>>>0)+hi*4294967296}function _emscripten_glClientWaitSync(sync,flags,timeoutLo,timeoutHi){return GLctx.clientWaitSync(GL.syncs[sync],flags,convertI32PairToI53(timeoutLo,timeoutHi))}function _emscripten_glColorMask(red,green,blue,alpha){GLctx.colorMask(!!red,!!green,!!blue,!!alpha)}function _emscripten_glCompileShader(shader){GLctx.compileShader(GL.shaders[shader])}function _emscripten_glCompressedTexImage2D(target,level,internalFormat,width,height,border,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding||!imageSize){GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,imageSize,data)}else{GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,HEAPU8,data,imageSize)}return}GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,data?HEAPU8.subarray(data,data+imageSize):null)}function _emscripten_glCompressedTexImage3D(target,level,internalFormat,width,height,depth,border,imageSize,data){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexImage3D"](target,level,internalFormat,width,height,depth,border,imageSize,data)}else{GLctx["compressedTexImage3D"](target,level,internalFormat,width,height,depth,border,HEAPU8,data,imageSize)}}function _emscripten_glCompressedTexSubImage2D(target,level,xoffset,yoffset,width,height,format,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding||!imageSize){GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,imageSize,data)}else{GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,HEAPU8,data,imageSize)}return}GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,data?HEAPU8.subarray(data,data+imageSize):null)}function _emscripten_glCompressedTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data)}else{GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,HEAPU8,data,imageSize)}}function _emscripten_glCopyBufferSubData(x0,x1,x2,x3,x4){GLctx["copyBufferSubData"](x0,x1,x2,x3,x4)}function _emscripten_glCopyTexImage2D(x0,x1,x2,x3,x4,x5,x6,x7){GLctx["copyTexImage2D"](x0,x1,x2,x3,x4,x5,x6,x7)}function _emscripten_glCopyTexSubImage2D(x0,x1,x2,x3,x4,x5,x6,x7){GLctx["copyTexSubImage2D"](x0,x1,x2,x3,x4,x5,x6,x7)}function _emscripten_glCopyTexSubImage3D(x0,x1,x2,x3,x4,x5,x6,x7,x8){GLctx["copyTexSubImage3D"](x0,x1,x2,x3,x4,x5,x6,x7,x8)}function _emscripten_glCreateProgram(){var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id}function _emscripten_glCreateShader(shaderType){var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id}function _emscripten_glCullFace(x0){GLctx["cullFace"](x0)}function _emscripten_glDeleteBuffers(n,buffers){for(var i=0;i>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}}function _emscripten_glDeleteFramebuffers(n,framebuffers){for(var i=0;i>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}}function _emscripten_glDeleteProgram(id){if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null}function _emscripten_glDeleteQueries(n,ids){for(var i=0;i>2];var query=GL.queries[id];if(!query)continue;GLctx["deleteQuery"](query);GL.queries[id]=null}}function _emscripten_glDeleteQueriesEXT(n,ids){for(var i=0;i>2];var query=GL.queries[id];if(!query)continue;GLctx.disjointTimerQueryExt["deleteQueryEXT"](query);GL.queries[id]=null}}function _emscripten_glDeleteRenderbuffers(n,renderbuffers){for(var i=0;i>2];var renderbuffer=GL.renderbuffers[id];if(!renderbuffer)continue;GLctx.deleteRenderbuffer(renderbuffer);renderbuffer.name=0;GL.renderbuffers[id]=null}}function _emscripten_glDeleteSamplers(n,samplers){for(var i=0;i>2];var sampler=GL.samplers[id];if(!sampler)continue;GLctx["deleteSampler"](sampler);sampler.name=0;GL.samplers[id]=null}}function _emscripten_glDeleteShader(id){if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null}function _emscripten_glDeleteSync(id){if(!id)return;var sync=GL.syncs[id];if(!sync){GL.recordError(1281);return}GLctx.deleteSync(sync);sync.name=0;GL.syncs[id]=null}function _emscripten_glDeleteTextures(n,textures){for(var i=0;i>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}}function _emscripten_glDeleteTransformFeedbacks(n,ids){for(var i=0;i>2];var transformFeedback=GL.transformFeedbacks[id];if(!transformFeedback)continue;GLctx["deleteTransformFeedback"](transformFeedback);transformFeedback.name=0;GL.transformFeedbacks[id]=null}}function _emscripten_glDeleteVertexArrays(n,vaos){for(var i=0;i>2];GLctx["deleteVertexArray"](GL.vaos[id]);GL.vaos[id]=null}}function _emscripten_glDeleteVertexArraysOES(n,vaos){for(var i=0;i>2];GLctx["deleteVertexArray"](GL.vaos[id]);GL.vaos[id]=null}}function _emscripten_glDepthFunc(x0){GLctx["depthFunc"](x0)}function _emscripten_glDepthMask(flag){GLctx.depthMask(!!flag)}function _emscripten_glDepthRangef(x0,x1){GLctx["depthRange"](x0,x1)}function _emscripten_glDetachShader(program,shader){GLctx.detachShader(GL.programs[program],GL.shaders[shader])}function _emscripten_glDisable(x0){GLctx["disable"](x0)}function _emscripten_glDisableVertexAttribArray(index){GLctx.disableVertexAttribArray(index)}function _emscripten_glDrawArrays(mode,first,count){GLctx.drawArrays(mode,first,count)}function _emscripten_glDrawArraysInstanced(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}function _emscripten_glDrawArraysInstancedANGLE(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}function _emscripten_glDrawArraysInstancedARB(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}function _emscripten_glDrawArraysInstancedEXT(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}function _emscripten_glDrawArraysInstancedNV(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}var tempFixedLengthArray=[];function _emscripten_glDrawBuffers(n,bufs){var bufArray=tempFixedLengthArray[n];for(var i=0;i>2]}GLctx["drawBuffers"](bufArray)}function _emscripten_glDrawBuffersEXT(n,bufs){var bufArray=tempFixedLengthArray[n];for(var i=0;i>2]}GLctx["drawBuffers"](bufArray)}function _emscripten_glDrawBuffersWEBGL(n,bufs){var bufArray=tempFixedLengthArray[n];for(var i=0;i>2]}GLctx["drawBuffers"](bufArray)}function _emscripten_glDrawElements(mode,count,type,indices){GLctx.drawElements(mode,count,type,indices)}function _emscripten_glDrawElementsInstanced(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _emscripten_glDrawElementsInstancedANGLE(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _emscripten_glDrawElementsInstancedARB(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _emscripten_glDrawElementsInstancedEXT(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _emscripten_glDrawElementsInstancedNV(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _glDrawElements(mode,count,type,indices){GLctx.drawElements(mode,count,type,indices)}function _emscripten_glDrawRangeElements(mode,start,end,count,type,indices){_glDrawElements(mode,count,type,indices)}function _emscripten_glEnable(x0){GLctx["enable"](x0)}function _emscripten_glEnableVertexAttribArray(index){GLctx.enableVertexAttribArray(index)}function _emscripten_glEndQuery(x0){GLctx["endQuery"](x0)}function _emscripten_glEndQueryEXT(target){GLctx.disjointTimerQueryExt["endQueryEXT"](target)}function _emscripten_glEndTransformFeedback(){GLctx["endTransformFeedback"]()}function _emscripten_glFenceSync(condition,flags){var sync=GLctx.fenceSync(condition,flags);if(sync){var id=GL.getNewId(GL.syncs);sync.name=id;GL.syncs[id]=sync;return id}return 0}function _emscripten_glFinish(){GLctx["finish"]()}function _emscripten_glFlush(){GLctx["flush"]()}function _emscripten_glFramebufferRenderbuffer(target,attachment,renderbuffertarget,renderbuffer){GLctx.framebufferRenderbuffer(target,attachment,renderbuffertarget,GL.renderbuffers[renderbuffer])}function _emscripten_glFramebufferTexture2D(target,attachment,textarget,texture,level){GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)}function _emscripten_glFramebufferTextureLayer(target,attachment,texture,level,layer){GLctx.framebufferTextureLayer(target,attachment,GL.textures[texture],level,layer)}function _emscripten_glFrontFace(x0){GLctx["frontFace"](x0)}function __glGenObject(n,buffers,createFunction,objectTable){for(var i=0;i>2]=id}}function _emscripten_glGenBuffers(n,buffers){__glGenObject(n,buffers,"createBuffer",GL.buffers)}function _emscripten_glGenFramebuffers(n,ids){__glGenObject(n,ids,"createFramebuffer",GL.framebuffers)}function _emscripten_glGenQueries(n,ids){__glGenObject(n,ids,"createQuery",GL.queries)}function _emscripten_glGenQueriesEXT(n,ids){for(var i=0;i>2]=0;return}var id=GL.getNewId(GL.queries);query.name=id;GL.queries[id]=query;HEAP32[ids+i*4>>2]=id}}function _emscripten_glGenRenderbuffers(n,renderbuffers){__glGenObject(n,renderbuffers,"createRenderbuffer",GL.renderbuffers)}function _emscripten_glGenSamplers(n,samplers){__glGenObject(n,samplers,"createSampler",GL.samplers)}function _emscripten_glGenTextures(n,textures){__glGenObject(n,textures,"createTexture",GL.textures)}function _emscripten_glGenTransformFeedbacks(n,ids){__glGenObject(n,ids,"createTransformFeedback",GL.transformFeedbacks)}function _emscripten_glGenVertexArrays(n,arrays){__glGenObject(n,arrays,"createVertexArray",GL.vaos)}function _emscripten_glGenVertexArraysOES(n,arrays){__glGenObject(n,arrays,"createVertexArray",GL.vaos)}function _emscripten_glGenerateMipmap(x0){GLctx["generateMipmap"](x0)}function __glGetActiveAttribOrUniform(funcName,program,index,bufSize,length,size,type,name){program=GL.programs[program];var info=GLctx[funcName](program,index);if(info){var numBytesWrittenExclNull=name&&stringToUTF8(info.name,name,bufSize);if(length)HEAP32[length>>2]=numBytesWrittenExclNull;if(size)HEAP32[size>>2]=info.size;if(type)HEAP32[type>>2]=info.type}}function _emscripten_glGetActiveAttrib(program,index,bufSize,length,size,type,name){__glGetActiveAttribOrUniform("getActiveAttrib",program,index,bufSize,length,size,type,name)}function _emscripten_glGetActiveUniform(program,index,bufSize,length,size,type,name){__glGetActiveAttribOrUniform("getActiveUniform",program,index,bufSize,length,size,type,name)}function _emscripten_glGetActiveUniformBlockName(program,uniformBlockIndex,bufSize,length,uniformBlockName){program=GL.programs[program];var result=GLctx["getActiveUniformBlockName"](program,uniformBlockIndex);if(!result)return;if(uniformBlockName&&bufSize>0){var numBytesWrittenExclNull=stringToUTF8(result,uniformBlockName,bufSize);if(length)HEAP32[length>>2]=numBytesWrittenExclNull}else{if(length)HEAP32[length>>2]=0}}function _emscripten_glGetActiveUniformBlockiv(program,uniformBlockIndex,pname,params){if(!params){GL.recordError(1281);return}program=GL.programs[program];if(pname==35393){var name=GLctx["getActiveUniformBlockName"](program,uniformBlockIndex);HEAP32[params>>2]=name.length+1;return}var result=GLctx["getActiveUniformBlockParameter"](program,uniformBlockIndex,pname);if(result===null)return;if(pname==35395){for(var i=0;i>2]=result[i]}}else{HEAP32[params>>2]=result}}function _emscripten_glGetActiveUniformsiv(program,uniformCount,uniformIndices,pname,params){if(!params){GL.recordError(1281);return}if(uniformCount>0&&uniformIndices==0){GL.recordError(1281);return}program=GL.programs[program];var ids=[];for(var i=0;i>2])}var result=GLctx["getActiveUniforms"](program,ids,pname);if(!result)return;var len=result.length;for(var i=0;i>2]=result[i]}}function _emscripten_glGetAttachedShaders(program,maxCount,count,shaders){var result=GLctx.getAttachedShaders(GL.programs[program]);var len=result.length;if(len>maxCount){len=maxCount}HEAP32[count>>2]=len;for(var i=0;i>2]=id}}function _emscripten_glGetAttribLocation(program,name){return GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name))}function writeI53ToI64(ptr,num){HEAPU32[ptr>>2]=num;HEAPU32[ptr+4>>2]=(num-HEAPU32[ptr>>2])/4294967296}function emscriptenWebGLGet(name_,p,type){if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}var exts=GLctx.getSupportedExtensions()||[];ret=2*exts.length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i>>0]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err("GL_INVALID_ENUM in glGet"+type+"v: Unknown object returned from WebGL getParameter("+name_+")! (error: "+e+")");return}}break;default:GL.recordError(1280);err("GL_INVALID_ENUM in glGet"+type+"v: Native code calling glGet"+type+"v("+name_+") and it returns "+result+" of type "+typeof result+"!");return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p>>0]=ret?1:0;break}}function _emscripten_glGetBooleanv(name_,p){emscriptenWebGLGet(name_,p,4)}function _emscripten_glGetBufferParameteri64v(target,value,data){if(!data){GL.recordError(1281);return}writeI53ToI64(data,GLctx.getBufferParameter(target,value))}function _emscripten_glGetBufferParameteriv(target,value,data){if(!data){GL.recordError(1281);return}HEAP32[data>>2]=GLctx.getBufferParameter(target,value)}function _emscripten_glGetError(){var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error}function _emscripten_glGetFloatv(name_,p){emscriptenWebGLGet(name_,p,2)}function _emscripten_glGetFragDataLocation(program,name){return GLctx["getFragDataLocation"](GL.programs[program],UTF8ToString(name))}function _emscripten_glGetFramebufferAttachmentParameteriv(target,attachment,pname,params){var result=GLctx.getFramebufferAttachmentParameter(target,attachment,pname);if(result instanceof WebGLRenderbuffer||result instanceof WebGLTexture){result=result.name|0}HEAP32[params>>2]=result}function emscriptenWebGLGetIndexed(target,index,data,type){if(!data){GL.recordError(1281);return}var result=GLctx["getIndexedParameter"](target,index);var ret;switch(typeof result){case"boolean":ret=result?1:0;break;case"number":ret=result;break;case"object":if(result===null){switch(target){case 35983:case 35368:ret=0;break;default:{GL.recordError(1280);return}}}else if(result instanceof WebGLBuffer){ret=result.name|0}else{GL.recordError(1280);return}break;default:GL.recordError(1280);return}switch(type){case 1:writeI53ToI64(data,ret);break;case 0:HEAP32[data>>2]=ret;break;case 2:HEAPF32[data>>2]=ret;break;case 4:HEAP8[data>>0]=ret?1:0;break;default:throw"internal emscriptenWebGLGetIndexed() error, bad type: "+type}}function _emscripten_glGetInteger64i_v(target,index,data){emscriptenWebGLGetIndexed(target,index,data,1)}function _emscripten_glGetInteger64v(name_,p){emscriptenWebGLGet(name_,p,1)}function _emscripten_glGetIntegeri_v(target,index,data){emscriptenWebGLGetIndexed(target,index,data,0)}function _emscripten_glGetIntegerv(name_,p){emscriptenWebGLGet(name_,p,0)}function _emscripten_glGetInternalformativ(target,internalformat,pname,bufSize,params){if(bufSize<0){GL.recordError(1281);return}if(!params){GL.recordError(1281);return}var ret=GLctx["getInternalformatParameter"](target,internalformat,pname);if(ret===null)return;for(var i=0;i>2]=ret[i]}}function _emscripten_glGetProgramBinary(program,bufSize,length,binaryFormat,binary){GL.recordError(1282)}function _emscripten_glGetProgramInfoLog(program,maxLength,length,infoLog){var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _emscripten_glGetProgramiv(program,pname,p){if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){for(var i=0;i>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){for(var i=0;i>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){for(var i=0;i>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}}function _emscripten_glGetQueryObjecti64vEXT(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param;if(GL.currentContext.version<2){param=GLctx.disjointTimerQueryExt["getQueryObjectEXT"](query,pname)}else{param=GLctx["getQueryParameter"](query,pname)}var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}writeI53ToI64(params,ret)}function _emscripten_glGetQueryObjectivEXT(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param=GLctx.disjointTimerQueryExt["getQueryObjectEXT"](query,pname);var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}HEAP32[params>>2]=ret}function _emscripten_glGetQueryObjectui64vEXT(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param;if(GL.currentContext.version<2){param=GLctx.disjointTimerQueryExt["getQueryObjectEXT"](query,pname)}else{param=GLctx["getQueryParameter"](query,pname)}var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}writeI53ToI64(params,ret)}function _emscripten_glGetQueryObjectuiv(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param=GLctx["getQueryParameter"](query,pname);var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}HEAP32[params>>2]=ret}function _emscripten_glGetQueryObjectuivEXT(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param=GLctx.disjointTimerQueryExt["getQueryObjectEXT"](query,pname);var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}HEAP32[params>>2]=ret}function _emscripten_glGetQueryiv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx["getQuery"](target,pname)}function _emscripten_glGetQueryivEXT(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx.disjointTimerQueryExt["getQueryEXT"](target,pname)}function _emscripten_glGetRenderbufferParameteriv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx.getRenderbufferParameter(target,pname)}function _emscripten_glGetSamplerParameterfv(sampler,pname,params){if(!params){GL.recordError(1281);return}HEAPF32[params>>2]=GLctx["getSamplerParameter"](GL.samplers[sampler],pname)}function _emscripten_glGetSamplerParameteriv(sampler,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx["getSamplerParameter"](GL.samplers[sampler],pname)}function _emscripten_glGetShaderInfoLog(shader,maxLength,length,infoLog){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _emscripten_glGetShaderPrecisionFormat(shaderType,precisionType,range,precision){var result=GLctx.getShaderPrecisionFormat(shaderType,precisionType);HEAP32[range>>2]=result.rangeMin;HEAP32[range+4>>2]=result.rangeMax;HEAP32[precision>>2]=result.precision}function _emscripten_glGetShaderSource(shader,bufSize,length,source){var result=GLctx.getShaderSource(GL.shaders[shader]);if(!result)return;var numBytesWrittenExclNull=bufSize>0&&source?stringToUTF8(result,source,bufSize):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _emscripten_glGetShaderiv(shader,pname,p){if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}}function stringToNewUTF8(jsString){var length=lengthBytesUTF8(jsString)+1;var cString=_malloc(length);stringToUTF8(jsString,cString,length);return cString}function _emscripten_glGetString(name_){var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));ret=stringToNewUTF8(exts.join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s&&stringToNewUTF8(s);break;case 7938:var glVersion=GLctx.getParameter(7938);if(GL.currentContext.version>=2)glVersion="OpenGL ES 3.0 ("+glVersion+")";else{glVersion="OpenGL ES 2.0 ("+glVersion+")"}ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion="OpenGL ES GLSL ES "+ver_num[1]+" ("+glslVersion+")"}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret}function _emscripten_glGetStringi(name,index){if(GL.currentContext.version<2){GL.recordError(1282);return 0}var stringiCache=GL.stringiCache[name];if(stringiCache){if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index]}switch(name){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));exts=exts.map(function(e){return stringToNewUTF8(e)});stringiCache=GL.stringiCache[name]=exts;if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index];default:GL.recordError(1280);return 0}}function _emscripten_glGetSynciv(sync,pname,bufSize,length,values){if(bufSize<0){GL.recordError(1281);return}if(!values){GL.recordError(1281);return}var ret=GLctx.getSyncParameter(GL.syncs[sync],pname);if(ret!==null){HEAP32[values>>2]=ret;if(length)HEAP32[length>>2]=1}}function _emscripten_glGetTexParameterfv(target,pname,params){if(!params){GL.recordError(1281);return}HEAPF32[params>>2]=GLctx.getTexParameter(target,pname)}function _emscripten_glGetTexParameteriv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx.getTexParameter(target,pname)}function _emscripten_glGetTransformFeedbackVarying(program,index,bufSize,length,size,type,name){program=GL.programs[program];var info=GLctx["getTransformFeedbackVarying"](program,index);if(!info)return;if(name&&bufSize>0){var numBytesWrittenExclNull=stringToUTF8(info.name,name,bufSize);if(length)HEAP32[length>>2]=numBytesWrittenExclNull}else{if(length)HEAP32[length>>2]=0}if(size)HEAP32[size>>2]=info.size;if(type)HEAP32[type>>2]=info.type}function _emscripten_glGetUniformBlockIndex(program,uniformBlockName){return GLctx["getUniformBlockIndex"](GL.programs[program],UTF8ToString(uniformBlockName))}function _emscripten_glGetUniformIndices(program,uniformCount,uniformNames,uniformIndices){if(!uniformIndices){GL.recordError(1281);return}if(uniformCount>0&&(uniformNames==0||uniformIndices==0)){GL.recordError(1281);return}program=GL.programs[program];var names=[];for(var i=0;i>2]));var result=GLctx["getUniformIndices"](program,names);if(!result)return;var len=result.length;for(var i=0;i>2]=result[i]}}function webglGetLeftBracePos(name){return name.slice(-1)=="]"&&name.lastIndexOf("[")}function webglPrepareUniformLocationsBeforeFirstUse(program){var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};for(i=0;i0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex0?"["+webglLoc+"]":""))}return webglLoc}else{GL.recordError(1282)}}function emscriptenWebGLGetUniform(program,location,params,type){if(!params){GL.recordError(1281);return}program=GL.programs[program];webglPrepareUniformLocationsBeforeFirstUse(program);var data=GLctx.getUniform(program,webglGetUniformLocation(location));if(typeof data=="number"||typeof data=="boolean"){switch(type){case 0:HEAP32[params>>2]=data;break;case 2:HEAPF32[params>>2]=data;break}}else{for(var i=0;i>2]=data[i];break;case 2:HEAPF32[params+i*4>>2]=data[i];break}}}}function _emscripten_glGetUniformfv(program,location,params){emscriptenWebGLGetUniform(program,location,params,2)}function _emscripten_glGetUniformiv(program,location,params){emscriptenWebGLGetUniform(program,location,params,0)}function _emscripten_glGetUniformuiv(program,location,params){emscriptenWebGLGetUniform(program,location,params,0)}function emscriptenWebGLGetVertexAttrib(index,pname,params,type){if(!params){GL.recordError(1281);return}var data=GLctx.getVertexAttrib(index,pname);if(pname==34975){HEAP32[params>>2]=data&&data["name"]}else if(typeof data=="number"||typeof data=="boolean"){switch(type){case 0:HEAP32[params>>2]=data;break;case 2:HEAPF32[params>>2]=data;break;case 5:HEAP32[params>>2]=Math.fround(data);break}}else{for(var i=0;i>2]=data[i];break;case 2:HEAPF32[params+i*4>>2]=data[i];break;case 5:HEAP32[params+i*4>>2]=Math.fround(data[i]);break}}}}function _emscripten_glGetVertexAttribIiv(index,pname,params){emscriptenWebGLGetVertexAttrib(index,pname,params,0)}function _emscripten_glGetVertexAttribIuiv(index,pname,params){emscriptenWebGLGetVertexAttrib(index,pname,params,0)}function _emscripten_glGetVertexAttribPointerv(index,pname,pointer){if(!pointer){GL.recordError(1281);return}HEAP32[pointer>>2]=GLctx.getVertexAttribOffset(index,pname)}function _emscripten_glGetVertexAttribfv(index,pname,params){emscriptenWebGLGetVertexAttrib(index,pname,params,2)}function _emscripten_glGetVertexAttribiv(index,pname,params){emscriptenWebGLGetVertexAttrib(index,pname,params,5)}function _emscripten_glHint(x0,x1){GLctx["hint"](x0,x1)}function _emscripten_glInvalidateFramebuffer(target,numAttachments,attachments){var list=tempFixedLengthArray[numAttachments];for(var i=0;i>2]}GLctx["invalidateFramebuffer"](target,list)}function _emscripten_glInvalidateSubFramebuffer(target,numAttachments,attachments,x,y,width,height){var list=tempFixedLengthArray[numAttachments];for(var i=0;i>2]}GLctx["invalidateSubFramebuffer"](target,list,x,y,width,height)}function _emscripten_glIsBuffer(buffer){var b=GL.buffers[buffer];if(!b)return 0;return GLctx.isBuffer(b)}function _emscripten_glIsEnabled(x0){return GLctx["isEnabled"](x0)}function _emscripten_glIsFramebuffer(framebuffer){var fb=GL.framebuffers[framebuffer];if(!fb)return 0;return GLctx.isFramebuffer(fb)}function _emscripten_glIsProgram(program){program=GL.programs[program];if(!program)return 0;return GLctx.isProgram(program)}function _emscripten_glIsQuery(id){var query=GL.queries[id];if(!query)return 0;return GLctx["isQuery"](query)}function _emscripten_glIsQueryEXT(id){var query=GL.queries[id];if(!query)return 0;return GLctx.disjointTimerQueryExt["isQueryEXT"](query)}function _emscripten_glIsRenderbuffer(renderbuffer){var rb=GL.renderbuffers[renderbuffer];if(!rb)return 0;return GLctx.isRenderbuffer(rb)}function _emscripten_glIsSampler(id){var sampler=GL.samplers[id];if(!sampler)return 0;return GLctx["isSampler"](sampler)}function _emscripten_glIsShader(shader){var s=GL.shaders[shader];if(!s)return 0;return GLctx.isShader(s)}function _emscripten_glIsSync(sync){return GLctx.isSync(GL.syncs[sync])}function _emscripten_glIsTexture(id){var texture=GL.textures[id];if(!texture)return 0;return GLctx.isTexture(texture)}function _emscripten_glIsTransformFeedback(id){return GLctx["isTransformFeedback"](GL.transformFeedbacks[id])}function _emscripten_glIsVertexArray(array){var vao=GL.vaos[array];if(!vao)return 0;return GLctx["isVertexArray"](vao)}function _emscripten_glIsVertexArrayOES(array){var vao=GL.vaos[array];if(!vao)return 0;return GLctx["isVertexArray"](vao)}function _emscripten_glLineWidth(x0){GLctx["lineWidth"](x0)}function _emscripten_glLinkProgram(program){program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}}function _emscripten_glPauseTransformFeedback(){GLctx["pauseTransformFeedback"]()}function _emscripten_glPixelStorei(pname,param){if(pname==3317){GL.unpackAlignment=param}GLctx.pixelStorei(pname,param)}function _emscripten_glPolygonOffset(x0,x1){GLctx["polygonOffset"](x0,x1)}function _emscripten_glProgramBinary(program,binaryFormat,binary,length){GL.recordError(1280)}function _emscripten_glProgramParameteri(program,pname,value){GL.recordError(1280)}function _emscripten_glQueryCounterEXT(id,target){GLctx.disjointTimerQueryExt["queryCounterEXT"](GL.queries[id],target)}function _emscripten_glReadBuffer(x0){GLctx["readBuffer"](x0)}function computeUnpackAlignedImageSize(width,height,sizePerPixel,alignment){function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=width*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,alignment);return height*alignedRowSize}function __colorChannelsInGlTextureFormat(format){var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1}function heapObjectForWebGLType(type){type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16}function heapAccessShiftForWebGLHeap(heap){return 31-Math.clz32(heap.BYTES_PER_ELEMENT)}function emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat){var heap=heapObjectForWebGLType(type);var shift=heapAccessShiftForWebGLHeap(heap);var byteSize=1<>shift,pixels+bytes>>shift)}function _emscripten_glReadPixels(x,y,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels)}else{var heap=heapObjectForWebGLType(type);GLctx.readPixels(x,y,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)}function _emscripten_glReleaseShaderCompiler(){}function _emscripten_glRenderbufferStorage(x0,x1,x2,x3){GLctx["renderbufferStorage"](x0,x1,x2,x3)}function _emscripten_glRenderbufferStorageMultisample(x0,x1,x2,x3,x4){GLctx["renderbufferStorageMultisample"](x0,x1,x2,x3,x4)}function _emscripten_glResumeTransformFeedback(){GLctx["resumeTransformFeedback"]()}function _emscripten_glSampleCoverage(value,invert){GLctx.sampleCoverage(value,!!invert)}function _emscripten_glSamplerParameterf(sampler,pname,param){GLctx["samplerParameterf"](GL.samplers[sampler],pname,param)}function _emscripten_glSamplerParameterfv(sampler,pname,params){var param=HEAPF32[params>>2];GLctx["samplerParameterf"](GL.samplers[sampler],pname,param)}function _emscripten_glSamplerParameteri(sampler,pname,param){GLctx["samplerParameteri"](GL.samplers[sampler],pname,param)}function _emscripten_glSamplerParameteriv(sampler,pname,params){var param=HEAP32[params>>2];GLctx["samplerParameteri"](GL.samplers[sampler],pname,param)}function _emscripten_glScissor(x0,x1,x2,x3){GLctx["scissor"](x0,x1,x2,x3)}function _emscripten_glShaderBinary(){GL.recordError(1280)}function _emscripten_glShaderSource(shader,count,string,length){var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)}function _emscripten_glStencilFunc(x0,x1,x2){GLctx["stencilFunc"](x0,x1,x2)}function _emscripten_glStencilFuncSeparate(x0,x1,x2,x3){GLctx["stencilFuncSeparate"](x0,x1,x2,x3)}function _emscripten_glStencilMask(x0){GLctx["stencilMask"](x0)}function _emscripten_glStencilMaskSeparate(x0,x1){GLctx["stencilMaskSeparate"](x0,x1)}function _emscripten_glStencilOp(x0,x1,x2){GLctx["stencilOp"](x0,x1,x2)}function _emscripten_glStencilOpSeparate(x0,x1,x2,x3){GLctx["stencilOpSeparate"](x0,x1,x2,x3)}function _emscripten_glTexImage2D(target,level,internalFormat,width,height,border,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,null)}return}GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null)}function _emscripten_glTexImage3D(target,level,internalFormat,width,height,depth,border,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,null)}}function _emscripten_glTexParameterf(x0,x1,x2){GLctx["texParameterf"](x0,x1,x2)}function _emscripten_glTexParameterfv(target,pname,params){var param=HEAPF32[params>>2];GLctx.texParameterf(target,pname,param)}function _emscripten_glTexParameteri(x0,x1,x2){GLctx["texParameteri"](x0,x1,x2)}function _emscripten_glTexParameteriv(target,pname,params){var param=HEAP32[params>>2];GLctx.texParameteri(target,pname,param)}function _emscripten_glTexStorage2D(x0,x1,x2,x3,x4){GLctx["texStorage2D"](x0,x1,x2,x3,x4)}function _emscripten_glTexStorage3D(x0,x1,x2,x3,x4,x5){GLctx["texStorage3D"](x0,x1,x2,x3,x4,x5)}function _emscripten_glTexSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,null)}return}var pixelData=null;if(pixels)pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)}function _emscripten_glTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,null)}}function _emscripten_glTransformFeedbackVaryings(program,count,varyings,bufferMode){program=GL.programs[program];var vars=[];for(var i=0;i>2]));GLctx["transformFeedbackVaryings"](program,vars,bufferMode)}function _emscripten_glUniform1f(location,v0){GLctx.uniform1f(webglGetUniformLocation(location),v0)}var miniTempWebGLFloatBuffers=[];function _emscripten_glUniform1fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform1fv(webglGetUniformLocation(location),HEAPF32,value>>2,count);return}if(count<=288){var view=miniTempWebGLFloatBuffers[count-1];for(var i=0;i>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1fv(webglGetUniformLocation(location),view)}function _emscripten_glUniform1i(location,v0){GLctx.uniform1i(webglGetUniformLocation(location),v0)}var __miniTempWebGLIntBuffers=[];function _emscripten_glUniform1iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform1iv(webglGetUniformLocation(location),HEAP32,value>>2,count);return}if(count<=288){var view=__miniTempWebGLIntBuffers[count-1];for(var i=0;i>2]}}else{var view=HEAP32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1iv(webglGetUniformLocation(location),view)}function _emscripten_glUniform1ui(location,v0){GLctx.uniform1ui(webglGetUniformLocation(location),v0)}function _emscripten_glUniform1uiv(location,count,value){count&&GLctx.uniform1uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count)}function _emscripten_glUniform2f(location,v0,v1){GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)}function _emscripten_glUniform2fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform2fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*2);return}if(count<=144){var view=miniTempWebGLFloatBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2fv(webglGetUniformLocation(location),view)}function _emscripten_glUniform2i(location,v0,v1){GLctx.uniform2i(webglGetUniformLocation(location),v0,v1)}function _emscripten_glUniform2iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform2iv(webglGetUniformLocation(location),HEAP32,value>>2,count*2);return}if(count<=144){var view=__miniTempWebGLIntBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2iv(webglGetUniformLocation(location),view)}function _emscripten_glUniform2ui(location,v0,v1){GLctx.uniform2ui(webglGetUniformLocation(location),v0,v1)}function _emscripten_glUniform2uiv(location,count,value){count&&GLctx.uniform2uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*2)}function _emscripten_glUniform3f(location,v0,v1,v2){GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)}function _emscripten_glUniform3fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform3fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*3);return}if(count<=96){var view=miniTempWebGLFloatBuffers[3*count-1];for(var i=0;i<3*count;i+=3){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*12>>2)}GLctx.uniform3fv(webglGetUniformLocation(location),view)}function _emscripten_glUniform3i(location,v0,v1,v2){GLctx.uniform3i(webglGetUniformLocation(location),v0,v1,v2)}function _emscripten_glUniform3iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform3iv(webglGetUniformLocation(location),HEAP32,value>>2,count*3);return}if(count<=96){var view=__miniTempWebGLIntBuffers[3*count-1];for(var i=0;i<3*count;i+=3){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2];view[i+2]=HEAP32[value+(4*i+8)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*12>>2)}GLctx.uniform3iv(webglGetUniformLocation(location),view)}function _emscripten_glUniform3ui(location,v0,v1,v2){GLctx.uniform3ui(webglGetUniformLocation(location),v0,v1,v2)}function _emscripten_glUniform3uiv(location,count,value){count&&GLctx.uniform3uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*3)}function _emscripten_glUniform4f(location,v0,v1,v2,v3){GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)}function _emscripten_glUniform4fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform4fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<4*count;i+=4){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4fv(webglGetUniformLocation(location),view)}function _emscripten_glUniform4i(location,v0,v1,v2,v3){GLctx.uniform4i(webglGetUniformLocation(location),v0,v1,v2,v3)}function _emscripten_glUniform4iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform4iv(webglGetUniformLocation(location),HEAP32,value>>2,count*4);return}if(count<=72){var view=__miniTempWebGLIntBuffers[4*count-1];for(var i=0;i<4*count;i+=4){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2];view[i+2]=HEAP32[value+(4*i+8)>>2];view[i+3]=HEAP32[value+(4*i+12)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4iv(webglGetUniformLocation(location),view)}function _emscripten_glUniform4ui(location,v0,v1,v2,v3){GLctx.uniform4ui(webglGetUniformLocation(location),v0,v1,v2,v3)}function _emscripten_glUniform4uiv(location,count,value){count&&GLctx.uniform4uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*4)}function _emscripten_glUniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding){program=GL.programs[program];GLctx["uniformBlockBinding"](program,uniformBlockIndex,uniformBlockBinding)}function _emscripten_glUniformMatrix2fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count-1];for(var i=0;i<4*count;i+=4){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,view)}function _emscripten_glUniformMatrix2x3fv(location,count,transpose,value){count&&GLctx.uniformMatrix2x3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*6)}function _emscripten_glUniformMatrix2x4fv(location,count,transpose,value){count&&GLctx.uniformMatrix2x4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*8)}function _emscripten_glUniformMatrix3fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*9);return}if(count<=32){var view=miniTempWebGLFloatBuffers[9*count-1];for(var i=0;i<9*count;i+=9){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2];view[i+4]=HEAPF32[value+(4*i+16)>>2];view[i+5]=HEAPF32[value+(4*i+20)>>2];view[i+6]=HEAPF32[value+(4*i+24)>>2];view[i+7]=HEAPF32[value+(4*i+28)>>2];view[i+8]=HEAPF32[value+(4*i+32)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*36>>2)}GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,view)}function _emscripten_glUniformMatrix3x2fv(location,count,transpose,value){count&&GLctx.uniformMatrix3x2fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*6)}function _emscripten_glUniformMatrix3x4fv(location,count,transpose,value){count&&GLctx.uniformMatrix3x4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*12)}function _emscripten_glUniformMatrix4fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<16*count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)}function _emscripten_glUniformMatrix4x2fv(location,count,transpose,value){count&&GLctx.uniformMatrix4x2fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*8)}function _emscripten_glUniformMatrix4x3fv(location,count,transpose,value){count&&GLctx.uniformMatrix4x3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*12)}function _emscripten_glUseProgram(program){program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program}function _emscripten_glValidateProgram(program){GLctx.validateProgram(GL.programs[program])}function _emscripten_glVertexAttrib1f(x0,x1){GLctx["vertexAttrib1f"](x0,x1)}function _emscripten_glVertexAttrib1fv(index,v){GLctx.vertexAttrib1f(index,HEAPF32[v>>2])}function _emscripten_glVertexAttrib2f(x0,x1,x2){GLctx["vertexAttrib2f"](x0,x1,x2)}function _emscripten_glVertexAttrib2fv(index,v){GLctx.vertexAttrib2f(index,HEAPF32[v>>2],HEAPF32[v+4>>2])}function _emscripten_glVertexAttrib3f(x0,x1,x2,x3){GLctx["vertexAttrib3f"](x0,x1,x2,x3)}function _emscripten_glVertexAttrib3fv(index,v){GLctx.vertexAttrib3f(index,HEAPF32[v>>2],HEAPF32[v+4>>2],HEAPF32[v+8>>2])}function _emscripten_glVertexAttrib4f(x0,x1,x2,x3,x4){GLctx["vertexAttrib4f"](x0,x1,x2,x3,x4)}function _emscripten_glVertexAttrib4fv(index,v){GLctx.vertexAttrib4f(index,HEAPF32[v>>2],HEAPF32[v+4>>2],HEAPF32[v+8>>2],HEAPF32[v+12>>2])}function _emscripten_glVertexAttribDivisor(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _emscripten_glVertexAttribDivisorANGLE(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _emscripten_glVertexAttribDivisorARB(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _emscripten_glVertexAttribDivisorEXT(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _emscripten_glVertexAttribDivisorNV(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _emscripten_glVertexAttribI4i(x0,x1,x2,x3,x4){GLctx["vertexAttribI4i"](x0,x1,x2,x3,x4)}function _emscripten_glVertexAttribI4iv(index,v){GLctx.vertexAttribI4i(index,HEAP32[v>>2],HEAP32[v+4>>2],HEAP32[v+8>>2],HEAP32[v+12>>2])}function _emscripten_glVertexAttribI4ui(x0,x1,x2,x3,x4){GLctx["vertexAttribI4ui"](x0,x1,x2,x3,x4)}function _emscripten_glVertexAttribI4uiv(index,v){GLctx.vertexAttribI4ui(index,HEAPU32[v>>2],HEAPU32[v+4>>2],HEAPU32[v+8>>2],HEAPU32[v+12>>2])}function _emscripten_glVertexAttribIPointer(index,size,type,stride,ptr){GLctx["vertexAttribIPointer"](index,size,type,stride,ptr)}function _emscripten_glVertexAttribPointer(index,size,type,normalized,stride,ptr){GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)}function _emscripten_glViewport(x0,x1,x2,x3){GLctx["viewport"](x0,x1,x2,x3)}function _emscripten_glWaitSync(sync,flags,timeoutLo,timeoutHi){GLctx.waitSync(GL.syncs[sync],flags,convertI32PairToI53(timeoutLo,timeoutHi))}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}function _emscripten_set_main_loop(func,fps,simulateInfiniteLoop){var browserIterationFunc=getWasmTableEntry(func);setMainLoop(browserIterationFunc,fps,simulateInfiniteLoop)}var JSEvents={inEventHandler:0,removeAllEventListeners:function(){for(var i=JSEvents.eventHandlers.length-1;i>=0;--i){JSEvents._removeHandler(i)}JSEvents.eventHandlers=[];JSEvents.deferredCalls=[]},registerRemoveEventListeners:function(){if(!JSEvents.removeEventListenersRegistered){__ATEXIT__.push(JSEvents.removeAllEventListeners);JSEvents.removeEventListenersRegistered=true}},deferredCalls:[],deferCall:function(targetFunction,precedence,argsList){function arraysHaveEqualContent(arrA,arrB){if(arrA.length!=arrB.length)return false;for(var i in arrA){if(arrA[i]!=arrB[i])return false}return true}for(var i in JSEvents.deferredCalls){var call=JSEvents.deferredCalls[i];if(call.targetFunction==targetFunction&&arraysHaveEqualContent(call.argsList,argsList)){return}}JSEvents.deferredCalls.push({targetFunction:targetFunction,precedence:precedence,argsList:argsList});JSEvents.deferredCalls.sort(function(x,y){return x.precedence2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||(typeof document!="undefined"?document.querySelector(target):undefined);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _emscripten_webgl_do_create_context(target,attributes){var a=attributes>>2;var powerPreference=HEAP32[a+(24>>2)];var contextAttributes={"alpha":!!HEAP32[a+(0>>2)],"depth":!!HEAP32[a+(4>>2)],"stencil":!!HEAP32[a+(8>>2)],"antialias":!!HEAP32[a+(12>>2)],"premultipliedAlpha":!!HEAP32[a+(16>>2)],"preserveDrawingBuffer":!!HEAP32[a+(20>>2)],"powerPreference":__emscripten_webgl_power_preferences[powerPreference],"failIfMajorPerformanceCaveat":!!HEAP32[a+(28>>2)],majorVersion:HEAP32[a+(32>>2)],minorVersion:HEAP32[a+(36>>2)],enableExtensionsByDefault:HEAP32[a+(40>>2)],explicitSwapControl:HEAP32[a+(44>>2)],proxyContextToMainThread:HEAP32[a+(48>>2)],renderViaOffscreenBackBuffer:HEAP32[a+(52>>2)]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl&&!contextAttributes.renderViaOffscreenBackBuffer){contextAttributes.renderViaOffscreenBackBuffer=true}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle}var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;function _emscripten_webgl_destroy_context(contextHandle){if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)}function _emscripten_webgl_init_context_attributes(attributes){var a=attributes>>2;for(var i=0;i<56>>2;++i){HEAP32[a+i]=0}HEAP32[a+(0>>2)]=HEAP32[a+(4>>2)]=HEAP32[a+(12>>2)]=HEAP32[a+(16>>2)]=HEAP32[a+(32>>2)]=HEAP32[a+(40>>2)]=1}function _emscripten_webgl_make_context_current(contextHandle){var success=GL.makeContextCurrent(contextHandle);return success?0:-5}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_fdstat_get(fd,pbuf){try{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4;HEAP8[pbuf>>0]=type;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doReadv(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function convertI32PairToI53Checked(lo,hi){return hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var offset=convertI32PairToI53Checked(offset_low,offset_high);if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doWritev(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr}return ret}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _getTempRet0(){return getTempRet0()}function _getaddrinfo(node,service,hint,out){var addr=0;var port=0;var flags=0;var family=0;var type=0;var proto=0;var ai;function allocaddrinfo(family,type,proto,canon,addr,port){var sa,salen,ai;var errno;salen=family===10?28:16;addr=family===10?inetNtop6(addr):inetNtop4(addr);sa=_malloc(salen);errno=writeSockaddr(sa,family,addr,port);assert(!errno);ai=_malloc(32);HEAP32[ai+4>>2]=family;HEAP32[ai+8>>2]=type;HEAP32[ai+12>>2]=proto;HEAP32[ai+24>>2]=canon;HEAPU32[ai+20>>2]=sa;if(family===10){HEAP32[ai+16>>2]=28}else{HEAP32[ai+16>>2]=16}HEAP32[ai+28>>2]=0;return ai}if(hint){flags=HEAP32[hint>>2];family=HEAP32[hint+4>>2];type=HEAP32[hint+8>>2];proto=HEAP32[hint+12>>2]}if(type&&!proto){proto=type===2?17:6}if(!type&&proto){type=proto===17?2:1}if(proto===0){proto=6}if(type===0){type=1}if(!node&&!service){return-2}if(flags&~(1|2|4|1024|8|16|32)){return-1}if(hint!==0&&HEAP32[hint>>2]&2&&!node){return-1}if(flags&32){return-2}if(type!==0&&type!==1&&type!==2){return-7}if(family!==0&&family!==2&&family!==10){return-6}if(service){service=UTF8ToString(service);port=parseInt(service,10);if(isNaN(port)){if(flags&1024){return-2}return-8}}if(!node){if(family===0){family=2}if((flags&1)===0){if(family===2){addr=_htonl(2130706433)}else{addr=[0,0,0,1]}}ai=allocaddrinfo(family,type,proto,null,addr,port);HEAPU32[out>>2]=ai;return 0}node=UTF8ToString(node);addr=inetPton4(node);if(addr!==null){if(family===0||family===2){family=2}else if(family===10&&flags&8){addr=[0,0,_htonl(65535),addr];family=10}else{return-2}}else{addr=inetPton6(node);if(addr!==null){if(family===0||family===10){family=10}else{return-2}}}if(addr!=null){ai=allocaddrinfo(family,type,proto,node,addr,port);HEAPU32[out>>2]=ai;return 0}if(flags&4){return-2}node=DNS.lookup_name(node);addr=inetPton4(node);if(family===0){family=2}else if(family===10){addr=[0,0,_htonl(65535),addr]}ai=allocaddrinfo(family,type,proto,null,addr,port);HEAPU32[out>>2]=ai;return 0}function _getentropy(buffer,size){if(!_getentropy.randomDevice){_getentropy.randomDevice=getRandomDevice()}for(var i=0;i>0]=_getentropy.randomDevice()}return 0}function _glActiveTexture(x0){GLctx["activeTexture"](x0)}function _glAttachShader(program,shader){GLctx.attachShader(GL.programs[program],GL.shaders[shader])}function _glBeginTransformFeedback(x0){GLctx["beginTransformFeedback"](x0)}function _glBindAttribLocation(program,index,name){GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))}function _glBindBuffer(target,buffer){if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])}function _glBindBufferBase(target,index,buffer){GLctx["bindBufferBase"](target,index,GL.buffers[buffer])}function _glBindFramebuffer(target,framebuffer){GLctx.bindFramebuffer(target,framebuffer?GL.framebuffers[framebuffer]:GL.currentContext.defaultFbo)}function _glBindRenderbuffer(target,renderbuffer){GLctx.bindRenderbuffer(target,GL.renderbuffers[renderbuffer])}function _glBindTexture(target,texture){GLctx.bindTexture(target,GL.textures[texture])}function _glBindVertexArray(vao){GLctx["bindVertexArray"](GL.vaos[vao])}function _glBlendEquation(x0){GLctx["blendEquation"](x0)}function _glBlendFunc(x0,x1){GLctx["blendFunc"](x0,x1)}function _glBlendFuncSeparate(x0,x1,x2,x3){GLctx["blendFuncSeparate"](x0,x1,x2,x3)}function _glBlitFramebuffer(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9){GLctx["blitFramebuffer"](x0,x1,x2,x3,x4,x5,x6,x7,x8,x9)}function _glBufferData(target,size,data,usage){if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}}else{GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)}}function _glBufferSubData(target,offset,size,data){if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))}function _glCheckFramebufferStatus(x0){return GLctx["checkFramebufferStatus"](x0)}function _glClear(x0){GLctx["clear"](x0)}function _glClearBufferfv(buffer,drawbuffer,value){GLctx["clearBufferfv"](buffer,drawbuffer,HEAPF32,value>>2)}function _glClearColor(x0,x1,x2,x3){GLctx["clearColor"](x0,x1,x2,x3)}function _glClearDepthf(x0){GLctx["clearDepth"](x0)}function _glColorMask(red,green,blue,alpha){GLctx.colorMask(!!red,!!green,!!blue,!!alpha)}function _glCompileShader(shader){GLctx.compileShader(GL.shaders[shader])}function _glCompressedTexImage2D(target,level,internalFormat,width,height,border,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding||!imageSize){GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,imageSize,data)}else{GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,HEAPU8,data,imageSize)}return}GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,data?HEAPU8.subarray(data,data+imageSize):null)}function _glCompressedTexSubImage2D(target,level,xoffset,yoffset,width,height,format,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding||!imageSize){GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,imageSize,data)}else{GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,HEAPU8,data,imageSize)}return}GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,data?HEAPU8.subarray(data,data+imageSize):null)}function _glCompressedTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data)}else{GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,HEAPU8,data,imageSize)}}function _glCopyBufferSubData(x0,x1,x2,x3,x4){GLctx["copyBufferSubData"](x0,x1,x2,x3,x4)}function _glCopyTexSubImage2D(x0,x1,x2,x3,x4,x5,x6,x7){GLctx["copyTexSubImage2D"](x0,x1,x2,x3,x4,x5,x6,x7)}function _glCreateProgram(){var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id}function _glCreateShader(shaderType){var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id}function _glCullFace(x0){GLctx["cullFace"](x0)}function _glDeleteBuffers(n,buffers){for(var i=0;i>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}}function _glDeleteFramebuffers(n,framebuffers){for(var i=0;i>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}}function _glDeleteProgram(id){if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null}function _glDeleteRenderbuffers(n,renderbuffers){for(var i=0;i>2];var renderbuffer=GL.renderbuffers[id];if(!renderbuffer)continue;GLctx.deleteRenderbuffer(renderbuffer);renderbuffer.name=0;GL.renderbuffers[id]=null}}function _glDeleteShader(id){if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null}function _glDeleteTextures(n,textures){for(var i=0;i>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}}function _glDeleteVertexArrays(n,vaos){for(var i=0;i>2];GLctx["deleteVertexArray"](GL.vaos[id]);GL.vaos[id]=null}}function _glDepthFunc(x0){GLctx["depthFunc"](x0)}function _glDepthMask(flag){GLctx.depthMask(!!flag)}function _glDisable(x0){GLctx["disable"](x0)}function _glDisableVertexAttribArray(index){GLctx.disableVertexAttribArray(index)}function _glDrawArrays(mode,first,count){GLctx.drawArrays(mode,first,count)}function _glDrawArraysInstanced(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}function _glDrawBuffers(n,bufs){var bufArray=tempFixedLengthArray[n];for(var i=0;i>2]}GLctx["drawBuffers"](bufArray)}function _glDrawElementsInstanced(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _glEnable(x0){GLctx["enable"](x0)}function _glEnableVertexAttribArray(index){GLctx.enableVertexAttribArray(index)}function _glEndTransformFeedback(){GLctx["endTransformFeedback"]()}function _glFinish(){GLctx["finish"]()}function _glFramebufferRenderbuffer(target,attachment,renderbuffertarget,renderbuffer){GLctx.framebufferRenderbuffer(target,attachment,renderbuffertarget,GL.renderbuffers[renderbuffer])}function _glFramebufferTexture2D(target,attachment,textarget,texture,level){GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)}function _glFramebufferTextureLayer(target,attachment,texture,level,layer){GLctx.framebufferTextureLayer(target,attachment,GL.textures[texture],level,layer)}function _glFrontFace(x0){GLctx["frontFace"](x0)}function _glGenBuffers(n,buffers){__glGenObject(n,buffers,"createBuffer",GL.buffers)}function _glGenFramebuffers(n,ids){__glGenObject(n,ids,"createFramebuffer",GL.framebuffers)}function _glGenRenderbuffers(n,renderbuffers){__glGenObject(n,renderbuffers,"createRenderbuffer",GL.renderbuffers)}function _glGenTextures(n,textures){__glGenObject(n,textures,"createTexture",GL.textures)}function _glGenVertexArrays(n,arrays){__glGenObject(n,arrays,"createVertexArray",GL.vaos)}function _glGenerateMipmap(x0){GLctx["generateMipmap"](x0)}function _glGetError(){var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error}function _glGetFloatv(name_,p){emscriptenWebGLGet(name_,p,2)}function _glGetIntegerv(name_,p){emscriptenWebGLGet(name_,p,0)}function _glGetProgramBinary(program,bufSize,length,binaryFormat,binary){GL.recordError(1282)}function _glGetProgramInfoLog(program,maxLength,length,infoLog){var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetProgramiv(program,pname,p){if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){for(var i=0;i>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){for(var i=0;i>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){for(var i=0;i>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}}function _glGetShaderInfoLog(shader,maxLength,length,infoLog){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetShaderSource(shader,bufSize,length,source){var result=GLctx.getShaderSource(GL.shaders[shader]);if(!result)return;var numBytesWrittenExclNull=bufSize>0&&source?stringToUTF8(result,source,bufSize):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetShaderiv(shader,pname,p){if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}}function _glGetString(name_){var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));ret=stringToNewUTF8(exts.join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s&&stringToNewUTF8(s);break;case 7938:var glVersion=GLctx.getParameter(7938);if(GL.currentContext.version>=2)glVersion="OpenGL ES 3.0 ("+glVersion+")";else{glVersion="OpenGL ES 2.0 ("+glVersion+")"}ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion="OpenGL ES GLSL ES "+ver_num[1]+" ("+glslVersion+")"}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret}function _glGetStringi(name,index){if(GL.currentContext.version<2){GL.recordError(1282);return 0}var stringiCache=GL.stringiCache[name];if(stringiCache){if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index]}switch(name){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));exts=exts.map(function(e){return stringToNewUTF8(e)});stringiCache=GL.stringiCache[name]=exts;if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index];default:GL.recordError(1280);return 0}}function _glGetUniformBlockIndex(program,uniformBlockName){return GLctx["getUniformBlockIndex"](GL.programs[program],UTF8ToString(uniformBlockName))}function _glGetUniformLocation(program,name){name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex>2]}GLctx["invalidateFramebuffer"](target,list)}function _glLinkProgram(program){program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}}function _glPixelStorei(pname,param){if(pname==3317){GL.unpackAlignment=param}GLctx.pixelStorei(pname,param)}function _glProgramBinary(program,binaryFormat,binary,length){GL.recordError(1280)}function _glProgramParameteri(program,pname,value){GL.recordError(1280)}function _glReadBuffer(x0){GLctx["readBuffer"](x0)}function _glReadPixels(x,y,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels)}else{var heap=heapObjectForWebGLType(type);GLctx.readPixels(x,y,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)}function _glRenderbufferStorage(x0,x1,x2,x3){GLctx["renderbufferStorage"](x0,x1,x2,x3)}function _glRenderbufferStorageMultisample(x0,x1,x2,x3,x4){GLctx["renderbufferStorageMultisample"](x0,x1,x2,x3,x4)}function _glScissor(x0,x1,x2,x3){GLctx["scissor"](x0,x1,x2,x3)}function _glShaderSource(shader,count,string,length){var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)}function _glTexImage2D(target,level,internalFormat,width,height,border,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,null)}return}GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null)}function _glTexImage3D(target,level,internalFormat,width,height,depth,border,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,null)}}function _glTexParameterf(x0,x1,x2){GLctx["texParameterf"](x0,x1,x2)}function _glTexParameteri(x0,x1,x2){GLctx["texParameteri"](x0,x1,x2)}function _glTexStorage2D(x0,x1,x2,x3,x4){GLctx["texStorage2D"](x0,x1,x2,x3,x4)}function _glTexSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,null)}return}var pixelData=null;if(pixels)pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)}function _glTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,null)}}function _glTransformFeedbackVaryings(program,count,varyings,bufferMode){program=GL.programs[program];var vars=[];for(var i=0;i>2]));GLctx["transformFeedbackVaryings"](program,vars,bufferMode)}function _glUniform1f(location,v0){GLctx.uniform1f(webglGetUniformLocation(location),v0)}function _glUniform1i(location,v0){GLctx.uniform1i(webglGetUniformLocation(location),v0)}function _glUniform1iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform1iv(webglGetUniformLocation(location),HEAP32,value>>2,count);return}if(count<=288){var view=__miniTempWebGLIntBuffers[count-1];for(var i=0;i>2]}}else{var view=HEAP32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1iv(webglGetUniformLocation(location),view)}function _glUniform1ui(location,v0){GLctx.uniform1ui(webglGetUniformLocation(location),v0)}function _glUniform2f(location,v0,v1){GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)}function _glUniform2fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform2fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*2);return}if(count<=144){var view=miniTempWebGLFloatBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2fv(webglGetUniformLocation(location),view)}function _glUniform2i(location,v0,v1){GLctx.uniform2i(webglGetUniformLocation(location),v0,v1)}function _glUniform2iv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform2iv(webglGetUniformLocation(location),HEAP32,value>>2,count*2);return}if(count<=144){var view=__miniTempWebGLIntBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2iv(webglGetUniformLocation(location),view)}function _glUniform3f(location,v0,v1,v2){GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)}function _glUniform3fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform3fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*3);return}if(count<=96){var view=miniTempWebGLFloatBuffers[3*count-1];for(var i=0;i<3*count;i+=3){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*12>>2)}GLctx.uniform3fv(webglGetUniformLocation(location),view)}function _glUniform3i(location,v0,v1,v2){GLctx.uniform3i(webglGetUniformLocation(location),v0,v1,v2)}function _glUniform4f(location,v0,v1,v2,v3){GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)}function _glUniform4fv(location,count,value){if(GL.currentContext.version>=2){count&&GLctx.uniform4fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<4*count;i+=4){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4fv(webglGetUniformLocation(location),view)}function _glUniform4i(location,v0,v1,v2,v3){GLctx.uniform4i(webglGetUniformLocation(location),v0,v1,v2,v3)}function _glUniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding){program=GL.programs[program];GLctx["uniformBlockBinding"](program,uniformBlockIndex,uniformBlockBinding)}function _glUniformMatrix2fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count-1];for(var i=0;i<4*count;i+=4){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniformMatrix2fv(webglGetUniformLocation(location),!!transpose,view)}function _glUniformMatrix3fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*9);return}if(count<=32){var view=miniTempWebGLFloatBuffers[9*count-1];for(var i=0;i<9*count;i+=9){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2];view[i+4]=HEAPF32[value+(4*i+16)>>2];view[i+5]=HEAPF32[value+(4*i+20)>>2];view[i+6]=HEAPF32[value+(4*i+24)>>2];view[i+7]=HEAPF32[value+(4*i+28)>>2];view[i+8]=HEAPF32[value+(4*i+32)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*36>>2)}GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,view)}function _glUniformMatrix4fv(location,count,transpose,value){if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<16*count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)}function _glUseProgram(program){program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program}function _glVertexAttrib4f(x0,x1,x2,x3,x4){GLctx["vertexAttrib4f"](x0,x1,x2,x3,x4)}function _glVertexAttrib4fv(index,v){GLctx.vertexAttrib4f(index,HEAPF32[v>>2],HEAPF32[v+4>>2],HEAPF32[v+8>>2],HEAPF32[v+12>>2])}function _glVertexAttribDivisor(index,divisor){GLctx["vertexAttribDivisor"](index,divisor)}function _glVertexAttribI4ui(x0,x1,x2,x3,x4){GLctx["vertexAttribI4ui"](x0,x1,x2,x3,x4)}function _glVertexAttribIPointer(index,size,type,stride,ptr){GLctx["vertexAttribIPointer"](index,size,type,stride,ptr)}function _glVertexAttribPointer(index,size,type,normalized,stride,ptr){GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)}function _glViewport(x0,x1,x2,x3){GLctx["viewport"](x0,x1,x2,x3)}var GodotRuntime={get_func:function(ptr){return wasmTable.get(ptr)},error:function(){err.apply(null,Array.from(arguments))},print:function(){out.apply(null,Array.from(arguments))},malloc:function(p_size){return _malloc(p_size)},free:function(p_ptr){_free(p_ptr)},getHeapValue:function(p_ptr,p_type){return getValue(p_ptr,p_type)},setHeapValue:function(p_ptr,p_value,p_type){setValue(p_ptr,p_value,p_type)},heapSub:function(p_heap,p_ptr,p_len){const bytes=p_heap.BYTES_PER_ELEMENT;return p_heap.subarray(p_ptr/bytes,p_ptr/bytes+p_len)},heapSlice:function(p_heap,p_ptr,p_len){const bytes=p_heap.BYTES_PER_ELEMENT;return p_heap.slice(p_ptr/bytes,p_ptr/bytes+p_len)},heapCopy:function(p_dst,p_src,p_ptr){const bytes=p_src.BYTES_PER_ELEMENT;return p_dst.set(p_src,p_ptr/bytes)},parseString:function(p_ptr){return UTF8ToString(p_ptr)},parseStringArray:function(p_ptr,p_size){const strings=[];const ptrs=GodotRuntime.heapSub(HEAP32,p_ptr,p_size);ptrs.forEach(function(ptr){strings.push(GodotRuntime.parseString(ptr))});return strings},strlen:function(p_str){return lengthBytesUTF8(p_str)},allocString:function(p_str){const length=GodotRuntime.strlen(p_str)+1;const c_str=GodotRuntime.malloc(length);stringToUTF8(p_str,c_str,length);return c_str},allocStringArray:function(p_strings){const size=p_strings.length;const c_ptr=GodotRuntime.malloc(size*4);for(let i=0;i>2)+i]=GodotRuntime.allocString(p_strings[i])}return c_ptr},freeStringArray:function(p_ptr,p_len){for(let i=0;i>2)+i])}GodotRuntime.free(p_ptr)},stringToHeap:function(p_str,p_ptr,p_len){return stringToUTF8Array(p_str,HEAP8,p_ptr,p_len)}};var GodotConfig={canvas:null,locale:"en",canvas_resize_policy:2,virtual_keyboard:false,persistent_drops:false,on_execute:null,on_exit:null,init_config:function(p_opts){GodotConfig.canvas_resize_policy=p_opts["canvasResizePolicy"];GodotConfig.canvas=p_opts["canvas"];GodotConfig.locale=p_opts["locale"]||GodotConfig.locale;GodotConfig.virtual_keyboard=p_opts["virtualKeyboard"];GodotConfig.persistent_drops=!!p_opts["persistentDrops"];GodotConfig.on_execute=p_opts["onExecute"];GodotConfig.on_exit=p_opts["onExit"];if(p_opts["focusCanvas"]){GodotConfig.canvas.focus()}},locate_file:function(file){return Module["locateFile"](file)},clear:function(){GodotConfig.canvas=null;GodotConfig.locale="en";GodotConfig.canvas_resize_policy=2;GodotConfig.virtual_keyboard=false;GodotConfig.persistent_drops=false;GodotConfig.on_execute=null;GodotConfig.on_exit=null}};var ERRNO_CODES={};var GodotFS={_idbfs:false,_syncing:false,_mount_points:[],is_persistent:function(){return GodotFS._idbfs?1:0},init:function(persistentPaths){GodotFS._idbfs=false;if(!Array.isArray(persistentPaths)){return Promise.reject(new Error("Persistent paths must be an array"))}if(!persistentPaths.length){return Promise.resolve()}GodotFS._mount_points=persistentPaths.slice();function createRecursive(dir){try{FS.stat(dir)}catch(e){if(e.errno!==ERRNO_CODES.ENOENT){throw e}FS.mkdirTree(dir)}}GodotFS._mount_points.forEach(function(path){createRecursive(path);FS.mount(IDBFS,{},path)});return new Promise(function(resolve,reject){FS.syncfs(true,function(err){if(err){GodotFS._mount_points=[];GodotFS._idbfs=false;GodotRuntime.print(`IndexedDB not available: ${err.message}`)}else{GodotFS._idbfs=true}resolve(err)})})},deinit:function(){GodotFS._mount_points.forEach(function(path){try{FS.unmount(path)}catch(e){GodotRuntime.print("Already unmounted",e)}if(GodotFS._idbfs&&IDBFS.dbs[path]){IDBFS.dbs[path].close();delete IDBFS.dbs[path]}});GodotFS._mount_points=[];GodotFS._idbfs=false;GodotFS._syncing=false},sync:function(){if(GodotFS._syncing){GodotRuntime.error("Already syncing!");return Promise.resolve()}GodotFS._syncing=true;return new Promise(function(resolve,reject){FS.syncfs(false,function(error){if(error){GodotRuntime.error(`Failed to save IDB file system: ${error.message}`)}GodotFS._syncing=false;resolve(error)})})},copy_to_fs:function(path,buffer){const idx=path.lastIndexOf("/");let dir="/";if(idx>0){dir=path.slice(0,idx)}try{FS.stat(dir)}catch(e){if(e.errno!==ERRNO_CODES.ENOENT){throw e}FS.mkdirTree(dir)}FS.writeFile(path,new Uint8Array(buffer))}};var GodotOS={request_quit:function(){},_async_cbs:[],_fs_sync_promise:null,atexit:function(p_promise_cb){GodotOS._async_cbs.push(p_promise_cb)},cleanup:function(exit_code){const cb=GodotConfig.on_exit;GodotFS.deinit();GodotConfig.clear();if(cb){cb(exit_code)}},finish_async:function(callback){GodotOS._fs_sync_promise.then(function(err){const promises=[];GodotOS._async_cbs.forEach(function(cb){promises.push(new Promise(cb))});return Promise.all(promises)}).then(function(){return GodotFS.sync()}).then(function(err){setTimeout(function(){callback()},0)})}};var GodotAudio={ctx:null,input:null,driver:null,interval:0,init:function(mix_rate,latency,onstatechange,onlatencyupdate){const opts={};if(mix_rate){opts["sampleRate"]=mix_rate}const ctx=new(window.AudioContext||window.webkitAudioContext)(opts);GodotAudio.ctx=ctx;ctx.onstatechange=function(){let state=0;switch(ctx.state){case"suspended":state=0;break;case"running":state=1;break;case"closed":state=2;break}onstatechange(state)};ctx.onstatechange();GodotAudio.interval=setInterval(function(){let computed_latency=0;if(ctx.baseLatency){computed_latency+=GodotAudio.ctx.baseLatency}if(ctx.outputLatency){computed_latency+=GodotAudio.ctx.outputLatency}onlatencyupdate(computed_latency)},1e3);GodotOS.atexit(GodotAudio.close_async);return ctx.destination.channelCount},create_input:function(callback){if(GodotAudio.input){return 0}function gotMediaInput(stream){try{GodotAudio.input=GodotAudio.ctx.createMediaStreamSource(stream);callback(GodotAudio.input)}catch(e){GodotRuntime.error("Failed creaating input.",e)}}if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){navigator.mediaDevices.getUserMedia({"audio":true}).then(gotMediaInput,function(e){GodotRuntime.error("Error getting user media.",e)})}else{if(!navigator.getUserMedia){navigator.getUserMedia=navigator.webkitGetUserMedia||navigator.mozGetUserMedia}if(!navigator.getUserMedia){GodotRuntime.error("getUserMedia not available.");return 1}navigator.getUserMedia({"audio":true},gotMediaInput,function(e){GodotRuntime.print(e)})}return 0},close_async:function(resolve,reject){const ctx=GodotAudio.ctx;GodotAudio.ctx=null;if(!ctx){resolve();return}if(GodotAudio.interval){clearInterval(GodotAudio.interval);GodotAudio.interval=0}if(GodotAudio.input){GodotAudio.input.disconnect();GodotAudio.input=null}let closed=Promise.resolve();if(GodotAudio.driver){closed=GodotAudio.driver.close()}closed.then(function(){return ctx.close()}).then(function(){ctx.onstatechange=null;resolve()}).catch(function(e){ctx.onstatechange=null;GodotRuntime.error("Error closing AudioContext",e);resolve()})}};function _godot_audio_capture_start(){return GodotAudio.create_input(function(input){input.connect(GodotAudio.driver.get_node())})}function _godot_audio_capture_stop(){if(GodotAudio.input){const tracks=GodotAudio.input["mediaStream"]["getTracks"]();for(let i=0;i=size){const high=size-wpos;wbuf.set(buffer.subarray(wpos,size));pending_samples-=high;wpos=0}if(pending_samples>0){wbuf.set(buffer.subarray(wpos,wpos+pending_samples),tot_sent-pending_samples)}port.postMessage({"cmd":"chunk","data":wbuf.subarray(0,tot_sent)});wpos+=pending_samples;pending_samples=0}this.receive=function(recv_buf){const buffer=GodotRuntime.heapSub(HEAPF32,p_in_buf,p_in_size);const from=rpos;let to_write=recv_buf.length;let high=0;if(rpos+to_write>=p_in_size){high=p_in_size-rpos;buffer.set(recv_buf.subarray(0,high),rpos);to_write-=high;rpos=0}if(to_write){buffer.set(recv_buf.subarray(high,to_write),rpos)}in_callback(from,recv_buf.length);rpos+=to_write};this.consumed=function(size,port){pending_samples+=size;send(port)}}GodotAudioWorklet.ring_buffer=new RingBuffer;GodotAudioWorklet.promise.then(function(){const node=GodotAudioWorklet.worklet;const buffer=GodotRuntime.heapSlice(HEAPF32,p_out_buf,p_out_size);node.connect(GodotAudio.ctx.destination);node.port.postMessage({"cmd":"start_nothreads","data":[buffer,p_in_size]});node.port.onmessage=function(event){if(!GodotAudioWorklet.worklet){return}if(event.data["cmd"]==="read"){const read=event.data["data"];GodotAudioWorklet.ring_buffer.consumed(read,GodotAudioWorklet.worklet.port)}else if(event.data["cmd"]==="input"){const buf=event.data["data"];if(buf.length>p_in_size){GodotRuntime.error("Input chunk is too big");return}GodotAudioWorklet.ring_buffer.receive(buf)}else{GodotRuntime.error(event.data)}}})},get_node:function(){return GodotAudioWorklet.worklet},close:function(){return new Promise(function(resolve,reject){if(GodotAudioWorklet.promise===null){return}GodotAudioWorklet.promise.then(function(){GodotAudioWorklet.worklet.port.postMessage({"cmd":"stop","data":null});GodotAudioWorklet.worklet.disconnect();GodotAudioWorklet.worklet=null;GodotAudioWorklet.promise=null;resolve()}).catch(function(err){})})}};function _godot_audio_worklet_create(channels){try{GodotAudioWorklet.create(channels)}catch(e){GodotRuntime.error("Error starting AudioDriverWorklet",e);return 1}return 0}function _godot_audio_worklet_start_no_threads(p_out_buf,p_out_size,p_out_callback,p_in_buf,p_in_size,p_in_callback){const out_callback=GodotRuntime.get_func(p_out_callback);const in_callback=GodotRuntime.get_func(p_in_callback);GodotAudioWorklet.start_no_threads(p_out_buf,p_out_size,out_callback,p_in_buf,p_in_size,in_callback)}function _godot_js_config_canvas_id_get(p_ptr,p_ptr_max){GodotRuntime.stringToHeap(`#${GodotConfig.canvas.id}`,p_ptr,p_ptr_max)}function _godot_js_config_locale_get(p_ptr,p_ptr_max){GodotRuntime.stringToHeap(GodotConfig.locale,p_ptr,p_ptr_max)}var GodotDisplayCursor={shape:"default",visible:true,cursors:{},set_style:function(style){GodotConfig.canvas.style.cursor=style},set_shape:function(shape){GodotDisplayCursor.shape=shape;let css=shape;if(shape in GodotDisplayCursor.cursors){const c=GodotDisplayCursor.cursors[shape];css=`url("${c.url}") ${c.x} ${c.y}, default`}if(GodotDisplayCursor.visible){GodotDisplayCursor.set_style(css)}},clear:function(){GodotDisplayCursor.set_style("");GodotDisplayCursor.shape="default";GodotDisplayCursor.visible=true;Object.keys(GodotDisplayCursor.cursors).forEach(function(key){URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);delete GodotDisplayCursor.cursors[key]})},lockPointer:function(){const canvas=GodotConfig.canvas;if(canvas.requestPointerLock){canvas.requestPointerLock()}},releasePointer:function(){if(document.exitPointerLock){document.exitPointerLock()}},isPointerLocked:function(){return document.pointerLockElement===GodotConfig.canvas}};var GodotEventListeners={handlers:[],has:function(target,event,method,capture){return GodotEventListeners.handlers.findIndex(function(e){return e.target===target&&e.event===event&&e.method===method&&e.capture===capture})!==-1},add:function(target,event,method,capture){if(GodotEventListeners.has(target,event,method,capture)){return}function Handler(p_target,p_event,p_method,p_capture){this.target=p_target;this.event=p_event;this.method=p_method;this.capture=p_capture}GodotEventListeners.handlers.push(new Handler(target,event,method,capture));target.addEventListener(event,method,capture)},clear:function(){GodotEventListeners.handlers.forEach(function(h){h.target.removeEventListener(h.event,h.method,h.capture)});GodotEventListeners.handlers.length=0}};function _emscripten_webgl_do_get_current_context(){return GL.currentContext?GL.currentContext.handle:0}var _emscripten_webgl_get_current_context=_emscripten_webgl_do_get_current_context;var GodotDisplayScreen={desired_size:[0,0],canvas_scale:1,hidpi:true,getPixelRatio:function(){return GodotDisplayScreen.hidpi?window.devicePixelRatio||1:1},isFullscreen:function(){const elem=document.fullscreenElement||document.mozFullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement;if(elem){return elem===GodotConfig.canvas}return document.fullscreen||document.mozFullScreen||document.webkitIsFullscreen},hasFullscreen:function(){return document.fullscreenEnabled||document.mozFullScreenEnabled||document.webkitFullscreenEnabled},requestFullscreen:function(){if(!GodotDisplayScreen.hasFullscreen()){return 1}const canvas=GodotConfig.canvas;try{const promise=(canvas.requestFullscreen||canvas.msRequestFullscreen||canvas.mozRequestFullScreen||canvas.mozRequestFullscreen||canvas.webkitRequestFullscreen).call(canvas);if(promise){promise.catch(function(){})}}catch(e){return 1}return 0},exitFullscreen:function(){if(!GodotDisplayScreen.isFullscreen()){return 0}try{const promise=document.exitFullscreen();if(promise){promise.catch(function(){})}}catch(e){return 1}return 0},_updateGL:function(){const gl_context_handle=_emscripten_webgl_get_current_context();const gl=GL.getContext(gl_context_handle);if(gl){GL.resizeOffscreenFramebuffer(gl)}},updateSize:function(){const isFullscreen=GodotDisplayScreen.isFullscreen();const wantsFullWindow=GodotConfig.canvas_resize_policy===2;const noResize=GodotConfig.canvas_resize_policy===0;const wwidth=GodotDisplayScreen.desired_size[0];const wheight=GodotDisplayScreen.desired_size[1];const canvas=GodotConfig.canvas;let width=wwidth;let height=wheight;if(noResize){if(canvas.width!==width||canvas.height!==height){GodotDisplayScreen.desired_size=[canvas.width,canvas.height];GodotDisplayScreen._updateGL();return 1}return 0}const scale=GodotDisplayScreen.getPixelRatio();if(isFullscreen||wantsFullWindow){width=window.innerWidth*scale;height=window.innerHeight*scale}const csw=`${width/scale}px`;const csh=`${height/scale}px`;const canvasWidth=canvas.width;const canvasHeight=canvas.height;const targetWidth=Math.floor(width*GodotDisplayScreen.canvas_scale);const targetHeight=Math.floor(height*GodotDisplayScreen.canvas_scale);if(canvas.style.width!==csw||canvas.style.height!==csh||canvas.width!==targetWidth||canvas.height!==targetHeight){canvas.width=targetWidth;canvas.height=targetHeight;canvas.style.width=csw;canvas.style.height=csh;document.documentElement.style.width=csw;document.documentElement.style.height=csh;document.body.style.width=csw;document.body.style.height=csh;GodotDisplayScreen._updateGL();return 1}return 0}};var GodotDisplayVK={textinput:null,textarea:null,available:function(){return GodotConfig.virtual_keyboard&&"ontouchstart"in window},init:function(input_cb){function create(what){const elem=document.createElement(what);elem.style.display="none";elem.style.position="absolute";elem.style.zIndex="-1";elem.style.background="transparent";elem.style.padding="0px";elem.style.margin="0px";elem.style.overflow="hidden";elem.style.width="0px";elem.style.height="0px";elem.style.border="0px";elem.style.outline="none";elem.readonly=true;elem.disabled=true;GodotEventListeners.add(elem,"input",function(evt){const c_str=GodotRuntime.allocString(elem.value);input_cb(c_str,elem.selectionEnd);GodotRuntime.free(c_str)},false);GodotEventListeners.add(elem,"blur",function(evt){elem.style.display="none";elem.readonly=true;elem.disabled=true},false);GodotConfig.canvas.insertAdjacentElement("beforebegin",elem);return elem}GodotDisplayVK.textinput=create("input");GodotDisplayVK.textarea=create("textarea");GodotDisplayVK.textinput.style.fontSize="16px";GodotDisplayVK.textarea.style.fontSize="16px";GodotDisplayVK.updateSize()},show:function(text,type,start,end){if(!GodotDisplayVK.textinput||!GodotDisplayVK.textarea){return}if(GodotDisplayVK.textinput.style.display!==""||GodotDisplayVK.textarea.style.display!==""){GodotDisplayVK.hide()}GodotDisplayVK.updateSize();let elem=GodotDisplayVK.textinput;switch(type){case 0:elem.inputmode="text";break;case 1:elem=GodotDisplayVK.textarea;break;case 2:elem.inputmode="numeric";break;case 3:elem.inputmode="decimal";break;case 4:elem.inputmode="tel";break;case 5:elem.inputmode="email";break;case 6:elem.inputmode="text";break;case 7:elem.inputmode="url";break;default:elem.inputmode="text";break}elem.readonly=false;elem.disabled=false;elem.value=text;elem.style.display="block";elem.focus();elem.setSelectionRange(start,end)},hide:function(){if(!GodotDisplayVK.textinput||!GodotDisplayVK.textarea){return}[GodotDisplayVK.textinput,GodotDisplayVK.textarea].forEach(function(elem){elem.blur();elem.style.display="none";elem.value=""})},updateSize:function(){if(!GodotDisplayVK.textinput||!GodotDisplayVK.textarea){return}const rect=GodotConfig.canvas.getBoundingClientRect();function update(elem){elem.style.left=`${rect.left}px`;elem.style.top=`${rect.top}px`;elem.style.width=`${rect.width}px`;elem.style.height=`${rect.height}px`}update(GodotDisplayVK.textinput);update(GodotDisplayVK.textarea)},clear:function(){if(GodotDisplayVK.textinput){GodotDisplayVK.textinput.remove();GodotDisplayVK.textinput=null}if(GodotDisplayVK.textarea){GodotDisplayVK.textarea.remove();GodotDisplayVK.textarea=null}}};var GodotDisplay={window_icon:"",findDPI:function(){function testDPI(dpi){return window.matchMedia(`(max-resolution: ${dpi}dpi)`).matches}function bisect(low,high,func){const mid=parseInt((high-low)/2+low,10);if(high-low<=1){return func(high)?high:low}if(func(mid)){return bisect(low,mid,func)}return bisect(mid,high,func)}try{const dpi=bisect(0,800,testDPI);return dpi>=96?dpi:96}catch(e){return 96}}};function _godot_js_display_alert(p_text){window.alert(GodotRuntime.parseString(p_text))}function _godot_js_display_canvas_focus(){GodotConfig.canvas.focus()}function _godot_js_display_canvas_is_focused(){return document.activeElement===GodotConfig.canvas}function _godot_js_display_clipboard_get(callback){const func=GodotRuntime.get_func(callback);try{navigator.clipboard.readText().then(function(result){const ptr=GodotRuntime.allocString(result);func(ptr);GodotRuntime.free(ptr)}).catch(function(e){})}catch(e){}}function _godot_js_display_clipboard_set(p_text){const text=GodotRuntime.parseString(p_text);if(!navigator.clipboard||!navigator.clipboard.writeText){return 1}navigator.clipboard.writeText(text).catch(function(e){GodotRuntime.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:",e)});return 0}function _godot_js_display_cursor_is_hidden(){return!GodotDisplayCursor.visible}function _godot_js_display_cursor_is_locked(){return GodotDisplayCursor.isPointerLocked()?1:0}function _godot_js_display_cursor_lock_set(p_lock){if(p_lock){GodotDisplayCursor.lockPointer()}else{GodotDisplayCursor.releasePointer()}}function _godot_js_display_cursor_set_custom_shape(p_shape,p_ptr,p_len,p_hotspot_x,p_hotspot_y){const shape=GodotRuntime.parseString(p_shape);const old_shape=GodotDisplayCursor.cursors[shape];if(p_len>0){const png=new Blob([GodotRuntime.heapSlice(HEAPU8,p_ptr,p_len)],{type:"image/png"});const url=URL.createObjectURL(png);GodotDisplayCursor.cursors[shape]={url:url,x:p_hotspot_x,y:p_hotspot_y}}else{delete GodotDisplayCursor.cursors[shape]}if(shape===GodotDisplayCursor.shape){GodotDisplayCursor.set_shape(GodotDisplayCursor.shape)}if(old_shape){URL.revokeObjectURL(old_shape.url)}}function _godot_js_display_cursor_set_shape(p_string){GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string))}function _godot_js_display_cursor_set_visible(p_visible){const visible=p_visible!==0;if(visible===GodotDisplayCursor.visible){return}GodotDisplayCursor.visible=visible;if(visible){GodotDisplayCursor.set_shape(GodotDisplayCursor.shape)}else{GodotDisplayCursor.set_style("none")}}function _godot_js_display_desired_size_set(width,height){GodotDisplayScreen.desired_size=[width,height];GodotDisplayScreen.updateSize()}function _godot_js_display_fullscreen_cb(callback){const canvas=GodotConfig.canvas;const func=GodotRuntime.get_func(callback);function change_cb(evt){if(evt.target===canvas){func(GodotDisplayScreen.isFullscreen())}}GodotEventListeners.add(document,"fullscreenchange",change_cb,false);GodotEventListeners.add(document,"mozfullscreenchange",change_cb,false);GodotEventListeners.add(document,"webkitfullscreenchange",change_cb,false)}function _godot_js_display_fullscreen_exit(){return GodotDisplayScreen.exitFullscreen()}function _godot_js_display_fullscreen_request(){return GodotDisplayScreen.requestFullscreen()}function _godot_js_display_glGetBufferSubData(target,offset,size,data){const gl_context_handle=_emscripten_webgl_get_current_context();const gl=GL.getContext(gl_context_handle);if(gl){gl.GLctx["getBufferSubData"](target,offset,HEAPU8,data,size)}}function _godot_js_display_has_webgl(p_version){if(p_version!==1&&p_version!==2){return false}try{return!!document.createElement("canvas").getContext(p_version===2?"webgl2":"webgl")}catch(e){}return false}function _godot_js_display_is_swap_ok_cancel(){const win=["Windows","Win64","Win32","WinCE"];const plat=navigator.platform||"";if(win.indexOf(plat)!==-1){return 1}return 0}function _godot_js_display_notification_cb(callback,p_enter,p_exit,p_in,p_out){const canvas=GodotConfig.canvas;const func=GodotRuntime.get_func(callback);const notif=[p_enter,p_exit,p_in,p_out];["mouseover","mouseleave","focus","blur"].forEach(function(evt_name,idx){GodotEventListeners.add(canvas,evt_name,function(){func(notif[idx])},true)})}function _godot_js_display_pixel_ratio_get(){return GodotDisplayScreen.getPixelRatio()}function _godot_js_display_screen_dpi_get(){return GodotDisplay.findDPI()}function _godot_js_display_screen_size_get(width,height){const scale=GodotDisplayScreen.getPixelRatio();GodotRuntime.setHeapValue(width,window.screen.width*scale,"i32");GodotRuntime.setHeapValue(height,window.screen.height*scale,"i32")}function _godot_js_display_setup_canvas(p_width,p_height,p_fullscreen,p_hidpi){const canvas=GodotConfig.canvas;GodotEventListeners.add(canvas,"contextmenu",function(ev){ev.preventDefault()},false);GodotEventListeners.add(canvas,"webglcontextlost",function(ev){alert("WebGL context lost, please reload the page");ev.preventDefault()},false);GodotEventListeners.add(canvas,"webglcontextrestored",function(ev){alert("WebGL context restored, please reload the page");ev.preventDefault()},false);GodotDisplayScreen.hidpi=!!p_hidpi;switch(GodotConfig.canvas_resize_policy){case 0:GodotDisplayScreen.desired_size=[canvas.width,canvas.height];break;case 1:GodotDisplayScreen.desired_size=[p_width,p_height];break;default:canvas.style.position="absolute";canvas.style.top=0;canvas.style.left=0;break}GodotDisplayScreen.updateSize();if(p_fullscreen){GodotDisplayScreen.requestFullscreen()}}function _godot_js_display_size_update(){const updated=GodotDisplayScreen.updateSize();if(updated){GodotDisplayVK.updateSize()}return updated}function _godot_js_display_touchscreen_is_available(){return"ontouchstart"in window}function _godot_js_display_vk_available(){return GodotDisplayVK.available()}function _godot_js_display_vk_cb(p_input_cb){const input_cb=GodotRuntime.get_func(p_input_cb);if(GodotDisplayVK.available()){GodotDisplayVK.init(input_cb)}}function _godot_js_display_vk_hide(){GodotDisplayVK.hide()}function _godot_js_display_vk_show(p_text,p_type,p_start,p_end){const text=GodotRuntime.parseString(p_text);const start=p_start>0?p_start:0;const end=p_end>0?p_end:start;GodotDisplayVK.show(text,p_type,start,end)}function _godot_js_display_window_blur_cb(callback){const func=GodotRuntime.get_func(callback);GodotEventListeners.add(window,"blur",function(){func()},false)}function _godot_js_display_window_icon_set(p_ptr,p_len){let link=document.getElementById("-gd-engine-icon");if(link===null){link=document.createElement("link");link.rel="icon";link.id="-gd-engine-icon";document.head.appendChild(link)}const old_icon=GodotDisplay.window_icon;const png=new Blob([GodotRuntime.heapSlice(HEAPU8,p_ptr,p_len)],{type:"image/png"});GodotDisplay.window_icon=URL.createObjectURL(png);link.href=GodotDisplay.window_icon;if(old_icon){URL.revokeObjectURL(old_icon)}}function _godot_js_display_window_size_get(p_width,p_height){if(GodotConfig.canvas==null){GodotRuntime.setHeapValue(p_width,1024,"i32");GodotRuntime.setHeapValue(p_height,1024,"i32")}else{GodotRuntime.setHeapValue(p_width,GodotConfig.canvas.width,"i32");GodotRuntime.setHeapValue(p_height,GodotConfig.canvas.height,"i32")}}function _godot_js_display_window_title_set(p_data){document.title=GodotRuntime.parseString(p_data)}function _godot_js_eval(p_js,p_use_global_ctx,p_union_ptr,p_byte_arr,p_byte_arr_write,p_callback){const js_code=GodotRuntime.parseString(p_js);let eval_ret=null;try{if(p_use_global_ctx){const global_eval=eval;eval_ret=global_eval(js_code)}else{eval_ret=eval(js_code)}}catch(e){GodotRuntime.error(e)}switch(typeof eval_ret){case"boolean":GodotRuntime.setHeapValue(p_union_ptr,eval_ret,"i32");return 1;case"number":GodotRuntime.setHeapValue(p_union_ptr,eval_ret,"double");return 3;case"string":GodotRuntime.setHeapValue(p_union_ptr,GodotRuntime.allocString(eval_ret),"*");return 4;case"object":if(eval_ret===null){break}if(ArrayBuffer.isView(eval_ret)&&!(eval_ret instanceof Uint8Array)){eval_ret=new Uint8Array(eval_ret.buffer)}else if(eval_ret instanceof ArrayBuffer){eval_ret=new Uint8Array(eval_ret)}if(eval_ret instanceof Uint8Array){const func=GodotRuntime.get_func(p_callback);const bytes_ptr=func(p_byte_arr,p_byte_arr_write,eval_ret.length);HEAPU8.set(eval_ret,bytes_ptr);return 20}break}return 0}var IDHandler={_last_id:0,_references:{},get:function(p_id){return IDHandler._references[p_id]},add:function(p_data){const id=++IDHandler._last_id;IDHandler._references[id]=p_data;return id},remove:function(p_id){delete IDHandler._references[p_id]}};var GodotFetch={onread:function(id,result){const obj=IDHandler.get(id);if(!obj){return}if(result.value){obj.chunks.push(result.value)}obj.reading=false;obj.done=result.done},onresponse:function(id,response){const obj=IDHandler.get(id);if(!obj){return}let chunked=false;response.headers.forEach(function(value,header){const v=value.toLowerCase().trim();const h=header.toLowerCase().trim();if(h==="transfer-encoding"&&v==="chunked"){chunked=true}});obj.status=response.status;obj.response=response;obj.reader=response.body.getReader();obj.chunked=chunked},onerror:function(id,err){GodotRuntime.error(err);const obj=IDHandler.get(id);if(!obj){return}obj.error=err},create:function(method,url,headers,body){const obj={request:null,response:null,reader:null,error:null,done:false,reading:false,status:0,chunks:[],bodySize:-1};const id=IDHandler.add(obj);const init={method:method,headers:headers,body:body};obj.request=fetch(url,init);obj.request.then(GodotFetch.onresponse.bind(null,id)).catch(GodotFetch.onerror.bind(null,id));return id},free:function(id){const obj=IDHandler.get(id);if(!obj){return}IDHandler.remove(id);if(!obj.request){return}obj.request.then(function(response){response.abort()}).catch(function(e){})},read:function(id){const obj=IDHandler.get(id);if(!obj){return}if(obj.reader&&!obj.reading){if(obj.done){obj.reader=null;return}obj.reading=true;obj.reader.read().then(GodotFetch.onread.bind(null,id)).catch(GodotFetch.onerror.bind(null,id))}}};function _godot_js_fetch_body_length_get(p_id){const obj=IDHandler.get(p_id);if(!obj||!obj.response){return-1}return obj.bodySize}function _godot_js_fetch_create(p_method,p_url,p_headers,p_headers_size,p_body,p_body_size){const method=GodotRuntime.parseString(p_method);const url=GodotRuntime.parseString(p_url);const headers=GodotRuntime.parseStringArray(p_headers,p_headers_size);const body=p_body_size?GodotRuntime.heapSlice(HEAP8,p_body,p_body_size):null;return GodotFetch.create(method,url,headers.map(function(hv){const idx=hv.indexOf(":");if(idx<=0){return[]}return[hv.slice(0,idx).trim(),hv.slice(idx+1).trim()]}).filter(function(v){return v.length===2}),body)}function _godot_js_fetch_free(id){GodotFetch.free(id)}function _godot_js_fetch_http_status_get(p_id){const obj=IDHandler.get(p_id);if(!obj||!obj.response){return 0}return obj.status}function _godot_js_fetch_is_chunked(p_id){const obj=IDHandler.get(p_id);if(!obj||!obj.response){return-1}return obj.chunked?1:0}function _godot_js_fetch_read_chunk(p_id,p_buf,p_buf_size){const obj=IDHandler.get(p_id);if(!obj||!obj.response){return 0}let to_read=p_buf_size;const chunks=obj.chunks;while(to_read&&chunks.length){const chunk=obj.chunks[0];if(chunk.length>to_read){GodotRuntime.heapCopy(HEAP8,chunk.slice(0,to_read),p_buf);chunks[0]=chunk.slice(to_read);to_read=0}else{GodotRuntime.heapCopy(HEAP8,chunk,p_buf);to_read-=chunk.length;chunks.pop()}}if(!chunks.length){GodotFetch.read(p_id)}return p_buf_size-to_read}function _godot_js_fetch_read_headers(p_id,p_parse_cb,p_ref){const obj=IDHandler.get(p_id);if(!obj||!obj.response){return 1}const cb=GodotRuntime.get_func(p_parse_cb);const arr=[];obj.response.headers.forEach(function(v,h){arr.push(`${h}:${v}`)});const c_ptr=GodotRuntime.allocStringArray(arr);cb(arr.length,c_ptr,p_ref);GodotRuntime.freeStringArray(c_ptr,arr.length);return 0}function _godot_js_fetch_state_get(p_id){const obj=IDHandler.get(p_id);if(!obj){return-1}if(obj.error){return-1}if(!obj.response){return 0}if(obj.reader){return 1}if(obj.done){return 2}return-1}var GodotInputGamepads={samples:[],get_pads:function(){try{const pads=navigator.getGamepads();if(pads){return pads}return[]}catch(e){return[]}},get_samples:function(){return GodotInputGamepads.samples},get_sample:function(index){const samples=GodotInputGamepads.samples;return index=0){os="Android"}else if(ua.indexOf("Linux")>=0){os="Linux"}else if(ua.indexOf("iPhone")>=0){os="iOS"}else if(ua.indexOf("Macintosh")>=0){os="MacOSX"}else if(ua.indexOf("Windows")>=0){os="Windows"}const id=pad.id;const exp1=/vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;const exp2=/^([0-9a-f]+)-([0-9a-f]+)-/i;let vendor="";let product="";if(exp1.test(id)){const match=exp1.exec(id);vendor=match[1].padStart(4,"0");product=match[2].padStart(4,"0")}else if(exp2.test(id)){const match=exp2.exec(id);vendor=match[1].padStart(4,"0");product=match[2].padStart(4,"0")}if(!vendor||!product){return`${os}Unknown`}return os+vendor+product}};var GodotInputDragDrop={promises:[],pending_files:[],add_entry:function(entry){if(entry.isDirectory){GodotInputDragDrop.add_dir(entry)}else if(entry.isFile){GodotInputDragDrop.add_file(entry)}else{GodotRuntime.error("Unrecognized entry...",entry)}},add_dir:function(entry){GodotInputDragDrop.promises.push(new Promise(function(resolve,reject){const reader=entry.createReader();reader.readEntries(function(entries){for(let i=0;i{const path=elem["path"];GodotFS.copy_to_fs(DROP+path,elem["data"]);let idx=path.indexOf("/");if(idx===-1){drops.push(DROP+path)}else{const sub=path.substr(0,idx);idx=sub.indexOf("/");if(idx<0&&drops.indexOf(DROP+sub)===-1){drops.push(DROP+sub)}}files.push(DROP+path)});GodotInputDragDrop.promises=[];GodotInputDragDrop.pending_files=[];callback(drops);if(GodotConfig.persistent_drops){GodotOS.atexit(function(resolve,reject){GodotInputDragDrop.remove_drop(files,DROP);resolve()})}else{GodotInputDragDrop.remove_drop(files,DROP)}})},remove_drop:function(files,drop_path){const dirs=[drop_path.substr(0,drop_path.length-1)];files.forEach(function(file){FS.unlink(file);let dir=file.replace(drop_path,"");let idx=dir.lastIndexOf("/");while(idx>0){dir=dir.substr(0,idx);if(dirs.indexOf(drop_path+dir)===-1){dirs.push(drop_path+dir)}idx=dir.lastIndexOf("/")}});dirs.sort(function(a,b){const al=(a.match(/\//g)||[]).length;const bl=(b.match(/\//g)||[]).length;if(al>bl){return-1}else if(al0){var leap=__isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate}function _strftime(s,maxsize,format,tm){var tm_zone=HEAP32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value=="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}return thisDate.getFullYear()}return thisDate.getFullYear()-1}var EXPANSION_RULES_2={"%a":function(date){return WEEKDAYS[date.tm_wday].substring(0,3)},"%A":function(date){return WEEKDAYS[date.tm_wday]},"%b":function(date){return MONTHS[date.tm_mon].substring(0,3)},"%B":function(date){return MONTHS[date.tm_mon]},"%C":function(date){var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":function(date){return leadingNulls(date.tm_mday,2)},"%e":function(date){return leadingSomething(date.tm_mday,2," ")},"%g":function(date){return getWeekBasedYear(date).toString().substring(2)},"%G":function(date){return getWeekBasedYear(date)},"%H":function(date){return leadingNulls(date.tm_hour,2)},"%I":function(date){var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":function(date){return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900)?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,date.tm_mon-1),3)},"%m":function(date){return leadingNulls(date.tm_mon+1,2)},"%M":function(date){return leadingNulls(date.tm_min,2)},"%n":function(){return"\n"},"%p":function(date){if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}return"PM"},"%S":function(date){return leadingNulls(date.tm_sec,2)},"%t":function(){return"\t"},"%u":function(date){return date.tm_wday||7},"%U":function(date){var days=date.tm_yday+7-date.tm_wday;return leadingNulls(Math.floor(days/7),2)},"%V":function(date){var val=Math.floor((date.tm_yday+7-(date.tm_wday+6)%7)/7);if((date.tm_wday+371-date.tm_yday-2)%7<=2){val++}if(!val){val=52;var dec31=(date.tm_wday+7-date.tm_yday-1)%7;if(dec31==4||dec31==5&&__isLeapYear(date.tm_year%400-1)){val++}}else if(val==53){var jan1=(date.tm_wday+371-date.tm_yday)%7;if(jan1!=4&&(jan1!=3||!__isLeapYear(date.tm_year)))val=1}return leadingNulls(val,2)},"%w":function(date){return date.tm_wday},"%W":function(date){var days=date.tm_yday+7-(date.tm_wday+6)%7;return leadingNulls(Math.floor(days/7),2)},"%y":function(date){return(date.tm_year+1900).toString().substring(2)},"%Y":function(date){return date.tm_year+1900},"%z":function(date){var off=date.tm_gmtoff;var ahead=off>=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":function(date){return date.tm_zone},"%%":function(){return"%"}};pattern=pattern.replace(/%%/g,"\0\0");for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}pattern=pattern.replace(/\0\0/g,"%");var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1}function _strftime_l(s,maxsize,format,tm){return _strftime(s,maxsize,format,tm)}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}function getCFunc(ident){var func=Module["_"+ident];return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;itype==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();Module["requestFullscreen"]=function Module_requestFullscreen(lockPointer,resizeCanvas){Browser.requestFullscreen(lockPointer,resizeCanvas)};Module["requestAnimationFrame"]=function Module_requestAnimationFrame(func){Browser.requestAnimationFrame(func)};Module["setCanvasSize"]=function Module_setCanvasSize(width,height,noUpdates){Browser.setCanvasSize(width,height,noUpdates)};Module["pauseMainLoop"]=function Module_pauseMainLoop(){Browser.mainLoop.pause()};Module["resumeMainLoop"]=function Module_resumeMainLoop(){Browser.mainLoop.resume()};Module["getUserMedia"]=function Module_getUserMedia(){Browser.getUserMedia()};Module["createContext"]=function Module_createContext(canvas,useWebGL,setInModule,webGLContextAttributes){return Browser.createContext(canvas,useWebGL,setInModule,webGLContextAttributes)};var preloadedImages={};var preloadedAudios={};var GLctx;for(var i=0;i<32;++i)tempFixedLengthArray.push(new Array(i));var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i+1)}var __miniTempWebGLIntBuffersStorage=new Int32Array(288);for(var i=0;i<288;++i){__miniTempWebGLIntBuffers[i]=__miniTempWebGLIntBuffersStorage.subarray(0,i+1)}Module["request_quit"]=function(){GodotOS.request_quit()};Module["onExit"]=GodotOS.cleanup;GodotOS._fs_sync_promise=Promise.resolve();Module["initConfig"]=GodotConfig.init_config;Module["initFS"]=GodotFS.init;Module["copyToFS"]=GodotFS.copy_to_fs;ERRNO_CODES={"EPERM":63,"ENOENT":44,"ESRCH":71,"EINTR":27,"EIO":29,"ENXIO":60,"E2BIG":1,"ENOEXEC":45,"EBADF":8,"ECHILD":12,"EAGAIN":6,"EWOULDBLOCK":6,"ENOMEM":48,"EACCES":2,"EFAULT":21,"ENOTBLK":105,"EBUSY":10,"EEXIST":20,"EXDEV":75,"ENODEV":43,"ENOTDIR":54,"EISDIR":31,"EINVAL":28,"ENFILE":41,"EMFILE":33,"ENOTTY":59,"ETXTBSY":74,"EFBIG":22,"ENOSPC":51,"ESPIPE":70,"EROFS":69,"EMLINK":34,"EPIPE":64,"EDOM":18,"ERANGE":68,"ENOMSG":49,"EIDRM":24,"ECHRNG":106,"EL2NSYNC":156,"EL3HLT":107,"EL3RST":108,"ELNRNG":109,"EUNATCH":110,"ENOCSI":111,"EL2HLT":112,"EDEADLK":16,"ENOLCK":46,"EBADE":113,"EBADR":114,"EXFULL":115,"ENOANO":104,"EBADRQC":103,"EBADSLT":102,"EDEADLOCK":16,"EBFONT":101,"ENOSTR":100,"ENODATA":116,"ETIME":117,"ENOSR":118,"ENONET":119,"ENOPKG":120,"EREMOTE":121,"ENOLINK":47,"EADV":122,"ESRMNT":123,"ECOMM":124,"EPROTO":65,"EMULTIHOP":36,"EDOTDOT":125,"EBADMSG":9,"ENOTUNIQ":126,"EBADFD":127,"EREMCHG":128,"ELIBACC":129,"ELIBBAD":130,"ELIBSCN":131,"ELIBMAX":132,"ELIBEXEC":133,"ENOSYS":52,"ENOTEMPTY":55,"ENAMETOOLONG":37,"ELOOP":32,"EOPNOTSUPP":138,"EPFNOSUPPORT":139,"ECONNRESET":15,"ENOBUFS":42,"EAFNOSUPPORT":5,"EPROTOTYPE":67,"ENOTSOCK":57,"ENOPROTOOPT":50,"ESHUTDOWN":140,"ECONNREFUSED":14,"EADDRINUSE":3,"ECONNABORTED":13,"ENETUNREACH":40,"ENETDOWN":38,"ETIMEDOUT":73,"EHOSTDOWN":142,"EHOSTUNREACH":23,"EINPROGRESS":26,"EALREADY":7,"EDESTADDRREQ":17,"EMSGSIZE":35,"EPROTONOSUPPORT":66,"ESOCKTNOSUPPORT":137,"EADDRNOTAVAIL":4,"ENETRESET":39,"EISCONN":30,"ENOTCONN":53,"ETOOMANYREFS":141,"EUSERS":136,"EDQUOT":19,"ESTALE":72,"ENOTSUP":138,"ENOMEDIUM":148,"EILSEQ":25,"EOVERFLOW":61,"ECANCELED":11,"ENOTRECOVERABLE":56,"EOWNERDEAD":62,"ESTRPIPE":135};GodotOS.atexit(function(resolve,reject){GodotDisplayCursor.clear();resolve()});GodotOS.atexit(function(resolve,reject){GodotEventListeners.clear();resolve()});GodotOS.atexit(function(resolve,reject){GodotDisplayVK.clear();resolve()});GodotJSWrapper.proxies=new Map;var asmLibraryArg={"Qc":___call_sighandler,"Dc":___syscall_accept4,"Cc":___syscall_bind,"ld":___syscall_chdir,"kd":___syscall_chmod,"Bc":___syscall_connect,"md":___syscall_faccessat,"ea":___syscall_fcntl64,"_c":___syscall_getcwd,"Pc":___syscall_getdents64,"gb":___syscall_ioctl,"Ac":___syscall_listen,"Tc":___syscall_lstat64,"Sc":___syscall_mkdirat,"Vc":___syscall_newfstatat,"hb":___syscall_openat,"Rc":___syscall_poll,"Oc":___syscall_readlinkat,"yc":___syscall_recvfrom,"Lc":___syscall_renameat,"Mc":___syscall_rmdir,"xc":___syscall_sendmsg,"wc":___syscall_sendto,"eb":___syscall_socket,"Wc":___syscall_stat64,"Kc":___syscall_statfs64,"Ic":___syscall_symlink,"Nc":___syscall_unlinkat,"gd":__dlinit,"jd":__dlopen_js,"hd":__dlsym_js,"Ra":__emscripten_date_now,"bd":__emscripten_get_now_is_monotonic,"Fc":__emscripten_throw_longjmp,"cd":__gmtime_js,"dd":__localtime_js,"ed":__tzset_js,"ha":_abort,"lb":_emscripten_cancel_main_loop,"uh":_emscripten_force_exit,"Hc":_emscripten_get_heap_max,"Qa":_emscripten_get_now,"ri":_emscripten_glActiveTexture,"qi":_emscripten_glAttachShader,"jf":_emscripten_glBeginQuery,"Ji":_emscripten_glBeginQueryEXT,"Qe":_emscripten_glBeginTransformFeedback,"pi":_emscripten_glBindAttribLocation,"oi":_emscripten_glBindBuffer,"Ne":_emscripten_glBindBufferBase,"Oe":_emscripten_glBindBufferRange,"ni":_emscripten_glBindFramebuffer,"mi":_emscripten_glBindRenderbuffer,"Sd":_emscripten_glBindSampler,"li":_emscripten_glBindTexture,"Id":_emscripten_glBindTransformFeedback,"Ve":_emscripten_glBindVertexArray,"Ai":_emscripten_glBindVertexArrayOES,"ji":_emscripten_glBlendColor,"ii":_emscripten_glBlendEquation,"hi":_emscripten_glBlendEquationSeparate,"gi":_emscripten_glBlendFunc,"fi":_emscripten_glBlendFuncSeparate,"Ye":_emscripten_glBlitFramebuffer,"ei":_emscripten_glBufferData,"di":_emscripten_glBufferSubData,"ci":_emscripten_glCheckFramebufferStatus,"bi":_emscripten_glClear,"pe":_emscripten_glClearBufferfi,"qe":_emscripten_glClearBufferfv,"se":_emscripten_glClearBufferiv,"re":_emscripten_glClearBufferuiv,"ai":_emscripten_glClearColor,"_h":_emscripten_glClearDepthf,"Zh":_emscripten_glClearStencil,"ae":_emscripten_glClientWaitSync,"Yh":_emscripten_glColorMask,"Xh":_emscripten_glCompileShader,"Wh":_emscripten_glCompressedTexImage2D,"of":_emscripten_glCompressedTexImage3D,"Vh":_emscripten_glCompressedTexSubImage2D,"nf":_emscripten_glCompressedTexSubImage3D,"ne":_emscripten_glCopyBufferSubData,"Uh":_emscripten_glCopyTexImage2D,"Th":_emscripten_glCopyTexSubImage2D,"pf":_emscripten_glCopyTexSubImage3D,"Sh":_emscripten_glCreateProgram,"Rh":_emscripten_glCreateShader,"Oh":_emscripten_glCullFace,"Nh":_emscripten_glDeleteBuffers,"Mh":_emscripten_glDeleteFramebuffers,"Lh":_emscripten_glDeleteProgram,"lf":_emscripten_glDeleteQueries,"Li":_emscripten_glDeleteQueriesEXT,"Kh":_emscripten_glDeleteRenderbuffers,"Ud":_emscripten_glDeleteSamplers,"Jh":_emscripten_glDeleteShader,"be":_emscripten_glDeleteSync,"Ih":_emscripten_glDeleteTextures,"Hd":_emscripten_glDeleteTransformFeedbacks,"Ue":_emscripten_glDeleteVertexArrays,"zi":_emscripten_glDeleteVertexArraysOES,"Hh":_emscripten_glDepthFunc,"Gh":_emscripten_glDepthMask,"Fh":_emscripten_glDepthRangef,"Eh":_emscripten_glDetachShader,"Dh":_emscripten_glDisable,"Ch":_emscripten_glDisableVertexAttribArray,"Bh":_emscripten_glDrawArrays,"fe":_emscripten_glDrawArraysInstanced,"ui":_emscripten_glDrawArraysInstancedANGLE,"pd":_emscripten_glDrawArraysInstancedARB,"wf":_emscripten_glDrawArraysInstancedEXT,"qd":_emscripten_glDrawArraysInstancedNV,"df":_emscripten_glDrawBuffers,"uf":_emscripten_glDrawBuffersEXT,"wi":_emscripten_glDrawBuffersWEBGL,"Ah":_emscripten_glDrawElements,"ee":_emscripten_glDrawElementsInstanced,"ti":_emscripten_glDrawElementsInstancedANGLE,"nd":_emscripten_glDrawElementsInstancedARB,"od":_emscripten_glDrawElementsInstancedEXT,"vf":_emscripten_glDrawElementsInstancedNV,"sf":_emscripten_glDrawRangeElements,"zh":_emscripten_glEnable,"yh":_emscripten_glEnableVertexAttribArray,"gf":_emscripten_glEndQuery,"Ii":_emscripten_glEndQueryEXT,"Pe":_emscripten_glEndTransformFeedback,"de":_emscripten_glFenceSync,"xh":_emscripten_glFinish,"wh":_emscripten_glFlush,"vh":_emscripten_glFramebufferRenderbuffer,"th":_emscripten_glFramebufferTexture2D,"We":_emscripten_glFramebufferTextureLayer,"sh":_emscripten_glFrontFace,"rh":_emscripten_glGenBuffers,"ph":_emscripten_glGenFramebuffers,"mf":_emscripten_glGenQueries,"Mi":_emscripten_glGenQueriesEXT,"oh":_emscripten_glGenRenderbuffers,"Vd":_emscripten_glGenSamplers,"nh":_emscripten_glGenTextures,"Gd":_emscripten_glGenTransformFeedbacks,"Te":_emscripten_glGenVertexArrays,"yi":_emscripten_glGenVertexArraysOES,"qh":_emscripten_glGenerateMipmap,"mh":_emscripten_glGetActiveAttrib,"lh":_emscripten_glGetActiveUniform,"he":_emscripten_glGetActiveUniformBlockName,"ie":_emscripten_glGetActiveUniformBlockiv,"le":_emscripten_glGetActiveUniformsiv,"kh":_emscripten_glGetAttachedShaders,"jh":_emscripten_glGetAttribLocation,"ih":_emscripten_glGetBooleanv,"Wd":_emscripten_glGetBufferParameteri64v,"hh":_emscripten_glGetBufferParameteriv,"gh":_emscripten_glGetError,"fh":_emscripten_glGetFloatv,"Ce":_emscripten_glGetFragDataLocation,"eh":_emscripten_glGetFramebufferAttachmentParameteriv,"Xd":_emscripten_glGetInteger64i_v,"Zd":_emscripten_glGetInteger64v,"Re":_emscripten_glGetIntegeri_v,"dh":_emscripten_glGetIntegerv,"ud":_emscripten_glGetInternalformativ,"Bd":_emscripten_glGetProgramBinary,"bh":_emscripten_glGetProgramInfoLog,"ch":_emscripten_glGetProgramiv,"Ci":_emscripten_glGetQueryObjecti64vEXT,"Ei":_emscripten_glGetQueryObjectivEXT,"Bi":_emscripten_glGetQueryObjectui64vEXT,"ef":_emscripten_glGetQueryObjectuiv,"Di":_emscripten_glGetQueryObjectuivEXT,"ff":_emscripten_glGetQueryiv,"Fi":_emscripten_glGetQueryivEXT,"ah":_emscripten_glGetRenderbufferParameteriv,"Kd":_emscripten_glGetSamplerParameterfv,"Ld":_emscripten_glGetSamplerParameteriv,"Zg":_emscripten_glGetShaderInfoLog,"Yg":_emscripten_glGetShaderPrecisionFormat,"Xg":_emscripten_glGetShaderSource,"_g":_emscripten_glGetShaderiv,"Wg":_emscripten_glGetString,"oe":_emscripten_glGetStringi,"Yd":_emscripten_glGetSynciv,"Vg":_emscripten_glGetTexParameterfv,"Ug":_emscripten_glGetTexParameteriv,"Le":_emscripten_glGetTransformFeedbackVarying,"ke":_emscripten_glGetUniformBlockIndex,"me":_emscripten_glGetUniformIndices,"Rg":_emscripten_glGetUniformLocation,"Tg":_emscripten_glGetUniformfv,"Sg":_emscripten_glGetUniformiv,"De":_emscripten_glGetUniformuiv,"Je":_emscripten_glGetVertexAttribIiv,"Ie":_emscripten_glGetVertexAttribIuiv,"Ng":_emscripten_glGetVertexAttribPointerv,"Pg":_emscripten_glGetVertexAttribfv,"Og":_emscripten_glGetVertexAttribiv,"Mg":_emscripten_glHint,"yd":_emscripten_glInvalidateFramebuffer,"xd":_emscripten_glInvalidateSubFramebuffer,"Lg":_emscripten_glIsBuffer,"Kg":_emscripten_glIsEnabled,"Jg":_emscripten_glIsFramebuffer,"Ig":_emscripten_glIsProgram,"kf":_emscripten_glIsQuery,"Ki":_emscripten_glIsQueryEXT,"Hg":_emscripten_glIsRenderbuffer,"Td":_emscripten_glIsSampler,"Gg":_emscripten_glIsShader,"ce":_emscripten_glIsSync,"Eg":_emscripten_glIsTexture,"Fd":_emscripten_glIsTransformFeedback,"Se":_emscripten_glIsVertexArray,"xi":_emscripten_glIsVertexArrayOES,"Dg":_emscripten_glLineWidth,"Cg":_emscripten_glLinkProgram,"Ed":_emscripten_glPauseTransformFeedback,"Bg":_emscripten_glPixelStorei,"Ag":_emscripten_glPolygonOffset,"Ad":_emscripten_glProgramBinary,"zd":_emscripten_glProgramParameteri,"Hi":_emscripten_glQueryCounterEXT,"tf":_emscripten_glReadBuffer,"zg":_emscripten_glReadPixels,"yg":_emscripten_glReleaseShaderCompiler,"xg":_emscripten_glRenderbufferStorage,"Xe":_emscripten_glRenderbufferStorageMultisample,"Cd":_emscripten_glResumeTransformFeedback,"wg":_emscripten_glSampleCoverage,"Nd":_emscripten_glSamplerParameterf,"Md":_emscripten_glSamplerParameterfv,"Rd":_emscripten_glSamplerParameteri,"Qd":_emscripten_glSamplerParameteriv,"vg":_emscripten_glScissor,"tg":_emscripten_glShaderBinary,"sg":_emscripten_glShaderSource,"rg":_emscripten_glStencilFunc,"qg":_emscripten_glStencilFuncSeparate,"pg":_emscripten_glStencilMask,"og":_emscripten_glStencilMaskSeparate,"ng":_emscripten_glStencilOp,"mg":_emscripten_glStencilOpSeparate,"lg":_emscripten_glTexImage2D,"rf":_emscripten_glTexImage3D,"kg":_emscripten_glTexParameterf,"ig":_emscripten_glTexParameterfv,"hg":_emscripten_glTexParameteri,"gg":_emscripten_glTexParameteriv,"wd":_emscripten_glTexStorage2D,"vd":_emscripten_glTexStorage3D,"fg":_emscripten_glTexSubImage2D,"qf":_emscripten_glTexSubImage3D,"Me":_emscripten_glTransformFeedbackVaryings,"eg":_emscripten_glUniform1f,"dg":_emscripten_glUniform1fv,"cg":_emscripten_glUniform1i,"bg":_emscripten_glUniform1iv,"Be":_emscripten_glUniform1ui,"xe":_emscripten_glUniform1uiv,"ag":_emscripten_glUniform2f,"$f":_emscripten_glUniform2fv,"Zf":_emscripten_glUniform2i,"Yf":_emscripten_glUniform2iv,"Ae":_emscripten_glUniform2ui,"we":_emscripten_glUniform2uiv,"Xf":_emscripten_glUniform3f,"Wf":_emscripten_glUniform3fv,"Vf":_emscripten_glUniform3i,"Uf":_emscripten_glUniform3iv,"ze":_emscripten_glUniform3ui,"ve":_emscripten_glUniform3uiv,"Tf":_emscripten_glUniform4f,"Sf":_emscripten_glUniform4fv,"Rf":_emscripten_glUniform4i,"Qf":_emscripten_glUniform4iv,"ye":_emscripten_glUniform4ui,"te":_emscripten_glUniform4uiv,"ge":_emscripten_glUniformBlockBinding,"Nf":_emscripten_glUniformMatrix2fv,"cf":_emscripten_glUniformMatrix2x3fv,"af":_emscripten_glUniformMatrix2x4fv,"Mf":_emscripten_glUniformMatrix3fv,"bf":_emscripten_glUniformMatrix3x2fv,"_e":_emscripten_glUniformMatrix3x4fv,"Lf":_emscripten_glUniformMatrix4fv,"$e":_emscripten_glUniformMatrix4x2fv,"Ze":_emscripten_glUniformMatrix4x3fv,"Kf":_emscripten_glUseProgram,"Jf":_emscripten_glValidateProgram,"If":_emscripten_glVertexAttrib1f,"Hf":_emscripten_glVertexAttrib1fv,"Gf":_emscripten_glVertexAttrib2f,"Ff":_emscripten_glVertexAttrib2fv,"Ef":_emscripten_glVertexAttrib3f,"Cf":_emscripten_glVertexAttrib3fv,"Bf":_emscripten_glVertexAttrib4f,"Af":_emscripten_glVertexAttrib4fv,"Jd":_emscripten_glVertexAttribDivisor,"si":_emscripten_glVertexAttribDivisorANGLE,"rd":_emscripten_glVertexAttribDivisorARB,"xf":_emscripten_glVertexAttribDivisorEXT,"td":_emscripten_glVertexAttribDivisorNV,"He":_emscripten_glVertexAttribI4i,"Fe":_emscripten_glVertexAttribI4iv,"Ge":_emscripten_glVertexAttribI4ui,"Ee":_emscripten_glVertexAttribI4uiv,"Ke":_emscripten_glVertexAttribIPointer,"zf":_emscripten_glVertexAttribPointer,"yf":_emscripten_glViewport,"$d":_emscripten_glWaitSync,"fd":_emscripten_memcpy_big,"Gc":_emscripten_resize_heap,"kb":_emscripten_set_main_loop,"cb":_emscripten_webgl_commit_frame,"sc":_emscripten_webgl_create_context,"Xb":_emscripten_webgl_destroy_context,"uc":_emscripten_webgl_init_context_attributes,"rc":_emscripten_webgl_make_context_current,"Yc":_environ_get,"Zc":_environ_sizes_get,"ra":_fd_close,"Xc":_fd_fdstat_get,"$c":_fd_read,"vc":_fd_seek,"fb":_fd_write,"x":_getTempRet0,"mj":_getaddrinfo,"Ec":_getentropy,"c":_glActiveTexture,"Ma":_glAttachShader,"_a":_glBeginTransformFeedback,"tb":_glBindAttribLocation,"b":_glBindBuffer,"P":_glBindBufferBase,"e":_glBindFramebuffer,"ba":_glBindRenderbuffer,"a":_glBindTexture,"k":_glBindVertexArray,"E":_glBlendEquation,"Z":_glBlendFunc,"v":_glBlendFuncSeparate,"ka":_glBlitFramebuffer,"n":_glBufferData,"K":_glBufferSubData,"L":_glCheckFramebufferStatus,"J":_glClear,"oa":_glClearBufferfv,"O":_glClearColor,"_":_glClearDepthf,"M":_glColorMask,"ma":_glCompileShader,"yb":_glCompressedTexImage2D,"cj":_glCompressedTexSubImage2D,"xb":_glCompressedTexSubImage3D,"_i":_glCopyBufferSubData,"Xa":_glCopyTexSubImage2D,"Ya":_glCreateProgram,"Ca":_glCreateShader,"qa":_glCullFace,"N":_glDeleteBuffers,"F":_glDeleteFramebuffers,"R":_glDeleteProgram,"V":_glDeleteRenderbuffers,"I":_glDeleteShader,"y":_glDeleteTextures,"ga":_glDeleteVertexArrays,"$":_glDepthFunc,"H":_glDepthMask,"i":_glDisable,"o":_glDisableVertexAttribArray,"z":_glDrawArrays,"wa":_glDrawArraysInstanced,"Ga":_glDrawBuffers,"da":_glDrawElements,"Ha":_glDrawElementsInstanced,"q":_glEnable,"j":_glEnableVertexAttribArray,"Za":_glEndTransformFeedback,"Bb":_glFinish,"aa":_glFramebufferRenderbuffer,"u":_glFramebufferTexture2D,"bj":_glFramebufferTextureLayer,"zb":_glFrontFace,"B":_glGenBuffers,"D":_glGenFramebuffers,"ja":_glGenRenderbuffers,"t":_glGenTextures,"W":_glGenVertexArrays,"S":_glGenerateMipmap,"Ab":_glGetError,"vb":_glGetFloatv,"ca":_glGetIntegerv,"Ri":_glGetProgramBinary,"rb":_glGetProgramInfoLog,"Ba":_glGetProgramiv,"Na":_glGetShaderInfoLog,"Qi":_glGetShaderSource,"fa":_glGetShaderiv,"ua":_glGetString,"Yi":_glGetStringi,"Wi":_glGetUniformBlockIndex,"ta":_glGetUniformLocation,"fj":_glInvalidateFramebuffer,"sb":_glLinkProgram,"na":_glPixelStorei,"Xi":_glProgramBinary,"Ti":_glProgramParameteri,"la":_glReadBuffer,"$a":_glReadPixels,"ia":_glRenderbufferStorage,"Da":_glRenderbufferStorageMultisample,"Q":_glScissor,"La":_glShaderSource,"p":_glTexImage2D,"Fa":_glTexImage3D,"g":_glTexParameterf,"d":_glTexParameteri,"ej":_glTexStorage2D,"Ea":_glTexSubImage2D,"Oa":_glTexSubImage3D,"Ui":_glTransformFeedbackVaryings,"f":_glUniform1f,"s":_glUniform1i,"ab":_glUniform1iv,"wb":_glUniform1ui,"Wa":_glUniform2f,"l":_glUniform2fv,"Aa":_glUniform2i,"T":_glUniform2iv,"Va":_glUniform3f,"Y":_glUniform3fv,"za":_glUniform3i,"va":_glUniform4f,"w":_glUniform4fv,"ya":_glUniform4i,"Vi":_glUniformBlockBinding,"qb":_glUniformMatrix2fv,"pb":_glUniformMatrix3fv,"m":_glUniformMatrix4fv,"pa":_glUseProgram,"A":_glVertexAttrib4f,"U":_glVertexAttrib4fv,"G":_glVertexAttribDivisor,"jj":_glVertexAttribI4ui,"Ia":_glVertexAttribIPointer,"h":_glVertexAttribPointer,"r":_glViewport,"Qh":_godot_audio_capture_start,"Pf":_godot_audio_capture_stop,"Pd":_godot_audio_has_script_processor,"_b":_godot_audio_has_worklet,"Ij":_godot_audio_init,"Jj":_godot_audio_is_available,"aj":_godot_audio_resume,"tc":_godot_audio_script_create,"ic":_godot_audio_script_start,"Pb":_godot_audio_worklet_create,"Hj":_godot_audio_worklet_start_no_threads,"Mb":_godot_js_config_canvas_id_get,"Qg":_godot_js_config_locale_get,"Ub":_godot_js_display_alert,"jb":_godot_js_display_canvas_focus,"_d":_godot_js_display_canvas_is_focused,"ad":_godot_js_display_clipboard_get,"id":_godot_js_display_clipboard_set,"ue":_godot_js_display_cursor_is_hidden,"je":_godot_js_display_cursor_is_locked,"Sa":_godot_js_display_cursor_lock_set,"ib":_godot_js_display_cursor_set_custom_shape,"hf":_godot_js_display_cursor_set_shape,"Ta":_godot_js_display_cursor_set_visible,"jg":_godot_js_display_desired_size_set,"hc":_godot_js_display_fullscreen_cb,"Df":_godot_js_display_fullscreen_exit,"Of":_godot_js_display_fullscreen_request,"wj":_godot_js_display_glGetBufferSubData,"db":_godot_js_display_has_webgl,"zc":_godot_js_display_is_swap_ok_cancel,"fc":_godot_js_display_notification_cb,"Yb":_godot_js_display_pixel_ratio_get,"Zb":_godot_js_display_screen_dpi_get,"ug":_godot_js_display_screen_size_get,"Jc":_godot_js_display_setup_canvas,"Fg":_godot_js_display_size_update,"Od":_godot_js_display_touchscreen_is_available,"dc":_godot_js_display_vk_available,"ec":_godot_js_display_vk_cb,"bc":_godot_js_display_vk_hide,"cc":_godot_js_display_vk_show,"gc":_godot_js_display_window_blur_cb,"Sb":_godot_js_display_window_icon_set,"_f":_godot_js_display_window_size_get,"Tb":_godot_js_display_window_title_set,"ki":_godot_js_eval,"ij":_godot_js_fetch_body_length_get,"lj":_godot_js_fetch_create,"Db":_godot_js_fetch_free,"gj":_godot_js_fetch_http_status_get,"kj":_godot_js_fetch_is_chunked,"hj":_godot_js_fetch_read_chunk,"dj":_godot_js_fetch_read_headers,"bb":_godot_js_fetch_state_get,"jc":_godot_js_input_drop_files_cb,"lc":_godot_js_input_gamepad_cb,"$b":_godot_js_input_gamepad_sample,"Dd":_godot_js_input_gamepad_sample_count,"sd":_godot_js_input_gamepad_sample_get,"mc":_godot_js_input_key_cb,"qc":_godot_js_input_mouse_button_cb,"pc":_godot_js_input_mouse_move_cb,"oc":_godot_js_input_mouse_wheel_cb,"kc":_godot_js_input_paste_cb,"nc":_godot_js_input_touch_cb,"Qb":_godot_js_input_vibrate_handheld,"$h":_godot_js_os_download_buffer,"Wb":_godot_js_os_execute,"$g":_godot_js_os_finish_async,"Lb":_godot_js_os_fs_is_persistent,"ac":_godot_js_os_fs_sync,"Vb":_godot_js_os_hw_concurrency_get,"Nb":_godot_js_os_request_quit_cb,"Rb":_godot_js_os_shell_open,"Kb":_godot_js_pwa_cb,"Ob":_godot_js_pwa_update,"Jb":_godot_js_rtc_datachannel_close,"Bj":_godot_js_rtc_datachannel_connect,"yj":_godot_js_rtc_datachannel_destroy,"Cj":_godot_js_rtc_datachannel_get_buffered_amount,"Gj":_godot_js_rtc_datachannel_id_get,"Dj":_godot_js_rtc_datachannel_is_negotiated,"Gb":_godot_js_rtc_datachannel_is_ordered,"Aj":_godot_js_rtc_datachannel_label_get,"Fj":_godot_js_rtc_datachannel_max_packet_lifetime_get,"Ej":_godot_js_rtc_datachannel_max_retransmits_get,"zj":_godot_js_rtc_datachannel_protocol_get,"Ib":_godot_js_rtc_datachannel_ready_state_get,"Hb":_godot_js_rtc_datachannel_send,"xj":_godot_js_rtc_pc_close,"rj":_godot_js_rtc_pc_create,"qj":_godot_js_rtc_pc_datachannel_create,"Fb":_godot_js_rtc_pc_destroy,"sj":_godot_js_rtc_pc_ice_candidate_add,"uj":_godot_js_rtc_pc_local_description_set,"vj":_godot_js_rtc_pc_offer_create,"tj":_godot_js_rtc_pc_remote_description_set,"Uc":_godot_js_set_canvas_scale,"Eb":_godot_js_websocket_buffered_amount,"oj":_godot_js_websocket_close,"nj":_godot_js_websocket_create,"Cb":_godot_js_websocket_destroy,"pj":_godot_js_websocket_send,"Oi":_godot_js_wrapper_create_cb,"vi":_godot_js_wrapper_create_object,"Gi":_godot_js_wrapper_interface_get,"Pi":_godot_js_wrapper_object_call,"Zi":_godot_js_wrapper_object_get,"ub":_godot_js_wrapper_object_getvar,"$i":_godot_js_wrapper_object_set,"Si":_godot_js_wrapper_object_setvar,"Ph":_godot_js_wrapper_object_unref,"ob":invoke_ii,"Ka":invoke_iii,"Ua":invoke_iiii,"nb":invoke_iiiii,"Ni":invoke_iiiiiii,"mb":invoke_iiiiiiiiii,"sa":invoke_vi,"xa":invoke_vii,"Ja":invoke_viii,"C":_setTempRet0,"Pa":_strftime,"X":_strftime_l};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["Lj"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["Nj"]).apply(null,arguments)};var __Z13godot_js_mainiPPc=Module["__Z13godot_js_mainiPPc"]=function(){return(__Z13godot_js_mainiPPc=Module["__Z13godot_js_mainiPPc"]=Module["asm"]["Oj"]).apply(null,arguments)};var _main=Module["_main"]=function(){return(_main=Module["_main"]=Module["asm"]["Pj"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["Qj"]).apply(null,arguments)};var _htonl=Module["_htonl"]=function(){return(_htonl=Module["_htonl"]=Module["asm"]["Rj"]).apply(null,arguments)};var _htons=Module["_htons"]=function(){return(_htons=Module["_htons"]=Module["asm"]["Sj"]).apply(null,arguments)};var _ntohs=Module["_ntohs"]=function(){return(_ntohs=Module["_ntohs"]=Module["asm"]["Tj"]).apply(null,arguments)};var _fflush=Module["_fflush"]=function(){return(_fflush=Module["_fflush"]=Module["asm"]["Uj"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["Vj"]).apply(null,arguments)};var ___funcs_on_exit=Module["___funcs_on_exit"]=function(){return(___funcs_on_exit=Module["___funcs_on_exit"]=Module["asm"]["Wj"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["Xj"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["Yj"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["Zj"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["_j"]).apply(null,arguments)};function invoke_vii(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}Module["callMain"]=callMain;Module["cwrap"]=cwrap;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args){var entryFunction=Module["_main"];args=args||[];args.unshift(thisProgram);var argc=args.length;var argv=stackAlloc((argc+1)*4);var argv_ptr=argv>>2;args.forEach(arg=>{HEAP32[argv_ptr++]=allocateUTF8OnStack(arg)});HEAP32[argv_ptr]=0;try{var ret=entryFunction(argc,argv);exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=false;if(Module["noInitialRun"])shouldRunNow=false;run(); + + + return Godot.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = Godot; +else if (typeof define === 'function' && define['amd']) + define([], function() { return Godot; }); +else if (typeof exports === 'object') + exports["Godot"] = Godot; + +const Preloader = /** @constructor */ function () { // eslint-disable-line no-unused-vars + function getTrackedResponse(response, load_status) { + function onloadprogress(reader, controller) { + return reader.read().then(function (result) { + if (load_status.done) { + return Promise.resolve(); + } + if (result.value) { + controller.enqueue(result.value); + load_status.loaded += result.value.length; + } + if (!result.done) { + return onloadprogress(reader, controller); + } + load_status.done = true; + return Promise.resolve(); + }); + } + const reader = response.body.getReader(); + return new Response(new ReadableStream({ + start: function (controller) { + onloadprogress(reader, controller).then(function () { + controller.close(); + }); + }, + }), { headers: response.headers }); + } + + function loadFetch(file, tracker, fileSize, raw) { + tracker[file] = { + total: fileSize || 0, + loaded: 0, + done: false, + }; + return fetch(file).then(function (response) { + if (!response.ok) { + return Promise.reject(new Error(`Failed loading file '${file}'`)); + } + const tr = getTrackedResponse(response, tracker[file]); + if (raw) { + return Promise.resolve(tr); + } + return tr.arrayBuffer(); + }); + } + + function retry(func, attempts = 1) { + function onerror(err) { + if (attempts <= 1) { + return Promise.reject(err); + } + return new Promise(function (resolve, reject) { + setTimeout(function () { + retry(func, attempts - 1).then(resolve).catch(reject); + }, 1000); + }); + } + return func().catch(onerror); + } + + const DOWNLOAD_ATTEMPTS_MAX = 4; + const loadingFiles = {}; + const lastProgress = { loaded: 0, total: 0 }; + let progressFunc = null; + + const animateProgress = function () { + let loaded = 0; + let total = 0; + let totalIsValid = true; + let progressIsFinal = true; + + Object.keys(loadingFiles).forEach(function (file) { + const stat = loadingFiles[file]; + if (!stat.done) { + progressIsFinal = false; + } + if (!totalIsValid || stat.total === 0) { + totalIsValid = false; + total = 0; + } else { + total += stat.total; + } + loaded += stat.loaded; + }); + if (loaded !== lastProgress.loaded || total !== lastProgress.total) { + lastProgress.loaded = loaded; + lastProgress.total = total; + if (typeof progressFunc === 'function') { + progressFunc(loaded, total); + } + } + if (!progressIsFinal) { + requestAnimationFrame(animateProgress); + } + }; + + this.animateProgress = animateProgress; + + this.setProgressFunc = function (callback) { + progressFunc = callback; + }; + + this.loadPromise = function (file, fileSize, raw = false) { + return retry(loadFetch.bind(null, file, loadingFiles, fileSize, raw), DOWNLOAD_ATTEMPTS_MAX); + }; + + this.preloadedFiles = []; + this.preload = function (pathOrBuffer, destPath, fileSize) { + let buffer = null; + if (typeof pathOrBuffer === 'string') { + const me = this; + return this.loadPromise(pathOrBuffer, fileSize).then(function (buf) { + me.preloadedFiles.push({ + path: destPath || pathOrBuffer, + buffer: buf, + }); + return Promise.resolve(); + }); + } else if (pathOrBuffer instanceof ArrayBuffer) { + buffer = new Uint8Array(pathOrBuffer); + } else if (ArrayBuffer.isView(pathOrBuffer)) { + buffer = new Uint8Array(pathOrBuffer.buffer); + } + if (buffer) { + this.preloadedFiles.push({ + path: destPath, + buffer: pathOrBuffer, + }); + return Promise.resolve(); + } + return Promise.reject(new Error('Invalid object for preloading')); + }; +}; + +/** + * An object used to configure the Engine instance based on godot export options, and to override those in custom HTML + * templates if needed. + * + * @header Engine configuration + * @summary The Engine configuration object. This is just a typedef, create it like a regular object, e.g.: + * + * ``const MyConfig = { executable: 'godot', unloadAfterInit: false }`` + * + * @typedef {Object} EngineConfig + */ +const EngineConfig = {}; // eslint-disable-line no-unused-vars + +/** + * @struct + * @constructor + * @ignore + */ +const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-vars + const cfg = /** @lends {InternalConfig.prototype} */ { + /** + * Whether the unload the engine automatically after the instance is initialized. + * + * @memberof EngineConfig + * @default + * @type {boolean} + */ + unloadAfterInit: true, + /** + * The HTML DOM Canvas object to use. + * + * By default, the first canvas element in the document will be used is none is specified. + * + * @memberof EngineConfig + * @default + * @type {?HTMLCanvasElement} + */ + canvas: null, + /** + * The name of the WASM file without the extension. (Set by Godot Editor export process). + * + * @memberof EngineConfig + * @default + * @type {string} + */ + executable: '', + /** + * An alternative name for the game pck to load. The executable name is used otherwise. + * + * @memberof EngineConfig + * @default + * @type {?string} + */ + mainPack: null, + /** + * Specify a language code to select the proper localization for the game. + * + * The browser locale will be used if none is specified. See complete list of + * :ref:`supported locales `. + * + * @memberof EngineConfig + * @type {?string} + * @default + */ + locale: null, + /** + * The canvas resize policy determines how the canvas should be resized by Godot. + * + * ``0`` means Godot won't do any resizing. This is useful if you want to control the canvas size from + * javascript code in your template. + * + * ``1`` means Godot will resize the canvas on start, and when changing window size via engine functions. + * + * ``2`` means Godot will adapt the canvas size to match the whole browser window. + * + * @memberof EngineConfig + * @type {number} + * @default + */ + canvasResizePolicy: 2, + /** + * The arguments to be passed as command line arguments on startup. + * + * See :ref:`command line tutorial `. + * + * **Note**: :js:meth:`startGame ` will always add the ``--main-pack`` argument. + * + * @memberof EngineConfig + * @type {Array} + * @default + */ + args: [], + /** + * When enabled, the game canvas will automatically grab the focus when the engine starts. + * + * @memberof EngineConfig + * @type {boolean} + * @default + */ + focusCanvas: true, + /** + * When enabled, this will turn on experimental virtual keyboard support on mobile. + * + * @memberof EngineConfig + * @type {boolean} + * @default + */ + experimentalVK: false, + /** + * The progressive web app service worker to install. + * @memberof EngineConfig + * @default + * @type {string} + */ + serviceWorker: '', + /** + * @ignore + * @type {Array.} + */ + persistentPaths: ['/userfs'], + /** + * @ignore + * @type {boolean} + */ + persistentDrops: false, + /** + * @ignore + * @type {Array.} + */ + gdnativeLibs: [], + /** + * @ignore + * @type {Array.} + */ + fileSizes: [], + /** + * A callback function for handling Godot's ``OS.execute`` calls. + * + * This is for example used in the Web Editor template to switch between project manager and editor, and for running the game. + * + * @callback EngineConfig.onExecute + * @param {string} path The path that Godot's wants executed. + * @param {Array.} args The arguments of the "command" to execute. + */ + /** + * @ignore + * @type {?function(string, Array.)} + */ + onExecute: null, + /** + * A callback function for being notified when the Godot instance quits. + * + * **Note**: This function will not be called if the engine crashes or become unresponsive. + * + * @callback EngineConfig.onExit + * @param {number} status_code The status code returned by Godot on exit. + */ + /** + * @ignore + * @type {?function(number)} + */ + onExit: null, + /** + * A callback function for displaying download progress. + * + * The function is called once per frame while downloading files, so the usage of ``requestAnimationFrame()`` + * is not necessary. + * + * If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate. + * Possible reasons include: + * + * - Files are delivered with server-side chunked compression + * - Files are delivered with server-side compression on Chromium + * - Not all file downloads have started yet (usually on servers without multi-threading) + * + * @callback EngineConfig.onProgress + * @param {number} current The current amount of downloaded bytes so far. + * @param {number} total The total amount of bytes to be downloaded. + */ + /** + * @ignore + * @type {?function(number, number)} + */ + onProgress: null, + /** + * A callback function for handling the standard output stream. This method should usually only be used in debug pages. + * + * By default, ``console.log()`` is used. + * + * @callback EngineConfig.onPrint + * @param {...*} [var_args] A variadic number of arguments to be printed. + */ + /** + * @ignore + * @type {?function(...*)} + */ + onPrint: function () { + console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console + }, + /** + * A callback function for handling the standard error stream. This method should usually only be used in debug pages. + * + * By default, ``console.error()`` is used. + * + * @callback EngineConfig.onPrintError + * @param {...*} [var_args] A variadic number of arguments to be printed as errors. + */ + /** + * @ignore + * @type {?function(...*)} + */ + onPrintError: function (var_args) { + console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console + }, + }; + + /** + * @ignore + * @struct + * @constructor + * @param {EngineConfig} opts + */ + function Config(opts) { + this.update(opts); + } + + Config.prototype = cfg; + + /** + * @ignore + * @param {EngineConfig} opts + */ + Config.prototype.update = function (opts) { + const config = opts || {}; + // NOTE: We must explicitly pass the default, accessing it via + // the key will fail due to closure compiler renames. + function parse(key, def) { + if (typeof (config[key]) === 'undefined') { + return def; + } + return config[key]; + } + // Module config + this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit); + this.onPrintError = parse('onPrintError', this.onPrintError); + this.onPrint = parse('onPrint', this.onPrint); + this.onProgress = parse('onProgress', this.onProgress); + + // Godot config + this.canvas = parse('canvas', this.canvas); + this.executable = parse('executable', this.executable); + this.mainPack = parse('mainPack', this.mainPack); + this.locale = parse('locale', this.locale); + this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy); + this.persistentPaths = parse('persistentPaths', this.persistentPaths); + this.persistentDrops = parse('persistentDrops', this.persistentDrops); + this.experimentalVK = parse('experimentalVK', this.experimentalVK); + this.focusCanvas = parse('focusCanvas', this.focusCanvas); + this.serviceWorker = parse('serviceWorker', this.serviceWorker); + this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs); + this.fileSizes = parse('fileSizes', this.fileSizes); + this.args = parse('args', this.args); + this.onExecute = parse('onExecute', this.onExecute); + this.onExit = parse('onExit', this.onExit); + }; + + /** + * @ignore + * @param {string} loadPath + * @param {Response} response + */ + Config.prototype.getModuleConfig = function (loadPath, response) { + let r = response; + return { + 'print': this.onPrint, + 'printErr': this.onPrintError, + 'thisProgram': this.executable, + 'noExitRuntime': true, + 'dynamicLibraries': [`${loadPath}.side.wasm`], + 'instantiateWasm': function (imports, onSuccess) { + function done(result) { + onSuccess(result['instance'], result['module']); + } + if (typeof (WebAssembly.instantiateStreaming) !== 'undefined') { + WebAssembly.instantiateStreaming(Promise.resolve(r), imports).then(done); + } else { + r.arrayBuffer().then(function (buffer) { + WebAssembly.instantiate(buffer, imports).then(done); + }); + } + r = null; + return {}; + }, + 'locateFile': function (path) { + if (path.endsWith('.worker.js')) { + return `${loadPath}.worker.js`; + } else if (path.endsWith('.audio.worklet.js')) { + return `${loadPath}.audio.worklet.js`; + } else if (path.endsWith('.js')) { + return `${loadPath}.js`; + } else if (path.endsWith('.side.wasm')) { + return `${loadPath}.side.wasm`; + } else if (path.endsWith('.wasm')) { + return `${loadPath}.wasm`; + } + return path; + }, + }; + }; + + /** + * @ignore + * @param {function()} cleanup + */ + Config.prototype.getGodotConfig = function (cleanup) { + // Try to find a canvas + if (!(this.canvas instanceof HTMLCanvasElement)) { + const nodes = document.getElementsByTagName('canvas'); + if (nodes.length && nodes[0] instanceof HTMLCanvasElement) { + this.canvas = nodes[0]; + } + if (!this.canvas) { + throw new Error('No canvas found in page'); + } + } + // Canvas can grab focus on click, or key events won't work. + if (this.canvas.tabIndex < 0) { + this.canvas.tabIndex = 0; + } + + // Browser locale, or custom one if defined. + let locale = this.locale; + if (!locale) { + locale = navigator.languages ? navigator.languages[0] : navigator.language; + locale = locale.split('.')[0]; + } + locale = locale.replace('-', '_'); + const onExit = this.onExit; + + // Godot configuration. + return { + 'canvas': this.canvas, + 'canvasResizePolicy': this.canvasResizePolicy, + 'locale': locale, + 'persistentDrops': this.persistentDrops, + 'virtualKeyboard': this.experimentalVK, + 'focusCanvas': this.focusCanvas, + 'onExecute': this.onExecute, + 'onExit': function (p_code) { + cleanup(); // We always need to call the cleanup callback to free memory. + if (typeof (onExit) === 'function') { + onExit(p_code); + } + }, + }; + }; + return new Config(initConfig); +}; + +/** + * Projects exported for the Web expose the :js:class:`Engine` class to the JavaScript environment, that allows + * fine control over the engine's start-up process. + * + * This API is built in an asynchronous manner and requires basic understanding + * of `Promises `__. + * + * @module Engine + * @header HTML5 shell class reference + */ +const Engine = (function () { + const preloader = new Preloader(); + + let loadPromise = null; + let loadPath = ''; + let initPromise = null; + + /** + * @classdesc The ``Engine`` class provides methods for loading and starting exported projects on the Web. For default export + * settings, this is already part of the exported HTML page. To understand practical use of the ``Engine`` class, + * see :ref:`Custom HTML page for Web export `. + * + * @description Create a new Engine instance with the given configuration. + * + * @global + * @constructor + * @param {EngineConfig} initConfig The initial config for this instance. + */ + function Engine(initConfig) { // eslint-disable-line no-shadow + this.config = new InternalConfig(initConfig); + this.rtenv = null; + } + + /** + * Load the engine from the specified base path. + * + * @param {string} basePath Base path of the engine to load. + * @param {number=} [size=0] The file size if known. + * @returns {Promise} A Promise that resolves once the engine is loaded. + * + * @function Engine.load + */ + Engine.load = function (basePath, size) { + if (loadPromise == null) { + loadPath = basePath; + loadPromise = preloader.loadPromise(`${loadPath}.wasm`, size, true); + requestAnimationFrame(preloader.animateProgress); + } + return loadPromise; + }; + + /** + * Unload the engine to free memory. + * + * This method will be called automatically depending on the configuration. See :js:attr:`unloadAfterInit`. + * + * @function Engine.unload + */ + Engine.unload = function () { + loadPromise = null; + }; + + /** + * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for. + * + * @param {number=} [majorVersion=1] The major WebGL version to check for. + * @returns {boolean} If the given major version of WebGL is available. + * @function Engine.isWebGLAvailable + */ + Engine.isWebGLAvailable = function (majorVersion = 1) { + try { + return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]); + } catch (e) { /* Not available */ } + return false; + }; + + /** + * Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution. + * @ignore + * @constructor + */ + function SafeEngine(initConfig) { + const proto = /** @lends Engine.prototype */ { + /** + * Initialize the engine instance. Optionally, pass the base path to the engine to load it, + * if it hasn't been loaded yet. See :js:meth:`Engine.load`. + * + * @param {string=} basePath Base path of the engine to load. + * @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized. + */ + init: function (basePath) { + if (initPromise) { + return initPromise; + } + if (loadPromise == null) { + if (!basePath) { + initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.')); + return initPromise; + } + Engine.load(basePath, this.config.fileSizes[`${basePath}.wasm`]); + } + const me = this; + function doInit(promise) { + // Care! Promise chaining is bogus with old emscripten versions. + // This caused a regression with the Mono build (which uses an older emscripten version). + // Make sure to test that when refactoring. + return new Promise(function (resolve, reject) { + promise.then(function (response) { + const cloned = new Response(response.clone().body, { 'headers': [['content-type', 'application/wasm']] }); + Godot(me.config.getModuleConfig(loadPath, cloned)).then(function (module) { + const paths = me.config.persistentPaths; + module['initFS'](paths).then(function (err) { + me.rtenv = module; + if (me.config.unloadAfterInit) { + Engine.unload(); + } + resolve(); + }); + }); + }); + }); + } + preloader.setProgressFunc(this.config.onProgress); + initPromise = doInit(loadPromise); + return initPromise; + }, + + /** + * Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the + * instance. + * + * If not provided, the ``path`` is derived from the URL of the loaded file. + * + * @param {string|ArrayBuffer} file The file to preload. + * + * If a ``string`` the file will be loaded from that path. + * + * If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file. + * + * @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string. + * + * @returns {Promise} A Promise that resolves once the file is loaded. + */ + preloadFile: function (file, path) { + return preloader.preload(file, path, this.config.fileSizes[file]); + }, + + /** + * Start the engine instance using the given override configuration (if any). + * :js:meth:`startGame ` can be used in typical cases instead. + * + * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init `. + * The engine must be loaded beforehand. + * + * Fails if a canvas cannot be found on the page, or not specified in the configuration. + * + * @param {EngineConfig} override An optional configuration override. + * @return {Promise} Promise that resolves once the engine started. + */ + start: function (override) { + this.config.update(override); + const me = this; + return me.init().then(function () { + if (!me.rtenv) { + return Promise.reject(new Error('The engine must be initialized before it can be started')); + } + + let config = {}; + try { + config = me.config.getGodotConfig(function () { + me.rtenv = null; + }); + } catch (e) { + return Promise.reject(e); + } + // Godot configuration. + me.rtenv['initConfig'](config); + + // Preload GDNative libraries. + const libs = []; + me.config.gdnativeLibs.forEach(function (lib) { + libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true })); + }); + return Promise.all(libs).then(function () { + return new Promise(function (resolve, reject) { + preloader.preloadedFiles.forEach(function (file) { + me.rtenv['copyToFS'](file.path, file.buffer); + }); + preloader.preloadedFiles.length = 0; // Clear memory + me.rtenv['callMain'](me.config.args); + initPromise = null; + if (me.config.serviceWorker && 'serviceWorker' in navigator) { + navigator.serviceWorker.register(me.config.serviceWorker); + } + resolve(); + }); + }); + }); + }, + + /** + * Start the game instance using the given configuration override (if any). + * + * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init `. + * + * This will load the engine if it is not loaded, and preload the main pck. + * + * This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack` + * properties set (normally done by the editor during export). + * + * @param {EngineConfig} override An optional configuration override. + * @return {Promise} Promise that resolves once the game started. + */ + startGame: function (override) { + this.config.update(override); + // Add main-pack argument. + const exe = this.config.executable; + const pack = this.config.mainPack || `${exe}.pck`; + this.config.args = ['--main-pack', pack].concat(this.config.args); + // Start and init with execName as loadPath if not inited. + const me = this; + return Promise.all([ + this.init(exe), + this.preloadFile(pack, pack), + ]).then(function () { + return me.start.apply(me); + }); + }, + + /** + * Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system. + * + * @param {string} path The location where the file will be created. + * @param {ArrayBuffer} buffer The content of the file. + */ + copyToFS: function (path, buffer) { + if (this.rtenv == null) { + throw new Error('Engine must be inited before copying files'); + } + this.rtenv['copyToFS'](path, buffer); + }, + + /** + * Request that the current instance quit. + * + * This is akin the user pressing the close button in the window manager, and will + * have no effect if the engine has crashed, or is stuck in a loop. + * + */ + requestQuit: function () { + if (this.rtenv) { + this.rtenv['request_quit'](); + } + }, + }; + + Engine.prototype = proto; + // Closure compiler exported instance methods. + Engine.prototype['init'] = Engine.prototype.init; + Engine.prototype['preloadFile'] = Engine.prototype.preloadFile; + Engine.prototype['start'] = Engine.prototype.start; + Engine.prototype['startGame'] = Engine.prototype.startGame; + Engine.prototype['copyToFS'] = Engine.prototype.copyToFS; + Engine.prototype['requestQuit'] = Engine.prototype.requestQuit; + // Also expose static methods as instance methods + Engine.prototype['load'] = Engine.load; + Engine.prototype['unload'] = Engine.unload; + Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable; + return new Engine(initConfig); + } + + // Closure compiler exported static methods. + SafeEngine['load'] = Engine.load; + SafeEngine['unload'] = Engine.unload; + SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable; + + return SafeEngine; +}()); +if (typeof window !== 'undefined') { + window['Engine'] = Engine; +} diff --git a/public/assets/games/bobble/index-nothreads.pck b/public/assets/games/bobble/index-nothreads.pck new file mode 100644 index 00000000..6226ee72 Binary files /dev/null and b/public/assets/games/bobble/index-nothreads.pck differ diff --git a/public/assets/games/bobble/index-nothreads.wasm b/public/assets/games/bobble/index-nothreads.wasm new file mode 100644 index 00000000..917a765f Binary files /dev/null and b/public/assets/games/bobble/index-nothreads.wasm differ diff --git a/public/assets/games/bobble/index.html b/public/assets/games/bobble/index.html new file mode 100644 index 00000000..5159c982 --- /dev/null +++ b/public/assets/games/bobble/index.html @@ -0,0 +1,1139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + Bobble + + + + + + + + + + + + HTML5 canvas appears to be unsupported in the current browser.
+ Please try the direct downloads or use a different browser. +
+
+
+ +
+ +
+ + + +
+ +
+ +
+
+
+
+
+ +
+
+
+
+ + + + + + + diff --git a/public/assets/games/bobble/paystation.js b/public/assets/games/bobble/paystation.js new file mode 100644 index 00000000..fc78c534 --- /dev/null +++ b/public/assets/games/bobble/paystation.js @@ -0,0 +1,1860 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.XPayStationWidget = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o' : SPINNERS[options.spinner] || Object.values(SPINNERS)[0]; + + var template = function (settings) { + var host = document.createElement('div'); + host.className = settings.prefix; + + var overlay = document.createElement('div'); + overlay.className = settings.prefix + '-overlay'; + + var content = document.createElement('div'); + content.className = settings.prefix + '-content' + ' ' + settings.prefix + '-content__hidden'; + + var iframe = document.createElement('iframe'); + iframe.className = settings.prefix + '-content-iframe'; + iframe.src = settings.url; + iframe.frameBorder = '0'; + iframe.allowFullscreen = true; + + var spinner = document.createElement('div'); + spinner.className = settings.prefix + '-spinner'; + spinner.innerHTML = settings.spinner; + + content.appendChild(iframe); + + host.appendChild(overlay); + host.appendChild(content); + host.appendChild(spinner); + + return host; + }; + + var bodyElement = global.document.body; + var lightBoxElement = template({ + prefix: CLASS_PREFIX, + url: url, + spinner: spinner + }); + var lightBoxOverlayElement = lightBoxElement.querySelector('.' + CLASS_PREFIX + '-overlay'); + var lightBoxContentElement = lightBoxElement.querySelector('.' + CLASS_PREFIX + '-content'); + var lightBoxIframeElement = lightBoxContentElement.querySelector('.' + CLASS_PREFIX + '-content-iframe'); + var lightBoxSpinnerElement = lightBoxElement.querySelector('.' + CLASS_PREFIX + '-spinner'); + + var psDimensions = { + width: withDefaultPXUnit(MIN_PS_DIMENSIONS.width), + height: withDefaultPXUnit(MIN_PS_DIMENSIONS.height) + }; + + function withDefaultPXUnit(value) { + var isStringWithoutUnit = typeof value === 'string' && String(parseFloat(value)).length === value.length; + if (isStringWithoutUnit) { + return value + 'px'; + } + return typeof value === 'number' ? value + 'px' : value + } + + lightBoxElement.style.zIndex = options.zIndex; + + lightBoxOverlayElement.style.opacity = options.overlayOpacity; + lightBoxOverlayElement.style.backgroundColor = options.overlayBackground; + + lightBoxContentElement.style.backgroundColor = options.contentBackground; + lightBoxContentElement.style.margin = withDefaultPXUnit(options.contentMargin); + lightBoxContentElement.style.width = options.width ? withDefaultPXUnit(options.width) : 'auto'; + lightBoxContentElement.style.height = options.height ? withDefaultPXUnit(options.height) : 'auto'; + + if (options.spinnerColor) { + lightBoxSpinnerElement.querySelector('path').style.fill = options.spinnerColor; + } + + if (options.spinner === 'custom') { + var spinnerCustom = lightBoxSpinnerElement.querySelector('.spinner-custom'); + spinnerCustom.style['-webkit-animation-duration'] = options.spinnerRotationPeriod + 's;'; + spinnerCustom.style['animation-duration'] = options.spinnerRotationPeriod + 's;'; + } + + if (options.closeByClick) { + lightBoxOverlayElement.addEventListener('click', (function () { + this.closeFrame(); + }).bind(this)); + } + + bodyElement.appendChild(lightBoxElement); + + if (options.closeByKeyboard) { + + bodyElement.addEventListener(handleKeyupEventName, HandleBoundSpecificKeyup); + + bodyElement.addEventListener('keyup', handleGlobalKeyup, false); + } + + var showContent = Helpers.once((function () { + hideSpinner(options); + lightBoxContentElement.classList.remove(CLASS_PREFIX + '-content__hidden'); + this.triggerEvent('load'); + }).bind(this)); + + var lightBoxResize = function () { + var width = options.width ? options.width : psDimensions.width; + var height = options.height ? options.height : psDimensions.height; + + lightBoxContentElement.style.left = '0px'; + lightBoxContentElement.style.top = '0px'; + lightBoxContentElement.style.borderRadius = '8px'; + lightBoxContentElement.style.width = withDefaultPXUnit(width); + lightBoxContentElement.style.height = withDefaultPXUnit(height); + + var containerWidth = lightBoxElement.clientWidth, + containerHeight = lightBoxElement.clientHeight; + + var contentWidth = outerWidth(lightBoxContentElement), + contentHeight = outerHeight(lightBoxContentElement); + + var horMargin = contentWidth - lightBoxContentElement.offsetWidth, + vertMargin = contentHeight - lightBoxContentElement.offsetHeight; + + var horDiff = containerWidth - contentWidth, + vertDiff = containerHeight - contentHeight; + + if (horDiff < 0) { + lightBoxContentElement.style.width = containerWidth - horMargin + 'px'; + } else { + lightBoxContentElement.style.left = Math.round(horDiff / 2) + 'px'; + } + + if (vertDiff < 0) { + lightBoxContentElement.style.height = containerHeight - vertMargin + 'px'; + } else { + lightBoxContentElement.style.top = Math.round(vertDiff / 2) + 'px'; + } + }; + + if (options.width && options.height) { + lightBoxResize = Helpers.once(lightBoxResize.bind(this)); + } + + function outerWidth(el) { + var width = el.offsetWidth; + var style = getComputedStyle(el); + + width += parseInt(style.marginLeft) + parseInt(style.marginRight); + return width; + } + + function outerHeight(el) { + var height = el.offsetHeight; + var style = getComputedStyle(el); + + height += parseInt(style.marginTop) + parseInt(style.marginBottom); + return height; + } + + var bodyStyles; + var hideScrollbar = (function () { + bodyStyles = Helpers.zipObject(['overflow', 'paddingRight'].map(function (key) { + return [key, getComputedStyle(bodyElement)[key]]; + })); + + var bodyPad = parseInt((getComputedStyle(bodyElement)['paddingRight'] || 0), 10); + bodyElement.style.overflow = 'hidden'; + bodyElement.style.paddingRight = withDefaultPXUnit(bodyPad + this.measureScrollbar()); + }).bind(this); + + var resetScrollbar = function () { + if (bodyStyles) { + Object.keys(bodyStyles).forEach(function(key) { + bodyElement.style[key] = bodyStyles[key]; + }) + } + }; + + var showSpinner = function () { + lightBoxSpinnerElement.style.display = 'block'; + }; + + var hideSpinner = function () { + lightBoxSpinnerElement.style.display = 'none'; + }; + + var loadTimer; + lightBoxIframeElement.addEventListener('load', function handleLoad(event) { + var timeout = !(options.width && options.height) ? (options.resizeTimeout || 30000) : 1000; // 30000 if psDimensions will not arrive and custom timeout is not provided + loadTimer = global.setTimeout(function () { + lightBoxResize(); + showContent(); + }, timeout); + lightBoxIframeElement.removeEventListener('load', handleLoad); + + }); + + var iframeWindow = lightBoxIframeElement.contentWindow || lightBoxIframeElement; + + // Cross-window communication + this.message = new PostMessage(iframeWindow); + if (options.width && options.height) { + this.message.on('dimensions', (function () { + lightBoxResize(); + showContent(); + })); + } else { + this.message.on('dimensions', (function (event) { + var data = event.detail; + if (data.dimensions) { + psDimensions = Helpers.zipObject(['width', 'height'].map(function (dim) { + return [dim, Math.max(MIN_PS_DIMENSIONS[dim] || 0, data.dimensions[dim] || 0) + 'px']; + })); + + lightBoxResize(); + } + showContent(); + })); + } + this.message.on('widget-detection', (function () { + this.message.send('widget-detected', {version: version, lightBoxOptions: options}); + }).bind(this)); + this.message.on('widget-close', (function () { + this.closeFrame(); + }).bind(this)); + this.message.on('close', (function () { + this.closeFrame(); + }).bind(this)); + this.message.on('status', (function (event) { + this.triggerEvent('status', event.detail); + }).bind(this)); + this.message.on('user-country', (function (event) { + this.triggerEvent('user-country', event.detail); + }).bind(this)); + this.message.on('fcp', (function (event) { + this.triggerEvent('fcp', event.detail); + }).bind(this)); + + // Resize + window.addEventListener(handleResizeEventName, lightBoxResize); + window.addEventListener('resize', handleGlobalResize); + + // Clean up after close + var that = this; + this.on('close', function handleClose(event) { + that.message.off(); + bodyElement.removeEventListener(handleKeyupEventName, HandleBoundSpecificKeyup) + bodyElement.removeEventListener('keyup', handleGlobalKeyup); + + window.removeEventListener('resize', handleGlobalResize) + + window.removeEventListener(handleResizeEventName, lightBoxResize); + lightBoxElement.parentNode.removeChild(lightBoxElement); + resetScrollbar(); + that.off('close', handleClose); + }); + + showSpinner(); + hideScrollbar(); + this.triggerEvent('open'); + }; + + LightBox.prototype.closeFrame = function () { + if (!this.options.modal) { + this.triggerEvent('close'); + } + }; + + LightBox.prototype.close = function () { + this.closeFrame(); + }; + + LightBox.prototype.on = function () { + this.eventObject.on.apply(this.eventObject, arguments); + }; + + LightBox.prototype.off = function () { + this.eventObject.off.apply(this.eventObject, arguments); + }; + + LightBox.prototype.getPostMessage = function () { + return this.message; + }; + + LightBox._NAMESPACE = '.xpaystation-widget-lightbox'; + + return LightBox; + })(); + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + + },{"./helpers":7,"./postmessage":10,"./spinners/round.svg":11,"./spinners/xsolla.svg":12,"./styles/lightbox.scss":13,"./version":14}],9:[function(require,module,exports){ + function objectAssign() { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign Polyfill + Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e,r){"use strict";if(null==e)throw new TypeError("Cannot convert first argument to object");for(var t=Object(e),n=1;n>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(t=o),n=0;n"; + + },{}],12:[function(require,module,exports){ + module.exports = ""; + + },{}],13:[function(require,module,exports){ + module.exports = require('sassify')('.xpaystation-widget-lightbox{position:fixed;top:0;left:0;bottom:0;right:0;width:100%;height:100%;-webkit-animation:xpaystation-widget-lightbox-fadein 0.15s;animation:xpaystation-widget-lightbox-fadein 0.15s}.xpaystation-widget-lightbox-overlay{position:absolute;top:0;left:0;bottom:0;right:0;z-index:1}.xpaystation-widget-lightbox-content{position:relative;top:0;left:0;z-index:3}.xpaystation-widget-lightbox-content__hidden{visibility:hidden;z-index:-1}.xpaystation-widget-lightbox-content-iframe{width:100%;height:100%;border:0;background:transparent}.xpaystation-widget-lightbox-spinner{position:absolute;top:50%;left:50%;display:none;z-index:2;pointer-events:none}.xpaystation-widget-lightbox-spinner .spinner-xsolla{width:56px;height:55px;margin-top:-28px;margin-left:-26px}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-x,.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-s,.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-o,.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-l,.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-a{-webkit-animation:xpaystation-widget-lightbox-bouncedelay 1s infinite ease-in-out;-webkit-animation-fill-mode:both;animation:xpaystation-widget-lightbox-bouncedelay 1s infinite ease-in-out;animation-fill-mode:both}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-x{-webkit-animation-delay:0s;animation-delay:0s}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-s{-webkit-animation-delay:.2s;animation-delay:.2s}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-o{-webkit-animation-delay:.4s;animation-delay:.4s}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-l{-webkit-animation-delay:.6s;animation-delay:.6s}.xpaystation-widget-lightbox-spinner .spinner-xsolla .spinner-xsolla-a{-webkit-animation-delay:.8s;animation-delay:.8s}.xpaystation-widget-lightbox-spinner .spinner-round{margin-top:-23px;margin-left:-23px;-webkit-animation:xpaystation-widget-lightbox-spin 3s infinite linear;animation:xpaystation-widget-lightbox-spin 3s infinite linear}.xpaystation-widget-lightbox-spinner .spinner-custom{-webkit-animation:xpaystation-widget-lightbox-spin infinite linear;animation:xpaystation-widget-lightbox-spin infinite linear}@-webkit-keyframes xpaystation-widget-lightbox-bouncedelay{0%,80%,100%{opacity:0}40%{opacity:1}}@keyframes xpaystation-widget-lightbox-bouncedelay{0%,80%,100%{opacity:0}40%{opacity:1}}@-webkit-keyframes xpaystation-widget-lightbox-fadein{from{opacity:0}to{opacity:1}}@keyframes xpaystation-widget-lightbox-fadein{from{opacity:0}to{opacity:1}}@-webkit-keyframes xpaystation-widget-lightbox-spin{from{-webkit-transform:rotate(0deg)}to{-webkit-transform:rotate(360deg)}}@keyframes xpaystation-widget-lightbox-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}} /*# sourceMappingURL=data:application/json;base64,ewoJInZlcnNpb24iOiAzLAoJImZpbGUiOiAibGlnaHRib3guc2NzcyIsCgkic291cmNlcyI6IFsKCQkibGlnaHRib3guc2NzcyIKCV0sCgkic291cmNlc0NvbnRlbnQiOiBbCgkJIiRsaWdodGJveC1wcmVmaXg6ICd4cGF5c3RhdGlvbi13aWRnZXQtbGlnaHRib3gnO1xuJGxpZ2h0Ym94LWNsYXNzOiAnLicgKyAkbGlnaHRib3gtcHJlZml4O1xuXG4jeyRsaWdodGJveC1jbGFzc30ge1xuICBwb3NpdGlvbjogZml4ZWQ7XG4gIHRvcDogMDtcbiAgbGVmdDogMDtcbiAgYm90dG9tOiAwO1xuICByaWdodDogMDtcbiAgd2lkdGg6IDEwMCU7XG4gIGhlaWdodDogMTAwJTtcbiAgLXdlYmtpdC1hbmltYXRpb246ICN7JGxpZ2h0Ym94L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exports = '1.2.9'; + + },{}],"bowser":[function(require,module,exports){ + /*! + * Bowser - a browser detector + * https://github.com/ded/bowser + * MIT License | (c) Dustin Diaz 2015 + */ + + !function (root, name, definition) { + if (typeof module != 'undefined' && module.exports) module.exports = definition() + else if (typeof define == 'function' && define.amd) define(name, definition) + else root[name] = definition() + }(this, 'bowser', function () { + /** + * See useragents.js for examples of navigator.userAgent + */ + + var t = true + + function detect(ua) { + + function getFirstMatch(regex) { + var match = ua.match(regex); + return (match && match.length > 1 && match[1]) || ''; + } + + function getSecondMatch(regex) { + var match = ua.match(regex); + return (match && match.length > 1 && match[2]) || ''; + } + + var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase() + , likeAndroid = /like android/i.test(ua) + , android = !likeAndroid && /android/i.test(ua) + , nexusMobile = /nexus\s*[0-6]\s*/i.test(ua) + , nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua) + , chromeos = /CrOS/.test(ua) + , silk = /silk/i.test(ua) + , sailfish = /sailfish/i.test(ua) + , tizen = /tizen/i.test(ua) + , webos = /(web|hpw)(o|0)s/i.test(ua) + , windowsphone = /windows phone/i.test(ua) + , samsungBrowser = /SamsungBrowser/i.test(ua) + , windows = !windowsphone && /windows/i.test(ua) + , mac = !iosdevice && !silk && /macintosh/i.test(ua) + , linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua) + , edgeVersion = getSecondMatch(/edg([ea]|ios)\/(\d+(\.\d+)?)/i) + , versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i) + , tablet = /tablet/i.test(ua) && !/tablet pc/i.test(ua) + , mobile = !tablet && /[^-]mobi/i.test(ua) + , xbox = /xbox/i.test(ua) + , result + + if (/opera/i.test(ua)) { + // an old Opera + result = { + name: 'Opera' + , opera: t + , version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i) + } + } else if (/opr\/|opios/i.test(ua)) { + // a new Opera + result = { + name: 'Opera' + , opera: t + , version: getFirstMatch(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i) || versionIdentifier + } + } + else if (/SamsungBrowser/i.test(ua)) { + result = { + name: 'Samsung Internet for Android' + , samsungBrowser: t + , version: versionIdentifier || getFirstMatch(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i) + } + } + else if (/Whale/i.test(ua)) { + result = { + name: 'NAVER Whale browser' + , whale: t + , version: getFirstMatch(/(?:whale)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/MZBrowser/i.test(ua)) { + result = { + name: 'MZ Browser' + , mzbrowser: t + , version: getFirstMatch(/(?:MZBrowser)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/coast/i.test(ua)) { + result = { + name: 'Opera Coast' + , coast: t + , version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i) + } + } + else if (/focus/i.test(ua)) { + result = { + name: 'Focus' + , focus: t + , version: getFirstMatch(/(?:focus)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/yabrowser/i.test(ua)) { + result = { + name: 'Yandex Browser' + , yandexbrowser: t + , version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i) + } + } + else if (/ucbrowser/i.test(ua)) { + result = { + name: 'UC Browser' + , ucbrowser: t + , version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/mxios/i.test(ua)) { + result = { + name: 'Maxthon' + , maxthon: t + , version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/epiphany/i.test(ua)) { + result = { + name: 'Epiphany' + , epiphany: t + , version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/puffin/i.test(ua)) { + result = { + name: 'Puffin' + , puffin: t + , version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i) + } + } + else if (/sleipnir/i.test(ua)) { + result = { + name: 'Sleipnir' + , sleipnir: t + , version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (/k-meleon/i.test(ua)) { + result = { + name: 'K-Meleon' + , kMeleon: t + , version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i) + } + } + else if (windowsphone) { + result = { + name: 'Windows Phone' + , osname: 'Windows Phone' + , windowsphone: t + } + if (edgeVersion) { + result.msedge = t + result.version = edgeVersion + } + else { + result.msie = t + result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i) + } + } + else if (/msie|trident/i.test(ua)) { + result = { + name: 'Internet Explorer' + , msie: t + , version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) + } + } else if (chromeos) { + result = { + name: 'Chrome' + , osname: 'Chrome OS' + , chromeos: t + , chromeBook: t + , chrome: t + , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) + } + } else if (/edg([ea]|ios)/i.test(ua)) { + result = { + name: 'Microsoft Edge' + , msedge: t + , version: edgeVersion + } + } + else if (/vivaldi/i.test(ua)) { + result = { + name: 'Vivaldi' + , vivaldi: t + , version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier + } + } + else if (sailfish) { + result = { + name: 'Sailfish' + , osname: 'Sailfish OS' + , sailfish: t + , version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) + } + } + else if (/seamonkey\//i.test(ua)) { + result = { + name: 'SeaMonkey' + , seamonkey: t + , version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) + } + } + else if (/firefox|iceweasel|fxios/i.test(ua)) { + result = { + name: 'Firefox' + , firefox: t + , version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i) + } + if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { + result.firefoxos = t + result.osname = 'Firefox OS' + } + } + else if (silk) { + result = { + name: 'Amazon Silk' + , silk: t + , version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i) + } + } + else if (/phantom/i.test(ua)) { + result = { + name: 'PhantomJS' + , phantom: t + , version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) + } + } + else if (/slimerjs/i.test(ua)) { + result = { + name: 'SlimerJS' + , slimer: t + , version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i) + } + } + else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { + result = { + name: 'BlackBerry' + , osname: 'BlackBerry OS' + , blackberry: t + , version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) + } + } + else if (webos) { + result = { + name: 'WebOS' + , osname: 'WebOS' + , webos: t + , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) + }; + /touchpad\//i.test(ua) && (result.touchpad = t) + } + else if (/bada/i.test(ua)) { + result = { + name: 'Bada' + , osname: 'Bada' + , bada: t + , version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) + }; + } + else if (tizen) { + result = { + name: 'Tizen' + , osname: 'Tizen' + , tizen: t + , version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier + }; + } + else if (/qupzilla/i.test(ua)) { + result = { + name: 'QupZilla' + , qupzilla: t + , version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier + } + } + else if (/chromium/i.test(ua)) { + result = { + name: 'Chromium' + , chromium: t + , version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier + } + } + else if (/chrome|crios|crmo/i.test(ua)) { + result = { + name: 'Chrome' + , chrome: t + , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) + } + } + else if (android) { + result = { + name: 'Android' + , version: versionIdentifier + } + } + else if (/safari|applewebkit/i.test(ua)) { + result = { + name: 'Safari' + , safari: t + } + if (versionIdentifier) { + result.version = versionIdentifier + } + } + else if (iosdevice) { + result = { + name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' + } + // WTF: version is not part of user agent in web apps + if (versionIdentifier) { + result.version = versionIdentifier + } + } + else if(/googlebot/i.test(ua)) { + result = { + name: 'Googlebot' + , googlebot: t + , version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier + } + } + else { + result = { + name: getFirstMatch(/^(.*)\/(.*) /), + version: getSecondMatch(/^(.*)\/(.*) /) + }; + } + + // set webkit or gecko flag for browsers based on these engines + if (!result.msedge && /(apple)?webkit/i.test(ua)) { + if (/(apple)?webkit\/537\.36/i.test(ua)) { + result.name = result.name || "Blink" + result.blink = t + } else { + result.name = result.name || "Webkit" + result.webkit = t + } + if (!result.version && versionIdentifier) { + result.version = versionIdentifier + } + } else if (!result.opera && /gecko\//i.test(ua)) { + result.name = result.name || "Gecko" + result.gecko = t + result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i) + } + + // set OS flags for platforms that have multiple browsers + if (!result.windowsphone && (android || result.silk)) { + result.android = t + result.osname = 'Android' + } else if (!result.windowsphone && iosdevice) { + result[iosdevice] = t + result.ios = t + result.osname = 'iOS' + } else if (mac) { + result.mac = t + result.osname = 'macOS' + } else if (xbox) { + result.xbox = t + result.osname = 'Xbox' + } else if (windows) { + result.windows = t + result.osname = 'Windows' + } else if (linux) { + result.linux = t + result.osname = 'Linux' + } + + function getWindowsVersion (s) { + switch (s) { + case 'NT': return 'NT' + case 'XP': return 'XP' + case 'NT 5.0': return '2000' + case 'NT 5.1': return 'XP' + case 'NT 5.2': return '2003' + case 'NT 6.0': return 'Vista' + case 'NT 6.1': return '7' + case 'NT 6.2': return '8' + case 'NT 6.3': return '8.1' + case 'NT 10.0': return '10' + default: return undefined + } + } + + // OS version extraction + var osVersion = ''; + if (result.windows) { + osVersion = getWindowsVersion(getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i)) + } else if (result.windowsphone) { + osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); + } else if (result.mac) { + osVersion = getFirstMatch(/Mac OS X (\d+([_\.\s]\d+)*)/i); + osVersion = osVersion.replace(/[_\s]/g, '.'); + } else if (iosdevice) { + osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); + osVersion = osVersion.replace(/[_\s]/g, '.'); + } else if (android) { + osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); + } else if (result.webos) { + osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); + } else if (result.blackberry) { + osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); + } else if (result.bada) { + osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); + } else if (result.tizen) { + osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); + } + if (osVersion) { + result.osversion = osVersion; + } + + // device type extraction + var osMajorVersion = !result.windows && osVersion.split('.')[0]; + if ( + tablet + || nexusTablet + || iosdevice == 'ipad' + || (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile))) + || result.silk + ) { + result.tablet = t + } else if ( + mobile + || iosdevice == 'iphone' + || iosdevice == 'ipod' + || android + || nexusMobile + || result.blackberry + || result.webos + || result.bada + ) { + result.mobile = t + } + + // Graded Browser Support + // http://developer.yahoo.com/yui/articles/gbs + if (result.msedge || + (result.msie && result.version >= 10) || + (result.yandexbrowser && result.version >= 15) || + (result.vivaldi && result.version >= 1.0) || + (result.chrome && result.version >= 20) || + (result.samsungBrowser && result.version >= 4) || + (result.whale && compareVersions([result.version, '1.0']) === 1) || + (result.mzbrowser && compareVersions([result.version, '6.0']) === 1) || + (result.focus && compareVersions([result.version, '1.0']) === 1) || + (result.firefox && result.version >= 20.0) || + (result.safari && result.version >= 6) || + (result.opera && result.version >= 10.0) || + (result.ios && result.osversion && result.osversion.split(".")[0] >= 6) || + (result.blackberry && result.version >= 10.1) + || (result.chromium && result.version >= 20) + ) { + result.a = t; + } + else if ((result.msie && result.version < 10) || + (result.chrome && result.version < 20) || + (result.firefox && result.version < 20.0) || + (result.safari && result.version < 6) || + (result.opera && result.version < 10.0) || + (result.ios && result.osversion && result.osversion.split(".")[0] < 6) + || (result.chromium && result.version < 20) + ) { + result.c = t + } else result.x = t + + return result + } + + var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent || '' : '') + + bowser.test = function (browserList) { + for (var i = 0; i < browserList.length; ++i) { + var browserItem = browserList[i]; + if (typeof browserItem=== 'string') { + if (browserItem in bowser) { + return true; + } + } + } + return false; + } + + /** + * Get version precisions count + * + * @example + * getVersionPrecision("1.10.3") // 3 + * + * @param {string} version + * @return {number} + */ + function getVersionPrecision(version) { + return version.split(".").length; + } + + /** + * Array::map polyfill + * + * @param {Array} arr + * @param {Function} iterator + * @return {Array} + */ + function map(arr, iterator) { + var result = [], i; + if (Array.prototype.map) { + return Array.prototype.map.call(arr, iterator); + } + for (i = 0; i < arr.length; i++) { + result.push(iterator(arr[i])); + } + return result; + } + + /** + * Calculate browser version weight + * + * @example + * compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1 + * compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1 + * compareVersions(['1.10.2.1', '1.10.2.1']); // 0 + * compareVersions(['1.10.2.1', '1.0800.2']); // -1 + * + * @param {Array} versions versions to compare + * @return {Number} comparison result + */ + function compareVersions(versions) { + // 1) get common precision for both versions, for example for "10.0" and "9" it should be 2 + var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1])); + var chunks = map(versions, function (version) { + var delta = precision - getVersionPrecision(version); + + // 2) "9" -> "9.0" (for precision = 2) + version = version + new Array(delta + 1).join(".0"); + + // 3) "9.0" -> ["000000000"", "000000009"] + return map(version.split("."), function (chunk) { + return new Array(20 - chunk.length).join("0") + chunk; + }).reverse(); + }); + + // iterate in reverse order by reversed chunks array + while (--precision >= 0) { + // 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true) + if (chunks[0][precision] > chunks[1][precision]) { + return 1; + } + else if (chunks[0][precision] === chunks[1][precision]) { + if (precision === 0) { + // all version chunks are same + return 0; + } + } + else { + return -1; + } + } + } + + /** + * Check if browser is unsupported + * + * @example + * bowser.isUnsupportedBrowser({ + * msie: "10", + * firefox: "23", + * chrome: "29", + * safari: "5.1", + * opera: "16", + * phantom: "534" + * }); + * + * @param {Object} minVersions map of minimal version to browser + * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map + * @param {String} [ua] user agent string + * @return {Boolean} + */ + function isUnsupportedBrowser(minVersions, strictMode, ua) { + var _bowser = bowser; + + // make strictMode param optional with ua param usage + if (typeof strictMode === 'string') { + ua = strictMode; + strictMode = void(0); + } + + if (strictMode === void(0)) { + strictMode = false; + } + if (ua) { + _bowser = detect(ua); + } + + var version = "" + _bowser.version; + for (var browser in minVersions) { + if (minVersions.hasOwnProperty(browser)) { + if (_bowser[browser]) { + if (typeof minVersions[browser] !== 'string') { + throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions)); + } + + // browser version and min supported version. + return compareVersions([version, minVersions[browser]]) < 0; + } + } + } + + return strictMode; // not found + } + + /** + * Check if browser is supported + * + * @param {Object} minVersions map of minimal version to browser + * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map + * @param {String} [ua] user agent string + * @return {Boolean} + */ + function check(minVersions, strictMode, ua) { + return !isUnsupportedBrowser(minVersions, strictMode, ua); + } + + bowser.isUnsupportedBrowser = isUnsupportedBrowser; + bowser.compareVersions = compareVersions; + bowser.check = check; + + /* + * Set our detect method to the main bowser object so we can + * reuse it to test other user agents. + * This is needed to implement future tests. + */ + bowser._detect = detect; + + /* + * Set our detect public method to the main bowser object + * This is needed to implement bowser in server side + */ + bowser.detect = detect; + return bowser + }); + + },{}],"main":[function(require,module,exports){ + var Helpers = require('./helpers') + var App = require('./app'); + var polyfills = require('./polyfills'); + + polyfills.applyPolyfills(); + + var instance; + + module.exports = (function () { + var getInstance = function () { + if (!instance) { + instance = new App(); + } + return instance; + }; + + return Object.assign(Helpers.zipObject(['init', 'isMobile', 'open', 'close', 'on', 'off', 'sendMessage', 'onMessage'].map(function (methodName) { + var app = getInstance(); + return [methodName, function () { + return app[methodName].apply(app, arguments); + }]; + })), { + eventTypes: App.eventTypes, + }); + })(); + + },{"./app":3,"./helpers":7,"./polyfills":9}]},{},["main"])("main") + }); + + //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJub2RlX21vZHVsZXMvY3NzaWZ5L2Jyb3dzZXIuanMiLCJub2RlX21vZHVsZXMvc2Fzc2lmeS9saWIvc2Fzc2lmeS1icm93c2VyLmpzIiwic3JjL2FwcC5qcyIsInNyYy9jaGlsZHdpbmRvdy5qcyIsInNyYy9kZXZpY2UuanMiLCJzcmMvZXhjZXB0aW9uLmpzIiwic3JjL2hlbHBlcnMuanMiLCJzcmMvbGlnaHRib3guanMiLCJzcmMvcG9seWZpbGxzLmpzIiwic3JjL3Bvc3RtZXNzYWdlLmpzIiwic3JjL3NwaW5uZXJzL3JvdW5kLnN2ZyIsInNyYy9zcGlubmVycy94c29sbGEuc3ZnIiwic3JjL3N0eWxlcy9saWdodGJveC5zY3NzIiwic3JjL3ZlcnNpb24uanMiLCJib3dlcl9jb21wb25lbnRzL2Jvd3Nlci9zcmMvYm93c2VyLmpzIiwic3JjL21haW4uanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0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5lcihjbGlja0V2ZW50TmFtZSwgaGFuZGxlQ2xpY2tFdmVudCk7XG5cbiAgICAgICAgICAgIHZhciBjbGlja0V2ZW50ID0gZG9jdW1lbnQuY3JlYXRlRXZlbnQoJ0V2ZW50Jyk7XG4gICAgICAgICAgICBjbGlja0V2ZW50LmluaXRFdmVudChjbGlja0V2ZW50TmFtZSwgZmFsc2UsIHRydWUpO1xuXG4gICAgICAgICAgICBib2R5RWxlbWVudC5hZGRFdmVudExpc3RlbmVyKCdjbGljaycsIChmdW5jdGlvbihldmVudCkge1xuICAgICAgICAgICAgICAgIGNsaWNrRXZlbnQuc291cmNlRXZlbnQgPSBldmVudDtcbiAgICAgICAgICAgICAgICBib2R5RWxlbWVudC5kaXNwYXRjaEV2ZW50KGNsaWNrRXZlbnQpO1xuICAgICAgICAgICAgfSkuYmluZCh0aGlzKSwgZmFsc2UpO1xuXG4gICAgICAgICAgICBib2R5RWxlbWVudC5hZGRFdmVudExpc3RlbmVyKGNsaWNrRXZlbnROYW1lLCBoYW5kbGVDbGlja0V2ZW50KTtcbiAgICAgICAgICAgIHRoaXMudHJpZ2dlckV2ZW50KEFwcC5ldmVudFR5cGVzLklOSVQpO1xuICAgICAgICB9XG4gICAgICAgIHJlYWR5KGluaXRpYWxpemUuYmluZCh0aGlzLCBvcHRpb25zKSk7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogT3BlbiBwYXltZW50IGludGVyZmFjZSAoUGF5U3RhdGlvbilcbiAgICAgKi9cbiAgICBBcHAucHJvdG90eXBlLm9wZW4gPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHRoaXMuY2hlY2tDb25maWcoKTtcbiAgICAgICAgdGhpcy5jaGVja0FwcCgpO1xuXG4gICAgICAgIHZhciB0cmlnZ2VyU3BsaXRTdGF0dXMgPSAoZnVuY3Rpb24gKGRhdGEpIHtcbiAgICAgICAgICAgIHN3aXRjaCAoKChkYXRhIHx8IHt9KS5wYXltZW50SW5mbyB8fCB7fSkuc3RhdHVzKSB7XG4gICAgICAgICAgICAgICAgY2FzZSAnaW52b2ljZSc6XG4gICAgICAgICAgICAgICAgICAgIHRoaXMudHJpZ2dlckV2ZW50KEFwcC5ldmVudFR5cGVzLlNUQVRVU19JTlZPSUNFLCBkYXRhKTtcbiAgICAgICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICAgICAgY2FzZSAnZGVsaXZlcmluZyc6XG4gICAgICAgICAgICAgICAgICAgIHRoaXMudHJpZ2dlckV2ZW50KEFwcC5ldmVudFR5cGVzLlNUQVRVU19ERUxJVkVSSU5HLCBkYXRhKTtcbiAgICAgICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICAgICAgY2FzZSAndHJvdWJsZWQnOlxuICAgICAgICAgICAgICAgICAgICB0aGlzLnRyaWdnZXJFdmVudChBcHAuZXZlbnRUeXBlcy5TVEFUVVNfVFJPVUJMRUQsIGRhdGEpO1xuICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICBjYXNlICdkb25lJzpcbiAgICAgICAgICAgICAgICAgICAgdGhpcy50cmlnZ2VyRXZlbnQoQXBwLmV2ZW50VHlwZXMuU1RBVFVTX0RPTkUsIGRhdGEpO1xuICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSkuYmluZCh0aGlzKTtcblxuICAgICAgICB2YXIgdXJsID0gdGhpcy5nZXRQYXltZW50VXJsKCk7XG4gICAgICAgIHZhciB0aGF0ID0gdGhpcztcblxuICAgICAgICBmdW5jdGlvbiBoYW5kbGVTdGF0dXMoZXZlbnQpIHtcbiAgICAgICAgICAgIHZhciBzdGF0dXNEYXRhID0gZXZlbnQuZGV0YWlsO1xuICAgICAgICAgICAgdGhhdC50cmlnZ2VyRXZlbnQoQXBwLmV2ZW50VHlwZXMuU1RBVFVTLCBzdGF0dXNEYXRhKTtcbiAgICAgICAgICAgIHRyaWdnZXJTcGxpdFN0YXR1cyhzdGF0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dnZXJFdmVudCgnZmNwJywgZXZlbnQuZGV0YWlsKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9O1xuXG4gICAgICAgIHN3aXRjaCAob3B0aW9ucy50YXJnZXQpIHtcbiAgICAgICAgICAgIGNhc2UgJ19zZWxmJzpcbiAgICAgICAgICAgICAgICB0aGlzLmNoaWxkV2luZG93ID0gZ2xvYmFsLndpbmRvdztcbiAgICAgICAgICAgICAgICBhZGRIYW5kbGVycygpO1xuICAgICAgICAgICAgICAgIHRoaXMuY2hpbGRXaW5kb3cubG9jYXRpb24uaHJlZiA9IHVybDtcbiAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIGNhc2UgJ19wYXJlbnQnOlxuICAgICAgICAgICAgICAgIHRoaXMuY2hpbGRXaW5kb3cgPSBnbG9iYWwud2luZG93LnBhcmVudDtcbiAgICAgICAgICAgICAgICBhZGRIYW5kbGVycygpO1xuICAgICAgICAgICAgICAgIHRoaXMuY2hpbGRXaW5kb3cubG9jYXRpb24uaHJlZiA9IHVybDtcbiAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIGNhc2UgJ19ibGFuayc6XG4gICAgICAgICAgICBkZWZhdWx0OlxuICAgICAgICAgICAgICAgIHRoaXMuY2hpbGRXaW5kb3cgPSBnbG9iYWwud2luZG93Lm9wZW4odXJsKTtcbiAgICAgICAgICAgICAgICB0aGlzLmNoaWxkV2luZG93LmZvY3VzKCk7XG4gICAgICAgICAgICAgICAgYWRkSGFuZGxlcnMoKTtcblxuICAgICAgICAgICAgICAgIHZhciBjaGVja1dpbmRvdyA9IChmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgICAgIGlmICh0aGlzLmNoaWxkV2luZG93KSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAodGhpcy5jaGlsZFdpbmRvdy5jbG9zZWQpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLnRyaWdnZXJFdmVudCgnY2xvc2UnKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgdGltZXIgPSBnbG9iYWwuc2V0VGltZW91dChjaGVja1dpbmRvdywgMTAwKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH0pLmJpbmQodGhpcyk7XG4gICAgICAgICAgICAgICAgdmFyIHRpbWVyID0gZ2xvYmFsLnNldFRpbWVvdXQoY2hlY2tXaW5kb3csIDEwMCk7XG4gICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLnRyaWdnZXJFdmVudCgnb3BlbicpO1xuICAgIH07XG5cbiAgICBDaGlsZFdpbmRvdy5wcm90b3R5cGUuY2xvc2UgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHRoaXMudHJpZ2dlckV2ZW50KCdjbG9zZScpO1xuICAgIH07XG5cbiAgICBDaGlsZFdpbmRvdy5wcm90b3R5cGUub24gPSBmdW5jdGlvbiAoZXZlbnQsIGhhbmRsZXIsIG9wdGlvbnMpIHtcbiAgICAgICAgaWYgKHR5cGVvZiBoYW5kbGVyICE9PSAnZnVuY3Rpb24nKSB7XG4gICAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLmV2ZW50T2JqZWN0Lm9uKGV2ZW50LCBoYW5kbGVyLCBvcHRpb25zKTtcbiAgICB9O1xuXG4gICAgQ2hpbGRXaW5kb3cucHJvdG90eXBlLm9mZiA9IGZ1bmN0aW9uIChldmVudCwgaGFuZGxlciwgb3B0aW9ucykge1xuICAgICAgICB0aGlzLmV2ZW50T2JqZWN0Lm9mZihldmVudCwgaGFuZGxlciwgb3B0aW9ucyk7XG4gICAgfTtcblxuICAgIENoaWxkV2luZG93LnByb3RvdHlwZS5nZXRQb3N0TWVzc2FnZSA9IGZ1bmN0aW9uICgpIHtcbiAgIC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LCBsZW4gPSBvYmoubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgICAgICAgICAgICAgIGJ1aWxkUGFyYW1zKFxuICAgICAgICAgICAgICAgICAgICAgIHByZWZpeCArICdbJyArICh0eXBlb2Ygb2JqW2ldID09PSAnb2JqZWN0JyAmJiBvYmpbaV0gPyBpIDogJycpICsgJ10nLFxuICAgICAgICAgICAgICAgICAgICAgIG9ialtpXVxuICAgICAgICAgICAgICAgICAgKTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgIH0gZWxzZSBpZiAoU3RyaW5nKG9iaikgPT09ICdbb2JqZWN0IE9iamVjdF0nKSB7XG4gICAgICAgICAgICAgIGZvciAoa2V5IGluIG9iaikge1xuICAgICAgICAgICAgICAgICAgYnVpbGRQYXJhbXMocHJlZml4ICsgJ1snICsga2V5ICsgJ10nLCBvYmpba2V5XSk7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICBhZGQocHJlZml4LCBvYmopO1xuICAgICAgICAgIH1cbiAgICAgIH0gZWxzZSBpZiAoQXJyYXkuaXNBcnJheShvYmopKSB7XG4gICAgICAgICAgZm9yIChpID0gMCwgbGVuID0gb2JqLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICAgICAgICAgIGFkZChvYmpbaV0ubmFtZSwgb2JqW2ldLnZhbHVlKTtcbiAgICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICAgIGZvciAoa2V5IGluIG9iaikge1xuICAgICAgICAgICAgICBidWlsZFBhcmFtcyhrZXksIG9ialtrZXldKTtcbiAgICAgICAgICB9XG4gICAgICB9XG4gICAgICByZXR1cm4gcztcbiAgfTtcblxuICByZXR1cm4gYnVpbGRQYXJhbXMoJycsIGEpLmpvaW4oJyYnKTtcbn07XG5cblxuZnVuY3Rpb24gb25jZShmKSB7XG4gIHJldHVybiBmdW5jdGlvbigpIHtcbiAgICAgIGYoYXJndW1l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Ck7XG5cbiAgICAgICAgICAgIHZhciBjb250YWluZXJXaWR0aCA9IGxpZ2h0Qm94RWxlbWVudC5jbGllbnRXaWR0aCxcbiAgICAgICAgICAgICAgICBjb250YWluZXJIZWlnaHQgPSBsaWdodEJveEVsZW1lbnQuY2xpZW50SGVpZ2h0O1xuXG4gICAgICAgICAgICB2YXIgY29udGVudFdpZHRoID0gb3V0ZXJXaWR0aChsaWdodEJveENvbnRlbnRFbGVtZW50KSxcbiAgICAgICAgICAgICAgICBjb250ZW50SGVpZ2h0ID0gb3V0ZXJIZWlnaHQobGlnaHRCb3hDb250ZW50RWxlbWVudCk7XG5cbiAgICAgICAgICAgIHZhciBob3JNYXJnaW4gPSBjb250ZW50V2lkdGggLSBsaWdodEJveENvbnRlbnRFbGVtZW50Lm9mZnNldFdpZHRoLFxuICAgICAgICAgICAgICAgIHZlcnRNYXJnaW4gPSBjb250ZW50SGVpZ2h0IC0gbGlnaHRCb3hDb250ZW50RWxlbWVudC5vZmZzZXRIZWlnaHQ7XG5cbiAgICAgICAgICAgIHZhciBob3JEaWZmID0gY29udGFpbmVyV2lkdGggLSBjb250ZW50V2lkdGgsXG4gICAgICAgICAgICAgICAgdmVydERpZmYgPSBjb250YWluZXJIZWlnaHQgLSBjb250ZW50SGVpZ2h0O1xuXG4gICAgICAgICAgICBpZiAoaG9yRGlmZiA8IDApIHtcbiAgICAgICAgICAgICAgICBsaWdodEJveENvbnRlbnRFbGVtZW50LnN0eWxlLndpZHRoID0gY29udGFpbmVyV2lkdGggLSBob3JNYXJnaW4gKyAncHgnO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICBsaWdodEJveENvbnRlbnRFbGVtZW50LnN0eWxlLmxlZnQgPSBNYXRoLnJvdW5kKGhvckRpZmYgLyAyKSArICdweCc7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGlmICh2ZXJ0RGlmZiA8IDApIHtcbiAgICAgICAgICAgICAgICBsaWdodEJveENvbnRlbnRFbGVtZW50LnN0eWxlLmhlaWdodCA9IGNvbnRhaW5lckhlaWdodCAtIHZlcnRNYXJnaW4gKyAncHgnO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICBsaWdodEJveENvbnRlbnRFbGVtZW50LnN0eWxlLnRvcCA9IE1hdGgucm91bmQodmVydERpZmYgLyAyKSArICdweCc7XG4gICAgICAgICAgICB9XG4gICAgICAgIH07XG5cbiAgICAgICAgaWYgKG9wdGlvbnMud2lkdGggJiYgb3B0aW9ucy5oZWlnaHQpIHtcbiAgICAgICAgICAgIGxpZ2h0Qm94UmVzaXplID0gSGVscGVycy5vbmNlKGxpZ2h0Qm94UmVzaXplLmJpbmQodGhpcykpO1xuICAgICAgICB9XG5cbiAgICAgICAgZnVuY3Rpb24gb3V0ZXJXaWR0aChlbCkge1xuICAgICAgICAgICAgdmFyIHdpZHRoID0gZWwub2Zmc2V0V2lkdGg7XG4gICAgICAgICAgICB2YXIgc3R5bGUgPSBnZXRDb21wdXRlZFN0eWxlKGVsKTtcblxuICAgICAgICAgICAgd2lkdGggKz0gcGFyc2VJbnQoc3R5bGUubWFyZ2luTGVmdCkgKyBwYXJzZUludChzdHlsZS5tYXJnaW5SaWdodCk7XG4gICAgICAgICAgICByZXR1cm4gd2lkdGg7XG4gICAgICAgIH1cblxuICAgICAgICBmdW5jdGlvbiBvdXRlckhlaWdodChlbCkge1xuICAgICAgICAgICAgdmFyIGhlaWdodCA9IGVsLm9mZnNldEhlaWdodDtcbiAgICAgICAgICAgIHZhciBzdHlsZSA9IGdldENvbXB1dGVkU3R5bGUoZWwpO1xuXG4gICAgICAgICAgICBoZWlnaHQgKz0gcGFyc2VJbnQoc3R5bGUubWFyZ2luVG9wKSArIHBhcnNlSW50KHN0eWxlLm1hcmdpbkJvdHRvbSk7XG4gICAgICAgICAgICByZXR1cm4gaGVpZ2h0O1xuICAgICAgICB9XG5cbiAgICAgICAgdmFyIGJvZHlTdHlsZXM7XG4gICAgICAgIHZhciBoaWRlU2Nyb2xsYmFyID0gKGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIGJvZHlTdHlsZXMgPSBIZWxwZXJzLnppcE9iamVjdChbJ292ZXJmbG93JywgJ3BhZGRpbmdSaWdodCddLm1hcChmdW5jdGlvbiAoa2V5KSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIFtrZXksIGdldENvbXB1dGVkU3R5bGUoYm9keUVsZW1lbnQpW2tleV1dO1xuICAgICAgICAgICAgfSkpO1xuXG4gICAgICAgICAgICB2YXIgYm9keVBhZCA9IHBhcnNlSW50KChnZXRDb21wdXRlZFN0eWxlKGJvZHlFbGVtZW50KVsncGFkZGluZ1JpZ2h0J10gfHwgMCksIDEwKTtcbiAgICAgICAgICAgIGJvZHlFbGVtZW50LnN0eWxlLm92ZXJmbG93ID0gJ2hpZGRlbic7XG4gICAgICAgICAgICBib2R5RWxlbWVudC5zdHlsZS5wYWRkaW5nUmlnaHQgPSB3aXRoRGVmYXVsdFBYVW5pdChib2R5UGFkICsgdGhpcy5tZWFzdXJlU2Nyb2xsYmFyKCkpO1xuICAgICAgICB9KS5iaW5kKHRoaXMpO1xuXG4gICAgICAgIHZhciByZXNldFNjcm9sbGJhciA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIGlmIChib2R5U3R5bGVzKSB7XG4gICAgICAgICAgICAgICAgT2JqZWN0LmtleXMoYm9keVN0eWxlcykuZm9yRWFjaChmdW5jdGlvbihrZXkpIHtcbiAgICAgICAgICAgICAgICAgICAgYm9keUVsZW1lbnQuc3R5bGVba2V5XSA9IGJvZHlTdHlsZXNba2V5XTtcbiAgICAgICAgICAgICAgICB9KVxuICAgICAgICAgICAgfVxuICAgICAgICB9O1xuXG4gICAgICAgIHZhciBzaG93U3Bpbm5lciA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIGxpZ2h0Qm94U3Bpbm5lckVsZW1lbnQuc3R5bGUuZGlzcGxheSA9ICdibG9jayc7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ZyYW1lV2luZG93KTtcbiAgICAgICAgaWYgKG9wdGlvbnMud2lkdGggJiYgb3B0aW9ucy5oZWlnaHQpIHtcbiAgICAgICAgICAgIHRoaXMubWVzc2FnZS5vbignZGltZW5zaW9ucycsIChmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgbGlnaHRCb3hSZXNpemUoKTtcbiAgICAgICAgICAgICAgICBzaG93Q29udGVudCgpO1xuICAgICAgICAgICAgfSkpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgdGhpcy5tZXNzYWdlLm9uKCdkaW1lbnNpb25zJywgKGZ1bmN0aW9uIChldmVudCkge1xuICAgICAgICAgICAgICAgIHZhciBkYXRhID0gZXZlbnQuZGV0YWlsO1xuICAgICAgICAgICAgICAgIGlmIChkYXRhLmRpbWVuc2lvbnMpIHtcbiAgICAgICAgICAgICAgICAgICAgcHNEaW1lbnNpb25zID0gSGVscGVycy56aXBPYmplY3QoWyd3aWR0aCcsICdoZWlnaHQnXS5tYXAoZnVuY3Rpb24gKGRpbSkge1xuICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIFtkaW0sIE1hdGgubWF4KE1JTl9QU19ESU1FTlNJT05TW2RpbV0gfHwgMCwgZGF0YS5kaW1lbnNpb25zW2RpbV0gfHwgMCkgKyAncHgnXTtcbiAgICAgICAgICAgICAgICAgICAgfSkpO1xuXG4gICAgICAgICAgICAgICAgICAgIGxpZ2h0Qm94UmVzaXplKCk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIHNob3dDb250ZW50KCk7XG4gICAgICAgICAgICB9KSk7XG4gICAgICAgIH1cbiAgICAgICAgdGhpcy5tZXNzYWdlLm9uKCd3aWRnZXQtZGV0ZWN0aW9uJywgKGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHRoaXMubWVzc2FnZS5zZW5kKCd3aWRnZXQtZGV0ZWN0ZWQnLCB7dmVyc2lvbjogdmVyc2lvbiwgbGlnaHRCb3h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9seWZpbGxzLmFwcGx5UG9seWZpbGxzKCk7XG5cbnZhciBpbnN0YW5jZTtcblxubW9kdWxlLmV4cG9ydHMgPSAoZnVuY3Rpb24gKCkge1xuICAgIHZhciBnZXRJbnN0YW5jZSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgaWYgKCFpbnN0YW5jZSkge1xuICAgICAgICAgICAgaW5zdGFuY2UgPSBuZXcgQXBwKCk7XG4gICAgICAgIH1cbiAgICAgICAgcmV0dXJuIGluc3RhbmNlO1xuICAgIH07XG5cbiAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihIZWxwZXJzLnppcE9iamVjdChbJ2luaXQnLCAnb3BlbicsICdjbG9zZScsICdvbicsICdvZmYnLCAnc2VuZE1lc3NhZ2UnLCAnb25NZXNzYWdlJ10ubWFwKGZ1bmN0aW9uIChtZXRob2ROYW1lKSB7XG4gICAgICAgIHZhciBhcHAgPSBnZXRJbnN0YW5jZSgpO1xuICAgICAgICByZXR1cm4gW21ldGhvZE5hbWUsIGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHJldHVybiBhcHBbbWV0aG9kTmFtZV0uYXBwbHkoYXBwLCBhcmd1bWVudHMpO1xuICAgICAgICB9XTtcbiAgICB9KSksIHtcbiAgICAgICAgZXZlbnRUeXBlczogQXBwLmV2ZW50VHlwZXMsXG4gICAgfSk7XG59KSgpO1xuIl19 + \ No newline at end of file diff --git a/public/assets/games/bobble/screenfull.js b/public/assets/games/bobble/screenfull.js new file mode 100644 index 00000000..b6fccee0 --- /dev/null +++ b/public/assets/games/bobble/screenfull.js @@ -0,0 +1,184 @@ +/*! +* screenfull +* v5.1.0 - 2020-12-24 +* (c) Sindre Sorhus; MIT License +*/ +(function () { + 'use strict'; + + var document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {}; + var isCommonjs = typeof module !== 'undefined' && module.exports; + + var fn = (function () { + var val; + + var fnMap = [ + [ + 'requestFullscreen', + 'exitFullscreen', + 'fullscreenElement', + 'fullscreenEnabled', + 'fullscreenchange', + 'fullscreenerror' + ], + // New WebKit + [ + 'webkitRequestFullscreen', + 'webkitExitFullscreen', + 'webkitFullscreenElement', + 'webkitFullscreenEnabled', + 'webkitfullscreenchange', + 'webkitfullscreenerror' + + ], + // Old WebKit + [ + 'webkitRequestFullScreen', + 'webkitCancelFullScreen', + 'webkitCurrentFullScreenElement', + 'webkitCancelFullScreen', + 'webkitfullscreenchange', + 'webkitfullscreenerror' + + ], + [ + 'mozRequestFullScreen', + 'mozCancelFullScreen', + 'mozFullScreenElement', + 'mozFullScreenEnabled', + 'mozfullscreenchange', + 'mozfullscreenerror' + ], + [ + 'msRequestFullscreen', + 'msExitFullscreen', + 'msFullscreenElement', + 'msFullscreenEnabled', + 'MSFullscreenChange', + 'MSFullscreenError' + ] + ]; + + var i = 0; + var l = fnMap.length; + var ret = {}; + + for (; i < l; i++) { + val = fnMap[i]; + if (val && val[1] in document) { + for (i = 0; i < val.length; i++) { + ret[fnMap[0][i]] = val[i]; + } + return ret; + } + } + + return false; + })(); + + var eventNameMap = { + change: fn.fullscreenchange, + error: fn.fullscreenerror + }; + + var screenfull = { + request: function (element, options) { + return new Promise(function (resolve, reject) { + var onFullScreenEntered = function () { + this.off('change', onFullScreenEntered); + resolve(); + }.bind(this); + + this.on('change', onFullScreenEntered); + + element = element || document.documentElement; + + var returnPromise = element[fn.requestFullscreen](options); + + if (returnPromise instanceof Promise) { + returnPromise.then(onFullScreenEntered).catch(reject); + } + }.bind(this)); + }, + exit: function () { + return new Promise(function (resolve, reject) { + if (!this.isFullscreen) { + resolve(); + return; + } + + var onFullScreenExit = function () { + this.off('change', onFullScreenExit); + resolve(); + }.bind(this); + + this.on('change', onFullScreenExit); + + var returnPromise = document[fn.exitFullscreen](); + + if (returnPromise instanceof Promise) { + returnPromise.then(onFullScreenExit).catch(reject); + } + }.bind(this)); + }, + toggle: function (element, options) { + return this.isFullscreen ? this.exit() : this.request(element, options); + }, + onchange: function (callback) { + this.on('change', callback); + }, + onerror: function (callback) { + this.on('error', callback); + }, + on: function (event, callback) { + var eventName = eventNameMap[event]; + if (eventName) { + document.addEventListener(eventName, callback, false); + } + }, + off: function (event, callback) { + var eventName = eventNameMap[event]; + if (eventName) { + document.removeEventListener(eventName, callback, false); + } + }, + raw: fn + }; + + if (!fn) { + if (isCommonjs) { + module.exports = {isEnabled: false}; + } else { + window.screenfull = {isEnabled: false}; + } + + return; + } + + Object.defineProperties(screenfull, { + isFullscreen: { + get: function () { + return Boolean(document[fn.fullscreenElement]); + } + }, + element: { + enumerable: true, + get: function () { + return document[fn.fullscreenElement]; + } + }, + isEnabled: { + enumerable: true, + get: function () { + // Coerce to boolean in case of old WebKit + return Boolean(document[fn.fullscreenEnabled]); + } + } + }); + + if (isCommonjs) { + module.exports = screenfull; + } else { + window.screenfull = screenfull; + } +})(); diff --git a/public/assets/games/bobble/winterpixel_discord.js b/public/assets/games/bobble/winterpixel_discord.js new file mode 100644 index 00000000..9cfa3af2 --- /dev/null +++ b/public/assets/games/bobble/winterpixel_discord.js @@ -0,0 +1,12976 @@ +var DiscordSDK = (function (exports) { + 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + var eventemitter3 = {exports: {}}; + + (function (module) { + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + { + module.exports = EventEmitter; + } + } (eventemitter3)); + + var eventemitter3Exports = eventemitter3.exports; + var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports); + + var util; + (function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util || (util = {})); + var objectUtil; + (function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; + })(objectUtil || (objectUtil = {})); + const ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", + ]); + const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + + const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", + ]); + const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); + }; + class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + } + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; + + const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; + }; + + let overrideErrorMap = errorMap; + function setErrorMap(map) { + overrideErrorMap = map; + } + function getErrorMap() { + return overrideErrorMap; + } + + const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; + }; + const EMPTY_PATH = []; + function addIssueToContext(ctx, issueData) { + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); + } + class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + } + const INVALID = Object.freeze({ + status: "aborted", + }); + const DIRTY = (value) => ({ status: "dirty", value }); + const OK = (value) => ({ status: "valid", value }); + const isAborted = (x) => x.status === "aborted"; + const isDirty = (x) => x.status === "dirty"; + const isValid = (x) => x.status === "valid"; + const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + + var errorUtil; + (function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; + })(errorUtil || (errorUtil = {})); + + class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + } + const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } + }; + function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + class ZodType { + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } + } + const cuidRegex = /^c[^\s-]{8,}$/i; + const cuid2Regex = /^[a-z][a-z0-9]*$/; + const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; + // const uuidRegex = + // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; + const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + // from https://stackoverflow.com/a/46181/1550155 + // old version: too slow, didn't support unicode + // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; + //old email regex + // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; + // eslint-disable-next-line + // const emailRegex = + // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; + // const emailRegex = + // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + // const emailRegex = + // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; + const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + // const emailRegex = + // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; + // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression + const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + let emojiRegex; + const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; + const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; + // Adapted from https://stackoverflow.com/a/3143231 + const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } + }; + function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; + } + class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + } + // + ); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); + } + class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + } + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + } + ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); + }; + class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); + }; + class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + } + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; + class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; + class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; + class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; + class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; + class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + } + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; + class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + } + ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; + class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + } + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; + class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; + function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } + } + class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } + } + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); + }; + class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } + } + ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + ////////// ////////// + ////////// ZodDiscriminatedUnion ////////// + ////////// ////////// + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return Object.keys(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else { + return null; + } + }; + class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } + } + function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && + bType === ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } + } + class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } + } + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; + class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } + } + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; + class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } + } + class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + } + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; + class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + } + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; + class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap, + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } + } + class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + } + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; + class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + } + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; + function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); + } + class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } + } + ZodEnum.create = createZodEnum; + class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + } + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; + class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && + ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } + } + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; + class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; + } + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); + } + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc + // effect: RefinementEffect + ) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + util.assertNever(effect); + } + } + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; + class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); + }; + class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); + }; + class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } + } + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); + }; + class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } + } + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; + class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + } + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; + const BRAND = Symbol("zod_brand"); + class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } + } + class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } + } + class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } + } + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); + }; + const custom = (check, params = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); + }; + const late = { + object: ZodObject.lazycreate, + }; + var ZodFirstPartyTypeKind; + (function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + const instanceOfType = ( + // const instanceOfType = any>( + cls, params = { + message: `Input not instance of ${cls.name}`, + }) => custom((data) => data instanceof cls, params); + const stringType = ZodString.create; + const numberType = ZodNumber.create; + const nanType = ZodNaN.create; + const bigIntType = ZodBigInt.create; + const booleanType = ZodBoolean.create; + const dateType = ZodDate.create; + const symbolType = ZodSymbol.create; + const undefinedType = ZodUndefined.create; + const nullType = ZodNull.create; + const anyType = ZodAny.create; + const unknownType = ZodUnknown.create; + const neverType = ZodNever.create; + const voidType = ZodVoid.create; + const arrayType = ZodArray.create; + const objectType = ZodObject.create; + const strictObjectType = ZodObject.strictCreate; + const unionType = ZodUnion.create; + const discriminatedUnionType = ZodDiscriminatedUnion.create; + const intersectionType = ZodIntersection.create; + const tupleType = ZodTuple.create; + const recordType = ZodRecord.create; + const mapType = ZodMap.create; + const setType = ZodSet.create; + const functionType = ZodFunction.create; + const lazyType = ZodLazy.create; + const literalType = ZodLiteral.create; + const enumType = ZodEnum.create; + const nativeEnumType = ZodNativeEnum.create; + const promiseType = ZodPromise.create; + const effectsType = ZodEffects.create; + const optionalType = ZodOptional.create; + const nullableType = ZodNullable.create; + const preprocessType = ZodEffects.createWithPreprocess; + const pipelineType = ZodPipeline.create; + const ostring = () => stringType().optional(); + const onumber = () => numberType().optional(); + const oboolean = () => booleanType().optional(); + const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), + }; + const NEVER = INVALID; + + var z = /*#__PURE__*/Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap: setErrorMap, + getErrorMap: getErrorMap, + makeIssue: makeIssue, + EMPTY_PATH: EMPTY_PATH, + addIssueToContext: addIssueToContext, + ParseStatus: ParseStatus, + INVALID: INVALID, + DIRTY: DIRTY, + OK: OK, + isAborted: isAborted, + isDirty: isDirty, + isValid: isValid, + isAsync: isAsync, + get util () { return util; }, + get objectUtil () { return objectUtil; }, + ZodParsedType: ZodParsedType, + getParsedType: getParsedType, + ZodType: ZodType, + ZodString: ZodString, + ZodNumber: ZodNumber, + ZodBigInt: ZodBigInt, + ZodBoolean: ZodBoolean, + ZodDate: ZodDate, + ZodSymbol: ZodSymbol, + ZodUndefined: ZodUndefined, + ZodNull: ZodNull, + ZodAny: ZodAny, + ZodUnknown: ZodUnknown, + ZodNever: ZodNever, + ZodVoid: ZodVoid, + ZodArray: ZodArray, + ZodObject: ZodObject, + ZodUnion: ZodUnion, + ZodDiscriminatedUnion: ZodDiscriminatedUnion, + ZodIntersection: ZodIntersection, + ZodTuple: ZodTuple, + ZodRecord: ZodRecord, + ZodMap: ZodMap, + ZodSet: ZodSet, + ZodFunction: ZodFunction, + ZodLazy: ZodLazy, + ZodLiteral: ZodLiteral, + ZodEnum: ZodEnum, + ZodNativeEnum: ZodNativeEnum, + ZodPromise: ZodPromise, + ZodEffects: ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional: ZodOptional, + ZodNullable: ZodNullable, + ZodDefault: ZodDefault, + ZodCatch: ZodCatch, + ZodNaN: ZodNaN, + BRAND: BRAND, + ZodBranded: ZodBranded, + ZodPipeline: ZodPipeline, + ZodReadonly: ZodReadonly, + custom: custom, + Schema: ZodType, + ZodSchema: ZodType, + late: late, + get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, + coerce: coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + 'enum': enumType, + 'function': functionType, + 'instanceof': instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + 'null': nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean: oboolean, + onumber: onumber, + optional: optionalType, + ostring: ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + 'undefined': undefinedType, + union: unionType, + unknown: unknownType, + 'void': voidType, + NEVER: NEVER, + ZodIssueCode: ZodIssueCode, + quotelessJson: quotelessJson, + ZodError: ZodError + }); + + var BigInteger = {exports: {}}; + + (function (module) { + var bigInt = (function (undefined$1) { + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + }; + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + }; + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + }; + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + }; + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + }; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + }; + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + }; + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var t = iterations === undefined$1 ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + }; + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + }; + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < top) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix !== 10) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix != 10) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }; + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + }; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; + })(); + + // Node.js check + if (module.hasOwnProperty("exports")) { + module.exports = bigInt; + } + } (BigInteger)); + + var BigIntegerExports = BigInteger.exports; + var bigInt = /*@__PURE__*/getDefaultExportFromCjs(BigIntegerExports); + + /** + * Context: Due to Discord supporting more than 32 permissions, permission calculation has become more complicated than naive + * bit operations on `number`s. To support this generically, we have created BigFlagUtils to work with bit-flags greater + * than 32-bits in size. + * + * Ideally, we would like to use BigInt, which is pretty efficient, but some JavaScript engines do not support it. + * + * This file is intended to be a set of lower-level operators that act directly on "BigFlags". + * + * If you're working with permissions, in most cases you can probably use PermissionUtils. + */ + const MAX_BIG_INT = 64; + const SMALL_INT = 16; + const PARTS = MAX_BIG_INT / SMALL_INT; + function checkBrowserSupportsBigInt() { + try { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions + BigInt; + return true; + } + catch (e) { + return false; + } + } + /** + * Takes the sliced output of `toHexReverseArray` and converts hex to decimal. + */ + function fromHexReverseArray(hexValues, start, size) { + let value = 0; + for (let i = 0; i < size; i++) { + const byte = hexValues[start + i]; + if (byte === undefined) { + break; + } + value += byte * 16 ** i; + } + return value; + } + /** + * Converts a number string to array of hex bytes based on the implementation found at + * https://stackoverflow.com/questions/18626844/convert-a-large-integer-to-a-hex-string-in-javascript + * + * To avoid extra allocations it returns the values in reverse. + */ + function toHexReverseArray(value) { + const sum = []; + for (let i = 0; i < value.length; i++) { + let s = Number(value[i]); + for (let j = 0; s || j < sum.length; j++) { + s += (sum[j] || 0) * 10; + sum[j] = s % 16; + s = (s - sum[j]) / 16; + } + } + return sum; + } + /** + * Splits a big integers into array of small integers to perform fast bitwise operations. + */ + function splitBigInt(value) { + const sum = toHexReverseArray(value); + const parts = Array(PARTS); + for (let i = 0; i < PARTS; i++) { + // Highest bits to lowest bits. + parts[PARTS - 1 - i] = fromHexReverseArray(sum, i * PARTS, PARTS); + } + return parts; + } + class HighLow { + static fromString(value) { + return new HighLow(splitBigInt(value), value); + } + static fromBit(index) { + const parts = Array(PARTS); + const offset = Math.floor(index / SMALL_INT); + for (let i = 0; i < PARTS; i++) { + // Highest bits to lowest bits. + parts[PARTS - 1 - i] = i === offset ? 1 << (index - offset * SMALL_INT) : 0; + } + return new HighLow(parts); + } + constructor(parts, str) { + this.parts = parts; + this.str = str; + } + and({ parts }) { + return new HighLow(this.parts.map((v, i) => v & parts[i])); + } + or({ parts }) { + return new HighLow(this.parts.map((v, i) => v | parts[i])); + } + xor({ parts }) { + return new HighLow(this.parts.map((v, i) => v ^ parts[i])); + } + not() { + return new HighLow(this.parts.map((v) => ~v)); + } + equals({ parts }) { + return this.parts.every((v, i) => v === parts[i]); + } + /** + * For the average case the string representation is provided, but + * when we need to convert high and low to string we just let the + * slower big-integer library do it. + */ + toString() { + if (this.str != null) { + return this.str; + } + const array = new Array(MAX_BIG_INT / 4); + this.parts.forEach((value, offset) => { + const hex = toHexReverseArray(value.toString()); + for (let i = 0; i < 4; i++) { + array[i + offset * 4] = hex[4 - 1 - i] || 0; + } + }); + return (this.str = bigInt.fromArray(array, 16).toString()); + } + toJSON() { + return this.toString(); + } + } + const SUPPORTS_BIGINT = checkBrowserSupportsBigInt(); + // Polyfill toJSON on BigInt if necessary. + if (SUPPORTS_BIGINT && BigInt.prototype.toJSON == null) { + BigInt.prototype.toJSON = function () { + return this.toString(); + }; + } + const HIGH_LOW_CACHE = {}; + const convertToBigFlag = SUPPORTS_BIGINT + ? function convertToBigFlagBigInt(value) { + return BigInt(value); + } + : function convertToBigFlagHighLow(value) { + if (value instanceof HighLow) { + return value; + } + if (typeof value === 'number') { + value = value.toString(); + } + // These type assertions are ugly, but there doesn't seem to be a + // runtime costless way to do a type assertion above. + if (HIGH_LOW_CACHE[value] != null) { + return HIGH_LOW_CACHE[value]; + } + HIGH_LOW_CACHE[value] = HighLow.fromString(value); + return HIGH_LOW_CACHE[value]; + }; + const EMPTY_FLAG = convertToBigFlag(0); + const flagAnd = SUPPORTS_BIGINT + ? function flagAndBigInt(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first & second; + } + : function flagAndHighLow(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first.and(second); + }; + const flagOr = SUPPORTS_BIGINT + ? function flagOrBigInt(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first | second; + } + : function flagOrHighLow(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first.or(second); + }; + const flagXor = SUPPORTS_BIGINT + ? function flagXorBigInt(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first ^ second; + } + : function flagXorHighLow(first = EMPTY_FLAG, second = EMPTY_FLAG) { + return first.xor(second); + }; + const flagNot = SUPPORTS_BIGINT + ? function flagNotBigInt(first = EMPTY_FLAG) { + return ~first; + } + : function flagNotHighLow(first = EMPTY_FLAG) { + return first.not(); + }; + const flagEquals = SUPPORTS_BIGINT + ? function flagEqualsBigInt(first, second) { + return first === second; + } + : function flagEqualsHighLow(first, second) { + if (first == null || second == null) { + // eslint-disable-next-line eqeqeq + return first == second; + } + return first.equals(second); + }; + function flagOrMultiple(...flags) { + let result = flags[0]; + for (let i = 1; i < flags.length; i++) { + result = flagOr(result, flags[i]); + } + return result; + } + function flagHas(base, flag) { + return flagEquals(flagAnd(base, flag), flag); + } + function flagHasAny(base, flag) { + return !flagEquals(flagAnd(base, flag), EMPTY_FLAG); + } + function flagAdd(base, flag) { + return flag === EMPTY_FLAG ? base : flagOr(base, flag); + } + function flagRemove(base, flag) { + return flag === EMPTY_FLAG ? base : flagXor(base, flagAnd(base, flag)); + } + const getFlag = SUPPORTS_BIGINT + ? function getFlagBigInt(index) { + return BigInt(1) << BigInt(index); + } + : function getFlagHighLow(index) { + return HighLow.fromBit(index); + }; + var BigFlagUtils = { + combine: flagOrMultiple, + add: flagAdd, + remove: flagRemove, + filter: flagAnd, + invert: flagNot, + has: flagHas, + hasAny: flagHasAny, + equals: flagEquals, + deserialize: convertToBigFlag, + getFlag: getFlag, + }; + + exports.RPCCloseCodes = void 0; + (function (RPCCloseCodes) { + RPCCloseCodes[RPCCloseCodes["CLOSE_NORMAL"] = 1000] = "CLOSE_NORMAL"; + RPCCloseCodes[RPCCloseCodes["CLOSE_UNSUPPORTED"] = 1003] = "CLOSE_UNSUPPORTED"; + RPCCloseCodes[RPCCloseCodes["CLOSE_ABNORMAL"] = 1006] = "CLOSE_ABNORMAL"; + RPCCloseCodes[RPCCloseCodes["INVALID_CLIENTID"] = 4000] = "INVALID_CLIENTID"; + RPCCloseCodes[RPCCloseCodes["INVALID_ORIGIN"] = 4001] = "INVALID_ORIGIN"; + RPCCloseCodes[RPCCloseCodes["RATELIMITED"] = 4002] = "RATELIMITED"; + RPCCloseCodes[RPCCloseCodes["TOKEN_REVOKED"] = 4003] = "TOKEN_REVOKED"; + RPCCloseCodes[RPCCloseCodes["INVALID_VERSION"] = 4004] = "INVALID_VERSION"; + RPCCloseCodes[RPCCloseCodes["INVALID_ENCODING"] = 4005] = "INVALID_ENCODING"; + })(exports.RPCCloseCodes || (exports.RPCCloseCodes = {})); + exports.RPCErrorCodes = void 0; + (function (RPCErrorCodes) { + RPCErrorCodes[RPCErrorCodes["INVALID_PAYLOAD"] = 4000] = "INVALID_PAYLOAD"; + RPCErrorCodes[RPCErrorCodes["INVALID_COMMAND"] = 4002] = "INVALID_COMMAND"; + RPCErrorCodes[RPCErrorCodes["INVALID_EVENT"] = 4004] = "INVALID_EVENT"; + RPCErrorCodes[RPCErrorCodes["INVALID_PERMISSIONS"] = 4006] = "INVALID_PERMISSIONS"; + })(exports.RPCErrorCodes || (exports.RPCErrorCodes = {})); + /** + * @deprecated use OrientationTypeObject instead + */ + exports.Orientation = void 0; + (function (Orientation) { + Orientation["LANDSCAPE"] = "landscape"; + Orientation["PORTRAIT"] = "portrait"; + })(exports.Orientation || (exports.Orientation = {})); + exports.Platform = void 0; + (function (Platform) { + Platform["MOBILE"] = "mobile"; + Platform["DESKTOP"] = "desktop"; + })(exports.Platform || (exports.Platform = {})); + const Permissions = Object.freeze({ + CREATE_INSTANT_INVITE: BigFlagUtils.getFlag(0), + ADMINISTRATOR: BigFlagUtils.getFlag(3), + }); + + /** + * This is a helper function which coerces an unsupported arg value to the key/value UNHANDLED: -1 + * This is necessary to handle a scenario where a new enum value is added in the Discord Client, + * so that the sdk will not throw an error when given a (newly) valid enum value. + * + * To remove the requirement for consumers of this sdk to import an enum when parsing data, + * we instead use an object cast as const (readonly). This maintains parity with the previous + * schema (which used zod.enum), and behaves more like a union type, i.e. 'foo' | 'bar' | -1 + * + * @param inputObject This object must include the key/value pair UNHANDLED = -1 + */ + function zodCoerceUnhandledValue(inputObject) { + return preprocessType((arg) => { + var _a; + const [objectKey] = (_a = Object.entries(inputObject).find(([, value]) => value === arg)) !== null && _a !== void 0 ? _a : []; + if (arg != null && objectKey === undefined) { + return inputObject.UNHANDLED; + } + return arg; + }, stringType().or(numberType())); + } + /** + * Fallback to the default zod value if parsing fails. + */ + function fallbackToDefault(schema) { + const transform = custom().transform((data) => { + const res = schema.safeParse(data); + if (res.success) { + return res.data; + } + return schema._def.defaultValue(); + }); + // Must set this inner schema so inspection works correctly + transform.overlayType = schema; + // transform._def.schema = schema; + return transform; + } + + /** + * This file is generated. + * Run "pnpm sync" to regenerate file. + * @generated + */ + // INITIATE_IMAGE_UPLOAD + const InitiateImageUploadResponseSchema = z.object({ image_url: z.string() }); + // OPEN_SHARE_MOMENT_DIALOG + const OpenShareMomentDialogRequestSchema = z.object({ mediaUrl: z.string().max(1024) }); + // AUTHENTICATE + const AuthenticateRequestSchema = z.object({ access_token: z.union([z.string(), z.null()]).optional() }); + const AuthenticateResponseSchema = z.object({ + access_token: z.string(), + user: z.object({ + username: z.string(), + discriminator: z.string(), + id: z.string(), + avatar: z.union([z.string(), z.null()]).optional(), + public_flags: z.number(), + global_name: z.union([z.string(), z.null()]).optional(), + }), + scopes: z.array(fallbackToDefault(z + .enum([ + 'identify', + 'email', + 'connections', + 'guilds', + 'guilds.join', + 'guilds.members.read', + 'gdm.join', + 'rpc', + 'rpc.notifications.read', + 'rpc.voice.read', + 'rpc.voice.write', + 'rpc.video.read', + 'rpc.video.write', + 'rpc.screenshare.read', + 'rpc.screenshare.write', + 'rpc.activities.write', + 'bot', + 'webhook.incoming', + 'messages.read', + 'applications.builds.upload', + 'applications.builds.read', + 'applications.commands', + 'applications.commands.update', + 'applications.commands.permissions.update', + 'applications.store.update', + 'applications.entitlements', + 'activities.read', + 'activities.write', + 'relationships.read', + 'voice', + 'dm_channels.read', + 'role_connections.write', + ]) + .or(z.literal(-1)) + .default(-1))), + expires: z.string(), + application: z.object({ + description: z.string(), + icon: z.union([z.string(), z.null()]).optional(), + id: z.string(), + rpc_origins: z.array(z.string()).optional(), + name: z.string(), + }), + }); + // GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS + const GetActivityInstanceConnectedParticipantsResponseSchema = z.object({ + participants: z.array(z.object({ + id: z.string(), + username: z.string(), + global_name: z.union([z.string(), z.null()]).optional(), + discriminator: z.string(), + avatar: z.union([z.string(), z.null()]).optional(), + flags: z.number(), + bot: z.boolean(), + avatar_decoration_data: z + .union([z.object({ asset: z.string(), skuId: z.string().optional() }), z.null()]) + .optional(), + premium_type: z.union([z.number(), z.null()]).optional(), + nickname: z.string().optional(), + })), + }); + /** + * RPC Commands which support schemas. + */ + var Command; + (function (Command) { + Command["INITIATE_IMAGE_UPLOAD"] = "INITIATE_IMAGE_UPLOAD"; + Command["OPEN_SHARE_MOMENT_DIALOG"] = "OPEN_SHARE_MOMENT_DIALOG"; + Command["AUTHENTICATE"] = "AUTHENTICATE"; + Command["GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS"] = "GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS"; + })(Command || (Command = {})); + const emptyResponseSchema = z.object({}).optional().nullable(); + const emptyRequestSchema = z.void(); + /** + * Request & Response schemas for each supported RPC Command. + */ + const Schemas = { + [Command.INITIATE_IMAGE_UPLOAD]: { + request: emptyRequestSchema, + response: InitiateImageUploadResponseSchema, + }, + [Command.OPEN_SHARE_MOMENT_DIALOG]: { + request: OpenShareMomentDialogRequestSchema, + response: emptyResponseSchema, + }, + [Command.AUTHENTICATE]: { + request: AuthenticateRequestSchema, + response: AuthenticateResponseSchema, + }, + [Command.GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS]: { + request: emptyRequestSchema, + response: GetActivityInstanceConnectedParticipantsResponseSchema, + }, + }; + + // DISPATCH is sent as cmd but is a special case, so is excluded from Commands enum + const DISPATCH = 'DISPATCH'; + var Commands$1; + (function (Commands) { + Commands["AUTHORIZE"] = "AUTHORIZE"; + Commands["AUTHENTICATE"] = "AUTHENTICATE"; + Commands["GET_GUILDS"] = "GET_GUILDS"; + Commands["GET_GUILD"] = "GET_GUILD"; + Commands["GET_CHANNEL"] = "GET_CHANNEL"; + Commands["GET_CHANNELS"] = "GET_CHANNELS"; + Commands["SELECT_VOICE_CHANNEL"] = "SELECT_VOICE_CHANNEL"; + Commands["SELECT_TEXT_CHANNEL"] = "SELECT_TEXT_CHANNEL"; + Commands["SUBSCRIBE"] = "SUBSCRIBE"; + Commands["UNSUBSCRIBE"] = "UNSUBSCRIBE"; + Commands["CAPTURE_SHORTCUT"] = "CAPTURE_SHORTCUT"; + Commands["SET_CERTIFIED_DEVICES"] = "SET_CERTIFIED_DEVICES"; + Commands["SET_ACTIVITY"] = "SET_ACTIVITY"; + Commands["GET_SKUS"] = "GET_SKUS"; + Commands["GET_ENTITLEMENTS"] = "GET_ENTITLEMENTS"; + Commands["GET_SKUS_EMBEDDED"] = "GET_SKUS_EMBEDDED"; + Commands["GET_ENTITLEMENTS_EMBEDDED"] = "GET_ENTITLEMENTS_EMBEDDED"; + Commands["START_PURCHASE"] = "START_PURCHASE"; + Commands["SET_CONFIG"] = "SET_CONFIG"; + Commands["SEND_ANALYTICS_EVENT"] = "SEND_ANALYTICS_EVENT"; + Commands["USER_SETTINGS_GET_LOCALE"] = "USER_SETTINGS_GET_LOCALE"; + Commands["OPEN_EXTERNAL_LINK"] = "OPEN_EXTERNAL_LINK"; + Commands["ENCOURAGE_HW_ACCELERATION"] = "ENCOURAGE_HW_ACCELERATION"; + Commands["CAPTURE_LOG"] = "CAPTURE_LOG"; + Commands["SET_ORIENTATION_LOCK_STATE"] = "SET_ORIENTATION_LOCK_STATE"; + Commands["OPEN_INVITE_DIALOG"] = "OPEN_INVITE_DIALOG"; + Commands["GET_PLATFORM_BEHAVIORS"] = "GET_PLATFORM_BEHAVIORS"; + Commands["GET_CHANNEL_PERMISSIONS"] = "GET_CHANNEL_PERMISSIONS"; + Commands["OPEN_SHARE_MOMENT_DIALOG"] = "OPEN_SHARE_MOMENT_DIALOG"; + Commands["INITIATE_IMAGE_UPLOAD"] = "INITIATE_IMAGE_UPLOAD"; + Commands["GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS"] = "GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS"; + })(Commands$1 || (Commands$1 = {})); + const ReceiveFramePayload = objectType({ + cmd: stringType(), + data: unknownType(), + evt: nullType(), + nonce: stringType(), + }) + .passthrough(); + const ScopesObject = Object.assign(Object.assign({}, AuthenticateResponseSchema.shape.scopes.element.overlayType._def.innerType.options[0].Values), { UNHANDLED: -1 }); + const Scopes = zodCoerceUnhandledValue(ScopesObject); + const User = objectType({ + id: stringType(), + username: stringType(), + discriminator: stringType(), + global_name: stringType().optional().nullable(), + avatar: stringType().optional().nullable(), + avatar_decoration_data: objectType({ + asset: stringType(), + sku_id: stringType().optional(), + }) + .nullable(), + bot: booleanType(), + flags: numberType().optional().nullable(), + premium_type: numberType().optional().nullable(), + }); + const GuildMember = objectType({ + user: User, + nick: stringType().optional().nullable(), + roles: arrayType(stringType()), + joined_at: stringType(), + deaf: booleanType(), + mute: booleanType(), + }); + const Emoji = objectType({ + id: stringType(), + name: stringType().optional().nullable(), + roles: arrayType(stringType()).optional().nullable(), + user: User.optional().nullable(), + require_colons: booleanType().optional().nullable(), + managed: booleanType().optional().nullable(), + animated: booleanType().optional().nullable(), + available: booleanType().optional().nullable(), + }); + const VoiceState = objectType({ + mute: booleanType(), + deaf: booleanType(), + self_mute: booleanType(), + self_deaf: booleanType(), + suppress: booleanType(), + }); + const UserVoiceState = objectType({ + mute: booleanType(), + nick: stringType(), + user: User, + voice_state: VoiceState, + volume: numberType(), + }); + const StatusObject = { + UNHANDLED: -1, + IDLE: 'idle', + DND: 'dnd', + ONLINE: 'online', + OFFLINE: 'offline', + }; + const Status = zodCoerceUnhandledValue(StatusObject); + const Activity = objectType({ + name: stringType(), + type: numberType(), + url: stringType().optional().nullable(), + created_at: numberType().optional().nullable(), + timestamps: objectType({ + start: numberType(), + end: numberType(), + }) + .partial() + .optional() + .nullable(), + application_id: stringType().optional().nullable(), + details: stringType().optional().nullable(), + state: stringType().optional().nullable(), + emoji: Emoji.optional().nullable(), + party: objectType({ + id: stringType().optional().nullable(), + size: arrayType(numberType()).optional().nullable(), + }) + .optional() + .nullable(), + assets: objectType({ + large_image: stringType().nullable(), + large_text: stringType().nullable(), + small_image: stringType().nullable(), + small_text: stringType().nullable(), + }) + .partial() + .optional() + .nullable(), + secrets: objectType({ + join: stringType(), + match: stringType(), + }) + .partial() + .optional() + .nullable(), + instance: booleanType().optional().nullable(), + flags: numberType().optional().nullable(), + }); + const PermissionOverwriteTypeObject = { + UNHANDLED: -1, + ROLE: 0, + MEMBER: 1, + }; + const PermissionOverwrite = objectType({ + id: stringType(), + type: zodCoerceUnhandledValue(PermissionOverwriteTypeObject), + allow: stringType(), + deny: stringType(), + }); + const ChannelTypesObject = { + UNHANDLED: -1, + DM: 1, + GROUP_DM: 3, + GUILD_TEXT: 0, + GUILD_VOICE: 2, + GUILD_CATEGORY: 4, + GUILD_ANNOUNCEMENT: 5, + GUILD_STORE: 6, + ANNOUNCEMENT_THREAD: 10, + PUBLIC_THREAD: 11, + PRIVATE_THREAD: 12, + GUILD_STAGE_VOICE: 13, + GUILD_DIRECTORY: 14, + GUILD_FORUM: 15, + }; + const Channel = objectType({ + id: stringType(), + type: zodCoerceUnhandledValue(ChannelTypesObject), + guild_id: stringType().optional().nullable(), + position: numberType().optional().nullable(), + permission_overwrites: arrayType(PermissionOverwrite).optional().nullable(), + name: stringType().optional().nullable(), + topic: stringType().optional().nullable(), + nsfw: booleanType().optional().nullable(), + last_message_id: stringType().optional().nullable(), + bitrate: numberType().optional().nullable(), + user_limit: numberType().optional().nullable(), + rate_limit_per_user: numberType().optional().nullable(), + recipients: arrayType(User).optional().nullable(), + icon: stringType().optional().nullable(), + owner_id: stringType().optional().nullable(), + application_id: stringType().optional().nullable(), + parent_id: stringType().optional().nullable(), + last_pin_timestamp: stringType().optional().nullable(), + }); + const PresenceUpdate = objectType({ + user: User, + guild_id: stringType(), + status: Status, + activities: arrayType(Activity), + client_status: objectType({ + desktop: Status, + mobile: Status, + web: Status, + }) + .partial(), + }); + const Role = objectType({ + id: stringType(), + name: stringType(), + color: numberType(), + hoist: booleanType(), + position: numberType(), + permissions: stringType(), + managed: booleanType(), + mentionable: booleanType(), + }); + const Guild = objectType({ + id: stringType(), + name: stringType(), + owner_id: stringType(), + icon: stringType().nullable(), + icon_hash: stringType().optional().nullable(), + splash: stringType().nullable(), + discovery_splash: stringType().nullable(), + owner: booleanType().optional().nullable(), + permissions: stringType().optional().nullable(), + region: stringType(), + afk_channel_id: stringType().nullable(), + afk_timeout: numberType(), + widget_enabled: booleanType().optional().nullable(), + widget_channel_id: stringType().optional().nullable(), + verification_level: numberType(), + default_message_notifications: numberType(), + explicit_content_filter: numberType(), + roles: arrayType(Role), + emojis: arrayType(Emoji), + features: arrayType(stringType()), + mfa_level: numberType(), + application_id: stringType().nullable(), + system_channel_id: stringType().nullable(), + system_channel_flags: numberType(), + rules_channel_id: stringType().nullable(), + joined_at: stringType().optional().nullable(), + large: booleanType().optional().nullable(), + unavailable: booleanType().optional().nullable(), + member_count: numberType().optional().nullable(), + voice_states: arrayType(VoiceState).optional().nullable(), + members: arrayType(GuildMember).optional().nullable(), + channels: arrayType(Channel).optional().nullable(), + presences: arrayType(PresenceUpdate).optional().nullable(), + max_presences: numberType().optional().nullable(), + max_members: numberType().optional().nullable(), + vanity_url_code: stringType().nullable(), + description: stringType().nullable(), + banner: stringType().nullable(), + premium_tier: numberType(), + premium_subscription_count: numberType().optional().nullable(), + preferred_locale: stringType(), + public_updates_channel_id: stringType().nullable(), + max_video_channel_users: numberType().optional().nullable(), + approximate_member_count: numberType().optional().nullable(), + approximate_presence_count: numberType().optional().nullable(), + }); + const ChannelMention = objectType({ + id: stringType(), + guild_id: stringType(), + type: numberType(), + name: stringType(), + }); + const Attachment = objectType({ + id: stringType(), + filename: stringType(), + size: numberType(), + url: stringType(), + proxy_url: stringType(), + height: numberType().optional().nullable(), + width: numberType().optional().nullable(), + }); + const EmbedFooter = objectType({ + text: stringType(), + icon_url: stringType().optional().nullable(), + proxy_icon_url: stringType().optional().nullable(), + }); + const Image = objectType({ + url: stringType().optional().nullable(), + proxy_url: stringType().optional().nullable(), + height: numberType().optional().nullable(), + width: numberType().optional().nullable(), + }); + const Video = Image.omit({ proxy_url: true }); + const EmbedProvider = objectType({ + name: stringType().optional().nullable(), + url: stringType().optional().nullable(), + }); + const EmbedAuthor = objectType({ + name: stringType().optional().nullable(), + url: stringType().optional().nullable(), + icon_url: stringType().optional().nullable(), + proxy_icon_url: stringType().optional().nullable(), + }); + const EmbedField = objectType({ + name: stringType(), + value: stringType(), + inline: booleanType(), + }); + const Embed = objectType({ + title: stringType().optional().nullable(), + type: stringType().optional().nullable(), + description: stringType().optional().nullable(), + url: stringType().optional().nullable(), + timestamp: stringType().optional().nullable(), + color: numberType().optional().nullable(), + footer: EmbedFooter.optional().nullable(), + image: Image.optional().nullable(), + thumbnail: Image.optional().nullable(), + video: Video.optional().nullable(), + provider: EmbedProvider.optional().nullable(), + author: EmbedAuthor.optional().nullable(), + fields: arrayType(EmbedField).optional().nullable(), + }); + const Reaction = objectType({ + count: numberType(), + me: booleanType(), + emoji: Emoji, + }); + const MessageActivity = objectType({ + type: numberType(), + party_id: stringType().optional().nullable(), + }); + const MessageApplication = objectType({ + id: stringType(), + cover_image: stringType().optional().nullable(), + description: stringType(), + icon: stringType().optional().nullable(), + name: stringType(), + }); + const MessageReference = objectType({ + message_id: stringType().optional().nullable(), + channel_id: stringType().optional().nullable(), + guild_id: stringType().optional().nullable(), + }); + const Message = objectType({ + id: stringType(), + channel_id: stringType(), + guild_id: stringType().optional().nullable(), + author: User.optional().nullable(), + member: GuildMember.optional().nullable(), + content: stringType(), + timestamp: stringType(), + edited_timestamp: stringType().optional().nullable(), + tts: booleanType(), + mention_everyone: booleanType(), + mentions: arrayType(User), + mention_roles: arrayType(stringType()), + mention_channels: arrayType(ChannelMention), + attachments: arrayType(Attachment), + embeds: arrayType(Embed), + reactions: arrayType(Reaction).optional().nullable(), + nonce: unionType([stringType(), numberType()]).optional().nullable(), + pinned: booleanType(), + webhook_id: stringType().optional().nullable(), + type: numberType(), + activity: MessageActivity.optional().nullable(), + application: MessageApplication.optional().nullable(), + message_reference: MessageReference.optional().nullable(), + flags: numberType().optional().nullable(), + stickers: arrayType(unknownType()).optional().nullable(), + // Cannot self reference, but this is possibly a Message + referenced_message: unknownType().optional().nullable(), + }); + const VoiceDevice = objectType({ + id: stringType(), + name: stringType(), + }); + const KeyTypesObject = { + UNHANDLED: -1, + KEYBOARD_KEY: 0, + MOUSE_BUTTON: 1, + KEYBOARD_MODIFIER_KEY: 2, + GAMEPAD_BUTTON: 3, + }; + const ShortcutKey = objectType({ + type: zodCoerceUnhandledValue(KeyTypesObject), + code: numberType(), + name: stringType(), + }); + const VoiceSettingModeTypeObject = { + UNHANDLED: -1, + PUSH_TO_TALK: 'PUSH_TO_TALK', + VOICE_ACTIVITY: 'VOICE_ACTIVITY', + }; + const VoiceSettingsMode = objectType({ + type: zodCoerceUnhandledValue(VoiceSettingModeTypeObject), + auto_threshold: booleanType(), + threshold: numberType(), + shortcut: arrayType(ShortcutKey), + delay: numberType(), + }); + const VoiceSettingsIO = objectType({ + device_id: stringType(), + volume: numberType(), + available_devices: arrayType(VoiceDevice), + }); + const CertifiedDeviceTypeObject = { + UNHANDLED: -1, + AUDIO_INPUT: 'AUDIO_INPUT', + AUDIO_OUTPUT: 'AUDIO_OUTPUT', + VIDEO_INPUT: 'VIDEO_INPUT', + }; + const CertifiedDevice = objectType({ + type: zodCoerceUnhandledValue(CertifiedDeviceTypeObject), + id: stringType(), + vendor: objectType({ + name: stringType(), + url: stringType(), + }), + model: objectType({ + name: stringType(), + url: stringType(), + }), + related: arrayType(stringType()), + echo_cancellation: booleanType().optional().nullable(), + noise_suppression: booleanType().optional().nullable(), + automatic_gain_control: booleanType().optional().nullable(), + hardware_mute: booleanType().optional().nullable(), + }); + const SkuTypeObject = { + UNHANDLED: -1, + APPLICATION: 1, + DLC: 2, + CONSUMABLE: 3, + BUNDLE: 4, + SUBSCRIPTION: 5, + }; + const Sku = objectType({ + id: stringType(), + name: stringType(), + type: zodCoerceUnhandledValue(SkuTypeObject), + price: objectType({ + amount: numberType(), + currency: stringType(), + }), + application_id: stringType(), + flags: numberType(), + release_date: stringType().nullable(), + }); + const EntitlementTypesObject = { + UNHANDLED: -1, + PURCHASE: 1, + PREMIUM_SUBSCRIPTION: 2, + DEVELOPER_GIFT: 3, + TEST_MODE_PURCHASE: 4, + FREE_PURCHASE: 5, + USER_GIFT: 6, + PREMIUM_PURCHASE: 7, + }; + const Entitlement = objectType({ + id: stringType(), + sku_id: stringType(), + application_id: stringType(), + user_id: stringType(), + gift_code_flags: numberType(), + type: zodCoerceUnhandledValue(EntitlementTypesObject), + gifter_user_id: stringType().optional().nullable(), + branches: arrayType(stringType()).optional().nullable(), + starts_at: stringType().optional().nullable(), + ends_at: stringType().optional().nullable(), + parent_id: stringType().optional().nullable(), + consumed: booleanType().optional().nullable(), + deleted: booleanType().optional().nullable(), + gift_code_batch_id: stringType().optional().nullable(), + }); + const OrientationLockStateTypeObject = { + UNHANDLED: -1, + UNLOCKED: 1, + PORTRAIT: 2, + LANDSCAPE: 3, + }; + const OrientationLockState = zodCoerceUnhandledValue(OrientationLockStateTypeObject); + const ThermalStateTypeObject = { + UNHANDLED: -1, + NOMINAL: 0, + FAIR: 1, + SERIOUS: 2, + CRITICAL: 3, + }; + const ThermalState = zodCoerceUnhandledValue(ThermalStateTypeObject); + const OrientationTypeObject = { + UNHANDLED: -1, + PORTRAIT: 0, + LANDSCAPE: 1, + }; + const Orientation = zodCoerceUnhandledValue(OrientationTypeObject); + const LayoutModeTypeObject = { + UNHANDLED: -1, + FOCUSED: 0, + PIP: 1, + GRID: 2, + }; + const LayoutMode = zodCoerceUnhandledValue(LayoutModeTypeObject); + + var Common = /*#__PURE__*/Object.freeze({ + __proto__: null, + Activity: Activity, + Attachment: Attachment, + CertifiedDevice: CertifiedDevice, + CertifiedDeviceTypeObject: CertifiedDeviceTypeObject, + Channel: Channel, + ChannelMention: ChannelMention, + ChannelTypesObject: ChannelTypesObject, + get Commands () { return Commands$1; }, + DISPATCH: DISPATCH, + Embed: Embed, + EmbedAuthor: EmbedAuthor, + EmbedField: EmbedField, + EmbedFooter: EmbedFooter, + EmbedProvider: EmbedProvider, + Emoji: Emoji, + Entitlement: Entitlement, + EntitlementTypesObject: EntitlementTypesObject, + Guild: Guild, + GuildMember: GuildMember, + Image: Image, + KeyTypesObject: KeyTypesObject, + LayoutMode: LayoutMode, + LayoutModeTypeObject: LayoutModeTypeObject, + Message: Message, + MessageActivity: MessageActivity, + MessageApplication: MessageApplication, + MessageReference: MessageReference, + Orientation: Orientation, + OrientationLockState: OrientationLockState, + OrientationLockStateTypeObject: OrientationLockStateTypeObject, + OrientationTypeObject: OrientationTypeObject, + PermissionOverwrite: PermissionOverwrite, + PermissionOverwriteTypeObject: PermissionOverwriteTypeObject, + PresenceUpdate: PresenceUpdate, + Reaction: Reaction, + ReceiveFramePayload: ReceiveFramePayload, + Role: Role, + Scopes: Scopes, + ScopesObject: ScopesObject, + ShortcutKey: ShortcutKey, + Sku: Sku, + SkuTypeObject: SkuTypeObject, + Status: Status, + StatusObject: StatusObject, + ThermalState: ThermalState, + ThermalStateTypeObject: ThermalStateTypeObject, + User: User, + UserVoiceState: UserVoiceState, + Video: Video, + VoiceDevice: VoiceDevice, + VoiceSettingModeTypeObject: VoiceSettingModeTypeObject, + VoiceSettingsIO: VoiceSettingsIO, + VoiceSettingsMode: VoiceSettingsMode, + VoiceState: VoiceState + }); + + // ERROR is sent as evt but is a special case, so is excluded from Events enum + const ERROR = 'ERROR'; + exports.Events = void 0; + (function (Events) { + Events["READY"] = "READY"; + Events["VOICE_STATE_UPDATE"] = "VOICE_STATE_UPDATE"; + Events["SPEAKING_START"] = "SPEAKING_START"; + Events["SPEAKING_STOP"] = "SPEAKING_STOP"; + Events["ACTIVITY_LAYOUT_MODE_UPDATE"] = "ACTIVITY_LAYOUT_MODE_UPDATE"; + Events["ORIENTATION_UPDATE"] = "ORIENTATION_UPDATE"; + Events["CURRENT_USER_UPDATE"] = "CURRENT_USER_UPDATE"; + Events["ENTITLEMENT_CREATE"] = "ENTITLEMENT_CREATE"; + Events["THERMAL_STATE_UPDATE"] = "THERMAL_STATE_UPDATE"; + Events["ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE"] = "ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE"; + })(exports.Events || (exports.Events = {})); + const DispatchEventFrame = ReceiveFramePayload.extend({ + evt: nativeEnumType(exports.Events), + nonce: stringType().nullable(), + cmd: literalType(DISPATCH), + data: objectType({}).passthrough(), + }); + const ErrorEvent = ReceiveFramePayload.extend({ + evt: literalType(ERROR), + data: objectType({ + code: numberType(), + message: stringType().optional(), + }) + .passthrough(), + cmd: nativeEnumType(Commands$1), + nonce: stringType().nullable(), + }); + const OtherEvent = DispatchEventFrame.extend({ + evt: stringType(), + }); + const EventFrame = unionType([DispatchEventFrame, OtherEvent, ErrorEvent]); + function parseEventPayload(data) { + const event = data.evt; + if (!(event in exports.Events)) { + throw new Error(`Unrecognized event type ${data.evt}`); + } + const eventSchema = EventSchema[event]; + return eventSchema.payload.parse(data); + } + const EventSchema = { + /** + * @description + * The READY event is emitted by Discord's RPC server in reply to a client + * initiating the RPC handshake. The event includes information about + * - the rpc server version + * - the discord client configuration + * - the (basic) user object + * + * Unlike other events, READY will only be omitted once, immediately after the + * Embedded App SDK is initialized + * + * # Supported Platforms + * | Web | iOS | Android | + * |-----|-----|---------| + * | ✅ | ✅ | ✅ | + * + * Required scopes: [] + * + */ + [exports.Events.READY]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.READY), + data: objectType({ + v: numberType(), + config: objectType({ + cdn_host: stringType().optional(), + api_endpoint: stringType(), + environment: stringType(), + }), + user: objectType({ + id: stringType(), + username: stringType(), + discriminator: stringType(), + avatar: stringType().optional(), + }) + .optional(), + }), + }), + }, + [exports.Events.VOICE_STATE_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.VOICE_STATE_UPDATE), + data: UserVoiceState, + }), + subscribeArgs: objectType({ + channel_id: stringType(), + }), + }, + [exports.Events.SPEAKING_START]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.SPEAKING_START), + data: objectType({ + lobby_id: stringType().optional(), + channel_id: stringType().optional(), + user_id: stringType(), + }), + }), + subscribeArgs: objectType({ + lobby_id: stringType().nullable().optional(), + channel_id: stringType().nullable().optional(), + }), + }, + [exports.Events.SPEAKING_STOP]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.SPEAKING_STOP), + data: objectType({ + lobby_id: stringType().optional(), + channel_id: stringType().optional(), + user_id: stringType(), + }), + }), + subscribeArgs: objectType({ + lobby_id: stringType().nullable().optional(), + channel_id: stringType().nullable().optional(), + }), + }, + [exports.Events.ACTIVITY_LAYOUT_MODE_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.ACTIVITY_LAYOUT_MODE_UPDATE), + data: objectType({ + layout_mode: zodCoerceUnhandledValue(LayoutModeTypeObject), + }), + }), + }, + [exports.Events.ORIENTATION_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.ORIENTATION_UPDATE), + data: objectType({ + screen_orientation: zodCoerceUnhandledValue(OrientationTypeObject), + /** + * @deprecated use screen_orientation instead + */ + orientation: nativeEnumType(exports.Orientation), + }), + }), + }, + [exports.Events.CURRENT_USER_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.CURRENT_USER_UPDATE), + data: User, + }), + }, + [exports.Events.ENTITLEMENT_CREATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.ENTITLEMENT_CREATE), + data: objectType({ entitlement: Entitlement }), + }), + }, + [exports.Events.THERMAL_STATE_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.THERMAL_STATE_UPDATE), + data: objectType({ thermal_state: ThermalState }), + }), + }, + [exports.Events.ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE]: { + payload: DispatchEventFrame.extend({ + evt: literalType(exports.Events.ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE), + data: objectType({ + participants: GetActivityInstanceConnectedParticipantsResponseSchema.shape.participants, + }), + }), + }, + }; + + /** + * Assets x is statically unreachable at build-time, + * and throws at runtime if data is dynamic. + */ + function assertUnreachable(_x, runtimeError) { + throw runtimeError; + } + + const EmptyResponse = objectType({}).nullable(); + const AuthorizeResponse = objectType({ + code: stringType(), + }); + const GetGuildsResponse = objectType({ + guilds: arrayType(objectType({ + id: stringType(), + name: stringType(), + })), + }); + const GetGuildResponse = objectType({ + id: stringType(), + name: stringType(), + icon_url: stringType().optional(), + members: arrayType(GuildMember), + }); + const GetChannelResponse = objectType({ + id: stringType(), + type: zodCoerceUnhandledValue(ChannelTypesObject), + guild_id: stringType().optional().nullable(), + name: stringType().optional().nullable(), + topic: stringType().optional().nullable(), + bitrate: numberType().optional().nullable(), + user_limit: numberType().optional().nullable(), + position: numberType().optional().nullable(), + voice_states: arrayType(UserVoiceState), + messages: arrayType(Message), + }); + const GetChannelsResponse = objectType({ + channels: arrayType(Channel), + }); + const NullableChannelResponse = GetChannelResponse.nullable(); + const SelectVoiceChannelResponse = GetChannelResponse.nullable(); + const SelectTextChannelResponse = GetChannelResponse.nullable(); + const VoiceSettingsResponse = objectType({ + input: VoiceSettingsIO, + output: VoiceSettingsIO, + mode: VoiceSettingsMode, + automatic_gain_control: booleanType(), + echo_cancellation: booleanType(), + noise_suppression: booleanType(), + qos: booleanType(), + silence_warning: booleanType(), + deaf: booleanType(), + mute: booleanType(), + }); + const SubscribeResponse = objectType({ + evt: stringType(), + }); + const CaptureShortcutResponse = objectType({ shortcut: ShortcutKey }); + const SetActivityResponse = Activity; + const GetSkusResponse = objectType({ skus: arrayType(Sku) }); + const GetEntitlementsResponse = objectType({ entitlements: arrayType(Entitlement) }); + const StartPurchaseResponse = arrayType(Entitlement).nullable(); + const SetConfigResponse = objectType({ + use_interactive_pip: booleanType(), + }); + const UserSettingsGetLocaleResponse = objectType({ + locale: stringType(), + }); + const EncourageHardwareAccelerationResponse = objectType({ + enabled: booleanType(), + }); + const GetChannelPermissionsResponse = objectType({ + permissions: bigIntType().or(stringType()), + }); + /** + * Because of the nature of Platform Behavior changes + * every key/value is optional and may eventually be removed + */ + const GetPlatformBehaviorsResponse = objectType({ + iosKeyboardResizesView: optionalType(booleanType()), + }); + const ResponseFrame = ReceiveFramePayload.extend({ + cmd: nativeEnumType(Commands$1), + evt: nullType(), + }); + function parseResponseData({ cmd, data }) { + switch (cmd) { + case Commands$1.AUTHORIZE: + return AuthorizeResponse.parse(data); + case Commands$1.CAPTURE_SHORTCUT: + return CaptureShortcutResponse.parse(data); + case Commands$1.ENCOURAGE_HW_ACCELERATION: + return EncourageHardwareAccelerationResponse.parse(data); + case Commands$1.GET_CHANNEL: + return GetChannelResponse.parse(data); + case Commands$1.GET_CHANNELS: + return GetChannelsResponse.parse(data); + case Commands$1.GET_CHANNEL_PERMISSIONS: + return GetChannelPermissionsResponse.parse(data); + case Commands$1.GET_GUILD: + return GetGuildResponse.parse(data); + case Commands$1.GET_GUILDS: + return GetGuildsResponse.parse(data); + case Commands$1.GET_PLATFORM_BEHAVIORS: + return GetPlatformBehaviorsResponse.parse(data); + case Commands$1.GET_CHANNEL: + return GetChannelResponse.parse(data); + case Commands$1.SELECT_TEXT_CHANNEL: + return SelectTextChannelResponse.parse(data); + case Commands$1.SELECT_VOICE_CHANNEL: + return SelectVoiceChannelResponse.parse(data); + case Commands$1.SET_ACTIVITY: + return SetActivityResponse.parse(data); + case Commands$1.GET_SKUS_EMBEDDED: + return GetSkusResponse.parse(data); + case Commands$1.GET_ENTITLEMENTS_EMBEDDED: + return GetEntitlementsResponse.parse(data); + case Commands$1.SET_CONFIG: + return SetConfigResponse.parse(data); + case Commands$1.START_PURCHASE: + return StartPurchaseResponse.parse(data); + case Commands$1.SUBSCRIBE: + case Commands$1.UNSUBSCRIBE: + return SubscribeResponse.parse(data); + case Commands$1.USER_SETTINGS_GET_LOCALE: + return UserSettingsGetLocaleResponse.parse(data); + // Empty Responses + case Commands$1.OPEN_EXTERNAL_LINK: + case Commands$1.SET_ORIENTATION_LOCK_STATE: + case Commands$1.SET_CERTIFIED_DEVICES: + case Commands$1.SEND_ANALYTICS_EVENT: + case Commands$1.OPEN_INVITE_DIALOG: + case Commands$1.CAPTURE_LOG: + case Commands$1.GET_SKUS: + case Commands$1.GET_ENTITLEMENTS: + return EmptyResponse.parse(data); + // Generated Responses + case Commands$1.AUTHENTICATE: + case Commands$1.INITIATE_IMAGE_UPLOAD: + case Commands$1.OPEN_SHARE_MOMENT_DIALOG: + case Commands$1.GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS: + const { response } = Schemas[cmd]; + return response.parse(data); + default: + assertUnreachable(cmd, new Error(`Unrecognized command ${cmd}`)); + } + } + function parseResponsePayload(payload) { + return Object.assign(Object.assign({}, payload), { data: parseResponseData(payload) }); + } + + var responses = /*#__PURE__*/Object.freeze({ + __proto__: null, + AuthenticateResponse: AuthenticateResponseSchema, + AuthorizeResponse: AuthorizeResponse, + CaptureShortcutResponse: CaptureShortcutResponse, + EmptyResponse: EmptyResponse, + EncourageHardwareAccelerationResponse: EncourageHardwareAccelerationResponse, + GetChannelPermissionsResponse: GetChannelPermissionsResponse, + GetChannelResponse: GetChannelResponse, + GetChannelsResponse: GetChannelsResponse, + GetEntitlementsResponse: GetEntitlementsResponse, + GetGuildResponse: GetGuildResponse, + GetGuildsResponse: GetGuildsResponse, + GetPlatformBehaviorsResponse: GetPlatformBehaviorsResponse, + GetSkusResponse: GetSkusResponse, + InitiateImageUploadResponse: InitiateImageUploadResponseSchema, + NullableChannelResponse: NullableChannelResponse, + ResponseFrame: ResponseFrame, + SelectTextChannelResponse: SelectTextChannelResponse, + SelectVoiceChannelResponse: SelectVoiceChannelResponse, + SetActivityResponse: SetActivityResponse, + SetConfigResponse: SetConfigResponse, + StartPurchaseResponse: StartPurchaseResponse, + SubscribeResponse: SubscribeResponse, + UserSettingsGetLocaleResponse: UserSettingsGetLocaleResponse, + VoiceSettingsResponse: VoiceSettingsResponse, + parseResponsePayload: parseResponsePayload + }); + + objectType({ + frame_id: stringType(), + platform: nativeEnumType(exports.Platform).optional().nullable(), + }); + objectType({ + v: literalType(1), + encoding: literalType('json').optional(), + client_id: stringType(), + frame_id: stringType(), + }); + const ClosePayload = objectType({ + code: numberType(), + message: stringType().optional(), + }); + const IncomingPayload = objectType({ + evt: stringType().nullable(), + nonce: stringType().nullable(), + data: unknownType().nullable(), + cmd: stringType(), + }) + .passthrough(); + function parseIncomingPayload(payload) { + const incoming = IncomingPayload.parse(payload); + if (incoming.evt != null) { + if (incoming.evt === ERROR) { + return ErrorEvent.parse(incoming); + } + return parseEventPayload(EventFrame.parse(incoming)); + } + else { + return parseResponsePayload(ResponseFrame.passthrough().parse(incoming)); + } + } + + function commandFactory(sendCommand, cmd, response, transferTransform = () => undefined) { + const payload = ReceiveFramePayload.extend({ + cmd: literalType(cmd), + data: response, + }); + return async (args) => { + const reply = await sendCommand({ cmd, args, transfer: transferTransform(args) }); + const parsed = payload.parse(reply); + return parsed.data; + }; + } + function schemaCommandFactory(cmd, transferTransform = () => undefined) { + const response = Schemas[cmd].response; + const payload = ReceiveFramePayload.extend({ + cmd: literalType(cmd), + data: response, + }); + return (sendCommand) => async (args) => { + const reply = await sendCommand({ + // @ts-expect-error - Merge commands + cmd: cmd, + args, + transfer: transferTransform(args), + }); + const parsed = payload.parse(reply); + return parsed.data; + }; + } + + /** + * Authenticate Activity + */ + const authenticate = schemaCommandFactory(Command.AUTHENTICATE); + + /** + * Should be called directly after a `ready` payload is received from the + * Discord client. It includes a list of all scopes that your activity would + * like to be authorized to use. If the user does not yet have a valid token + * for all scopes requested, this command will open an OAuth modal. Once an + * authorized token is available, it will be returned in the command response. + */ + const authorize = (sendCommand) => commandFactory(sendCommand, Commands$1.AUTHORIZE, AuthorizeResponse); + + /** + * + */ + const captureLog = (sendCommand) => commandFactory(sendCommand, Commands$1.CAPTURE_LOG, EmptyResponse); + + /** + * + */ + const encourageHardwareAcceleration = (sendCommand) => commandFactory(sendCommand, Commands$1.ENCOURAGE_HW_ACCELERATION, EncourageHardwareAccelerationResponse); + + /** + * + */ + const getEntitlements = (sendCommand) => commandFactory(sendCommand, Commands$1.GET_ENTITLEMENTS_EMBEDDED, GetEntitlementsResponse); + + /* + * + */ + const getSkus = (sendCommand) => commandFactory(sendCommand, Commands$1.GET_SKUS_EMBEDDED, GetSkusResponse); + + /** + * Returns a bigint representing Permissions for the current user in the currently connected channel. Use PermissionsUtils to calculate if a user has a particular permission. + * Always returns `0n` (no valid permissions) in a (G)DM context, so is unnecessary to call when discordSdk.guildId == null. + */ + const getChannelPermissions = (sendCommand) => commandFactory(sendCommand, Commands$1.GET_CHANNEL_PERMISSIONS, GetChannelPermissionsResponse); + + /** + * Returns an object with information about platform behaviors + * This command can be utilized to inform and react to a breaking change in platform behavior + * + * @returns {GetPlatformBehaviorsPayload} payload - The command return value + * @returns {boolean} payload.data.iosKeyboardResizesView - If on iOS the webview is resized when the keyboard is opened + */ + const getPlatformBehaviors = (sendCommand) => commandFactory(sendCommand, Commands$1.GET_PLATFORM_BEHAVIORS, GetPlatformBehaviorsResponse); + + /** + * + */ + const openExternalLink = (sendCommand) => commandFactory(sendCommand, Commands$1.OPEN_EXTERNAL_LINK, EmptyResponse); + + /** + * Opens the invite dialog within the discord client, allowing users to share invite links to friends. + * Does not work in (G)DM contexts (throws RPCError.INVALID_CHANNEL), so should not be called if discordSdk.guildId == null + * Similarly, if the user does not have Permissions.CREATE_INSTANT_INVITE this command throws RPCErrors.INVALID_PERMISSIONS, so checking the user's permissions via getChannelPermissions is highly recommended. + */ + const openInviteDialog = (sendCommand) => commandFactory(sendCommand, Commands$1.OPEN_INVITE_DIALOG, EmptyResponse); + + /** + * Opens the Share Moment Dialog in the user's client, allowing them to share the media at mediaUrl as a message. + * + * @param {string} mediaUrl - a Discord CDN URL for the piece of media to be shared. + * @returns {Promise} + */ + const openShareMomentDialog = schemaCommandFactory(Command.OPEN_SHARE_MOMENT_DIALOG); + + Activity.pick({ + state: true, + details: true, + timestamps: true, + assets: true, + party: true, + secrets: true, + buttons: true, + instance: true, + supported_platforms: true, + type: true, + }) + .extend({ + type: Activity.shape.type.optional(), + instance: Activity.shape.instance.optional(), + }) + .nullable(); + /** + * + * @description + * RPC documentation here: https://discord.com/developers/docs/topics/rpc#setactivity + * Calling setActivity allows modifying how your activity's rich presence is displayed in the Discord App + * + * Supported Platforms + * | Web | iOS | Android | + * |-----|-----|---------| + * | ✅ | ✅ | ✅ | + * + * Required scopes: [rpc.activities.write] + * + * @example + * await discordSdk.commands.setActivity({ + * activity: { + * type: 0, + * details: 'Details', + * state: 'Playing', + * }, + * }); + */ + const setActivity = (sendCommand) => commandFactory(sendCommand, Commands$1.SET_ACTIVITY, SetActivityResponse); + + /** + * + */ + const setConfig = (sendCommand) => commandFactory(sendCommand, Commands$1.SET_CONFIG, SetConfigResponse); + + /** + * @args - the primary args to send with the command. + * @fallbackArgs - the args to try the command with in the case where an old Discord + * client doesn't support one of the new args. + */ + function compatCommandFactory({ sendCommand, cmd, response, fallbackTransform, transferTransform = () => undefined, }) { + const payload = ReceiveFramePayload.extend({ + cmd: literalType(cmd), + data: response, + }); + return async (args) => { + try { + const reply = await sendCommand({ cmd, args, transfer: transferTransform(args) }); + const parsed = payload.parse(reply); + return parsed.data; + } + catch (error) { + if (error.code === exports.RPCErrorCodes.INVALID_PAYLOAD) { + const fallbackArgs = fallbackTransform(args); + const reply = await sendCommand({ cmd, args: fallbackArgs, transfer: transferTransform(fallbackArgs) }); + const parsed = payload.parse(reply); + return parsed.data; + } + else { + throw error; + } + } + }; + } + + const fallbackTransform = (args) => { + return { + lock_state: args.lock_state, + picture_in_picture_lock_state: args.picture_in_picture_lock_state, + }; + }; + const setOrientationLockState = (sendCommand) => compatCommandFactory({ + sendCommand, + cmd: Commands$1.SET_ORIENTATION_LOCK_STATE, + response: EmptyResponse, + fallbackTransform, + }); + + /** + * + */ + const startPurchase = (sendCommand) => commandFactory(sendCommand, Commands$1.START_PURCHASE, StartPurchaseResponse); + + /** + * + */ + const userSettingsGetLocale = (sendCommand) => commandFactory(sendCommand, Commands$1.USER_SETTINGS_GET_LOCALE, UserSettingsGetLocaleResponse); + + /** + * Triggers the file upload flow in the Discord app. The user will be prompted to select a valid image file + * and then it will be uploaded on the app side to the Discord CDN. + * + * NOTE: The URL provided by the API is an ephemeral attachment URL, so the image will not be permanently + * accessible at the link provided. + * + * @returns {Promise<{image_url: string}>} + */ + const initiateImageUpload = schemaCommandFactory(Command.INITIATE_IMAGE_UPLOAD); + + /** + * + * @description + * RPC documentation here: https://discord.com/developers/docs/topics/rpc#getchannel + * Calling getChannel gets info about the requested channel such as the channel name. + * + * Supported Platforms + * | Web | iOS | Android | + * |-----|-----|---------| + * | ✅ | ✅ | ✅ | + * + * Required scopes: + * - [guilds] for guild channels + * - [guilds, dm_channels.read] for GDM channels. dm_channels.read requires approval from Discord. + * + * @example + * await discordSdk.commands.getActivity({ + * channel_id: discordSdk.channelId, + * }); + */ + const getChannel = (sendCommand) => commandFactory(sendCommand, Commands$1.GET_CHANNEL, GetChannelResponse); + + /** + * Gets all participants connected to the instance + */ + const getInstanceConnectedParticipants = schemaCommandFactory(Command.GET_ACTIVITY_INSTANCE_CONNECTED_PARTICIPANTS); + + function commands(sendCommand) { + return { + authenticate: authenticate(sendCommand), + authorize: authorize(sendCommand), + captureLog: captureLog(sendCommand), + encourageHardwareAcceleration: encourageHardwareAcceleration(sendCommand), + getChannel: getChannel(sendCommand), + getChannelPermissions: getChannelPermissions(sendCommand), + getEntitlements: getEntitlements(sendCommand), + getPlatformBehaviors: getPlatformBehaviors(sendCommand), + getSkus: getSkus(sendCommand), + openExternalLink: openExternalLink(sendCommand), + openInviteDialog: openInviteDialog(sendCommand), + openShareMomentDialog: openShareMomentDialog(sendCommand), + setActivity: setActivity(sendCommand), + setConfig: setConfig(sendCommand), + setOrientationLockState: setOrientationLockState(sendCommand), + startPurchase: startPurchase(sendCommand), + userSettingsGetLocale: userSettingsGetLocale(sendCommand), + initiateImageUpload: initiateImageUpload(sendCommand), + getInstanceConnectedParticipants: getInstanceConnectedParticipants(sendCommand), + }; + } + + // Unique ID creation requires a high quality random # generator. In the browser we therefore + // require the crypto API and do not support built-in fallback to lower quality random number + // generators (like Math.random()). + let getRandomValues; + const rnds8 = new Uint8Array(16); + function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); + } + + /** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + + const byteToHex = []; + + for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); + } + + function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; + } + + const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); + var native = { + randomUUID + }; + + function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); + } + + class SDKError extends Error { + constructor(code, message = '') { + super(message); + this.code = code; + this.message = message; + this.name = 'Discord SDK Error'; + } + } + + function getDefaultSdkConfiguration() { + return { + disableConsoleLogOverride: false, + }; + } + + const consoleLevels = ['log', 'warn', 'debug', 'info', 'error']; + function wrapConsoleMethod(console, level, callback) { + const _consoleMethod = console[level]; + const _console = console; + if (!_consoleMethod) { + return; + } + console[level] = function () { + const args = [].slice.call(arguments); + const message = '' + args.join(' '); + callback(level, message); + _consoleMethod.apply(_console, args); + }; + } + + var Opcodes; + (function (Opcodes) { + Opcodes[Opcodes["HANDSHAKE"] = 0] = "HANDSHAKE"; + Opcodes[Opcodes["FRAME"] = 1] = "FRAME"; + Opcodes[Opcodes["CLOSE"] = 2] = "CLOSE"; + Opcodes[Opcodes["HELLO"] = 3] = "HELLO"; + })(Opcodes || (Opcodes = {})); + const ALLOWED_ORIGINS = new Set(getAllowedOrigins()); + function getAllowedOrigins() { + if (typeof window === 'undefined') + return []; + return [ + window.location.origin, + 'https://discord.com', + 'https://discordapp.com', + 'https://ptb.discord.com', + 'https://ptb.discordapp.com', + 'https://canary.discord.com', + 'https://canary.discordapp.com', + 'https://staging.discord.co', + 'http://localhost:3333', + 'https://pax.discord.com', + 'null', + ]; + } + /** + * The embedded application is running in an IFrame either within the main Discord client window or in a popout. The RPC server is always running in the main Discord client window. In either case, the referrer is the correct origin. + */ + function getRPCServerSource() { + var _a; + return [(_a = window.parent.opener) !== null && _a !== void 0 ? _a : window.parent, !!document.referrer ? document.referrer : '*']; + } + class DiscordSDK { + getTransfer(payload) { + var _a; + switch (payload.cmd) { + case Commands$1.SUBSCRIBE: + case Commands$1.UNSUBSCRIBE: + return undefined; + default: + return (_a = payload.transfer) !== null && _a !== void 0 ? _a : undefined; + } + } + constructor(clientId, configuration) { + this.source = null; + this.sourceOrigin = ''; + this.eventBus = new EventEmitter(); + this.pendingCommands = new Map(); + this.sendCommand = (payload) => { + var _a; + if (this.source == null) + throw new Error('Attempting to send message before initialization'); + const nonce = v4(); + (_a = this.source) === null || _a === void 0 ? void 0 : _a.postMessage([Opcodes.FRAME, Object.assign(Object.assign({}, payload), { nonce })], this.sourceOrigin, this.getTransfer(payload)); + const promise = new Promise((resolve, reject) => { + this.pendingCommands.set(nonce, { resolve, reject }); + }); + return promise; + }; + this.commands = commands(this.sendCommand); + /** + * WARNING - All "console" logs are emitted as messages to the Discord client + * If you write "console.log" anywhere in handleMessage or subsequent message handling + * there is a good chance you will cause an infinite loop where you receive a message + * which causes "console.log" which sends a message, which causes the discord client to + * send a reply which causes handleMessage to fire again, and again to inifinity + * + * If you need to log within handleMessage, consider setting + * config.disableConsoleLogOverride to true when initializing the SDK + */ + this.handleMessage = (event) => { + if (!ALLOWED_ORIGINS.has(event.origin)) + return; + const tuple = event.data; + if (!Array.isArray(tuple)) { + return; + } + const [opcode, data] = tuple; + switch (opcode) { + case Opcodes.HELLO: + // backwards compat; the Discord client will still send HELLOs for old applications. + // + // TODO: figure out compatibility approach; it would be easier to maintain compatibility at the SDK level, not the underlying RPC protocol level... + return; + case Opcodes.CLOSE: + return this.handleClose(data); + case Opcodes.HANDSHAKE: + return this.handleHandshake(); + case Opcodes.FRAME: + return this.handleFrame(data); + default: + throw new Error('Invalid message format'); + } + }; + this.isReady = false; + this.clientId = clientId; + this.configuration = configuration !== null && configuration !== void 0 ? configuration : getDefaultSdkConfiguration(); + if (typeof window !== 'undefined') { + window.addEventListener('message', this.handleMessage); + } + if (typeof window === 'undefined') { + this.frameId = ''; + this.instanceId = ''; + this.platform = exports.Platform.DESKTOP; + this.guildId = null; + this.channelId = null; + return; + } + // START Capture URL Query Params + const urlParams = new URLSearchParams(this._getSearch()); + const frameId = urlParams.get('frame_id'); + if (!frameId) { + throw new Error('frame_id query param is not defined'); + } + this.frameId = frameId; + const instanceId = urlParams.get('instance_id'); + if (!instanceId) { + throw new Error('instance_id query param is not defined'); + } + this.instanceId = instanceId; + const platform = urlParams.get('platform'); + if (!platform) { + throw new Error('platform query param is not defined'); + } + else if (platform !== exports.Platform.DESKTOP && platform !== exports.Platform.MOBILE) { + throw new Error(`Invalid query param "platform" of "${platform}". Valid values are "${exports.Platform.DESKTOP}" or "${exports.Platform.MOBILE}"`); + } + this.platform = platform; + this.guildId = urlParams.get('guild_id'); + this.channelId = urlParams.get('channel_id'); + // END Capture URL Query Params + [this.source, this.sourceOrigin] = getRPCServerSource(); + this.addOnReadyListener(); + this.handshake(); + } + close(code, message) { + var _a; + window.removeEventListener('message', this.handleMessage); + const nonce = v4(); + (_a = this.source) === null || _a === void 0 ? void 0 : _a.postMessage([Opcodes.CLOSE, { code, message, nonce }], this.sourceOrigin); + } + async subscribe(event, listener, ...rest) { + const [subscribeArgs] = rest; + const listenerCount = this.eventBus.listenerCount(event); + const emitter = this.eventBus.on(event, listener); + // If first subscription, subscribe via RPC + if (Object.values(exports.Events).includes(event) && event !== exports.Events.READY && listenerCount === 0) { + await this.sendCommand({ + cmd: Commands$1.SUBSCRIBE, + args: subscribeArgs, + evt: event, + }); + } + return emitter; + } + async unsubscribe(event, listener, ...rest) { + const [unsubscribeArgs] = rest; + if (event !== exports.Events.READY && this.eventBus.listenerCount(event) === 1) { + await this.sendCommand({ + cmd: Commands$1.UNSUBSCRIBE, + evt: event, + args: unsubscribeArgs, + }); + } + return this.eventBus.off(event, listener); + } + async ready() { + if (this.isReady) { + return; + } + else { + await new Promise((resolve) => { + this.eventBus.once(exports.Events.READY, resolve); + }); + } + } + handshake() { + var _a; + (_a = this.source) === null || _a === void 0 ? void 0 : _a.postMessage([ + Opcodes.HANDSHAKE, + { + v: 1, + encoding: 'json', + client_id: this.clientId, + frame_id: this.frameId, + }, + ], this.sourceOrigin); + } + addOnReadyListener() { + this.eventBus.once(exports.Events.READY, () => { + this.overrideConsoleLogging(); + this.isReady = true; + }); + } + overrideConsoleLogging() { + if (this.configuration.disableConsoleLogOverride) + return; + const sendCaptureLogCommand = (level, message) => { + this.commands.captureLog({ + level, + message, + }); + }; + consoleLevels.forEach((level) => { + wrapConsoleMethod(console, level, sendCaptureLogCommand); + }); + } + handleClose(data) { + ClosePayload.parse(data); + } + handleHandshake() { } + handleFrame(payload) { + var _a, _b; + let parsed; + try { + parsed = parseIncomingPayload(payload); + } + catch (e) { + console.error('Failed to parse', payload); + console.error(e); + return; + } + if (parsed.cmd === 'DISPATCH') { + this.eventBus.emit(parsed.evt, parsed.data); + } + else { + if (parsed.evt === ERROR) { + // In response to a command + if (parsed.nonce != null) { + (_a = this.pendingCommands.get(parsed.nonce)) === null || _a === void 0 ? void 0 : _a.reject(parsed.data); + this.pendingCommands.delete(parsed.nonce); + return; + } + // General error + this.eventBus.emit('error', new SDKError(parsed.data.code, parsed.data.message)); + } + if (parsed.nonce == null) { + console.error('Missing nonce', payload); + return; + } + (_b = this.pendingCommands.get(parsed.nonce)) === null || _b === void 0 ? void 0 : _b.resolve(parsed); + this.pendingCommands.delete(parsed.nonce); + } + } + _getSearch() { + return typeof window === 'undefined' ? '' : window.location.search; + } + } + + function can(permission, permissions) { + return BigFlagUtils.has(BigFlagUtils.deserialize(permissions), permission); + } + var PermissionUtils = { + can, + }; + + /* + * decimal.js-light v2.5.0 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js-light + * Copyright (c) 2018 Michael Mclaughlin + * MIT Expat Licence + */ + + + // ------------------------------------ EDITABLE DEFAULTS ------------------------------------- // + + + // The limit on the value of `precision`, and on the value of the first argument to + // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. + var MAX_DIGITS = 1e9, // 0 to 1e9 + + + // The initial configuration properties of the Decimal constructor. + defaults = { + + // These values must be integers within the stated ranges (inclusive). + // Most of these values can be changed during run-time using `Decimal.config`. + + // The maximum number of significant digits of the result of a calculation or base conversion. + // E.g. `Decimal.config({ precision: 20 });` + precision: 20, // 1 to MAX_DIGITS + + // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`, + // `toFixed`, `toPrecision` and `toSignificantDigits`. + // + // ROUND_UP 0 Away from zero. + // ROUND_DOWN 1 Towards zero. + // ROUND_CEIL 2 Towards +Infinity. + // ROUND_FLOOR 3 Towards -Infinity. + // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + // + // E.g. + // `Decimal.rounding = 4;` + // `Decimal.rounding = Decimal.ROUND_HALF_UP;` + rounding: 4, // 0 to 8 + + // The exponent value at and beneath which `toString` returns exponential notation. + // JavaScript numbers: -7 + toExpNeg: -7, // 0 to -MAX_E + + // The exponent value at and above which `toString` returns exponential notation. + // JavaScript numbers: 21 + toExpPos: 21, // 0 to MAX_E + + // The natural logarithm of 10. + // 115 digits + LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286' + }, + + + // ------------------------------------ END OF EDITABLE DEFAULTS -------------------------------- // + + + Decimal, + external = true, + + decimalError = '[DecimalError] ', + invalidArgument = decimalError + 'Invalid argument: ', + exponentOutOfRange = decimalError + 'Exponent out of range: ', + + mathfloor = Math.floor, + mathpow = Math.pow, + + isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + + ONE, + BASE = 1e7, + LOG_BASE = 7, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), // 1286742750677284 + + // Decimal.prototype object + P = {}; + + + // Decimal prototype methods + + + /* + * absoluteValue abs + * comparedTo cmp + * decimalPlaces dp + * dividedBy div + * dividedToIntegerBy idiv + * equals eq + * exponent + * greaterThan gt + * greaterThanOrEqualTo gte + * isInteger isint + * isNegative isneg + * isPositive ispos + * isZero + * lessThan lt + * lessThanOrEqualTo lte + * logarithm log + * minus sub + * modulo mod + * naturalExponential exp + * naturalLogarithm ln + * negated neg + * plus add + * precision sd + * squareRoot sqrt + * times mul + * toDecimalPlaces todp + * toExponential + * toFixed + * toInteger toint + * toNumber + * toPower pow + * toPrecision + * toSignificantDigits tosd + * toString + * valueOf val + */ + + + /* + * Return a new Decimal whose value is the absolute value of this Decimal. + * + */ + P.absoluteValue = P.abs = function () { + var x = new this.constructor(this); + if (x.s) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this Decimal is greater than the value of `y`, + * -1 if the value of this Decimal is less than the value of `y`, + * 0 if they have the same value + * + */ + P.comparedTo = P.cmp = function (y) { + var i, j, xdL, ydL, + x = this; + + y = new x.constructor(y); + + // Signs differ? + if (x.s !== y.s) return x.s || -y.s; + + // Compare exponents. + if (x.e !== y.e) return x.e > y.e ^ x.s < 0 ? 1 : -1; + + xdL = x.d.length; + ydL = y.d.length; + + // Compare digit by digit. + for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { + if (x.d[i] !== y.d[i]) return x.d[i] > y.d[i] ^ x.s < 0 ? 1 : -1; + } + + // Compare lengths. + return xdL === ydL ? 0 : xdL > ydL ^ x.s < 0 ? 1 : -1; + }; + + + /* + * Return the number of decimal places of the value of this Decimal. + * + */ + P.decimalPlaces = P.dp = function () { + var x = this, + w = x.d.length - 1, + dp = (w - x.e) * LOG_BASE; + + // Subtract the number of trailing zeros of the last word. + w = x.d[w]; + if (w) for (; w % 10 == 0; w /= 10) dp--; + + return dp < 0 ? 0 : dp; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to + * `precision` significant digits. + * + */ + P.dividedBy = P.div = function (y) { + return divide(this, new this.constructor(y)); + }; + + + /* + * Return a new Decimal whose value is the integer part of dividing the value of this Decimal + * by the value of `y`, truncated to `precision` significant digits. + * + */ + P.dividedToIntegerBy = P.idiv = function (y) { + var x = this, + Ctor = x.constructor; + return round(divide(x, new Ctor(y), 0, 1), Ctor.precision); + }; + + + /* + * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. + * + */ + P.equals = P.eq = function (y) { + return !this.cmp(y); + }; + + + /* + * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent). + * + */ + P.exponent = function () { + return getBase10Exponent(this); + }; + + + /* + * Return true if the value of this Decimal is greater than the value of `y`, otherwise return + * false. + * + */ + P.greaterThan = P.gt = function (y) { + return this.cmp(y) > 0; + }; + + + /* + * Return true if the value of this Decimal is greater than or equal to the value of `y`, + * otherwise return false. + * + */ + P.greaterThanOrEqualTo = P.gte = function (y) { + return this.cmp(y) >= 0; + }; + + + /* + * Return true if the value of this Decimal is an integer, otherwise return false. + * + */ + P.isInteger = P.isint = function () { + return this.e > this.d.length - 2; + }; + + + /* + * Return true if the value of this Decimal is negative, otherwise return false. + * + */ + P.isNegative = P.isneg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this Decimal is positive, otherwise return false. + * + */ + P.isPositive = P.ispos = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this Decimal is 0, otherwise return false. + * + */ + P.isZero = function () { + return this.s === 0; + }; + + + /* + * Return true if the value of this Decimal is less than `y`, otherwise return false. + * + */ + P.lessThan = P.lt = function (y) { + return this.cmp(y) < 0; + }; + + + /* + * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. + * + */ + P.lessThanOrEqualTo = P.lte = function (y) { + return this.cmp(y) < 1; + }; + + + /* + * Return the logarithm of the value of this Decimal to the specified base, truncated to + * `precision` significant digits. + * + * If no base is specified, return log[10](x). + * + * log[base](x) = ln(x) / ln(base) + * + * The maximum error of the result is 1 ulp (unit in the last place). + * + * [base] {number|string|Decimal} The base of the logarithm. + * + */ + P.logarithm = P.log = function (base) { + var r, + x = this, + Ctor = x.constructor, + pr = Ctor.precision, + wpr = pr + 5; + + // Default base is 10. + if (base === void 0) { + base = new Ctor(10); + } else { + base = new Ctor(base); + + // log[-b](x) = NaN + // log[0](x) = NaN + // log[1](x) = NaN + if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + 'NaN'); + } + + // log[b](-x) = NaN + // log[b](0) = -Infinity + if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity')); + + // log[b](1) = 0 + if (x.eq(ONE)) return new Ctor(0); + + external = false; + r = divide(ln(x, wpr), ln(base, wpr), wpr); + external = true; + + return round(r, pr); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to + * `precision` significant digits. + * + */ + P.minus = P.sub = function (y) { + var x = this; + y = new x.constructor(y); + return x.s == y.s ? subtract(x, y) : add(x, (y.s = -y.s, y)); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to + * `precision` significant digits. + * + */ + P.modulo = P.mod = function (y) { + var q, + x = this, + Ctor = x.constructor, + pr = Ctor.precision; + + y = new Ctor(y); + + // x % 0 = NaN + if (!y.s) throw Error(decimalError + 'NaN'); + + // Return x if x is 0. + if (!x.s) return round(new Ctor(x), pr); + + // Prevent rounding of intermediate calculations. + external = false; + q = divide(x, y, 0, 1).times(y); + external = true; + + return x.minus(q); + }; + + + /* + * Return a new Decimal whose value is the natural exponential of the value of this Decimal, + * i.e. the base e raised to the power the value of this Decimal, truncated to `precision` + * significant digits. + * + */ + P.naturalExponential = P.exp = function () { + return exp(this); + }; + + + /* + * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, + * truncated to `precision` significant digits. + * + */ + P.naturalLogarithm = P.ln = function () { + return ln(this); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by + * -1. + * + */ + P.negated = P.neg = function () { + var x = new this.constructor(this); + x.s = -x.s || 0; + return x; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to + * `precision` significant digits. + * + */ + P.plus = P.add = function (y) { + var x = this; + y = new x.constructor(y); + return x.s == y.s ? add(x, y) : subtract(x, (y.s = -y.s, y)); + }; + + + /* + * Return the number of significant digits of the value of this Decimal. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + * + */ + P.precision = P.sd = function (z) { + var e, sd, w, + x = this; + + if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); + + e = getBase10Exponent(x) + 1; + w = x.d.length - 1; + sd = w * LOG_BASE + 1; + w = x.d[w]; + + // If non-zero... + if (w) { + + // Subtract the number of trailing zeros of the last word. + for (; w % 10 == 0; w /= 10) sd--; + + // Add the number of digits of the first word. + for (w = x.d[0]; w >= 10; w /= 10) sd++; + } + + return z && e > sd ? e : sd; + }; + + + /* + * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision` + * significant digits. + * + */ + P.squareRoot = P.sqrt = function () { + var e, n, pr, r, s, t, wpr, + x = this, + Ctor = x.constructor; + + // Negative or zero? + if (x.s < 1) { + if (!x.s) return new Ctor(0); + + // sqrt(-x) = NaN + throw Error(decimalError + 'NaN'); + } + + e = getBase10Exponent(x); + external = false; + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = digitsToString(x.d); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new Ctor(n); + } else { + r = new Ctor(s.toString()); + } + + pr = Ctor.precision; + s = wpr = pr + 3; + + // Newton-Raphson iteration. + for (;;) { + t = r; + r = t.plus(divide(x, t, wpr + 2)).times(0.5); + + if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r.d)).slice(0, wpr)) { + n = n.slice(wpr - 3, wpr + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or + // 4999, i.e. approaching a rounding boundary, continue the iteration. + if (s == wpr && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the exact result as the + // nines may infinitely repeat. + round(t, pr + 1, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } else if (n != '9999') { + break; + } + + wpr += 4; + } + } + + external = true; + + return round(r, pr); + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to + * `precision` significant digits. + * + */ + P.times = P.mul = function (y) { + var carry, e, i, k, r, rL, t, xdL, ydL, + x = this, + Ctor = x.constructor, + xd = x.d, + yd = (y = new Ctor(y)).d; + + // Return 0 if either is 0. + if (!x.s || !y.s) return new Ctor(0); + + y.s *= x.s; + e = x.e + y.e; + xdL = xd.length; + ydL = yd.length; + + // Ensure xd points to the longer array. + if (xdL < ydL) { + r = xd; + xd = yd; + yd = r; + rL = xdL; + xdL = ydL; + ydL = rL; + } + + // Initialise the result array with zeros. + r = []; + rL = xdL + ydL; + for (i = rL; i--;) r.push(0); + + // Multiply! + for (i = ydL; --i >= 0;) { + carry = 0; + for (k = xdL + i; k > i;) { + t = r[k] + yd[i] * xd[k - i - 1] + carry; + r[k--] = t % BASE | 0; + carry = t / BASE | 0; + } + + r[k] = (r[k] + carry) % BASE | 0; + } + + // Remove trailing zeros. + for (; !r[--rL];) r.pop(); + + if (carry) ++e; + else r.shift(); + + y.d = r; + y.e = e; + + return external ? round(y, Ctor.precision) : y; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` + * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. + * + * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toDecimalPlaces = P.todp = function (dp, rm) { + var x = this, + Ctor = x.constructor; + + x = new Ctor(x); + if (dp === void 0) return x; + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + return round(x, dp + getBase10Exponent(x) + 1, rm); + }; + + + /* + * Return a string representing the value of this Decimal in exponential notation rounded to + * `dp` fixed decimal places using rounding mode `rounding`. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toExponential = function (dp, rm) { + var str, + x = this, + Ctor = x.constructor; + + if (dp === void 0) { + str = toString(x, true); + } else { + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = round(new Ctor(x), dp + 1, rm); + str = toString(x, true, dp + 1); + } + + return str; + }; + + + /* + * Return a string representing the value of this Decimal in normal (fixed-point) notation to + * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is + * omitted. + * + * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. + * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. + * (-0).toFixed(3) is '0.000'. + * (-0.5).toFixed(0) is '-0'. + * + */ + P.toFixed = function (dp, rm) { + var str, y, + x = this, + Ctor = x.constructor; + + if (dp === void 0) return toString(x); + + checkInt32(dp, 0, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + y = round(new Ctor(x), dp + getBase10Exponent(x) + 1, rm); + str = toString(y.abs(), false, dp + getBase10Exponent(y) + 1); + + // To determine whether to add the minus sign look at the value before it was rounded, + // i.e. look at `x` rather than `y`. + return x.isneg() && !x.isZero() ? '-' + str : str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using + * rounding mode `rounding`. + * + */ + P.toInteger = P.toint = function () { + var x = this, + Ctor = x.constructor; + return round(new Ctor(x), getBase10Exponent(x) + 1, Ctor.rounding); + }; + + + /* + * Return the value of this Decimal converted to a number primitive. + * + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, + * truncated to `precision` significant digits. + * + * For non-integer or very large exponents pow(x, y) is calculated using + * + * x^y = exp(y*ln(x)) + * + * The maximum error is 1 ulp (unit in last place). + * + * y {number|string|Decimal} The power to which to raise this Decimal. + * + */ + P.toPower = P.pow = function (y) { + var e, k, pr, r, sign, yIsInt, + x = this, + Ctor = x.constructor, + guard = 12, + yn = +(y = new Ctor(y)); + + // pow(x, 0) = 1 + if (!y.s) return new Ctor(ONE); + + x = new Ctor(x); + + // pow(0, y > 0) = 0 + // pow(0, y < 0) = Infinity + if (!x.s) { + if (y.s < 1) throw Error(decimalError + 'Infinity'); + return x; + } + + // pow(1, y) = 1 + if (x.eq(ONE)) return x; + + pr = Ctor.precision; + + // pow(x, 1) = x + if (y.eq(ONE)) return round(x, pr); + + e = y.e; + k = y.d.length - 1; + yIsInt = e >= k; + sign = x.s; + + if (!yIsInt) { + + // pow(x < 0, y non-integer) = NaN + if (sign < 0) throw Error(decimalError + 'NaN'); + + // If y is a small integer use the 'exponentiation by squaring' algorithm. + } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { + r = new Ctor(ONE); + + // Max k of 9007199254740991 takes 53 loop iterations. + // Maximum digits array length; leaves [28, 34] guard digits. + e = Math.ceil(pr / LOG_BASE + 4); + + external = false; + + for (;;) { + if (k % 2) { + r = r.times(x); + truncate(r.d, e); + } + + k = mathfloor(k / 2); + if (k === 0) break; + + x = x.times(x); + truncate(x.d, e); + } + + external = true; + + return y.s < 0 ? new Ctor(ONE).div(r) : round(r, pr); + } + + // Result is negative if x is negative and the last digit of integer y is odd. + sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1; + + x.s = 1; + external = false; + r = y.times(ln(x, pr + guard)); + external = true; + r = exp(r); + r.s = sign; + + return r; + }; + + + /* + * Return a string representing the value of this Decimal rounded to `sd` significant digits + * using rounding mode `rounding`. + * + * Return exponential notation if `sd` is less than the number of digits necessary to represent + * the integer part of the value in normal notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toPrecision = function (sd, rm) { + var e, str, + x = this, + Ctor = x.constructor; + + if (sd === void 0) { + e = getBase10Exponent(x); + str = toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos); + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + + x = round(new Ctor(x), sd, rm); + e = getBase10Exponent(x); + str = toString(x, sd <= e || e <= Ctor.toExpNeg, sd); + } + + return str; + }; + + + /* + * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` + * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if + * omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + */ + P.toSignificantDigits = P.tosd = function (sd, rm) { + var x = this, + Ctor = x.constructor; + + if (sd === void 0) { + sd = Ctor.precision; + rm = Ctor.rounding; + } else { + checkInt32(sd, 1, MAX_DIGITS); + + if (rm === void 0) rm = Ctor.rounding; + else checkInt32(rm, 0, 8); + } + + return round(new Ctor(x), sd, rm); + }; + + + /* + * Return a string representing the value of this Decimal. + * + * Return exponential notation if this Decimal has a positive exponent equal to or greater than + * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. + * + */ + P.toString = P.valueOf = P.val = P.toJSON = P[Symbol.for('nodejs.util.inspect.custom')] = function () { + var x = this, + e = getBase10Exponent(x), + Ctor = x.constructor; + + return toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos); + }; + + + // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. + + + /* + * add P.minus, P.plus + * checkInt32 P.todp, P.toExponential, P.toFixed, P.toPrecision, P.tosd + * digitsToString P.log, P.sqrt, P.pow, toString, exp, ln + * divide P.div, P.idiv, P.log, P.mod, P.sqrt, exp, ln + * exp P.exp, P.pow + * getBase10Exponent P.exponent, P.sd, P.toint, P.sqrt, P.todp, P.toFixed, P.toPrecision, + * P.toString, divide, round, toString, exp, ln + * getLn10 P.log, ln + * getZeroString digitsToString, toString + * ln P.log, P.ln, P.pow, exp + * parseDecimal Decimal + * round P.abs, P.idiv, P.log, P.minus, P.mod, P.neg, P.plus, P.toint, P.sqrt, + * P.times, P.todp, P.toExponential, P.toFixed, P.pow, P.toPrecision, P.tosd, + * divide, getLn10, exp, ln + * subtract P.minus, P.plus + * toString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf + * truncate P.pow + * + * Throws: P.log, P.mod, P.sd, P.sqrt, P.pow, checkInt32, divide, round, + * getLn10, exp, ln, parseDecimal, Decimal, config + */ + + + function add(x, y) { + var carry, d, e, i, k, len, xd, yd, + Ctor = x.constructor, + pr = Ctor.precision; + + // If either is zero... + if (!x.s || !y.s) { + + // Return x if y is zero. + // Return y if y is non-zero. + if (!y.s) y = new Ctor(x); + return external ? round(y, pr) : y; + } + + xd = x.d; + yd = y.d; + + // x and y are finite, non-zero numbers with the same sign. + + k = x.e; + e = y.e; + xd = xd.slice(); + i = k - e; + + // If base 1e7 exponents differ... + if (i) { + if (i < 0) { + d = xd; + i = -i; + len = yd.length; + } else { + d = yd; + e = k; + len = xd.length; + } + + // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. + k = Math.ceil(pr / LOG_BASE); + len = k > len ? k + 1 : len + 1; + + if (i > len) { + i = len; + d.length = 1; + } + + // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. + d.reverse(); + for (; i--;) d.push(0); + d.reverse(); + } + + len = xd.length; + i = yd.length; + + // If yd is longer than xd, swap xd and yd so xd points to the longer array. + if (len - i < 0) { + i = len; + d = yd; + yd = xd; + xd = d; + } + + // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. + for (carry = 0; i;) { + carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; + xd[i] %= BASE; + } + + if (carry) { + xd.unshift(carry); + ++e; + } + + // Remove trailing zeros. + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + for (len = xd.length; xd[--len] == 0;) xd.pop(); + + y.d = xd; + y.e = e; + + return external ? round(y, pr) : y; + } + + + function checkInt32(i, min, max) { + if (i !== ~~i || i < min || i > max) { + throw Error(invalidArgument + i); + } + } + + + function digitsToString(d) { + var i, k, ws, + indexOfLastWord = d.length - 1, + str = '', + w = d[0]; + + if (indexOfLastWord > 0) { + str += w; + for (i = 1; i < indexOfLastWord; i++) { + ws = d[i] + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + str += ws; + } + + w = d[i]; + ws = w + ''; + k = LOG_BASE - ws.length; + if (k) str += getZeroString(k); + } else if (w === 0) { + return '0'; + } + + // Remove trailing zeros of last w. + for (; w % 10 === 0;) w /= 10; + + return str + w; + } + + + var divide = (function () { + + // Assumes non-zero x and k, and hence non-zero result. + function multiplyInteger(x, k) { + var temp, + carry = 0, + i = x.length; + + for (x = x.slice(); i--;) { + temp = x[i] * k + carry; + x[i] = temp % BASE | 0; + carry = temp / BASE | 0; + } + + if (carry) x.unshift(carry); + + return x; + } + + function compare(a, b, aL, bL) { + var i, r; + + if (aL != bL) { + r = aL > bL ? 1 : -1; + } else { + for (i = r = 0; i < aL; i++) { + if (a[i] != b[i]) { + r = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return r; + } + + function subtract(a, b, aL) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * BASE + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1;) a.shift(); + } + + return function (x, y, pr, dp) { + var cmp, e, i, k, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz, + Ctor = x.constructor, + sign = x.s == y.s ? 1 : -1, + xd = x.d, + yd = y.d; + + // Either 0? + if (!x.s) return new Ctor(x); + if (!y.s) throw Error(decimalError + 'Division by zero'); + + e = x.e - y.e; + yL = yd.length; + xL = xd.length; + q = new Ctor(sign); + qd = q.d = []; + + // Result exponent may be one less than e. + for (i = 0; yd[i] == (xd[i] || 0); ) ++i; + if (yd[i] > (xd[i] || 0)) --e; + + if (pr == null) { + sd = pr = Ctor.precision; + } else if (dp) { + sd = pr + (getBase10Exponent(x) - getBase10Exponent(y)) + 1; + } else { + sd = pr; + } + + if (sd < 0) return new Ctor(0); + + // Convert precision in number of base 10 digits to base 1e7 digits. + sd = sd / LOG_BASE + 2 | 0; + i = 0; + + // divisor < 1e7 + if (yL == 1) { + k = 0; + yd = yd[0]; + sd++; + + // k is the carry. + for (; (i < xL || k) && sd--; i++) { + t = k * BASE + (xd[i] || 0); + qd[i] = t / yd | 0; + k = t % yd | 0; + } + + // divisor >= 1e7 + } else { + + // Normalise xd and yd so highest order digit of yd is >= BASE/2 + k = BASE / (yd[0] + 1) | 0; + + if (k > 1) { + yd = multiplyInteger(yd, k); + xd = multiplyInteger(xd, k); + yL = yd.length; + xL = xd.length; + } + + xi = yL; + rem = xd.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL;) rem[remL++] = 0; + + yz = yd.slice(); + yz.unshift(0); + yd0 = yd[0]; + + if (yd[1] >= BASE / 2) ++yd0; + + do { + k = 0; + + // Compare divisor and remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, k. + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * BASE + (rem[1] || 0); + + // k will be how many times the divisor goes into the current remainder. + k = rem0 / yd0 | 0; + + // Algorithm: + // 1. product = divisor * trial digit (k) + // 2. if product > remainder: product -= divisor, k-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, k++ + + if (k > 1) { + if (k >= BASE) k = BASE - 1; + + // product = divisor * trial digit. + prod = multiplyInteger(yd, k); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + cmp = compare(prod, rem, prodL, remL); + + // product > remainder. + if (cmp == 1) { + k--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yd, prodL); + } + } else { + + // cmp is -1. + // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 + // to avoid it. If k is 1 there is a need to compare yd and rem again below. + if (k == 0) cmp = k = 1; + prod = yd.slice(); + } + + prodL = prod.length; + if (prodL < remL) prod.unshift(0); + + // Subtract product from remainder. + subtract(rem, prod, remL); + + // If product was < previous remainder. + if (cmp == -1) { + remL = rem.length; + + // Compare divisor and new remainder. + cmp = compare(yd, rem, yL, remL); + + // If divisor < new remainder, subtract divisor from remainder. + if (cmp < 1) { + k++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yd, remL); + } + } + + remL = rem.length; + } else if (cmp === 0) { + k++; + rem = [0]; + } // if cmp === 1, k will be 0 + + // Add the next digit, k, to the result array. + qd[i++] = k; + + // Update the remainder. + if (cmp && rem[0]) { + rem[remL++] = xd[xi] || 0; + } else { + rem = [xd[xi]]; + remL = 1; + } + + } while ((xi++ < xL || rem[0] !== void 0) && sd--); + } + + // Leading zero? + if (!qd[0]) qd.shift(); + + q.e = e; + + return round(q, dp ? pr + getBase10Exponent(q) + 1 : pr); + }; + })(); + + + /* + * Return a new Decimal whose value is the natural exponential of `x` truncated to `sd` + * significant digits. + * + * Taylor/Maclaurin series. + * + * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... + * + * Argument reduction: + * Repeat x = x / 32, k += 5, until |x| < 0.1 + * exp(x) = exp(x / 2^k)^(2^k) + * + * Previously, the argument was initially reduced by + * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) + * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was + * found to be slower than just dividing repeatedly by 32 as above. + * + * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) + * + * exp(x) is non-terminating for any finite, non-zero x. + * + */ + function exp(x, sd) { + var denominator, guard, pow, sum, t, wpr, + i = 0, + k = 0, + Ctor = x.constructor, + pr = Ctor.precision; + + if (getBase10Exponent(x) > 16) throw Error(exponentOutOfRange + getBase10Exponent(x)); + + // exp(0) = 1 + if (!x.s) return new Ctor(ONE); + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + t = new Ctor(0.03125); + + while (x.abs().gte(0.1)) { + x = x.times(t); // x = x / 2^5 + k += 5; + } + + // Estimate the precision increase necessary to ensure the first 4 rounding digits are correct. + guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; + wpr += guard; + denominator = pow = sum = new Ctor(ONE); + Ctor.precision = wpr; + + for (;;) { + pow = round(pow.times(x), wpr); + denominator = denominator.times(++i); + t = sum.plus(divide(pow, denominator, wpr)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + while (k--) sum = round(sum.times(sum), wpr); + Ctor.precision = pr; + return sd == null ? (external = true, round(sum, pr)) : sum; + } + + sum = t; + } + } + + + // Calculate the base 10 exponent from the base 1e7 exponent. + function getBase10Exponent(x) { + var e = x.e * LOG_BASE, + w = x.d[0]; + + // Add the number of digits of the first word of the digits array. + for (; w >= 10; w /= 10) e++; + return e; + } + + + function getLn10(Ctor, sd, pr) { + + if (sd > Ctor.LN10.sd()) { + + + // Reset global state in case the exception is caught. + external = true; + if (pr) Ctor.precision = pr; + throw Error(decimalError + 'LN10 precision limit exceeded'); + } + + return round(new Ctor(Ctor.LN10), sd); + } + + + function getZeroString(k) { + var zs = ''; + for (; k--;) zs += '0'; + return zs; + } + + + /* + * Return a new Decimal whose value is the natural logarithm of `x` truncated to `sd` significant + * digits. + * + * ln(n) is non-terminating (n != 1) + * + */ + function ln(y, sd) { + var c, c0, denominator, e, numerator, sum, t, wpr, x2, + n = 1, + guard = 10, + x = y, + xd = x.d, + Ctor = x.constructor, + pr = Ctor.precision; + + // ln(-x) = NaN + // ln(0) = -Infinity + if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity')); + + // ln(1) = 0 + if (x.eq(ONE)) return new Ctor(0); + + if (sd == null) { + external = false; + wpr = pr; + } else { + wpr = sd; + } + + if (x.eq(10)) { + if (sd == null) external = true; + return getLn10(Ctor, wpr); + } + + wpr += guard; + Ctor.precision = wpr; + c = digitsToString(xd); + c0 = c.charAt(0); + e = getBase10Exponent(x); + + if (Math.abs(e) < 1.5e15) { + + // Argument reduction. + // The series converges faster the closer the argument is to 1, so using + // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b + // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, + // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can + // later be divided by this number, then separate out the power of 10 using + // ln(a*10^b) = ln(a) + b*ln(10). + + // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). + //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { + // max n is 6 (gives 0.7 - 1.3) + while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { + x = x.times(y); + c = digitsToString(x.d); + c0 = c.charAt(0); + n++; + } + + e = getBase10Exponent(x); + + if (c0 > 1) { + x = new Ctor('0.' + c); + e++; + } else { + x = new Ctor(c0 + '.' + c.slice(1)); + } + } else { + + // The argument reduction method above may result in overflow if the argument y is a massive + // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this + // function using ln(x*10^e) = ln(x) + e*ln(10). + t = getLn10(Ctor, wpr + 2, pr).times(e + ''); + x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); + + Ctor.precision = pr; + return sd == null ? (external = true, round(x, pr)) : x; + } + + // x is reduced to a value near 1. + + // Taylor series. + // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) + // where x = (y - 1)/(y + 1) (|x| < 1) + sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr); + x2 = round(x.times(x), wpr); + denominator = 3; + + for (;;) { + numerator = round(numerator.times(x2), wpr); + t = sum.plus(divide(numerator, new Ctor(denominator), wpr)); + + if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { + sum = sum.times(2); + + // Reverse the argument reduction. + if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); + sum = divide(sum, new Ctor(n), wpr); + + Ctor.precision = pr; + return sd == null ? (external = true, round(sum, pr)) : sum; + } + + sum = t; + denominator += 2; + } + } + + + /* + * Parse the value of a new Decimal `x` from string `str`. + */ + function parseDecimal(x, str) { + var e, i, len; + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48;) ++i; + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(len - 1) === 48;) --len; + str = str.slice(i, len); + + if (str) { + len -= i; + e = e - i - 1; + x.e = mathfloor(e / LOG_BASE); + x.d = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first word of the digits array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.d.push(+str.slice(0, i)); + for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--;) str += '0'; + x.d.push(+str); + + if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e); + } else { + + // Zero. + x.s = 0; + x.e = 0; + x.d = [0]; + } + + return x; + } + + + /* + * Round `x` to `sd` significant digits, using rounding mode `rm` if present (truncate otherwise). + */ + function round(x, sd, rm) { + var i, j, k, n, rd, doRound, w, xdi, + xd = x.d; + + // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. + // w: the word of xd which contains the rounding digit, a base 1e7 number. + // xdi: the index of w within xd. + // n: the number of digits of w. + // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if + // they had leading zeros) + // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). + + // Get the length of the first word of the digits array xd. + for (n = 1, k = xd[0]; k >= 10; k /= 10) n++; + i = sd - n; + + // Is the rounding digit in the first word of xd? + if (i < 0) { + i += LOG_BASE; + j = sd; + w = xd[xdi = 0]; + } else { + xdi = Math.ceil((i + 1) / LOG_BASE); + k = xd.length; + if (xdi >= k) return x; + w = k = xd[xdi]; + + // Get the number of digits of w. + for (n = 1; k >= 10; k /= 10) n++; + + // Get the index of rd within w. + i %= LOG_BASE; + + // Get the index of rd within w, adjusted for leading zeros. + // The number of leading zeros of w is given by LOG_BASE - n. + j = i - LOG_BASE + n; + } + + if (rm !== void 0) { + k = mathpow(10, n - j - 1); + + // Get the rounding digit at index j of w. + rd = w / k % 10 | 0; + + // Are there any non-zero digits after the rounding digit? + doRound = sd < 0 || xd[xdi + 1] !== void 0 || w % k; + + // The expression `w % mathpow(10, n - j - 1)` returns all the digits of w to the right of the + // digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression will give + // 714. + + doRound = rm < 4 + ? (rd || doRound) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || doRound || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? w / mathpow(10, n - j) : 0 : xd[xdi - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + } + + if (sd < 1 || !xd[0]) { + if (doRound) { + k = getBase10Exponent(x); + xd.length = 1; + + // Convert sd to decimal places. + sd = sd - k - 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); + x.e = mathfloor(-sd / LOG_BASE) || 0; + } else { + xd.length = 1; + + // Zero. + xd[0] = x.e = x.s = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xd.length = xdi; + k = 1; + xdi--; + } else { + xd.length = xdi + 1; + k = mathpow(10, LOG_BASE - i); + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of w. + xd[xdi] = j > 0 ? (w / mathpow(10, n - j) % mathpow(10, j) | 0) * k : 0; + } + + if (doRound) { + for (;;) { + + // Is the digit to be rounded up in the first word of xd? + if (xdi == 0) { + if ((xd[0] += k) == BASE) { + xd[0] = 1; + ++x.e; + } + + break; + } else { + xd[xdi] += k; + if (xd[xdi] != BASE) break; + xd[xdi--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xd.length; xd[--i] === 0;) xd.pop(); + + if (external && (x.e > MAX_E || x.e < -MAX_E)) { + throw Error(exponentOutOfRange + getBase10Exponent(x)); + } + + return x; + } + + + function subtract(x, y) { + var d, e, i, j, k, len, xd, xe, xLTy, yd, + Ctor = x.constructor, + pr = Ctor.precision; + + // Return y negated if x is zero. + // Return x if y is zero and x is non-zero. + if (!x.s || !y.s) { + if (y.s) y.s = -y.s; + else y = new Ctor(x); + return external ? round(y, pr) : y; + } + + xd = x.d; + yd = y.d; + + // x and y are non-zero numbers with the same sign. + + e = y.e; + xe = x.e; + xd = xd.slice(); + k = xe - e; + + // If exponents differ... + if (k) { + xLTy = k < 0; + + if (xLTy) { + d = xd; + k = -k; + len = yd.length; + } else { + d = yd; + e = xe; + len = xd.length; + } + + // Numbers with massively different exponents would result in a very high number of zeros + // needing to be prepended, but this can be avoided while still ensuring correct rounding by + // limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. + i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; + + if (k > i) { + k = i; + d.length = 1; + } + + // Prepend zeros to equalise exponents. + d.reverse(); + for (i = k; i--;) d.push(0); + d.reverse(); + + // Base 1e7 exponents equal. + } else { + + // Check digits to determine which is the bigger number. + + i = xd.length; + len = yd.length; + xLTy = i < len; + if (xLTy) len = i; + + for (i = 0; i < len; i++) { + if (xd[i] != yd[i]) { + xLTy = xd[i] < yd[i]; + break; + } + } + + k = 0; + } + + if (xLTy) { + d = xd; + xd = yd; + yd = d; + y.s = -y.s; + } + + len = xd.length; + + // Append zeros to xd if shorter. + // Don't add zeros to yd if shorter as subtraction only needs to start at yd length. + for (i = yd.length - len; i > 0; --i) xd[len++] = 0; + + // Subtract yd from xd. + for (i = yd.length; i > k;) { + if (xd[--i] < yd[i]) { + for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; + --xd[j]; + xd[i] += BASE; + } + + xd[i] -= yd[i]; + } + + // Remove trailing zeros. + for (; xd[--len] === 0;) xd.pop(); + + // Remove leading zeros and adjust exponent accordingly. + for (; xd[0] === 0; xd.shift()) --e; + + // Zero? + if (!xd[0]) return new Ctor(0); + + y.d = xd; + y.e = e; + + //return external && xd.length >= pr / LOG_BASE ? round(y, pr) : y; + return external ? round(y, pr) : y; + } + + + function toString(x, isExp, sd) { + var k, + e = getBase10Exponent(x), + str = digitsToString(x.d), + len = str.length; + + if (isExp) { + if (sd && (k = sd - len) > 0) { + str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); + } else if (len > 1) { + str = str.charAt(0) + '.' + str.slice(1); + } + + str = str + (e < 0 ? 'e' : 'e+') + e; + } else if (e < 0) { + str = '0.' + getZeroString(-e - 1) + str; + if (sd && (k = sd - len) > 0) str += getZeroString(k); + } else if (e >= len) { + str += getZeroString(e + 1 - len); + if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); + } else { + if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); + if (sd && (k = sd - len) > 0) { + if (e + 1 === len) str += '.'; + str += getZeroString(k); + } + } + + return x.s < 0 ? '-' + str : str; + } + + + // Does not strip trailing zeros. + function truncate(arr, len) { + if (arr.length > len) { + arr.length = len; + return true; + } + } + + + // Decimal methods + + + /* + * clone + * config/set + */ + + + /* + * Create and return a Decimal constructor with the same configuration properties as this Decimal + * constructor. + * + */ + function clone(obj) { + var i, p, ps; + + /* + * The Decimal constructor and exported function. + * Return a new Decimal instance. + * + * value {number|string|Decimal} A numeric value. + * + */ + function Decimal(value) { + var x = this; + + // Decimal called without new. + if (!(x instanceof Decimal)) return new Decimal(value); + + // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor + // which points to Object. + x.constructor = Decimal; + + // Duplicate. + if (value instanceof Decimal) { + x.s = value.s; + x.e = value.e; + x.d = (value = value.d) ? value.slice() : value; + return; + } + + if (typeof value === 'number') { + + // Reject Infinity/NaN. + if (value * 0 !== 0) { + throw Error(invalidArgument + value); + } + + if (value > 0) { + x.s = 1; + } else if (value < 0) { + value = -value; + x.s = -1; + } else { + x.s = 0; + x.e = 0; + x.d = [0]; + return; + } + + // Fast path for small integers. + if (value === ~~value && value < 1e7) { + x.e = 0; + x.d = [value]; + return; + } + + return parseDecimal(x, value.toString()); + } else if (typeof value !== 'string') { + throw Error(invalidArgument + value); + } + + // Minus sign? + if (value.charCodeAt(0) === 45) { + value = value.slice(1); + x.s = -1; + } else { + x.s = 1; + } + + if (isDecimal.test(value)) parseDecimal(x, value); + else throw Error(invalidArgument + value); + } + + Decimal.prototype = P; + + Decimal.ROUND_UP = 0; + Decimal.ROUND_DOWN = 1; + Decimal.ROUND_CEIL = 2; + Decimal.ROUND_FLOOR = 3; + Decimal.ROUND_HALF_UP = 4; + Decimal.ROUND_HALF_DOWN = 5; + Decimal.ROUND_HALF_EVEN = 6; + Decimal.ROUND_HALF_CEIL = 7; + Decimal.ROUND_HALF_FLOOR = 8; + + Decimal.clone = clone; + Decimal.config = Decimal.set = config; + + if (obj === void 0) obj = {}; + if (obj) { + ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'LN10']; + for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; + } + + Decimal.config(obj); + + return Decimal; + } + + + /* + * Configure global settings for a Decimal constructor. + * + * `obj` is an object with one or more of the following properties, + * + * precision {number} + * rounding {number} + * toExpNeg {number} + * toExpPos {number} + * + * E.g. Decimal.config({ precision: 20, rounding: 4 }) + * + */ + function config(obj) { + if (!obj || typeof obj !== 'object') { + throw Error(decimalError + 'Object expected'); + } + var i, p, v, + ps = [ + 'precision', 1, MAX_DIGITS, + 'rounding', 0, 8, + 'toExpNeg', -1 / 0, 0, + 'toExpPos', 0, 1 / 0 + ]; + + for (i = 0; i < ps.length; i += 3) { + if ((v = obj[p = ps[i]]) !== void 0) { + if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; + else throw Error(invalidArgument + p + ': ' + v); + } + } + + if ((v = obj[p = 'LN10']) !== void 0) { + if (v == Math.LN10) this[p] = new this(v); + else throw Error(invalidArgument + p + ': ' + v); + } + + return this; + } + + + // Create and configure initial Decimal constructor. + var Decimal = clone(defaults); + + // Internal constant. + ONE = new Decimal(1); + + var Decimal$1 = Decimal; + + var CurrencyCodes; + (function (CurrencyCodes) { + CurrencyCodes["AED"] = "aed"; + CurrencyCodes["AFN"] = "afn"; + CurrencyCodes["ALL"] = "all"; + CurrencyCodes["AMD"] = "amd"; + CurrencyCodes["ANG"] = "ang"; + CurrencyCodes["AOA"] = "aoa"; + CurrencyCodes["ARS"] = "ars"; + CurrencyCodes["AUD"] = "aud"; + CurrencyCodes["AWG"] = "awg"; + CurrencyCodes["AZN"] = "azn"; + CurrencyCodes["BAM"] = "bam"; + CurrencyCodes["BBD"] = "bbd"; + CurrencyCodes["BDT"] = "bdt"; + CurrencyCodes["BGN"] = "bgn"; + CurrencyCodes["BHD"] = "bhd"; + CurrencyCodes["BIF"] = "bif"; + CurrencyCodes["BMD"] = "bmd"; + CurrencyCodes["BND"] = "bnd"; + CurrencyCodes["BOB"] = "bob"; + CurrencyCodes["BOV"] = "bov"; + CurrencyCodes["BRL"] = "brl"; + CurrencyCodes["BSD"] = "bsd"; + CurrencyCodes["BTN"] = "btn"; + CurrencyCodes["BWP"] = "bwp"; + CurrencyCodes["BYN"] = "byn"; + CurrencyCodes["BYR"] = "byr"; + CurrencyCodes["BZD"] = "bzd"; + CurrencyCodes["CAD"] = "cad"; + CurrencyCodes["CDF"] = "cdf"; + CurrencyCodes["CHE"] = "che"; + CurrencyCodes["CHF"] = "chf"; + CurrencyCodes["CHW"] = "chw"; + CurrencyCodes["CLF"] = "clf"; + CurrencyCodes["CLP"] = "clp"; + CurrencyCodes["CNY"] = "cny"; + CurrencyCodes["COP"] = "cop"; + CurrencyCodes["COU"] = "cou"; + CurrencyCodes["CRC"] = "crc"; + CurrencyCodes["CUC"] = "cuc"; + CurrencyCodes["CUP"] = "cup"; + CurrencyCodes["CVE"] = "cve"; + CurrencyCodes["CZK"] = "czk"; + CurrencyCodes["DJF"] = "djf"; + CurrencyCodes["DKK"] = "dkk"; + CurrencyCodes["DOP"] = "dop"; + CurrencyCodes["DZD"] = "dzd"; + CurrencyCodes["EGP"] = "egp"; + CurrencyCodes["ERN"] = "ern"; + CurrencyCodes["ETB"] = "etb"; + CurrencyCodes["EUR"] = "eur"; + CurrencyCodes["FJD"] = "fjd"; + CurrencyCodes["FKP"] = "fkp"; + CurrencyCodes["GBP"] = "gbp"; + CurrencyCodes["GEL"] = "gel"; + CurrencyCodes["GHS"] = "ghs"; + CurrencyCodes["GIP"] = "gip"; + CurrencyCodes["GMD"] = "gmd"; + CurrencyCodes["GNF"] = "gnf"; + CurrencyCodes["GTQ"] = "gtq"; + CurrencyCodes["GYD"] = "gyd"; + CurrencyCodes["HKD"] = "hkd"; + CurrencyCodes["HNL"] = "hnl"; + CurrencyCodes["HRK"] = "hrk"; + CurrencyCodes["HTG"] = "htg"; + CurrencyCodes["HUF"] = "huf"; + CurrencyCodes["IDR"] = "idr"; + CurrencyCodes["ILS"] = "ils"; + CurrencyCodes["INR"] = "inr"; + CurrencyCodes["IQD"] = "iqd"; + CurrencyCodes["IRR"] = "irr"; + CurrencyCodes["ISK"] = "isk"; + CurrencyCodes["JMD"] = "jmd"; + CurrencyCodes["JOD"] = "jod"; + CurrencyCodes["JPY"] = "jpy"; + CurrencyCodes["KES"] = "kes"; + CurrencyCodes["KGS"] = "kgs"; + CurrencyCodes["KHR"] = "khr"; + CurrencyCodes["KMF"] = "kmf"; + CurrencyCodes["KPW"] = "kpw"; + CurrencyCodes["KRW"] = "krw"; + CurrencyCodes["KWD"] = "kwd"; + CurrencyCodes["KYD"] = "kyd"; + CurrencyCodes["KZT"] = "kzt"; + CurrencyCodes["LAK"] = "lak"; + CurrencyCodes["LBP"] = "lbp"; + CurrencyCodes["LKR"] = "lkr"; + CurrencyCodes["LRD"] = "lrd"; + CurrencyCodes["LSL"] = "lsl"; + CurrencyCodes["LTL"] = "ltl"; + CurrencyCodes["LVL"] = "lvl"; + CurrencyCodes["LYD"] = "lyd"; + CurrencyCodes["MAD"] = "mad"; + CurrencyCodes["MDL"] = "mdl"; + CurrencyCodes["MGA"] = "mga"; + CurrencyCodes["MKD"] = "mkd"; + CurrencyCodes["MMK"] = "mmk"; + CurrencyCodes["MNT"] = "mnt"; + CurrencyCodes["MOP"] = "mop"; + CurrencyCodes["MRO"] = "mro"; + CurrencyCodes["MUR"] = "mur"; + CurrencyCodes["MVR"] = "mvr"; + CurrencyCodes["MWK"] = "mwk"; + CurrencyCodes["MXN"] = "mxn"; + CurrencyCodes["MXV"] = "mxv"; + CurrencyCodes["MYR"] = "myr"; + CurrencyCodes["MZN"] = "mzn"; + CurrencyCodes["NAD"] = "nad"; + CurrencyCodes["NGN"] = "ngn"; + CurrencyCodes["NIO"] = "nio"; + CurrencyCodes["NOK"] = "nok"; + CurrencyCodes["NPR"] = "npr"; + CurrencyCodes["NZD"] = "nzd"; + CurrencyCodes["OMR"] = "omr"; + CurrencyCodes["PAB"] = "pab"; + CurrencyCodes["PEN"] = "pen"; + CurrencyCodes["PGK"] = "pgk"; + CurrencyCodes["PHP"] = "php"; + CurrencyCodes["PKR"] = "pkr"; + CurrencyCodes["PLN"] = "pln"; + CurrencyCodes["PYG"] = "pyg"; + CurrencyCodes["QAR"] = "qar"; + CurrencyCodes["RON"] = "ron"; + CurrencyCodes["RSD"] = "rsd"; + CurrencyCodes["RUB"] = "rub"; + CurrencyCodes["RWF"] = "rwf"; + CurrencyCodes["SAR"] = "sar"; + CurrencyCodes["SBD"] = "sbd"; + CurrencyCodes["SCR"] = "scr"; + CurrencyCodes["SDG"] = "sdg"; + CurrencyCodes["SEK"] = "sek"; + CurrencyCodes["SGD"] = "sgd"; + CurrencyCodes["SHP"] = "shp"; + CurrencyCodes["SLL"] = "sll"; + CurrencyCodes["SOS"] = "sos"; + CurrencyCodes["SRD"] = "srd"; + CurrencyCodes["SSP"] = "ssp"; + CurrencyCodes["STD"] = "std"; + CurrencyCodes["SVC"] = "svc"; + CurrencyCodes["SYP"] = "syp"; + CurrencyCodes["SZL"] = "szl"; + CurrencyCodes["THB"] = "thb"; + CurrencyCodes["TJS"] = "tjs"; + CurrencyCodes["TMT"] = "tmt"; + CurrencyCodes["TND"] = "tnd"; + CurrencyCodes["TOP"] = "top"; + CurrencyCodes["TRY"] = "try"; + CurrencyCodes["TTD"] = "ttd"; + CurrencyCodes["TWD"] = "twd"; + CurrencyCodes["TZS"] = "tzs"; + CurrencyCodes["UAH"] = "uah"; + CurrencyCodes["UGX"] = "ugx"; + CurrencyCodes["USD"] = "usd"; + CurrencyCodes["USN"] = "usn"; + CurrencyCodes["USS"] = "uss"; + CurrencyCodes["UYI"] = "uyi"; + CurrencyCodes["UYU"] = "uyu"; + CurrencyCodes["UZS"] = "uzs"; + CurrencyCodes["VEF"] = "vef"; + CurrencyCodes["VND"] = "vnd"; + CurrencyCodes["VUV"] = "vuv"; + CurrencyCodes["WST"] = "wst"; + CurrencyCodes["XAF"] = "xaf"; + CurrencyCodes["XAG"] = "xag"; + CurrencyCodes["XAU"] = "xau"; + CurrencyCodes["XBA"] = "xba"; + CurrencyCodes["XBB"] = "xbb"; + CurrencyCodes["XBC"] = "xbc"; + CurrencyCodes["XBD"] = "xbd"; + CurrencyCodes["XCD"] = "xcd"; + CurrencyCodes["XDR"] = "xdr"; + CurrencyCodes["XFU"] = "xfu"; + CurrencyCodes["XOF"] = "xof"; + CurrencyCodes["XPD"] = "xpd"; + CurrencyCodes["XPF"] = "xpf"; + CurrencyCodes["XPT"] = "xpt"; + CurrencyCodes["XSU"] = "xsu"; + CurrencyCodes["XTS"] = "xts"; + CurrencyCodes["XUA"] = "xua"; + CurrencyCodes["YER"] = "yer"; + CurrencyCodes["ZAR"] = "zar"; + CurrencyCodes["ZMW"] = "zmw"; + CurrencyCodes["ZWL"] = "zwl"; + })(CurrencyCodes || (CurrencyCodes = {})); + const CurrencyExponents = { + [CurrencyCodes.AED]: 2, + [CurrencyCodes.AFN]: 2, + [CurrencyCodes.ALL]: 2, + [CurrencyCodes.AMD]: 2, + [CurrencyCodes.ANG]: 2, + [CurrencyCodes.AOA]: 2, + [CurrencyCodes.ARS]: 2, + [CurrencyCodes.AUD]: 2, + [CurrencyCodes.AWG]: 2, + [CurrencyCodes.AZN]: 2, + [CurrencyCodes.BAM]: 2, + [CurrencyCodes.BBD]: 2, + [CurrencyCodes.BDT]: 2, + [CurrencyCodes.BGN]: 2, + [CurrencyCodes.BHD]: 3, + [CurrencyCodes.BIF]: 0, + [CurrencyCodes.BMD]: 2, + [CurrencyCodes.BND]: 2, + [CurrencyCodes.BOB]: 2, + [CurrencyCodes.BOV]: 2, + [CurrencyCodes.BRL]: 2, + [CurrencyCodes.BSD]: 2, + [CurrencyCodes.BTN]: 2, + [CurrencyCodes.BWP]: 2, + [CurrencyCodes.BYR]: 0, + [CurrencyCodes.BYN]: 2, + [CurrencyCodes.BZD]: 2, + [CurrencyCodes.CAD]: 2, + [CurrencyCodes.CDF]: 2, + [CurrencyCodes.CHE]: 2, + [CurrencyCodes.CHF]: 2, + [CurrencyCodes.CHW]: 2, + [CurrencyCodes.CLF]: 0, + [CurrencyCodes.CLP]: 0, + [CurrencyCodes.CNY]: 2, + [CurrencyCodes.COP]: 2, + [CurrencyCodes.COU]: 2, + [CurrencyCodes.CRC]: 2, + [CurrencyCodes.CUC]: 2, + [CurrencyCodes.CUP]: 2, + [CurrencyCodes.CVE]: 2, + [CurrencyCodes.CZK]: 2, + [CurrencyCodes.DJF]: 0, + [CurrencyCodes.DKK]: 2, + [CurrencyCodes.DOP]: 2, + [CurrencyCodes.DZD]: 2, + [CurrencyCodes.EGP]: 2, + [CurrencyCodes.ERN]: 2, + [CurrencyCodes.ETB]: 2, + [CurrencyCodes.EUR]: 2, + [CurrencyCodes.FJD]: 2, + [CurrencyCodes.FKP]: 2, + [CurrencyCodes.GBP]: 2, + [CurrencyCodes.GEL]: 2, + [CurrencyCodes.GHS]: 2, + [CurrencyCodes.GIP]: 2, + [CurrencyCodes.GMD]: 2, + [CurrencyCodes.GNF]: 0, + [CurrencyCodes.GTQ]: 2, + [CurrencyCodes.GYD]: 2, + [CurrencyCodes.HKD]: 2, + [CurrencyCodes.HNL]: 2, + [CurrencyCodes.HRK]: 2, + [CurrencyCodes.HTG]: 2, + [CurrencyCodes.HUF]: 2, + [CurrencyCodes.IDR]: 2, + [CurrencyCodes.ILS]: 2, + [CurrencyCodes.INR]: 2, + [CurrencyCodes.IQD]: 3, + [CurrencyCodes.IRR]: 2, + [CurrencyCodes.ISK]: 0, + [CurrencyCodes.JMD]: 2, + [CurrencyCodes.JOD]: 3, + [CurrencyCodes.JPY]: 0, + [CurrencyCodes.KES]: 2, + [CurrencyCodes.KGS]: 2, + [CurrencyCodes.KHR]: 2, + [CurrencyCodes.KMF]: 0, + [CurrencyCodes.KPW]: 2, + [CurrencyCodes.KRW]: 0, + [CurrencyCodes.KWD]: 3, + [CurrencyCodes.KYD]: 2, + [CurrencyCodes.KZT]: 2, + [CurrencyCodes.LAK]: 2, + [CurrencyCodes.LBP]: 2, + [CurrencyCodes.LKR]: 2, + [CurrencyCodes.LRD]: 2, + [CurrencyCodes.LSL]: 2, + [CurrencyCodes.LTL]: 2, + [CurrencyCodes.LVL]: 2, + [CurrencyCodes.LYD]: 3, + [CurrencyCodes.MAD]: 2, + [CurrencyCodes.MDL]: 2, + [CurrencyCodes.MGA]: 2, + [CurrencyCodes.MKD]: 2, + [CurrencyCodes.MMK]: 2, + [CurrencyCodes.MNT]: 2, + [CurrencyCodes.MOP]: 2, + [CurrencyCodes.MRO]: 2, + [CurrencyCodes.MUR]: 2, + [CurrencyCodes.MVR]: 2, + [CurrencyCodes.MWK]: 2, + [CurrencyCodes.MXN]: 2, + [CurrencyCodes.MXV]: 2, + [CurrencyCodes.MYR]: 2, + [CurrencyCodes.MZN]: 2, + [CurrencyCodes.NAD]: 2, + [CurrencyCodes.NGN]: 2, + [CurrencyCodes.NIO]: 2, + [CurrencyCodes.NOK]: 2, + [CurrencyCodes.NPR]: 2, + [CurrencyCodes.NZD]: 2, + [CurrencyCodes.OMR]: 3, + [CurrencyCodes.PAB]: 2, + [CurrencyCodes.PEN]: 2, + [CurrencyCodes.PGK]: 2, + [CurrencyCodes.PHP]: 2, + [CurrencyCodes.PKR]: 2, + [CurrencyCodes.PLN]: 2, + [CurrencyCodes.PYG]: 0, + [CurrencyCodes.QAR]: 2, + [CurrencyCodes.RON]: 2, + [CurrencyCodes.RSD]: 2, + [CurrencyCodes.RUB]: 2, + [CurrencyCodes.RWF]: 0, + [CurrencyCodes.SAR]: 2, + [CurrencyCodes.SBD]: 2, + [CurrencyCodes.SCR]: 2, + [CurrencyCodes.SDG]: 2, + [CurrencyCodes.SEK]: 2, + [CurrencyCodes.SGD]: 2, + [CurrencyCodes.SHP]: 2, + [CurrencyCodes.SLL]: 2, + [CurrencyCodes.SOS]: 2, + [CurrencyCodes.SRD]: 2, + [CurrencyCodes.SSP]: 2, + [CurrencyCodes.STD]: 2, + [CurrencyCodes.SVC]: 2, + [CurrencyCodes.SYP]: 2, + [CurrencyCodes.SZL]: 2, + [CurrencyCodes.THB]: 2, + [CurrencyCodes.TJS]: 2, + [CurrencyCodes.TMT]: 2, + [CurrencyCodes.TND]: 3, + [CurrencyCodes.TOP]: 2, + [CurrencyCodes.TRY]: 2, + [CurrencyCodes.TTD]: 2, + [CurrencyCodes.TWD]: 2, + [CurrencyCodes.TZS]: 2, + [CurrencyCodes.UAH]: 2, + [CurrencyCodes.UGX]: 0, + [CurrencyCodes.USD]: 2, + [CurrencyCodes.USN]: 2, + [CurrencyCodes.USS]: 2, + [CurrencyCodes.UYI]: 0, + [CurrencyCodes.UYU]: 2, + [CurrencyCodes.UZS]: 2, + [CurrencyCodes.VEF]: 2, + [CurrencyCodes.VND]: 0, + [CurrencyCodes.VUV]: 0, + [CurrencyCodes.WST]: 2, + [CurrencyCodes.XAF]: 0, + [CurrencyCodes.XAG]: 0, + [CurrencyCodes.XAU]: 0, + [CurrencyCodes.XBA]: 0, + [CurrencyCodes.XBB]: 0, + [CurrencyCodes.XBC]: 0, + [CurrencyCodes.XBD]: 0, + [CurrencyCodes.XCD]: 2, + [CurrencyCodes.XDR]: 0, + [CurrencyCodes.XFU]: 0, + [CurrencyCodes.XOF]: 0, + [CurrencyCodes.XPD]: 0, + [CurrencyCodes.XPF]: 0, + [CurrencyCodes.XPT]: 0, + [CurrencyCodes.XSU]: 0, + [CurrencyCodes.XTS]: 0, + [CurrencyCodes.XUA]: 0, + [CurrencyCodes.YER]: 2, + [CurrencyCodes.ZAR]: 2, + [CurrencyCodes.ZMW]: 2, + [CurrencyCodes.ZWL]: 2, + }; + + function formatPrice(price, locale = 'en-US') { + const { amount, currency } = price; + const formatter = Intl.NumberFormat(locale, { style: 'currency', currency }); + return formatter.format(convertToMajorCurrencyUnits(amount, currency)); + } + function convertToMajorCurrencyUnits(minorUnitValue, currency) { + const exponent = CurrencyExponents[currency]; + if (exponent == null) { + console.warn(`Unexpected currency ${currency}`); + return minorUnitValue; + } + const minorUnit = new Decimal$1(minorUnitValue); + return minorUnit.dividedBy(10 ** exponent).toNumber(); + } + var PriceUtils = { + formatPrice, + }; + + var lodash_transform = {exports: {}}; + + /** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + lodash_transform.exports; + + (function (module, exports) { + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used to compose bitmasks for comparison styles. */ + var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ + function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + this.__data__ = new ListCache(entries); + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + return this.__data__['delete'](key); + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var cache = this.__data__; + if (cache instanceof ListCache) { + var pairs = cache.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + return this; + } + cache = this.__data__ = new MapCache(pairs); + } + cache.set(key, value); + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString.call(value); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag && !isHostObject(object), + othIsObj = othTag == objectTag && !isHostObject(other), + isSameTag = objTag == othTag; + + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value) { + return isArray(value) ? value : stringToPath(value); + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!seen.has(othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.add(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, customizer, bitmask, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= UNORDERED_COMPARE_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11, + // for data views in Edge < 14, and promises in Node.js. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = isKey(path, object) ? [path] : castPath(path); + + var result, + index = -1, + length = path.length; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result) { + return result; + } + var length = object ? object.length : 0; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoize(function(string) { + string = toString(string); + + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result); + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Assign cache to `_.memoize`. + memoize.Cache = MapCache; + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object) || isTypedArray(object); + iteratee = baseIteratee(iteratee); + + if (accumulator == null) { + if (isArr || isObject(object)) { + var Ctor = object.constructor; + if (isArr) { + accumulator = isArray(object) ? new Ctor : []; + } else { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + } else { + accumulator = {}; + } + } + (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + module.exports = transform; + } (lodash_transform, lodash_transform.exports)); + + var lodash_transformExports = lodash_transform.exports; + var transform = /*@__PURE__*/getDefaultExportFromCjs(lodash_transformExports); + + class DiscordSDKMock { + constructor(clientId, guildId, channelId) { + this.platform = exports.Platform.DESKTOP; + this.instanceId = '123456789012345678'; + this.configuration = getDefaultSdkConfiguration(); + this.source = null; + this.sourceOrigin = ''; + this.frameId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'; + this.eventBus = new EventEmitter(); + this.clientId = clientId; + this.commands = this._updateCommandMocks({}); + this.guildId = guildId; + this.channelId = channelId; + } + _updateCommandMocks(newCommands) { + // Wrap all the command functions with logging + this.commands = transform(Object.assign({}, commandsMockDefault, newCommands), (mock, func, name) => { + mock[name] = async (...args) => { + console.info(`DiscordSDKMock: ${String(name)}(${JSON.stringify(args)})`); + return await func(...args); + }; + }); + // redundant return here to satisfy the constructor defining commands + return this.commands; + } + emitReady() { + this.emitEvent('READY', undefined); + } + close(...args) { + console.info(`DiscordSDKMock: close(${JSON.stringify(args)})`); + } + ready() { + return Promise.resolve(); + } + async subscribe(event, listener, ..._subscribeArgs) { + return await this.eventBus.on(event, listener); + } + async unsubscribe(event, listener, ..._unsubscribeArgs) { + return await this.eventBus.off(event, listener); + } + emitEvent(event, data) { + this.eventBus.emit(event, data); + } + } + /** Default return values for all discord SDK commands */ + const commandsMockDefault = { + authorize: () => Promise.resolve({ code: 'mock_code' }), + authenticate: () => Promise.resolve({ + access_token: 'mock_token', + user: { + username: 'mock_user_username', + discriminator: 'mock_user_discriminator', + id: 'mock_user_id', + avatar: null, + public_flags: 1, + }, + scopes: [], + expires: new Date(2121, 1, 1).toString(), + application: { + description: 'mock_app_description', + icon: 'mock_app_icon', + id: 'mock_app_id', + name: 'mock_app_name', + }, + }), + setActivity: () => Promise.resolve({ + name: 'mock_activity_name', + type: 0, + }), + getChannel: () => Promise.resolve({ + id: 'mock_channel_id', + name: 'mock_channel_name', + type: ChannelTypesObject.GUILD_TEXT, + voice_states: [], + messages: [], + }), + getSkus: () => Promise.resolve({ skus: [] }), + getEntitlements: () => Promise.resolve({ entitlements: [] }), + startPurchase: () => Promise.resolve([]), + setConfig: () => Promise.resolve({ use_interactive_pip: false }), + userSettingsGetLocale: () => Promise.resolve({ locale: '' }), + openExternalLink: () => Promise.resolve(null), + encourageHardwareAcceleration: () => Promise.resolve({ enabled: true }), + captureLog: () => Promise.resolve(null), + setOrientationLockState: () => Promise.resolve(null), + openInviteDialog: () => Promise.resolve(null), + getPlatformBehaviors: () => Promise.resolve({ + iosKeyboardResizesView: true, + }), + getChannelPermissions: () => Promise.resolve({ permissions: bigInt(1234567890) }), + openShareMomentDialog: () => Promise.resolve(null), + initiateImageUpload: () => Promise.resolve({ + image_url: 'https://assets-global.website-files.com/6257adef93867e50d84d30e2/636e0b52aa9e99b832574a53_full_logo_blurple_RGB.png', + }), + getInstanceConnectedParticipants: () => Promise.resolve({ participants: [] }), + }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + /** + * Creates a regular expression from a target string. The target string + * may contain `{name}` tokens which will end up being translated to + * a named group match for a series of word characters with the group named `name` + * The substitution pattern is {a-z} because the named groups must be valid JS identifiers, + * making items like {0} invalid. + * + * @returns a RegExp object + **/ + const SUBSTITUTION_REGEX = /\{([a-z]+)\}/g; + function regexFromTarget(target) { + const regexString = target.replace(SUBSTITUTION_REGEX, (match, name) => `(?<${name}>[\\w-]+)`); + return new RegExp(`${regexString}(/|$)`); + } + /** + * + * Attempts to map the actual url (i.e. google.com) to a url path, per the url + * mappings set up in the embedded application. If the target contains `{foo}` + * tokens, they will be replace with the values contained in the original URL, + * via the pattern described in the prefix + * + * @returns null if URL doesn't match prefix, otherwise return rewritten URL + */ + function matchAndRewriteURL({ originalURL, prefix, prefixHost, target }) { + // coerce url with filler https protocol so we can retrieve host and pathname from target + const targetURL = new URL(`https://${target}`); + // Depending on the environment, the URL constructor may turn `{` and `}` into `%7B` and `%7D`, respectively + const targetRegEx = regexFromTarget(targetURL.host.replace(/%7B/g, '{').replace(/%7D/g, '}')); + const match = originalURL.toString().match(targetRegEx); + // Null match indicates that this target is not relevant + if (match == null) + return originalURL; + const newURL = new URL(originalURL.toString()); + newURL.host = prefixHost; + newURL.pathname = prefix.replace(SUBSTITUTION_REGEX, (_, matchName) => { + var _a; + const replaceValue = (_a = match.groups) === null || _a === void 0 ? void 0 : _a[matchName]; + if (replaceValue == null) + throw new Error('Misconfigured route.'); + return replaceValue; + }); + // Append the original path + newURL.pathname += newURL.pathname === '/' ? originalURL.pathname.slice(1) : originalURL.pathname; + // Remove the target's path from the new url path + newURL.pathname = newURL.pathname.replace(targetURL.pathname, ''); + // Add a trailing slash if original url had it, and if it doesn't already have one or if matches filename regex + if (originalURL.pathname.endsWith('/') && !newURL.pathname.endsWith('/')) { + newURL.pathname += '/'; + } + return newURL; + } + function absoluteURL(url, protocol = window.location.protocol, host = window.location.host) { + // If the first arg is a complete url, it will ignore the second arg + // This call structure lets us set relative urls to have a full url with the proper protocol and host + return new URL(url, `${protocol}//${host}`); + } + + function patchUrlMappings(mappings, { patchFetch = true, patchWebSocket = true, patchXhr = true, patchSrcAttributes = false } = {}) { + // Bail out if we're not in a browser + if (typeof window === 'undefined') + return; + if (patchFetch) { + const fetchImpl = window.fetch; + // fetch is a duplex, but this is consistent + window.fetch = function (input, init) { + // If fetch has Request as input, we need to resolve any stream + // before we create a new request with the mapped url + if (input instanceof Request) { + const newUrl = attemptRemap({ url: absoluteURL(input.url), mappings }); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const _a = (init !== null && init !== void 0 ? init : {}), newInit = __rest(_a, ["url"]); + Object.keys(Request.prototype).forEach((value) => { + if (value === 'url') + return; + try { + // @ts-expect-error + newInit[value] = input[value]; + } + catch (ex) { + console.warn(`Remapping fetch request key "${value}" failed`, ex); + } + }); + return new Promise((resolve, reject) => { + try { + input.blob().then((blob) => { + if (input.method.toUpperCase() !== 'HEAD' && input.method.toUpperCase() !== 'GET' && blob.size > 0) { + newInit.body = blob; + } + resolve(fetchImpl(new Request(newUrl, newInit))); + }); + } + catch (ex) { + reject(ex); + } + }); + } + // Assuming a generic url or string + const remapped = attemptRemap({ url: input instanceof URL ? input : absoluteURL(input), mappings }); + return fetchImpl(remapped, init); + }; + } + if (patchWebSocket) { + class WebSocketProxy extends WebSocket { + constructor(url, protocols) { + const remapped = attemptRemap({ url: url instanceof URL ? url : absoluteURL(url), mappings }); + super(remapped, protocols); + } + } + window.WebSocket = WebSocketProxy; + } + if (patchXhr) { + const openImpl = XMLHttpRequest.prototype.open; + // @ts-expect-error - the ts interface exports two 'open' methods + XMLHttpRequest.prototype.open = function (method, url, async, username, password) { + const remapped = attemptRemap({ url: absoluteURL(url), mappings }); + openImpl.apply(this, [method, remapped, async, username, password]); + }; + } + if (patchSrcAttributes) { + const callback = function (mutationsList) { + for (const mutation of mutationsList) { + if (mutation.type === 'attributes' && mutation.attributeName === 'src') { + attemptSetNodeSrc(mutation.target, mappings); + } + else if (mutation.type === 'childList') { + mutation.addedNodes.forEach((node) => recursivelyRemapChildNodes(node, mappings)); + } + } + }; + const observer = new MutationObserver(callback); + const config = { + attributeFilter: ['src'], + childList: true, + subtree: true, + }; + observer.observe(window.document, config); + window.document.querySelectorAll('[src]').forEach((node) => { + attemptSetNodeSrc(node, mappings); + }); + } + } + function recursivelyRemapChildNodes(node, mappings) { + if (node.hasChildNodes()) { + node.childNodes.forEach((child) => { + attemptSetNodeSrc(child, mappings); + recursivelyRemapChildNodes(child, mappings); + }); + } + } + function attemptSetNodeSrc(node, mappings) { + var _a; + if (node instanceof HTMLElement && node.hasAttribute('src')) { + const url = absoluteURL((_a = node.getAttribute('src')) !== null && _a !== void 0 ? _a : ''); + if (url.host === window.location.host) + return; + node.setAttribute('src', attemptRemap({ url, mappings }).toString()); + } + } + function attemptRemap({ url, mappings }) { + for (const mapping of mappings) { + const mapped = matchAndRewriteURL({ + originalURL: url, + prefix: mapping.prefix, + target: mapping.target, + prefixHost: window.location.host, + }); + if (mapped != null && (mapped === null || mapped === void 0 ? void 0 : mapped.toString()) !== url.toString()) { + return mapped; + } + } + return url; + } + + const { Commands } = Common; + + exports.Commands = Commands; + exports.Common = Common; + exports.DiscordSDK = DiscordSDK; + exports.DiscordSDKMock = DiscordSDKMock; + exports.PermissionUtils = PermissionUtils; + exports.Permissions = Permissions; + exports.PriceUtils = PriceUtils; + exports.Responses = responses; + exports.attemptRemap = attemptRemap; + exports.patchUrlMappings = patchUrlMappings; + + return exports; + +})({}); + + +//////////////////////////////////////////// +// WINTERPIXEL IMPL +//////////////////////////////////////////// + + +var discordSdk, discordEvents, discordPriceUtils; +var discordCallbacks = { + registerCallback: function(key, obj) { + console.log("[DiscordHTML] registerCallback: " + key); + this[key] = obj; + } +}; +window["discordCallbacks"] = discordCallbacks; +async function initializeDiscord(oauth_client_id) { + console.log("[DiscordHTML] initializeDiscord() " + oauth_client_id); + try { + console.log("[DiscordHTML] initializeDiscord()"); + // console.log(DiscordSDK); + discordSdk = new DiscordSDK.DiscordSDK(oauth_client_id); + discordEvents = DiscordSDK.Events; + discordPriceUtils = DiscordSDK.PriceUtils; + console.log("[DiscordHTML] initializeDiscord() awaiting ready()"); + // Wait for READY payload from the discord client + await discordSdk.ready(); + + console.log("[DiscordHTML] initializeDiscord() ready()"); + console.log (JSON.stringify(discordCallbacks)); + console.log(discordCallbacks); + console.log(discordCallbacks.on_discordReady); + discordCallbacks.on_discordReady(true); + } catch(error) { + console.error('[DiscordHTMl] initializeDiscord() error: ' + error); + discordCallbacks.on_discordReady(); // empty is error + } +} + +async function authorizeDiscord(oauth_client_id) { + console.log("[DiscordHTML] authorizeDiscord() " + oauth_client_id); + try { + // Pop open the OAuth permission modal and request for access to scopes listed in scope array below + console.log("[DiscordHTML] authorizeDiscord() authorizing."); + const {code} = await discordSdk.commands.authorize({ + client_id: oauth_client_id, + response_type: 'code', + state: '', + prompt: 'none', + scope: ['identify', 'guilds.members.read'], + }); + console.log("[DiscordHTML] authorized. code " + code); + discordCallbacks.on_discordAuthorized(code); + } catch(error) { + console.error('[DiscordHTMl] authorizeDiscord() error: ' + error + ' stringified error: ' + JSON.stringify(error)); + discordCallbacks.on_discordAuthorized(); // empty is error + discordSdk.close(1000, "Unauthorized") + } +}; + +async function authenticateDiscord(access_token) { + console.log("[DiscordHTML] authenticateDiscord()"); + // Authenticate with Discord client (using the access_token) + try { + var user = await discordSdk.commands.authenticate({access_token}); + var userJson = JSON.stringify(user); + console.log("[DiscordHTML] authenticated. user: " + userJson); + discordCallbacks.on_discordAuthenticated(userJson); + discordConnectParticipantsChanged(); + discordConnectPurchaseCallback(); + //discordLoadSkus(); + } catch (error) { + console.error("[DiscordHTML] authenticateDiscord() error: " + error); + discordCallbacks.on_discordAuthenticated(); // empty is error + } +}; + +function discordOpenURL(url) { + console.log("[DiscordHTML] discordOpenURL " + url); + discordSdk.commands.openExternalLink({url:url}) +}; + +function discordUpdateParticipants(participants) { + console.log("[Discord] discordUpdateParticipants"); + var participantsJsonString = JSON.stringify(participants); + console.log("[Discord] participants: " + participantsJsonString); + discordCallbacks.on_discordParticipantsChanged(participantsJsonString); +} + +async function discordGetParticipants() { + console.log("[DiscordHTML] discordGetInstanceConnectedParticipants()"); + try { + var participantData = await discordSdk.commands.getInstanceConnectedParticipants(); + discordUpdateParticipants(participantData); + } catch (error) { + console.log("[DiscordHTML] discordGetInstanceConnectedParticipants() error " + error); + } + return [] +}; + +function discordConnectParticipantsChanged() { + try { + console.log("[DiscordHTML] discordConnectParticipantsChanged() subscribing to participants update"); + discordSdk.subscribe(discordEvents.ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE, discordUpdateParticipants); + console.log("[DiscordHTML] discordConnectParticipantsChanged() subscribed to participants update"); + } catch (error) { + console.log("[DiscordHTML] discordConnectParticipantsChanged() error processing participants: " + JSON.stringify(error)); + } +} + +function discordQueryPurchases() { + try { + + } catch (error) { + console.log("[DiscordHTML] discordQueryPurchases() error " + error); + } +} + +function discordConnectPurchaseCallback() { + try { + console.log("[DiscordHTML] discordConnectPurchaseCallback()"); + discordSdk.subscribe('ENTITLEMENT_CREATE', () =>{ + console.log("[DiscordHTML] discord purchaseCallback()"); + discordCallbacks.on_purchaseCallback(); + }); + } catch (error) { + console.log("[DiscordHTML] discordConnectPurchaseCallback() error: " + error); + } +} + +async function discordLoadSkus() { + try { + console.log("[DiscordHTML] discordLoadSkus()"); + const skus = await discordSdk.commands.getSkus(); + // console.log("[DiscordHTML] skus: " + skus); + skus.skus.forEach(skuInfo => { + // console.log("[DiscordHTML] formatting price: " + skuInfo.price); + var formattedPrice = discordPriceUtils.formatPrice(skuInfo.price); + // console.log("[DiscordHTML] formated to: " + formattedPrice); + skuInfo.formatted_price = formattedPrice; + }) + const skusJson = JSON.stringify(skus); + // console.log("[DiscordHTML] skus jsonified: " + JSON.stringify(skus)); + discordCallbacks.on_skusLoaded(skusJson); + } catch (error) { + console.log("[DiscordHTML] discordLoadSkus() error: " + error); + } +} + +async function discordPurchaseSku(sku) { + try { + console.log("[DiscordHTML] discordPurchaseSku(" + sku + ")"); + await discordSdk.commands.startPurchase({sku_id: sku}); + console.log("[DiscordHTML] discordPurchaseSku(" + sku + ") finished"); + } catch (error) { + console.log("[DiscordHTML] discordPurchaseSku(" + sku + ") error: " + error + " error json: " + JSON.stringify(error)); + } +} diff --git a/public/assets/games/bobble/winterpixelads.js b/public/assets/games/bobble/winterpixelads.js new file mode 100644 index 00000000..707bf173 --- /dev/null +++ b/public/assets/games/bobble/winterpixelads.js @@ -0,0 +1,256 @@ + + + +class WinterpixelAds { + constructor() { + this.registered_events = {}; + this.adBreak = null; + this.adConfig = null; + this.adConfigReady = false; + this.driver = "winterpixel"; + + } + + init(adBreak, adConfig, driver) { + console.log("WinterpixelAds init"); + this.adBreak = adBreak; + this.adConfig = adConfig; + this.driver = driver; + console.log("WinterpixelAds driver: " + driver); + + + if(this.driver == "winterpixel") { + this.adConfig({ + sound: "on", + preloadAdBreaks: "on", + onReady: () => { + console.log("WinterpixelAds init adConfig onReady"); + this.adConfigReady = true; + } + }); + } + else if(this.driver == "adinplay") { + // do nothing + } + else if(this.driver == "crazygames") { + // Nothing required for crazy v2 sdk + } + else if(this.driver == "poki") { + PokiSDK.init().then(() => { + console.log("Poki SDK successfully initialized"); + console.log("[PokiSDK] measureEvent(loading, poki_sdk_loaded, poki_sdk_loaded)"); + PokiSDK.measure("loading", "poki_sdk_loaded", "poki_sdk_loaded"); + // fire your function to continue to game + PokiSDK.gameLoadingStart(); + }).catch(() => { + console.log("Initialized, but the user likely has adblock"); + console.log("[PokiSDK] measureEvent(loading, poki_sdk_loaded, poki_sdk_loaded_adblock)"); + PokiSDK.measure("loading", "poki_sdk_loaded", "poki_sdk_loaded_adblock"); + // fire your function to continue to game + }); + } + }; + + addEventListener(key, func) { + console.log("WinterpixelAds addEventListener"); + this.registered_events[key] = func; + }; + + gameplayStart() { + console.log("WinterpixelAds gameplayStart"); + + if(this.driver == "winterpixel") { + // todo + } + else if(this.driver == "crazygames") { + window.CrazyGames.SDK.game.gameplayStart(); + } + if(this.driver == "poki") { + PokiSDK.gameplayStart(); + } + } + + gameplayStop() { + console.log("WinterpixelAds gameplayStop"); + + if(this.driver == "winterpixel") { + // todo + } + else if(this.driver == "crazygames") { + window.CrazyGames.SDK.game.gameplayStop(); + } + if(this.driver == "poki") { + PokiSDK.gameplayStop(); + } + } + + gameLoadingStart() { + if(this.driver == "poki") { + PokiSDK.gameLoadingStart(); + } + } + + gameLoadingFinished() { + if(this.driver == "poki") { + PokiSDK.gameLoadingFinished(); + } + } + + happytime() { + console.log("WinterpixelAds happytime"); + + if(this.driver == "winterpixel") { + // todo + } + else if(this.driver == "crazygames") { + window.CrazyGames.SDK.game.happytime(); + } + } + + requestAd(adNameString) { + console.log("WinterpixelAds requestAd"); + + if(this.driver == "winterpixel") { + if(this.adConfigReady) { + this.adBreak({ + type: 'next', // ad shows at start of next level + name: 'next', + beforeAd: () => { + console.log("adBreak beforeAd"); + }, // You may also want to mute the game's sound. + afterAd: () => { + console.log("adBreak afterAd"); + }, + adBreakDone: (o) => { + console.log("preroll done"); + if(this.registered_events["adFinished"]) { + this.registered_events["adFinished"](); + } + } + }); + } + else{ + console.log("WinterpixelAds requestAd, adConfig not ready"); + if(this.registered_events["adError"]) { + this.registered_events["adError"](); + } + } + } + else if(this.driver == "adinplay") { + if(this.registered_events["adStarted"]) { + this.registered_events["adStarted"](); + } + + if(adNameString == "rewarded") { + show_rewarded(); // TODO rework + } + else { + show_preroll(); // TODO rework + } + } + else if(this.driver == "crazygames") { + const callbacks = { + adFinished: () => { + console.log("End ad (callback)") + if(this.registered_events["adFinished"]) { + this.registered_events["adFinished"](); + } + }, + adError: (error) => { + console.log("Error ad (callback)", error) + if(this.registered_events["adError"]) { + this.registered_events["adError"](); + } + }, + adStarted: () => { + console.log("Start ad (callback)") + if(this.registered_events["adStarted"]) { + this.registered_events["adStarted"](); + } + }, + }; + window.CrazyGames.SDK.ad.requestAd(adNameString, callbacks); + } + else if(this.driver == "poki") { + if(adNameString == "rewarded") { + // pause your game here if it isn't already + PokiSDK.rewardedBreak(() => { + if(this.registered_events["adStarted"]) { + this.registered_events["adStarted"](); + } + }).then((withReward) => { + console.log("Rewarded break finished, proceeding to game"); + if (withReward) { + if(this.registered_events["adFinished"]) { + this.registered_events["adFinished"](); + } + } else { + if(this.registered_events["adError"]) { + this.registered_events["adError"](); + } + } + }); + } else { + // pause your game here if it isn't already + PokiSDK.commercialBreak(() => { + if(this.registered_events["adStarted"]) { + this.registered_events["adStarted"](); + } + }).then(() => { + console.log("Commercial break finished, proceeding to game"); + if(this.registered_events["adFinished"]) { + this.registered_events["adFinished"](); + } + }); + } + } + } + + requestBanner(bannerDict) { + console.log("WinterpixelAds requestBanner"); + + if(this.driver == "winterpixel") { + // todo + } + else if(this.driver == "adinplay") { + request_banner(); + } + else if(this.driver == "crazygames") { + window.CrazyGames.SDK.banner.requestBanner(bannerDict); + } + } + + requestResponsiveBanner(bannerIdArray) { + console.log("WinterpixelAds requestResponsiveBanner"); + + if(this.driver == "winterpixel") { + // todo + } + else if(this.driver == "adinplay") { + request_banner(); + } + else if(this.driver == "crazygames") { + window.CrazyGames.SDK.banner.requestResponsiveBanner(bannerIdArray); + } + } + + measureEvent(category, action, label) { + console.log("[PokiSDK] js measure_event(" + category + ", " + action + ", " + label + ")"); + if (this.driver == "poki") { + if (PokiSDK) { + if (PokiSDK.measure) { + PokiSDK.measure(category, action, label); + } else { + console.log("[PokiSDK] js measure_event(" + category + ", " + action + ", " + label + "), but no PokiSDK.measure"); + } + } else { + console.log("[PokiSDK] js measure_event(" + category + ", " + action + ", " + label + "), but no PokiSDK"); + } + } + } +}; + +if (typeof window !== 'undefined') { + window['WinterpixelAds'] = new WinterpixelAds(); +} + diff --git a/public/assets/games/bulletzio/assets/SharedSystems-CYDh_xR8.js b/public/assets/games/bulletzio/assets/SharedSystems-CYDh_xR8.js new file mode 100644 index 00000000..86d914a5 --- /dev/null +++ b/public/assets/games/bulletzio/assets/SharedSystems-CYDh_xR8.js @@ -0,0 +1,311 @@ +import{o as Re,M as g,p as Be,q as Ue,E as u,s as b,t as Ae,v as q,F as K,x as Ie,l as m,S as p,h as B,w as Y,y as Fe,c as H,B as k,i as U,u as C,j as _,R as w,z as Ee,a as De,C as S,G as Oe,H as ze,I as He,J,e as X,K as Le,P as We,d as Ve,D as Q,L as je,N as $e,O as Ne}from"./index-BphGqh_l.js";import{b as qe,S as Z,G as ee,f as te,U as re,T as L,h as W,B as Ke,i as Ye,R as se}from"./colorToUniform-CXyy9as8.js";const ae=class A extends qe{constructor(e){e={...A.defaultOptions,...e},super(e),this.enabled=!0,this._state=Z.for2d(),this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.addResource("uTexture",0,1)}apply(e,t,r,a){e.applyFilter(this,t,r,a)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:r,...a}=e;let n,i;return t&&(n=ee.from(t)),r&&(i=te.from(r)),new A({gpuProgram:n,glProgram:i,...a})}};ae.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1};let Je=ae;var Xe=`in vec2 vMaskCoord; +in vec2 vTextureCoord; + +uniform sampler2D uTexture; +uniform sampler2D uMaskTexture; + +uniform float uAlpha; +uniform vec4 uMaskClamp; + +out vec4 finalColor; + +void main(void) +{ + float clip = step(3.5, + step(uMaskClamp.x, vMaskCoord.x) + + step(uMaskClamp.y, vMaskCoord.y) + + step(vMaskCoord.x, uMaskClamp.z) + + step(vMaskCoord.y, uMaskClamp.w)); + + // TODO look into why this is needed + float npmAlpha = uAlpha; + vec4 original = texture(uTexture, vTextureCoord); + vec4 masky = texture(uMaskTexture, vMaskCoord); + float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a); + + original *= (alphaMul * masky.r * uAlpha * clip); + + finalColor = original; +} +`,Qe=`in vec2 aPosition; + +out vec2 vTextureCoord; +out vec2 vMaskCoord; + + +uniform vec4 uInputSize; +uniform vec4 uOutputFrame; +uniform vec4 uOutputTexture; +uniform mat3 uFilterMatrix; + +vec4 filterVertexPosition( vec2 aPosition ) +{ + vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy; + + position.x = position.x * (2.0 / uOutputTexture.x) - 1.0; + position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z; + + return vec4(position, 0.0, 1.0); +} + +vec2 filterTextureCoord( vec2 aPosition ) +{ + return aPosition * (uOutputFrame.zw * uInputSize.zw); +} + +vec2 getFilterCoord( vec2 aPosition ) +{ + return ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy; +} + +void main(void) +{ + gl_Position = filterVertexPosition(aPosition); + vTextureCoord = filterTextureCoord(aPosition); + vMaskCoord = getFilterCoord(aPosition); +} +`,V=`struct GlobalFilterUniforms { + uInputSize:vec4, + uInputPixel:vec4, + uInputClamp:vec4, + uOutputFrame:vec4, + uGlobalFrame:vec4, + uOutputTexture:vec4, +}; + +struct MaskUniforms { + uFilterMatrix:mat3x3, + uMaskClamp:vec4, + uAlpha:f32, +}; + + +@group(0) @binding(0) var gfu: GlobalFilterUniforms; +@group(0) @binding(1) var uTexture: texture_2d; +@group(0) @binding(2) var uSampler : sampler; + +@group(1) @binding(0) var filterUniforms : MaskUniforms; +@group(1) @binding(1) var uMaskTexture: texture_2d; + +struct VSOutput { + @builtin(position) position: vec4, + @location(0) uv : vec2, + @location(1) filterUv : vec2, + }; + +fn filterVertexPosition(aPosition:vec2) -> vec4 +{ + var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy; + + position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0; + position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z; + + return vec4(position, 0.0, 1.0); +} + +fn filterTextureCoord( aPosition:vec2 ) -> vec2 +{ + return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw); +} + +fn globalTextureCoord( aPosition:vec2 ) -> vec2 +{ + return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw); +} + +fn getFilterCoord(aPosition:vec2 ) -> vec2 +{ + return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy; +} + +fn getSize() -> vec2 +{ + + + return gfu.uGlobalFrame.zw; +} + +@vertex +fn mainVertex( + @location(0) aPosition : vec2, +) -> VSOutput { + return VSOutput( + filterVertexPosition(aPosition), + filterTextureCoord(aPosition), + getFilterCoord(aPosition) + ); +} + +@fragment +fn mainFragment( + @location(0) uv: vec2, + @location(1) filterUv: vec2, + @builtin(position) position: vec4 +) -> @location(0) vec4 { + + var maskClamp = filterUniforms.uMaskClamp; + + var clip = step(3.5, + step(maskClamp.x, filterUv.x) + + step(maskClamp.y, filterUv.y) + + step(filterUv.x, maskClamp.z) + + step(filterUv.y, maskClamp.w)); + + var mask = textureSample(uMaskTexture, uSampler, filterUv); + var source = textureSample(uTexture, uSampler, uv); + + var npmAlpha = 0.0; + + var alphaMul = 1.0 - npmAlpha * (1.0 - mask.a); + + var a = (alphaMul * mask.r) * clip; + + return vec4(source.rgb, source.a) * a; +}`;class Ze extends Je{constructor(e){const{sprite:t,...r}=e,a=new Re(t.texture),n=new re({uFilterMatrix:{value:new g,type:"mat3x3"},uMaskClamp:{value:a.uClampFrame,type:"vec4"},uAlpha:{value:1,type:"f32"}}),i=ee.from({vertex:{source:V,entryPoint:"mainVertex"},fragment:{source:V,entryPoint:"mainFragment"}}),l=te.from({vertex:Qe,fragment:Xe,name:"mask-filter"});super({...r,gpuProgram:i,glProgram:l,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=a}apply(e,t,r,a){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,r,a)}}class ne{constructor(e,t){this.state=Z.for2d(),this._batches=Object.create(null),this._geometries=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init(this)}buildStart(e){if(!this._batches[e.uid]){const t=new Be;this._batches[e.uid]=t,this._geometries[t.uid]=new Ue}this._activeBatch=this._batches[e.uid],this._activeGeometry=this._geometries[this._activeBatch.uid],this._activeBatch.begin()}addToBatch(e){this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){const t=this._activeBatch,r=this._activeGeometry;t.finish(e),r.indexBuffer.setDataWithSize(t.indexBuffer,t.indexSize,!0),r.buffers[0].setDataWithSize(t.attributeBuffer.float32View,t.attributeSize,!1)}upload(e){const t=this._batches[e.uid],r=this._geometries[t.uid];t.dirty&&(t.dirty=!1,r.buffers[0].update(t.attributeSize*4))}execute(e){if(e.action==="startBatch"){const t=e.batcher,r=this._geometries[t.uid];this._adaptor.start(this,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor.destroy(),this._adaptor=null;for(const e in this._batches)this._batches[e].destroy();this._batches=null;for(const e in this._geometries)this._geometries[e].destroy();this._geometries=null}}ne.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"batch"};const Ct={name:"texture-bit",vertex:{header:` + + struct TextureUniforms { + uTextureMatrix:mat3x3, + } + + @group(2) @binding(2) var textureUniforms : TextureUniforms; + `,main:` + uv = (textureUniforms.uTextureMatrix * vec3(uv, 1.0)).xy; + `},fragment:{header:` + @group(2) @binding(0) var uTexture: texture_2d; + @group(2) @binding(1) var uSampler: sampler; + + + `,main:` + outColor = textureSample(uTexture, uSampler, vUV); + `}},wt={name:"texture-bit",vertex:{header:` + uniform mat3 uTextureMatrix; + `,main:` + uv = (uTextureMatrix * vec3(uv, 1.0)).xy; + `},fragment:{header:` + uniform sampler2D uTexture; + + + `,main:` + outColor = texture(uTexture, vUV); + `}};function et(s,e){const t=s.root,r=s.instructionSet;r.reset(),e.batch.buildStart(r),e.blendMode.buildStart(),e.colorMask.buildStart(),t.sortableChildren&&t.sortChildren(),ie(t,r,e,!0),e.batch.buildEnd(r),e.blendMode.buildEnd(r)}function P(s,e,t){s.globalDisplayStatus<7||!s.includeInBuild||(s.sortableChildren&&s.sortChildren(),s.isSimple?tt(s,e,t):ie(s,e,t,!1))}function tt(s,e,t){if(s.renderPipeId&&(t.blendMode.setBlendMode(s,s.groupBlendMode,e),s.didViewUpdate=!1,t[s.renderPipeId].addRenderable(s,e)),!s.renderGroup){const r=s.children,a=r.length;for(let n=0;n=0;i--){const l=s.effects[i];t[l.pipe].pop(l,s,e)}}}const rt=new q;class st extends K{constructor(){super(),this.filters=[new Ze({sprite:new Ie(m.EMPTY)})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}}class oe{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,r){const a=this._renderer;if(a.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,canBundle:!1,maskedContainer:t}),e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,P(n,r,a.renderPipes),n.includeInBuild=!1}a.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,canBundle:!1})}pop(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,canBundle:!1})}execute(e){const t=this._renderer,r=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const a=b.get(st);if(r){e.mask.mask.measurable=!0;const n=Ae(e.mask.mask,!0,rt);e.mask.mask.measurable=!1,n.ceil();const i=L.getOptimalTexture(n.width,n.height,1,!1);t.renderTarget.push(i,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=a.sprite;l.texture=i,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:a,maskedContainer:e.maskedContainer,filterTexture:i})}else a.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:a,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const a=this._activeMaskStage[this._activeMaskStage.length-1];r&&(t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:a.maskedContainer,filterEffect:a.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const a=this._activeMaskStage.pop();r&&L.returnTexture(a.filterTexture),b.return(a.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}oe.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"alphaMask"};class le{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;this._colorStackIndex--;const i=n[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._colorStack=null}}le.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"colorMask"};class ue{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,r){var a;const n=e,i=this._renderer;i.renderPipes.batch.break(r),i.renderPipes.blendMode.setBlendMode(n.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,canBundle:!1});const l=n.mask;l.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const o=this._maskHash.get(n);o.instructionsStart=r.instructionSize,P(l,r,i.renderPipes),l.includeInBuild=!1,i.renderPipes.batch.break(r),r.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,canBundle:!1});const d=r.instructionSize-o.instructionsStart-1;o.instructionsLength=d;const c=i.renderTarget.renderTarget.uid;(a=this._maskStackHash)[c]??(a[c]=0)}pop(e,t,r){const a=e,n=this._renderer;n.renderPipes.batch.break(r),n.renderPipes.blendMode.setBlendMode(a.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"popMaskBegin",canBundle:!1});const i=this._maskHash.get(e);for(let l=0;le.uniformStructures[l]),n=this._adaptor.createUboElements(a),i=this._generateUboSync(n.uboElements);r=this._syncFunctionHash[t]={layout:n,syncFunction:i}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,r){const a=this.getUniformGroupData(e);return e.buffer||(e.buffer=new H({data:new Float32Array(a.layout.size/4),usage:k.UNIFORM|k.COPY_DST})),t||(t=e.buffer.data),r||(r=0),a.syncFunction(e.uniforms,t,r),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const M=[{type:"mat3x3",test:s=>s.value.a!==void 0,ubo:` + var matrix = uv[name].toArray(true); + data[offset] = matrix[0]; + data[offset + 1] = matrix[1]; + data[offset + 2] = matrix[2]; + data[offset + 4] = matrix[3]; + data[offset + 5] = matrix[4]; + data[offset + 6] = matrix[5]; + data[offset + 8] = matrix[6]; + data[offset + 9] = matrix[7]; + data[offset + 10] = matrix[8]; + `,uniform:` + gl.uniformMatrix3fv(ud[name].location, false, uv[name].toArray(true)); + `},{type:"vec4",test:s=>s.type==="vec4"&&s.size===1&&s.value.width!==void 0,ubo:` + v = uv[name]; + data[offset] = v.x; + data[offset + 1] = v.y; + data[offset + 2] = v.width; + data[offset + 3] = v.height; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height) { + cv[0] = v.x; + cv[1] = v.y; + cv[2] = v.width; + cv[3] = v.height; + gl.uniform4f(ud[name].location, v.x, v.y, v.width, v.height); + } + `},{type:"vec2",test:s=>s.type==="vec2"&&s.size===1&&s.value.x!==void 0,ubo:` + v = uv[name]; + data[offset] = v.x; + data[offset + 1] = v.y; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.x || cv[1] !== v.y) { + cv[0] = v.x; + cv[1] = v.y; + gl.uniform2f(ud[name].location, v.x, v.y); + } + `},{type:"vec4",test:s=>s.type==="vec4"&&s.size===1&&s.value.red!==void 0,ubo:` + v = uv[name]; + data[offset] = v.red; + data[offset + 1] = v.green; + data[offset + 2] = v.blue; + data[offset + 3] = v.alpha; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha) { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + cv[3] = v.alpha; + gl.uniform4f(ud[name].location, v.red, v.green, v.blue, v.alpha); + } + `},{type:"vec3",test:s=>s.type==="vec3"&&s.size===1&&s.value.red!==void 0,ubo:` + v = uv[name]; + data[offset] = v.red; + data[offset + 1] = v.green; + data[offset + 2] = v.blue; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue) { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + gl.uniform3f(ud[name].location, v.red, v.green, v.blue); + } + `}];function Gt(s,e,t,r){const a=[` + var v = null; + var v2 = null; + var t = 0; + var index = 0; + var name = null; + var arrayOffset = null; + `];let n=0;for(let l=0;l1)h=o.offset/4,a.push(t(o,h-n));else{const f=r[o.data.type];h=o.offset/4,a.push(` + v = uv.${d}; + offset += ${h-n}; + ${f}; + `)}n=h}const i=a.join(` +`);return new Function("uv","data","offset",i)}function x(s,e){return` + for (let i = 0; i < ${s*e}; i++) { + data[offset + (((i / ${s})|0) * 4) + (i % ${s})] = v[i]; + } + `}const nt={f32:` + data[offset] = v;`,i32:` + data[offset] = v;`,"vec2":` + data[offset] = v[0]; + data[offset + 1] = v[1];`,"vec3":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2];`,"vec4":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 3] = v[3];`,"mat2x2":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 4] = v[2]; + data[offset + 5] = v[3];`,"mat3x3":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 4] = v[3]; + data[offset + 5] = v[4]; + data[offset + 6] = v[5]; + data[offset + 8] = v[6]; + data[offset + 9] = v[7]; + data[offset + 10] = v[8];`,"mat4x4":` + for (let i = 0; i < 16; i++) { + data[offset + i] = v[i]; + }`,"mat3x2":x(3,2),"mat4x2":x(4,2),"mat2x3":x(2,3),"mat4x3":x(4,3),"mat2x4":x(2,4),"mat3x4":x(3,4)},Rt={...nt,"mat2x2":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 3] = v[3]; + `};function it(s,e,t,r,a,n){const i=n?1:-1;return s.identity(),s.a=1/r*2,s.d=i*(1/a*2),s.tx=-1-e*s.a,s.ty=-i-t*s.d,s}const v=new Map;function de(s,e){if(!v.has(s)){const t=new m({source:new U({resource:s,...e})}),r=()=>{v.get(s)===t&&v.delete(s)};t.once("destroy",r),t.source.once("destroy",r),v.set(s,t)}return v.get(s)}function ot(s){const e=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}const ce=class he{constructor(e={}){if(this.uid=C("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...he.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;tr.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof m||e.depthStencilTexture instanceof _?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new _({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,r=this.resolution,a=!1){this.dirtyId++,this.colorTextures.forEach((n,i)=>{a&&i===0||n.source.resize(e,t,r)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,r)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};ce.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let I=ce;class Bt{constructor(e){this.rootViewPort=new w,this.viewport=new w,this.onRenderTargetChange=new Ee("onRenderTargetChange"),this.projectionMatrix=new g,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:r,frame:a}){this._renderTargetStack.length=0,this.push(e,t,r,a),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=ot(this.rootRenderTarget)}bind(e,t=!0,r,a){const n=this.getRenderTarget(e),i=this.renderTarget!==n;this.renderTarget=n,this.renderSurface=e;const l=this.getGpuRenderTarget(n);(n.pixelWidth!==l.width||n.pixelHeight!==l.height)&&(this.adaptor.resizeGpuRenderTarget(n),l.width=n.pixelWidth,l.height=n.pixelHeight);const o=n.colorTexture,d=this.viewport,c=o.pixelWidth,h=o.pixelHeight;if(!a&&e instanceof m&&(a=e.frame),a){const f=o._resolution;d.x=a.x*f+.5|0,d.y=a.y*f+.5|0,d.width=a.width*f+.5|0,d.height=a.height*f+.5|0}else d.x=0,d.y=0,d.width=c,d.height=h;return it(this.projectionMatrix,0,0,d.width/o.resolution,d.height/o.resolution,!n.isRoot),this.adaptor.startRenderPass(n,t,r,d),i&&this.onRenderTargetChange.emit(n),n}clear(e,t=B.ALL,r){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,r,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=B.ALL,r,a){const n=this.bind(e,t,r,a);return this._renderTargetStack.push({renderTarget:n,frame:a}),n}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,r,a,n){r.x<0&&(a.width+=r.x,n.x-=r.x,r.x=0),r.y<0&&(a.height+=r.y,n.y-=r.y,r.y=0);const{pixelWidth:i,pixelHeight:l}=e;return a.width=Math.min(a.width,i-r.x),a.height=Math.min(a.height,l-r.y),this.adaptor.copyToTexture(e,t,r,a,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return U.test(e)&&(e=de(e).source),e instanceof I?t=e:e instanceof _&&(t=new I({colorTextures:[e]}),U.test(e.source.resource)&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy();const r=this._gpuRenderTargetHash[t.uid];r&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(r))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}}class Ut extends De{constructor({buffer:e,offset:t,size:r}){super(),this.uid=C("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=C("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=r,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=C("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null}}class fe{constructor(e){this._renderer=e}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}fe.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"customRender"};function pe(s,e){const t=s.instructionSet,r=t.instructions;for(let a=0;a>16&255,a=s>>8&255,n=s&255,i=e>>16&255,l=e>>8&255,o=e&255,d=r+(i-r)*t,c=a+(l-a)*t,h=n+(o-n)*t;return(d<<16)+(c<<8)+h}const G=16777215;function xe(s,e){return s===G||e===G?s+e-G:lt(s,e,.5)}const ut=new S;function ve(s,e=!1){dt(s);const t=s.childrenToUpdate,r=s.updateTick++;for(const a in t){const n=t[a],i=n.list,l=n.index;for(let o=0;o1?1:t,s.worldAlpha=t,s.worldColorAlpha=s.worldColor+((t*255|0)<<24)}function be(s,e,t){if(e===s.updateTick)return;s.updateTick=e,s.didChange=!1;const r=s.localTransform;s.updateLocalTransform();const a=s.parent;if(a&&!a.renderGroup?(t=t|s._updateFlags,s.relativeGroupTransform.appendFrom(r,a.relativeGroupTransform),t&&j(s,a,t)):(t=s._updateFlags,s.relativeGroupTransform.copyFrom(r),t&&j(s,ut,t)),!s.renderGroup){const n=s.children,i=n.length;for(let o=0;o1?1:r,s.groupAlpha=r,s.groupColorAlpha=s.groupColor+((r*255|0)<<24)}t&ze&&(s.groupBlendMode=s.localBlendMode==="inherit"?e.groupBlendMode:s.localBlendMode),t&He&&(s.globalDisplayStatus=s.localDisplayStatus&e.globalDisplayStatus),s._updateFlags=0}function ct(s,e){const{list:t,index:r}=s.childrenRenderablesToUpdate;let a=!1;for(let n=0;n{this.destroyRenderable(e)}),t}destroy(){for(const e in this._gpuSpriteHash)b.return(this._gpuSpriteHash[e]);this._gpuSpriteHash=null,this._renderer=null}}ye.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"sprite"};const F=class Te{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new J(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...Te.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};F.extension={type:[u.WebGLSystem,u.WebGPUSystem,u.CanvasSystem],name:"background",priority:0};F.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let pt=F;const y={};X.handle(u.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");y[s.name]=s.ref},s=>{delete y[s.name]});class ke{constructor(e){this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e}setBlendMode(e,t,r){if(this._activeBlendMode===t){this._isAdvanced&&this._renderableList.push(e);return}this._activeBlendMode=t,this._isAdvanced&&this._endAdvancedBlendMode(r),this._isAdvanced=!!y[t],this._isAdvanced&&(this._beginAdvancedBlendMode(r),this._renderableList.push(e))}_beginAdvancedBlendMode(e){this._renderer.renderPipes.batch.break(e);const t=this._activeBlendMode;if(!y[t]){Y(`Unable to assign BlendMode: '${t}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}let r=this._filterHash[t];r||(r=this._filterHash[t]=new K,r.filters=[new y[t]]);const a={renderPipeId:"filter",action:"pushFilter",renderables:[],filterEffect:r,canBundle:!1};this._renderableList=a.renderables,e.add(a)}_endAdvancedBlendMode(e){this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}ke.extension={type:[u.WebGLPipes,u.WebGPUPipes,u.CanvasPipes],name:"blendMode"};const R={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},E=class Me{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof S||e instanceof m?{target:e,...t}:{...t,...e}}async image(e){const t=new Image;return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Me.defaultImageOptions);const{format:t,quality:r}=e,a=this.canvas(e);if(a.toBlob!==void 0)return new Promise((n,i)=>{a.toBlob(l=>{if(!l){i(new Error("ICanvas.toBlob failed!"));return}const o=new FileReader;o.onload=()=>n(o.result),o.onerror=i,o.readAsDataURL(l)},R[t],r)});if(a.toDataURL!==void 0)return a.toDataURL(R[t],r);if(a.convertToBlob!==void 0){const n=await a.convertToBlob({type:R[t],quality:r});return new Promise((i,l)=>{const o=new FileReader;o.onload=()=>i(o.result),o.onerror=l,o.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,r=this._renderer;if(t instanceof m)return r.texture.generateCanvas(t);const a=r.textureGenerator.generateTexture(e),n=r.texture.generateCanvas(a);return a.destroy(),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,r=this._renderer,a=t instanceof m?t:r.textureGenerator.generateTexture(e),n=r.texture.getPixels(a);return t instanceof S&&a.destroy(),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof m?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),r=document.createElement("a");r.download=e.filename??"image.png",r.href=t.toDataURL("image/png"),document.body.appendChild(r),r.click(),document.body.removeChild(r)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const r=this.canvas(e),a=r.toDataURL();console.log(`[Pixi Texture] ${r.width}px ${r.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${a}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};E.extension={type:[u.WebGLSystem,u.WebGPUSystem],name:"extract"};E.defaultImageOptions={format:"png",quality:1};let mt=E;class gt extends m{static create(e){return new m({source:new _(e)})}resize(e,t,r){return this.source.resize(e,t,r),this}}const xt=new w,vt=new q,bt=[0,0,0,0];class Ce{constructor(e){this._renderer=e}generateTexture(e){e instanceof S&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,r=e.antialias||this._renderer.view.antialias,a=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:J.shared.setValue(n).toArray():n=bt;const i=e.frame?.copyTo(xt)||Le(a,vt).rectangle;i.width=Math.max(i.width,1/t)|0,i.height=Math.max(i.height,1/t)|0;const l=gt.create({...e.textureSourceOptions,width:i.width,height:i.height,resolution:t,antialias:r}),o=g.shared.translate(-i.x,-i.y);return this._renderer.render({container:a,transform:o,target:l,clearColor:n}),l.source.updateMipmaps(),l}destroy(){this._renderer=null}}Ce.extension={type:[u.WebGLSystem,u.WebGPUSystem],name:"textureGenerator"};class we{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e"},uWorldTransformMatrix:{value:new g,type:"mat3x3"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4"},uResolution:{value:[0,0],type:"vec2"}},{isStatic:!0})}destroy(){this._renderer=null}}we.extension={type:[u.WebGLSystem,u.WebGPUSystem,u.CanvasSystem],name:"globalUniforms"};let $=!1;const N="8.2.0";function _t(s){if(!$){if(Q.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${N} (${s}) http://www.pixijs.com/ + +`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${N} - ${s} - http://www.pixijs.com/`);$=!0}}class D{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===se.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),_t(t)}}}D.extension={type:[u.WebGLSystem,u.WebGPUSystem,u.CanvasSystem],name:"hello",priority:-2};D.defaultOptions={hello:!1};const O=class Se{constructor(e){this._renderer=e,this.count=0,this.checkCount=0}init(e){e={...Se.defaultOptions,...e},this.checkCountMax=e.textureGCCheckCountMax,this.maxIdle=e.textureGCAMaxIdle,this.active=e.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const e=this._renderer.texture.managedTextures;for(let t=0;t-1&&this.count-r._touched>this.maxIdle&&(r._touched=-1,r.unload())}}destroy(){this._renderer=null}};O.extension={type:[u.WebGLSystem,u.WebGPUSystem],name:"textureGC"};O.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:60*60,textureGCCheckCountMax:600};let Pe=O;X.add(Pe);const z=class Ge{get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Ge.defaultOptions,...e},e.view&&(je($e,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new w(0,0,e.width,e.height),this.canvas=e.canvas||Q.get().createCanvas(),this.antialias=!!e.antialias,this.texture=de(this.canvas,e),this.renderTarget=new I({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.multiView=!!e.multiView,this.autoDensity&&(this.canvas.style.width=`${this.texture.width}px`,this.canvas.style.height=`${this.texture.height}px`),this.resolution=e.resolution}resize(e,t,r){this.texture.source.resize(e,t,r),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height,this.autoDensity&&(this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`)}destroy(e=!1){(typeof e=="boolean"?e:!!e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)}};z.extension={type:[u.WebGLSystem,u.WebGPUSystem,u.CanvasSystem],name:"view",priority:0};z.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};let yt=z;const At=[pt,we,D,yt,_e,Pe,Ce,mt,Ne],It=[ke,ne,ye,me,oe,ue,le,fe];export{Ut as B,T as G,Bt as R,At as S,Pt as U,It as a,nt as b,Gt as c,M as d,St as e,wt as f,Ct as t,Rt as u}; diff --git a/public/assets/games/bulletzio/assets/WebGLRenderer-DijL7diB.js b/public/assets/games/bulletzio/assets/WebGLRenderer-DijL7diB.js new file mode 100644 index 00000000..2b22a47e --- /dev/null +++ b/public/assets/games/bulletzio/assets/WebGLRenderer-DijL7diB.js @@ -0,0 +1,156 @@ +import{g as K,E as l,B,D as G,w as m,Q as Ae,l as S,j as $,S as g,R as H,h as A,M as z,e as v,A as Ne}from"./index-BphGqh_l.js";import{S as U,j as O,k as Y,m as q,n as P,b as x,h as Z,f as Ie,U as F,o as Q,R as ye}from"./colorToUniform-CXyy9as8.js";import{g as J}from"./getBatchSamplersUniformGroup-BY8U1LLP.js";import{e as De,G as Ce,c as Ge,b as Ue,U as Oe,R as Pe,B as ee,d as N,f as Fe,S as Me,a as Le}from"./SharedSystems-CYDh_xR8.js";class te{constructor(){this._didUpload=!1,this._tempState=U.for2d()}init(e){const r=K(),s=O({name:"batch",bits:[Y,q(r),P]});this._shader=new x({glProgram:s,resources:{batchSamplers:J(r)}}),e.renderer.runners.contextChange.add(this)}contextChange(){this._didUpload=!1}start(e,r){const s=e.renderer;s.shader.bind(this._shader,this._didUpload),s.shader.updateUniformGroup(s.globalUniforms.uniformGroup),s.geometry.bind(r,this._shader.glProgram)}execute(e,r){const s=e.renderer;this._didUpload=!0,this._tempState.blendMode=r.blendMode,s.state.set(this._tempState);const n=r.textures.textures;for(let i=0;i(t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t))(T||{});class He{constructor(e,r){this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=r}}class re{constructor(e){this._gpuBuffers=Object.create(null),this._boundBufferBases=Object.create(null),this._renderer=e}destroy(){this._renderer=null,this._gl=null,this._gpuBuffers=null,this._boundBufferBases=null}contextChange(){this._gpuBuffers=Object.create(null),this._gl=this._renderer.gl}getGlBuffer(e){return this._gpuBuffers[e.uid]||this.createGLBuffer(e)}bind(e){const{_gl:r}=this,s=this.getGlBuffer(e);r.bindBuffer(s.type,s.buffer)}bindBufferBase(e,r){const{_gl:s}=this;if(this._boundBufferBases[r]!==e){const n=this.getGlBuffer(e);this._boundBufferBases[r]=e,s.bindBufferBase(s.UNIFORM_BUFFER,r,n.buffer)}}bindBufferRange(e,r,s){const{_gl:n}=this;s=s||0;const i=this.getGlBuffer(e);n.bindBufferRange(n.UNIFORM_BUFFER,r||0,i.buffer,s*256,256)}updateBuffer(e){const{_gl:r}=this,s=this.getGlBuffer(e);if(e._updateID===s.updateID)return s;s.updateID=e._updateID,r.bindBuffer(s.type,s.buffer);const n=e.data;if(s.byteLength>=e.data.byteLength)r.bufferSubData(s.type,0,n,0,e._updateSize/n.BYTES_PER_ELEMENT);else{const i=e.descriptor.usage&B.STATIC?r.STATIC_DRAW:r.DYNAMIC_DRAW;s.byteLength=n.byteLength,r.bufferData(s.type,n,i)}return s}destroyAll(){const e=this._gl;for(const r in this._gpuBuffers)e.deleteBuffer(this._gpuBuffers[r].buffer);this._gpuBuffers=Object.create(null)}onBufferDestroy(e,r){const s=this._gpuBuffers[e.uid],n=this._gl;r||n.deleteBuffer(s.buffer),this._gpuBuffers[e.uid]=null}createGLBuffer(e){const{_gl:r}=this;let s=T.ARRAY_BUFFER;e.descriptor.usage&B.INDEX?s=T.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&B.UNIFORM&&(s=T.UNIFORM_BUFFER);const n=new He(r.createBuffer(),s);return this._gpuBuffers[e.uid]=n,e.on("destroy",this.onBufferDestroy,this),n}}re.extension={type:[l.WebGLSystem],name:"buffer"};const M=class se{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){if(e={...se.defaultOptions,...e},e.context)this.initFromContext(e.context);else{const r=this._renderer.background.alpha<1,s=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:r,premultipliedAlpha:s,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof G.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const r=this._renderer.view.canvas;r.addEventListener("webglcontextlost",this.handleContextLost,!1),r.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,r){let s;const n=this._renderer.view.canvas;if(e===2&&(s=n.getContext("webgl2",r)),!s&&(s=n.getContext("webgl",r),!s))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=s,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,r={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...r,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...r,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const s=e.getExtension("WEBGL_provoking_vertex");s&&s.provokingVertexWEBGL(s.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this._renderer.runners.contextChange.emit(this.gl)}destroy(){const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(e){const r=e.getContextAttributes();r&&!r.stencil&&m("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=this.supports,n=this.webGLVersion===2,i=this.extensions;s.uint32Indices=n||!!i.uint32ElementIndex,s.uniformBufferObject=n,s.vertexArrayObject=n||!!i.vertexArrayObject,s.srgbTextures=n||!!i.srgb,s.nonPowOf2wrapping=n,s.nonPowOf2mipmaps=n,s.msaa=n,s.uint32Indices||m("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};M.extension={type:[l.WebGLSystem],name:"context"};M.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2};let we=M;var D=(t=>(t[t.RGBA=6408]="RGBA",t[t.RGB=6407]="RGB",t[t.RG=33319]="RG",t[t.RED=6403]="RED",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.ALPHA=6406]="ALPHA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t))(D||{}),ne=(t=>(t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t))(ne||{}),f=(t=>(t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.BYTE=5120]="BYTE",t[t.SHORT=5122]="SHORT",t[t.INT=5124]="INT",t[t.FLOAT=5126]="FLOAT",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.HALF_FLOAT=36193]="HALF_FLOAT",t))(f||{});const w={uint8x2:f.UNSIGNED_BYTE,uint8x4:f.UNSIGNED_BYTE,sint8x2:f.BYTE,sint8x4:f.BYTE,unorm8x2:f.UNSIGNED_BYTE,unorm8x4:f.UNSIGNED_BYTE,snorm8x2:f.BYTE,snorm8x4:f.BYTE,uint16x2:f.UNSIGNED_SHORT,uint16x4:f.UNSIGNED_SHORT,sint16x2:f.SHORT,sint16x4:f.SHORT,unorm16x2:f.UNSIGNED_SHORT,unorm16x4:f.UNSIGNED_SHORT,snorm16x2:f.SHORT,snorm16x4:f.SHORT,float16x2:f.HALF_FLOAT,float16x4:f.HALF_FLOAT,float32:f.FLOAT,float32x2:f.FLOAT,float32x3:f.FLOAT,float32x4:f.FLOAT,uint32:f.UNSIGNED_INT,uint32x2:f.UNSIGNED_INT,uint32x3:f.UNSIGNED_INT,uint32x4:f.UNSIGNED_INT,sint32:f.INT,sint32x2:f.INT,sint32x3:f.INT,sint32x4:f.INT};function Ve(t){return w[t]??w.float32}const ke={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class ie{constructor(e){this._geometryVaoHash=Object.create(null),this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");const r=this._renderer.context.extensions.vertexArrayObject;r&&(e.createVertexArray=()=>r.createVertexArrayOES(),e.bindVertexArray=n=>r.bindVertexArrayOES(n),e.deleteVertexArray=n=>r.deleteVertexArrayOES(n));const s=this._renderer.context.extensions.vertexAttribDivisorANGLE;s&&(e.drawArraysInstanced=(n,i,a,o)=>{s.drawArraysInstancedANGLE(n,i,a,o)},e.drawElementsInstanced=(n,i,a,o,c)=>{s.drawElementsInstancedANGLE(n,i,a,o,c)},e.vertexAttribDivisor=(n,i)=>s.vertexAttribDivisorANGLE(n,i)),this._activeGeometry=null,this._activeVao=null,this._geometryVaoHash=Object.create(null)}bind(e,r){const s=this.gl;this._activeGeometry=e;const n=this.getVao(e,r);this._activeVao!==n&&(this._activeVao=n,s.bindVertexArray(n)),this.updateBuffers()}reset(){this.unbind()}updateBuffers(){const e=this._activeGeometry,r=this._renderer.buffer;for(let s=0;s1?i.drawElementsInstanced(o,r||a.indexBuffer.data.length,u,(s||0)*c,n):i.drawElements(o,r||a.indexBuffer.data.length,u,(s||0)*c)}else n>1?i.drawArraysInstanced(o,s||0,r||a.getSize(),n):i.drawArrays(o,s||0,r||a.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}ie.extension={type:[l.WebGLSystem],name:"geometry"};const Xe=new Ae({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),L=class ae{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:r,antialias:s}={...ae.defaultOptions,...e};this.useBackBuffer=r,this._antialias=s,this._renderer.context.supports.msaa||(m("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=U.for2d();const n=new Ie({vertex:` + attribute vec2 aPosition; + out vec2 vUv; + + void main() { + gl_Position = vec4(aPosition, 0.0, 1.0); + + vUv = (aPosition + 1.0) / 2.0; + + // flip dem UVs + vUv.y = 1.0 - vUv.y; + }`,fragment:` + in vec2 vUv; + out vec4 finalColor; + + uniform sampler2D uTexture; + + void main() { + finalColor = texture(uTexture, vUv); + }`,name:"big-triangle"});this._bigTriangleShader=new x({glProgram:n,resources:{uTexture:S.WHITE.source}})}renderStart(e){const r=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!r.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:Xe,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new S({source:new $({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};L.extension={type:[l.WebGLSystem],name:"backBuffer",priority:1};L.defaultOptions={useBackBuffer:!1};let We=L;class oe{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}oe.extension={type:[l.WebGLSystem],name:"colorMask"};class ce{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,r){this._renderer.geometry.bind(e,r.glProgram)}finishRenderPass(){}draw(e){const r=this._renderer,{geometry:s,shader:n,state:i,skipSync:a,topology:o,size:c,start:u,instanceCount:_}=e;r.shader.bind(n,a),r.geometry.bind(s,r.shader._activeProgram),i&&r.state.set(i),r.geometry.draw(o,c,u,_??s.instanceCount)}destroy(){this._renderer=null}}ce.extension={type:[l.WebGLSystem],name:"encoder"};class je{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this.msaaRenderBuffer=[]}}class ue{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:g.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this._stencilCache.enabled=!1,this._stencilCache.stencilMode=g.NONE,this._stencilCache.stencilReference=0}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let r=this._renderTargetStencilState[e.uid];r||(r=this._renderTargetStencilState[e.uid]={stencilMode:g.DISABLED,stencilReference:0}),this.setStencilMode(r.stencilMode,r.stencilReference)}setStencilMode(e,r){const s=this._renderTargetStencilState[this._activeRenderTarget.uid],n=this._gl,i=Ce[e],a=this._stencilCache;if(s.stencilMode=e,s.stencilReference=r,e===g.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,n.disable(n.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,n.enable(n.STENCIL_TEST)),(e!==a.stencilMode||a.stencilReference!==r)&&(a.stencilMode=e,a.stencilReference=r,n.stencilFunc(this._comparisonFuncMapping[i.stencilBack.compare],r,255),n.stencilOp(n.KEEP,n.KEEP,this._stencilOpsMapping[i.stencilBack.passOp]))}}ue.extension={type:[l.WebGLSystem],name:"stencil"};const _e={f32:4,"vec2":8,"vec3":12,"vec4":16,"mat2x2":16*2,"mat3x3":16*3,"mat4x4":16*4};function Ke(t){const e=t.map(i=>({data:i,offset:0,size:0}));let r=0,s=0,n=0;for(let i=0;i1&&(r=Math.max(r,16)*a.data.size),a.size=r,s%r!==0&&s<16){const o=s%r%16;s+=o,n+=o}s+r>16?(n=Math.ceil(n/16)*16,a.offset=n,n+=r,s=r):(a.offset=n,s+=r,n+=r)}return n=Math.ceil(n/16)*16,{uboElements:e,size:n}}function $e(t,e){const r=Math.max(_e[t.data.type]/16,1),s=t.data.value.length/t.data.size,n=(4-s%4)%4;return` + v = uv.${t.data.name}; + offset += ${e}; + + arrayOffset = offset; + + t = 0; + + for(var i=0; i < ${t.data.size*r}; i++) + { + for(var j = 0; j < ${s}; j++) + { + data[arrayOffset++] = v[t++]; + } + ${n!==0?`arrayOffset += ${n};`:""} + } + `}function ze(t){return Ge(t,"uboStd40",$e,Ue)}class fe extends Oe{constructor(){super({createUboElements:Ke,generateUboSync:ze})}}fe.extension={type:[l.WebGLSystem],name:"ubo"};class Ye{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}init(e,r){this._renderer=e,this._renderTargetSystem=r,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}copyToTexture(e,r,s,n,i){const a=this._renderTargetSystem,o=this._renderer,c=a.getGpuRenderTarget(e),u=o.gl;return this.finishRenderPass(e),u.bindFramebuffer(u.FRAMEBUFFER,c.resolveTargetFramebuffer),o.texture.bind(r,0),u.copyTexSubImage2D(u.TEXTURE_2D,0,i.x,i.y,s.x,s.y,n.width,n.height),r}startRenderPass(e,r=!0,s,n){const i=this._renderTargetSystem,a=e.colorTexture,o=i.getGpuRenderTarget(e);let c=n.y;e.isRoot&&(c=a.pixelHeight-n.height),e.colorTextures.forEach(h=>{this._renderer.texture.unbind(h)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,o.framebuffer);const _=this._viewPortCache;(_.x!==n.x||_.y!==c||_.width!==n.width||_.height!==n.height)&&(_.x=n.x,_.y=c,_.width=n.width,_.height=n.height,u.viewport(n.x,c,n.width,n.height)),!o.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(o),this.clear(e,r,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa)return;const n=this._renderer.gl;n.bindFramebuffer(n.FRAMEBUFFER,s.resolveTargetFramebuffer),n.bindFramebuffer(n.READ_FRAMEBUFFER,s.framebuffer),n.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.FRAMEBUFFER,s.framebuffer)}initGpuRenderTarget(e){const r=this._renderer,s=r.gl,n=new je;return e.colorTexture.resource===r.gl.canvas?(n.framebuffer=null,n):(this._initColor(e,n),s.bindFramebuffer(s.FRAMEBUFFER,null),n)}destroyGpuRenderTarget(e){const r=this._renderer.gl;e.framebuffer&&(r.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(r.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(r.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(s=>{r.deleteRenderbuffer(s)}),e.msaaRenderBuffer=null}clear(e,r,s){if(!r)return;const n=this._renderTargetSystem;typeof r=="boolean"&&(r=r?A.ALL:A.NONE);const i=this._renderer.gl;if(r&A.COLOR){s??(s=n.defaultClearColor);const a=this._clearColorCache,o=s;(a[0]!==o[0]||a[1]!==o[1]||a[2]!==o[2]||a[3]!==o[3])&&(a[0]=o[0],a[1]=o[1],a[2]=o[2],a[3]=o[3],i.clearColor(o[0],o[1],o[2],o[3]))}i.clear(r)}resizeGpuRenderTarget(e){if(e.isRoot)return;const s=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,s),e.stencil&&this._resizeStencil(s)}_initColor(e,r){const s=this._renderer,n=s.gl,i=n.createFramebuffer();if(r.resolveTargetFramebuffer=i,n.bindFramebuffer(n.FRAMEBUFFER,i),r.width=e.colorTexture.source.pixelWidth,r.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((a,o)=>{const c=a.source;c.antialias&&(s.context.supports.msaa?r.msaa=!0:m("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(c,0);const _=s.texture.getGlSource(c).texture;n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+o,3553,_,0)}),r.msaa){const a=n.createFramebuffer();r.framebuffer=a,n.bindFramebuffer(n.FRAMEBUFFER,a),e.colorTextures.forEach((o,c)=>{const u=n.createRenderbuffer();r.msaaRenderBuffer[c]=u})}else r.framebuffer=i;this._resizeColor(e,r)}_resizeColor(e,r){const s=e.colorTexture.source;if(r.width=s.pixelWidth,r.height=s.pixelHeight,e.colorTextures.forEach((n,i)=>{i!==0&&n.source.resize(s.width,s.height,s._resolution)}),r.msaa){const n=this._renderer,i=n.gl,a=r.framebuffer;i.bindFramebuffer(i.FRAMEBUFFER,a),e.colorTextures.forEach((o,c)=>{const u=o.source;n.texture.bindSource(u,0);const h=n.texture.getGlSource(u).internalFormat,d=r.msaaRenderBuffer[c];i.bindRenderbuffer(i.RENDERBUFFER,d),i.renderbufferStorageMultisample(i.RENDERBUFFER,4,h,u.pixelWidth,u.pixelHeight),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+c,i.RENDERBUFFER,d)})}}_initStencil(e){if(e.framebuffer===null)return;const r=this._renderer.gl,s=r.createRenderbuffer();e.depthStencilRenderBuffer=s,r.bindRenderbuffer(r.RENDERBUFFER,s),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,s),this._resizeStencil(e)}_resizeStencil(e){const r=this._renderer.gl;r.bindRenderbuffer(r.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?r.renderbufferStorageMultisample(r.RENDERBUFFER,4,r.DEPTH24_STENCIL8,e.width,e.height):r.renderbufferStorage(r.RENDERBUFFER,this._renderer.context.webGLVersion===2?r.DEPTH24_STENCIL8:r.DEPTH_STENCIL,e.width,e.height)}}class he extends Pe{constructor(e){super(e),this.adaptor=new Ye,this.adaptor.init(e,this)}}he.extension={type:[l.WebGLSystem],name:"renderTarget"};function qe(t,e){const r=[],s=[` + var g = s.groups; + var sS = r.shader; + var p = s.glProgram; + var ugS = r.uniformGroup; + var resources; + `];let n=!1,i=0,a=0;const o=e._getProgramData(t.glProgram);for(const u in t.groups){const _=t.groups[u];r.push(` + resources = g[${u}].resources; + `);for(const h in _.resources){const d=_.resources[h];if(d instanceof F)d.ubo?r.push(` + sS.bindUniformBlock( + resources[${h}], + sS._uniformBindMap[${u}[${h}], + ${i++} + ); + `):r.push(` + ugS.updateUniformGroup(resources[${h}], p, sD); + `);else if(d instanceof ee)r.push(` + sS.bindUniformBlock( + resources[${h}], + sS._uniformBindMap[${u}[${h}], + ${i++} + ); + `);else if(d instanceof $){const E=t._uniformBindMap[u][h],b=o.uniformData[E];b&&(n||(n=!0,s.push(` + var tS = r.texture; + `)),e._gl.uniform1i(b.location,a),r.push(` + tS.bind(resources[${h}], ${a}); + `),a++)}}}const c=[...s,...r].join(` +`);return new Function("r","s","sD",c)}class Ze{constructor(e,r){this.program=e,this.uniformData=r,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function V(t,e,r){const s=t.createShader(e);return t.shaderSource(s,r),t.compileShader(s),s}function I(t){const e=new Array(t);for(let r=0;ra>o?1:-1);for(let a=0;a`${_}: ${u}`),s=t.getShaderInfoLog(e),n=s.split(` +`),i={},a=n.map(u=>parseFloat(u.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(u=>u&&!i[u]?(i[u]=!0,!0):!1),o=[""];a.forEach(u=>{r[u-1]=`%c${r[u-1]}%c`,o.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const c=r.join(` +`);o[0]=c,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...o),console.groupEnd()}function st(t,e,r,s){t.getProgramParameter(e,t.LINK_STATUS)||(t.getShaderParameter(r,t.COMPILE_STATUS)||X(t,r),t.getShaderParameter(s,t.COMPILE_STATUS)||X(t,s),console.error("PixiJS Error: Could not initialize shader."),t.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",t.getProgramInfoLog(e)))}function nt(t,e){const r=V(t,t.VERTEX_SHADER,e.vertex),s=V(t,t.FRAGMENT_SHADER,e.fragment),n=t.createProgram();t.attachShader(n,r),t.attachShader(n,s);const i=e.transformFeedbackVaryings;i&&(typeof t.transformFeedbackVaryings!="function"?m("TransformFeedback is not supported but TransformFeedbackVaryings are given."):t.transformFeedbackVaryings(n,i.names,i.bufferMode==="separate"?t.SEPARATE_ATTRIBS:t.INTERLEAVED_ATTRIBS)),t.linkProgram(n),t.getProgramParameter(n,t.LINK_STATUS)||st(t,n,r,s),e._attributeData=et(n,t,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=rt(n,t),e._uniformBlockData=tt(n,t),t.deleteShader(r),t.deleteShader(s);const a={};for(const c in e._uniformData){const u=e._uniformData[c];a[c]={location:t.getUniformLocation(n,c),value:le(u.type,u.size)}}return new Ze(n,a)}const R={textureCount:0,blockIndex:0};class me{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._nextIndex=0,this._boundUniformsIdsToIndexHash=Object.create(null),this._boundIndexToUniformsHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._maxBindings=e.MAX_UNIFORM_BUFFER_BINDINGS?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0,this._programDataHash=Object.create(null),this._boundUniformsIdsToIndexHash=Object.create(null),this._boundIndexToUniformsHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,r){if(this._setProgram(e.glProgram),r)return;R.textureCount=0,R.blockIndex=0;let s=this._shaderSyncFunctions[e.glProgram._key];s||(s=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),s(this._renderer,e,R)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,R)}bindUniformBlock(e,r,s=0){const n=this._renderer.buffer,i=this._getProgramData(this._activeProgram),a=e._bufferResource;a&&this._renderer.ubo.updateUniformGroup(e),n.updateBuffer(e.buffer);let o=this._boundUniformsIdsToIndexHash[e.uid];if(o===void 0){const _=this._nextIndex++%this._maxBindings,h=this._boundIndexToUniformsHash[_];h&&(this._boundUniformsIdsToIndexHash[h.uid]=void 0),o=this._boundUniformsIdsToIndexHash[e.uid]=_,this._boundIndexToUniformsHash[_]=e,a?n.bindBufferRange(e.buffer,_,e.offset):n.bindBufferBase(e.buffer,_)}const c=this._gl,u=this._activeProgram._uniformBlockData[r].index;i.uniformBlockBindings[s]!==o&&(i.uniformBlockBindings[s]=o,c.uniformBlockBinding(i.program,u,o))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const r=this._getProgramData(e);this._gl.useProgram(r.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const r=e._key;return this._programDataHash[r]=nt(this._gl,e),this._programDataHash[r]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy(),this._programDataHash[e]=null;this._programDataHash=null,this._boundUniformsIdsToIndexHash=null}_generateShaderSync(e,r){return qe(e,r)}}me.extension={type:[l.WebGLSystem],name:"shader"};const it={f32:`if (cv !== v) { + cu.value = v; + gl.uniform1f(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2f(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3f(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4f(location, v[0], v[1], v[2], v[3]); + }`,i32:`if (cv !== v) { + cu.value = v; + gl.uniform1i(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2i(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3i(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`,u32:`if (cv !== v) { + cu.value = v; + gl.uniform1ui(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2ui(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3ui(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4ui(location, v[0], v[1], v[2], v[3]); + }`,bool:`if (cv !== v) { + cu.value = v; + gl.uniform1i(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2i(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3i(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`,"mat2x2":"gl.uniformMatrix2fv(location, false, v);","mat3x3":"gl.uniformMatrix3fv(location, false, v);","mat4x4":"gl.uniformMatrix4fv(location, false, v);"},at={f32:"gl.uniform1fv(location, v);","vec2":"gl.uniform2fv(location, v);","vec3":"gl.uniform3fv(location, v);","vec4":"gl.uniform4fv(location, v);","mat2x2":"gl.uniformMatrix2fv(location, false, v);","mat3x3":"gl.uniformMatrix3fv(location, false, v);","mat4x4":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);"};function ot(t,e){const r=[` + var v = null; + var cv = null; + var cu = null; + var t = 0; + var gl = renderer.gl; + var name = null; + `];for(const s in t.uniforms){if(!e[s]){t.uniforms[s]instanceof F?t.uniforms[s].ubo?r.push(` + renderer.shader.bindUniformBlock(uv.${s}, "${s}"); + `):r.push(` + renderer.shader.updateUniformGroup(uv.${s}); + `):t.uniforms[s]instanceof ee&&r.push(` + renderer.shader.bindBufferResource(uv.${s}, "${s}"); + `);continue}const n=t.uniformStructures[s];let i=!1;for(let a=0;a>1,s++;this.stateId=e.data}for(let r=0;r>1,1),n=Math.max(n>>1,1)}}},Se={id:"image",upload(t,e,r,s){const n=t.alphaMode==="premultiply-alpha-on-upload";r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n);const i=e.width,a=e.height,o=t.pixelWidth,c=t.pixelHeight,u=t.resourceWidth,_=t.resourceHeight;u1){const u=Math.min(t.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[n](c,s.TEXTURE_MAX_ANISOTROPY_EXT,u)}t.compare&&e[n](c,e.TEXTURE_COMPARE_FUNC,Tt[t.compare])}function vt(t){return{r8unorm:t.RED,r8snorm:t.RED,r8uint:t.RED,r8sint:t.RED,r16uint:t.RED,r16sint:t.RED,r16float:t.RED,rg8unorm:t.RG,rg8snorm:t.RG,rg8uint:t.RG,rg8sint:t.RG,r32uint:t.RED,r32sint:t.RED,r32float:t.RED,rg16uint:t.RG,rg16sint:t.RG,rg16float:t.RG,rgba8unorm:t.RGBA,"rgba8unorm-srgb":t.RGBA,rgba8snorm:t.RGBA,rgba8uint:t.RGBA,rgba8sint:t.RGBA,bgra8unorm:t.RGBA,"bgra8unorm-srgb":t.RGBA,rgb9e5ufloat:t.RGB,rgb10a2unorm:t.RGBA,rg11b10ufloat:t.RGB,rg32uint:t.RG,rg32sint:t.RG,rg32float:t.RG,rgba16uint:t.RGBA,rgba16sint:t.RGBA,rgba16float:t.RGBA,rgba32uint:t.RGBA,rgba32sint:t.RGBA,rgba32float:t.RGBA,stencil8:t.STENCIL_INDEX8,depth16unorm:t.DEPTH_COMPONENT,depth24plus:t.DEPTH_COMPONENT,"depth24plus-stencil8":t.DEPTH_STENCIL,depth32float:t.DEPTH_COMPONENT,"depth32float-stencil8":t.DEPTH_STENCIL}}function xt(t,e){let r={},s=t.RGBA;return t instanceof G.get().getWebGLRenderingContext()?e.srgb&&(r={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(r={"rgba8unorm-srgb":t.SRGB8_ALPHA8,"bgra8unorm-srgb":t.SRGB8_ALPHA8},s=t.RGBA8),{r8unorm:t.R8,r8snorm:t.R8_SNORM,r8uint:t.R8UI,r8sint:t.R8I,r16uint:t.R16UI,r16sint:t.R16I,r16float:t.R16F,rg8unorm:t.RG8,rg8snorm:t.RG8_SNORM,rg8uint:t.RG8UI,rg8sint:t.RG8I,r32uint:t.R32UI,r32sint:t.R32I,r32float:t.R32F,rg16uint:t.RG16UI,rg16sint:t.RG16I,rg16float:t.RG16F,rgba8unorm:t.RGBA,...r,rgba8snorm:t.RGBA8_SNORM,rgba8uint:t.RGBA8UI,rgba8sint:t.RGBA8I,bgra8unorm:s,rgb9e5ufloat:t.RGB9_E5,rgb10a2unorm:t.RGB10_A2,rg11b10ufloat:t.R11F_G11F_B10F,rg32uint:t.RG32UI,rg32sint:t.RG32I,rg32float:t.RG32F,rgba16uint:t.RGBA16UI,rgba16sint:t.RGBA16I,rgba16float:t.RGBA16F,rgba32uint:t.RGBA32UI,rgba32sint:t.RGBA32I,rgba32float:t.RGBA32F,stencil8:t.STENCIL_INDEX8,depth16unorm:t.DEPTH_COMPONENT16,depth24plus:t.DEPTH_COMPONENT24,"depth24plus-stencil8":t.DEPTH24_STENCIL8,depth32float:t.DEPTH_COMPONENT32F,"depth32float-stencil8":t.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function Bt(t){return{r8unorm:t.UNSIGNED_BYTE,r8snorm:t.BYTE,r8uint:t.UNSIGNED_BYTE,r8sint:t.BYTE,r16uint:t.UNSIGNED_SHORT,r16sint:t.SHORT,r16float:t.HALF_FLOAT,rg8unorm:t.UNSIGNED_BYTE,rg8snorm:t.BYTE,rg8uint:t.UNSIGNED_BYTE,rg8sint:t.BYTE,r32uint:t.UNSIGNED_INT,r32sint:t.INT,r32float:t.FLOAT,rg16uint:t.UNSIGNED_SHORT,rg16sint:t.SHORT,rg16float:t.HALF_FLOAT,rgba8unorm:t.UNSIGNED_BYTE,"rgba8unorm-srgb":t.UNSIGNED_BYTE,rgba8snorm:t.BYTE,rgba8uint:t.UNSIGNED_BYTE,rgba8sint:t.BYTE,bgra8unorm:t.UNSIGNED_BYTE,"bgra8unorm-srgb":t.UNSIGNED_BYTE,rgb9e5ufloat:t.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:t.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:t.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:t.UNSIGNED_INT,rg32sint:t.INT,rg32float:t.FLOAT,rgba16uint:t.UNSIGNED_SHORT,rgba16sint:t.SHORT,rgba16float:t.HALF_FLOAT,rgba32uint:t.UNSIGNED_INT,rgba32sint:t.INT,rgba32float:t.FLOAT,stencil8:t.UNSIGNED_BYTE,depth16unorm:t.UNSIGNED_SHORT,depth24plus:t.UNSIGNED_INT,"depth24plus-stencil8":t.UNSIGNED_INT_24_8,depth32float:t.FLOAT,"depth32float-stencil8":t.FLOAT_32_UNSIGNED_INT_24_8_REV}}const At=4;class ge{constructor(e){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:Se,buffer:bt,video:pt,compressed:gt},this._useSeparateSamplers=!1,this._renderer=e}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=xt(e,this._renderer.context.extensions),this._mapFormatToType=Bt(e),this._mapFormatToFormat=vt(e)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null);for(let r=0;r<16;r++)this.bind(S.EMPTY,r)}initSource(e){this.bind(e)}bind(e,r=0){const s=e.source;e?(this.bindSource(s,r),this._useSeparateSamplers&&this._bindSampler(s.style,r)):(this.bindSource(null,r),this._useSeparateSamplers&&this._bindSampler(null,r))}bindSource(e,r=0){const s=this._gl;if(e._touched=this._renderer.textureGC.count,this._boundTextures[r]!==e){this._boundTextures[r]=e,this._activateLocation(r),e=e||S.EMPTY.source;const n=this.getGlSource(e);s.bindTexture(n.target,n.texture)}}_bindSampler(e,r=0){const s=this._gl;if(!e){this._boundSamplers[r]=null,s.bindSampler(r,null);return}const n=this._getGlSampler(e);this._boundSamplers[r]!==n&&(this._boundSamplers[r]=n,s.bindSampler(r,n))}unbind(e){const r=e.source,s=this._boundTextures,n=this._gl;for(let i=0;i1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",s.TEXTURE_2D,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,r)}onSourceUnload(e){const r=this._glTextures[e.uid];r&&(this.unbind(e),this._glTextures[e.uid]=null,this._gl.deleteTexture(r.texture))}onSourceUpdate(e){const r=this._gl,s=this.getGlSource(e);r.bindTexture(r.TEXTURE_2D,s.texture),this._boundTextures[this._activeTextureLocation]=e,this._uploads[e.uploadMethodId]?this._uploads[e.uploadMethodId].upload(e,s,r,this._renderer.context.webGLVersion):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e.pixelWidth,e.pixelHeight,0,r.RGBA,r.UNSIGNED_BYTE,null),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,r=!0){r&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}onSourceDestroy(e){e.off("destroy",this.onSourceDestroy,this),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("unload",this.onSourceUnload,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(e),1),this.onSourceUnload(e)}_initSampler(e){const r=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,j(e,r,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return this._glTextures[e.uid]||this._initSource(e)}generateCanvas(e){const{pixels:r,width:s,height:n}=this.getPixels(e),i=G.get().createCanvas();i.width=s,i.height=n;const a=i.getContext("2d");if(a){const o=a.createImageData(s,n);o.data.set(r),a.putImageData(o,0,0)}return i}getPixels(e){const r=e.source.resolution,s=e.frame,n=Math.max(Math.round(s.width*r),1),i=Math.max(Math.round(s.height*r),1),a=new Uint8Array(At*n*i),o=this._renderer,c=o.renderTarget.getRenderTarget(e),u=o.renderTarget.getGpuRenderTarget(c),_=o.gl;return _.bindFramebuffer(_.FRAMEBUFFER,u.resolveTargetFramebuffer),_.readPixels(Math.round(s.x*r),Math.round(s.y*r),n,i,_.RGBA,_.UNSIGNED_BYTE,a),{pixels:new Uint8ClampedArray(a.buffer),width:n,height:i}}destroy(){this.managedTextures.slice().forEach(e=>this.onSourceDestroy(e)),this.managedTextures=null,this._renderer=null}}ge.extension={type:[l.WebGLSystem],name:"texture"};class pe{init(){const e=new F({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uTransformMatrix:{value:new z,type:"mat3x3"},uRound:{value:0,type:"f32"}}),r=K(),s=O({name:"graphics",bits:[Y,q(r),Q,P]});this.shader=new x({glProgram:s,resources:{localUniforms:e,batchSamplers:J(r)}})}execute(e,r){const s=r.context,n=s.customShader||this.shader,i=e.renderer,a=i.graphicsContext,{geometry:o,instructions:c}=a.getContextRenderData(s);n.groups[0]=i.globalUniforms.bindGroup,i.state.set(e.state),i.shader.bind(n),i.geometry.bind(o,n.glProgram);const u=c.instructions;for(let _=0;_",value:new z}}}})}execute(e,r){const s=e.renderer;let n=r._shader;if(n){if(!n.glProgram){m("Mesh shader has no glProgram",r.shader);return}}else{n=this._shader;const i=r.texture,a=i.source;n.resources.uTexture=a,n.resources.uSampler=a.style,n.resources.textureUniforms.uniforms.uTextureMatrix=i.textureMatrix.mapCoord}n.groups[100]=s.globalUniforms.bindGroup,n.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:r._geometry,shader:n,state:r.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Re.extension={type:[l.WebGLPipesAdaptor],name:"mesh"};const Nt=[...Me,fe,We,we,re,ge,he,ie,Ee,me,ce,mt,ue,oe],It=[...Le],yt=[te,Re,pe],Te=[],ve=[],xe=[];v.handleByNamedList(l.WebGLSystem,Te);v.handleByNamedList(l.WebGLPipes,ve);v.handleByNamedList(l.WebGLPipesAdaptor,xe);v.add(...Nt,...It,...yt);class Ot extends Ne{constructor(){const e={name:"webgl",type:ye.WEBGL,systems:Te,renderPipes:ve,renderPipeAdaptors:xe};super(e)}}export{Ot as WebGLRenderer}; diff --git a/public/assets/games/bulletzio/assets/browserAll-0a2jxxd3.js b/public/assets/games/bulletzio/assets/browserAll-0a2jxxd3.js new file mode 100644 index 00000000..d2fc96fd --- /dev/null +++ b/public/assets/games/bulletzio/assets/browserAll-0a2jxxd3.js @@ -0,0 +1 @@ +import{P as m,r as J,E as w,T as L,U as Q,a as ee,w as y,e as z,C as Z}from"./index-BphGqh_l.js";import"./webworkerAll-DrJagYzl.js";import"./colorToUniform-CXyy9as8.js";import"./getBatchSamplersUniformGroup-BY8U1LLP.js";class M{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=M.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new m,this.page=new m,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,n,s){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var O=/iPhone/i,C=/iPod/i,S=/iPad/i,U=/\biOS-universal(?:.+)Mac\b/i,k=/\bAndroid(?:.+)Mobile\b/i,H=/Android/i,b=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,A=/Silk/i,g=/Windows Phone/i,X=/\bWindows(?:.+)ARM\b/i,R=/BlackBerry/i,F=/BB10/i,Y=/Opera Mini/i,K=/\b(CriOS|Chrome)(?:.+)Mobile/i,$=/Mobile(?:.+)Firefox\b/i,G=function(o){return typeof o<"u"&&o.platform==="MacIntel"&&typeof o.maxTouchPoints=="number"&&o.maxTouchPoints>1&&typeof MSStream>"u"};function te(o){return function(e){return e.test(o)}}function W(o){var e={userAgent:"",platform:"",maxTouchPoints:0};!o&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof o=="string"?e.userAgent=o:o&&o.userAgent&&(e={userAgent:o.userAgent,platform:o.platform,maxTouchPoints:o.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var n=te(t),s={apple:{phone:n(O)&&!n(g),ipod:n(C),tablet:!n(O)&&(n(S)||G(e))&&!n(g),universal:n(U),device:(n(O)||n(C)||n(S)||n(U)||G(e))&&!n(g)},amazon:{phone:n(b),tablet:!n(b)&&n(A),device:n(b)||n(A)},android:{phone:!n(g)&&n(b)||!n(g)&&n(k),tablet:!n(g)&&!n(b)&&!n(k)&&(n(A)||n(H)),device:!n(g)&&(n(b)||n(A)||n(k)||n(H))||n(/\bokhttp\b/i)},windows:{phone:n(g),tablet:n(X),device:n(g)||n(X)},other:{blackberry:n(R),blackberry10:n(F),opera:n(Y),firefox:n($),chrome:n(K),device:n(R)||n(F)||n(Y)||n($)||n(K)},any:!1,phone:!1,tablet:!1};return s.any=s.apple.device||s.android.device||s.windows.device||s.other.device,s.phone=s.apple.phone||s.android.phone||s.windows.phone,s.tablet=s.apple.tablet||s.android.tablet||s.windows.tablet,s}const ie=W.default??W,ne=ie(globalThis.navigator),se=9,I=100,oe=0,re=0,j=2,N=1,ae=-1e3,he=-1e3,le=2;class V{constructor(e,t=ne){this._mobileInfo=t,this.debug=!1,this._isActive=!1,this._isMobileAccessibility=!1,this._pool=[],this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook();const i=document.createElement("div");i.style.width=`${I}px`,i.style.height=`${I}px`,i.style.position="absolute",i.style.top=`${oe}px`,i.style.left=`${re}px`,i.style.zIndex=j.toString(),this._div=i,this._renderer=e,this._onKeyDown=this._onKeyDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),globalThis.addEventListener("keydown",this._onKeyDown,!1)}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}_createTouchHook(){const e=document.createElement("button");e.style.width=`${N}px`,e.style.height=`${N}px`,e.style.position="absolute",e.style.top=`${ae}px`,e.style.left=`${he}px`,e.style.zIndex=le.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){this._isActive||(this._isActive=!0,globalThis.document.addEventListener("mousemove",this._onMouseMove,!0),globalThis.removeEventListener("keydown",this._onKeyDown,!1),this._renderer.runners.postrender.add(this),this._renderer.view.canvas.parentNode?.appendChild(this._div))}_deactivate(){!this._isActive||this._isMobileAccessibility||(this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._onMouseMove,!0),globalThis.addEventListener("keydown",this._onKeyDown,!1),this._renderer.runners.postrender.remove(this),this._div.parentNode?.removeChild(this._div))}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&e.isInteractive()&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let i=0;i title : ${e.title}
tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:i}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>i&&(e.height=i-e.y)}_addChild(e){let t=this._pool.pop();t||(t=document.createElement("button"),t.style.width=`${I}px`,t.style.height=`${I}px`,t.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",t.style.position="absolute",t.style.zIndex=j.toString(),t.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?t.setAttribute("aria-live","off"):t.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?t.setAttribute("aria-relevant","additions"):t.setAttribute("aria-relevant","text"),t.addEventListener("click",this._onClick.bind(this)),t.addEventListener("focus",this._onFocus.bind(this)),t.addEventListener("focusout",this._onFocusOut.bind(this))),t.style.pointerEvents=e.accessiblePointerEvents,t.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?t.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(t.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&t.setAttribute("aria-label",e.accessibleHint),this.debug&&this._updateDebugHTML(t),e._accessibleActive=!0,e._accessibleDiv=t,t.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv),e._accessibleDiv.tabIndex=e.tabIndex}_dispatchEvent(e,t){const{container:i}=e.target,n=this._renderer.events.rootBoundary,s=Object.assign(new M(n),{target:i});n.rootTarget=this._renderer.lastObjectRendered,t.forEach(r=>n.dispatchEvent(s,r))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode===se&&this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){this._destroyTouchHook(),this._div=null,globalThis.document.removeEventListener("mousemove",this._onMouseMove,!0),globalThis.removeEventListener("keydown",this._onKeyDown),this._pool=null,this._children=null,this._renderer=null}}V.extension={type:[w.WebGLSystem,w.WebGPUSystem],name:"accessibility"};const ue={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,_accessibleActive:!1,_accessibleDiv:null,accessibleType:"button",accessiblePointerEvents:"auto",accessibleChildren:!0,_renderId:-1};class de{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(L.system.add(this._tickerUpdate,this,Q.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(L.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTimei.priority-n.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let i=0,n=t.length;i=0;n--)if(e.currentTarget=i[n],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,i=this._allInteractiveElements){if(i.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const n=Array.isArray(t)?t:[t];for(let s=i.length-1;s>=0;s--)n.forEach(r=>{e.currentTarget=i[s],this.notifyTarget(e,r)})}propagationPath(e){const t=[e];for(let i=0;i=0;l--){const d=h[l],u=this.hitTestMoveRecursive(d,this._isInteractive(t)?t:d.eventMode,i,n,s,r||s(e,i));if(u){if(u.length>0&&!u[u.length-1].parent)continue;const v=e.isInteractive();(u.length>0||v)&&(v&&this._allInteractiveElements.push(e),u.push(e)),this._hitElements.length===0&&(this._hitElements=u),a=!0}}}const c=this._isInteractive(t),p=e.isInteractive();return p&&p&&this._allInteractiveElements.push(e),r||this._hitElements.length>0?null:a?this._hitElements:c&&!s(e,i)&&n(e,i)?p?[e]:[]:null}hitTestRecursive(e,t,i,n,s){if(this._interactivePrune(e)||s(e,i))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(E.pauseUpdate=!1),e.interactiveChildren&&e.children){const c=e.children,p=i;for(let h=c.length-1;h>=0;h--){const l=c[h],d=this.hitTestRecursive(l,this._isInteractive(t)?t:l.eventMode,p,n,s);if(d){if(d.length>0&&!d[d.length-1].parent)continue;const u=e.isInteractive();return(d.length>0||u)&&d.push(e),d}}}const r=this._isInteractive(t),a=e.isInteractive();return r&&n(e,i)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.includeInBuild||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,P),!e.hitArea.contains(P.x,P.y)))return!0;if(e.effects&&e.effects.length)for(let i=0;i0&&s!==t.target){const c=e.type==="mousemove"?"mouseout":"pointerout",p=this.createPointerEvent(e,c,s);if(this.dispatchEvent(p,"pointerout"),i&&this.dispatchEvent(p,"mouseout"),!t.composedPath().includes(s)){const h=this.createPointerEvent(e,"pointerleave",s);for(h.eventPhase=h.AT_TARGET;h.target&&!t.composedPath().includes(h.target);)h.currentTarget=h.target,this.notifyTarget(h),i&&this.notifyTarget(h,"mouseleave"),h.target=h.target.parent;this.freeEvent(h)}this.freeEvent(p)}if(s!==t.target){const c=e.type==="mousemove"?"mouseover":"pointerover",p=this.clonePointerEvent(t,c);this.dispatchEvent(p,"pointerover"),i&&this.dispatchEvent(p,"mouseover");let h=s?.parent;for(;h&&h!==this.rootTarget.parent&&h!==t.target;)h=h.parent;if(!h||h===this.rootTarget.parent){const d=this.clonePointerEvent(t,"pointerenter");for(d.eventPhase=d.AT_TARGET;d.target&&d.target!==s&&d.target!==this.rootTarget.parent;)d.currentTarget=d.target,this.notifyTarget(d),i&&this.notifyTarget(d,"mouseenter"),d.target=d.target.parent;this.freeEvent(d)}this.freeEvent(p)}const r=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?r.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&r.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?r.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&r.push("globaltouchmove")),i&&(this.moveOnAll?r.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&r.push("globalmousemove"),this.cursor=t.target?.cursor),r.length>0&&this.all(t,r),this._allInteractiveElements.length=0,this._hitElements.length=0,n.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof f)){y("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.createPointerEvent(e),n=i.pointerType==="mouse"||i.pointerType==="pen";this.dispatchEvent(i,"pointerover"),n&&this.dispatchEvent(i,"mouseover"),i.pointerType==="mouse"&&(this.cursor=i.target?.cursor);const s=this.clonePointerEvent(i,"pointerenter");for(s.eventPhase=s.AT_TARGET;s.target&&s.target!==this.rootTarget.parent;)s.currentTarget=s.target,this.notifyTarget(s),n&&this.notifyTarget(s,"mouseenter"),s.target=s.target.parent;t.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(s)}mapPointerOut(e){if(!(e instanceof f)){y("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const i=e.pointerType==="mouse"||e.pointerType==="pen",n=this.findMountedTarget(t.overTargets),s=this.createPointerEvent(e,"pointerout",n);this.dispatchEvent(s),i&&this.dispatchEvent(s,"mouseout");const r=this.createPointerEvent(e,"pointerleave",n);for(r.eventPhase=r.AT_TARGET;r.target&&r.target!==this.rootTarget.parent;)r.currentTarget=r.target,this.notifyTarget(r),i&&this.notifyTarget(r,"mouseleave"),r.target=r.target.parent;t.overTargets=null,this.freeEvent(s),this.freeEvent(r)}this.cursor=null}mapPointerUp(e){if(!(e instanceof f)){y("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),i=this.createPointerEvent(e);if(this.dispatchEvent(i,"pointerup"),i.pointerType==="touch")this.dispatchEvent(i,"touchend");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const a=i.button===2;this.dispatchEvent(i,a?"rightup":"mouseup")}const n=this.trackingData(e.pointerId),s=this.findMountedTarget(n.pressTargetsByButton[e.button]);let r=s;if(s&&!i.composedPath().includes(s)){let a=s;for(;a&&!i.composedPath().includes(a);){if(i.currentTarget=a,this.notifyTarget(i,"pointerupoutside"),i.pointerType==="touch")this.notifyTarget(i,"touchendoutside");else if(i.pointerType==="mouse"||i.pointerType==="pen"){const c=i.button===2;this.notifyTarget(i,c?"rightupoutside":"mouseupoutside")}a=a.parent}delete n.pressTargetsByButton[e.button],r=a}if(r){const a=this.clonePointerEvent(i,"click");a.target=r,a.path=null,n.clicksByButton[e.button]||(n.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const c=n.clicksByButton[e.button];if(c.target===a.target&&t-c.timeStamp<200?++c.clickCount:c.clickCount=1,c.target=a.target,c.timeStamp=t,a.detail=c.clickCount,a.pointerType==="mouse"){const p=a.button===2;this.dispatchEvent(a,p?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(i)}mapPointerUpOutside(e){if(!(e instanceof f)){y("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),i=this.findMountedTarget(t.pressTargetsByButton[e.button]),n=this.createPointerEvent(e);if(i){let s=i;for(;s;)n.currentTarget=s,this.notifyTarget(n,"pointerupoutside"),n.pointerType==="touch"?this.notifyTarget(n,"touchendoutside"):(n.pointerType==="mouse"||n.pointerType==="pen")&&this.notifyTarget(n,n.button===2?"rightupoutside":"mouseupoutside"),s=s.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(n)}mapWheel(e){if(!(e instanceof T)){y("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let i=1;i(i==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=n),t[i]=n,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:i}=this.renderer;this.setTargetElement(t),this.resolution=i,x._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e=e||"default";let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const i=this.cursorStyles[e];if(i)switch(typeof i){case"string":t&&(this.domElement.style.cursor=i);break;case"function":i(e);break;case"object":t&&Object.assign(this.domElement.style,i);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let i=0,n=t.length;i0&&(t=e.composedPath()[0]);const i=t!==this.domElement?"outside":"",n=this._normalizeToPointerData(e);for(let s=0,r=n.length;s"u"&&(s.button=0),typeof s.buttons>"u"&&(s.buttons=1),typeof s.isPrimary>"u"&&(s.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof s.width>"u"&&(s.width=s.radiusX||1),typeof s.height>"u"&&(s.height=s.radiusY||1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="touch"),typeof s.pointerId>"u"&&(s.pointerId=s.identifier||0),typeof s.pressure>"u"&&(s.pressure=s.force||.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),typeof s.layerX>"u"&&(s.layerX=s.offsetX=s.clientX),typeof s.layerY>"u"&&(s.layerY=s.offsetY=s.clientY),s.isNormalized=!0,s.type=e.type,t.push(s)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const i=e;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=fe),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,t.push(i)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=ge[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};B.extension={name:"events",type:[w.WebGLSystem,w.CanvasSystem,w.WebGPUSystem],priority:-1};B.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let q=B;const me={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(o){this.eventMode=o?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??q.defaultEventMode},set eventMode(o){this._internalEventMode=o},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(o,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,n=typeof t=="object"?t.signal:void 0,s=typeof t=="object"?t.once===!0:!1,r=typeof e=="function"?void 0:e;o=i?`${o}capture`:o;const a=typeof e=="function"?e:e.handleEvent,c=this;n&&n.addEventListener("abort",()=>{c.off(o,a,r)}),s?c.once(o,a,r):c.on(o,a,r)},removeEventListener(o,e,t){const i=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,n=typeof e=="function"?void 0:e;o=i?`${o}capture`:o,e=typeof e=="function"?e:e.handleEvent,this.off(o,e,n)},dispatchEvent(o){if(!(o instanceof M))throw new Error("Container cannot propagate events outside of the Federated Events API");return o.defaultPrevented=!1,o.path=null,o.target=this,o.manager.dispatchEvent(o),!o.defaultPrevented}};z.add(V);Z.mixin(ue);z.add(q);Z.mixin(me); diff --git a/public/assets/games/bulletzio/assets/colorToUniform-CXyy9as8.js b/public/assets/games/bulletzio/assets/colorToUniform-CXyy9as8.js new file mode 100644 index 00000000..5986d81b --- /dev/null +++ b/public/assets/games/bulletzio/assets/colorToUniform-CXyy9as8.js @@ -0,0 +1,257 @@ +import{m as mt,u as K,a as dt,d as T,j as ht,l as pt,n as X,w as gt,g as N}from"./index-BphGqh_l.js";const C=Object.create(null),Y=Object.create(null);function W(o,t){let e=Y[o];return e===void 0&&(C[t]===void 0&&(C[t]=1),Y[o]=e=C[t]++),e}let G;function xt(){if(!G){G="mediump";const o=mt();o&&o.getShaderPrecisionFormat&&(G=o.getShaderPrecisionFormat(o.FRAGMENT_SHADER,o.HIGH_FLOAT).precision?"highp":"mediump")}return G}function vt(o,t,e){return t?o:e?(o=o.replace("out vec4 finalColor;",""),` + + #ifdef GL_ES // This checks if it is WebGL1 + #define in varying + #define finalColor gl_FragColor + #define texture texture2D + #endif + ${o} + `):` + + #ifdef GL_ES // This checks if it is WebGL1 + #define in attribute + #define out varying + #endif + ${o} + `}function bt(o,t,e){const r=e?t.maxSupportedFragmentPrecision:t.maxSupportedVertexPrecision;if(o.substring(0,9)!=="precision"){let n=e?t.requestedFragmentPrecision:t.requestedVertexPrecision;return n==="highp"&&r!=="highp"&&(n="mediump"),`precision ${n} float; +${o}`}else if(r!=="highp"&&o.substring(0,15)==="precision highp")return o.replace("precision highp","precision mediump");return o}function Pt(o,t){return t?`#version 300 es +${o}`:o}const yt={},_t={};function Mt(o,{name:t="pixi-program"},e=!0){t=t.replace(/\s+/g,"-"),t+=e?"-fragment":"-vertex";const r=e?yt:_t;return r[t]?(r[t]++,t+=`-${r[t]}`):r[t]=1,o.indexOf("#define SHADER_NAME")!==-1?o:`${`#define SHADER_NAME ${t}`} +${o}`}function Gt(o,t){return t?o.replace("#version 300 es",""):o}const $={stripVersion:Gt,ensurePrecision:bt,addProgramDefines:vt,setProgramName:Mt,insertVersion:Pt},U=Object.create(null),ot=class L{constructor(t){t={...L.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,r={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:xt()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let n=t.fragment,s=t.vertex;Object.keys($).forEach(a=>{const i=r[a];n=$[a](n,i,!0),s=$[a](s,i,!1)}),this.fragment=n,this.vertex=s,this._key=W(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return U[e]||(U[e]=new L(t)),U[e]}};ot.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let nt=ot;const q={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function St(o){return q[o]??q.float32}const Tt={f32:"float32","vec2":"float32x2","vec3":"float32x3","vec4":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2":"sint32x2","vec3":"sint32x3","vec4":"sint32x4",u32:"uint32","vec2":"uint32x2","vec3":"uint32x3","vec4":"uint32x4",bool:"uint32","vec2":"uint32x2","vec3":"uint32x3","vec4":"uint32x4"};function Ct({source:o,entryPoint:t}){const e={},r=o.indexOf(`fn ${t}`);if(r!==-1){const n=o.indexOf("->",r);if(n!==-1){const s=o.substring(r,n),a=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;let i;for(;(i=a.exec(s))!==null;){const u=Tt[i[3]]??"float32";e[i[2]]={location:parseInt(i[1],10),format:u,stride:St(u).stride,offset:0,instance:!1,start:0}}}}return e}function A(o){const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,r=/@binding\((\d+)\)/,n=/var(<[^>]+>)? (\w+)/,s=/:\s*(\w+)/,a=/struct\s+(\w+)\s*{([^}]+)}/g,i=/(\w+)\s*:\s*([\w\<\>]+)/g,u=/struct\s+(\w+)/,f=o.match(t)?.map(l=>({group:parseInt(l.match(e)[1],10),binding:parseInt(l.match(r)[1],10),name:l.match(n)[2],isUniform:l.match(n)[1]==="",type:l.match(s)[1]}));if(!f)return{groups:[],structs:[]};const c=o.match(a)?.map(l=>{const m=l.match(u)[1],p=l.match(i).reduce((g,x)=>{const[v,b]=x.split(":");return g[v.trim()]=b.trim(),g},{});return p?{name:m,members:p}:null}).filter(({name:l})=>f.some(m=>m.type===l))??[];return{groups:f,structs:c}}var P=(o=>(o[o.VERTEX=1]="VERTEX",o[o.FRAGMENT=2]="FRAGMENT",o[o.COMPUTE=4]="COMPUTE",o))(P||{});function $t({groups:o}){const t=[];for(let e=0;ee.has(a.name)?!1:(e.add(a.name),!0)),s=[...o.groups,...t.groups].filter(a=>{const i=`${a.name}-${a.binding}`;return r.has(i)?!1:(r.add(i),!0)});return{structs:n,groups:s}}const E=Object.create(null);class S{constructor(t){this._layoutKey=0;const{fragment:e,vertex:r,layout:n,gpuLayout:s,name:a}=t;if(this.name=a,this.fragment=e,this.vertex=r,e.source===r.source){const i=A(e.source);this.structsAndGroups=i}else{const i=A(r.source),u=A(e.source);this.structsAndGroups=At(i,u)}this.layout=n??Ut(this.structsAndGroups),this.gpuLayout=s??$t(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,r=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=W(r,"program")}get attributeData(){return this._attributeData??(this._attributeData=Ct(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return E[e]||(E[e]=new S(t)),E[e]}}const st=["f32","i32","vec2","vec3","vec4","mat2x2","mat3x3","mat4x4","mat3x2","mat4x2","mat2x3","mat4x3","mat2x4","mat3x4"],Et=st.reduce((o,t)=>(o[t]=!0,o),{});function wt(o,t){switch(o){case"f32":return 0;case"vec2":return new Float32Array(2*t);case"vec3":return new Float32Array(3*t);case"vec4":return new Float32Array(4*t);case"mat2x2":return new Float32Array([1,0,0,1]);case"mat3x3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const it=class at{constructor(t,e){this._touched=0,this.uid=K("uniform"),this._resourceType="uniformGroup",this._resourceId=K("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...at.defaultOptions,...e},this.uniformStructures=t;const r={};for(const n in t){const s=t[n];if(s.name=n,s.size=s.size??1,!Et[s.type])throw new Error(`Uniform type ${s.type} is not supported. Supported uniform types are: ${st.join(", ")}`);s.value??(s.value=wt(s.type,s.size)),r[n]=s.value}this.uniforms=r,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=W(Object.keys(r).map(n=>`${n}-${t[n].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};it.defaultOptions={ubo:!1,isStatic:!1};let Ft=it;var H=(o=>(o[o.WEBGL=1]="WEBGL",o[o.WEBGPU=2]="WEBGPU",o[o.BOTH=3]="BOTH",o))(H||{});class ut extends dt{constructor(t){super(),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[];let{gpuProgram:e,glProgram:r,groups:n,resources:s,compatibleRenderers:a,groupMap:i}=t;this.gpuProgram=e,this.glProgram=r,a===void 0&&(a=0,e&&(a|=H.WEBGPU),r&&(a|=H.WEBGL)),this.compatibleRenderers=a;const u={};if(!s&&!n&&(s={}),s&&n)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&n&&!i)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&n&&i)for(const f in i)for(const c in i[f]){const l=i[f][c];u[l]={group:f,binding:c,name:l}}else if(e&&n&&!i){const f=e.structsAndGroups.groups;i={},f.forEach(c=>{i[c.group]=i[c.group]||{},i[c.group][c.binding]=c.name,u[c.name]=c})}else if(s){if(e){const f=e.structsAndGroups.groups;i={},f.forEach(c=>{i[c.group]=i[c.group]||{},i[c.group][c.binding]=c.name,u[c.name]=c})}else{i={},n={99:new T},this._ownedBindGroups.push(n[99]);let f=0;for(const c in s)u[c]={group:99,binding:f,name:c},i[99]=i[99]||{},i[99][f]=c,f++}n={};for(const f in s){const c=f;let l=s[f];!l.source&&!l._resourceType&&(l=new Ft(l));const m=u[c];m&&(n[m.group]||(n[m.group]=new T,this._ownedBindGroups.push(n[m.group])),n[m.group].setResource(l,m.binding))}}this.groups=n,this._uniformBindMap=i,this.resources=this._buildResourceAccessor(n,u)}addResource(t,e,r){var n,s;(n=this._uniformBindMap)[e]||(n[e]={}),(s=this._uniformBindMap[e])[r]||(s[r]=t),this.groups[e]||(this.groups[e]=new T,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const r={};for(const n in e){const s=e[n];Object.defineProperty(r,s.name,{get(){return t[s.group].getResource(s.binding)},set(a){t[s.group].setResource(a,s.binding)}})}return r}destroy(t=!1){this.emit("destroy",this),t&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(e=>{e.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null}static from(t){const{gpu:e,gl:r,...n}=t;let s,a;return e&&(s=S.from(e)),r&&(a=nt.from(r)),new ut({gpuProgram:s,glProgram:a,...n})}}const zt={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8},w=0,F=1,z=2,O=3,B=4,R=5,V=class ct{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<r.replace(/[{()}]/g,""))??[]).forEach(r=>{t[r]=[]}),t}function Q(o,t){let e;const r=/@in\s+([^;]+);/g;for(;(e=r.exec(o))!==null;)t.push(e[1])}function tt(o,t,e=!1){const r=[];Q(t,r),o.forEach(i=>{i.header&&Q(i.header,r)});const n=r;e&&n.sort();const s=n.map((i,u)=>` @location(${u}) ${i},`).join(` +`);let a=t.replace(/@in\s+[^;]+;\s*/g,"");return a=a.replace("{{in}}",` +${s} +`),a}function et(o,t){let e;const r=/@out\s+([^;]+);/g;for(;(e=r.exec(o))!==null;)t.push(e[1])}function jt(o){const e=/\b(\w+)\s*:/g.exec(o);return e?e[1]:""}function It(o){const t=/@.*?\s+/g;return o.replace(t,"")}function kt(o,t){const e=[];et(t,e),o.forEach(u=>{u.header&&et(u.header,e)});let r=0;const n=e.sort().map(u=>u.indexOf("builtin")>-1?u:`@location(${r++}) ${u}`).join(`, +`),s=e.sort().map(u=>` var ${It(u)};`).join(` +`),a=`return VSOutput( + ${e.sort().map(u=>` ${jt(u)}`).join(`, +`)});`;let i=t.replace(/@out\s+[^;]+;\s*/g,"");return i=i.replace("{{struct}}",` +${n} +`),i=i.replace("{{start}}",` +${s} +`),i=i.replace("{{return}}",` +${a} +`),i}function rt(o,t){let e=o;for(const r in t){const n=t[r];n.join(` +`).length?e=e.replace(`{{${r}}}`,`//-----${r} START-----// +${n.join(` +`)} +//----${r} FINISH----//`):e=e.replace(`{{${r}}}`,"")}return e}const h=Object.create(null),j=new Map;let Dt=0;function Nt({template:o,bits:t}){const e=lt(o,t);if(h[e])return h[e];const{vertex:r,fragment:n}=Ht(o,t);return h[e]=ft(r,n,t),h[e]}function Lt({template:o,bits:t}){const e=lt(o,t);return h[e]||(h[e]=ft(o.vertex,o.fragment,t)),h[e]}function Ht(o,t){const e=t.map(a=>a.vertex).filter(a=>!!a),r=t.map(a=>a.fragment).filter(a=>!!a);let n=tt(e,o.vertex,!0);n=kt(e,n);const s=tt(r,o.fragment,!0);return{vertex:n,fragment:s}}function lt(o,t){return t.map(e=>(j.has(e)||j.set(e,Dt++),j.get(e))).sort((e,r)=>e-r).join("-")+o.vertex+o.fragment}function ft(o,t,e){const r=J(o),n=J(t);return e.forEach(s=>{Z(s.vertex,r,s.name),Z(s.fragment,n,s.name)}),{vertex:rt(o,r),fragment:rt(t,n)}}const Vt=` + @in aPosition: vec2; + @in aUV: vec2; + + @out @builtin(position) vPosition: vec4; + @out vUV : vec2; + @out vColor : vec4; + + {{header}} + + struct VSOutput { + {{struct}} + }; + + @vertex + fn main( {{in}} ) -> VSOutput { + + var worldTransformMatrix = globalUniforms.uWorldTransformMatrix; + var modelMatrix = mat3x3( + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ); + var position = aPosition; + var uv = aUV; + + {{start}} + + vColor = vec4(1., 1., 1., 1.); + + {{main}} + + vUV = uv; + + var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix; + + vPosition = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + + vColor *= globalUniforms.uWorldColorAlpha; + + {{end}} + + {{return}} + }; +`,Wt=` + @in vUV : vec2; + @in vColor : vec4; + + {{header}} + + @fragment + fn main( + {{in}} + ) -> @location(0) vec4 { + + {{start}} + + var outColor:vec4; + + {{main}} + + return outColor * vColor; + }; +`,Kt=` + in vec2 aPosition; + in vec2 aUV; + + out vec4 vColor; + out vec2 vUV; + + {{header}} + + void main(void){ + + mat3 worldTransformMatrix = uWorldTransformMatrix; + mat3 modelMatrix = mat3( + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ); + vec2 position = aPosition; + vec2 uv = aUV; + + {{start}} + + vColor = vec4(1.); + + {{main}} + + vUV = uv; + + mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix; + + gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + + vColor *= uWorldColorAlpha; + + {{end}} + } +`,Xt=` + + in vec4 vColor; + in vec2 vUV; + + out vec4 finalColor; + + {{header}} + + void main(void) { + + {{start}} + + vec4 outColor; + + {{main}} + + finalColor = outColor * vColor; + } +`,Yt={name:"global-uniforms-bit",vertex:{header:` + struct GlobalUniforms { + uProjectionMatrix:mat3x3, + uWorldTransformMatrix:mat3x3, + uWorldColorAlpha: vec4, + uResolution: vec2, + } + + @group(0) @binding(0) var globalUniforms : GlobalUniforms; + `}},qt={name:"global-uniforms-bit",vertex:{header:` + uniform mat3 uProjectionMatrix; + uniform mat3 uWorldTransformMatrix; + uniform vec4 uWorldColorAlpha; + uniform vec2 uResolution; + `}};function oe({bits:o,name:t}){const e=Nt({template:{fragment:Wt,vertex:Vt},bits:[Yt,...o]});return S.from({name:t,vertex:{source:e.vertex,entryPoint:"main"},fragment:{source:e.fragment,entryPoint:"main"}})}function ne({bits:o,name:t}){return new nt({name:t,...Lt({template:{vertex:Kt,fragment:Xt},bits:[qt,...o]})})}const se={name:"color-bit",vertex:{header:` + @in aColor: vec4; + `,main:` + vColor *= vec4(aColor.rgb * aColor.a, aColor.a); + `}},ie={name:"color-bit",vertex:{header:` + in vec4 aColor; + `,main:` + vColor *= vec4(aColor.rgb * aColor.a, aColor.a); + `}},I={};function Zt(o){const t=[];if(o===1)t.push("@group(1) @binding(0) var textureSource1: texture_2d;"),t.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let e=0;for(let r=0;r;`),t.push(`@group(1) @binding(${e++}) var textureSampler${r+1}: sampler;`)}return t.join(` +`)}function Jt(o){const t=[];if(o===1)t.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{t.push("switch vTextureId {");for(let e=0;e; + @out @interpolate(flat) vTextureId : u32; + `,main:` + vTextureId = aTextureIdAndRound.y; + `,end:` + if(aTextureIdAndRound.x == 1) + { + vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw); + } + `},fragment:{header:` + @in @interpolate(flat) vTextureId: u32; + + ${Zt(N())} + `,main:` + var uvDx = dpdx(vUV); + var uvDy = dpdy(vUV); + + ${Jt(N())} + `}}),I[o]}const k={};function Qt(o){const t=[];for(let e=0;e0&&t.push("else"),e, targetSize: vec2) -> vec2 + { + return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0; + } + `}},le={name:"round-pixels-bit",vertex:{header:` + vec2 roundPixels(vec2 position, vec2 targetSize) + { + return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0; + } + `}},D={name:"local-uniform-bit",vertex:{header:` + + struct LocalUniforms { + uTransformMatrix:mat3x3, + uColor:vec4, + uRound:f32, + } + + @group(1) @binding(0) var localUniforms : LocalUniforms; + `,main:` + vColor *= localUniforms.uColor; + modelMatrix *= localUniforms.uTransformMatrix; + `,end:` + if(localUniforms.uRound == 1) + { + vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw); + } + `}},fe={...D,vertex:{...D.vertex,header:D.vertex.header.replace("group(1)","group(2)")}},me={name:"local-uniform-bit",vertex:{header:` + + uniform mat3 uTransformMatrix; + uniform vec4 uColor; + uniform float uRound; + `,main:` + vColor *= uColor; + modelMatrix = uTransformMatrix; + `,end:` + if(uRound == 1.) + { + gl_Position.xy = roundPixels(gl_Position.xy, uResolution); + } + `}};class de{constructor(){this.vertexSize=4,this.indexSize=6,this.location=0,this.batcher=null,this.batch=null,this.roundPixels=0}get blendMode(){return this.renderable.groupBlendMode}packAttributes(t,e,r,n){const s=this.renderable,a=this.texture,i=s.groupTransform,u=i.a,f=i.b,c=i.c,l=i.d,m=i.tx,p=i.ty,g=this.bounds,x=g.maxX,v=g.minX,b=g.maxY,y=g.minY,d=a.uvs,_=s.groupColorAlpha,M=n<<16|this.roundPixels&65535;t[r+0]=u*v+c*y+m,t[r+1]=l*y+f*v+p,t[r+2]=d.x0,t[r+3]=d.y0,e[r+4]=_,e[r+5]=M,t[r+6]=u*x+c*y+m,t[r+7]=l*y+f*x+p,t[r+8]=d.x1,t[r+9]=d.y1,e[r+10]=_,e[r+11]=M,t[r+12]=u*x+c*b+m,t[r+13]=l*b+f*x+p,t[r+14]=d.x2,t[r+15]=d.y2,e[r+16]=_,e[r+17]=M,t[r+18]=u*v+c*b+m,t[r+19]=l*b+f*v+p,t[r+20]=d.x3,t[r+21]=d.y3,e[r+22]=_,e[r+23]=M}packIndex(t,e,r){t[e]=r+0,t[e+1]=r+1,t[e+2]=r+2,t[e+3]=r+0,t[e+4]=r+2,t[e+5]=r+3}reset(){this.renderable=null,this.texture=null,this.batcher=null,this.batch=null,this.bounds=null}}function he(o,t,e){const r=(o>>24&255)/255;t[e++]=(o&255)/255*r,t[e++]=(o>>8&255)/255*r,t[e++]=(o>>16&255)/255*r,t[e++]=r}export{de as B,S as G,H as R,ee as S,re as T,Ft as U,se as a,ut as b,oe as c,W as d,D as e,nt as f,ae as g,St as h,he as i,ne as j,ie as k,fe as l,ue as m,le as n,me as o,ce as r}; diff --git a/public/assets/games/bulletzio/assets/getBatchSamplersUniformGroup-BY8U1LLP.js b/public/assets/games/bulletzio/assets/getBatchSamplersUniformGroup-BY8U1LLP.js new file mode 100644 index 00000000..d2546ceb --- /dev/null +++ b/public/assets/games/bulletzio/assets/getBatchSamplersUniformGroup-BY8U1LLP.js @@ -0,0 +1 @@ +import{U as e}from"./colorToUniform-CXyy9as8.js";const i={};function a(r){let o=i[r];if(o)return o;const n=new Int32Array(r);for(let t=0;ti.map(i=>__vite__fileDeps[i]); +function zte(n,e){for(var t=0;ti[r]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=t(r);fetch(r.href,s)}})();var Dc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ol(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function Gte(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}),t}var p9={exports:{}},zP={},m9={exports:{}},H0={exports:{}};H0.exports;(function(n,e){/** + * @license React + * react.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",i=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),u=Symbol.for("react.provider"),f=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),g=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),w=Symbol.for("react.offscreen"),C=Symbol.iterator,E="@@iterator";function b(q){if(q===null||typeof q!="object")return null;var he=C&&q[C]||q[E];return typeof he=="function"?he:null}var B={current:null},I={transition:null},R={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},k={current:null},O={},j=null;function U(q){j=q}O.setExtraStackFrame=function(q){j=q},O.getCurrentStack=null,O.getStackAddendum=function(){var q="";j&&(q+=j);var he=O.getCurrentStack;return he&&(q+=he()||""),q};var S=!1,F=!1,Z=!1,P=!1,T=!1,V={ReactCurrentDispatcher:B,ReactCurrentBatchConfig:I,ReactCurrentOwner:k};V.ReactDebugCurrentFrame=O,V.ReactCurrentActQueue=R;function H(q){{for(var he=arguments.length,Ve=new Array(he>1?he-1:0),$e=1;$e1?he-1:0),$e=1;$e1){for(var Pn=Array(Mn),Wn=0;Wn1){for(var Bi=Array(Wn),nr=0;nr is not supported and will be removed in a future major release. Did you mean to render instead?")),he.Provider},set:function(Yt){he.Provider=Yt}},_currentValue:{get:function(){return he._currentValue},set:function(Yt){he._currentValue=Yt}},_currentValue2:{get:function(){return he._currentValue2},set:function(Yt){he._currentValue2=Yt}},_threadCount:{get:function(){return he._threadCount},set:function(Yt){he._threadCount=Yt}},Consumer:{get:function(){return Ve||(Ve=!0,X("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?")),he.Consumer}},displayName:{get:function(){return he.displayName},set:function(Yt){Dt||(H("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",Yt),Dt=!0)}}}),he.Consumer=$t}return he._currentRenderer=null,he._currentRenderer2=null,he}var Ln=-1,Un=0,Kn=1,yi=2;function N(q){if(q._status===Ln){var he=q._result,Ve=he();if(Ve.then(function($t){if(q._status===Un||q._status===Ln){var Yt=q;Yt._status=Kn,Yt._result=$t}},function($t){if(q._status===Un||q._status===Ln){var Yt=q;Yt._status=yi,Yt._result=$t}}),q._status===Ln){var $e=q;$e._status=Un,$e._result=Ve}}if(q._status===Kn){var Dt=q._result;return Dt===void 0&&X(`lazy: Expected the result of a dynamic import() call. Instead received: %s + +Your code should look like: + const MyComponent = lazy(() => import('./MyComponent')) + +Did you accidentally put curly braces around the import?`,Dt),"default"in Dt||X(`lazy: Expected the result of a dynamic import() call. Instead received: %s + +Your code should look like: + const MyComponent = lazy(() => import('./MyComponent'))`,Dt),Dt.default}else throw q._result}function D(q){var he={_status:Ln,_result:q},Ve={$$typeof:v,_payload:he,_init:N};{var $e,Dt;Object.defineProperties(Ve,{defaultProps:{configurable:!0,get:function(){return $e},set:function($t){X("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),$e=$t,Object.defineProperty(Ve,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return Dt},set:function($t){X("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),Dt=$t,Object.defineProperty(Ve,"propTypes",{enumerable:!0})}}})}return Ve}function Q(q){q!=null&&q.$$typeof===p?X("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof q!="function"?X("forwardRef requires a render function but was given %s.",q===null?"null":typeof q):q.length!==0&&q.length!==2&&X("forwardRef render functions accept exactly two parameters: props and ref. %s",q.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),q!=null&&(q.defaultProps!=null||q.propTypes!=null)&&X("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var he={$$typeof:d,render:q};{var Ve;Object.defineProperty(he,"displayName",{enumerable:!1,configurable:!0,get:function(){return Ve},set:function($e){Ve=$e,!q.name&&!q.displayName&&(q.displayName=$e)}})}return he}var W;W=Symbol.for("react.module.reference");function z(q){return!!(typeof q=="string"||typeof q=="function"||q===s||q===l||T||q===a||q===A||q===g||P||q===w||S||F||Z||typeof q=="object"&&q!==null&&(q.$$typeof===v||q.$$typeof===p||q.$$typeof===u||q.$$typeof===f||q.$$typeof===d||q.$$typeof===W||q.getModuleId!==void 0))}function ue(q,he){z(q)||X("memo: The first argument must be a component. Instead received: %s",q===null?"null":typeof q);var Ve={$$typeof:p,type:q,compare:he===void 0?null:he};{var $e;Object.defineProperty(Ve,"displayName",{enumerable:!1,configurable:!0,get:function(){return $e},set:function(Dt){$e=Dt,!q.name&&!q.displayName&&(q.displayName=Dt)}})}return Ve}function Se(){var q=B.current;return q===null&&X(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: +1. You might have mismatching versions of React and the renderer (such as React DOM) +2. You might be breaking the Rules of Hooks +3. You might have more than one copy of React in the same app +See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),q}function ze(q){var he=Se();if(q._context!==void 0){var Ve=q._context;Ve.Consumer===q?X("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):Ve.Provider===q&&X("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return he.useContext(q)}function ht(q){var he=Se();return he.useState(q)}function bt(q,he,Ve){var $e=Se();return $e.useReducer(q,he,Ve)}function J(q){var he=Se();return he.useRef(q)}function le(q,he){var Ve=Se();return Ve.useEffect(q,he)}function Ae(q,he){var Ve=Se();return Ve.useInsertionEffect(q,he)}function me(q,he){var Ve=Se();return Ve.useLayoutEffect(q,he)}function de(q,he){var Ve=Se();return Ve.useCallback(q,he)}function Fe(q,he){var Ve=Se();return Ve.useMemo(q,he)}function Qe(q,he,Ve){var $e=Se();return $e.useImperativeHandle(q,he,Ve)}function Le(q,he){{var Ve=Se();return Ve.useDebugValue(q,he)}}function wt(){var q=Se();return q.useTransition()}function Mt(q){var he=Se();return he.useDeferredValue(q)}function it(){var q=Se();return q.useId()}function vt(q,he,Ve){var $e=Se();return $e.useSyncExternalStore(q,he,Ve)}var cn=0,bn,Bn,Sn,Wt,Ut,qn,Dn;function Ei(){}Ei.__reactDisabledLog=!0;function ur(){{if(cn===0){bn=console.log,Bn=console.info,Sn=console.warn,Wt=console.error,Ut=console.group,qn=console.groupCollapsed,Dn=console.groupEnd;var q={configurable:!0,enumerable:!0,value:Ei,writable:!0};Object.defineProperties(console,{info:q,log:q,warn:q,error:q,group:q,groupCollapsed:q,groupEnd:q})}cn++}}function ji(){{if(cn--,cn===0){var q={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:re({},q,{value:bn}),info:re({},q,{value:Bn}),warn:re({},q,{value:Sn}),error:re({},q,{value:Wt}),group:re({},q,{value:Ut}),groupCollapsed:re({},q,{value:qn}),groupEnd:re({},q,{value:Dn})})}cn<0&&X("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Gr=V.ReactCurrentDispatcher,Vn;function fr(q,he,Ve){{if(Vn===void 0)try{throw Error()}catch(Dt){var $e=Dt.stack.trim().match(/\n( *(at )?)/);Vn=$e&&$e[1]||""}return` +`+Vn+q}}var ys=!1,di;{var ho=typeof WeakMap=="function"?WeakMap:Map;di=new ho}function go(q,he){if(!q||ys)return"";{var Ve=di.get(q);if(Ve!==void 0)return Ve}var $e;ys=!0;var Dt=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var $t;$t=Gr.current,Gr.current=null,ur();try{if(he){var Yt=function(){throw Error()};if(Object.defineProperty(Yt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Yt,[])}catch(ai){$e=ai}Reflect.construct(q,[],Yt)}else{try{Yt.call()}catch(ai){$e=ai}q.call(Yt.prototype)}}else{try{throw Error()}catch(ai){$e=ai}q()}}catch(ai){if(ai&&$e&&typeof ai.stack=="string"){for(var un=ai.stack.split(` +`),sn=$e.stack.split(` +`),Mn=un.length-1,Pn=sn.length-1;Mn>=1&&Pn>=0&&un[Mn]!==sn[Pn];)Pn--;for(;Mn>=1&&Pn>=0;Mn--,Pn--)if(un[Mn]!==sn[Pn]){if(Mn!==1||Pn!==1)do if(Mn--,Pn--,Pn<0||un[Mn]!==sn[Pn]){var Wn=` +`+un[Mn].replace(" at new "," at ");return q.displayName&&Wn.includes("")&&(Wn=Wn.replace("",q.displayName)),typeof q=="function"&&di.set(q,Wn),Wn}while(Mn>=1&&Pn>=0);break}}}finally{ys=!1,Gr.current=$t,ji(),Error.prepareStackTrace=Dt}var Bi=q?q.displayName||q.name:"",nr=Bi?fr(Bi):"";return typeof q=="function"&&di.set(q,nr),nr}function sa(q,he,Ve){return go(q,!1)}function cA(q){var he=q.prototype;return!!(he&&he.isReactComponent)}function wa(q,he,Ve){if(q==null)return"";if(typeof q=="function")return go(q,cA(q));if(typeof q=="string")return fr(q);switch(q){case A:return fr("Suspense");case g:return fr("SuspenseList")}if(typeof q=="object")switch(q.$$typeof){case d:return sa(q.render);case p:return wa(q.type,he,Ve);case v:{var $e=q,Dt=$e._payload,$t=$e._init;try{return wa($t(Dt),he,Ve)}catch{}}}return""}var Vl={},Ul=V.ReactDebugCurrentFrame;function zl(q){if(q){var he=q._owner,Ve=wa(q.type,q._source,he?he.type:null);Ul.setExtraStackFrame(Ve)}else Ul.setExtraStackFrame(null)}function vf(q,he,Ve,$e,Dt){{var $t=Function.call.bind(Y);for(var Yt in q)if($t(q,Yt)){var un=void 0;try{if(typeof q[Yt]!="function"){var sn=Error(($e||"React class")+": "+Ve+" type `"+Yt+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof q[Yt]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw sn.name="Invariant Violation",sn}un=q[Yt](he,Yt,$e,Ve,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Mn){un=Mn}un&&!(un instanceof Error)&&(zl(Dt),X("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",$e||"React class",Ve,Yt,typeof un),zl(null)),un instanceof Error&&!(un.message in Vl)&&(Vl[un.message]=!0,zl(Dt),X("Failed %s type: %s",Ve,un.message),zl(null))}}}function Hn(q){if(q){var he=q._owner,Ve=wa(q.type,q._source,he?he.type:null);U(Ve)}else U(null)}var po;po=!1;function tu(){if(k.current){var q=ne(k.current.type);if(q)return` + +Check the render method of \``+q+"`."}return""}function gn(q){if(q!==void 0){var he=q.fileName.replace(/^.*[\\\/]/,""),Ve=q.lineNumber;return` + +Check your code at `+he+":"+Ve+"."}return""}function mo(q){return q!=null?gn(q.__source):""}var Xi={};function ya(q){var he=tu();if(!he){var Ve=typeof q=="string"?q:q.displayName||q.name;Ve&&(he=` + +Check the top-level render call using <`+Ve+">.")}return he}function vo(q,he){if(!(!q._store||q._store.validated||q.key!=null)){q._store.validated=!0;var Ve=ya(he);if(!Xi[Ve]){Xi[Ve]=!0;var $e="";q&&q._owner&&q._owner!==k.current&&($e=" It was passed a child from "+ne(q._owner.type)+"."),Hn(q),X('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',Ve,$e),Hn(null)}}}function Wo(q,he){if(typeof q=="object"){if(oe(q))for(var Ve=0;Ve",Dt=" Did you accidentally export a JSX literal instead of a component?"):Yt=typeof q,X("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Yt,Dt)}var un=nt.apply(this,arguments);if(un==null)return un;if($e)for(var sn=2;sn10&&H("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),$e._updatedFibers.clear()}}}var Zo=!1,_o=null;function wf(q){if(_o===null)try{var he=("require"+Math.random()).slice(0,7),Ve=n&&n[he];_o=Ve.call(n,"timers").setImmediate}catch{_o=function(Dt){Zo===!1&&(Zo=!0,typeof MessageChannel>"u"&&X("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var $t=new MessageChannel;$t.port1.onmessage=Dt,$t.port2.postMessage(void 0)}}return _o(q)}var ja=0,yf=!1;function Ef(q){{var he=ja;ja++,R.current===null&&(R.current=[]);var Ve=R.isBatchingLegacy,$e;try{if(R.isBatchingLegacy=!0,$e=q(),!Ve&&R.didScheduleLegacyUpdate){var Dt=R.current;Dt!==null&&(R.didScheduleLegacyUpdate=!1,Gl(Dt))}}catch(Bi){throw Ns(he),Bi}finally{R.isBatchingLegacy=Ve}if($e!==null&&typeof $e=="object"&&typeof $e.then=="function"){var $t=$e,Yt=!1,un={then:function(Bi,nr){Yt=!0,$t.then(function(ai){Ns(he),ja===0?Xa(ai,Bi,nr):Bi(ai)},function(ai){Ns(he),nr(ai)})}};return!yf&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){Yt||(yf=!0,X("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),un}else{var sn=$e;if(Ns(he),ja===0){var Mn=R.current;Mn!==null&&(Gl(Mn),R.current=null);var Pn={then:function(Bi,nr){R.current===null?(R.current=[],Xa(sn,Bi,nr)):Bi(sn)}};return Pn}else{var Wn={then:function(Bi,nr){Bi(sn)}};return Wn}}}}function Ns(q){q!==ja-1&&X("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ja=q}function Xa(q,he,Ve){{var $e=R.current;if($e!==null)try{Gl($e),wf(function(){$e.length===0?(R.current=null,he(q)):Xa(q,he,Ve)})}catch(Dt){Ve(Dt)}else he(q)}}var rs=!1;function Gl(q){if(!rs){rs=!0;var he=0;try{for(;he1?Q-1:0),z=1;z=1&&le>=0&&ht[J]!==bt[le];)le--;for(;J>=1&&le>=0;J--,le--)if(ht[J]!==bt[le]){if(J!==1||le!==1)do if(J--,le--,le<0||ht[J]!==bt[le]){var Ae=` +`+ht[J].replace(" at new "," at ");return D.displayName&&Ae.includes("")&&(Ae=Ae.replace("",D.displayName)),typeof D=="function"&&ft.set(D,Ae),Ae}while(J>=1&&le>=0);break}}}finally{je=!1,be.current=Se,ce(),Error.prepareStackTrace=ue}var me=D?D.displayName||D.name:"",de=me?Re(me):"";return typeof D=="function"&&ft.set(D,de),de}function oe(D,Q,W){return we(D,!1)}function Bt(D){var Q=D.prototype;return!!(Q&&Q.isReactComponent)}function Ze(D,Q,W){if(D==null)return"";if(typeof D=="function")return we(D,Bt(D));if(typeof D=="string")return Re(D);switch(D){case f:return Re("Suspense");case d:return Re("SuspenseList")}if(typeof D=="object")switch(D.$$typeof){case u:return oe(D.render);case A:return Ze(D.type,Q,W);case g:{var z=D,ue=z._payload,Se=z._init;try{return Ze(Se(ue),Q,W)}catch{}}}return""}var lt=Object.prototype.hasOwnProperty,_e={},qe=E.ReactDebugCurrentFrame;function ct(D){if(D){var Q=D._owner,W=Ze(D.type,D._source,Q?Q.type:null);qe.setExtraStackFrame(W)}else qe.setExtraStackFrame(null)}function ne(D,Q,W,z,ue){{var Se=Function.call.bind(lt);for(var ze in D)if(Se(D,ze)){var ht=void 0;try{if(typeof D[ze]!="function"){var bt=Error((z||"React class")+": "+W+" type `"+ze+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof D[ze]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw bt.name="Invariant Violation",bt}ht=D[ze](Q,ze,z,W,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(J){ht=J}ht&&!(ht instanceof Error)&&(ct(ue),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",z||"React class",W,ze,typeof ht),ct(null)),ht instanceof Error&&!(ht.message in _e)&&(_e[ht.message]=!0,ct(ue),b("Failed %s type: %s",W,ht.message),ct(null))}}}var Y=Array.isArray;function Ce(D){return Y(D)}function De(D){{var Q=typeof Symbol=="function"&&Symbol.toStringTag,W=Q&&D[Symbol.toStringTag]||D.constructor.name||"Object";return W}}function ke(D){try{return Ee(D),!1}catch{return!0}}function Ee(D){return""+D}function pt(D){if(ke(D))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",De(D)),Ee(D)}var Ue=E.ReactCurrentOwner,We={key:!0,ref:!0,__self:!0,__source:!0},yt,Je,Te;Te={};function nt(D){if(lt.call(D,"ref")){var Q=Object.getOwnPropertyDescriptor(D,"ref").get;if(Q&&Q.isReactWarning)return!1}return D.ref!==void 0}function st(D){if(lt.call(D,"key")){var Q=Object.getOwnPropertyDescriptor(D,"key").get;if(Q&&Q.isReactWarning)return!1}return D.key!==void 0}function Ke(D,Q){if(typeof D.ref=="string"&&Ue.current&&Q&&Ue.current.stateNode!==Q){var W=P(Ue.current.type);Te[W]||(b('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',P(Ue.current.type),D.ref),Te[W]=!0)}}function ut(D,Q){{var W=function(){yt||(yt=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",Q))};W.isReactWarning=!0,Object.defineProperty(D,"key",{get:W,configurable:!0})}}function It(D,Q){{var W=function(){Je||(Je=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",Q))};W.isReactWarning=!0,Object.defineProperty(D,"ref",{get:W,configurable:!0})}}var Qt=function(D,Q,W,z,ue,Se,ze){var ht={$$typeof:e,type:D,key:Q,ref:W,props:ze,_owner:Se};return ht._store={},Object.defineProperty(ht._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ht,"_self",{configurable:!1,enumerable:!1,writable:!1,value:z}),Object.defineProperty(ht,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ue}),Object.freeze&&(Object.freeze(ht.props),Object.freeze(ht)),ht};function ve(D,Q,W,z,ue){{var Se,ze={},ht=null,bt=null;W!==void 0&&(pt(W),ht=""+W),st(Q)&&(pt(Q.key),ht=""+Q.key),nt(Q)&&(bt=Q.ref,Ke(Q,ue));for(Se in Q)lt.call(Q,Se)&&!We.hasOwnProperty(Se)&&(ze[Se]=Q[Se]);if(D&&D.defaultProps){var J=D.defaultProps;for(Se in J)ze[Se]===void 0&&(ze[Se]=J[Se])}if(ht||bt){var le=typeof D=="function"?D.displayName||D.name||"Unknown":D;ht&&ut(ze,le),bt&&It(ze,le)}return Qt(D,ht,bt,ue,z,Ue.current,ze)}}var rt=E.ReactCurrentOwner,xe=E.ReactDebugCurrentFrame;function Oe(D){if(D){var Q=D._owner,W=Ze(D.type,D._source,Q?Q.type:null);xe.setExtraStackFrame(W)}else xe.setExtraStackFrame(null)}var mt;mt=!1;function At(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function St(){{if(rt.current){var D=P(rt.current.type);if(D)return` + +Check the render method of \``+D+"`."}return""}}function tn(D){{if(D!==void 0){var Q=D.fileName.replace(/^.*[\\\/]/,""),W=D.lineNumber;return` + +Check your code at `+Q+":"+W+"."}return""}}var on={};function Pt(D){{var Q=St();if(!Q){var W=typeof D=="string"?D:D.displayName||D.name;W&&(Q=` + +Check the top-level render call using <`+W+">.")}return Q}}function Jt(D,Q){{if(!D._store||D._store.validated||D.key!=null)return;D._store.validated=!0;var W=Pt(Q);if(on[W])return;on[W]=!0;var z="";D&&D._owner&&D._owner!==rt.current&&(z=" It was passed a child from "+P(D._owner.type)+"."),Oe(D),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',W,z),Oe(null)}}function Fn(D,Q){{if(typeof D!="object")return;if(Ce(D))for(var W=0;W",ht=" Did you accidentally export a JSX literal instead of a component?"):J=typeof D,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",J,ht)}var le=ve(D,Q,W,ue,Se);if(le==null)return le;if(ze){var Ae=Q.children;if(Ae!==void 0)if(z)if(Ce(Ae)){for(var me=0;me0?"{key: someKey, "+Fe.join(": ..., ")+": ...}":"{key: someKey}";if(!Kn[de+Qe]){var Le=Fe.length>0?"{"+Fe.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX: + let props = %s; + <%s {...props} /> +React keys must be passed directly to JSX without using spread: + let props = %s; + <%s key={someKey} {...props} />`,Qe,de,Le,de),Kn[de+Qe]=!0}}return D===i?Un(le):Ln(le),le}}var N=yi;zP.Fragment=i,zP.jsxDEV=N})();p9.exports=zP;var G=p9.exports,v9={exports:{}},Ra={},C9={exports:{}},w9={};(function(n){/** + * @license React + * scheduler.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var e=!1,t=!1,i=5;function r(Te,nt){var st=Te.length;Te.push(nt),l(Te,nt,st)}function s(Te){return Te.length===0?null:Te[0]}function a(Te){if(Te.length===0)return null;var nt=Te[0],st=Te.pop();return st!==nt&&(Te[0]=st,u(Te,st,0)),nt}function l(Te,nt,st){for(var Ke=st;Ke>0;){var ut=Ke-1>>>1,It=Te[ut];if(f(It,nt)>0)Te[ut]=nt,Te[Ke]=It,Ke=ut;else return}}function u(Te,nt,st){for(var Ke=st,ut=Te.length,It=ut>>>1;Kest&&(!Te||ct()));){var Ke=P.callback;if(typeof Ke=="function"){P.callback=null,T=P.priorityLevel;var ut=P.expirationTime<=st,It=Ke(ut);st=n.unstable_now(),typeof It=="function"?P.callback=It:P===s(S)&&a(S),ee(st)}else a(S);P=s(S)}if(P!==null)return!0;var Qt=s(F);return Qt!==null&&Ue(re,Qt.startTime-st),!1}function ce(Te,nt){switch(Te){case d:case A:case g:case p:case v:break;default:Te=g}var st=T;T=Te;try{return nt()}finally{T=st}}function be(Te){var nt;switch(T){case d:case A:case g:nt=g;break;default:nt=T;break}var st=T;T=nt;try{return Te()}finally{T=st}}function ye(Te){var nt=T;return function(){var st=T;T=nt;try{return Te.apply(this,arguments)}finally{T=st}}}function Re(Te,nt,st){var Ke=n.unstable_now(),ut;if(typeof st=="object"&&st!==null){var It=st.delay;typeof It=="number"&&It>0?ut=Ke+It:ut=Ke}else ut=Ke;var Qt;switch(Te){case d:Qt=R;break;case A:Qt=k;break;case v:Qt=U;break;case p:Qt=j;break;case g:default:Qt=O;break}var ve=ut+Qt,rt={id:Z++,callback:nt,priorityLevel:Te,startTime:ut,expirationTime:ve,sortIndex:-1};return ut>Ke?(rt.sortIndex=ut,r(F,rt),s(S)===null&&rt===s(F)&&(X?We():X=!0,Ue(re,ut-Ke))):(rt.sortIndex=ve,r(S,rt),!H&&!V&&(H=!0,pt(fe))),rt}function je(){}function ft(){!H&&!V&&(H=!0,pt(fe))}function tt(){return s(S)}function we(Te){Te.callback=null}function oe(){return T}var Bt=!1,Ze=null,lt=-1,_e=i,qe=-1;function ct(){var Te=n.unstable_now()-qe;return!(Te<_e)}function ne(){}function Y(Te){if(Te<0||Te>125){console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported");return}Te>0?_e=Math.floor(1e3/Te):_e=i}var Ce=function(){if(Ze!==null){var Te=n.unstable_now();qe=Te;var nt=!0,st=!0;try{st=Ze(nt,Te)}finally{st?De():(Bt=!1,Ze=null)}}else Bt=!1},De;if(typeof te=="function")De=function(){te(Ce)};else if(typeof MessageChannel<"u"){var ke=new MessageChannel,Ee=ke.port2;ke.port1.onmessage=Ce,De=function(){Ee.postMessage(null)}}else De=function(){_(Ce,0)};function pt(Te){Ze=Te,Bt||(Bt=!0,De())}function Ue(Te,nt){lt=_(function(){Te(n.unstable_now())},nt)}function We(){$(lt),lt=-1}var yt=ne,Je=null;n.unstable_IdlePriority=v,n.unstable_ImmediatePriority=d,n.unstable_LowPriority=p,n.unstable_NormalPriority=g,n.unstable_Profiling=Je,n.unstable_UserBlockingPriority=A,n.unstable_cancelCallback=we,n.unstable_continueExecution=ft,n.unstable_forceFrameRate=Y,n.unstable_getCurrentPriorityLevel=oe,n.unstable_getFirstCallbackNode=tt,n.unstable_next=be,n.unstable_pauseExecution=je,n.unstable_requestPaint=yt,n.unstable_runWithPriority=ce,n.unstable_scheduleCallback=Re,n.unstable_shouldYield=ct,n.unstable_wrapCallback=ye,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)})()})(w9);C9.exports=w9;var Xte=C9.exports;/** + * @license React + * react-dom.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var n=ge,e=Xte,t=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,i=!1;function r(o){i=o}function s(o){if(!i){for(var c=arguments.length,h=new Array(c>1?c-1:0),m=1;m1?c-1:0),m=1;m2&&(o[0]==="o"||o[0]==="O")&&(o[1]==="n"||o[1]==="N")}function ve(o,c,h,m){if(h!==null&&h.type===ke)return!1;switch(typeof c){case"function":case"symbol":return!0;case"boolean":{if(m)return!1;if(h!==null)return!h.acceptsBooleans;var y=o.toLowerCase().slice(0,5);return y!=="data-"&&y!=="aria-"}default:return!1}}function rt(o,c,h,m){if(c===null||typeof c>"u"||ve(o,c,h,m))return!0;if(m)return!1;if(h!==null)switch(h.type){case Ue:return!c;case We:return c===!1;case yt:return isNaN(c);case Je:return isNaN(c)||c<1}return!1}function xe(o){return mt.hasOwnProperty(o)?mt[o]:null}function Oe(o,c,h,m,y,x,M){this.acceptsBooleans=c===pt||c===Ue||c===We,this.attributeName=m,this.attributeNamespace=y,this.mustUseProperty=h,this.propertyName=o,this.type=c,this.sanitizeURL=x,this.removeEmptyString=M}var mt={},At=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];At.forEach(function(o){mt[o]=new Oe(o,ke,!1,o,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(o){var c=o[0],h=o[1];mt[c]=new Oe(c,Ee,!1,h,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(o){mt[o]=new Oe(o,pt,!1,o.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(o){mt[o]=new Oe(o,pt,!1,o,null,!1,!1)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(function(o){mt[o]=new Oe(o,Ue,!1,o.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(o){mt[o]=new Oe(o,Ue,!0,o,null,!1,!1)}),["capture","download"].forEach(function(o){mt[o]=new Oe(o,We,!1,o,null,!1,!1)}),["cols","rows","size","span"].forEach(function(o){mt[o]=new Oe(o,Je,!1,o,null,!1,!1)}),["rowSpan","start"].forEach(function(o){mt[o]=new Oe(o,yt,!1,o.toLowerCase(),null,!1,!1)});var St=/[\-\:]([a-z])/g,tn=function(o){return o[1].toUpperCase()};["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(function(o){var c=o.replace(St,tn);mt[c]=new Oe(c,Ee,!1,o,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(o){var c=o.replace(St,tn);mt[c]=new Oe(c,Ee,!1,o,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(o){var c=o.replace(St,tn);mt[c]=new Oe(c,Ee,!1,o,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(o){mt[o]=new Oe(o,Ee,!1,o.toLowerCase(),null,!1,!1)});var on="xlinkHref";mt[on]=new Oe("xlinkHref",Ee,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(o){mt[o]=new Oe(o,Ee,!1,o.toLowerCase(),null,!0,!0)});var Pt=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i,Jt=!1;function Fn(o){!Jt&&Pt.test(o)&&(Jt=!0,a("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.",JSON.stringify(o)))}function Ln(o,c,h,m){if(m.mustUseProperty){var y=m.propertyName;return o[y]}else{qe(h,c),m.sanitizeURL&&Fn(""+h);var x=m.attributeName,M=null;if(m.type===We){if(o.hasAttribute(x)){var L=o.getAttribute(x);return L===""?!0:rt(c,h,m,!1)?L:L===""+h?h:L}}else if(o.hasAttribute(x)){if(rt(c,h,m,!1))return o.getAttribute(x);if(m.type===Ue)return h;M=o.getAttribute(x)}return rt(c,h,m,!1)?M===null?h:M:M===""+h?h:M}}function Un(o,c,h,m){{if(!It(c))return;if(!o.hasAttribute(c))return h===void 0?void 0:null;var y=o.getAttribute(c);return qe(h,c),y===""+h?h:y}}function Kn(o,c,h,m){var y=xe(c);if(!Qt(c,y,m)){if(rt(c,h,y,m)&&(h=null),m||y===null){if(It(c)){var x=c;h===null?o.removeAttribute(x):(qe(h,c),o.setAttribute(x,""+h))}return}var M=y.mustUseProperty;if(M){var L=y.propertyName;if(h===null){var K=y.type;o[L]=K===Ue?!1:""}else o[L]=h;return}var ie=y.attributeName,ae=y.attributeNamespace;if(h===null)o.removeAttribute(ie);else{var Ie=y.type,Be;Ie===Ue||Ie===We&&h===!0?Be="":(qe(h,ie),Be=""+h,y.sanitizeURL&&Fn(Be.toString())),ae?o.setAttributeNS(ae,ie,Be):o.setAttribute(ie,Be)}}}var yi=Symbol.for("react.element"),N=Symbol.for("react.portal"),D=Symbol.for("react.fragment"),Q=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),z=Symbol.for("react.provider"),ue=Symbol.for("react.context"),Se=Symbol.for("react.forward_ref"),ze=Symbol.for("react.suspense"),ht=Symbol.for("react.suspense_list"),bt=Symbol.for("react.memo"),J=Symbol.for("react.lazy"),le=Symbol.for("react.scope"),Ae=Symbol.for("react.debug_trace_mode"),me=Symbol.for("react.offscreen"),de=Symbol.for("react.legacy_hidden"),Fe=Symbol.for("react.cache"),Qe=Symbol.for("react.tracing_marker"),Le=Symbol.iterator,wt="@@iterator";function Mt(o){if(o===null||typeof o!="object")return null;var c=Le&&o[Le]||o[wt];return typeof c=="function"?c:null}var it=Object.assign,vt=0,cn,bn,Bn,Sn,Wt,Ut,qn;function Dn(){}Dn.__reactDisabledLog=!0;function Ei(){{if(vt===0){cn=console.log,bn=console.info,Bn=console.warn,Sn=console.error,Wt=console.group,Ut=console.groupCollapsed,qn=console.groupEnd;var o={configurable:!0,enumerable:!0,value:Dn,writable:!0};Object.defineProperties(console,{info:o,log:o,warn:o,error:o,group:o,groupCollapsed:o,groupEnd:o})}vt++}}function ur(){{if(vt--,vt===0){var o={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:it({},o,{value:cn}),info:it({},o,{value:bn}),warn:it({},o,{value:Bn}),error:it({},o,{value:Sn}),group:it({},o,{value:Wt}),groupCollapsed:it({},o,{value:Ut}),groupEnd:it({},o,{value:qn})})}vt<0&&a("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ji=t.ReactCurrentDispatcher,Gr;function Vn(o,c,h){{if(Gr===void 0)try{throw Error()}catch(y){var m=y.stack.trim().match(/\n( *(at )?)/);Gr=m&&m[1]||""}return` +`+Gr+o}}var fr=!1,ys;{var di=typeof WeakMap=="function"?WeakMap:Map;ys=new di}function ho(o,c){if(!o||fr)return"";{var h=ys.get(o);if(h!==void 0)return h}var m;fr=!0;var y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var x;x=ji.current,ji.current=null,Ei();try{if(c){var M=function(){throw Error()};if(Object.defineProperty(M.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(M,[])}catch(Xe){m=Xe}Reflect.construct(o,[],M)}else{try{M.call()}catch(Xe){m=Xe}o.call(M.prototype)}}else{try{throw Error()}catch(Xe){m=Xe}o()}}catch(Xe){if(Xe&&m&&typeof Xe.stack=="string"){for(var L=Xe.stack.split(` +`),K=m.stack.split(` +`),ie=L.length-1,ae=K.length-1;ie>=1&&ae>=0&&L[ie]!==K[ae];)ae--;for(;ie>=1&&ae>=0;ie--,ae--)if(L[ie]!==K[ae]){if(ie!==1||ae!==1)do if(ie--,ae--,ae<0||L[ie]!==K[ae]){var Ie=` +`+L[ie].replace(" at new "," at ");return o.displayName&&Ie.includes("")&&(Ie=Ie.replace("",o.displayName)),typeof o=="function"&&ys.set(o,Ie),Ie}while(ie>=1&&ae>=0);break}}}finally{fr=!1,ji.current=x,ur(),Error.prepareStackTrace=y}var Be=o?o.displayName||o.name:"",Ye=Be?Vn(Be):"";return typeof o=="function"&&ys.set(o,Ye),Ye}function go(o,c,h){return ho(o,!0)}function sa(o,c,h){return ho(o,!1)}function cA(o){var c=o.prototype;return!!(c&&c.isReactComponent)}function wa(o,c,h){if(o==null)return"";if(typeof o=="function")return ho(o,cA(o));if(typeof o=="string")return Vn(o);switch(o){case ze:return Vn("Suspense");case ht:return Vn("SuspenseList")}if(typeof o=="object")switch(o.$$typeof){case Se:return sa(o.render);case bt:return wa(o.type,c,h);case J:{var m=o,y=m._payload,x=m._init;try{return wa(x(y),c,h)}catch{}}}return""}function Vl(o){switch(o._debugOwner&&o._debugOwner.type,o._debugSource,o.tag){case p:return Vn(o.type);case j:return Vn("Lazy");case R:return Vn("Suspense");case F:return Vn("SuspenseList");case u:case d:case O:return sa(o.type);case B:return sa(o.type.render);case f:return go(o.type);default:return""}}function Ul(o){try{var c="",h=o;do c+=Vl(h),h=h.return;while(h);return c}catch(m){return` +Error generating stack: `+m.message+` +`+m.stack}}function zl(o,c,h){var m=o.displayName;if(m)return m;var y=c.displayName||c.name||"";return y!==""?h+"("+y+")":h}function vf(o){return o.displayName||"Context"}function Hn(o){if(o==null)return null;if(typeof o.tag=="number"&&a("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof o=="function")return o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case D:return"Fragment";case N:return"Portal";case W:return"Profiler";case Q:return"StrictMode";case ze:return"Suspense";case ht:return"SuspenseList"}if(typeof o=="object")switch(o.$$typeof){case ue:var c=o;return vf(c)+".Consumer";case z:var h=o;return vf(h._context)+".Provider";case Se:return zl(o,o.render,"ForwardRef");case bt:var m=o.displayName||null;return m!==null?m:Hn(o.type)||"Memo";case J:{var y=o,x=y._payload,M=y._init;try{return Hn(M(x))}catch{return null}}}return null}function po(o,c,h){var m=c.displayName||c.name||"";return o.displayName||(m!==""?h+"("+m+")":h)}function tu(o){return o.displayName||"Context"}function gn(o){var c=o.tag,h=o.type;switch(c){case V:return"Cache";case E:var m=h;return tu(m)+".Consumer";case b:var y=h;return tu(y._context)+".Provider";case S:return"DehydratedFragment";case B:return po(h,h.render,"ForwardRef");case w:return"Fragment";case p:return h;case g:return"Portal";case A:return"Root";case v:return"Text";case j:return Hn(h);case C:return h===Q?"StrictMode":"Mode";case P:return"Offscreen";case I:return"Profiler";case Z:return"Scope";case R:return"Suspense";case F:return"SuspenseList";case H:return"TracingMarker";case f:case u:case U:case d:case k:case O:if(typeof h=="function")return h.displayName||h.name||null;if(typeof h=="string")return h;break}return null}var mo=t.ReactDebugCurrentFrame,Xi=null,ya=!1;function vo(){{if(Xi===null)return null;var o=Xi._debugOwner;if(o!==null&&typeof o<"u")return gn(o)}return null}function Wo(){return Xi===null?"":Ul(Xi)}function tr(){mo.getCurrentStack=null,Xi=null,ya=!1}function Si(o){mo.getCurrentStack=o===null?null:Wo,Xi=o,ya=!1}function Cf(){return Xi}function Yr(o){ya=o}function jr(o){return""+o}function Ea(o){switch(typeof o){case"boolean":case"number":case"string":case"undefined":return o;case"object":return De(o),o;default:return""}}var Hs={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function Zo(o,c){Hs[c.type]||c.onChange||c.onInput||c.readOnly||c.disabled||c.value==null||a("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."),c.onChange||c.readOnly||c.disabled||c.checked==null||a("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")}function _o(o){var c=o.type,h=o.nodeName;return h&&h.toLowerCase()==="input"&&(c==="checkbox"||c==="radio")}function wf(o){return o._valueTracker}function ja(o){o._valueTracker=null}function yf(o){var c="";return o&&(_o(o)?c=o.checked?"true":"false":c=o.value),c}function Ef(o){var c=_o(o)?"checked":"value",h=Object.getOwnPropertyDescriptor(o.constructor.prototype,c);De(o[c]);var m=""+o[c];if(!(o.hasOwnProperty(c)||typeof h>"u"||typeof h.get!="function"||typeof h.set!="function")){var y=h.get,x=h.set;Object.defineProperty(o,c,{configurable:!0,get:function(){return y.call(this)},set:function(L){De(L),m=""+L,x.call(this,L)}}),Object.defineProperty(o,c,{enumerable:h.enumerable});var M={getValue:function(){return m},setValue:function(L){De(L),m=""+L},stopTracking:function(){ja(o),delete o[c]}};return M}}function Ns(o){wf(o)||(o._valueTracker=Ef(o))}function Xa(o){if(!o)return!1;var c=wf(o);if(!c)return!0;var h=c.getValue(),m=yf(o);return m!==h?(c.setValue(m),!0):!1}function rs(o){if(o=o||(typeof document<"u"?document:void 0),typeof o>"u")return null;try{return o.activeElement||o.body}catch{return o.body}}var Gl=!1,nu=!1,iu=!1,$o=!1;function Bf(o){var c=o.type==="checkbox"||o.type==="radio";return c?o.checked!=null:o.value!=null}function q(o,c){var h=o,m=c.checked,y=it({},c,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:m??h._wrapperState.initialChecked});return y}function he(o,c){Zo("input",c),c.checked!==void 0&&c.defaultChecked!==void 0&&!nu&&(a("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",vo()||"A component",c.type),nu=!0),c.value!==void 0&&c.defaultValue!==void 0&&!Gl&&(a("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components",vo()||"A component",c.type),Gl=!0);var h=o,m=c.defaultValue==null?"":c.defaultValue;h._wrapperState={initialChecked:c.checked!=null?c.checked:c.defaultChecked,initialValue:Ea(c.value!=null?c.value:m),controlled:Bf(c)}}function Ve(o,c){var h=o,m=c.checked;m!=null&&Kn(h,"checked",m,!1)}function $e(o,c){var h=o;{var m=Bf(c);!h._wrapperState.controlled&&m&&!$o&&(a("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),$o=!0),h._wrapperState.controlled&&!m&&!iu&&(a("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"),iu=!0)}Ve(o,c);var y=Ea(c.value),x=c.type;if(y!=null)x==="number"?(y===0&&h.value===""||h.value!=y)&&(h.value=jr(y)):h.value!==jr(y)&&(h.value=jr(y));else if(x==="submit"||x==="reset"){h.removeAttribute("value");return}c.hasOwnProperty("value")?un(h,c.type,y):c.hasOwnProperty("defaultValue")&&un(h,c.type,Ea(c.defaultValue)),c.checked==null&&c.defaultChecked!=null&&(h.defaultChecked=!!c.defaultChecked)}function Dt(o,c,h){var m=o;if(c.hasOwnProperty("value")||c.hasOwnProperty("defaultValue")){var y=c.type,x=y==="submit"||y==="reset";if(x&&(c.value===void 0||c.value===null))return;var M=jr(m._wrapperState.initialValue);h||M!==m.value&&(m.value=M),m.defaultValue=M}var L=m.name;L!==""&&(m.name=""),m.defaultChecked=!m.defaultChecked,m.defaultChecked=!!m._wrapperState.initialChecked,L!==""&&(m.name=L)}function $t(o,c){var h=o;$e(h,c),Yt(h,c)}function Yt(o,c){var h=c.name;if(c.type==="radio"&&h!=null){for(var m=o;m.parentNode;)m=m.parentNode;qe(h,"name");for(var y=m.querySelectorAll("input[name="+JSON.stringify(""+h)+'][type="radio"]'),x=0;x.")))}):c.dangerouslySetInnerHTML!=null&&(Pn||(Pn=!0,a("Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected.")))),c.selected!=null&&!sn&&(a("Use the `defaultValue` or `value` props on must be an array if `multiple` is true.%s",h,uA()):!o.multiple&&m&&a("The `%s` prop supplied to